Exemple #1
0
 def A2m1f(eps):
   """Private: return A2-1"""
   coeff = [
     25, 36, 64, 0, 256,
   ]
   m = Geodesic.nA2_//2
   t = Math.polyval(m, coeff, 0, Math.sq(eps)) / coeff[m + 1]
   return t * (1 - eps) - eps
Exemple #2
0
 def A1m1f(eps):
   """Private: return A1-1."""
   coeff = [
     1, 4, 64, 0, 256,
   ]
   m = Geodesic.nA1_//2
   t = Math.polyval(m, coeff, 0, Math.sq(eps)) / coeff[m + 1]
   return (t + eps) / (1 - eps)
Exemple #3
0
 def _A2m1f(eps):
   """Private: return A2-1"""
   coeff = [
     -11, -28, -192, 0, 256,
   ]
   m = Geodesic.nA2_//2
   t = Math.polyval(m, coeff, 0, Math.sq(eps)) / coeff[m + 1]
   return (t - eps) / (1 + eps)
Exemple #4
0
 def _A1m1f(eps):
   """Private: return A1-1."""
   coeff = [
     1, 4, 64, 0, 256,
   ]
   m = Geodesic.nA1_//2
   t = Math.polyval(m, coeff, 0, Math.sq(eps)) / coeff[m + 1]
   return (t + eps) / (1 - eps)
Exemple #5
0
 def _transit(lon1, lon2):
     """Count crossings of prime meridian for AddPoint."""
     # Return 1 or -1 if crossing prime meridian in east or west direction.
     # Otherwise return zero.
     # Compute lon12 the same way as Geodesic::Inverse.
     lon1 = Math.AngNormalize(lon1)
     lon2 = Math.AngNormalize(lon2)
     lon12, _ = Math.AngDiff(lon1, lon2)
     cross = (1 if lon1 <= 0 and lon2 > 0 and lon12 > 0 else
              (-1 if lon2 <= 0 and lon1 > 0 and lon12 < 0 else 0))
     return cross
Exemple #6
0
 def transit(lon1, lon2):
   # Return 1 or -1 if crossing prime meridian in east or west direction.
   # Otherwise return zero.
   from geographiclib.geodesic import Geodesic
   # Compute lon12 the same way as Geodesic::Inverse.
   lon1 = Math.AngNormalize(lon1);
   lon2 = Math.AngNormalize(lon2);
   lon12 = Math.AngDiff(lon1, lon2);
   cross = (1 if lon1 < 0 and lon2 >= 0 and lon12 > 0
            else (-1 if lon2 < 0 and lon1 >= 0 and lon12 < 0 else 0))
   return cross
Exemple #7
0
  def Position(self, s12, outmask = GeodesicCapability.STANDARD):
    """Find the position on the line given *s12*

    :param s12: the distance from the first point to the second in
      meters
    :param outmask: the :ref:`output mask <outmask>`
    :return: a :ref:`dict`

    The default value of *outmask* is STANDARD, i.e., the *lat1*,
    *lon1*, *azi1*, *lat2*, *lon2*, *azi2*, *s12*, *a12* entries are
    returned.  The :class:`~geographiclib.geodesicline.GeodesicLine`
    object must have been constructed with the DISTANCE_IN capability.

    """

    from geographiclib.geodesic import Geodesic
    result = {'lat1': self.lat1,
              'lon1': self.lon1 if outmask & Geodesic.LONG_UNROLL else
              Math.AngNormalize(self.lon1),
              'azi1': self.azi1, 's12': s12}
    a12, lat2, lon2, azi2, s12, m12, M12, M21, S12 = self._GenPosition(
      False, s12, outmask)
    outmask &= Geodesic.OUT_MASK
    result['a12'] = a12
    if outmask & Geodesic.LATITUDE: result['lat2'] = lat2
    if outmask & Geodesic.LONGITUDE: result['lon2'] = lon2
    if outmask & Geodesic.AZIMUTH: result['azi2'] = azi2
    if outmask & Geodesic.REDUCEDLENGTH: result['m12'] = m12
    if outmask & Geodesic.GEODESICSCALE:
      result['M12'] = M12; result['M21'] = M21
    if outmask & Geodesic.AREA: result['S12'] = S12
    return result
Exemple #8
0
  def ArcPosition(self, a12, outmask = GeodesicCapability.STANDARD):
    """Find the position on the line given *a12*

    :param a12: spherical arc length from the first point to the second
      in degrees
    :param outmask: the :ref:`output mask <outmask>`
    :return: a :ref:`dict`

    The default value of *outmask* is STANDARD, i.e., the *lat1*,
    *lon1*, *azi1*, *lat2*, *lon2*, *azi2*, *s12*, *a12* entries are
    returned.

    """

    from geographiclib.geodesic import Geodesic
    result = {'lat1': self.lat1,
              'lon1': self.lon1 if outmask & Geodesic.LONG_UNROLL else
              Math.AngNormalize(self.lon1),
              'azi1': self.azi1, 'a12': a12}
    a12, lat2, lon2, azi2, s12, m12, M12, M21, S12 = self._GenPosition(
      True, a12, outmask)
    outmask &= Geodesic.OUT_MASK
    if outmask & Geodesic.DISTANCE: result['s12'] = s12
    if outmask & Geodesic.LATITUDE: result['lat2'] = lat2
    if outmask & Geodesic.LONGITUDE: result['lon2'] = lon2
    if outmask & Geodesic.AZIMUTH: result['azi2'] = azi2
    if outmask & Geodesic.REDUCEDLENGTH: result['m12'] = m12
    if outmask & Geodesic.GEODESICSCALE:
      result['M12'] = M12; result['M21'] = M21
    if outmask & Geodesic.AREA: result['S12'] = S12
    return result
Exemple #9
0
 def CheckPosition(lat, lon):
     """Check that lat and lon are legal and return normalized lon"""
     if (abs(lat) > 90):
         raise ValueError("latitude " + str(lat) + " not in [-90, 90]")
     if (lon < -540 or lon >= 540):
         raise ValueError("longitude " + str(lon) + " not in [-540, 540)")
     return Math.AngNormalize(lon)
Exemple #10
0
 def C3coeff(self):
   """Private: return coefficients for C3"""
   coeff = [
     3, 128,
     2, 5, 128,
     -1, 3, 3, 64,
     -1, 0, 1, 8,
     -1, 1, 4,
     5, 256,
     1, 3, 128,
     -3, -2, 3, 64,
     1, -3, 2, 32,
     7, 512,
     -10, 9, 384,
     5, -9, 5, 192,
     7, 512,
     -14, 7, 512,
     21, 2560,
   ]
   o = 0; k = 0
   for l in range(1, Geodesic.nC3_): # l is index of C3[l]
     for j in range(Geodesic.nC3_ - 1, l - 1, -1): # coeff of eps^j
       m = min(Geodesic.nC3_ - j - 1, j) # order of polynomial in n
       self._C3x[k] = Math.polyval(m, coeff, o, self._n) / coeff[o + m + 1]
       k += 1
       o += m + 2
Exemple #11
0
 def _C3coeff(self):
   """Private: return coefficients for C3"""
   coeff = [
     3, 128,
     2, 5, 128,
     -1, 3, 3, 64,
     -1, 0, 1, 8,
     -1, 1, 4,
     5, 256,
     1, 3, 128,
     -3, -2, 3, 64,
     1, -3, 2, 32,
     7, 512,
     -10, 9, 384,
     5, -9, 5, 192,
     7, 512,
     -14, 7, 512,
     21, 2560,
   ]
   o = 0; k = 0
   for l in range(1, Geodesic.nC3_): # l is index of C3[l]
     for j in range(Geodesic.nC3_ - 1, l - 1, -1): # coeff of eps^j
       m = min(Geodesic.nC3_ - j - 1, j) # order of polynomial in n
       self._C3x[k] = Math.polyval(m, coeff, o, self._n) / coeff[o + m + 1]
       k += 1
       o += m + 2
Exemple #12
0
  def InverseLine(self, lat1, lon1, lat2, lon2,
                  caps = GeodesicCapability.STANDARD |
                  GeodesicCapability.DISTANCE_IN):
    """Define a GeodesicLine object in terms of the invese geodesic problem

    :param lat1: latitude of the first point in degrees
    :param lon1: longitude of the first point in degrees
    :param lat2: latitude of the second point in degrees
    :param lon2: longitude of the second point in degrees
    :param caps: the :ref:`capabilities <outmask>`
    :return: a :class:`~geographiclib.geodesicline.GeodesicLine`

    This function sets point 3 of the GeodesicLine to correspond to
    point 2 of the inverse geodesic problem.  The default value of *caps*
    is STANDARD | DISTANCE_IN, allowing direct geodesic problem to be
    solved.

    """

    from geographiclib.geodesicline import GeodesicLine
    a12, _, salp1, calp1, _, _, _, _, _, _ = self._GenInverse(
      lat1, lon1, lat2, lon2, 0)
    azi1 = Math.atan2d(salp1, calp1)
    if caps & (Geodesic.OUT_MASK & Geodesic.DISTANCE_IN):
      caps |= Geodesic.DISTANCE
    line = GeodesicLine(self, lat1, lon1, azi1, caps, salp1, calp1)
    line.SetArc(a12)
    return line
Exemple #13
0
 def CheckPosition(lat, lon):
   """Check that lat and lon are legal and return normalized lon"""
   if abs(lat) > 90:
     raise ValueError("latitude " + str(lat) + " not in [-90, 90]")
   # if not Math.isfinite(lon):
   #   raise ValueError("longitude " + str(lon) + " not a finite number")
   return Math.AngNormalize(lon)
Exemple #14
0
 def _C4coeff(self):
   """Private: return coefficients for C4"""
   coeff = [
     97, 15015,
     1088, 156, 45045,
     -224, -4784, 1573, 45045,
     -10656, 14144, -4576, -858, 45045,
     64, 624, -4576, 6864, -3003, 15015,
     100, 208, 572, 3432, -12012, 30030, 45045,
     1, 9009,
     -2944, 468, 135135,
     5792, 1040, -1287, 135135,
     5952, -11648, 9152, -2574, 135135,
     -64, -624, 4576, -6864, 3003, 135135,
     8, 10725,
     1856, -936, 225225,
     -8448, 4992, -1144, 225225,
     -1440, 4160, -4576, 1716, 225225,
     -136, 63063,
     1024, -208, 105105,
     3584, -3328, 1144, 315315,
     -128, 135135,
     -2560, 832, 405405,
     128, 99099,
   ]
   o = 0; k = 0
   for l in range(Geodesic.nC4_): # l is index of C4[l]
     for j in range(Geodesic.nC4_ - 1, l - 1, -1): # coeff of eps^j
       m = Geodesic.nC4_ - j - 1 # order of polynomial in n
       self._C4x[k] = Math.polyval(m, coeff, o, self._n) / coeff[o + m + 1]
       k += 1
       o += m + 2
Exemple #15
0
 def C4coeff(self):
   """Private: return coefficients for C4"""
   coeff = [
     97, 15015,
     1088, 156, 45045,
     -224, -4784, 1573, 45045,
     -10656, 14144, -4576, -858, 45045,
     64, 624, -4576, 6864, -3003, 15015,
     100, 208, 572, 3432, -12012, 30030, 45045,
     1, 9009,
     -2944, 468, 135135,
     5792, 1040, -1287, 135135,
     5952, -11648, 9152, -2574, 135135,
     -64, -624, 4576, -6864, 3003, 135135,
     8, 10725,
     1856, -936, 225225,
     -8448, 4992, -1144, 225225,
     -1440, 4160, -4576, 1716, 225225,
     -136, 63063,
     1024, -208, 105105,
     3584, -3328, 1144, 315315,
     -128, 135135,
     -2560, 832, 405405,
     128, 99099,
   ]
   o = 0; k = 0
   for l in range(Geodesic.nC4_): # l is index of C4[l]
     for j in range(Geodesic.nC4_ - 1, l - 1, -1): # coeff of eps^j
       m = Geodesic.nC4_ - j - 1 # order of polynomial in n
       self._C4x[k] = Math.polyval(m, coeff, o, self._n) / coeff[o + m + 1]
       k += 1
       o += m + 2
Exemple #16
0
  def ArcPosition(self, a12,
                  outmask = GeodesicCapability.LATITUDE |
                  GeodesicCapability.LONGITUDE | GeodesicCapability.AZIMUTH |
                  GeodesicCapability.DISTANCE):
    """Return the point a spherical arc length a12 along the geodesic line.
    Return a dictionary with (some) of the following entries:

      lat1 latitude of point 1
      lon1 longitude of point 1
      azi1 azimuth of line at point 1
      lat2 latitude of point 2
      lon2 longitude of point 2
      azi2 azimuth of line at point 2
      s12 distance from 1 to 2
      a12 arc length on auxiliary sphere from 1 to 2
      m12 reduced length of geodesic
      M12 geodesic scale 2 relative to 1
      M21 geodesic scale 1 relative to 2
      S12 area between geodesic and equator

    outmask determines which fields get included and if outmask is
    omitted, then only the basic geodesic fields are computed.  The
    LONG_UNROLL bit unrolls the longitudes (instead of reducing them to
    the range [-180,180)).  The mask is an or'ed combination of the
    following values

      Geodesic.LATITUDE
      Geodesic.LONGITUDE
      Geodesic.AZIMUTH
      Geodesic.DISTANCE
      Geodesic.REDUCEDLENGTH
      Geodesic.GEODESICSCALE
      Geodesic.AREA
      Geodesic.ALL (all of the above)
      Geodesic.LONG_UNROLL

    The default value of outmask is LATITUDE | LONGITUDE | AZIMUTH |
    DISTANCE.

    """

    from geographiclib.geodesic import Geodesic
    Geodesic.CheckDistance(a12)
    result = {'lat1': self._lat1,
              'lon1': self._lon1 if outmask & Geodesic.LONG_UNROLL else
              Math.AngNormalize(self._lon1),
              'azi1': self._azi1, 'a12': a12}
    a12, lat2, lon2, azi2, s12, m12, M12, M21, S12 = self.GenPosition(
      True, a12, outmask)
    outmask &= Geodesic.OUT_MASK
    if outmask & Geodesic.DISTANCE: result['s12'] = s12
    if outmask & Geodesic.LATITUDE: result['lat2'] = lat2
    if outmask & Geodesic.LONGITUDE: result['lon2'] = lon2
    if outmask & Geodesic.AZIMUTH: result['azi2'] = azi2
    if outmask & Geodesic.REDUCEDLENGTH: result['m12'] = m12
    if outmask & Geodesic.GEODESICSCALE:
      result['M12'] = M12; result['M21'] = M21
    if outmask & Geodesic.AREA: result['S12'] = S12
    return result
Exemple #17
0
  def Inverse(self, lat1, lon1, lat2, lon2, outmask = STANDARD):
    """Solve the inverse geodesic problem.  Compute geodesic between (lat1,
    lon1) and (lat2, lon2).  Return a dictionary with (some) of the
    following entries:

      lat1 latitude of point 1
      lon1 longitude of point 1
      azi1 azimuth of line at point 1
      lat2 latitude of point 2
      lon2 longitude of point 2
      azi2 azimuth of line at point 2
      s12 distance from 1 to 2
      a12 arc length on auxiliary sphere from 1 to 2
      m12 reduced length of geodesic
      M12 geodesic scale 2 relative to 1
      M21 geodesic scale 1 relative to 2
      S12 area between geodesic and equator

    outmask determines which fields get included and if outmask is
    omitted, then only the basic geodesic fields are computed.  The mask
    is an or'ed combination of the following values

      Geodesic.AZIMUTH
      Geodesic.DISTANCE
      Geodesic.STANDARD (all of the above)
      Geodesic.REDUCEDLENGTH
      Geodesic.GEODESICSCALE
      Geodesic.AREA
      Geodesic.ALL (all of the above)
      Geodesic.LONG_UNROLL

    If Geodesic.LONG_UNROLL is set, then lon1 is unchanged and lon2 -
    lon1 indicates whether the geodesic is east going or west going.
    Otherwise lon1 and lon2 are both reduced to the range [-180,180).

    The default value of outmask is STANDARD.

    """

    lon1a = Geodesic.CheckPosition(lat1, lon1)
    lon2a = Geodesic.CheckPosition(lat2, lon2)
    if outmask & Geodesic.LONG_UNROLL:
      lon2 = lon1 + Math.AngDiff(lon1a, lon2a)
    else:
      lon1 = lon1a; lon2 = lon2a

    result = {'lat1': lat1, 'lon1': lon1, 'lat2': lat2, 'lon2': lon2}
    a12, s12, azi1, azi2, m12, M12, M21, S12 = self.GenInverse(
      lat1, lon1a, lat2, lon2a, outmask)
    outmask &= Geodesic.OUT_MASK
    result['a12'] = a12
    if outmask & Geodesic.DISTANCE: result['s12'] = s12
    if outmask & Geodesic.AZIMUTH:
      result['azi1'] = azi1; result['azi2'] = azi2
    if outmask & Geodesic.REDUCEDLENGTH: result['m12'] = m12
    if outmask & Geodesic.GEODESICSCALE:
      result['M12'] = M12; result['M21'] = M21
    if outmask & Geodesic.AREA: result['S12'] = S12
    return result
Exemple #18
0
 def _C1f(eps, c):
   """Private: return C1."""
   coeff = [
     -1, 6, -16, 32,
     -9, 64, -128, 2048,
     9, -16, 768,
     3, -5, 512,
     -7, 1280,
     -7, 2048,
   ]
   eps2 = Math.sq(eps)
   d = eps
   o = 0
   for l in range(1, Geodesic.nC1_ + 1): # l is index of C1p[l]
     m = (Geodesic.nC1_ - l) // 2        # order of polynomial in eps^2
     c[l] = d * Math.polyval(m, coeff, o, eps2) / coeff[o + m + 1]
     o += m + 2
     d *= eps
Exemple #19
0
 def C2f(eps, c):
   """Private: return C2"""
   coeff = [
     1, 2, 16, 32,
     35, 64, 384, 2048,
     15, 80, 768,
     7, 35, 512,
     63, 1280,
     77, 2048,
   ]
   eps2 = Math.sq(eps)
   d = eps
   o = 0
   for l in range(1, Geodesic.nC2_ + 1): # l is index of C2[l]
     m = (Geodesic.nC2_ - l) // 2        # order of polynomial in eps^2
     c[l] = d * Math.polyval(m, coeff, o, eps2) / coeff[o + m + 1]
     o += m + 2
     d *= eps
Exemple #20
0
 def _C1pf(eps, c):
   """Private: return C1'"""
   coeff = [
     205, -432, 768, 1536,
     4005, -4736, 3840, 12288,
     -225, 116, 384,
     -7173, 2695, 7680,
     3467, 7680,
     38081, 61440,
   ]
   eps2 = Math.sq(eps)
   d = eps
   o = 0
   for l in range(1, Geodesic.nC1p_ + 1): # l is index of C1p[l]
     m = (Geodesic.nC1p_ - l) // 2 # order of polynomial in eps^2
     c[l] = d * Math.polyval(m, coeff, o, eps2) / coeff[o + m + 1]
     o += m + 2
     d *= eps
Exemple #21
0
 def C1f(eps, c):
   """Private: return C1."""
   coeff = [
     -1, 6, -16, 32,
     -9, 64, -128, 2048,
     9, -16, 768,
     3, -5, 512,
     -7, 1280,
     -7, 2048,
   ]
   eps2 = Math.sq(eps)
   d = eps
   o = 0
   for l in range(1, Geodesic.nC1_ + 1): # l is index of C1p[l]
     m = (Geodesic.nC1_ - l) // 2        # order of polynomial in eps^2
     c[l] = d * Math.polyval(m, coeff, o, eps2) / coeff[o + m + 1]
     o += m + 2
     d *= eps
Exemple #22
0
 def C1pf(eps, c):
   """Private: return C1'"""
   coeff = [
     205, -432, 768, 1536,
     4005, -4736, 3840, 12288,
     -225, 116, 384,
     -7173, 2695, 7680,
     3467, 7680,
     38081, 61440,
   ]
   eps2 = Math.sq(eps)
   d = eps
   o = 0
   for l in range(1, Geodesic.nC1p_ + 1): # l is index of C1p[l]
     m = (Geodesic.nC1p_ - l) // 2 # order of polynomial in eps^2
     c[l] = d * Math.polyval(m, coeff, o, eps2) / coeff[o + m + 1]
     o += m + 2
     d *= eps
Exemple #23
0
 def _C2f(eps, c):
   """Private: return C2"""
   coeff = [
     1, 2, 16, 32,
     35, 64, 384, 2048,
     15, 80, 768,
     7, 35, 512,
     63, 1280,
     77, 2048,
   ]
   eps2 = Math.sq(eps)
   d = eps
   o = 0
   for l in range(1, Geodesic.nC2_ + 1): # l is index of C2[l]
     m = (Geodesic.nC2_ - l) // 2        # order of polynomial in eps^2
     c[l] = d * Math.polyval(m, coeff, o, eps2) / coeff[o + m + 1]
     o += m + 2
     d *= eps
  def Position(self, s12,
               outmask = GeodesicCapability.LATITUDE |
               GeodesicCapability.LONGITUDE | GeodesicCapability.AZIMUTH):
    """Return the point a distance s12 along the geodesic line.  Return a
    dictionary with (some) of the following entries:

      lat1 latitude of point 1
      lon1 longitude of point 1
      azi1 azimuth of line at point 1
      lat2 latitude of point 2
      lon2 longitude of point 2
      azi2 azimuth of line at point 2
      s12 distance from 1 to 2
      a12 arc length on auxiliary sphere from 1 to 2
      m12 reduced length of geodesic
      M12 geodesic scale 2 relative to 1
      M21 geodesic scale 1 relative to 2
      S12 area between geodesic and equator

    outmask determines which fields get included and if outmask is
    omitted, then only the basic geodesic fields are computed.  The
    LONG_NOWRAP bit prevents the longitudes being reduced to the range
    [-180,180).  The mask is an or'ed combination of the following
    values

      Geodesic.LATITUDE
      Geodesic.LONGITUDE
      Geodesic.AZIMUTH
      Geodesic.REDUCEDLENGTH
      Geodesic.GEODESICSCALE
      Geodesic.AREA
      Geodesic.ALL
      Geodesic.LONG_NOWRAP

    """

    from geographiclib.geodesic import Geodesic
    Geodesic.CheckDistance(s12)
    result = {'lat1': self._lat1,
              'lon1': self._lon1 if outmask & Geodesic.LONG_NOWRAP else
              Math.AngNormalize(self._lon1),
              'azi1': self._azi1, 's12': s12}
    a12, lat2, lon2, azi2, s12, m12, M12, M21, S12 = self.GenPosition(
      False, s12, outmask)
    outmask &= Geodesic.OUT_MASK
    result['a12'] = a12
    if outmask & Geodesic.LATITUDE: result['lat2'] = lat2
    if outmask & Geodesic.LONGITUDE: result['lon2'] = lon2
    if outmask & Geodesic.AZIMUTH: result['azi2'] = azi2
    if outmask & Geodesic.REDUCEDLENGTH: result['m12'] = m12
    if outmask & Geodesic.GEODESICSCALE:
      result['M12'] = M12; result['M21'] = M21
    if outmask & Geodesic.AREA: result['S12'] = S12
    return result
Exemple #25
0
 def _C4f(self, eps, c):
   """Private: return C4"""
   # Evaluate C4 coeffs by Horner's method
   # Elements c[0] thru c[nC4_ - 1] are set
   mult = 1
   o = 0
   for l in range(Geodesic.nC4_): # l is index of C4[l]
     m = Geodesic.nC4_ - l - 1    # order of polynomial in eps
     c[l] = mult * Math.polyval(m, self._C4x, o, eps)
     o += m + 1
     mult *= eps
Exemple #26
0
 def test_GeodSolve73(self):
     # Check for backwards from the pole bug reported by Anon on 2016-02-13.
     # This only affected the Java implementation.  It was introduced in Java
     # version 1.44 and fixed in 1.46-SNAPSHOT on 2016-01-17.
     # Also the + sign on azi2 is a check on the normalizing of azimuths
     # (converting -0.0 to +0.0).
     dir = Geodesic.WGS84.Direct(90, 10, 180, -1e6)
     self.assertAlmostEqual(dir["lat2"], 81.04623, delta=0.5e-5)
     self.assertAlmostEqual(dir["lon2"], -170, delta=0.5e-5)
     self.assertAlmostEqual(dir["azi2"], 0, delta=0.5e-5)
     self.assertTrue(Math.copysign(1, dir["azi2"]) > 0)
Exemple #27
0
 def _C3f(self, eps, c):
   """Private: return C3"""
   # Evaluate C3
   # Elements c[1] thru c[nC3_ - 1] are set
   mult = 1
   o = 0
   for l in range(1, Geodesic.nC3_): # l is index of C3[l]
     m = Geodesic.nC3_ - l - 1       # order of polynomial in eps
     mult *= eps
     c[l] = mult * Math.polyval(m, self._C3x, o, eps)
     o += m + 1
Exemple #28
0
 def C4f(self, eps, c):
   """Private: return C4"""
   # Evaluate C4 coeffs by Horner's method
   # Elements c[0] thru c[nC4_ - 1] are set
   mult = 1
   o = 0
   for l in range(Geodesic.nC4_): # l is index of C4[l]
     m = Geodesic.nC4_ - l - 1    # order of polynomial in eps
     c[l] = mult * Math.polyval(m, self._C4x, o, eps)
     o += m + 1
     mult *= eps
Exemple #29
0
 def C3f(self, eps, c):
   """Private: return C3"""
   # Evaluate C3
   # Elements c[1] thru c[nC3_ - 1] are set
   mult = 1
   o = 0
   for l in range(1, Geodesic.nC3_): # l is index of C3[l]
     m = Geodesic.nC3_ - l - 1       # order of polynomial in eps
     mult *= eps
     c[l] = mult * Math.polyval(m, self._C3x, o, eps)
     o += m + 1
Exemple #30
0
 def __init__(self, lat0, lon0, h0=0):
     self.lat0 = lat0
     self.lon0 = geomath.AngNormalize(lon0)
     self.h0 = h0
     self.origin = (earth_forward(self.lat0, self.lon0, self.h0))
     phi = math.radians(lat0)
     lam = math.radians(lon0)
     sphi = math.sin(phi)
     cphi = 0 if abs(self.lat0) == 90 else math.cos(phi)
     slam = 0 if self.lon0 == -180 else math.sin(lam)
     clam = 0 if abs(self.lon0) == 90 else math.cos(lam)
     self.rot = geocentric_rotation(sphi, cphi, slam, clam)
Exemple #31
0
  def __init__(self, a, f):
    """
    Construct a Geodesic object for ellipsoid with major radius a and
    flattening f.
    """

    self._a = float(a)
    self._f = float(f) if f <= 1 else 1.0/f
    self._f1 = 1 - self._f
    self._e2 = self._f * (2 - self._f)
    self._ep2 = self._e2 / Math.sq(self._f1) # e2 / (1 - e2)
    self._n = self._f / ( 2 - self._f)
    self._b = self._a * self._f1
    # authalic radius squared
    self._c2 = (Math.sq(self._a) + Math.sq(self._b) *
                (1 if self._e2 == 0 else
                 (Math.atanh(math.sqrt(self._e2)) if self._e2 > 0 else
                  math.atan(math.sqrt(-self._e2))) /
                 math.sqrt(abs(self._e2))))/2
    # The sig12 threshold for "really short"
    self._etol2 = 0.01 * Geodesic.tol2_ / max(0.1, math.sqrt(abs(self._e2)))
    if not(Math.isfinite(self._a) and self._a > 0):
      raise ValueError("Major radius is not positive")
    if not(Math.isfinite(self._b) and self._b > 0):
      raise ValueError("Minor radius is not positive")
    self._A3x = range(Geodesic.nA3x_)
    self._C3x = range(Geodesic.nC3x_)
    self._C4x = range(Geodesic.nC4x_)
    self.A3coeff()
    self.C3coeff()
    self.C4coeff()
Exemple #32
0
    def __init__(self, a, f):
        """
    Construct a Geodesic object for ellipsoid with major radius a and
    flattening f.
    """

        self._a = float(a)
        self._f = float(f) if f <= 1 else 1.0 / f
        self._f1 = 1 - self._f
        self._e2 = self._f * (2 - self._f)
        self._ep2 = self._e2 / Math.sq(self._f1)  # e2 / (1 - e2)
        self._n = self._f / (2 - self._f)
        self._b = self._a * self._f1
        # authalic radius squared
        self._c2 = (
            Math.sq(self._a) + Math.sq(self._b) *
            (1 if self._e2 == 0 else
             (Math.atanh(math.sqrt(self._e2)) if self._e2 > 0 else math.atan(
                 math.sqrt(-self._e2))) / math.sqrt(abs(self._e2)))) / 2
        # The sig12 threshold for "really short"
        self._etol2 = 0.01 * Geodesic.tol2_ / max(0.1, math.sqrt(abs(
            self._e2)))
        if not (Math.isfinite(self._a) and self._a > 0):
            raise ValueError("Major radius is not positive")
        if not (Math.isfinite(self._b) and self._b > 0):
            raise ValueError("Minor radius is not positive")
        self._A3x = range(Geodesic.nA3x_)
        self._C3x = range(Geodesic.nC3x_)
        self._C4x = range(Geodesic.nC4x_)
        self.A3coeff()
        self.C3coeff()
        self.C4coeff()
Exemple #33
0
    def test_GeodSolve80(self):
        # Some tests to add code coverage: computing scale in special cases + zero
        # length geodesic (includes GeodSolve80 - GeodSolve83) + using an incapable
        # line.
        inv = Geodesic.WGS84.Inverse(0, 0, 0, 90, Geodesic.GEODESICSCALE)
        self.assertAlmostEqual(inv["M12"], -0.00528427534, delta=0.5e-10)
        self.assertAlmostEqual(inv["M21"], -0.00528427534, delta=0.5e-10)

        inv = Geodesic.WGS84.Inverse(0, 0, 1e-6, 1e-6, Geodesic.GEODESICSCALE)
        self.assertAlmostEqual(inv["M12"], 1, delta=0.5e-10)
        self.assertAlmostEqual(inv["M21"], 1, delta=0.5e-10)

        inv = Geodesic.WGS84.Inverse(20.001, 0, 20.001, 0, Geodesic.ALL)
        self.assertAlmostEqual(inv["a12"], 0, delta=1e-13)
        self.assertAlmostEqual(inv["s12"], 0, delta=1e-8)
        self.assertAlmostEqual(inv["azi1"], 180, delta=1e-13)
        self.assertAlmostEqual(inv["azi2"], 180, delta=1e-13)
        self.assertAlmostEqual(inv["m12"], 0, delta=1e-8)
        self.assertAlmostEqual(inv["M12"], 1, delta=1e-15)
        self.assertAlmostEqual(inv["M21"], 1, delta=1e-15)
        self.assertAlmostEqual(inv["S12"], 0, delta=1e-10)
        self.assertTrue(Math.copysign(1, inv["a12"]) > 0)
        self.assertTrue(Math.copysign(1, inv["s12"]) > 0)
        self.assertTrue(Math.copysign(1, inv["m12"]) > 0)

        inv = Geodesic.WGS84.Inverse(90, 0, 90, 180, Geodesic.ALL)
        self.assertAlmostEqual(inv["a12"], 0, delta=1e-13)
        self.assertAlmostEqual(inv["s12"], 0, delta=1e-8)
        self.assertAlmostEqual(inv["azi1"], 0, delta=1e-13)
        self.assertAlmostEqual(inv["azi2"], 180, delta=1e-13)
        self.assertAlmostEqual(inv["m12"], 0, delta=1e-8)
        self.assertAlmostEqual(inv["M12"], 1, delta=1e-15)
        self.assertAlmostEqual(inv["M21"], 1, delta=1e-15)
        self.assertAlmostEqual(inv["S12"], 127516405431022.0, delta=0.5)

        # An incapable line which can't take distance as input
        line = Geodesic.WGS84.Line(1, 2, 90, Geodesic.LATITUDE)
        dir = line.Position(1000, Geodesic.EMPTY)
        self.assertTrue(Math.isnan(dir["a12"]))
 def Add(self, y):
   """Add a value"""
   # Here's Shewchuk's solution...
   # hold exact sum as [s, t, u]
   y, u = Math.sum(y, self._t)             # Accumulate starting at
   self._s, self._t = Math.sum(y, self._s) # least significant end
   # Start is _s, _t decreasing and non-adjacent.  Sum is now (s + t + u)
   # exactly with s, t, u non-adjacent and in decreasing order (except
   # for possible zeros).  The following code tries to normalize the
   # result.  Ideally, we want _s = round(s+t+u) and _u = round(s+t+u -
   # _s).  The follow does an approximate job (and maintains the
   # decreasing non-adjacent property).  Here are two "failures" using
   # 3-bit floats:
   #
   # Case 1: _s is not equal to round(s+t+u) -- off by 1 ulp
   # [12, -1] - 8 -> [4, 0, -1] -> [4, -1] = 3 should be [3, 0] = 3
   #
   # Case 2: _s+_t is not as close to s+t+u as it shold be
   # [64, 5] + 4 -> [64, 8, 1] -> [64,  8] = 72 (off by 1)
   #                    should be [80, -7] = 73 (exact)
   #
   # "Fixing" these problems is probably not worth the expense.  The
   # representation inevitably leads to small errors in the accumulated
   # values.  The additional errors illustrated here amount to 1 ulp of
   # the less significant word during each addition to the Accumulator
   # and an additional possible error of 1 ulp in the reported sum.
   #
   # Incidentally, the "ideal" representation described above is not
   # canonical, because _s = round(_s + _t) may not be true.  For
   # example, with 3-bit floats:
   #
   # [128, 16] + 1 -> [160, -16] -- 160 = round(145).
   # But [160, 0] - 16 -> [128, 16] -- 128 = round(144).
   #
   if self._s == 0:            # This implies t == 0,
     self._s = u               # so result is u
   else:
     self._t += u              # otherwise just accumulate u to t.
Exemple #35
0
 def Add(self, y):
     """Add a value"""
     # Here's Shewchuk's solution...
     # hold exact sum as [s, t, u]
     y, u = Math.sum(y, self._t)  # Accumulate starting at
     self._s, self._t = Math.sum(y, self._s)  # least significant end
     # Start is _s, _t decreasing and non-adjacent.  Sum is now (s + t + u)
     # exactly with s, t, u non-adjacent and in decreasing order (except
     # for possible zeros).  The following code tries to normalize the
     # result.  Ideally, we want _s = round(s+t+u) and _u = round(s+t+u -
     # _s).  The follow does an approximate job (and maintains the
     # decreasing non-adjacent property).  Here are two "failures" using
     # 3-bit floats:
     #
     # Case 1: _s is not equal to round(s+t+u) -- off by 1 ulp
     # [12, -1] - 8 -> [4, 0, -1] -> [4, -1] = 3 should be [3, 0] = 3
     #
     # Case 2: _s+_t is not as close to s+t+u as it shold be
     # [64, 5] + 4 -> [64, 8, 1] -> [64,  8] = 72 (off by 1)
     #                    should be [80, -7] = 73 (exact)
     #
     # "Fixing" these problems is probably not worth the expense.  The
     # representation inevitably leads to small errors in the accumulated
     # values.  The additional errors illustrated here amount to 1 ulp of
     # the less significant word during each addition to the Accumulator
     # and an additional possible error of 1 ulp in the reported sum.
     #
     # Incidentally, the "ideal" representation described above is not
     # canonical, because _s = round(_s + _t) may not be true.  For
     # example, with 3-bit floats:
     #
     # [128, 16] + 1 -> [160, -16] -- 160 = round(145).
     # But [160, 0] - 16 -> [128, 16] -- 128 = round(144).
     #
     if self._s == 0:  # This implies t == 0,
         self._s = u  # so result is u
     else:
         self._t += u  # otherwise just accumulate u to t.
Exemple #36
0
 def test_Planimeter19(self):
     # Coverage tests, includes Planimeter19 - Planimeter20 (degenerate
     # polygons) + extra cases.
     PlanimeterTest.polygon.Clear()
     num, perimeter, area = PlanimeterTest.polygon.Compute(False, True)
     self.assertTrue(area == 0)
     self.assertTrue(perimeter == 0)
     num, perimeter, area = PlanimeterTest.polygon.TestPoint(
         1, 1, False, True)
     self.assertTrue(area == 0)
     self.assertTrue(perimeter == 0)
     num, perimeter, area = PlanimeterTest.polygon.TestEdge(
         90, 1000, False, True)
     self.assertTrue(Math.isnan(area))
     self.assertTrue(Math.isnan(perimeter))
     PlanimeterTest.polygon.AddPoint(1, 1)
     num, perimeter, area = PlanimeterTest.polygon.Compute(False, True)
     self.assertTrue(area == 0)
     self.assertTrue(perimeter == 0)
     PlanimeterTest.polyline.Clear()
     num, perimeter, area = PlanimeterTest.polyline.Compute(False, True)
     self.assertTrue(perimeter == 0)
     num, perimeter, area = PlanimeterTest.polyline.TestPoint(
         1, 1, False, True)
     self.assertTrue(perimeter == 0)
     num, perimeter, area = PlanimeterTest.polyline.TestEdge(
         90, 1000, False, True)
     self.assertTrue(Math.isnan(perimeter))
     PlanimeterTest.polyline.AddPoint(1, 1)
     num, perimeter, area = PlanimeterTest.polyline.Compute(False, True)
     self.assertTrue(perimeter == 0)
     PlanimeterTest.polygon.AddPoint(1, 1)
     num, perimeter, area = PlanimeterTest.polyline.TestEdge(
         90, 1000, False, True)
     self.assertAlmostEqual(perimeter, 1000, delta=1e-10)
     num, perimeter, area = PlanimeterTest.polyline.TestPoint(
         2, 2, False, True)
     self.assertAlmostEqual(perimeter, 156876.149, delta=0.5e-3)
Exemple #37
0
 def C2f(eps, c):
     eps2 = Math.sq(eps)
     d = eps
     c[1] = d * (eps2 * (eps2 + 2) + 16) / 32
     d *= eps
     c[2] = d * (eps2 * (35 * eps2 + 64) + 384) / 2048
     d *= eps
     c[3] = d * (15 * eps2 + 80) / 768
     d *= eps
     c[4] = d * (7 * eps2 + 35) / 512
     d *= eps
     c[5] = 63 * d / 1280
     d *= eps
     c[6] = 77 * d / 2048
Exemple #38
0
 def C2f(eps, c):
   eps2 = Math.sq(eps)
   d = eps
   c[1] = d*(eps2*(eps2+2)+16)/32
   d *= eps
   c[2] = d*(eps2*(35*eps2+64)+384)/2048
   d *= eps
   c[3] = d*(15*eps2+80)/768
   d *= eps
   c[4] = d*(7*eps2+35)/512
   d *= eps
   c[5] = 63*d/1280
   d *= eps
   c[6] = 77*d/2048
Exemple #39
0
 def C1pf(eps, c):
   eps2 = Math.sq(eps)
   d = eps
   c[1] = d*(eps2*(205*eps2-432)+768)/1536
   d *= eps
   c[2] = d*(eps2*(4005*eps2-4736)+3840)/12288
   d *= eps
   c[3] = d*(116-225*eps2)/384
   d *= eps
   c[4] = d*(2695-7173*eps2)/7680
   d *= eps
   c[5] = 3467*d/7680
   d *= eps
   c[6] = 38081*d/61440
Exemple #40
0
 def C1f(eps, c):
   eps2 = Math.sq(eps)
   d = eps
   c[1] = d*((6-eps2)*eps2-16)/32
   d *= eps
   c[2] = d*((64-9*eps2)*eps2-128)/2048
   d *= eps
   c[3] = d*(9*eps2-16)/768
   d *= eps
   c[4] = d*(3*eps2-5)/512
   d *= eps
   c[5] = -7*d/1280
   d *= eps
   c[6] = -7*d/2048
Exemple #41
0
 def C1pf(eps, c):
     eps2 = Math.sq(eps)
     d = eps
     c[1] = d * (eps2 * (205 * eps2 - 432) + 768) / 1536
     d *= eps
     c[2] = d * (eps2 * (4005 * eps2 - 4736) + 3840) / 12288
     d *= eps
     c[3] = d * (116 - 225 * eps2) / 384
     d *= eps
     c[4] = d * (2695 - 7173 * eps2) / 7680
     d *= eps
     c[5] = 3467 * d / 7680
     d *= eps
     c[6] = 38081 * d / 61440
Exemple #42
0
 def C1f(eps, c):
     eps2 = Math.sq(eps)
     d = eps
     c[1] = d * ((6 - eps2) * eps2 - 16) / 32
     d *= eps
     c[2] = d * ((64 - 9 * eps2) * eps2 - 128) / 2048
     d *= eps
     c[3] = d * (9 * eps2 - 16) / 768
     d *= eps
     c[4] = d * (3 * eps2 - 5) / 512
     d *= eps
     c[5] = -7 * d / 1280
     d *= eps
     c[6] = -7 * d / 2048
Exemple #43
0
  def ArcDirect(self, lat1, lon1, azi1, a12,
                outmask = GeodesicCapability.STANDARD):
    """Solve the direct geodesic problem in terms of spherical arc length

    :param lat1: latitude of the first point in degrees
    :param lon1: longitude of the first point in degrees
    :param azi1: azimuth at the first point in degrees
    :param a12: spherical arc length from the first point to the second
      in degrees
    :param outmask: the :ref:`output mask <outmask>`
    :return: a :ref:`dict`

    Compute geodesic starting at (*lat1*, *lon1*) with azimuth *azi1*
    and arc length *a12*.  The default value of *outmask* is STANDARD,
    i.e., the *lat1*, *lon1*, *azi1*, *lat2*, *lon2*, *azi2*, *s12*,
    *a12* entries are returned.

    """

    a12, lat2, lon2, azi2, s12, m12, M12, M21, S12 = self._GenDirect(
      lat1, lon1, azi1, True, a12, outmask)
    outmask &= Geodesic.OUT_MASK
    result = {'lat1': Math.LatFix(lat1),
              'lon1': lon1 if outmask & Geodesic.LONG_UNROLL else
              Math.AngNormalize(lon1),
              'azi1': Math.AngNormalize(azi1),
              'a12': a12}
    if outmask & Geodesic.DISTANCE: result['s12'] = s12
    if outmask & Geodesic.LATITUDE: result['lat2'] = lat2
    if outmask & Geodesic.LONGITUDE: result['lon2'] = lon2
    if outmask & Geodesic.AZIMUTH: result['azi2'] = azi2
    if outmask & Geodesic.REDUCEDLENGTH: result['m12'] = m12
    if outmask & Geodesic.GEODESICSCALE:
      result['M12'] = M12; result['M21'] = M21
    if outmask & Geodesic.AREA: result['S12'] = S12
    return result
Exemple #44
0
 def _A3coeff(self):
   """Private: return coefficients for A3"""
   coeff = [
     -3, 128,
     -2, -3, 64,
     -1, -3, -1, 16,
     3, -1, -2, 8,
     1, -1, 2,
     1, 1,
   ]
   o = 0; k = 0
   for j in range(Geodesic.nA3_ - 1, -1, -1): # coeff of eps^j
     m = min(Geodesic.nA3_ - j - 1, j) # order of polynomial in n
     self._A3x[k] = Math.polyval(m, coeff, o, self._n) / coeff[o + m + 1]
     k += 1
     o += m + 2
Exemple #45
0
 def A3coeff(self):
   """Private: return coefficients for A3"""
   coeff = [
     -3, 128,
     -2, -3, 64,
     -1, -3, -1, 16,
     3, -1, -2, 8,
     1, -1, 2,
     1, 1,
   ]
   o = 0; k = 0
   for j in range(Geodesic.nA3_ - 1, -1, -1): # coeff of eps^j
     m = min(Geodesic.nA3_ - j - 1, j) # order of polynomial in n
     self._A3x[k] = Math.polyval(m, coeff, o, self._n) / coeff[o + m + 1]
     k += 1
     o += m + 2
Exemple #46
0
 def test_GeodSolve55(self):
     # Check fix for nan + point on equator or pole not returning all nans in
     # Geodesic::Inverse, found 2015-09-23.
     inv = Geodesic.WGS84.Inverse(Math.nan, 0, 0, 90)
     self.assertTrue(Math.isnan(inv["azi1"]))
     self.assertTrue(Math.isnan(inv["azi2"]))
     self.assertTrue(Math.isnan(inv["s12"]))
     inv = Geodesic.WGS84.Inverse(Math.nan, 0, 90, 9)
     self.assertTrue(Math.isnan(inv["azi1"]))
     self.assertTrue(Math.isnan(inv["azi2"]))
     self.assertTrue(Math.isnan(inv["s12"]))
Exemple #47
0
 def Astroid(x, y):
   """Private: solve astroid equation."""
   # Solve k^4+2*k^3-(x^2+y^2-1)*k^2-2*y^2*k-y^2 = 0 for positive root k.
   # This solution is adapted from Geocentric::Reverse.
   p = Math.sq(x)
   q = Math.sq(y)
   r = (p + q - 1) / 6
   if not(q == 0 and r <= 0):
     # Avoid possible division by zero when r = 0 by multiplying equations
     # for s and t by r^3 and r, resp.
     S = p * q / 4            # S = r^3 * s
     r2 = Math.sq(r)
     r3 = r * r2
     # The discrimant of the quadratic equation for T3.  This is zero on
     # the evolute curve p^(1/3)+q^(1/3) = 1
     disc = S * (S + 2 * r3)
     u = r
     if (disc >= 0):
       T3 = S + r3
       # Pick the sign on the sqrt to maximize abs(T3).  This minimizes loss
       # of precision due to cancellation.  The result is unchanged because
       # of the way the T is used in definition of u.
       T3 += -math.sqrt(disc) if T3 < 0 else math.sqrt(disc) # T3 = (r * t)^3
       # N.B. cbrt always returns the real root.  cbrt(-8) = -2.
       T = Math.cbrt(T3)       # T = r * t
       # T can be zero; but then r2 / T -> 0.
       u += T + (r2 / T if T != 0 else 0)
     else:
       # T is complex, but the way u is defined the result is real.
       ang = math.atan2(math.sqrt(-disc), -(S + r3))
       # There are three possible cube roots.  We choose the root which
       # avoids cancellation.  Note that disc < 0 implies that r < 0.
       u += 2 * r * math.cos(ang / 3)
     v = math.sqrt(Math.sq(u) + q) # guaranteed positive
     # Avoid loss of accuracy when u < 0.
     uv = q / (v - u) if u < 0 else u + v # u+v, guaranteed positive
     w = (uv - q) / (2 * v)               # positive?
     # Rearrange expression for k to avoid loss of accuracy due to
     # subtraction.  Division by 0 not possible because uv > 0, w >= 0.
     k = uv / (math.sqrt(uv + Math.sq(w)) + w) # guaranteed positive
   else:                                       # q == 0 && r <= 0
     # y = 0 with |x| <= 1.  Handle this case directly.
     # for y small, positive root is k = abs(y)/sqrt(1-x^2)
     k = 0
   return k
Exemple #48
0
    def test_Planimeter0(self):
        # Check fix for pole-encircling bug found 2011-03-16
        points = [[89, 0], [89, 90], [89, 180], [89, 270]]
        num, perimeter, area = PlanimeterTest.Planimeter(points)
        self.assertAlmostEqual(perimeter, 631819.8745, delta = 1e-4)
        self.assertAlmostEqual(area, 24952305678.0, delta = 1)
        points = [[-89, 0], [-89, 90], [-89, 180], [-89, 270]]
        num, perimeter, area = PlanimeterTest.Planimeter(points)
        self.assertAlmostEqual(perimeter, 631819.8745, delta = 1e-4)
        self.assertAlmostEqual(area, -24952305678.0, delta = 1)

        points = [[0, -1], [-1, 0], [0, 1], [1, 0]]
        num, perimeter, area = PlanimeterTest.Planimeter(points)
        self.assertAlmostEqual(perimeter, 627598.2731, delta = 1e-4)
        self.assertAlmostEqual(area, 24619419146.0, delta = 1)

        points = [[90, 0], [0, 0], [0, 90]]
        num, perimeter, area = PlanimeterTest.Planimeter(points)
        self.assertAlmostEqual(perimeter, 30022685, delta = 1)
        self.assertAlmostEqual(area, 63758202715511.0, delta = 1)
        num, perimeter, area = PlanimeterTest.PolyLength(points)
        self.assertAlmostEqual(perimeter, 20020719, delta = 1)
        self.assertTrue(Math.isnan(area))
Exemple #49
0
  def __init__(self, a, f):
    """Construct a Geodesic object for ellipsoid with major radius a and
    flattening f.

    """

    self._a = float(a)
    self._f = float(f) if f <= 1 else 1.0/f
    self._f1 = 1 - self._f
    self._e2 = self._f * (2 - self._f)
    self._ep2 = self._e2 / Math.sq(self._f1) # e2 / (1 - e2)
    self._n = self._f / ( 2 - self._f)
    self._b = self._a * self._f1
    # authalic radius squared
    self._c2 = (Math.sq(self._a) + Math.sq(self._b) *
                (1 if self._e2 == 0 else
                 (Math.atanh(math.sqrt(self._e2)) if self._e2 > 0 else
                  math.atan(math.sqrt(-self._e2))) /
                 math.sqrt(abs(self._e2))))/2
    # The sig12 threshold for "really short".  Using the auxiliary sphere
    # solution with dnm computed at (bet1 + bet2) / 2, the relative error in
    # the azimuth consistency check is sig12^2 * abs(f) * min(1, 1-f/2) / 2.
    # (Error measured for 1/100 < b/a < 100 and abs(f) >= 1/1000.  For a given
    # f and sig12, the max error occurs for lines near the pole.  If the old
    # rule for computing dnm = (dn1 + dn2)/2 is used, then the error increases
    # by a factor of 2.)  Setting this equal to epsilon gives sig12 = etol2.
    # Here 0.1 is a safety factor (error decreased by 100) and max(0.001,
    # abs(f)) stops etol2 getting too large in the nearly spherical case.
    self._etol2 = 0.1 * Geodesic.tol2_ / math.sqrt( max(0.001, abs(self._f)) *
                                                    min(1.0, 1-self._f/2) / 2 )
    if not(Math.isfinite(self._a) and self._a > 0):
      raise ValueError("Major radius is not positive")
    if not(Math.isfinite(self._b) and self._b > 0):
      raise ValueError("Minor radius is not positive")
    self._A3x = list(range(Geodesic.nA3x_))
    self._C3x = list(range(Geodesic.nC3x_))
    self._C4x = list(range(Geodesic.nC4x_))
    self.A3coeff()
    self.C3coeff()
    self.C4coeff()
Exemple #50
0
  def Lambda12(self, sbet1, cbet1, dn1, sbet2, cbet2, dn2, salp1, calp1, diffp,
               # Scratch areas of the right size
               C1a, C2a, C3a):
    """Private: Solve hybrid problem"""
    if sbet1 == 0 and calp1 == 0:
      # Break degeneracy of equatorial line.  This case has already been
      # handled.
      calp1 = -Geodesic.tiny_

    # sin(alp1) * cos(bet1) = sin(alp0)
    salp0 = salp1 * cbet1
    calp0 = math.hypot(calp1, salp1 * sbet1) # calp0 > 0

    # real somg1, comg1, somg2, comg2, omg12, lam12
    # tan(bet1) = tan(sig1) * cos(alp1)
    # tan(omg1) = sin(alp0) * tan(sig1) = tan(omg1)=tan(alp1)*sin(bet1)
    ssig1 = sbet1; somg1 = salp0 * sbet1
    csig1 = comg1 = calp1 * cbet1
    ssig1, csig1 = Geodesic.SinCosNorm(ssig1, csig1)
    # SinCosNorm(somg1, comg1); -- don't need to normalize!

    # Enforce symmetries in the case abs(bet2) = -bet1.  Need to be careful
    # about this case, since this can yield singularities in the Newton
    # iteration.
    # sin(alp2) * cos(bet2) = sin(alp0)
    salp2 = salp0 / cbet2 if cbet2 != cbet1 else salp1
    # calp2 = sqrt(1 - sq(salp2))
    #       = sqrt(sq(calp0) - sq(sbet2)) / cbet2
    # and subst for calp0 and rearrange to give (choose positive sqrt
    # to give alp2 in [0, pi/2]).
    calp2 = (math.sqrt(Math.sq(calp1 * cbet1) +
                       ((cbet2 - cbet1) * (cbet1 + cbet2) if cbet1 < -sbet1
                        else (sbet1 - sbet2) * (sbet1 + sbet2))) / cbet2
             if cbet2 != cbet1 or abs(sbet2) != -sbet1 else abs(calp1))
    # tan(bet2) = tan(sig2) * cos(alp2)
    # tan(omg2) = sin(alp0) * tan(sig2).
    ssig2 = sbet2; somg2 = salp0 * sbet2
    csig2 = comg2 = calp2 * cbet2
    ssig2, csig2 = Geodesic.SinCosNorm(ssig2, csig2)
    # SinCosNorm(somg2, comg2); -- don't need to normalize!

    # sig12 = sig2 - sig1, limit to [0, pi]
    sig12 = math.atan2(max(csig1 * ssig2 - ssig1 * csig2, 0.0),
                       csig1 * csig2 + ssig1 * ssig2)

    # omg12 = omg2 - omg1, limit to [0, pi]
    omg12 = math.atan2(max(comg1 * somg2 - somg1 * comg2, 0.0),
                       comg1 * comg2 + somg1 * somg2)
    # real B312, h0
    k2 = Math.sq(calp0) * self._ep2
    eps = k2 / (2 * (1 + math.sqrt(1 + k2)) + k2)
    self.C3f(eps, C3a)
    B312 = (Geodesic.SinCosSeries(True, ssig2, csig2, C3a, Geodesic.nC3_-1) -
            Geodesic.SinCosSeries(True, ssig1, csig1, C3a, Geodesic.nC3_-1))
    h0 = -self._f * self.A3f(eps)
    domg12 = salp0 * h0 * (sig12 + B312)
    lam12 = omg12 + domg12

    if diffp:
      if calp2 == 0:
        dlam12 = - 2 * self._f1 * dn1 / sbet1
      else:
        dummy, dlam12, dummy, dummy, dummy = self.Lengths(
          eps, sig12, ssig1, csig1, dn1, ssig2, csig2, dn2, cbet1, cbet2,
          False, C1a, C2a)
        dlam12 *= self._f1 / (calp2 * cbet2)
    else:
      dlam12 = Math.nan

    return (lam12, salp2, calp2, sig12, ssig1, csig1, ssig2, csig2, eps,
            domg12, dlam12)
Exemple #51
0
 def CheckDistance(s):
   """Check that s is a legal distance"""
   if not (Math.isfinite(s)):
     raise ValueError("distance " + str(s) + " not a finite number")
  def __init__(self, geod, lat1, lon1, azi1,
               caps = GeodesicCapability.STANDARD |
               GeodesicCapability.DISTANCE_IN,
               salp1 = Math.nan, calp1 = Math.nan):
    """Construct a GeodesicLine object

    :param geod: a :class:`~geographiclib.geodesic.Geodesic` object
    :param lat1: latitude of the first point in degrees
    :param lon1: longitude of the first point in degrees
    :param azi1: azimuth at the first point in degrees
    :param caps: the :ref:`capabilities <outmask>`

    This creates an object allowing points along a geodesic starting at
    (*lat1*, *lon1*), with azimuth *azi1* to be found.  The default
    value of *caps* is STANDARD | DISTANCE_IN.  The optional parameters
    *salp1* and *calp1* should not be supplied; they are part of the
    private interface.

    """

    from geographiclib.geodesic import Geodesic
    self.a = geod.a
    """The equatorial radius in meters (readonly)"""
    self.f = geod.f
    """The flattening (readonly)"""
    self._b = geod._b
    self._c2 = geod._c2
    self._f1 = geod._f1
    self.caps = (caps | Geodesic.LATITUDE | Geodesic.AZIMUTH |
                  Geodesic.LONG_UNROLL)
    """the capabilities (readonly)"""

    # Guard against underflow in salp0
    self.lat1 = Math.LatFix(lat1)
    """the latitude of the first point in degrees (readonly)"""
    self.lon1 = lon1
    """the longitude of the first point in degrees (readonly)"""
    if Math.isnan(salp1) or Math.isnan(calp1):
      self.azi1 = Math.AngNormalize(azi1)
      self.salp1, self.calp1 = Math.sincosd(Math.AngRound(azi1))
    else:
      self.azi1 = azi1
      """the azimuth at the first point in degrees (readonly)"""
      self.salp1 = salp1
      """the sine of the azimuth at the first point (readonly)"""
      self.calp1 = calp1
      """the cosine of the azimuth at the first point (readonly)"""

    # real cbet1, sbet1
    sbet1, cbet1 = Math.sincosd(Math.AngRound(lat1)); sbet1 *= self._f1
    # Ensure cbet1 = +epsilon at poles
    sbet1, cbet1 = Math.norm(sbet1, cbet1); cbet1 = max(Geodesic.tiny_, cbet1)
    self._dn1 = math.sqrt(1 + geod._ep2 * Math.sq(sbet1))

    # Evaluate alp0 from sin(alp1) * cos(bet1) = sin(alp0),
    self._salp0 = self.salp1 * cbet1 # alp0 in [0, pi/2 - |bet1|]
    # Alt: calp0 = hypot(sbet1, calp1 * cbet1).  The following
    # is slightly better (consider the case salp1 = 0).
    self._calp0 = math.hypot(self.calp1, self.salp1 * sbet1)
    # Evaluate sig with tan(bet1) = tan(sig1) * cos(alp1).
    # sig = 0 is nearest northward crossing of equator.
    # With bet1 = 0, alp1 = pi/2, we have sig1 = 0 (equatorial line).
    # With bet1 =  pi/2, alp1 = -pi, sig1 =  pi/2
    # With bet1 = -pi/2, alp1 =  0 , sig1 = -pi/2
    # Evaluate omg1 with tan(omg1) = sin(alp0) * tan(sig1).
    # With alp0 in (0, pi/2], quadrants for sig and omg coincide.
    # No atan2(0,0) ambiguity at poles since cbet1 = +epsilon.
    # With alp0 = 0, omg1 = 0 for alp1 = 0, omg1 = pi for alp1 = pi.
    self._ssig1 = sbet1; self._somg1 = self._salp0 * sbet1
    self._csig1 = self._comg1 = (cbet1 * self.calp1
                                 if sbet1 != 0 or self.calp1 != 0 else 1)
    # sig1 in (-pi, pi]
    self._ssig1, self._csig1 = Math.norm(self._ssig1, self._csig1)
    # No need to normalize
    # self._somg1, self._comg1 = Math.norm(self._somg1, self._comg1)

    self._k2 = Math.sq(self._calp0) * geod._ep2
    eps = self._k2 / (2 * (1 + math.sqrt(1 + self._k2)) + self._k2)

    if self.caps & Geodesic.CAP_C1:
      self._A1m1 = Geodesic._A1m1f(eps)
      self._C1a = list(range(Geodesic.nC1_ + 1))
      Geodesic._C1f(eps, self._C1a)
      self._B11 = Geodesic._SinCosSeries(
        True, self._ssig1, self._csig1, self._C1a)
      s = math.sin(self._B11); c = math.cos(self._B11)
      # tau1 = sig1 + B11
      self._stau1 = self._ssig1 * c + self._csig1 * s
      self._ctau1 = self._csig1 * c - self._ssig1 * s
      # Not necessary because C1pa reverts C1a
      #    _B11 = -_SinCosSeries(true, _stau1, _ctau1, _C1pa)

    if self.caps & Geodesic.CAP_C1p:
      self._C1pa = list(range(Geodesic.nC1p_ + 1))
      Geodesic._C1pf(eps, self._C1pa)

    if self.caps & Geodesic.CAP_C2:
      self._A2m1 = Geodesic._A2m1f(eps)
      self._C2a = list(range(Geodesic.nC2_ + 1))
      Geodesic._C2f(eps, self._C2a)
      self._B21 = Geodesic._SinCosSeries(
        True, self._ssig1, self._csig1, self._C2a)

    if self.caps & Geodesic.CAP_C3:
      self._C3a = list(range(Geodesic.nC3_))
      geod._C3f(eps, self._C3a)
      self._A3c = -self.f * self._salp0 * geod._A3f(eps)
      self._B31 = Geodesic._SinCosSeries(
        True, self._ssig1, self._csig1, self._C3a)

    if self.caps & Geodesic.CAP_C4:
      self._C4a = list(range(Geodesic.nC4_))
      geod._C4f(eps, self._C4a)
      # Multiplier = a^2 * e^2 * cos(alpha0) * sin(alpha0)
      self._A4 = Math.sq(self.a) * self._calp0 * self._salp0 * geod._e2
      self._B41 = Geodesic._SinCosSeries(
        False, self._ssig1, self._csig1, self._C4a)
    self.s13 = Math.nan
    """the distance between point 1 and point 3 in meters (readonly)"""
    self.a13 = Math.nan
    """the arc length between point 1 and point 3 in degrees (readonly)"""
  def _GenPosition(self, arcmode, s12_a12, outmask):
    """Private: General solution of position along geodesic"""
    from geographiclib.geodesic import Geodesic
    a12 = lat2 = lon2 = azi2 = s12 = m12 = M12 = M21 = S12 = Math.nan
    outmask &= self.caps & Geodesic.OUT_MASK
    if not (arcmode or
            (self.caps & (Geodesic.OUT_MASK & Geodesic.DISTANCE_IN))):
      # Uninitialized or impossible distance calculation requested
      return a12, lat2, lon2, azi2, s12, m12, M12, M21, S12

    # Avoid warning about uninitialized B12.
    B12 = 0.0; AB1 = 0.0
    if arcmode:
      # Interpret s12_a12 as spherical arc length
      sig12 = math.radians(s12_a12)
      ssig12, csig12 = Math.sincosd(s12_a12)
    else:
      # Interpret s12_a12 as distance
      tau12 = s12_a12 / (self._b * (1 + self._A1m1))
      s = math.sin(tau12); c = math.cos(tau12)
      # tau2 = tau1 + tau12
      B12 = - Geodesic._SinCosSeries(True,
                                    self._stau1 * c + self._ctau1 * s,
                                    self._ctau1 * c - self._stau1 * s,
                                    self._C1pa)
      sig12 = tau12 - (B12 - self._B11)
      ssig12 = math.sin(sig12); csig12 = math.cos(sig12)
      if abs(self.f) > 0.01:
        # Reverted distance series is inaccurate for |f| > 1/100, so correct
        # sig12 with 1 Newton iteration.  The following table shows the
        # approximate maximum error for a = WGS_a() and various f relative to
        # GeodesicExact.
        #     erri = the error in the inverse solution (nm)
        #     errd = the error in the direct solution (series only) (nm)
        #     errda = the error in the direct solution (series + 1 Newton) (nm)
        #
        #       f     erri  errd errda
        #     -1/5    12e6 1.2e9  69e6
        #     -1/10  123e3  12e6 765e3
        #     -1/20   1110 108e3  7155
        #     -1/50  18.63 200.9 27.12
        #     -1/100 18.63 23.78 23.37
        #     -1/150 18.63 21.05 20.26
        #      1/150 22.35 24.73 25.83
        #      1/100 22.35 25.03 25.31
        #      1/50  29.80 231.9 30.44
        #      1/20   5376 146e3  10e3
        #      1/10  829e3  22e6 1.5e6
        #      1/5   157e6 3.8e9 280e6
        ssig2 = self._ssig1 * csig12 + self._csig1 * ssig12
        csig2 = self._csig1 * csig12 - self._ssig1 * ssig12
        B12 = Geodesic._SinCosSeries(True, ssig2, csig2, self._C1a)
        serr = ((1 + self._A1m1) * (sig12 + (B12 - self._B11)) -
                s12_a12 / self._b)
        sig12 = sig12 - serr / math.sqrt(1 + self._k2 * Math.sq(ssig2))
        ssig12 = math.sin(sig12); csig12 = math.cos(sig12)
        # Update B12 below

    # real omg12, lam12, lon12
    # real ssig2, csig2, sbet2, cbet2, somg2, comg2, salp2, calp2
    # sig2 = sig1 + sig12
    ssig2 = self._ssig1 * csig12 + self._csig1 * ssig12
    csig2 = self._csig1 * csig12 - self._ssig1 * ssig12
    dn2 = math.sqrt(1 + self._k2 * Math.sq(ssig2))
    if outmask & (
      Geodesic.DISTANCE | Geodesic.REDUCEDLENGTH | Geodesic.GEODESICSCALE):
      if arcmode or abs(self.f) > 0.01:
        B12 = Geodesic._SinCosSeries(True, ssig2, csig2, self._C1a)
      AB1 = (1 + self._A1m1) * (B12 - self._B11)
    # sin(bet2) = cos(alp0) * sin(sig2)
    sbet2 = self._calp0 * ssig2
    # Alt: cbet2 = hypot(csig2, salp0 * ssig2)
    cbet2 = math.hypot(self._salp0, self._calp0 * csig2)
    if cbet2 == 0:
      # I.e., salp0 = 0, csig2 = 0.  Break the degeneracy in this case
      cbet2 = csig2 = Geodesic.tiny_
    # tan(alp0) = cos(sig2)*tan(alp2)
    salp2 = self._salp0; calp2 = self._calp0 * csig2 # No need to normalize

    if outmask & Geodesic.DISTANCE:
      s12 = self._b * ((1 + self._A1m1) * sig12 + AB1) if arcmode else s12_a12

    if outmask & Geodesic.LONGITUDE:
      # tan(omg2) = sin(alp0) * tan(sig2)
      somg2 = self._salp0 * ssig2; comg2 = csig2 # No need to normalize
      E = Math.copysign(1, self._salp0)          # East or west going?
      # omg12 = omg2 - omg1
      omg12 = (E * (sig12
                    - (math.atan2(          ssig2,       csig2) -
                       math.atan2(    self._ssig1, self._csig1))
                    + (math.atan2(E *       somg2,       comg2) -
                       math.atan2(E * self._somg1, self._comg1)))
               if outmask & Geodesic.LONG_UNROLL
               else math.atan2(somg2 * self._comg1 - comg2 * self._somg1,
                               comg2 * self._comg1 + somg2 * self._somg1))
      lam12 = omg12 + self._A3c * (
        sig12 + (Geodesic._SinCosSeries(True, ssig2, csig2, self._C3a)
                 - self._B31))
      lon12 = math.degrees(lam12)
      lon2 = (self.lon1 + lon12 if outmask & Geodesic.LONG_UNROLL else
              Math.AngNormalize(Math.AngNormalize(self.lon1) +
                                Math.AngNormalize(lon12)))

    if outmask & Geodesic.LATITUDE:
      lat2 = Math.atan2d(sbet2, self._f1 * cbet2)

    if outmask & Geodesic.AZIMUTH:
      # minus signs give range [-180, 180). 0- converts -0 to +0.
      azi2 = Math.atan2d(salp2, calp2)

    if outmask & (Geodesic.REDUCEDLENGTH | Geodesic.GEODESICSCALE):
      B22 = Geodesic._SinCosSeries(True, ssig2, csig2, self._C2a)
      AB2 = (1 + self._A2m1) * (B22 - self._B21)
      J12 = (self._A1m1 - self._A2m1) * sig12 + (AB1 - AB2)
      if outmask & Geodesic.REDUCEDLENGTH:
        # Add parens around (_csig1 * ssig2) and (_ssig1 * csig2) to ensure
        # accurate cancellation in the case of coincident points.
        m12 = self._b * ((      dn2 * (self._csig1 * ssig2) -
                          self._dn1 * (self._ssig1 * csig2))
                         - self._csig1 * csig2 * J12)
      if outmask & Geodesic.GEODESICSCALE:
        t = (self._k2 * (ssig2 - self._ssig1) *
             (ssig2 + self._ssig1) / (self._dn1 + dn2))
        M12 = csig12 + (t * ssig2 - csig2 * J12) * self._ssig1 / self._dn1
        M21 = csig12 - (t * self._ssig1 - self._csig1 * J12) * ssig2 / dn2

    if outmask & Geodesic.AREA:
      B42 = Geodesic._SinCosSeries(False, ssig2, csig2, self._C4a)
      # real salp12, calp12
      if self._calp0 == 0 or self._salp0 == 0:
        # alp12 = alp2 - alp1, used in atan2 so no need to normalize
        salp12 = salp2 * self.calp1 - calp2 * self.salp1
        calp12 = calp2 * self.calp1 + salp2 * self.salp1
      else:
        # tan(alp) = tan(alp0) * sec(sig)
        # tan(alp2-alp1) = (tan(alp2) -tan(alp1)) / (tan(alp2)*tan(alp1)+1)
        # = calp0 * salp0 * (csig1-csig2) / (salp0^2 + calp0^2 * csig1*csig2)
        # If csig12 > 0, write
        #   csig1 - csig2 = ssig12 * (csig1 * ssig12 / (1 + csig12) + ssig1)
        # else
        #   csig1 - csig2 = csig1 * (1 - csig12) + ssig12 * ssig1
        # No need to normalize
        salp12 = self._calp0 * self._salp0 * (
          self._csig1 * (1 - csig12) + ssig12 * self._ssig1 if csig12 <= 0
          else ssig12 * (self._csig1 * ssig12 / (1 + csig12) + self._ssig1))
        calp12 = (Math.sq(self._salp0) +
                  Math.sq(self._calp0) * self._csig1 * csig2)
      S12 = (self._c2 * math.atan2(salp12, calp12) +
             self._A4 * (B42 - self._B41))

    a12 = s12_a12 if arcmode else math.degrees(sig12)
    return a12, lat2, lon2, azi2, s12, m12, M12, M21, S12
Exemple #54
0
  def InverseStart(self, sbet1, cbet1, dn1, sbet2, cbet2, dn2, lam12,
                   # Scratch areas of the right size
                   C1a, C2a):
    """Private: Find a starting value for Newton's method."""
    # Return a starting point for Newton's method in salp1 and calp1 (function
    # value is -1).  If Newton's method doesn't need to be used, return also
    # salp2 and calp2 and function value is sig12.
    sig12 = -1; salp2 = calp2 = dnm = Math.nan # Return values
    # bet12 = bet2 - bet1 in [0, pi); bet12a = bet2 + bet1 in (-pi, 0]
    sbet12 = sbet2 * cbet1 - cbet2 * sbet1
    cbet12 = cbet2 * cbet1 + sbet2 * sbet1
    # Volatile declaration needed to fix inverse cases
    # 88.202499451857 0 -88.202499451857 179.981022032992859592
    # 89.262080389218 0 -89.262080389218 179.992207982775375662
    # 89.333123580033 0 -89.333123580032997687 179.99295812360148422
    # which otherwise fail with g++ 4.4.4 x86 -O3
    sbet12a = sbet2 * cbet1
    sbet12a += cbet2 * sbet1

    shortline = cbet12 >= 0 and sbet12 < 0.5 and cbet2 * lam12 < 0.5
    omg12 = lam12
    if shortline:
      sbetm2 = Math.sq(sbet1 + sbet2)
      # sin((bet1+bet2)/2)^2
      # =  (sbet1 + sbet2)^2 / ((sbet1 + sbet2)^2 + (cbet1 + cbet2)^2)
      sbetm2 /= sbetm2 + Math.sq(cbet1 + cbet2)
      dnm = math.sqrt(1 + self._ep2 * sbetm2)
      omg12 /= self._f1 * dnm
    somg12 = math.sin(omg12); comg12 = math.cos(omg12)

    salp1 = cbet2 * somg12
    calp1 = (
      sbet12 + cbet2 * sbet1 * Math.sq(somg12) / (1 + comg12) if comg12 >= 0
      else sbet12a - cbet2 * sbet1 * Math.sq(somg12) / (1 - comg12))

    ssig12 = math.hypot(salp1, calp1)
    csig12 = sbet1 * sbet2 + cbet1 * cbet2 * comg12

    if shortline and ssig12 < self._etol2:
      # really short lines
      salp2 = cbet1 * somg12
      calp2 = sbet12 - cbet1 * sbet2 * (Math.sq(somg12) / (1 + comg12)
                                        if comg12 >= 0 else 1 - comg12)
      salp2, calp2 = Geodesic.SinCosNorm(salp2, calp2)
      # Set return value
      sig12 = math.atan2(ssig12, csig12)
    elif (abs(self._n) >= 0.1 or # Skip astroid calc if too eccentric
          csig12 >= 0 or
          ssig12 >= 6 * abs(self._n) * math.pi * Math.sq(cbet1)):
      # Nothing to do, zeroth order spherical approximation is OK
      pass
    else:
      # Scale lam12 and bet2 to x, y coordinate system where antipodal point
      # is at origin and singular point is at y = 0, x = -1.
      # real y, lamscale, betscale
      # Volatile declaration needed to fix inverse case
      # 56.320923501171 0 -56.320923501171 179.664747671772880215
      # which otherwise fails with g++ 4.4.4 x86 -O3
      # volatile real x
      if self._f >= 0:            # In fact f == 0 does not get here
        # x = dlong, y = dlat
        k2 = Math.sq(sbet1) * self._ep2
        eps = k2 / (2 * (1 + math.sqrt(1 + k2)) + k2)
        lamscale = self._f * cbet1 * self.A3f(eps) * math.pi
        betscale = lamscale * cbet1
        x = (lam12 - math.pi) / lamscale
        y = sbet12a / betscale
      else:                     # _f < 0
        # x = dlat, y = dlong
        cbet12a = cbet2 * cbet1 - sbet2 * sbet1
        bet12a = math.atan2(sbet12a, cbet12a)
        # real m12b, m0, dummy
        # In the case of lon12 = 180, this repeats a calculation made in
        # Inverse.
        dummy, m12b, m0, dummy, dummy = self.Lengths(
          self._n, math.pi + bet12a, sbet1, -cbet1, dn1, sbet2, cbet2, dn2,
          cbet1, cbet2, False, C1a, C2a)
        x = -1 + m12b / (cbet1 * cbet2 * m0 * math.pi)
        betscale = (sbet12a / x if x < -0.01
                    else -self._f * Math.sq(cbet1) * math.pi)
        lamscale = betscale / cbet1
        y = (lam12 - math.pi) / lamscale

      if y > -Geodesic.tol1_ and x > -1 - Geodesic.xthresh_:
        # strip near cut
        if self._f >= 0:
          salp1 = min(1.0, -x); calp1 = - math.sqrt(1 - Math.sq(salp1))
        else:
          calp1 = max((0.0 if x > -Geodesic.tol1_ else -1.0), x)
          salp1 = math.sqrt(1 - Math.sq(calp1))
      else:
        # Estimate alp1, by solving the astroid problem.
        #
        # Could estimate alpha1 = theta + pi/2, directly, i.e.,
        #   calp1 = y/k; salp1 = -x/(1+k);  for _f >= 0
        #   calp1 = x/(1+k); salp1 = -y/k;  for _f < 0 (need to check)
        #
        # However, it's better to estimate omg12 from astroid and use
        # spherical formula to compute alp1.  This reduces the mean number of
        # Newton iterations for astroid cases from 2.24 (min 0, max 6) to 2.12
        # (min 0 max 5).  The changes in the number of iterations are as
        # follows:
        #
        # change percent
        #    1       5
        #    0      78
        #   -1      16
        #   -2       0.6
        #   -3       0.04
        #   -4       0.002
        #
        # The histogram of iterations is (m = number of iterations estimating
        # alp1 directly, n = number of iterations estimating via omg12, total
        # number of trials = 148605):
        #
        #  iter    m      n
        #    0   148    186
        #    1 13046  13845
        #    2 93315 102225
        #    3 36189  32341
        #    4  5396      7
        #    5   455      1
        #    6    56      0
        #
        # Because omg12 is near pi, estimate work with omg12a = pi - omg12
        k = Geodesic.Astroid(x, y)
        omg12a = lamscale * ( -x * k/(1 + k) if self._f >= 0
                               else -y * (1 + k)/k )
        somg12 = math.sin(omg12a); comg12 = -math.cos(omg12a)
        # Update spherical estimate of alp1 using omg12 instead of lam12
        salp1 = cbet2 * somg12
        calp1 = sbet12a - cbet2 * sbet1 * Math.sq(somg12) / (1 - comg12)
    # Sanity check on starting guess.  Backwards check allows NaN through.
    if not (salp1 <= 0):
      salp1, calp1 = Geodesic.SinCosNorm(salp1, calp1)
    else:
      salp1 = 1; calp1 = 0
    return sig12, salp1, calp1, salp2, calp2, dnm
Exemple #55
0
 def A2m1f(eps):
   """Private: return A2-1"""
   eps2 = Math.sq(eps)
   t = eps2*(eps2*(25*eps2+36)+64)/256
   return t * (1 - eps) - eps
Exemple #56
0
 def A3f(self, eps):
   """Private: return A3"""
   # Evaluate A3
   return Math.polyval(Geodesic.nA3_ - 1, self._A3x, 0, eps)
Exemple #57
0
 def A1m1f(eps):
   """Private: return A1-1."""
   eps2 = Math.sq(eps)
   t = eps2*(eps2*(eps2+4)+64)/256
   return (t + eps) / (1 - eps)
Exemple #58
0
 def test_GeodSolve14(self):
     # Check fix for inverse ignoring lon12 = nan
     inv = Geodesic.WGS84.Inverse(0, 0, 1, Math.nan)
     self.assertTrue(Math.isnan(inv["azi1"]))
     self.assertTrue(Math.isnan(inv["azi2"]))
     self.assertTrue(Math.isnan(inv["s12"]))
Exemple #59
0
  def __init__(self, geod, lat1, lon1, azi1, caps = GeodesicCapability.ALL):
    from geographiclib.geodesic import Geodesic
    self._a = geod._a
    self._f = geod._f
    self._b = geod._b
    self._c2 = geod._c2
    self._f1 = geod._f1
    self._caps = caps | Geodesic.LATITUDE | Geodesic.AZIMUTH

    # Guard against underflow in salp0
    azi1 = Geodesic.AngRound(Math.AngNormalize(azi1))
    lon1 = Math.AngNormalize(lon1)
    self._lat1 = lat1
    self._lon1 = lon1
    self._azi1 = azi1
    # alp1 is in [0, pi]
    alp1 = azi1 * Math.degree
    # Enforce sin(pi) == 0 and cos(pi/2) == 0.  Better to face the ensuing
    # problems directly than to skirt them.
    self._salp1 = 0 if     azi1  == -180 else math.sin(alp1)
    self._calp1 = 0 if abs(azi1) ==   90 else math.cos(alp1)
    # real cbet1, sbet1, phi
    phi = lat1 * Math.degree
    # Ensure cbet1 = +epsilon at poles
    sbet1 = self._f1 * math.sin(phi)
    cbet1 = Geodesic.tiny_ if abs(lat1) == 90 else math.cos(phi)
    sbet1, cbet1 = Geodesic.SinCosNorm(sbet1, cbet1)
    self._dn1 = math.sqrt(1 + geod._ep2 * Math.sq(sbet1))

    # Evaluate alp0 from sin(alp1) * cos(bet1) = sin(alp0),
    self._salp0 = self._salp1 * cbet1 # alp0 in [0, pi/2 - |bet1|]
    # Alt: calp0 = hypot(sbet1, calp1 * cbet1).  The following
    # is slightly better (consider the case salp1 = 0).
    self._calp0 = math.hypot(self._calp1, self._salp1 * sbet1)
    # Evaluate sig with tan(bet1) = tan(sig1) * cos(alp1).
    # sig = 0 is nearest northward crossing of equator.
    # With bet1 = 0, alp1 = pi/2, we have sig1 = 0 (equatorial line).
    # With bet1 =  pi/2, alp1 = -pi, sig1 =  pi/2
    # With bet1 = -pi/2, alp1 =  0 , sig1 = -pi/2
    # Evaluate omg1 with tan(omg1) = sin(alp0) * tan(sig1).
    # With alp0 in (0, pi/2], quadrants for sig and omg coincide.
    # No atan2(0,0) ambiguity at poles since cbet1 = +epsilon.
    # With alp0 = 0, omg1 = 0 for alp1 = 0, omg1 = pi for alp1 = pi.
    self._ssig1 = sbet1; self._somg1 = self._salp0 * sbet1
    self._csig1 = self._comg1 = (cbet1 * self._calp1
                                 if sbet1 != 0 or self._calp1 != 0 else 1)
    # sig1 in (-pi, pi]
    self._ssig1, self._csig1 = Geodesic.SinCosNorm(self._ssig1, self._csig1)
    # No need to normalize
    # self._somg1, self._comg1 = Geodesic.SinCosNorm(self._somg1, self._comg1)

    self._k2 = Math.sq(self._calp0) * geod._ep2
    eps = self._k2 / (2 * (1 + math.sqrt(1 + self._k2)) + self._k2)

    if self._caps & Geodesic.CAP_C1:
      self._A1m1 = Geodesic.A1m1f(eps)
      self._C1a = list(range(Geodesic.nC1_ + 1))
      Geodesic.C1f(eps, self._C1a)
      self._B11 = Geodesic.SinCosSeries(
        True, self._ssig1, self._csig1, self._C1a, Geodesic.nC1_)
      s = math.sin(self._B11); c = math.cos(self._B11)
      # tau1 = sig1 + B11
      self._stau1 = self._ssig1 * c + self._csig1 * s
      self._ctau1 = self._csig1 * c - self._ssig1 * s
      # Not necessary because C1pa reverts C1a
      #    _B11 = -SinCosSeries(true, _stau1, _ctau1, _C1pa, nC1p_)

    if self._caps & Geodesic.CAP_C1p:
      self._C1pa = list(range(Geodesic.nC1p_ + 1))
      Geodesic.C1pf(eps, self._C1pa)

    if self._caps & Geodesic.CAP_C2:
      self._A2m1 = Geodesic.A2m1f(eps)
      self._C2a = list(range(Geodesic.nC2_ + 1))
      Geodesic.C2f(eps, self._C2a)
      self._B21 = Geodesic.SinCosSeries(
        True, self._ssig1, self._csig1, self._C2a, Geodesic.nC2_)

    if self._caps & Geodesic.CAP_C3:
      self._C3a = list(range(Geodesic.nC3_))
      geod.C3f(eps, self._C3a)
      self._A3c = -self._f * self._salp0 * geod.A3f(eps)
      self._B31 = Geodesic.SinCosSeries(
        True, self._ssig1, self._csig1, self._C3a, Geodesic.nC3_-1)

    if self._caps & Geodesic.CAP_C4:
      self._C4a = list(range(Geodesic.nC4_))
      geod.C4f(eps, self._C4a)
      # Multiplier = a^2 * e^2 * cos(alpha0) * sin(alpha0)
      self._A4 = Math.sq(self._a) * self._calp0 * self._salp0 * geod._e2
      self._B41 = Geodesic.SinCosSeries(
        False, self._ssig1, self._csig1, self._C4a, Geodesic.nC4_)
Exemple #60
0
  def GenInverse(self, lat1, lon1, lat2, lon2, outmask):
    """Private: General version of the inverse problem"""
    a12 = s12 = azi1 = azi2 = m12 = M12 = M21 = S12 = Math.nan # return vals

    outmask &= Geodesic.OUT_MASK
    # Compute longitude difference (AngDiff does this carefully).  Result is
    # in [-180, 180] but -180 is only for west-going geodesics.  180 is for
    # east-going and meridional geodesics.
    lon12 = Math.AngDiff(Math.AngNormalize(lon1), Math.AngNormalize(lon2))
    # If very close to being on the same half-meridian, then make it so.
    lon12 = Geodesic.AngRound(lon12)
    # Make longitude difference positive.
    lonsign = 1 if lon12 >= 0 else -1
    lon12 *= lonsign
    # If really close to the equator, treat as on equator.
    lat1 = Geodesic.AngRound(lat1)
    lat2 = Geodesic.AngRound(lat2)
    # Swap points so that point with higher (abs) latitude is point 1
    swapp = 1 if abs(lat1) >= abs(lat2) else -1
    if swapp < 0:
      lonsign *= -1
      lat2, lat1 = lat1, lat2
    # Make lat1 <= 0
    latsign = 1 if lat1 < 0 else -1
    lat1 *= latsign
    lat2 *= latsign
    # Now we have
    #
    #     0 <= lon12 <= 180
    #     -90 <= lat1 <= 0
    #     lat1 <= lat2 <= -lat1
    #
    # longsign, swapp, latsign register the transformation to bring the
    # coordinates to this canonical form.  In all cases, 1 means no change was
    # made.  We make these transformations so that there are few cases to
    # check, e.g., on verifying quadrants in atan2.  In addition, this
    # enforces some symmetries in the results returned.

    # real phi, sbet1, cbet1, sbet2, cbet2, s12x, m12x

    phi = lat1 * Math.degree
    # Ensure cbet1 = +epsilon at poles
    sbet1 = self._f1 * math.sin(phi)
    cbet1 = Geodesic.tiny_ if lat1 == -90 else math.cos(phi)
    sbet1, cbet1 = Geodesic.SinCosNorm(sbet1, cbet1)

    phi = lat2 * Math.degree
    # Ensure cbet2 = +epsilon at poles
    sbet2 = self._f1 * math.sin(phi)
    cbet2 = Geodesic.tiny_ if abs(lat2) == 90 else math.cos(phi)
    sbet2, cbet2 = Geodesic.SinCosNorm(sbet2, cbet2)

    # If cbet1 < -sbet1, then cbet2 - cbet1 is a sensitive measure of the
    # |bet1| - |bet2|.  Alternatively (cbet1 >= -sbet1), abs(sbet2) + sbet1 is
    # a better measure.  This logic is used in assigning calp2 in Lambda12.
    # Sometimes these quantities vanish and in that case we force bet2 = +/-
    # bet1 exactly.  An example where is is necessary is the inverse problem
    # 48.522876735459 0 -48.52287673545898293 179.599720456223079643
    # which failed with Visual Studio 10 (Release and Debug)

    if cbet1 < -sbet1:
      if cbet2 == cbet1:
        sbet2 = sbet1 if sbet2 < 0 else -sbet1
    else:
      if abs(sbet2) == -sbet1:
        cbet2 = cbet1

    dn1 = math.sqrt(1 + self._ep2 * Math.sq(sbet1))
    dn2 = math.sqrt(1 + self._ep2 * Math.sq(sbet2))

    lam12 = lon12 * Math.degree
    slam12 = 0 if lon12 == 180 else math.sin(lam12)
    clam12 = math.cos(lam12)      # lon12 == 90 isn't interesting

    # real a12, sig12, calp1, salp1, calp2, salp2
    # index zero elements of these arrays are unused
    C1a = list(range(Geodesic.nC1_ + 1))
    C2a = list(range(Geodesic.nC2_ + 1))
    C3a = list(range(Geodesic.nC3_))

    meridian = lat1 == -90 or slam12 == 0

    if meridian:

      # Endpoints are on a single full meridian, so the geodesic might lie on
      # a meridian.

      calp1 = clam12; salp1 = slam12 # Head to the target longitude
      calp2 = 1; salp2 = 0           # At the target we're heading north

      # tan(bet) = tan(sig) * cos(alp)
      ssig1 = sbet1; csig1 = calp1 * cbet1
      ssig2 = sbet2; csig2 = calp2 * cbet2

      # sig12 = sig2 - sig1
      sig12 = math.atan2(max(csig1 * ssig2 - ssig1 * csig2, 0.0),
                         csig1 * csig2 + ssig1 * ssig2)

      s12x, m12x, dummy, M12, M21 = self.Lengths(
        self._n, sig12, ssig1, csig1, dn1, ssig2, csig2, dn2, cbet1, cbet2,
        (outmask & Geodesic.GEODESICSCALE) != 0, C1a, C2a)

      # Add the check for sig12 since zero length geodesics might yield m12 <
      # 0.  Test case was
      #
      #    echo 20.001 0 20.001 0 | GeodSolve -i
      #
      # In fact, we will have sig12 > pi/2 for meridional geodesic which is
      # not a shortest path.
      if sig12 < 1 or m12x >= 0:
        m12x *= self._b
        s12x *= self._b
        a12 = sig12 / Math.degree
      else:
        # m12 < 0, i.e., prolate and too close to anti-podal
        meridian = False
    # end if meridian:

    #real omg12
    if (not meridian and
        sbet1 == 0 and   # and sbet2 == 0
        # Mimic the way Lambda12 works with calp1 = 0
        (self._f <= 0 or lam12 <= math.pi - self._f * math.pi)):

      # Geodesic runs along equator
      calp1 = calp2 = 0; salp1 = salp2 = 1
      s12x = self._a * lam12
      sig12 = omg12 = lam12 / self._f1
      m12x = self._b * math.sin(sig12)
      if outmask & Geodesic.GEODESICSCALE:
        M12 = M21 = math.cos(sig12)
      a12 = lon12 / self._f1

    elif not meridian:

      # Now point1 and point2 belong within a hemisphere bounded by a
      # meridian and geodesic is neither meridional or equatorial.

      # Figure a starting point for Newton's method
      sig12, salp1, calp1, salp2, calp2, dnm = self.InverseStart(
        sbet1, cbet1, dn1, sbet2, cbet2, dn2, lam12, C1a, C2a)

      if sig12 >= 0:
        # Short lines (InverseStart sets salp2, calp2, dnm)
        s12x = sig12 * self._b * dnm
        m12x = (Math.sq(dnm) * self._b * math.sin(sig12 / dnm))
        if outmask & Geodesic.GEODESICSCALE:
          M12 = M21 = math.cos(sig12 / dnm)
        a12 = sig12 / Math.degree
        omg12 = lam12 / (self._f1 * dnm)
      else:

        # Newton's method.  This is a straightforward solution of f(alp1) =
        # lambda12(alp1) - lam12 = 0 with one wrinkle.  f(alp) has exactly one
        # root in the interval (0, pi) and its derivative is positive at the
        # root.  Thus f(alp) is positive for alp > alp1 and negative for alp <
        # alp1.  During the course of the iteration, a range (alp1a, alp1b) is
        # maintained which brackets the root and with each evaluation of f(alp)
        # the range is shrunk if possible.  Newton's method is restarted
        # whenever the derivative of f is negative (because the new value of
        # alp1 is then further from the solution) or if the new estimate of
        # alp1 lies outside (0,pi); in this case, the new starting guess is
        # taken to be (alp1a + alp1b) / 2.
        # real ssig1, csig1, ssig2, csig2, eps
        numit = 0
        tripn = tripb = False
        # Bracketing range
        salp1a = Geodesic.tiny_; calp1a = 1
        salp1b = Geodesic.tiny_; calp1b = -1

        while numit < Geodesic.maxit2_:
          # the WGS84 test set: mean = 1.47, sd = 1.25, max = 16
          # WGS84 and random input: mean = 2.85, sd = 0.60
          (nlam12, salp2, calp2, sig12, ssig1, csig1, ssig2, csig2,
           eps, omg12, dv) = self.Lambda12(
            sbet1, cbet1, dn1, sbet2, cbet2, dn2,
            salp1, calp1, numit < Geodesic.maxit1_, C1a, C2a, C3a)
          v = nlam12 - lam12
          # 2 * tol0 is approximately 1 ulp for a number in [0, pi].
          # Reversed test to allow escape with NaNs
          if tripb or not (abs(v) >= (8 if tripn else 2) * Geodesic.tol0_):
            break
          # Update bracketing values
          if v > 0 and (numit > Geodesic.maxit1_ or
                        calp1/salp1 > calp1b/salp1b):
            salp1b = salp1; calp1b = calp1
          elif v < 0 and (numit > Geodesic.maxit1_ or
                          calp1/salp1 < calp1a/salp1a):
            salp1a = salp1; calp1a = calp1

          numit += 1
          if numit < Geodesic.maxit1_ and dv > 0:
            dalp1 = -v/dv
            sdalp1 = math.sin(dalp1); cdalp1 = math.cos(dalp1)
            nsalp1 = salp1 * cdalp1 + calp1 * sdalp1
            if nsalp1 > 0 and abs(dalp1) < math.pi:
              calp1 = calp1 * cdalp1 - salp1 * sdalp1
              salp1 = nsalp1
              salp1, calp1 = Geodesic.SinCosNorm(salp1, calp1)
              # In some regimes we don't get quadratic convergence because
              # slope -> 0.  So use convergence conditions based on epsilon
              # instead of sqrt(epsilon).
              tripn = abs(v) <= 16 * Geodesic.tol0_
              continue
          # Either dv was not postive or updated value was outside legal range.
          # Use the midpoint of the bracket as the next estimate.  This
          # mechanism is not needed for the WGS84 ellipsoid, but it does catch
          # problems with more eccentric ellipsoids.  Its efficacy is such for
          # the WGS84 test set with the starting guess set to alp1 = 90deg:
          # the WGS84 test set: mean = 5.21, sd = 3.93, max = 24
          # WGS84 and random input: mean = 4.74, sd = 0.99
          salp1 = (salp1a + salp1b)/2
          calp1 = (calp1a + calp1b)/2
          salp1, calp1 = Geodesic.SinCosNorm(salp1, calp1)
          tripn = False
          tripb = (abs(salp1a - salp1) + (calp1a - calp1) < Geodesic.tolb_ or
                   abs(salp1 - salp1b) + (calp1 - calp1b) < Geodesic.tolb_)

        s12x, m12x, dummy, M12, M21 = self.Lengths(
          eps, sig12, ssig1, csig1, dn1, ssig2, csig2, dn2, cbet1, cbet2,
          (outmask & Geodesic.GEODESICSCALE) != 0, C1a, C2a)

        m12x *= self._b
        s12x *= self._b
        a12 = sig12 / Math.degree
        omg12 = lam12 - omg12
    # end elif not meridian

    if outmask & Geodesic.DISTANCE:
      s12 = 0 + s12x           # Convert -0 to 0

    if outmask & Geodesic.REDUCEDLENGTH:
      m12 = 0 + m12x           # Convert -0 to 0

    if outmask & Geodesic.AREA:
      # From Lambda12: sin(alp1) * cos(bet1) = sin(alp0)
      salp0 = salp1 * cbet1
      calp0 = math.hypot(calp1, salp1 * sbet1) # calp0 > 0
      # real alp12
      if calp0 != 0 and salp0 != 0:
        # From Lambda12: tan(bet) = tan(sig) * cos(alp)
        ssig1 = sbet1; csig1 = calp1 * cbet1
        ssig2 = sbet2; csig2 = calp2 * cbet2
        k2 = Math.sq(calp0) * self._ep2
        eps = k2 / (2 * (1 + math.sqrt(1 + k2)) + k2)
        # Multiplier = a^2 * e^2 * cos(alpha0) * sin(alpha0).
        A4 = Math.sq(self._a) * calp0 * salp0 * self._e2
        ssig1, csig1 = Geodesic.SinCosNorm(ssig1, csig1)
        ssig2, csig2 = Geodesic.SinCosNorm(ssig2, csig2)
        C4a = list(range(Geodesic.nC4_))
        self.C4f(eps, C4a)
        B41 = Geodesic.SinCosSeries(False, ssig1, csig1, C4a, Geodesic.nC4_)
        B42 = Geodesic.SinCosSeries(False, ssig2, csig2, C4a, Geodesic.nC4_)
        S12 = A4 * (B42 - B41)
      else:
        # Avoid problems with indeterminate sig1, sig2 on equator
        S12 = 0
      if (not meridian and
          omg12 < 0.75 * math.pi and # Long difference too big
          sbet2 - sbet1 < 1.75):     # Lat difference too big
        # Use tan(Gamma/2) = tan(omg12/2)
        # * (tan(bet1/2)+tan(bet2/2))/(1+tan(bet1/2)*tan(bet2/2))
        # with tan(x/2) = sin(x)/(1+cos(x))
        somg12 = math.sin(omg12); domg12 = 1 + math.cos(omg12)
        dbet1 = 1 + cbet1; dbet2 = 1 + cbet2
        alp12 = 2 * math.atan2( somg12 * ( sbet1 * dbet2 + sbet2 * dbet1 ),
                                domg12 * ( sbet1 * sbet2 + dbet1 * dbet2 ) )
      else:
        # alp12 = alp2 - alp1, used in atan2 so no need to normalize
        salp12 = salp2 * calp1 - calp2 * salp1
        calp12 = calp2 * calp1 + salp2 * salp1
        # The right thing appears to happen if alp1 = +/-180 and alp2 = 0, viz
        # salp12 = -0 and alp12 = -180.  However this depends on the sign
        # being attached to 0 correctly.  The following ensures the correct
        # behavior.
        if salp12 == 0 and calp12 < 0:
          salp12 = Geodesic.tiny_ * calp1
          calp12 = -1
        alp12 = math.atan2(salp12, calp12)
      S12 += self._c2 * alp12
      S12 *= swapp * lonsign * latsign
      # Convert -0 to 0
      S12 += 0

    # Convert calp, salp to azimuth accounting for lonsign, swapp, latsign.
    if swapp < 0:
      salp2, salp1 = salp1, salp2
      calp2, calp1 = calp1, calp2
      if outmask & Geodesic.GEODESICSCALE:
        M21, M12 = M12, M21

    salp1 *= swapp * lonsign; calp1 *= swapp * latsign
    salp2 *= swapp * lonsign; calp2 *= swapp * latsign

    if outmask & Geodesic.AZIMUTH:
      # minus signs give range [-180, 180). 0- converts -0 to +0.
      azi1 = 0 - math.atan2(-salp1, calp1) / Math.degree
      azi2 = 0 - math.atan2(-salp2, calp2) / Math.degree

    # Returned value in [0, 180]
    return a12, s12, azi1, azi2, m12, M12, M21, S12