1

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

3

4 u'''Various utility functions.

5

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

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

8 U{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

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

12

13 from pygeodesy.basics import copysign0, isint, isstr

14 from 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

18 from pygeodesy.errors import _ValueError, _xkwds, _xkwds_get

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

20 from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS

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

22

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

24

25__all__ = _ALL_LAZY.utily

26__version__ = '23.05.11'

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

43 def 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

49 def 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

62 def 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

75 def 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

81 def 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

89 def 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

100 def 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

125 def 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

137 def 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

159 def 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

175 def 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

192 def 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

208 def 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

225 def 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

235 def 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

245 def 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

255 def 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

265 def 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

292 def 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

307 def 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

326 def 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

338 def 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

348 def 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

358 def 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

368 def 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

378 def 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

390 def 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

402 def 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

427 def 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

442 def 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

463 def 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

475 def 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

487 def 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

499 def 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

525 def 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

537 def 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

551 def 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

563 def 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

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

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

577 '''

578 return args

579

580

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

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

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

584

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

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

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

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

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

590

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

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

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

594

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

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

597

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

599

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

601 B{C{lat}}.

602

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

604 '''

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

606

607

608 def _radians2m(rad, radius, lat):

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

610 '''

611 m = circle4(radius, lat).radius

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

613

614

615 def radiansPI(deg):

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

617

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

619

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

621 '''

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

623

624

625 def radiansPI2(deg):

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

627

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

629

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

631 '''

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

633

634

635 def radiansPI_2(deg):

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

637

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

639

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

641 '''

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

643

644

645 def _sin0cos2(q, r, sign):

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

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

648 '''

649 if r < PI_2:

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

651 t = s, c, -s, -c, s

652 else: # r == PI_2

653 t = _1_0, _0_0, _N_1_0, _0_0, _1_0

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

655# t = _0_0, _1_0, _0_0, _N_1_0, _0_0

656# q &= 3

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

658 c = t[q + 1] or _0_0

659 return s, c

660

661

662 def sincos2(rad):

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

664

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

666

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

668

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

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

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

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

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

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

675 '''

676 if _isfinite(rad):

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

678 if q < 0:

679 q -= 1

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

681 else:

682 t = NAN, NAN

683 return t

684

685

686 def sincos2_(*rads):

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

688

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

690

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

692

693 @see: function L{sincos2}.

694 '''

695 for r in rads:

696 s, c = sincos2(r)

697 yield s

698 yield c

699

700

701 def sincos2d(deg, **adeg):

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

703

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

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

706

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

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

709

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

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

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

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

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

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

716 '''

717 if _isfinite(deg):

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

719 if q < 0:

720 q -= 1

721 d = deg - q * _90_0

722 if adeg:

723 t = _xkwds_get(adeg, adeg=_0_0)

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

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

726 else:

727 t = NAN, NAN

728 return t

729

730

731 def SinCos2(x):

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

733

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

735

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

737 '''

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

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

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

741

742

743 def sincos2d_(*degs):

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

745

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

747

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

749

750 @see: Function L{sincos2d}.

751 '''

752 for d in degs:

753 s, c = sincos2d(d)

754 yield s

755 yield c

756

757

758 def sincostan3(rad):

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

760

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

762

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

764

765 @see: Function L{sincos2}.

766 '''

767 rad %= PI2 # see ._wrap comments

768 if rad:

769 s, c = sincos2(rad)

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

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

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

773 c = _1_0

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

775 return s, c, t

776

777

778 def SM2m(sm):

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

780

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

782

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

784

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

786 '''

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

788

789

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

791 '''Compute the tangent of half angle.

792

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

794 @kwarg semi: Angle or edge name and index

795 for semi-circular error.

796

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

798

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

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

801 '''

802 # .formy.excessKarney_, .sphericalTrigonometry.areaOf

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

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

805 break

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

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

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

809

810 return tan(rad * _0_5)

811

812

813 def tand(deg, **error_kwds):

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

815

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

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

818

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

820

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

822 '''

823 s, c = sincos2d(deg)

824 if isnear0(c):

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

826 return s / c

827

828

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

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

831

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

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

834

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

836

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

838 '''

839 for d in degs:

840 yield tand(d, **error_kwds)

841

842

843 def tanPI_2_2(rad):

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

845

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

847

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

849 '''

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

851

852

853 def toise2m(toises):

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

855

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

857

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

859

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

861

862 @see: Function L{fathom2m}.

863 '''

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

865

866

867 def truncate(x, ndigits=None):

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

869

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

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

872 aka I{precision}.

873

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

875

876 @see: Python function C{round}.

877 '''

878 if isint(ndigits):

879 p = _10_0**ndigits

880 x = int(x * p) / p

881 return x

882

883

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

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

886

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

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

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

890 range (C{bool}).

891

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

893 C{degrees}).

894

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

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

897 '''

898 d = lon2 - lon1

899 if wrap and fabs(d) > _180_0:

900 u = _wrap(d, _180_0, _360_0)

901 if u != d:

902 return u, (lon1 + u)

903 return d, lon2

904

905

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

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

908 '''

909 lat, lon = p2.lat, p2.lon

910 if wrap and _Wrap.normal:

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

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

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

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

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

916 return p2

917

918

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

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

921 '''

922 w = wrap

923 if w:

924 w = _Wrap.normal

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

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

927 p2 = _unrollon(p2, p3)

928 return p2, p3, w # was wrapped?

929

930

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

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

933

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

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

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

937 range (C{bool}).

938

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

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

941

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

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

944 '''

945 r = rad2 - rad1

946 if wrap and fabs(r) > PI:

947 u = _wrap(r, PI, PI2)

948 if u != r:

949 return u, (rad1 + u)

950 return r, rad2

951

952

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

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

955 '''

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

957 return _ValueError(x, **kwds)

958

959

960 class _Wrap(object):

961

962 _normal = False # default

963

964 @property

965 def normal(self):

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

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

968 '''

969 return self._normal

970

971 @normal.setter # PYCHOK setter!

972 def normal(self, setting):

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

974 '''

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

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

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

978 if t:

979 self.latlon, self.philam = t

980 self._normal = setting

981

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

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

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

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

986 return self.latlon(lat, lon)

987

988# def normalatlon(self, *latlon):

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

990

991# def normalamphi(self, *philam):

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

993

994 def wraplatlon(self, lat, lon):

995 return wrap90(lat), wrap180(lon)

996

997 latlon = wraplatlon # default

998

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

1000 if wrap:

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

1002 lon21, lon2 = unroll180(lon1, lon2)

1003 else:

1004 lon21 = lon2 - lon1

1005 return lon21, lat2, lon2

1006

1007 def _latlonop(self, wrap):

1008 if wrap and self._normal is not None:

1009 return self.latlon

1010 else:

1011 return _passargs

1012

1013 def wraphilam(self, phi, lam):

1014 return wrapPI_2(phi), wrapPI(lam)

1015

1016 philam = wraphilam # default

1017

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

1019 if wrap:

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

1021 lam21, lam2 = unrollPI(lam1, lam2)

1022 else:

1023 lam21 = lam2 - lam1

1024 return lam21, phi2, lam2

1025

1026 def _philamop(self, wrap):

1027 if wrap and self._normal is not None:

1028 return self.philam

1029 else:

1030 return _passargs

1031

1032 def wraphilam(self, phi, lam):

1033 return wrapPI_2(phi), wrapPI(lam)

1034

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

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

1037 '''

1038 if wrap and self._normal is not None:

1039 lat, lon = ll.latlon

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

1041 _n = self.latlon

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

1043 ll.latlon = _n(lat, lon)

1044 return ll

1045

1046_Wrap = _Wrap() # PYCHOK singleton

1047

1048

1049 def _wrap(angle, wrap, modulo):

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

1051

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

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

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

1055

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

1057 '''

1058 a = float(angle)

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

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

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

1062 a %= modulo

1063 if a > wrap:

1064 a -= modulo

1065 return a

1066

1067

1068 def wrap90(deg):

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

1070

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

1072

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

1074 '''

1075 return _wrap(deg, _90_0, _360_0)

1076

1077

1078 def wrap180(deg):

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

1080

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

1082

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

1084 '''

1085 return _wrap(deg, _180_0, _360_0)

1086

1087

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

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

1090

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

1092

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

1094 '''

1095 return _wrap(deg, _360_0, _360_0)

1096

1097

1098 def wrapPI(rad):

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

1100

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

1102

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

1104 '''

1105 return _wrap(rad, PI, PI2)

1106

1107

1108 def wrapPI2(rad):

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

1110

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

1112

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

1114 '''

1115 return _wrap(rad, PI2, PI2)

1116

1117

1118 def wrapPI_2(rad):

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

1120

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

1122

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

1124 '''

1125 return _wrap(rad, PI_2, PI2)

1126

1127

1128 def wrap_normal(*normal):

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

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

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

1132

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

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

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

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

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

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

1139

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

1141 '''

1142 t = _Wrap.normal

1143 if normal:

1144 _Wrap.normal = normal[0]

1145 return t

1146

1147

1148 def yard2m(yards):

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

1150

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

1152

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

1154

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

1156 '''

1157 return Float(yards=yards) * _M_YARD_UK

1158

1159# **) MIT License

1160#

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

1162#

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

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

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

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

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

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

1169#

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

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

1172#

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

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

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

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

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

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

1179# OTHER DEALINGS IN THE SOFTWARE.