1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
|
include "base.pxi"
cimport cython
from libc.math cimport ceil, isnan, round
from pyproj._compat cimport cstrencode, empty_array
import math
from collections import namedtuple
from pyproj.enums import GeodIntermediateFlag
from pyproj.exceptions import GeodError
geodesic_version_str = (
f"{GEODESIC_VERSION_MAJOR}.{GEODESIC_VERSION_MINOR}.{GEODESIC_VERSION_PATCH}"
)
GeodIntermediateReturn = namedtuple(
"GeodIntermediateReturn", ["npts", "del_s", "dist", "lons", "lats", "azis"]
)
GeodIntermediateReturn.__doc__ = """
.. versionadded:: 3.1.0
Geod Intermediate Return value (Named Tuple)
Parameters
----------
npts: int
number of points
del_s: float
delimiter distance between two successive points
dist: float
distance between the initial and terminus points
out_lons: Any
array of the output lons
out_lats: Any
array of the output lats
out_azis: Any
array of the output azis
"""
cdef:
int GEOD_INTER_FLAG_DEFAULT = GeodIntermediateFlag.DEFAULT
int GEOD_INTER_FLAG_NPTS_MASK = (
GeodIntermediateFlag.NPTS_ROUND
| GeodIntermediateFlag.NPTS_CEIL
| GeodIntermediateFlag.NPTS_TRUNC
)
int GEOD_INTER_FLAG_NPTS_ROUND = GeodIntermediateFlag.NPTS_ROUND
int GEOD_INTER_FLAG_NPTS_CEIL = GeodIntermediateFlag.NPTS_CEIL
int GEOD_INTER_FLAG_NPTS_TRUNC = GeodIntermediateFlag.NPTS_TRUNC
int GEOD_INTER_FLAG_DEL_S_MASK = (
GeodIntermediateFlag.DEL_S_RECALC | GeodIntermediateFlag.DEL_S_NO_RECALC
)
int GEOD_INTER_FLAG_DEL_S_RECALC = GeodIntermediateFlag.DEL_S_RECALC
int GEOD_INTER_FLAG_DEL_S_NO_RECALC = GeodIntermediateFlag.DEL_S_NO_RECALC
int GEOD_INTER_FLAG_AZIS_MASK = (
GeodIntermediateFlag.AZIS_DISCARD | GeodIntermediateFlag.AZIS_KEEP
)
int GEOD_INTER_FLAG_AZIS_DISCARD = GeodIntermediateFlag.AZIS_DISCARD
int GEOD_INTER_FLAG_AZIS_KEEP = GeodIntermediateFlag.AZIS_KEEP
cdef double _reverse_azimuth(double azi, double factor) nogil:
if azi > 0:
azi = azi - factor
else:
azi = azi + factor
return azi
def reverse_azimuth(object azi, bint radians=False):
cdef PyBuffWriteManager azibuff = PyBuffWriteManager(azi)
cdef Py_ssize_t iii
cdef double factor = 180
if radians:
factor = math.pi
with nogil:
for iii in range(azibuff.len):
azibuff.data[iii] = _reverse_azimuth(azibuff.data[iii], factor=factor)
cdef class Geod:
def __init__(self, double a, double f, bint sphere, double b, double es):
geod_init(&self._geod_geodesic, <double> a, <double> f)
self.a = a
self.f = f
self.initstring = f"+{a=} +{f=}"
self.sphere = sphere
self.b = b
self.es = es
def __reduce__(self):
"""special method that allows pyproj.Geod instance to be pickled"""
return self.__class__, (self.initstring,)
@cython.boundscheck(False)
@cython.wraparound(False)
def _fwd(
self,
object lons,
object lats,
object az,
object dist,
bint radians=False,
bint return_back_azimuth=True,
):
"""
forward transformation - determine longitude, latitude and back azimuth
of a terminus point given an initial point longitude and latitude, plus
forward azimuth and distance.
if radians=True, lons/lats are radians instead of degrees.
if return_back_azimuth=True, the return azimuth will be the forward azimuth instead of the forward azimuth.
"""
cdef:
PyBuffWriteManager lonbuff = PyBuffWriteManager(lons)
PyBuffWriteManager latbuff = PyBuffWriteManager(lats)
PyBuffWriteManager azbuff = PyBuffWriteManager(az)
PyBuffWriteManager distbuff = PyBuffWriteManager(dist)
# process data in buffer
if not lonbuff.len == latbuff.len == azbuff.len == distbuff.len:
raise GeodError("Array lengths are not the same.")
cdef:
double lat1
double lon1
double az1
double s12
double plon2
double plat2
double pazi2
Py_ssize_t iii
with nogil:
for iii in range(lonbuff.len):
if not radians:
lon1 = lonbuff.data[iii]
lat1 = latbuff.data[iii]
az1 = azbuff.data[iii]
s12 = distbuff.data[iii]
else:
lon1 = _RAD2DG * lonbuff.data[iii]
lat1 = _RAD2DG * latbuff.data[iii]
az1 = _RAD2DG * azbuff.data[iii]
s12 = distbuff.data[iii]
geod_direct(
&self._geod_geodesic,
lat1,
lon1,
az1,
s12,
&plat2,
&plon2,
&pazi2,
)
# by default (return_back_azimuth=True),
# forward azimuth needs to be flipped 180 degrees
# to match the (back azimuth) output of PROJ geod utilities.
if return_back_azimuth:
pazi2 = _reverse_azimuth(pazi2, factor=180)
if not radians:
lonbuff.data[iii] = plon2
latbuff.data[iii] = plat2
azbuff.data[iii] = pazi2
else:
lonbuff.data[iii] = _DG2RAD * plon2
latbuff.data[iii] = _DG2RAD * plat2
azbuff.data[iii] = _DG2RAD * pazi2
@cython.boundscheck(False)
@cython.wraparound(False)
def _fwd_point(
self,
object lon1in,
object lat1in,
object az1in,
object s12in,
bint radians=False,
bint return_back_azimuth=True,
):
"""
Scalar optimized function
forward transformation - determine longitude, latitude and back azimuth
of a terminus point given an initial point longitude and latitude, plus
forward azimuth and distance.
if radians=True, lons/lats are radians instead of degrees.
"""
cdef:
double plon2
double plat2
double pazi2
double lon1 = lon1in
double lat1 = lat1in
double az1 = az1in
double s12 = s12in
# We do the type-checking internally here due to automatically
# casting length-1 arrays to float that we don't want to return scalar for.
# Ex: float(np.array([0])) works and we don't want to accept numpy arrays
for x_in in (lon1in, lat1in, az1in, s12in):
if not isinstance(x_in, (float, int)):
raise TypeError("Scalar input is required for point based functions")
with nogil:
if radians:
lon1 = _RAD2DG * lon1
lat1 = _RAD2DG * lat1
az1 = _RAD2DG * az1
geod_direct(
&self._geod_geodesic,
lat1,
lon1,
az1,
s12,
&plat2,
&plon2,
&pazi2,
)
# back azimuth needs to be flipped 180 degrees
# to match what PROJ geod utility produces.
if return_back_azimuth:
pazi2 =_reverse_azimuth(pazi2, factor=180)
if radians:
plon2 = _DG2RAD * plon2
plat2 = _DG2RAD * plat2
pazi2 = _DG2RAD * pazi2
return plon2, plat2, pazi2
@cython.boundscheck(False)
@cython.wraparound(False)
def _inv(
self,
object lons1,
object lats1,
object lons2,
object lats2,
bint radians=False,
bint return_back_azimuth=True,
):
"""
inverse transformation - return forward azimuth (azi12) and back azimuths (azi21), plus distance
between an initial and terminus lat/lon pair.
if radians=True, lons/lats are radians instead of degree
if return_back_azimuth=True, azi21 is a back azimuth (180 degrees flipped),
otherwise azi21 is also a forward azimuth.
"""
cdef:
PyBuffWriteManager lon1buff = PyBuffWriteManager(lons1)
PyBuffWriteManager lat1buff = PyBuffWriteManager(lats1)
PyBuffWriteManager lon2buff = PyBuffWriteManager(lons2)
PyBuffWriteManager lat2buff = PyBuffWriteManager(lats2)
# process data in buffer
if not lon1buff.len == lat1buff.len == lon2buff.len == lat2buff.len:
raise GeodError("Array lengths are not the same.")
cdef:
double lat1
double lon1
double lat2
double lon2
double pazi1
double pazi2
double ps12
Py_ssize_t iii
with nogil:
for iii in range(lon1buff.len):
if radians:
lon1 = _RAD2DG * lon1buff.data[iii]
lat1 = _RAD2DG * lat1buff.data[iii]
lon2 = _RAD2DG * lon2buff.data[iii]
lat2 = _RAD2DG * lat2buff.data[iii]
else:
lon1 = lon1buff.data[iii]
lat1 = lat1buff.data[iii]
lon2 = lon2buff.data[iii]
lat2 = lat2buff.data[iii]
geod_inverse(
&self._geod_geodesic,
lat1, lon1, lat2, lon2,
&ps12, &pazi1, &pazi2,
)
# by default (return_back_azimuth=True),
# forward azimuth needs to be flipped 180 degrees
# to match the (back azimuth) output of PROJ geod utilities.
if return_back_azimuth:
pazi2 = _reverse_azimuth(pazi2, factor=180)
if radians:
lon1buff.data[iii] = _DG2RAD * pazi1
lat1buff.data[iii] = _DG2RAD * pazi2
else:
lon1buff.data[iii] = pazi1
lat1buff.data[iii] = pazi2
# write azimuth data into lon2 buffer
lon2buff.data[iii] = ps12
@cython.boundscheck(False)
@cython.wraparound(False)
def _inv_point(
self,
object lon1in,
object lat1in,
object lon2in,
object lat2in,
bint radians=False,
bint return_back_azimuth=True,
):
"""
Scalar optimized function
inverse transformation - return forward and back azimuth, plus distance
between an initial and terminus lat/lon pair.
if radians=True, lons/lats are radians instead of degree
"""
cdef:
double pazi1
double pazi2
double ps12
double lon1 = lon1in
double lat1 = lat1in
double lon2 = lon2in
double lat2 = lat2in
# We do the type-checking internally here due to automatically
# casting length-1 arrays to float that we don't want to return scalar for.
# Ex: float(np.array([0])) works and we don't want to accept numpy arrays
for x_in in (lon1in, lat1in, lon2in, lat2in):
if not isinstance(x_in, (float, int)):
raise TypeError("Scalar input is required for point based functions")
with nogil:
if radians:
lon1 = _RAD2DG * lon1
lat1 = _RAD2DG * lat1
lon2 = _RAD2DG * lon2
lat2 = _RAD2DG * lat2
geod_inverse(
&self._geod_geodesic,
lat1, lon1, lat2, lon2,
&ps12, &pazi1, &pazi2,
)
# back azimuth needs to be flipped 180 degrees
# to match what proj4 geod utility produces.
if return_back_azimuth:
pazi2 =_reverse_azimuth(pazi2, factor=180)
if radians:
pazi1 = _DG2RAD * pazi1
pazi2 = _DG2RAD * pazi2
return pazi1, pazi2, ps12
@cython.boundscheck(False)
@cython.wraparound(False)
def _inv_or_fwd_intermediate(
self,
double lon1,
double lat1,
double lon2_or_azi1,
double lat2,
int npts,
double del_s,
bint radians,
int initial_idx,
int terminus_idx,
int flags,
object out_lons,
object out_lats,
object out_azis,
bint return_back_azimuth,
bint is_fwd,
) -> GeodIntermediateReturn:
"""
.. versionadded:: 3.1.0
given initial and terminus lat/lon, find npts intermediate points.
using given lons, lats buffers
"""
cdef:
Py_ssize_t iii
double pazi2
double s12
double plon2
double plat2
geod_geodesicline line
bint store_az = (
out_azis is not None or
(flags & GEOD_INTER_FLAG_AZIS_MASK) == GEOD_INTER_FLAG_AZIS_KEEP
)
PyBuffWriteManager lons_buff
PyBuffWriteManager lats_buff
PyBuffWriteManager azis_buff
if not is_fwd and (del_s == 0) == (npts == 0):
raise GeodError("inv_intermediate: "
"npts and del_s are mutually exclusive, "
"only one of them must be != 0.")
with nogil:
if radians:
lon1 *= _RAD2DG
lat1 *= _RAD2DG
lon2_or_azi1 *= _RAD2DG
if not is_fwd:
lat2 *= _RAD2DG
if is_fwd:
# do fwd computation to set azimuths, distance.
geod_lineinit(&line, &self._geod_geodesic, lat1, lon1, lon2_or_azi1, 0u)
line.s13 = del_s * (npts + initial_idx + terminus_idx - 1)
else:
# do inverse computation to set azimuths, distance.
geod_inverseline(&line, &self._geod_geodesic, lat1, lon1,
lat2, lon2_or_azi1, 0u)
if npts == 0:
# calc the number of required points by the distance increment
# s12 holds a temporary float value of npts (just reusing this var)
s12 = line.s13 / del_s - initial_idx - terminus_idx + 1
if (flags & GEOD_INTER_FLAG_NPTS_MASK) == \
GEOD_INTER_FLAG_NPTS_ROUND:
s12 = round(s12)
elif (flags & GEOD_INTER_FLAG_NPTS_MASK) == \
GEOD_INTER_FLAG_NPTS_CEIL:
s12 = ceil(s12)
npts = int(s12)
if (flags & GEOD_INTER_FLAG_DEL_S_MASK) == GEOD_INTER_FLAG_DEL_S_RECALC:
# calc the distance increment by the number of required points
del_s = line.s13 / (npts + initial_idx + terminus_idx - 1)
with gil:
if out_lons is None:
out_lons = empty_array(npts)
if out_lats is None:
out_lats = empty_array(npts)
if out_azis is None and store_az:
out_azis = empty_array(npts)
lons_buff = PyBuffWriteManager(out_lons)
lats_buff = PyBuffWriteManager(out_lats)
if store_az:
azis_buff = PyBuffWriteManager(out_azis)
if lons_buff.len < npts \
or lats_buff.len < npts \
or (store_az and azis_buff.len < npts):
raise GeodError(
"Arrays are not long enough ("
f"{lons_buff.len}, {lats_buff.len}, "
f"{azis_buff.len if store_az else -1}) < {npts}.")
# loop over intermediate points, compute lat/lons.
for iii in range(0, npts):
s12 = (iii + initial_idx) * del_s
geod_position(&line, s12, &plat2, &plon2, &pazi2)
if radians:
plat2 *= _DG2RAD
plon2 *= _DG2RAD
lats_buff.data[iii] = plat2
lons_buff.data[iii] = plon2
if store_az:
# by default (return_back_azimuth=True),
# forward azimuth needs to be flipped 180 degrees
# to match the (back azimuth) output of PROJ geod utilities.
if return_back_azimuth:
pazi2 =_reverse_azimuth(pazi2, factor=180)
azis_buff.data[iii] = pazi2
return GeodIntermediateReturn(
npts, del_s, line.s13, out_lons, out_lats, out_azis)
@cython.boundscheck(False)
@cython.wraparound(False)
def _line_length(self, object lons, object lats, bint radians=False):
"""
Calculate the distance between points along a line.
Parameters
----------
lons: array
The longitude points along a line.
lats: array
The latitude points along a line.
radians: bool, default=False
If True, the input data is assumed to be in radians.
Returns
-------
float:
The total distance.
"""
cdef PyBuffWriteManager lonbuff = PyBuffWriteManager(lons)
cdef PyBuffWriteManager latbuff = PyBuffWriteManager(lats)
# process data in buffer
if lonbuff.len != latbuff.len:
raise GeodError("Array lengths are not the same.")
if lonbuff.len == 1:
lonbuff.data[0] = 0
return 0.0
cdef:
double lat1
double lon1
double lat2
double lon2
double pazi1
double pazi2
double ps12
double total_distance = 0.0
Py_ssize_t iii
with nogil:
for iii in range(lonbuff.len - 1):
if radians:
lon1 = _RAD2DG * lonbuff.data[iii]
lat1 = _RAD2DG * latbuff.data[iii]
lon2 = _RAD2DG * lonbuff.data[iii + 1]
lat2 = _RAD2DG * latbuff.data[iii + 1]
else:
lon1 = lonbuff.data[iii]
lat1 = latbuff.data[iii]
lon2 = lonbuff.data[iii + 1]
lat2 = latbuff.data[iii + 1]
geod_inverse(
&self._geod_geodesic,
lat1, lon1, lat2, lon2,
&ps12, &pazi1, &pazi2,
)
lonbuff.data[iii] = ps12
total_distance += ps12
return total_distance
@cython.boundscheck(False)
@cython.wraparound(False)
def _polygon_area_perimeter(self, object lons, object lats, bint radians=False):
"""
A simple interface for computing the area of a geodesic polygon.
lats should be in the range [-90 deg, 90 deg].
Only simple polygons (which are not self-intersecting) are allowed.
There's no need to "close" the polygon by repeating the first vertex.
The area returned is signed with counter-clockwise traversal being treated as
positive.
Parameters
----------
lons: array
An array of longitude values.
lats: array
An array of latitude values.
radians: bool, default=False
If True, the input data is assumed to be in radians.
Returns
-------
(float, float):
The area (meter^2) and perimeter (meters) of the polygon.
"""
cdef PyBuffWriteManager lonbuff = PyBuffWriteManager(lons)
cdef PyBuffWriteManager latbuff = PyBuffWriteManager(lats)
# process data in buffer
if not lonbuff.len == latbuff.len:
raise GeodError("Array lengths are not the same.")
cdef double polygon_area
cdef double polygon_perimeter
cdef Py_ssize_t iii
with nogil:
if radians:
for iii in range(lonbuff.len):
lonbuff.data[iii] *= _RAD2DG
latbuff.data[iii] *= _RAD2DG
geod_polygonarea(
&self._geod_geodesic,
latbuff.data, lonbuff.data, lonbuff.len,
&polygon_area, &polygon_perimeter
)
return (polygon_area, polygon_perimeter)
def __repr__(self):
return f"{self.__class__.__name__}({self.initstring!r})"
|