Coverage for pygeodesy/utily.py: 90%

321 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-09-01 13:41 -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 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 m2chain(meter): 

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

392 

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

394 

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

396 

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

398 ''' 

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

400 

401 

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

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

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

405 

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

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

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

409 L{a_f2Tuple}). 

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

411 

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

413 

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

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

416 

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

418 

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

420 or B{C{lat}}. 

421 

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

423 ''' 

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

425 

426 

427def m2fathom(meter): 

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

429 

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

431 

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

433 

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

435 

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

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

438 ''' 

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

440 

441 

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

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

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

445 

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

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

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

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

450 I{International} foot. 

451 

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

453 

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

455 ''' 

456 # * 3.2808333333333333, US Survey 3937 / 1200 

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

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

459 (_M_FOOT_FR if pied else 

460 (_M_FOOT_GE if fuss else _M_FOOT)))) 

461 

462 

463def m2furlong(meter): 

464 '''Convert meter to furlongs. 

465 

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

467 

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

469 

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

471 ''' 

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

473 

474 

475def m2km(meter): 

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

477 

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

479 

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

481 

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

483 ''' 

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

485 

486 

487def m2NM(meter): 

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

489 

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

491 

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

493 

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

495 ''' 

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

497 

498 

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

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

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

502 

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

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

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

506 L{a_f2Tuple}). 

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

508 

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

510 

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

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

513 

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

515 

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

517 or B{C{lat}}. 

518 

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

520 ''' 

521 m = circle4(radius, lat).radius 

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

523 

524 

525def m2SM(meter): 

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

527 

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

529 

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

531 

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

533 ''' 

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

535 

536 

537def m2toise(meter): 

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

539 

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

541 

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

543 

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

545 

546 @see: Function L{m2fathom}. 

547 ''' 

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

549 

550 

551def m2yard(meter): 

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

553 

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

555 

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

557 

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

559 ''' 

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

561 

562 

563def NM2m(nm): 

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

565 

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

567 

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

569 

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

571 ''' 

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

573 

574 

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

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

577 ''' 

578 return arg 

579 

580 

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

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

583 ''' 

584 return args 

585 

586 

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

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

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

590 

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

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

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

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

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

596 

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

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

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

600 

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

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

603 

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

605 

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

607 B{C{lat}}. 

608 

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

610 ''' 

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

612 

613 

614def _radians2m(rad, radius, lat): 

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

616 ''' 

617 m = circle4(radius, lat).radius 

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

619 

620 

621def radiansPI(deg): 

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

623 

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

625 

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

627 ''' 

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

629 

630 

631def radiansPI2(deg): 

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

633 

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

635 

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

637 ''' 

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

639 

640 

641def radiansPI_2(deg): 

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

643 

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

645 

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

647 ''' 

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

649 

650 

651def _sin0cos2(q, r, sign): 

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

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

654 ''' 

655 if r < PI_2: 

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

657 t = s, c, -s, -c, s 

658 else: # r == PI_2 

659 t = _1_0, _0_0, _N_1_0, _0_0, _1_0 

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

661# t = _0_0, _1_0, _0_0, _N_1_0, _0_0 

662# q &= 3 

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

664 c = t[q + 1] or _0_0 

665 return s, c 

666 

667 

668def sincos2(rad): 

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

670 

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

672 

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

674 

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

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

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

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

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

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

681 ''' 

682 if _isfinite(rad): 

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

684 if q < 0: 

685 q -= 1 

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

687 else: 

688 t = NAN, NAN 

689 return t 

690 

691 

692def sincos2_(*rads): 

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

694 

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

696 

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

698 

699 @see: function L{sincos2}. 

700 ''' 

701 for r in rads: 

702 s, c = sincos2(r) 

703 yield s 

704 yield c 

705 

706 

707def sincos2d(deg, **adeg): 

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

709 

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

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

712 

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

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

715 

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

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

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

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

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

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

722 ''' 

723 if _isfinite(deg): 

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

725 if q < 0: 

726 q -= 1 

727 d = deg - q * _90_0 

728 if adeg: 

729 t = _xkwds_get(adeg, adeg=_0_0) 

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

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

732 else: 

733 t = NAN, NAN 

734 return t 

735 

736 

737def SinCos2(x): 

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

739 

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

741 

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

743 ''' 

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

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

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

747 

748 

749def sincos2d_(*degs): 

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

751 

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

753 

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

755 

756 @see: Function L{sincos2d}. 

757 ''' 

758 for d in degs: 

759 s, c = sincos2d(d) 

760 yield s 

761 yield c 

762 

763 

764def sincostan3(rad): 

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

766 

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

768 

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

770 

771 @see: Function L{sincos2}. 

772 ''' 

773 rad %= PI2 # see ._wrap comments 

774 if rad: 

775 s, c = sincos2(rad) 

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

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

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

779 c = _1_0 

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

781 return s, c, t 

782 

783 

784def SM2m(sm): 

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

786 

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

788 

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

790 

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

792 ''' 

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

794 

795 

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

797 '''Compute the tangent of half angle. 

798 

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

800 @kwarg semi: Angle or edge name and index 

801 for semi-circular error. 

802 

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

804 

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

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

807 ''' 

808 # .formy.excessKarney_, .sphericalTrigonometry.areaOf 

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

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

811 break 

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

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

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

815 

816 return tan(rad * _0_5) 

817 

818 

819def tand(deg, **error_kwds): 

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

821 

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

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

824 

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

826 

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

828 ''' 

829 s, c = sincos2d(deg) 

830 if isnear0(c): 

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

832 return s / c 

833 

834 

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

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

837 

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

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

840 

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

842 

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

844 ''' 

845 for d in degs: 

846 yield tand(d, **error_kwds) 

847 

848 

849def tanPI_2_2(rad): 

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

851 

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

853 

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

855 ''' 

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

857 

858 

859def toise2m(toises): 

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

861 

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

863 

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

865 

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

867 

868 @see: Function L{fathom2m}. 

869 ''' 

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

871 

872 

873def truncate(x, ndigits=None): 

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

875 

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

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

878 aka I{precision}. 

879 

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

881 

882 @see: Python function C{round}. 

883 ''' 

884 if isint(ndigits): 

885 p = _10_0**ndigits 

886 x = int(x * p) / p 

887 return x 

888 

889 

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

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

892 

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

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

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

896 range (C{bool}). 

897 

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

899 C{degrees}). 

900 

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

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

903 ''' 

904 d = lon2 - lon1 

905 if wrap and fabs(d) > _180_0: 

906 u = _wrap(d, _180_0, _360_0) 

907 if u != d: 

908 return u, (lon1 + u) 

909 return d, lon2 

910 

911 

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

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

914 ''' 

915 lat, lon = p2.lat, p2.lon 

916 if wrap and _Wrap.normal: 

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

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

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

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

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

922 return p2 

923 

924 

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

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

927 ''' 

928 w = wrap 

929 if w: 

930 w = _Wrap.normal 

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

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

933 p2 = _unrollon(p2, p3) 

934 return p2, p3, w # was wrapped? 

935 

936 

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

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

939 

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

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

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

943 range (C{bool}). 

944 

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

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

947 

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

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

950 ''' 

951 r = rad2 - rad1 

952 if wrap and fabs(r) > PI: 

953 u = _wrap(r, PI, PI2) 

954 if u != r: 

955 return u, (rad1 + u) 

956 return r, rad2 

957 

958 

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

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

961 ''' 

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

963 return _ValueError(x, **kwds) 

964 

965 

966class _Wrap(object): 

967 

968 _normal = False # default 

969 

970 @property 

971 def normal(self): 

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

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

974 ''' 

975 return self._normal 

976 

977 @normal.setter # PYCHOK setter! 

978 def normal(self, setting): 

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

980 ''' 

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

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

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

984 if t: 

985 self.latlon, self.philam = t 

986 self._normal = setting 

987 

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

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

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

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

992 return self.latlon(lat, lon) 

993 

994# def normalatlon(self, *latlon): 

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

996 

997# def normalamphi(self, *philam): 

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

999 

1000 def wraplatlon(self, lat, lon): 

1001 return wrap90(lat), wrap180(lon) 

1002 

1003 latlon = wraplatlon # default 

1004 

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

1006 if wrap: 

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

1008 lon21, lon2 = unroll180(lon1, lon2) 

1009 else: 

1010 lon21 = lon2 - lon1 

1011 return lon21, lat2, lon2 

1012 

1013 def _latlonop(self, wrap): 

1014 if wrap and self._normal is not None: 

1015 return self.latlon 

1016 else: 

1017 return _passargs 

1018 

1019 def wraphilam(self, phi, lam): 

1020 return wrapPI_2(phi), wrapPI(lam) 

1021 

1022 philam = wraphilam # default 

1023 

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

1025 if wrap: 

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

1027 lam21, lam2 = unrollPI(lam1, lam2) 

1028 else: 

1029 lam21 = lam2 - lam1 

1030 return lam21, phi2, lam2 

1031 

1032 def _philamop(self, wrap): 

1033 if wrap and self._normal is not None: 

1034 return self.philam 

1035 else: 

1036 return _passargs 

1037 

1038 def wraphilam(self, phi, lam): 

1039 return wrapPI_2(phi), wrapPI(lam) 

1040 

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

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

1043 ''' 

1044 if wrap and self._normal is not None: 

1045 lat, lon = ll.latlon 

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

1047 _n = self.latlon 

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

1049 ll.latlon = _n(lat, lon) 

1050 return ll 

1051 

1052_Wrap = _Wrap() # PYCHOK singleton 

1053 

1054 

1055def _wrap(angle, wrap, modulo): 

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

1057 

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

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

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

1061 

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

1063 ''' 

1064 a = float(angle) 

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

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

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

1068 a %= modulo 

1069 if a > wrap: 

1070 a -= modulo 

1071 return a 

1072 

1073 

1074def wrap90(deg): 

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

1076 

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

1078 

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

1080 ''' 

1081 return _wrap(deg, _90_0, _360_0) 

1082 

1083 

1084def wrap180(deg): 

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

1086 

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

1088 

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

1090 ''' 

1091 return _wrap(deg, _180_0, _360_0) 

1092 

1093 

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

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

1096 

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

1098 

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

1100 ''' 

1101 return _wrap(deg, _360_0, _360_0) 

1102 

1103 

1104def wrapPI(rad): 

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

1106 

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

1108 

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

1110 ''' 

1111 return _wrap(rad, PI, PI2) 

1112 

1113 

1114def wrapPI2(rad): 

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

1116 

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

1118 

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

1120 ''' 

1121 return _wrap(rad, PI2, PI2) 

1122 

1123 

1124def wrapPI_2(rad): 

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

1126 

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

1128 

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

1130 ''' 

1131 return _wrap(rad, PI_2, PI2) 

1132 

1133 

1134def wrap_normal(*normal): 

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

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

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

1138 

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

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

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

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

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

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

1145 

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

1147 ''' 

1148 t = _Wrap.normal 

1149 if normal: 

1150 _Wrap.normal = normal[0] 

1151 return t 

1152 

1153 

1154def yard2m(yards): 

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

1156 

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

1158 

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

1160 

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

1162 ''' 

1163 return Float(yards=yards) * _M_YARD_UK 

1164 

1165# **) MIT License 

1166# 

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

1168# 

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

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

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

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

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

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

1175# 

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

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

1178# 

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

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

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

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

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

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

1185# OTHER DEALINGS IN THE SOFTWARE.