Coverage for pygeodesy/utily.py: 90%

323 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-09-15 09:43 -0400

1 

2# -*- coding: utf-8 -*- 

3 

4u'''Various utility functions. 

5 

6After I{(C) Chris Veness 2011-2015} published under the same MIT Licence**, see 

7U{Latitude/Longitude<https://www.Movable-Type.co.UK/scripts/latlong.html>} and 

8U{Vector-based geodesy<https://www.Movable-Type.co.UK/scripts/latlong-vectors.html>}. 

9''' 

10# make sure int/int division yields float quotient, see .basics 

11from __future__ import division as _; del _ # PYCHOK semicolon 

12 

13from pygeodesy.basics import copysign0, isint, isstr 

14from pygeodesy.constants import EPS, EPS0, INF, NAN, NEG0, NINF, PI, PI2, PI_2, R_M, \ 

15 _float as _F, _isfinite, isnan, isnear0, isneg0, _M_KM, \ 

16 _M_NM, _M_SM, _0_0, _1__90, _0_5, _1_0, _N_1_0, _2__PI, \ 

17 _10_0, _90_0, _N_90_0, _180_0, _N_180_0, _360_0, _400_0 

18from pygeodesy.errors import _ValueError, _xkwds, _xkwds_get 

19from pygeodesy.interns import _edge_, _radians_, _semi_circular_, _SPACE_ 

20from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS 

21from pygeodesy.units import Degrees, Feet, Float, Lam, Lam_, Meter, Meter2, Radians 

22 

23from math import acos, asin, atan2, cos, degrees, fabs, radians, sin, tan # pow 

24 

25__all__ = _ALL_LAZY.utily 

26__version__ = '23.08.15' 

27 

28# read constant name "_M_Unit" as "meter per Unit" 

29_M_CHAIN = _F( 20.1168) # yard2m(1) * 22 

30_M_FATHOM = _F( 1.8288) # yard2m(1) * 2 or _M_NM * 1e-3 

31_M_FOOT = _F( 0.3048) # Int'l (1 / 3.2808398950131 = 10_000 / (254 * 12)) 

32_M_FOOT_GE = _F( 0.31608) # German Fuss (1 / 3.1637560111364) 

33_M_FOOT_FR = _F( 0.3248406) # French Pied-du-Roi or pied (1 / 3.0784329298739) 

34_M_FOOT_USVY = _F( 0.3048006096012192) # US Survey (1200 / 3937) 

35_M_FURLONG = _F( 201.168) # 220 * yard2m(1) == 10 * m2chain(1) 

36# _M_KM = _F(1000.0) # kilo meter 

37# _M_NM = _F(1852.0) # nautical mile 

38# _M_SM = _F(1609.344) # statute mile 

39_M_TOISE = _F( 1.9490436) # French toise, 6 pieds (6 / 3.0784329298739) 

40_M_YARD_UK = _F( 0.9144) # 254 * 12 * 3 / 10_000 == 3 * ft2m(1) Int'l 

41 

42 

43def acos1(x): 

44 '''Return C{math.acos(max(-1, min(1, B{x})))}. 

45 ''' 

46 return acos(x) if fabs(x) < _1_0 else (PI if x < 0 else _0_0) 

47 

48 

49def acre2ha(acres): 

50 '''Convert acres to hectare. 

51 

52 @arg acres: Value in acres (C{scalar}). 

53 

54 @return: Value in C{hectare} (C{float}). 

55 

56 @raise ValueError: Invalid B{C{acres}}. 

57 ''' 

58 # 0.40468564224 == acre2m2(1) / 10_000 

59 return Float(ha=Float(acres) * 0.40468564224) 

60 

61 

62def acre2m2(acres): 

63 '''Convert acres to I{square} meter. 

64 

65 @arg acres: Value in acres (C{scalar}). 

66 

67 @return: Value in C{meter^2} (C{float}). 

68 

69 @raise ValueError: Invalid B{C{acres}}. 

70 ''' 

71 # 4046.8564224 == chain2m(1) * furlong2m(1) 

72 return Meter2(Float(acres) * 4046.8564224) 

73 

74 

75def asin1(x): 

76 '''Return C{math.asin(max(-1, min(1, B{x})))}. 

77 ''' 

78 return asin(x) if fabs(x) < _1_0 else (PI_2 if x > 0 else -PI_2) # not PI3_2! 

79 

80 

81def atand(y_x): 

82 '''Return C{atan(B{y_x})} angle in C{degrees}. 

83 

84 @see: Function L{pygeodesy.atan2d}. 

85 ''' 

86 return atan2d(y_x, _1_0) 

87 

88 

89def atan2b(y, x): 

90 '''Return C{atan2(B{y}, B{x})} in degrees M{[0..+360]}. 

91 

92 @see: Function L{pygeodesy.atan2d}. 

93 ''' 

94 d = atan2d(y, x) 

95 if d < 0: 

96 d += _360_0 

97 return d 

98 

99 

100def atan2d(y, x, reverse=False): 

101 '''Return C{atan2(B{y}, B{x})} in degrees M{[-180..+180]}, 

102 optionally I{reversed} (by 180 degrees for C{azi2}). 

103 

104 @see: I{Karney}'s C++ function U{Math.atan2d 

105 <https://GeographicLib.SourceForge.io/C++/doc/classGeographicLib_1_1Math.html>}. 

106 ''' 

107 if fabs(y) > fabs(x) > 0: 

108 if y < 0: # q = 3 

109 d = degrees(atan2(x, -y)) - _90_0 

110 else: # q = 2 

111 d = _90_0 - degrees(atan2(x, y)) 

112 elif x < 0: # q = 1 

113 d = copysign0(_180_0, y) - degrees(atan2(y, -x)) 

114 elif x > 0: # q = 0 

115 d = degrees(atan2(y, x)) if y else _0_0 

116 elif isnan(x) or isnan(y): 

117 return NAN 

118 else: # x == 0 

119 d = _N_90_0 if y < 0 else (_90_0 if y > 0 else _0_0) 

120 if reverse: 

121 d += _180_0 if d < 0 else _N_180_0 

122 return d 

123 

124 

125def chain2m(chains): 

126 '''Convert I{UK} chains to meter. 

127 

128 @arg chains: Value in chains (C{scalar}). 

129 

130 @return: Value in C{meter} (C{float}). 

131 

132 @raise ValueError: Invalid B{C{chains}}. 

133 ''' 

134 return Meter(Float(chains=chains) * _M_CHAIN) 

135 

136 

137def circle4(earth, lat): 

138 '''Get the equatorial or a parallel I{circle of latitude}. 

139 

140 @arg earth: The earth radius, ellipsoid or datum 

141 (C{meter}, L{Ellipsoid}, L{Ellipsoid2}, 

142 L{Datum} or L{a_f2Tuple}). 

143 @arg lat: Geodetic latitude (C{degrees90}, C{str}). 

144 

145 @return: A L{Circle4Tuple}C{(radius, height, lat, beta)} 

146 instance. 

147 

148 @raise RangeError: Latitude B{C{lat}} outside valid range and 

149 L{pygeodesy.rangerrors} set to C{True}. 

150 

151 @raise TypeError: Invalid B{C{earth}}. 

152 

153 @raise ValueError: B{C{earth}} or B{C{lat}}. 

154 ''' 

155 E = _MODS.datums._spherical_datum(earth).ellipsoid 

156 return E.circle4(lat) 

157 

158 

159def cot(rad, **error_kwds): 

160 '''Return the C{cotangent} of an angle in C{radians}. 

161 

162 @arg rad: Angle (C{radians}). 

163 @kwarg error_kwds: Error to raise (C{ValueError}). 

164 

165 @return: C{cot(B{rad})}. 

166 

167 @raise ValueError: L{pygeodesy.isnear0}C{(sin(B{rad})}. 

168 ''' 

169 s, c = sincos2(rad) 

170 if isnear0(s): 

171 raise _valueError(cot, rad, **error_kwds) 

172 return c / s 

173 

174 

175def cot_(*rads, **error_kwds): 

176 '''Return the C{cotangent} of angle(s) in C{radiansresection}. 

177 

178 @arg rads: One or more angles (C{radians}). 

179 @kwarg error_kwds: Error to raise (C{ValueError}). 

180 

181 @return: Yield the C{cot(B{rad})} for each angle. 

182 

183 @raise ValueError: See L{pygeodesy.cot}. 

184 ''' 

185 try: 

186 for r in rads: 

187 yield cot(r) 

188 except ValueError: 

189 raise _valueError(cot_, r, **error_kwds) 

190 

191 

192def cotd(deg, **error_kwds): 

193 '''Return the C{cotangent} of an angle in C{degrees}. 

194 

195 @arg deg: Angle (C{degrees}). 

196 @kwarg error_kwds: Error to raise (C{ValueError}). 

197 

198 @return: C{cot(B{deg})}. 

199 

200 @raise ValueError: L{pygeodesy.isnear0}C{(sin(B{deg})}. 

201 ''' 

202 s, c = sincos2d(deg) 

203 if isnear0(s): 

204 raise _valueError(cotd, deg, **error_kwds) 

205 return c / s 

206 

207 

208def cotd_(*degs, **error_kwds): 

209 '''Return the C{cotangent} of angle(s) in C{degrees}. 

210 

211 @arg degs: One or more angles (C{degrees}). 

212 @kwarg error_kwds: Error to raise (C{ValueError}). 

213 

214 @return: Yield the C{cot(B{deg})} for each angle. 

215 

216 @raise ValueError: See L{pygeodesy.cotd}. 

217 ''' 

218 try: 

219 for d in degs: 

220 yield cotd(d) 

221 except ValueError: 

222 raise _valueError(cotd_, d, **error_kwds) 

223 

224 

225def degrees90(rad): 

226 '''Convert radians to degrees and wrap M{[-270..+90]}. 

227 

228 @arg rad: Angle (C{radians}). 

229 

230 @return: Angle, wrapped (C{degrees90}). 

231 ''' 

232 return _wrap(degrees(rad), _90_0, _360_0) 

233 

234 

235def degrees180(rad): 

236 '''Convert radians to degrees and wrap M{[-180..+180]}. 

237 

238 @arg rad: Angle (C{radians}). 

239 

240 @return: Angle, wrapped (C{degrees180}). 

241 ''' 

242 return _wrap(degrees(rad), _180_0, _360_0) 

243 

244 

245def degrees360(rad): 

246 '''Convert radians to degrees and wrap M{[0..+360)}. 

247 

248 @arg rad: Angle (C{radians}). 

249 

250 @return: Angle, wrapped (C{degrees360}). 

251 ''' 

252 return _wrap(degrees(rad), _360_0, _360_0) 

253 

254 

255def degrees2grades(deg): 

256 '''Convert degrees to I{grades} (aka I{gons} or I{gradians}). 

257 

258 @arg deg: Angle (C{degrees}). 

259 

260 @return: Angle (C{grades}). 

261 ''' 

262 return Degrees(deg) * _400_0 / _360_0 

263 

264 

265def degrees2m(deg, radius=R_M, lat=0): 

266 '''Convert an angle to a distance along the equator or 

267 along the parallel at an other (geodetic) latitude. 

268 

269 @arg deg: The angle (C{degrees}). 

270 @kwarg radius: Mean earth radius, ellipsoid or datum 

271 (C{meter}, L{Ellipsoid}, L{Ellipsoid2}, 

272 L{Datum} or L{a_f2Tuple}). 

273 @kwarg lat: Parallel latitude (C{degrees90}, C{str}). 

274 

275 @return: Distance (C{meter}, same units as B{C{radius}} 

276 or equatorial and polar radii) or C{0.0} for 

277 near-polar B{C{lat}}. 

278 

279 @raise RangeError: Latitude B{C{lat}} outside valid range and 

280 L{pygeodesy.rangerrors} set to C{True}. 

281 

282 @raise TypeError: Invalid B{C{radius}}. 

283 

284 @raise ValueError: Invalid B{C{deg}}, B{C{radius}} or 

285 B{C{lat}}. 

286 

287 @see: Function L{radians2m} and L{m2degrees}. 

288 ''' 

289 return _radians2m(Lam_(deg=deg, clip=0), radius, lat) 

290 

291 

292def fathom2m(fathoms): 

293 '''Convert I{Imperial} fathom to meter. 

294 

295 @arg fathoms: Value in fathoms (C{scalar}). 

296 

297 @return: Value in C{meter} (C{float}). 

298 

299 @raise ValueError: Invalid B{C{fathoms}}. 

300 

301 @see: Function L{toise2m}, U{Fathom<https://WikiPedia.org/wiki/Fathom>} 

302 and U{Klafter<https://WikiPedia.org/wiki/Klafter>}. 

303 ''' 

304 return Meter(Float(fathoms=fathoms) * _M_FATHOM) 

305 

306 

307def ft2m(feet, usurvey=False, pied=False, fuss=False): 

308 '''Convert I{International}, I{US Survey}, I{French} or I{German} 

309 B{C{feet}} to C{meter}. 

310 

311 @arg feet: Value in feet (C{scalar}). 

312 @kwarg usurvey: If C{True}, convert I{US Survey} foot else ... 

313 @kwarg pied: If C{True}, convert French I{pied-du-Roi} else ... 

314 @kwarg fuss: If C{True}, convert German I{Fuss}, otherwise 

315 I{International} foot to C{meter}. 

316 

317 @return: Value in C{meter} (C{float}). 

318 

319 @raise ValueError: Invalid B{C{feet}}. 

320 ''' 

321 return Meter(Feet(feet) * (_M_FOOT_USVY if usurvey else 

322 (_M_FOOT_FR if pied else 

323 (_M_FOOT_GE if fuss else _M_FOOT)))) 

324 

325 

326def furlong2m(furlongs): 

327 '''Convert a furlong to meter. 

328 

329 @arg furlongs: Value in furlongs (C{scalar}). 

330 

331 @return: Value in C{meter} (C{float}). 

332 

333 @raise ValueError: Invalid B{C{furlongs}}. 

334 ''' 

335 return Meter(Float(furlongs=furlongs) * _M_FURLONG) 

336 

337 

338def grades(rad): 

339 '''Convert radians to I{grades} (aka I{gons} or I{gradians}). 

340 

341 @arg rad: Angle (C{radians}). 

342 

343 @return: Angle (C{grades}). 

344 ''' 

345 return Float(grades=Float(rad=rad) * _400_0 / PI2) 

346 

347 

348def grades400(rad): 

349 '''Convert radians to I{grades} (aka I{gons} or I{gradians}) and wrap M{[0..+400)}. 

350 

351 @arg rad: Angle (C{radians}). 

352 

353 @return: Angle, wrapped (C{grades}). 

354 ''' 

355 return Float(grades400=_wrap(grades(rad), _400_0, _400_0)) 

356 

357 

358def grades2degrees(gon): 

359 '''Convert I{grades} (aka I{gons} or I{gradians}) to C{degrees}. 

360 

361 @arg gon: Angle (C{grades}). 

362 

363 @return: Angle (C{degrees}). 

364 ''' 

365 return Degrees(Float(gon=gon) * _360_0 / _400_0) 

366 

367 

368def grades2radians(gon): 

369 '''Convert I{grades} (aka I{gons} or I{gradians}) to C{radians}. 

370 

371 @arg gon: Angle (C{grades}). 

372 

373 @return: Angle (C{radians}). 

374 ''' 

375 return Radians(Float(gon=gon) * PI2 / _400_0) 

376 

377 

378def km2m(km): 

379 '''Convert kilo meter to meter (m). 

380 

381 @arg km: Value in kilo meter (C{scalar}). 

382 

383 @return: Value in meter (C{float}). 

384 

385 @raise ValueError: Invalid B{C{km}}. 

386 ''' 

387 return Meter(Float(km=km) * _M_KM) 

388 

389 

390def _loneg(lon): 

391 '''(INTERNAL) "Complement" of C{lon}. 

392 ''' 

393 return _180_0 - lon 

394 

395 

396def m2chain(meter): 

397 '''Convert meter to I{UK} chains. 

398 

399 @arg meter: Value in meter (C{scalar}). 

400 

401 @return: Value in C{chains} (C{float}). 

402 

403 @raise ValueError: Invalid B{C{meter}}. 

404 ''' 

405 return Float(chain=Meter(meter) / _M_CHAIN) # * 0.049709695378986715 

406 

407 

408def m2degrees(distance, radius=R_M, lat=0): 

409 '''Convert a distance to an angle along the equator or 

410 along the parallel at an other (geodetic) latitude. 

411 

412 @arg distance: Distance (C{meter}, same units as B{C{radius}}). 

413 @kwarg radius: Mean earth radius, ellipsoid or datum (C{meter}, 

414 an L{Ellipsoid}, L{Ellipsoid2}, L{Datum} or 

415 L{a_f2Tuple}). 

416 @kwarg lat: Parallel latitude (C{degrees90}, C{str}). 

417 

418 @return: Angle (C{degrees}) or C{INF} for near-polar B{C{lat}}. 

419 

420 @raise RangeError: Latitude B{C{lat}} outside valid range and 

421 L{pygeodesy.rangerrors} set to C{True}. 

422 

423 @raise TypeError: Invalid B{C{radius}}. 

424 

425 @raise ValueError: Invalid B{C{distance}}, B{C{radius}} 

426 or B{C{lat}}. 

427 

428 @see: Function L{m2radians} and L{degrees2m}. 

429 ''' 

430 return degrees(m2radians(distance, radius=radius, lat=lat)) 

431 

432 

433def m2fathom(meter): 

434 '''Convert meter to I{Imperial} fathoms. 

435 

436 @arg meter: Value in meter (C{scalar}). 

437 

438 @return: Value in C{fathoms} (C{float}). 

439 

440 @raise ValueError: Invalid B{C{meter}}. 

441 

442 @see: Function L{m2toise}, U{Fathom<https://WikiPedia.org/wiki/Fathom>} 

443 and U{Klafter<https://WikiPedia.org/wiki/Klafter>}. 

444 ''' 

445 return Float(fathom=Meter(meter) / _M_FATHOM) # * 0.546806649 

446 

447 

448def m2ft(meter, usurvey=False, pied=False, fuss=False): 

449 '''Convert meter to I{International}, I{US Survey}, I{French} or 

450 or I{German} feet (C{ft}). 

451 

452 @arg meter: Value in meter (C{scalar}). 

453 @kwarg usurvey: If C{True}, convert to I{US Survey} foot else ... 

454 @kwarg pied: If C{True}, convert to French I{pied-du-Roi} else ... 

455 @kwarg fuss: If C{True}, convert to German I{Fuss}, otherwise to 

456 I{International} foot. 

457 

458 @return: Value in C{feet} (C{float}). 

459 

460 @raise ValueError: Invalid B{C{meter}}. 

461 ''' 

462 # * 3.2808333333333333, US Survey 3937 / 1200 

463 # * 3.2808398950131235, Int'l 10_000 / (254 * 12) 

464 return Float(feet=Meter(meter) / (_M_FOOT_USVY if usurvey else 

465 (_M_FOOT_FR if pied else 

466 (_M_FOOT_GE if fuss else _M_FOOT)))) 

467 

468 

469def m2furlong(meter): 

470 '''Convert meter to furlongs. 

471 

472 @arg meter: Value in meter (C{scalar}). 

473 

474 @return: Value in C{furlongs} (C{float}). 

475 

476 @raise ValueError: Invalid B{C{meter}}. 

477 ''' 

478 return Float(furlong=Meter(meter) / _M_FURLONG) # * 0.00497096954 

479 

480 

481def m2km(meter): 

482 '''Convert meter to kilo meter (Km). 

483 

484 @arg meter: Value in meter (C{scalar}). 

485 

486 @return: Value in Km (C{float}). 

487 

488 @raise ValueError: Invalid B{C{meter}}. 

489 ''' 

490 return Float(km=Meter(meter) / _M_KM) 

491 

492 

493def m2NM(meter): 

494 '''Convert meter to nautical miles (NM). 

495 

496 @arg meter: Value in meter (C{scalar}). 

497 

498 @return: Value in C{NM} (C{float}). 

499 

500 @raise ValueError: Invalid B{C{meter}}. 

501 ''' 

502 return Float(NM=Meter(meter) / _M_NM) # * 5.39956804e-4 

503 

504 

505def m2radians(distance, radius=R_M, lat=0): 

506 '''Convert a distance to an angle along the equator or 

507 along the parallel at an other (geodetic) latitude. 

508 

509 @arg distance: Distance (C{meter}, same units as B{C{radius}}). 

510 @kwarg radius: Mean earth radius, ellipsoid or datum (C{meter}, 

511 an L{Ellipsoid}, L{Ellipsoid2}, L{Datum} or 

512 L{a_f2Tuple}). 

513 @kwarg lat: Parallel latitude (C{degrees90}, C{str}). 

514 

515 @return: Angle (C{radians}) or C{INF} for near-polar B{C{lat}}. 

516 

517 @raise RangeError: Latitude B{C{lat}} outside valid range and 

518 L{pygeodesy.rangerrors} set to C{True}. 

519 

520 @raise TypeError: Invalid B{C{radius}}. 

521 

522 @raise ValueError: Invalid B{C{distance}}, B{C{radius}} 

523 or B{C{lat}}. 

524 

525 @see: Function L{m2degrees} and L{radians2m}. 

526 ''' 

527 m = circle4(radius, lat).radius 

528 return INF if m < EPS0 else Radians(Float(distance=distance) / m) 

529 

530 

531def m2SM(meter): 

532 '''Convert meter to statute miles (SM). 

533 

534 @arg meter: Value in meter (C{scalar}). 

535 

536 @return: Value in C{SM} (C{float}). 

537 

538 @raise ValueError: Invalid B{C{meter}}. 

539 ''' 

540 return Float(SM=Meter(meter) / _M_SM) # * 6.21369949e-4 == 1 / 1609.344 

541 

542 

543def m2toise(meter): 

544 '''Convert meter to French U{toises<https://WikiPedia.org/wiki/Toise>}. 

545 

546 @arg meter: Value in meter (C{scalar}). 

547 

548 @return: Value in C{toises} (C{float}). 

549 

550 @raise ValueError: Invalid B{C{meter}}. 

551 

552 @see: Function L{m2fathom}. 

553 ''' 

554 return Float(toise=Meter(meter) / _M_TOISE) # * 0.513083632632119 

555 

556 

557def m2yard(meter): 

558 '''Convert meter to I{UK} yards. 

559 

560 @arg meter: Value in meter (C{scalar}). 

561 

562 @return: Value in C{yards} (C{float}). 

563 

564 @raise ValueError: Invalid B{C{meter}}. 

565 ''' 

566 return Float(yard=Meter(meter) / _M_YARD_UK) # * 1.0936132983377078 

567 

568 

569def NM2m(nm): 

570 '''Convert nautical miles to meter (m). 

571 

572 @arg nm: Value in nautical miles (C{scalar}). 

573 

574 @return: Value in meter (C{float}). 

575 

576 @raise ValueError: Invalid B{C{nm}}. 

577 ''' 

578 return Meter(Float(nm=nm) * _M_NM) 

579 

580 

581def _passarg(arg): # in .auxilats.auxLat, .formy 

582 '''(INTERNAL) Helper, no-op. 

583 ''' 

584 return arg 

585 

586 

587def _passargs(*args): # in .formy 

588 '''(INTERNAL) Helper, no-op. 

589 ''' 

590 return args 

591 

592 

593def radians2m(rad, radius=R_M, lat=0): 

594 '''Convert an angle to a distance along the equator or 

595 along the parallel at an other (geodetic) latitude. 

596 

597 @arg rad: The angle (C{radians}). 

598 @kwarg radius: Mean earth radius, ellipsoid or datum 

599 (C{meter}, L{Ellipsoid}, L{Ellipsoid2}, 

600 L{Datum} or L{a_f2Tuple}). 

601 @kwarg lat: Parallel latitude (C{degrees90}, C{str}). 

602 

603 @return: Distance (C{meter}, same units as B{C{radius}} 

604 or equatorial and polar radii) or C{0.0} for 

605 near-polar B{C{lat}}. 

606 

607 @raise RangeError: Latitude B{C{lat}} outside valid range and 

608 L{pygeodesy.rangerrors} set to C{True}. 

609 

610 @raise TypeError: Invalid B{C{radius}}. 

611 

612 @raise ValueError: Invalid B{C{rad}}, B{C{radius}} or 

613 B{C{lat}}. 

614 

615 @see: Function L{degrees2m} and L{m2radians}. 

616 ''' 

617 return _radians2m(Lam(rad=rad, clip=0), radius, lat) 

618 

619 

620def _radians2m(rad, radius, lat): 

621 '''(INTERNAL) Helper for C{degrees2m} and C{radians2m}. 

622 ''' 

623 m = circle4(radius, lat).radius 

624 return _0_0 if m < EPS0 else (rad * m) 

625 

626 

627def radiansPI(deg): 

628 '''Convert and wrap degrees to radians M{[-PI..+PI]}. 

629 

630 @arg deg: Angle (C{degrees}). 

631 

632 @return: Radians, wrapped (C{radiansPI}) 

633 ''' 

634 return _wrap(radians(deg), PI, PI2) 

635 

636 

637def radiansPI2(deg): 

638 '''Convert and wrap degrees to radians M{[0..+2PI)}. 

639 

640 @arg deg: Angle (C{degrees}). 

641 

642 @return: Radians, wrapped (C{radiansPI2}) 

643 ''' 

644 return _wrap(radians(deg), PI2, PI2) 

645 

646 

647def radiansPI_2(deg): 

648 '''Convert and wrap degrees to radians M{[-3PI/2..+PI/2]}. 

649 

650 @arg deg: Angle (C{degrees}). 

651 

652 @return: Radians, wrapped (C{radiansPI_2}) 

653 ''' 

654 return _wrap(radians(deg), PI_2, PI2) 

655 

656 

657def _sin0cos2(q, r, sign): 

658 '''(INTERNAL) 2-tuple (C{sin(r), cos(r)}) in quadrant C{0 <= B{q} <= 3} 

659 and C{sin} zero I{signed} with B{C{sign}}. 

660 ''' 

661 if r < PI_2: 

662 s, c = sin(r), cos(r) 

663 t = s, c, -s, -c, s 

664 else: # r == PI_2 

665 t = _1_0, _0_0, _N_1_0, _0_0, _1_0 

666# else: # r == 0, testUtility failures 

667# t = _0_0, _1_0, _0_0, _N_1_0, _0_0 

668# q &= 3 

669 s = t[q] or (NEG0 if sign < 0 else _0_0) 

670 c = t[q + 1] or _0_0 

671 return s, c 

672 

673 

674def sincos2(rad): 

675 '''Return the C{sine} and C{cosine} of an angle in C{radians}. 

676 

677 @arg rad: Angle (C{radians}). 

678 

679 @return: 2-Tuple (C{sin(B{rad})}, C{cos(B{rad})}). 

680 

681 @see: U{GeographicLib<https://GeographicLib.SourceForge.io/C++/doc/ 

682 classGeographicLib_1_1Math.html#sincosd>} function U{sincosd 

683 <https://SourceForge.net/p/geographiclib/code/ci/release/tree/ 

684 python/geographiclib/geomath.py#l155>} and C++ U{sincosd 

685 <https://SourceForge.net/p/geographiclib/code/ci/release/tree/ 

686 include/GeographicLib/Math.hpp#l558>}. 

687 ''' 

688 if _isfinite(rad): 

689 q = int(rad * _2__PI) # int(math.floor) 

690 if q < 0: 

691 q -= 1 

692 t = _sin0cos2(q & 3, rad - q * PI_2, rad) 

693 else: 

694 t = NAN, NAN 

695 return t 

696 

697 

698def sincos2_(*rads): 

699 '''Return the C{sine} and C{cosine} of angle(s) in C{radians}. 

700 

701 @arg rads: One or more angles (C{radians}). 

702 

703 @return: Yield the C{sin(B{rad})} and C{cos(B{rad})} for each angle. 

704 

705 @see: function L{sincos2}. 

706 ''' 

707 for r in rads: 

708 s, c = sincos2(r) 

709 yield s 

710 yield c 

711 

712 

713def sincos2d(deg, **adeg): 

714 '''Return the C{sine} and C{cosine} of an angle in C{degrees}. 

715 

716 @arg deg: Angle (C{degrees}). 

717 @kwarg adeg: Optional correction (C{degrees}). 

718 

719 @return: 2-Tuple (C{sin(B{deg_})}, C{cos(B{deg_})}, C{B{deg_} = 

720 B{deg} + B{adeg}}). 

721 

722 @see: U{GeographicLib<https://GeographicLib.SourceForge.io/C++/doc/ 

723 classGeographicLib_1_1Math.html#sincosd>} function U{sincosd 

724 <https://SourceForge.net/p/geographiclib/code/ci/release/tree/ 

725 python/geographiclib/geomath.py#l155>} and C++ U{sincosd 

726 <https://SourceForge.net/p/geographiclib/code/ci/release/tree/ 

727 include/GeographicLib/Math.hpp#l558>}. 

728 ''' 

729 if _isfinite(deg): 

730 q = int(deg * _1__90) # int(math.floor) 

731 if q < 0: 

732 q -= 1 

733 d = deg - q * _90_0 

734 if adeg: 

735 t = _xkwds_get(adeg, adeg=_0_0) 

736 d = _MODS.karney._around(d + t) 

737 t = _sin0cos2(q & 3, radians(d), deg) 

738 else: 

739 t = NAN, NAN 

740 return t 

741 

742 

743def SinCos2(x): 

744 '''Get C{sin} and C{cos} of I{typed} angle. 

745 

746 @arg x: Angle (L{Degrees}, L{Radians} or C{radians}). 

747 

748 @return: 2-Tuple (C{sin(B{x})}, C{cos(B{x})}). 

749 ''' 

750 return sincos2d(x) if isinstance(x, Degrees) else ( 

751 sincos2(x) if isinstance(x, Radians) else 

752 sincos2(float(x))) # assume C{radians} 

753 

754 

755def sincos2d_(*degs): 

756 '''Return the C{sine} and C{cosine} of angle(s) in C{degrees}. 

757 

758 @arg degs: One or more angles (C{degrees}). 

759 

760 @return: Yield the C{sin(B{deg})} and C{cos(B{deg})} for each angle. 

761 

762 @see: Function L{sincos2d}. 

763 ''' 

764 for d in degs: 

765 s, c = sincos2d(d) 

766 yield s 

767 yield c 

768 

769 

770def sincostan3(rad): 

771 '''Return the C{sine}, C{cosine} and C{tangent} of an angle in C{radians}. 

772 

773 @arg rad: Angle (C{radians}). 

774 

775 @return: 3-Tuple (C{sin(B{rad})}, C{cos(B{rad})}, C{tan(B{rad})}). 

776 

777 @see: Function L{sincos2}. 

778 ''' 

779 rad %= PI2 # see ._wrap comments 

780 if rad: 

781 s, c = sincos2(rad) 

782 t = (s / c) if c else (NINF if s < 0 

783 else (INF if s > 0 else s)) 

784 else: # sin(-0.0) == tan(-0.0) = -0.0 

785 c = _1_0 

786 s = t = NEG0 if isneg0(rad) else _0_0 

787 return s, c, t 

788 

789 

790def SM2m(sm): 

791 '''Convert statute miles to meter (m). 

792 

793 @arg sm: Value in statute miles (C{scalar}). 

794 

795 @return: Value in meter (C{float}). 

796 

797 @raise ValueError: Invalid B{C{sm}}. 

798 ''' 

799 return Meter(Float(sm=sm) * _M_SM) 

800 

801 

802def tan_2(rad, **semi): # edge=1 

803 '''Compute the tangent of half angle. 

804 

805 @arg rad: Angle (C{radians}). 

806 @kwarg semi: Angle or edge name and index 

807 for semi-circular error. 

808 

809 @return: M{tan(rad / 2)} (C{float}). 

810 

811 @raise ValueError: If B{C{rad}} is semi-circular 

812 and B{C{semi}} is given. 

813 ''' 

814 # .formy.excessKarney_, .sphericalTrigonometry.areaOf 

815 if semi and isnear0(fabs(rad) - PI): 

816 for n, v in semi.items(): 

817 break 

818 n = _SPACE_(n, _radians_) if not isint(v) else \ 

819 _SPACE_(_MODS.streprs.Fmt.SQUARE(**semi), _edge_) 

820 raise _ValueError(n, rad, txt=_semi_circular_) 

821 

822 return tan(rad * _0_5) 

823 

824 

825def tand(deg, **error_kwds): 

826 '''Return the C{tangent} of an angle in C{degrees}. 

827 

828 @arg deg: Angle (C{degrees}). 

829 @kwarg error_kwds: Error to raise (C{ValueError}). 

830 

831 @return: C{tan(B{deg})}. 

832 

833 @raise ValueError: If L{pygeodesy.isnear0}C{(cos(B{deg})}. 

834 ''' 

835 s, c = sincos2d(deg) 

836 if isnear0(c): 

837 raise _valueError(tand, deg, **error_kwds) 

838 return s / c 

839 

840 

841def tand_(*degs, **error_kwds): 

842 '''Return the C{tangent} of angle(s) in C{degrees}. 

843 

844 @arg degs: One or more angles (C{degrees}). 

845 @kwarg error_kwds: Error to raise (C{ValueError}). 

846 

847 @return: Yield the C{tan(B{deg})} for each angle. 

848 

849 @raise ValueError: See L{pygeodesy.tand}. 

850 ''' 

851 for d in degs: 

852 yield tand(d, **error_kwds) 

853 

854 

855def tanPI_2_2(rad): 

856 '''Compute the tangent of half angle, 90 degrees rotated. 

857 

858 @arg rad: Angle (C{radians}). 

859 

860 @return: M{tan((rad + PI/2) / 2)} (C{float}). 

861 ''' 

862 return tan((rad + PI_2) * _0_5) 

863 

864 

865def toise2m(toises): 

866 '''Convert French U{toises<https://WikiPedia.org/wiki/Toise>} to meter. 

867 

868 @arg toises: Value in toises (C{scalar}). 

869 

870 @return: Value in C{meter} (C{float}). 

871 

872 @raise ValueError: Invalid B{C{toises}}. 

873 

874 @see: Function L{fathom2m}. 

875 ''' 

876 return Meter(Float(toises=toises) * _M_TOISE) 

877 

878 

879def truncate(x, ndigits=None): 

880 '''Truncate to the given number of digits. 

881 

882 @arg x: Value to truncate (C{scalar}). 

883 @kwarg ndigits: Number of digits (C{int}), 

884 aka I{precision}. 

885 

886 @return: Truncated B{C{x}} (C{float}). 

887 

888 @see: Python function C{round}. 

889 ''' 

890 if isint(ndigits): 

891 p = _10_0**ndigits 

892 x = int(x * p) / p 

893 return x 

894 

895 

896def unroll180(lon1, lon2, wrap=True): 

897 '''Unroll longitudinal delta and wrap longitude in degrees. 

898 

899 @arg lon1: Start longitude (C{degrees}). 

900 @arg lon2: End longitude (C{degrees}). 

901 @kwarg wrap: If C{True}, wrap and unroll to the M{(-180..+180]} 

902 range (C{bool}). 

903 

904 @return: 2-Tuple C{(B{lon2}-B{lon1}, B{lon2})} unrolled (C{degrees}, 

905 C{degrees}). 

906 

907 @see: Capability C{LONG_UNROLL} in U{GeographicLib 

908 <https://GeographicLib.SourceForge.io/html/python/interface.html#outmask>}. 

909 ''' 

910 d = lon2 - lon1 

911 if wrap and fabs(d) > _180_0: 

912 u = _wrap(d, _180_0, _360_0) 

913 if u != d: 

914 return u, (lon1 + u) 

915 return d, lon2 

916 

917 

918def _unrollon(p1, p2, wrap=False): # unroll180 == .karney._unroll2 

919 '''(INTERNAL) Wrap/normalize, unroll and replace longitude. 

920 ''' 

921 lat, lon = p2.lat, p2.lon 

922 if wrap and _Wrap.normal: 

923 lat, lon = _Wrap.latlon(lat, lon) 

924 _, lon = unroll180(p1.lon, lon, wrap=True) 

925 if lat != p2.lat or fabs(lon - p2.lon) > EPS: 

926 p2 = p2.dup(lat=lat, lon=wrap180(lon)) 

927 # p2 = p2.copy(); p2.latlon = lat, wrap180(lon) 

928 return p2 

929 

930 

931def _unrollon3(p1, p2, p3, wrap=False): 

932 '''(INTERNAL) Wrap/normalize, unroll 2 points. 

933 ''' 

934 w = wrap 

935 if w: 

936 w = _Wrap.normal 

937 p2 = _unrollon(p1, p2, wrap=w) 

938 p3 = _unrollon(p1, p3, wrap=w) 

939 p2 = _unrollon(p2, p3) 

940 return p2, p3, w # was wrapped? 

941 

942 

943def unrollPI(rad1, rad2, wrap=True): 

944 '''Unroll longitudinal delta and wrap longitude in radians. 

945 

946 @arg rad1: Start longitude (C{radians}). 

947 @arg rad2: End longitude (C{radians}). 

948 @kwarg wrap: If C{True}, wrap and unroll to the M{(-PI..+PI]} 

949 range (C{bool}). 

950 

951 @return: 2-Tuple C{(B{rad2}-B{rad1}, B{rad2})} unrolled 

952 (C{radians}, C{radians}). 

953 

954 @see: Capability C{LONG_UNROLL} in U{GeographicLib 

955 <https://GeographicLib.SourceForge.io/html/python/interface.html#outmask>}. 

956 ''' 

957 r = rad2 - rad1 

958 if wrap and fabs(r) > PI: 

959 u = _wrap(r, PI, PI2) 

960 if u != r: 

961 return u, (rad1 + u) 

962 return r, rad2 

963 

964 

965def _valueError(where, x, **kwds): 

966 '''(INTERNAL) Return a C{_ValueError}. 

967 ''' 

968 x = _MODS.streprs.Fmt.PAREN(where.__name__, x) 

969 return _ValueError(x, **kwds) 

970 

971 

972class _Wrap(object): 

973 

974 _normal = False # default 

975 

976 @property 

977 def normal(self): 

978 '''Get the current L{normal} setting (C{True}, 

979 C{False} or C{None}). 

980 ''' 

981 return self._normal 

982 

983 @normal.setter # PYCHOK setter! 

984 def normal(self, setting): 

985 '''Set L{normal} to C{True}, C{False} or C{None}. 

986 ''' 

987 t = {True: (_MODS.formy.normal, _MODS.formy.normal_), 

988 False: (self.wraplatlon, self.wraphilam), 

989 None: (_passargs, _passargs)}.get(setting, ()) 

990 if t: 

991 self.latlon, self.philam = t 

992 self._normal = setting 

993 

994 def latlonDMS2(self, lat, lon, **DMS2_kwds): 

995 if isstr(lat) or isstr(lon): 

996 kwds = _xkwds(DMS2_kwds, clipLon=0, clipLat=0) 

997 lat, lon = _MODS.dms.parseDMS2(lat, lon, **kwds) 

998 return self.latlon(lat, lon) 

999 

1000# def normalatlon(self, *latlon): 

1001# return _MODS.formy.normal(*latlon) 

1002 

1003# def normalamphi(self, *philam): 

1004# return _MODS.formy.normal_(*philam) 

1005 

1006 def wraplatlon(self, lat, lon): 

1007 return wrap90(lat), wrap180(lon) 

1008 

1009 latlon = wraplatlon # default 

1010 

1011 def latlon3(self, lon1, lat2, lon2, wrap): 

1012 if wrap: 

1013 lat2, lon2 = self.latlon(lat2, lon2) 

1014 lon21, lon2 = unroll180(lon1, lon2) 

1015 else: 

1016 lon21 = lon2 - lon1 

1017 return lon21, lat2, lon2 

1018 

1019 def _latlonop(self, wrap): 

1020 if wrap and self._normal is not None: 

1021 return self.latlon 

1022 else: 

1023 return _passargs 

1024 

1025 def wraphilam(self, phi, lam): 

1026 return wrapPI_2(phi), wrapPI(lam) 

1027 

1028 philam = wraphilam # default 

1029 

1030 def philam3(self, lam1, phi2, lam2, wrap): 

1031 if wrap: 

1032 phi2, lam2 = self.philam(phi2, lam2) 

1033 lam21, lam2 = unrollPI(lam1, lam2) 

1034 else: 

1035 lam21 = lam2 - lam1 

1036 return lam21, phi2, lam2 

1037 

1038 def _philamop(self, wrap): 

1039 if wrap and self._normal is not None: 

1040 return self.philam 

1041 else: 

1042 return _passargs 

1043 

1044 def wraphilam(self, phi, lam): 

1045 return wrapPI_2(phi), wrapPI(lam) 

1046 

1047 def point(self, ll, wrap=True): # in .points._fractional, -.PointsIter.iterate, ... 

1048 '''Return C{ll} or a copy, I{normalized} or I{wrap}'d. 

1049 ''' 

1050 if wrap and self._normal is not None: 

1051 lat, lon = ll.latlon 

1052 if fabs(lon) > 180 or fabs(lat) > 90: 

1053 _n = self.latlon 

1054 ll = ll.copy(name=_n.__name__) 

1055 ll.latlon = _n(lat, lon) 

1056 return ll 

1057 

1058_Wrap = _Wrap() # PYCHOK singleton 

1059 

1060 

1061def _wrap(angle, wrap, modulo): 

1062 '''(INTERNAL) Angle wrapper M{((wrap-modulo)..+wrap]}. 

1063 

1064 @arg angle: Angle (C{degrees}, C{radians} or C{grades}). 

1065 @arg wrap: Range (C{degrees}, C{radians} or C{grades}). 

1066 @arg modulo: Upper limit (360 C{degrees}, PI2 C{radians} or 400 C{grades}). 

1067 

1068 @return: The B{C{angle}}, wrapped (C{degrees}, C{radians} or C{grades}). 

1069 ''' 

1070 a = float(angle) 

1071 if not (wrap - modulo) <= a < wrap: 

1072 # math.fmod(-1.5, 3.14) == -1.5, but -1.5 % 3.14 == 1.64 

1073 # math.fmod(-1.5, 360) == -1.5, but -1.5 % 360 == 358.5 

1074 a %= modulo 

1075 if a > wrap: 

1076 a -= modulo 

1077 return a 

1078 

1079 

1080def wrap90(deg): 

1081 '''Wrap degrees to M{[-270..+90]}. 

1082 

1083 @arg deg: Angle (C{degrees}). 

1084 

1085 @return: Degrees, wrapped (C{degrees90}). 

1086 ''' 

1087 return _wrap(deg, _90_0, _360_0) 

1088 

1089 

1090def wrap180(deg): 

1091 '''Wrap degrees to M{[-180..+180]}. 

1092 

1093 @arg deg: Angle (C{degrees}). 

1094 

1095 @return: Degrees, wrapped (C{degrees180}). 

1096 ''' 

1097 return _wrap(deg, _180_0, _360_0) 

1098 

1099 

1100def wrap360(deg): # see .streprs._umod_360 

1101 '''Wrap degrees to M{[0..+360)}. 

1102 

1103 @arg deg: Angle (C{degrees}). 

1104 

1105 @return: Degrees, wrapped (C{degrees360}). 

1106 ''' 

1107 return _wrap(deg, _360_0, _360_0) 

1108 

1109 

1110def wrapPI(rad): 

1111 '''Wrap radians to M{[-PI..+PI]}. 

1112 

1113 @arg rad: Angle (C{radians}). 

1114 

1115 @return: Radians, wrapped (C{radiansPI}). 

1116 ''' 

1117 return _wrap(rad, PI, PI2) 

1118 

1119 

1120def wrapPI2(rad): 

1121 '''Wrap radians to M{[0..+2PI)}. 

1122 

1123 @arg rad: Angle (C{radians}). 

1124 

1125 @return: Radians, wrapped (C{radiansPI2}). 

1126 ''' 

1127 return _wrap(rad, PI2, PI2) 

1128 

1129 

1130def wrapPI_2(rad): 

1131 '''Wrap radians to M{[-3PI/2..+PI/2]}. 

1132 

1133 @arg rad: Angle (C{radians}). 

1134 

1135 @return: Radians, wrapped (C{radiansPI_2}). 

1136 ''' 

1137 return _wrap(rad, PI_2, PI2) 

1138 

1139 

1140def wrap_normal(*normal): 

1141 '''Define the operation for the keyword argument C{B{wrap}=True}, 

1142 across L{pygeodesy}: I{wrap}, I{normalize} or I{no-op}. For 

1143 backward compatibility, the default is I{wrap}. 

1144 

1145 @arg normal: If C{True}, I{normalize} lat- and longitude using 

1146 L{normal} or L{normal_}, if C{False}, I{wrap} the 

1147 lat- and longitude individually by L{wrap90} or 

1148 L{wrapPI_2} respectively L{wrap180}, L{wrapPI} or 

1149 if C{None}, leave lat- and longitude I{unchanged}. 

1150 Do not supply any value to get the current setting. 

1151 

1152 @return: The previous L{wrap_normal} setting (C{bool} or C{None}). 

1153 ''' 

1154 t = _Wrap.normal 

1155 if normal: 

1156 _Wrap.normal = normal[0] 

1157 return t 

1158 

1159 

1160def yard2m(yards): 

1161 '''Convert I{UK} yards to meter. 

1162 

1163 @arg yards: Value in yards (C{scalar}). 

1164 

1165 @return: Value in C{meter} (C{float}). 

1166 

1167 @raise ValueError: Invalid B{C{yards}}. 

1168 ''' 

1169 return Float(yards=yards) * _M_YARD_UK 

1170 

1171# **) MIT License 

1172# 

1173# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved. 

1174# 

1175# Permission is hereby granted, free of charge, to any person obtaining a 

1176# copy of this software and associated documentation files (the "Software"), 

1177# to deal in the Software without restriction, including without limitation 

1178# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

1179# and/or sell copies of the Software, and to permit persons to whom the 

1180# Software is furnished to do so, subject to the following conditions: 

1181# 

1182# The above copyright notice and this permission notice shall be included 

1183# in all copies or substantial portions of the Software. 

1184# 

1185# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

1186# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

1187# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

1188# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

1189# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

1190# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

1191# OTHER DEALINGS IN THE SOFTWARE.