1

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

3

4 u'''(INTERNAL) Private elliposiodal and spherical C{Nvector} base classes

5 L{LatLonNvectorBase} and L{NvectorBase} and function L{sumOf}.

6

7 Pure Python implementation of C{n-vector}-based geodesy tools for ellipsoidal

8 earth models, transcoded from JavaScript originals by I{(C) Chris Veness 2005-2016}

9 and published under the same MIT Licence**, see U{Vector-based geodesy

10<https://www.Movable-Type.co.UK/scripts/latlong-vectors.html>}.

11'''

12

13# from pygeodesy.basics import map1 # from .fsums

14 from pygeodesy.constants import EPS, EPS1, EPS_2, R_M, _2_0, _N_2_0

15# from pygeodesy.datums import _spherical_datum # from .formy

16 from pygeodesy.errors import IntersectionError, _ValueError, VectorError, \

17 _xkwds, _xkwds_pop

18 from pygeodesy.fmath import fdot, fidw, hypot_ # PYCHOK fdot shared

19 from pygeodesy.fsums import Fsum, fsumf_, map1

20 from pygeodesy.formy import _isequalTo, n_xyz2latlon, n_xyz2philam, \

21 _spherical_datum

22 from pygeodesy.interns import NN, _1_, _2_, _3_, _bearing_, _coincident_, \

23 _COMMASPACE_, _distance_, _h_, _insufficient_, \

24 _intersection_, _no_, _NorthPole_, _point_, \

25 _pole_, _SPACE_, _SouthPole_, _UNDER

26 from pygeodesy.latlonBase import LatLonBase, _ALL_DOCS, _MODS

27# from pygeodesy.lazily import _ALL_DOCS, _ALL_MODS as _MODS # from .latlonBase

28 from pygeodesy.named import notImplemented, _xother3

29 from pygeodesy.namedTuples import Trilaterate5Tuple, Vector3Tuple, \

30 Vector4Tuple

31 from pygeodesy.props import deprecated_method, property_doc_, \

32 Property_RO, _update_all

33 from pygeodesy.streprs import Fmt, hstr, unstr, _xattrs

34 from pygeodesy.units import Bearing, Height, Radius_, Scalar

35 from pygeodesy.utily import sincos2d, _unrollon, _unrollon3

36 from pygeodesy.vector3d import Vector3d, _xyzhdn3

37

38 from math import fabs, sqrt # atan2, cos, sin

39

40__all__ = (_NorthPole_, _SouthPole_) # constants

41__version__ = '23.05.15'

42

43

44 class NvectorBase(Vector3d): # XXX kept private

45 '''Base class for ellipsoidal and spherical C{Nvector}s.

46 '''

47 _datum = None # L{Datum}, overriden

48 _h = Height(h=0) # height (C{meter})

49 _H = NN # height prefix (C{str}), '↑' in JS version

50

51 def __init__(self, x_xyz, y=None, z=None, h=0, ll=None, datum=None, name=NN):

52 '''New n-vector normal to the earth's surface.

53

54 @arg x_xyz: X component of vector (C{scalar}) or (3-D) vector

55 (C{Nvector}, L{Vector3d}, L{Vector3Tuple} or

56 L{Vector4Tuple}).

57 @kwarg y: Y component of vector (C{scalar}), ignored if B{C{x_xyz}}

58 is not C{scalar}, otherwise same units as B{C{x_xyz}}.

59 @kwarg z: Z component of vector (C{scalar}), ignored if B{C{x_xyz}}

60 is not C{scalar}, otherwise same units as B{C{x_xyz}}.

61 @kwarg h: Optional height above surface (C{meter}).

62 @kwarg ll: Optional, original latlon (C{LatLon}).

63 @kwarg datum: Optional, I{pass-thru} datum (L{Datum}).

64 @kwarg name: Optional name (C{str}).

65

66 @raise TypeError: Non-scalar B{C{x}}, B{C{y}} or B{C{z}}

67 coordinate or B{C{x}} not an C{Nvector},

68 L{Vector3Tuple} or L{Vector4Tuple} or

69 invalid B{C{datum}}.

70

71 @example:

72

73 >>> from pygeodesy.sphericalNvector import Nvector

74 >>> v = Nvector(0.5, 0.5, 0.7071, 1)

75 >>> v.toLatLon() # 45.0°N, 045.0°E, +1.00m

76 '''

77 h, d, n = _xyzhdn3(x_xyz, h, datum, ll)

78 Vector3d.__init__(self, x_xyz, y=y, z=z, ll=ll, name=name or n)

79 if h:

80 self.h = h

81 if d is not None:

82 self._datum = _spherical_datum(d, name=self.name) # pass-thru

83

84 @Property_RO

85 def datum(self):

86 '''Get the I{pass-thru} datum (C{Datum}) or C{None}.

87 '''

88 return self._datum

89

90 @Property_RO

91 def Ecef(self):

92 '''Get the ECEF I{class} (L{EcefKarney}), I{lazily}.

93 '''

94 return _MODS.ecef.EcefKarney # default

95

96 @property_doc_(''' the height above surface (C{meter}).''')

97 def h(self):

98 '''Get the height above surface (C{meter}).

99 '''

100 return self._h

101

102 @h.setter # PYCHOK setter!

103 def h(self, h):

104 '''Set the height above surface (C{meter}).

105

106 @raise TypeError: If B{C{h}} invalid.

107

108 @raise VectorError: If B{C{h}} invalid.

109 '''

110 h = Height(h=h, Error=VectorError)

111 if self._h != h:

112 _update_all(self)

113 self._h = h

114

115 @property_doc_(''' the height prefix (C{str}).''')

116 def H(self):

117 '''Get the height prefix (C{str}).

118 '''

119 return self._H

120

121 @H.setter # PYCHOK setter!

122 def H(self, H):

123 '''Set the height prefix (C{str}).

124 '''

125 self._H = str(H) if H else NN

126

127 def hStr(self, prec=-2, m=NN):

128 '''Return a string for the height B{C{h}}.

129

130 @kwarg prec: Number of (decimal) digits, unstripped (C{int}).

131 @kwarg m: Optional unit of the height (C{str}).

132

133 @see: Function L{pygeodesy.hstr}.

134 '''

135 return NN(self.H, hstr(self.h, prec=prec, m=m))

136

137 @Property_RO

138 def isEllipsoidal(self):

139 '''Check whether this n-vector is ellipsoidal (C{bool} or C{None} if unknown).

140 '''

141 return self.datum.isEllipsoidal if self.datum else None

142

143 @Property_RO

144 def isSpherical(self):

145 '''Check whether this n-vector is spherical (C{bool} or C{None} if unknown).

146 '''

147 return self.datum.isSpherical if self.datum else None

148

149 @Property_RO

150 def lam(self):

151 '''Get the (geodetic) longitude in C{radians} (C{float}).

152 '''

153 return self.philam.lam

154

155 @Property_RO

156 def lat(self):

157 '''Get the (geodetic) latitude in C{degrees} (C{float}).

158 '''

159 return self.latlon.lat

160

161 @Property_RO

162 def latlon(self):

163 '''Get the (geodetic) lat-, longitude in C{degrees} (L{LatLon2Tuple}C{(lat, lon)}).

164 '''

165 return n_xyz2latlon(self.x, self.y, self.z, name=self.name)

166

167 @Property_RO

168 def latlonheight(self):

169 '''Get the (geodetic) lat-, longitude in C{degrees} and height (L{LatLon3Tuple}C{(lat, lon, height)}).

170 '''

171 return self.latlon.to3Tuple(self.h)

172

173 @Property_RO

174 def latlonheightdatum(self):

175 '''Get the lat-, longitude in C{degrees} with height and datum (L{LatLon4Tuple}C{(lat, lon, height, datum)}).

176 '''

177 return self.latlonheight.to4Tuple(self.datum)

178

179 @Property_RO

180 def lon(self):

181 '''Get the (geodetic) longitude in C{degrees} (C{float}).

182 '''

183 return self.latlon.lon

184

185 @Property_RO

186 def phi(self):

187 '''Get the (geodetic) latitude in C{radians} (C{float}).

188 '''

189 return self.philam.phi

190

191 @Property_RO

192 def philam(self):

193 '''Get the (geodetic) lat-, longitude in C{radians} (L{PhiLam2Tuple}C{(phi, lam)}).

194 '''

195 return n_xyz2philam(self.x, self.y, self.z, name=self.name)

196

197 @Property_RO

198 def philamheight(self):

199 '''Get the (geodetic) lat-, longitude in C{radians} and height (L{PhiLam3Tuple}C{(phi, lam, height)}).

200 '''

201 return self.philam.to3Tuple(self.h)

202

203 @Property_RO

204 def philamheightdatum(self):

205 '''Get the lat-, longitude in C{radians} with height and datum (L{PhiLam4Tuple}C{(phi, lam, height, datum)}).

206 '''

207 return self.philamheight.to4Tuple(self.datum)

208

209 @deprecated_method

210 def to2ab(self): # PYCHOK no cover

211 '''DEPRECATED, use property L{philam}.

212

213 @return: A L{PhiLam2Tuple}C{(phi, lam)}.

214 '''

215 return self.philam

216

217 @deprecated_method

218 def to3abh(self, height=None): # PYCHOK no cover

219 '''DEPRECATED, use property L{philamheight} or C{philam.to3Tuple(B{height})}.

220

221 @kwarg height: Optional height, overriding this

222 n-vector's height (C{meter}).

223

224 @return: A L{PhiLam3Tuple}C{(phi, lam, height)}.

225

226 @raise ValueError: Invalid B{C{height}}.

227 '''

228 return self.philamheight if height in (None, self.h) else \

229 self.philam.to3Tuple(height)

230

231 def toCartesian(self, h=None, Cartesian=None, datum=None, **Cartesian_kwds):

232 '''Convert this n-vector to C{Nvector}-based cartesian (ECEF) coordinates.

233

234 @kwarg h: Optional height, overriding this n-vector's height (C{meter}).

235 @kwarg Cartesian: Optional class to return the (ECEF) coordinates

236 (C{Cartesian}).

237 @kwarg datum: Optional datum (C{Datum}), overriding this datum.

238 @kwarg Cartesian_kwds: Optional, additional B{C{Cartesian}} keyword

239 arguments, ignored if C{B{Cartesian} is None}.

240

241 @return: The cartesian (ECEF) coordinates (B{C{Cartesian}}) or

242 if C{B{Cartesian} is None}, an L{Ecef9Tuple}C{(x, y, z,

243 lat, lon, height, C, M, datum)} with C{C} and C{M} if

244 available.

245

246 @raise TypeError: Invalid B{C{Cartesian}} or B{C{Cartesian_kwds}}

247 argument.

248

249 @raise ValueError: Invalid B{C{h}}.

250

251 @example:

252

253 >>> v = Nvector(0.5, 0.5, 0.7071)

254 >>> c = v.toCartesian() # [3194434, 3194434, 4487327]

255 >>> p = c.toLatLon() # 45.0°N, 45.0°E

256 '''

257 d = _spherical_datum(datum or self.datum, name=self.name)

258 E = d.ellipsoid

259 h = self.h if h is None else Height(h=h)

260

261 x, y, z = self.x, self.y, self.z

262 # Kenneth Gade eqn 22

263 n = E.b / hypot_(x * E.a_b, y * E.a_b, z)

264 r = h + n * E.a2_b2

265

266 x *= r

267 y *= r

268 z *= h + n

269

270 if Cartesian is None:

271 r = self.Ecef(d).reverse(x, y, z, M=True)

272 else:

273 kwds = _xkwds(Cartesian_kwds, datum=d) # h=0

274 r = Cartesian(x, y, z, **kwds)

275 return self._xnamed(r)

276

277 @deprecated_method

278 def to2ll(self): # PYCHOK no cover

279 '''DEPRECATED, use property L{latlon}.

280

281 @return: A L{LatLon2Tuple}C{(lat, lon)}.

282 '''

283 return self.latlon

284

285 @deprecated_method

286 def to3llh(self, height=None): # PYCHOK no cover

287 '''DEPRECATED, use property C{latlonheight} or C{latlon.to3Tuple(B{height})}.

288

289 @kwarg height: Optional height, overriding this

290 n-vector's height (C{meter}).

291

292 @return: A L{LatLon3Tuple}C{(lat, lon, height)}.

293

294 @raise ValueError: Invalid B{C{height}}.

295 '''

296 return self.latlonheight if height in (None, self.h) else \

297 self.latlon.to3Tuple(height)

298

299 def toLatLon(self, height=None, LatLon=None, datum=None, **LatLon_kwds):

300 '''Convert this n-vector to an C{Nvector}-based geodetic point.

301

302 @kwarg height: Optional height, overriding this n-vector's

303 height (C{meter}).

304 @kwarg LatLon: Optional class to return the geodetic point

305 (C{LatLon}) or C{None}.

306 @kwarg datum: Optional, spherical datum (C{Datum}).

307 @kwarg LatLon_kwds: Optional, additional B{C{LatLon}} keyword

308 arguments, ignored if C{B{LatLon} is None}.

309

310 @return: The geodetic point (C{LatLon}) or if C{B{LatLon} is None},

311 an L{Ecef9Tuple}C{(x, y, z, lat, lon, height, C, M,

312 datum)} with C{C} and C{M} if available.

313

314 @raise TypeError: Invalid B{C{LatLon}} or B{C{LatLon_kwds}}

315 argument.

316

317 @raise ValueError: Invalid B{C{height}}.

318

319 @example:

320

321 >>> v = Nvector(0.5, 0.5, 0.7071)

322 >>> p = v.toLatLon() # 45.0°N, 45.0°E

323 '''

324 d = _spherical_datum(datum or self.datum, name=self.name)

325 h = self.h if height is None else Height(height)

326 # use self.Cartesian(Cartesian=None) for better accuracy of the height

327 # than self.Ecef(d).forward(self.lat, self.lon, height=h, M=True)

328 if LatLon is None:

329 r = self.toCartesian(h=h, Cartesian=None, datum=d)

330 else:

331 kwds = _xkwds(LatLon_kwds, height=h, datum=d)

332 r = self._xnamed(LatLon(self.lat, self.lon, **kwds))

333 return r

334

335 def toStr(self, prec=5, fmt=Fmt.PAREN, sep=_COMMASPACE_): # PYCHOK expected

336 '''Return a string representation of this n-vector.

337

338 Height component is only included if non-zero.

339

340 @kwarg prec: Number of (decimal) digits, unstripped (C{int}).

341 @kwarg fmt: Enclosing backets format (C{str}).

342 @kwarg sep: Optional separator between components (C{str}).

343

344 @return: Comma-separated C{"(x, y, z [, h])"} enclosed in

345 B{C{fmt}} brackets (C{str}).

346

347 @example:

348

349 >>> Nvector(0.5, 0.5, 0.7071).toStr() # (0.5, 0.5, 0.7071)

350 >>> Nvector(0.5, 0.5, 0.7071, 1).toStr(-3) # (0.500, 0.500, 0.707, +1.00)

351 '''

352 t = Vector3d.toStr(self, prec=prec, fmt=NN, sep=sep)

353 if self.h:

354 t = sep.join((t, self.hStr()))

355 return (fmt % (t,)) if fmt else t

356

357 def toVector3d(self, norm=True):

358 '''Convert this n-vector to a 3-D vector, I{ignoring

359 the height}.

360

361 @kwarg norm: Normalize the 3-D vector (C{bool}).

362

363 @return: The (normalized) vector (L{Vector3d}).

364 '''

365 v = Vector3d.unit(self) if norm else self

366 return Vector3d(v.x, v.y, v.z, name=self.name)

367

368 @deprecated_method

369 def to4xyzh(self, h=None): # PYCHOK no cover

370 '''DEPRECATED, use property L{xyzh} or C{xyz.to4Tuple(B{h})}.

371 '''

372 return self.xyzh if h in (None, self.h) else Vector4Tuple(

373 self.x, self.y, self.z, h, name=self.name)

374

375 def unit(self, ll=None):

376 '''Normalize this n-vector to unit length.

377

378 @kwarg ll: Optional, original latlon (C{LatLon}).

379

380 @return: Normalized vector (C{Nvector}).

381 '''

382 return _xattrs(Vector3d.unit(self, ll=ll), _UNDER(_h_))

383

384 @Property_RO

385 def xyzh(self):

386 '''Get this n-vector's components (L{Vector4Tuple}C{(x, y, z, h)})

387 '''

388 return self.xyz.to4Tuple(self.h)

389

390

391 NorthPole = NvectorBase(0, 0, +1, name=_NorthPole_) # North pole (C{Nvector})

392 SouthPole = NvectorBase(0, 0, -1, name=_SouthPole_) # South pole (C{Nvector})

393

394

395 class _N_vector_(NvectorBase):

396 '''(INTERNAL) Minimal, low-overhead C{n-vector}.

397 '''

398 def __init__(self, x, y, z, h=0, name=NN):

399 self._x, self._y, self._z = x, y, z

400 if h:

401 self._h = h

402 if name:

403 self.name = name

404

405

406 class LatLonNvectorBase(LatLonBase):

407 '''(INTERNAL) Base class for n-vector-based ellipsoidal

408 and spherical C{LatLon} classes.

409 '''

410

411 def _update(self, updated, *attrs, **setters): # PYCHOK _Nv=None

412 '''(INTERNAL) Zap cached attributes if updated.

413

414 @see: C{ellipsoidalNvector.LatLon} and C{sphericalNvector.LatLon}

415 for the special case of B{C{_Nv}}.

416 '''

417 if updated:

418 _Nv = _xkwds_pop(setters, _Nv=None)

419 if _Nv is not None:

420 if _Nv._fromll is not None:

421 _Nv._fromll = None

422 self._Nv = None

423 LatLonBase._update(self, updated, *attrs, **setters)

424

425# def distanceTo(self, other, **kwds): # PYCHOK no cover

426# '''(INTERNAL) I{Must be overloaded}, see function C{notOverloaded}.

427# '''

428# _MODS.named.notOverloaded(self, other, **kwds)

429

430 def intersections2(self, radius1, other, radius2, **kwds): # PYCHOK expected

431 '''B{Not implemented}, throws a C{NotImplementedError} always.

432 '''

433 notImplemented(self, radius1, other, radius2, **kwds)

434

435 def others(self, *other, **name_other_up):

436 '''Refined class comparison.

437

438 @arg other: The other instance (C{LatLonNvectorBase}).

439 @kwarg name_other_up: Overriding C{name=other} and C{up=1}

440 keyword arguments.

441

442 @return: The B{C{other}} if compatible.

443

444 @raise TypeError: Incompatible B{C{other}} C{type}.

445 '''

446 if other:

447 other0 = other[0]

448 if isinstance(other0, (self.__class__, LatLonNvectorBase)): # XXX NvectorBase?

449 return other0

450

451 other, name, up = _xother3(self, other, **name_other_up)

452 if not isinstance(other, (self.__class__, LatLonNvectorBase)): # XXX NvectorBase?

453 LatLonBase.others(self, other, name=name, up=up + 1)

454 return other

455

456 def toNvector(self, Nvector=NvectorBase, **Nvector_kwds): # PYCHOK signature

457 '''Convert this point to C{Nvector} components, I{including height}.

458

459 @kwarg Nvector_kwds: Optional, additional B{C{Nvector}} keyword

460 arguments, ignored if C{B{Nvector} is None}.

461

462 @return: An B{C{Nvector}} or a L{Vector4Tuple}C{(x, y, z, h)} if

463 B{C{Nvector}} is C{None}.

464

465 @raise TypeError: Invalid B{C{Nvector}} or B{C{Nvector_kwds}}

466 argument.

467 '''

468 return LatLonBase.toNvector(self, Nvector=Nvector, **Nvector_kwds)

469

470 def triangulate(self, bearing1, other, bearing2, height=None, wrap=False):

471 '''Locate a point given this and an other point and a bearing

472 at this and the other point.

473

474 @arg bearing1: Bearing at this point (compass C{degrees360}).

475 @arg other: The other point (C{LatLon}).

476 @arg bearing2: Bearing at the other point (compass C{degrees360}).

477 @kwarg height: Optional height at the triangulated point,

478 overriding the mean height (C{meter}).

479 @kwarg wrap: If C{True}, use this and the B{C{other}} point

480 I{normalized} (C{bool}).

481

482 @return: Triangulated point (C{LatLon}).

483

484 @raise TypeError: Invalid B{C{other}} point.

485

486 @raise Valuerror: Points coincide.

487

488 @example:

489

490 >>> p = LatLon("47°18.228'N","002°34.326'W") # Basse Castouillet

491 >>> q = LatLon("47°18.664'N","002°31.717'W") # Basse Hergo

492 >>> t = p.triangulate(7, q, 295) # 47.323667°N, 002.568501°W'

493 '''

494 return _triangulate(self, bearing1, self.others(other), bearing2,

495 height=height, wrap=wrap, LatLon=self.classof)

496

497 def trilaterate(self, distance1, point2, distance2, point3, distance3,

498 radius=R_M, height=None, useZ=False, wrap=False):

499 '''Locate a point at given distances from this and two other points.

500

501 @arg distance1: Distance to this point (C{meter}, same units

502 as B{C{radius}}).

503 @arg point2: Second reference point (C{LatLon}).

504 @arg distance2: Distance to point2 (C{meter}, same units as

505 B{C{radius}}).

506 @arg point3: Third reference point (C{LatLon}).

507 @arg distance3: Distance to point3 (C{meter}, same units as

508 B{C{radius}}).

509 @kwarg radius: Mean earth radius (C{meter}).

510 @kwarg height: Optional height at trilaterated point, overriding

511 the mean height (C{meter}, same units as B{C{radius}}).

512 @kwarg useZ: Include Z component iff non-NaN, non-zero (C{bool}).

513 @kwarg wrap: If C{True}, use this, B{C{point2}} and B{C{point3}}

514 I{normalized} (C{bool}).

515

516 @return: Trilaterated point (C{LatLon}).

517

518 @raise IntersectionError: No intersection, trilateration failed.

519

520 @raise TypeError: Invalid B{C{point2}} or B{C{point3}}.

521

522 @raise ValueError: Some B{C{points}} coincide or invalid B{C{distance1}},

523 B{C{distance2}}, B{C{distance3}} or B{C{radius}}.

524

525 @see: U{Trilateration<https://WikiPedia.org/wiki/Trilateration>},

526 Veness' JavaScript U{Trilateration<https://www.Movable-Type.co.UK/

527 scripts/latlong-vectors.html>} and method C{LatLon.trilaterate2}

528 of other, non-C{Nvector LatLon} classes.

529 '''

530 return _trilaterate(self, distance1, self.others(point2=point2), distance2,

531 self.others(point3=point3), distance3,

532 radius=radius, height=height, useZ=useZ,

533 wrap=wrap, LatLon=self.classof)

534

535 def trilaterate5(self, distance1, point2, distance2, point3, distance3, # PYCHOK signature

536 area=False, eps=EPS1, radius=R_M, wrap=False):

537 '''B{Not implemented} for C{B{area}=True} and falls back to method

538 C{trilaterate} otherwise.

539

540 @return: A L{Trilaterate5Tuple}C{(min, minPoint, max, maxPoint, n)}

541 with a single trilaterated intersection C{minPoint I{is}

542 maxPoint}, C{min I{is} max} the nearest intersection

543 margin and count C{n = 1}.

544

545 @raise NotImplementedError: Keyword argument C{B{area}=True} not

546 (yet) supported.

547

548 @see: Method L{trilaterate} for other and more details.

549 '''

550 if area:

551 notImplemented(self, area=area)

552

553 t = _trilaterate(self, distance1, self.others(point2=point2), distance2,

554 self.others(point3=point3), distance3,

555 radius=radius, useZ=True, wrap=wrap,

556 LatLon=self.classof)

557 # ... and handle B{C{eps}} and C{IntersectionError}

558 # like function C{.latlonBase._trilaterate5}

559 d = self.distanceTo(t, radius=radius, wrap=wrap) # PYCHOK distanceTo

560 d = min(fabs(distance1 - d), fabs(distance2 - d), fabs(distance3 - d))

561 if d < eps: # min is max, minPoint is maxPoint

562 return Trilaterate5Tuple(d, t, d, t, 1) # n = 1

563 t = _SPACE_(_no_(_intersection_), Fmt.PAREN(min.__name__, Fmt.f(d, prec=3)))

564 raise IntersectionError(area=area, eps=eps, radius=radius, wrap=wrap, txt=t)

565

566

567 def _nsumOf(nvs, h_None, Vector, Vector_kwds): # .sphericalNvector, .vector3d

568 '''(INTERNAL) Separated to allow callers to embellish exceptions.

569 '''

570 X, Y, Z, n = Fsum(), Fsum(), Fsum(), 0

571 H = Fsum() if h_None is None else n

572 for n, v in enumerate(nvs or ()): # one pass

573 X += v.x

574 Y += v.y

575 Z += v.z

576 H += v.h

577 if n < 1:

578 raise ValueError(_SPACE_(Fmt.PARENSPACED(len=n), _insufficient_))

579

580 x, y, z = map1(float, X, Y, Z)

581 h = H.fover(n) if h_None is None else h_None

582 return Vector3Tuple(x, y, z).to4Tuple(h) if Vector is None else \

583 Vector(x, y, z, **_xkwds(Vector_kwds, h=h))

584

585

586 def sumOf(nvectors, Vector=None, h=None, **Vector_kwds):

587 '''Return the I{vectorial} sum of two or more n-vectors.

588

589 @arg nvectors: Vectors to be added (C{Nvector}[]).

590 @kwarg Vector: Optional class for the vectorial sum (C{Nvector})

591 or C{None}.

592 @kwarg h: Optional height, overriding the mean height (C{meter}).

593 @kwarg Vector_kwds: Optional, additional B{C{Vector}} keyword

594 arguments, ignored if C{B{Vector} is None}.

595

596 @return: Vectorial sum (B{C{Vector}}) or a L{Vector4Tuple}C{(x, y,

597 z, h)} if B{C{Vector}} is C{None}.

598

599 @raise VectorError: No B{C{nvectors}}.

600 '''

601 try:

602 return _nsumOf(nvectors, h, Vector, Vector_kwds)

603 except (TypeError, ValueError) as x:

604 raise VectorError(nvectors=nvectors, Vector=Vector, cause=x)

605

606

607 def _triangulate(point1, bearing1, point2, bearing2, height=None,

608 wrap=False, **LatLon_and_kwds):

609 # (INTERNAL) Locate a point given two known points and initial

610 # bearings from those points, see C{LatLon.triangulate} above

611

612 def _gc(p, b, _i_):

613 n = p.toNvector()

614 de = NorthPole.cross(n, raiser=_pole_).unit() # east vector @ n

615 dn = n.cross(de) # north vector @ n

616 s, c = sincos2d(Bearing(b, name=_bearing_ + _i_))

617 dest = de.times(s)

618 dnct = dn.times(c)

619 d = dnct.plus(dest) # direction vector @ n

620 return n.cross(d) # great circle point + bearing

621

622 if wrap:

623 point2 = _unrollon(point1, point2, wrap=wrap)

624 if _isequalTo(point1, point2, eps=EPS):

625 raise _ValueError(points=point2, wrap=wrap, txt=_coincident_)

626

627 gc1 = _gc(point1, bearing1, _1_) # great circle p1 + b1

628 gc2 = _gc(point2, bearing2, _2_) # great circle p2 + b2

629

630 n = gc1.cross(gc2, raiser=_point_) # n-vector of intersection point

631 h = point1._havg(point2, h=height)

632 kwds = _xkwds(LatLon_and_kwds, height=h)

633 return n.toLatLon(**kwds) # Nvector(n.x, n.y, n.z).toLatLon(...)

634

635

636 def _trilaterate(point1, distance1, point2, distance2, point3, distance3,

637 radius=R_M, height=None, useZ=False,

638 wrap=False, **LatLon_and_kwds):

639 # (INTERNAL) Locate a point at given distances from

640 # three other points, see LatLon.triangulate above

641

642 def _nr2(p, d, r, _i_, *qs): # .toNvector and angular distance squared

643 for q in qs:

644 if _isequalTo(p, q, eps=EPS):

645 raise _ValueError(points=p, txt=_coincident_)

646 return p.toNvector(), (Scalar(d, name=_distance_ + _i_) / r)**2

647

648 p1, r = point1, Radius_(radius)

649 p2, p3, _ = _unrollon3(p1, point2, point3, wrap)

650

651 n1, r12 = _nr2(p1, distance1, r, _1_)

652 n2, r22 = _nr2(p2, distance2, r, _2_, p1)

653 n3, r32 = _nr2(p3, distance3, r, _3_, p1, p2)

654

655 # the following uses x,y coordinate system with origin at n1, x axis n1->n2

656 y = n3.minus(n1)

657 x = n2.minus(n1)

658 z = None

659

660 d = x.length # distance n1->n2

661 if d > EPS_2: # and y.length > EPS_2:

662 X = x.unit() # unit vector in x direction n1->n2

663 i = X.dot(y) # signed magnitude of x component of n1->n3

664 Y = y.minus(X.times(i)).unit() # unit vector in y direction

665 j = Y.dot(y) # signed magnitude of y component of n1->n3

666 if fabs(j) > EPS_2:

667 # courtesy of U{Carlos Freitas<https://GitHub.com/mrJean1/PyGeodesy/issues/33>}

668 x = fsumf_(r12, -r22, d**2) / (d * _2_0) # n1->intersection x- and ...

669 y = fsumf_(r12, -r32, i**2, j**2, x * i * _N_2_0) / (j * _2_0) # ... y-component

670 # courtesy of U{AleixDev<https://GitHub.com/mrJean1/PyGeodesy/issues/43>}

671 z = fsumf_(max(r12, r22, r32), -(x**2), -(y**2)) # XXX not just r12!

672 if z > EPS:

673 n = n1.plus(X.times(x)).plus(Y.times(y))

674 if useZ: # include Z component

675 Z = X.cross(Y) # unit vector perpendicular to plane

676 n = n.plus(Z.times(sqrt(z)))

677 if height is None:

678 h = fidw((point1.height, point2.height, point3.height),

679 map1(fabs, distance1, distance2, distance3))

680 else:

681 h = Height(height)

682 kwds = _xkwds(LatLon_and_kwds, height=h)

683 return n.toLatLon(**kwds) # Nvector(n.x, n.y, n.z).toLatLon(...)

684

685 # no intersection, d < EPS_2 or fabs(j) < EPS_2 or z < EPS

686 t = _SPACE_(_no_, _intersection_, NN)

687 raise IntersectionError(point1=point1, distance1=distance1,

688 point2=point2, distance2=distance2,

689 point3=point3, distance3=distance3,

690 txt=unstr(t, z=z, useZ=useZ, wrap=wrap))

691

692

693__all__ += _ALL_DOCS(LatLonNvectorBase, NvectorBase, sumOf) # classes

694

695# **) MIT License

696#

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

698#

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

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

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

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

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

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

705#

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

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

708#

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

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

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

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

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

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

715# OTHER DEALINGS IN THE SOFTWARE.