Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

 

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

 

u'''Utilities for point lists, tuples, etc. 

 

Functions to handle collections and sequences of C{LatLon} points 

specified as 2-d U{NumPy<https://www.NumPy.org>}, C{arrays} or tuples 

as C{LatLon} or as C{pseudo-x/-y} pairs. 

 

C{NumPy} arrays are assumed to contain rows of points with a lat-, a 

longitude -and possibly other- values in different columns. While 

iterating over the array rows, create an instance of a given C{LatLon} 

class "on-the-fly" for each row with the row's lat- and longitude. 

 

The original C{NumPy} array is read-accessed only and never duplicated, 

except to return a I{subset} of the original array. 

 

For example, to process a C{NumPy} array, wrap the array by instantiating 

class L{Numpy2LatLon} and specifying the column index for the lat- and 

longitude in each row. Then, pass the L{Numpy2LatLon} instance to any 

L{pygeodesy} function or method accepting a I{points} argument. 

 

Similarly, class L{Tuple2LatLon} is used to instantiate a C{LatLon} from 

each 2+tuple in a sequence of such 2+tuples using the C{ilat} lat- and 

C{ilon} longitude index in each 2+tuple. 

''' 

 

from pygeodesy.basics import isclass, isint, isnear0, isnear1, isscalar, \ 

issequence, issubclassof, map1, _Sequence, \ 

_umod_360, _xcopy, _xdup, _xinstanceof 

from pygeodesy.datums import _spherical_datum 

from pygeodesy.dms import F_D, latDMS, lonDMS, parseDMS2, S_DEG, S_MIN, S_SEC 

from pygeodesy.errors import CrossError, crosserrors, _IndexError, \ 

_IsnotError, _TypeError, _ValueError, \ 

_xkwds, _xkwds_pop 

from pygeodesy.fmath import favg, fdot, Fsum, fsum, hypot 

# from pygeodesy.fsums import Fsum, fsum # from .fmath 

from pygeodesy.formy import _bearingTo2, equirectangular_, latlon2n_xyz 

from pygeodesy.interns import EPS, EPS1, NN, PI_2, R_M, \ 

_colinear_, _COMMASPACE_, _DEQUALSPACED_, \ 

_ELLIPSIS_, _height_, _immutable_, _lat_, \ 

_lon_, _near_, _not_, _point_, _SPACE_, \ 

_UNDER_, _valid_, _0_0, _0_5, _1_0, _3_0, \ 

_90_0, _N_90_0, _180_0, _360_0 

from pygeodesy.iters import LatLon2PsxyIter, PointsIter, points2 

from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS 

from pygeodesy.named import classname, nameof, notImplemented, notOverloaded, \ 

_NamedTuple, _xnamed, _xother3, _xotherError 

from pygeodesy.namedTuples import Bounds2Tuple, Bounds4Tuple, \ 

LatLon2Tuple, NearestOn3Tuple, \ 

NearestOn5Tuple, PhiLam2Tuple, \ 

Point3Tuple, Vector3Tuple, Vector4Tuple 

from pygeodesy.nvectorBase import NvectorBase, _N_vector_ 

from pygeodesy.props import deprecated_method, Property_RO, property_doc_, \ 

property_RO 

from pygeodesy.streprs import Fmt, hstr, instr, pairs 

from pygeodesy.units import Number_, Radius, Scalar, Scalar_ 

from pygeodesy.utily import atan2b, degrees90, degrees180, degrees2m, \ 

unroll180, unrollPI, wrap90, wrap180 

 

from math import cos, fmod, radians, sin 

 

__all__ = _ALL_LAZY.points 

__version__ = '22.04.28' 

 

_fin_ = 'fin' 

_ilat_ = 'ilat' 

_ilon_ = 'ilon' 

_ncols_ = 'ncols' 

_nrows_ = 'nrows' 

 

 

class LatLon_(object): # XXX in heights._HeightBase.height 

'''Low-overhead C{LatLon} class for L{Numpy2LatLon} and L{Tuple2LatLon}. 

''' 

# __slots__ efficiency is voided if the __slots__ class attribute 

# is used in a subclass of a class with the traditional __dict__, 

# see <https://docs.Python.org/2/reference/datamodel.html#slots> 

# and __slots__ must be repeated in sub-classes, see "Problems 

# with __slots__" in Luciano Ramalho, "Fluent Python", page 

# 276+, O'Reilly, 2016, also at <https://Books.Google.ie/ 

# books?id=bIZHCgAAQBAJ&lpg=PP1&dq=fluent%20python&pg= 

# PT364#v=onepage&q=“Problems%20with%20__slots__”&f=false> 

# 

# __slots__ = (_lat_, _lon_, _height_, _datum_, _name_) 

# Property_RO = property_RO # no __dict__ with __slots__! 

# 

# However, sys.getsizeof(LatLon_(1, 2)) is 72-88 with __slots__ 

# but only 48-64 bytes without in Python 2.7.18+ and Python 3+. 

 

def __init__(self, lat, lon, name=NN, height=0, datum=None): 

'''Creat a new, mininal, low-overhead L{LatLon_} instance, 

without height and datum. 

 

@arg lat: Latitude (C{degrees}). 

@arg lon: Longitude (C{degrees}). 

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

@kwarg height: Optional height (C{float} or C{int}). 

@kwarg datum: Optional datum (L{Datum}, L{Ellipsoid}, 

L{Ellipsoid2}, L{a_f2Tuple} or I{scalar} 

radius) or C{None}. 

 

@raise TypeError: Invalid B{C{datum}}. 

 

@note: The lat- and longitude are taken as-given, 

un-clipped and un-validated . 

''' 

try: # most common use case 

self.lat, self.lon = float(lat), float(lon) # Lat(lat), Lon(lon) 

except (TypeError, ValueError): 

self.lat, self.lon = parseDMS2(lat, lon, clipLat=0, clipLon=0) # PYCHOK LatLon2Tuple 

self.name = str(name) if name else NN 

self.height = height 

self.datum = datum if datum is None else \ 

_spherical_datum(datum, name=self.name) 

 

def __eq__(self, other): 

return isinstance(other, LatLon_) and \ 

other.lat == self.lat and \ 

other.lon == self.lon 

 

def __ne__(self, other): 

return not self.__eq__(other) 

 

def __repr__(self): 

return self.toRepr() 

 

def __str__(self): 

return self.toStr() 

 

def classof(self, *args, **kwds): 

'''Instantiate this very class. 

 

@arg args: Optional, positional arguments. 

@kwarg kwds: Optional, keyword arguments. 

 

@return: New instance (C{self.__class__}). 

''' 

return _xnamed(self.__class__(*args, **kwds), self.name) 

 

def copy(self, deep=False): 

'''Make a shallow or deep copy of this instance. 

 

@kwarg deep: If C{True} make a deep, otherwise a 

shallow copy (C{bool}). 

 

@return: The copy (C{This} (sub-)class). 

''' 

return _xcopy(self, deep=deep) 

 

def dup(self, **items): 

'''Duplicate this instance, replacing some items. 

 

@kwarg items: Attributes to be changed (C{any}). 

 

@return: The duplicate (C{This} (sub-)class). 

 

@raise AttributeError: Some B{C{items}} invalid. 

''' 

return _xdup(self, **items) 

 

def heightStr(self, prec=-2): 

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

 

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

 

@see: Function L{pygeodesy.hstr}. 

''' 

return hstr(self.height, prec=prec) 

 

def intermediateTo(self, other, fraction, height=None, wrap=False): 

'''Locate the point at a given fraction between (or along) this 

and an other point. 

 

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

@arg fraction: Fraction between both points (C{float}, 

0.0 for this and 1.0 for the other point). 

@kwarg height: Optional height (C{meter}), overriding the 

intermediate height. 

@kwarg wrap: Wrap and unroll longitudes (C{bool}). 

 

@return: Intermediate point (this C{LatLon}). 

 

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

''' 

f = Scalar(fraction=fraction) 

if isnear0(f): 

r = self 

elif isnear1(f) and not wrap: 

r = self.others(other) 

else: 

r = self.others(other) 

h = favg(self.height, r.height, f=f) if height is None else height 

_, lon = unroll180(self.lon, r.lon, wrap=wrap) 

r = self.classof(favg(self.lat, r.lat, f=f), 

favg(self.lon, lon, f=f), 

height=h, datum=self.datum, 

name=self.intermediateTo.__name__) 

return r 

 

@Property_RO # PYCHOK no cover 

def isEllipsoidal(self): 

'''Check whether this point is ellipsoidal (C{bool} or C{None} if unknown). 

''' 

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

 

@Property_RO # PYCHOK no cover 

def isEllipsoidalLatLon(self): 

'''Get C{LatLon} base. 

''' 

return False 

 

def isequalTo(self, other, eps=None): 

'''Compare this point with an other point, I{ignoring} height. 

 

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

@kwarg eps: Tolerance for equality (C{degrees}). 

 

@return: C{True} if both points are identical, 

I{ignoring} height, C{False} otherwise. 

 

@raise UnitError: Invalid B{C{eps}}. 

''' 

self.others(other) 

 

if eps: 

return max(abs(self.lat - other.lat), 

abs(self.lon - other.lon)) < Scalar_(eps=eps) 

else: 

return self.lat == other.lat and \ 

self.lon == other.lon 

 

@Property_RO 

def isSpherical(self): # PYCHOK no cover 

'''Check whether this point is spherical (C{bool} or C{None} if unknown). 

''' 

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

 

@Property_RO 

def latlon(self): 

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

''' 

return LatLon2Tuple(self.lat, self.lon, name=self.name) 

 

@Property_RO 

def latlonheight(self): 

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

''' 

return self.latlon.to3Tuple(self.height) 

 

@Property_RO 

def _N_vector(self): 

'''(INTERNAL) Get the minimal, low-overhead (C{nvectorBase._N_vector_}) 

''' 

return _N_vector_(*latlon2n_xyz(self.lat, self.lon), 

h=self.height, name=self.name) 

 

def others(self, *other, **name_other_up): # see .named._namedBase.others 

'''Refined class comparison. 

 

@arg other: The other instance (any C{type}). 

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

keyword arguments. 

 

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

 

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

''' 

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

if isinstance(other, self.__class__) or (hasattr(other, _lat_) 

and hasattr(other, _lon_)): 

return other 

raise _xotherError(self, other, name=name, up=up + 1) 

 

@Property_RO 

def philam(self): 

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

''' 

return PhiLam2Tuple(radians(self.lat), radians(self.lon), name=self.name) 

 

@Property_RO 

def philamheight(self): 

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

''' 

return self.philam.to3Tuple(self.height) 

 

@deprecated_method 

def points(self, points, closed=False, base=None): # PYCHOK no cover 

'''DEPRECATED, use method C{points2}.''' 

return points2(points, closed=closed, base=base) 

 

def points2(self, points, closed=False, base=None): 

'''Check a path or polygon represented by points. 

 

@arg points: The path or polygon points (C{LatLon}[]) 

@kwarg closed: Optionally, consider the polygon closed, 

ignoring any duplicate or closing final 

B{C{points}} (C{bool}). 

@kwarg base: Optionally, check all B{C{points}} against 

this base class, if C{None} don't check. 

 

@return: A L{Points2Tuple}C{(number, points)} with the number 

of points and the points C{list} or C{tuple}. 

 

@raise PointsError: Insufficient number of B{C{points}}. 

 

@raise TypeError: Some B{C{points}} are not B{C{base}}. 

''' 

return points2(points, closed=closed, base=base) 

 

def PointsIter(self, points, loop=0, dedup=False): 

'''Return a points iterator. 

 

@arg points: The path or polygon points (C{LatLon}[]) 

@kwarg loop: Number of loop-back points (non-negative C{int}). 

@kwarg dedup: Skip duplicate points (C{bool}). 

 

@return: A new C{PointsIter} iterator. 

 

@raise PointsError: Insufficient number of B{C{points}}. 

''' 

return PointsIter(points, loop=loop, base=self, dedup=dedup) 

 

@deprecated_method 

def to2ab(self): # PYCHOK no cover 

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

return self.philam 

 

def toNvector(self, h=None, Nvector=NvectorBase, **Nvector_kwds): 

'''Convert this point to C{n-vector} (normal to the earth's 

surface) components, I{including height}. 

 

@kwarg h: Optional height, overriding this point's height 

(C{meter}). 

@kwarg Nvector: Optional class to return the C{n-vector} 

components (C{Nvector}) or C{None}. 

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

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

 

@return: The C{n-vector} components B{C{Nvector}} or if 

B{C{Nvector}} is C{None}, a L{Vector4Tuple}C{(x, 

y, z, h)}. 

 

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

argument. 

''' 

x, y, z = latlon2n_xyz(self.lat, self.lon) 

r = Vector4Tuple(x, y, z, self.height if h is None else h) 

if Nvector is not None: 

r = Nvector(x, y, z, **_xkwds(Nvector_kwds, h=r.h, ll=self)) 

return _xnamed(r, self.name) 

 

def toRepr(self, **kwds): 

'''This L{LatLon_} as a string "class(<degrees>, ...)". 

 

@kwarg kwds: Optional, keyword arguments. 

 

@return: Class instance (C{str}). 

''' 

_ = _xkwds_pop(kwds, std=None) # PYCHOK std unused 

return Fmt.PAREN(classname(self), self.toStr(**kwds)) 

 

def toStr(self, form=F_D, prec=6, sep=_COMMASPACE_, **s_D_M_S_kwds): 

'''This L{LatLon_} as a string "<degrees>, <degrees>". 

 

@kwarg form: Format specifier (C{str} or L{F_D}, L{F_DM}, L{F_DMS}, 

L{F_DEG}, L{F_MIN}, L{F_SEC}, L{F_D60}, L{F__E}, 

L{F__F}, L{F__G}, L{F_RAD}, L{F_D_}, L{F_DM_}, L{F_DMS_}, 

L{F_DEG_}, L{F_MIN_}, L{F_SEC_}, L{F_D60_}, L{F__E_}, 

L{F__F_}, L{F__G_}, L{F_RAD_}, L{F_D__}, L{F_DM__}, 

L{F_DMS__}, L{F_DEG__}, L{F_MIN__}, L{F_SEC__}, L{F_D60__}, 

L{F__E__}, L{F__F__}, L{F__G__} or L{F_RAD__}) 

@kwarg prec: Number of decimal digits (0..9 or C{None} for default). 

Trailing zero decimals are stripped for B{C{prec}} 

values of 1 and above, but kept for negative B{C{prec}}. 

@kwarg sep: Separator between degrees, minutes, seconds and suffix (C{str}). 

@kwarg s_D_M_S: Optional keyword arguments C{B{s_D}=str}, C{B{s_M}=str} 

and/or C{B{s_S}=str} to override the degrees, minutes 

respectively seconds symbol, defaults L{S_DEG}, L{S_MIN} 

respectively L{S_SEC}. 

 

@return: This instance in the specified B{C{form}} (C{str}). 

 

@see: Function L{pygeodesy.degDMS} for B{C{form}} and B{C{s_D_M_S}}. 

''' 

def _split2(s_D=S_DEG, s_M=S_MIN, s_S=S_SEC, **kwds): 

return kwds, dict(s_D=s_D, s_M=s_M, s_S=s_S) 

 

kwds, s_D_M_S = _split2(**s_D_M_S_kwds) 

t = (latDMS(self.lat, form=form, prec=prec, **s_D_M_S), 

lonDMS(self.lon, form=form, prec=prec, **s_D_M_S)) 

if self.height: 

t += (self.heightStr(),) 

if self.name: 

t += (repr(self.name),) 

if kwds: 

t += pairs(kwds, prec=prec) 

return sep.join(t) 

 

@deprecated_method 

def toStr2(self, **kwds): # PYCHOK no cover 

'''DEPRECATED, used method L{toRepr}.''' 

return self.toRepr(**kwds) 

 

 

def _isLatLon(inst): 

'''(INTERNAL) Check a C{LatLon} or C{LatLon_} instance. 

''' 

return isinstance(inst, (LatLon_, _MODS.latlonBase.LatLonBase)) 

 

 

def _isLatLon_(LL): 

'''(INTERNAL) Check a (sub-)class of C{LatLon_}. 

''' 

return issubclassof(LL, LatLon_) or (isclass(LL) and 

all(hasattr(LL, a) for a in _ALL_ATTRS_)) 

 

 

# get all pseudo-slots for class C{LatLon_} 

_ALL_ATTRS_ = tuple(LatLon_(0, 0).__dict__.keys()) 

 

 

class _Basequence(_Sequence): # immutable, on purpose 

'''(INTERNAL) Base class. 

''' 

_array = [] 

_epsilon = EPS 

_itemname = _point_ 

 

def _contains(self, point): 

'''(INTERNAL) Check for a matching point. 

''' 

return any(self._findall(point, ())) 

 

def copy(self, deep=False): # PYCHOK no cover 

'''Make a shallow or deep copy of this instance. 

 

@kwarg deep: If C{True} make a deep, otherwise a 

shallow copy (C{bool}). 

 

@return: The copy (C{This class} or subclass thereof). 

''' 

return _xcopy(self, deep=deep) 

 

def _count(self, point): 

'''(INTERNAL) Count the number of matching points. 

''' 

return sum(1 for _ in self._findall(point, ())) # NOT len()! 

 

def dup(self, **items): # PYCHOK no cover 

'''Duplicate this instance, I{without replacing items}. 

 

@kwarg items: No attributes (I{not allowed}). 

 

@return: The duplicate (C{This} (sub-)class). 

 

@raise TypeError: Any B{C{items}} invalid. 

''' 

if items: 

t = _SPACE_(classname(self), _immutable_) 

raise _TypeError(txt=t, this=self, **items) 

return _xdup(self) 

 

@property_doc_(''' the equality tolerance (C{float}).''') 

def epsilon(self): 

'''Get the tolerance for equality tests (C{float}). 

''' 

return self._epsilon 

 

@epsilon.setter # PYCHOK setter! 

def epsilon(self, tol): 

'''Set the tolerance for equality tests. 

 

@arg tol: New tolerance (C{scalar}). 

 

@raise TypeError: Non-scalar B{C{tol}}. 

 

@raise ValueError: Out-of-bounds B{C{tol}}. 

''' 

self._epsilon = Scalar_(tol, name='tolerance') 

 

def _find(self, point, start_end): 

'''(INTERNAL) Find the first matching point index. 

''' 

for i in self._findall(point, start_end): 

return i 

return -1 

 

def _findall(self, point, start_end): # PYCHOK no cover 

'''(INTERNAL) I{Must be implemented/overloaded}. 

''' 

notImplemented(self, point, start_end) 

 

def _getitem(self, index): 

'''(INTERNAL) Return point [index] or return a slice. 

''' 

# Luciano Ramalho, "Fluent Python", page 290+, O'Reilly, 2016 

if isinstance(index, slice): 

# XXX an numpy.[nd]array slice is a view, not a copy 

return self.__class__(self._array[index], **self._slicekwds()) 

else: 

return self.point(self._array[index]) 

 

def _index(self, point, start_end): 

'''(INTERNAL) Find the first matching point index. 

''' 

for i in self._findall(point, start_end): 

return i 

raise _IndexError(self._itemname, point, txt=_not_('found')) 

 

@property_RO 

def isNumpy2(self): # PYCHOK no cover 

'''Is this a Numpy2 wrapper? 

''' 

return False # isinstance(self, (Numpy2LatLon, ...)) 

 

@property_RO 

def isPoints2(self): # PYCHOK no cover 

'''Is this a LatLon2 wrapper/converter? 

''' 

return False # isinstance(self, (LatLon2psxy, ...)) 

 

@property_RO 

def isTuple2(self): # PYCHOK no cover 

'''Is this a Tuple2 wrapper? 

''' 

return False # isinstance(self, (Tuple2LatLon, ...)) 

 

def _iter(self): 

'''(INTERNAL) Yield all points. 

''' 

_array, point = self._array, self.point 

for i in range(len(self)): 

yield point(_array[i]) 

 

def point(self, *attrs): # PYCHOK no cover 

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

 

@arg attrs: Optional arguments. 

''' 

notOverloaded(self, *attrs) 

 

def _range(self, start=None, end=None, step=1): 

'''(INTERNAL) Return the range. 

''' 

if step > 0: 

if start is None: 

start = 0 

if end is None: 

end = len(self) 

elif step < 0: 

if start is None: 

start = len(self) - 1 

if end is None: 

end = -1 

else: 

raise _ValueError(step=step) 

return range(start, end, step) 

 

def _repr(self): 

'''(INTERNAL) Return a string representation. 

''' 

# XXX use Python 3+ reprlib.repr 

t = repr(self._array[:1]) # only first row 

t = _SPACE_(t[:-1], _ELLIPSIS_, Fmt.SQUARE(t[-1:], len(self))) 

t = _SPACE_.join(t.split()) # coalesce spaces 

return instr(self, t, **self._slicekwds()) 

 

def _reversed(self): # PYCHOK false 

'''(INTERNAL) Yield all points in reverse order. 

''' 

_array, point = self._array, self.point 

for i in range(len(self) - 1, -1, -1): 

yield point(_array[i]) 

 

def _rfind(self, point, start_end): 

'''(INTERNAL) Find the last matching point index. 

''' 

def _r3(start=None, end=None, step=-1): 

return (start, end, step) # PYCHOK returns 

 

for i in self._findall(point, _r3(*start_end)): 

return i 

return -1 

 

def _slicekwds(self): # PYCHOK no cover 

'''(INTERNAL) I{Should be overloaded}. 

''' 

return {} 

 

 

class _Array2LatLon(_Basequence): # immutable, on purpose 

'''(INTERNAL) Base class for Numpy2LatLon or Tuple2LatLon. 

''' 

_array = () 

_ilat = 0 # row column index 

_ilon = 0 # row column index 

_LatLon = LatLon_ # default 

_shape = () 

 

def __init__(self, array, ilat=0, ilon=1, LatLon=None, shape=()): 

'''Handle a C{NumPy} or C{Tuple} array as a sequence of C{LatLon} points. 

''' 

ais = (_ilat_, ilat), (_ilon_, ilon) 

 

if len(shape) != 2 or shape[0] < 1 or shape[1] < len(ais): 

raise _IndexError('array.shape', shape) 

 

self._array = array 

self._shape = Shape2Tuple(shape) # *shape 

 

if LatLon: # check the point class 

if not _isLatLon_(LatLon): 

raise _IsnotError(_valid_, LatLon=LatLon) 

self._LatLon = LatLon 

 

# check the attr indices 

for n, (ai, i) in enumerate(ais): 

if not isint(i): 

raise _IsnotError(int.__name__, **{ai: i}) 

i = int(i) 

if not 0 <= i < shape[1]: 

raise _ValueError(ai, i) 

for aj, j in ais[:n]: 

if int(j) == i: 

raise _ValueError(_DEQUALSPACED_(ai, aj, i)) 

setattr(self, NN(_UNDER_, ai), i) 

 

def __contains__(self, latlon): 

'''Check for a specific lat-/longitude. 

 

@arg latlon: Point (C{LatLon}, L{LatLon2Tuple} or 2-tuple 

C{(lat, lon)}). 

 

@return: C{True} if B{C{latlon}} is present, C{False} otherwise. 

 

@raise TypeError: Invalid B{C{latlon}}. 

''' 

return self._contains(latlon) 

 

def __getitem__(self, index): 

'''Return row[index] as C{LatLon} or return a L{Numpy2LatLon} slice. 

''' 

return self._getitem(index) 

 

def __iter__(self): 

'''Yield rows as C{LatLon}. 

''' 

return self._iter() 

 

def __len__(self): 

'''Return the number of rows. 

''' 

return self._shape[0] 

 

def __repr__(self): 

'''Return a string representation. 

''' 

return self._repr() 

 

def __reversed__(self): # PYCHOK false 

'''Yield rows as C{LatLon} in reverse order. 

''' 

return self._reversed() 

 

__str__ = __repr__ 

 

def count(self, latlon): 

'''Count the number of rows with a specific lat-/longitude. 

 

@arg latlon: Point (C{LatLon}, L{LatLon2Tuple} or 2-tuple 

C{(lat, lon)}). 

 

@return: Count (C{int}). 

 

@raise TypeError: Invalid B{C{latlon}}. 

''' 

return self._count(latlon) 

 

def find(self, latlon, *start_end): 

'''Find the first row with a specific lat-/longitude. 

 

@arg latlon: Point (C{LatLon}) or 2-tuple (lat, lon). 

@arg start_end: Optional C{[start[, end]]} index (integers). 

 

@return: Index or -1 if not found (C{int}). 

 

@raise TypeError: Invalid B{C{latlon}}. 

''' 

return self._find(latlon, start_end) 

 

def _findall(self, latlon, start_end): 

'''(INTERNAL) Yield indices of all matching rows. 

''' 

try: 

lat, lon = latlon.lat, latlon.lon 

except AttributeError: 

try: 

lat, lon = latlon 

except (TypeError, ValueError): 

raise _IsnotError(_valid_, latlon=latlon) 

 

_ilat, _ilon = self._ilat, self._ilon 

_array, _eps = self._array, self._epsilon 

for i in self._range(*start_end): 

row = _array[i] 

if abs(row[_ilat] - lat) <= _eps and \ 

abs(row[_ilon] - lon) <= _eps: 

yield i 

 

def findall(self, latlon, *start_end): 

'''Yield indices of all rows with a specific lat-/longitude. 

 

@arg latlon: Point (C{LatLon}, L{LatLon2Tuple} or 2-tuple 

C{(lat, lon)}). 

@arg start_end: Optional C{[start[, end]]} index (C{int}). 

 

@return: Indices (C{iterable}). 

 

@raise TypeError: Invalid B{C{latlon}}. 

''' 

return self._findall(latlon, start_end) 

 

def index(self, latlon, *start_end): # PYCHOK Python 2- issue 

'''Find index of the first row with a specific lat-/longitude. 

 

@arg latlon: Point (C{LatLon}, L{LatLon2Tuple} or 2-tuple 

C{(lat, lon)}). 

@arg start_end: Optional C{[start[, end]]} index (C{int}). 

 

@return: Index (C{int}). 

 

@raise IndexError: Point not found. 

 

@raise TypeError: Invalid B{C{latlon}}. 

''' 

return self._index(latlon, start_end) 

 

@Property_RO 

def ilat(self): 

'''Get the latitudes column index (C{int}). 

''' 

return self._ilat 

 

@Property_RO 

def ilon(self): 

'''Get the longitudes column index (C{int}). 

''' 

return self._ilon 

 

# next = __iter__ 

 

def point(self, row): # PYCHOK *attrs 

'''Instantiate a point C{LatLon}. 

 

@arg row: Array row (numpy.array). 

 

@return: Point (C{LatLon}). 

''' 

return self._LatLon(row[self._ilat], row[self._ilon]) 

 

def rfind(self, latlon, *start_end): 

'''Find the last row with a specific lat-/longitude. 

 

@arg latlon: Point (C{LatLon}, L{LatLon2Tuple} or 2-tuple 

C{(lat, lon)}). 

@arg start_end: Optional C{[start[, end]]} index (C{int}). 

 

@note: Keyword order, first stop, then start. 

 

@return: Index or -1 if not found (C{int}). 

 

@raise TypeError: Invalid B{C{latlon}}. 

''' 

return self._rfind(latlon, start_end) 

 

def _slicekwds(self): 

'''(INTERNAL) Slice kwds. 

''' 

return dict(ilat=self._ilat, ilon=self._ilon) 

 

@Property_RO 

def shape(self): 

'''Get the shape of the C{NumPy} array or the C{Tuples} as 

L{Shape2Tuple}C{(nrows, ncols)}. 

''' 

return self._shape 

 

def _subset(self, indices): # PYCHOK no cover 

'''(INTERNAL) I{Must be implemented/overloaded}. 

''' 

notImplemented(self, indices) 

 

def subset(self, indices): 

'''Return a subset of the C{NumPy} array. 

 

@arg indices: Row indices (C{range} or C{int}[]). 

 

@note: A C{subset} is different from a C{slice} in 2 ways: 

(a) the C{subset} is typically specified as a list of 

(un-)ordered indices and (b) the C{subset} allocates 

a new, separate C{NumPy} array while a C{slice} is 

just an other C{view} of the original C{NumPy} array. 

 

@return: Sub-array (C{numpy.array}). 

 

@raise IndexError: Out-of-range B{C{indices}} value. 

 

@raise TypeError: If B{C{indices}} is not a C{range} 

nor an C{int}[]. 

''' 

if not issequence(indices, tuple): # NO tuple, only list 

# and range work properly to get Numpy array sub-sets 

raise _IsnotError(_valid_, indices=type(indices)) 

 

n = len(self) 

for i, v in enumerate(indices): 

if not isint(v): 

raise _TypeError(Fmt.SQUARE(indices=i), v) 

elif not 0 <= v < n: 

raise _IndexError(Fmt.SQUARE(indices=i), v) 

 

return self._subset(indices) 

 

 

class LatLon2psxy(_Basequence): 

'''Wrapper for C{LatLon} points as "on-the-fly" pseudo-xy coordinates. 

''' 

_closed = False 

_len = 0 

_deg2m = None # default, keep degrees 

_radius = None 

_wrap = True 

 

def __init__(self, latlons, closed=False, radius=None, wrap=True): 

'''Handle C{LatLon} points as pseudo-xy coordinates. 

 

@note: The C{LatLon} latitude is considered the I{pseudo-y} 

and longitude the I{pseudo-x} coordinate, likewise 

for L{LatLon2Tuple}. However, 2-tuples C{(x, y)} are 

considered as I{(longitude, latitude)}. 

 

@arg latlons: Points C{list}, C{sequence}, C{set}, C{tuple}, 

etc. (C{LatLon[]}). 

@kwarg closed: Optionally, close the polygon (C{bool}). 

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

@kwarg wrap: Wrap lat- and longitudes (C{bool}). 

 

@raise PointsError: Insufficient number of B{C{latlons}}. 

 

@raise TypeError: Some B{C{points}} are not B{C{base}}. 

''' 

self._closed = closed 

self._len, self._array = points2(latlons, closed=closed) 

if radius: 

self._radius = r = Radius(radius) 

self._deg2m = degrees2m(_1_0, r) 

self._wrap = wrap 

 

def __contains__(self, xy): 

'''Check for a matching point. 

 

@arg xy: Point (C{LatLon}, L{LatLon2Tuple} or 2-tuple 

C{(x, y)}) in (C{degrees}. 

 

@return: C{True} if B{C{xy}} is present, C{False} otherwise. 

 

@raise TypeError: Invalid B{C{xy}}. 

''' 

return self._contains(xy) 

 

def __getitem__(self, index): 

'''Return the pseudo-xy or return a L{LatLon2psxy} slice. 

''' 

return self._getitem(index) 

 

def __iter__(self): 

'''Yield all pseudo-xy's. 

''' 

return self._iter() 

 

def __len__(self): 

'''Return the number of pseudo-xy's. 

''' 

return self._len 

 

def __repr__(self): 

'''Return a string representation. 

''' 

return self._repr() 

 

def __reversed__(self): # PYCHOK false 

'''Yield all pseudo-xy's in reverse order. 

''' 

return self._reversed() 

 

__str__ = __repr__ 

 

def count(self, xy): 

'''Count the number of matching points. 

 

@arg xy: Point (C{LatLon}, L{LatLon2Tuple} or 2-tuple 

C{(x, y)}) in (C{degrees}. 

 

@return: Count (C{int}). 

 

@raise TypeError: Invalid B{C{xy}}. 

''' 

return self._count(xy) 

 

def find(self, xy, *start_end): 

'''Find the first matching point. 

 

@arg xy: Point (C{LatLon}, L{LatLon2Tuple} or 2-tuple 

C{(x, y)}) in (C{degrees}. 

@arg start_end: Optional C{[start[, end]]} index (C{int}). 

 

@return: Index or -1 if not found (C{int}). 

 

@raise TypeError: Invalid B{C{xy}}. 

''' 

return self._find(xy, start_end) 

 

def _findall(self, xy, start_end): 

'''(INTERNAL) Yield indices of all matching points. 

''' 

try: 

x, y = xy.lon, xy.lat 

 

def _x_y_ll3(ll): # match LatLon 

return ll.lon, ll.lat, ll 

 

except AttributeError: 

try: 

x, y = xy[:2] 

except (IndexError, TypeError, ValueError): 

raise _IsnotError(_valid_, xy=xy) 

 

_x_y_ll3 = self.point # PYCHOK expected 

 

_array, _eps = self._array, self._epsilon 

for i in self._range(*start_end): 

xi, yi, _ = _x_y_ll3(_array[i]) 

if abs(xi - x) <= _eps and \ 

abs(yi - y) <= _eps: 

yield i 

 

def findall(self, xy, *start_end): 

'''Yield indices of all matching points. 

 

@arg xy: Point (C{LatLon}, L{LatLon2Tuple} or 2-tuple 

C{(x, y)}) in (C{degrees}. 

@arg start_end: Optional C{[start[, end]]} index (C{int}). 

 

@return: Indices (C{iterator}). 

 

@raise TypeError: Invalid B{C{xy}}. 

''' 

return self._findall(xy, start_end) 

 

def index(self, xy, *start_end): # PYCHOK Python 2- issue 

'''Find the first matching point. 

 

@arg xy: Point (C{LatLon}) or 2-tuple (x, y) in (C{degrees}). 

@arg start_end: Optional C{[start[, end]]} index (C{int}). 

 

@return: Index (C{int}). 

 

@raise IndexError: Point not found. 

 

@raise TypeError: Invalid B{C{xy}}. 

''' 

return self._index(xy, start_end) 

 

@property_RO 

def isPoints2(self): 

'''Is this a LatLon2 wrapper/converter? 

''' 

return True # isinstance(self, (LatLon2psxy, ...)) 

 

def point(self, ll): # PYCHOK *attrs 

'''Create a pseudo-xy. 

 

@arg ll: Point (C{LatLon}). 

 

@return: An L{Point3Tuple}C{(x, y, ll)}. 

''' 

x, y = ll.lon, ll.lat # note, x, y = lon, lat 

if self._wrap: 

x, y = wrap180(x), wrap90(y) 

d = self._deg2m 

if d: # convert degrees to meter (or radians) 

x *= d 

y *= d 

return Point3Tuple(x, y, ll) 

 

def rfind(self, xy, *start_end): 

'''Find the last matching point. 

 

@arg xy: Point (C{LatLon}, L{LatLon2Tuple} or 2-tuple 

C{(x, y)}) in (C{degrees}. 

@arg start_end: Optional C{[start[, end]]} index (C{int}). 

 

@return: Index or -1 if not found (C{int}). 

 

@raise TypeError: Invalid B{C{xy}}. 

''' 

return self._rfind(xy, start_end) 

 

def _slicekwds(self): 

'''(INTERNAL) Slice kwds. 

''' 

return dict(closed=self._closed, radius=self._radius, wrap=self._wrap) 

 

 

class Numpy2LatLon(_Array2LatLon): # immutable, on purpose 

'''Wrapper for C{NumPy} arrays as "on-the-fly" C{LatLon} points. 

''' 

def __init__(self, array, ilat=0, ilon=1, LatLon=None): 

'''Handle a C{NumPy} array as a sequence of C{LatLon} points. 

 

@arg array: C{NumPy} array (C{numpy.array}). 

@kwarg ilat: Optional index of the latitudes column (C{int}). 

@kwarg ilon: Optional index of the longitudes column (C{int}). 

@kwarg LatLon: Optional C{LatLon} class to use (L{LatLon_}). 

 

@raise IndexError: If B{C{array.shape}} is not (1+, 2+). 

 

@raise TypeError: If B{C{array}} is not a C{NumPy} array or 

C{LatLon} is not a class with C{lat} 

and C{lon} attributes. 

 

@raise ValueError: If the B{C{ilat}} and/or B{C{ilon}} values 

are the same or out of range. 

 

@example: 

 

>>> type(array) 

<type 'numpy.ndarray'> # <class ...> in Python 3+ 

>>> points = Numpy2LatLon(array, lat=0, lon=1) 

>>> simply = simplifyRDP(points, ...) 

>>> type(simply) 

<type 'numpy.ndarray'> # <class ...> in Python 3+ 

>>> sliced = points[1:-1] 

>>> type(sliced) 

<class '...Numpy2LatLon'> 

''' 

try: # get shape and check some other numpy.array attrs 

s, _, _ = array.shape, array.nbytes, array.ndim # PYCHOK expected 

except AttributeError: 

raise _IsnotError('NumPy', array=type(array)) 

 

_Array2LatLon.__init__(self, array, ilat=ilat, ilon=ilon, 

LatLon=LatLon, shape=s) 

 

@property_RO 

def isNumpy2(self): 

'''Is this a Numpy2 wrapper? 

''' 

return True # isinstance(self, (Numpy2LatLon, ...)) 

 

def _subset(self, indices): 

return self._array[indices] # NumPy special 

 

 

class Shape2Tuple(_NamedTuple): 

'''2-Tuple C{(nrows, ncols)}, the number of rows and columns, 

both C{int}. 

''' 

_Names_ = (_nrows_, _ncols_) 

_Units_ = ( Number_, Number_) 

 

 

class Tuple2LatLon(_Array2LatLon): 

'''Wrapper for tuple sequences as "on-the-fly" C{LatLon} points. 

''' 

def __init__(self, tuples, ilat=0, ilon=1, LatLon=None): 

'''Handle a list of tuples, each containing a lat- and longitude 

and perhaps other values as a sequence of C{LatLon} points. 

 

@arg tuples: The C{list}, C{tuple} or C{sequence} of tuples (C{tuple}[]). 

@kwarg ilat: Optional index of the latitudes value (C{int}). 

@kwarg ilon: Optional index of the longitudes value (C{int}). 

@kwarg LatLon: Optional C{LatLon} class to use (L{LatLon_}). 

 

@raise IndexError: If C{(len(B{tuples}), min(len(t) for t 

in B{tuples}))} is not (1+, 2+). 

 

@raise TypeError: If B{C{tuples}} is not a C{list}, C{tuple} 

or C{sequence} or if B{C{LatLon}} is not a 

C{LatLon} with C{lat}, C{lon} and C{name} 

attributes. 

 

@raise ValueError: If the B{C{ilat}} and/or B{C{ilon}} values 

are the same or out of range. 

 

@example: 

 

>>> tuples = [(0, 1), (2, 3), (4, 5)] 

>>> type(tuples) 

<type 'list'> # <class ...> in Python 3+ 

>>> points = Tuple2LatLon(tuples, lat=0, lon=1) 

>>> simply = simplifyRW(points, 0.5, ...) 

>>> type(simply) 

<type 'list'> # <class ...> in Python 3+ 

>>> simply 

[(0, 1), (4, 5)] 

>>> sliced = points[1:-1] 

>>> type(sliced) 

<class '...Tuple2LatLon'> 

>>> sliced 

...Tuple2LatLon([(2, 3), ...][1], ilat=0, ilon=1) 

 

>>> closest, _ = nearestOn2(LatLon_(2, 1), points, adjust=False) 

>>> closest 

LatLon_(lat=1.0, lon=2.0) 

 

>>> closest, _ = nearestOn2(LatLon_(3, 2), points) 

>>> closest 

LatLon_(lat=2.001162, lon=3.001162) 

''' 

_xinstanceof(list, tuple, tuples=tuples) 

s = len(tuples), min(len(_) for _ in tuples) 

_Array2LatLon.__init__(self, tuples, ilat=ilat, ilon=ilon, 

LatLon=LatLon, shape=s) 

 

@property_RO 

def isTuple2(self): 

'''Is this a Tuple2 wrapper? 

''' 

return True # isinstance(self, (Tuple2LatLon, ...)) 

 

def _subset(self, indices): 

return type(self._array)(self._array[i] for i in indices) 

 

 

def _area2(points, adjust, wrap): 

'''(INTERNAL) Approximate the area in radians squared, I{signed}. 

''' 

if adjust: 

# approximate trapezoid by a rectangle, adjusting 

# the top width by the cosine of the latitudinal 

# average and bottom width by some fudge factor 

def _adjust(w, h): 

c = cos(h) if abs(h) < PI_2 else _0_0 

return w * h * (c + 1.2876) * _0_5 

else: 

def _adjust(w, h): # PYCHOK expected 

return w * h 

 

# setting radius=1 converts degrees to radians 

Ps = LatLon2PsxyIter(points, wrap=wrap, radius=_1_0, loop=1) 

x1, y1, ll = Ps[0] 

pts = [ll] 

 

A2 = Fsum() # trapezoidal area in radians**2 

for i, p in Ps.enumerate(closed=True): 

x2, y2, ll = p 

if 0 < i < 4: 

pts.append(ll) 

w, x2 = unrollPI(x1, x2, wrap=wrap if i else False) 

A2 += _adjust(w, (y2 + y1) * _0_5) 

x1, y1 = x2, y2 

 

return A2.fsum(), tuple(pts) 

 

 

def _areaError(pts, near_=NN): # imported by .ellipsoidalKarney 

'''(INTERNAL) Area issue. 

''' 

t = _ELLIPSIS_(pts[:3], NN) 

return _ValueError(NN(near_, 'zero or polar area'), txt=t) 

 

 

def areaOf(points, adjust=True, radius=R_M, wrap=True): 

'''Approximate the area of a polygon. 

 

@arg points: The polygon points (C{LatLon}[]). 

@kwarg adjust: Adjust the wrapped, unrolled longitudinal delta 

by the cosine of the mean latitude (C{bool}). 

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

@kwarg wrap: Wrap lat-, wrap and unroll longitudes (C{bool}). 

 

@return: Approximate area (I{square} C{meter}, same units as 

B{C{radius}} or C{radians} I{squared} if B{C{radius}} 

is C{None}). 

 

@raise PointsError: Insufficient number of B{C{points}} 

 

@raise TypeError: Some B{C{points}} are not C{LatLon}. 

 

@raise ValueError: Invalid B{C{radius}}. 

 

@note: This area approximation has limited accuracy and is 

ill-suited for regions exceeding several hundred Km 

or Miles or with near-polar latitudes. 

 

@see: L{sphericalNvector.areaOf}, L{sphericalTrigonometry.areaOf} 

and L{ellipsoidalKarney.areaOf}. 

''' 

a, _ = _area2(points, adjust, wrap) 

return abs(a) if radius is None else (abs(a) * Radius(radius)**2) 

 

 

def boundsOf(points, wrap=True, LatLon=None): 

'''Determine the lower-left SW and upper-right NE corners of a 

path or polygon. 

 

@arg points: The path or polygon points (C{LatLon}[]). 

@kwarg wrap: Wrap lat- and longitudes (C{bool}). 

@kwarg LatLon: Optional class to return the C{bounds} 

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

 

@return: A L{Bounds2Tuple}C{(latlonSW, latlonNE)} as 

B{C{LatLon}}s if B{C{LatLon}} is C{None} a 

L{Bounds4Tuple}C{(latS, lonW, latN, lonE)}. 

 

@raise PointsError: Insufficient number of B{C{points}} 

 

@raise TypeError: Some B{C{points}} are not C{LatLon}. 

 

@see: Function L{quadOf}. 

 

@example: 

 

>>> b = LatLon(45,1), LatLon(45,2), LatLon(46,2), LatLon(46,1) 

>>> boundsOf(b) # False 

>>> 45.0, 1.0, 46.0, 2.0 

''' 

Ps = LatLon2PsxyIter(points, wrap=wrap, loop=1) 

lox, loy, _ = hix, hiy, _ = Ps[0] 

 

for x, y, _ in Ps.iterate(closed=False): # [1:] 

if lox > x: 

lox = x 

elif hix < x: 

hix = x 

 

if loy > y: 

loy = y 

elif hiy < y: 

hiy = y 

 

return Bounds4Tuple(loy, lox, hiy, hix) if LatLon is None else \ 

Bounds2Tuple(LatLon(loy, lox), LatLon(hiy, hix)) # PYCHOK inconsistent 

 

 

def centroidOf(points, wrap=True, LatLon=None): 

'''Determine the centroid of a polygon. 

 

@arg points: The polygon points (C{LatLon}[]). 

@kwarg wrap: Wrap lat-, wrap and unroll longitudes (C{bool}). 

@kwarg LatLon: Optional class to return the centroid (C{LatLon}) 

or C{None}. 

 

@return: Centroid (B{C{LatLon}}) or a L{LatLon2Tuple}C{(lat, lon)} 

if C{B{LatLon} is None}. 

 

@raise PointsError: Insufficient number of B{C{points}} 

 

@raise TypeError: Some B{C{points}} are not C{LatLon}. 

 

@raise ValueError: The B{C{points}} enclose a pole or 

near-zero area. 

 

@see: U{Centroid<https://WikiPedia.org/wiki/Centroid#Of_a_polygon>} and 

Paul Bourke's U{Calculating The Area And Centroid Of A Polygon 

<https://www.SEAS.UPenn.edu/~ese502/lab-content/extra_materials/ 

Polygon%20Area%20and%20Centroid.pdf>}, 1988. 

''' 

A, X, Y = Fsum(), Fsum(), Fsum() 

 

# setting radius=1 converts degrees to radians 

Ps = LatLon2PsxyIter(points, wrap=wrap, radius=_1_0, loop=1) 

x1, y1, ll = Ps[0] 

pts = [ll] # for _areaError 

for i, p in Ps.enumerate(closed=True): 

x2, y2, ll = p 

if 0 < i < 4: 

pts.append(ll) 

if wrap and i != 0: 

_, x2 = unrollPI(x1, x2, wrap=wrap) 

t = x1 * y2 - x2 * y1 

A += t 

X += t * (x1 + x2) 

Y += t * (y1 + y2) 

# XXX more elaborately: 

# t1, t2 = x1 * y2, -(x2 * y1) 

# A.fadd_(t1, t2) 

# X.fadd_(t1 * x1, t1 * x2, t2 * x1, t2 * x2) 

# Y.fadd_(t1 * y1, t1 * y2, t2 * y1, t2 * y2) 

x1, y1 = x2, y2 

 

A = A.fmul(_3_0).fsum() # 6.0 / 2.0 

if isnear0(A): 

raise _areaError(pts, near_=_near_) 

Y, X = degrees90(Y.fdiv(A).fsum()), degrees180(X.fdiv(A).fsum()) 

return LatLon2Tuple(Y, X) if LatLon is None else LatLon(Y, X) 

 

 

def fractional(points, fi, j=None, wrap=None, LatLon=None, Vector=None, **kwds): 

'''Return the point at a given I{fractional} index. 

 

@arg points: The points (C{LatLon}[], L{Numpy2LatLon}[], 

L{Tuple2LatLon}[], C{Cartesian}[], C{Vector3d}[], 

L{Vector3Tuple}[]). 

@arg fi: The fractional index (L{FIx}, C{float} or C{int}). 

@kwarg j: Optionally, index of the other point (C{int}). 

@kwarg wrap: Wrap and unroll longitudes (C{bool}) or C{None} for 

backward compatible L{LatLon2Tuple} or B{C{LatLon}} 

with averaged lat- and longitudes. Use C{True} or 

C{False} to get the I{fractional} point computed 

method C{points[fi].intermediateTo}. 

@kwarg LatLon: Optional class to return the I{intermediate}, 

I{fractional} point (C{LatLon}) or C{None}. 

@kwarg Vector: Optional class to return the I{intermediate}, 

I{fractional} point (C{Cartesian}, C{Vector3d}) 

or C{None}. 

@kwarg kwds: Optional, additional B{C{LatLon}} I{or} B{C{Vector}} 

keyword arguments, ignored if both C{B{LatLon}} and 

C{B{Vector}} are C{None}. 

 

@return: A L{LatLon2Tuple}C{(lat, lon)} if B{C{wrap}}, B{C{LatLon}} 

and B{C{Vector}} all are C{None}, the defaults. 

 

An instance of B{C{LatLon}} if not C{None} I{or} an instance 

of B{C{Vector}} if not C{None}. 

 

Otherwise with B{C{wrap}} either C{True} or C{False} and 

B{C{LatLon}} and B{C{Vector}} both C{None}, an instance of 

B{C{points}}' (sub-)class C{intermediateTo} I{fractional}. 

 

Summarized as follows: 

 

>>> wrap | LatLon | Vector | returned type/value 

# -------+--------+--------+--------------+------ 

# | | | LatLon2Tuple | favg 

# None | None | None | or** | 

# | | | Vector3Tuple | favg 

# None | LatLon | None | LatLon | favg 

# None | None | Vector | Vector | favg 

# -------+--------+--------+--------------+------ 

# True | None | None | points' | .iTo 

# True | LatLon | None | LatLon | .iTo 

# True | None | Vector | Vector | .iTo 

# -------+--------+--------+--------------+------ 

# False | None | None | points' | .iTo 

# False | LatLon | None | LatLon | .iTo 

# False | None | Vector | Vector | .iTo 

# _____ 

# favg) averaged lat, lon or x, y, z values 

# .iTo) value from points[fi].intermediateTo 

# **) depends on base class of points[fi] 

 

@raise IndexError: Fractional index B{C{fi}} invalid or B{C{points}} 

not subscriptable or not closed. 

 

@raise TypeError: Invalid B{C{LatLon}}, B{C{Vector}} or B{C{kwds}} 

argument. 

 

@see: Class L{FIx} and method L{FIx.fractional}. 

''' 

if LatLon and Vector: # PYCHOK no cover 

kwds = _xkwds(kwds, fi=fi, LatLon=LatLon, Vector=Vector) 

raise _TypeError(txt=fractional.__name__, **kwds) 

try: 

if not isscalar(fi) or fi < 0: 

raise IndexError 

n = getattr(fi, _fin_, 0) 

w = wrap if Vector is None else False # intermediateTo 

p = _fractional(points, fi, j, fin=n, wrap=w) # see .units.FIx 

if LatLon: 

p = LatLon(p.lat, p.lon, **kwds) 

elif Vector: 

p = Vector(p.x, p.y, p.z, **kwds) 

except (IndexError, TypeError): 

raise _IndexError(fi=fi, points=points, wrap=wrap, txt=fractional.__name__) 

return p 

 

 

def _fractional(points, fi, j, fin=None, wrap=None): # in .frechet.py 

'''(INTERNAL) Compute point at L{fractional} index C{fi} and C{j}. 

''' 

i = int(fi) 

p = points[i] 

r = fi - float(i) 

if r > EPS: # EPS0? 

if j is None: 

j = i + 1 

if fin: 

j %= fin 

q = points[j] 

if r >= EPS1: # PYCHOK no cover 

p = q 

elif wrap is not None: # in (True, False) 

p = p.intermediateTo(q, r, wrap=wrap) 

elif _isLatLon(p): # backward compatible default 

p = LatLon2Tuple(favg(p.lat, q.lat, f=r), 

favg(p.lon, q.lon, f=r), 

name=fractional.__name__) 

else: # assume p and q are cartesian or vectorial 

z = p.z if p.z is q.z else favg(p.z, q.z, f=r) 

p = Vector3Tuple(favg(p.x, q.x, f=r), 

favg(p.y, q.y, f=r), z, 

name=fractional.__name__) 

return p 

 

 

def isclockwise(points, adjust=False, wrap=True): 

'''Determine the direction of a path or polygon. 

 

@arg points: The path or polygon points (C{LatLon}[]). 

@kwarg adjust: Adjust the wrapped, unrolled longitudinal delta 

by the cosine of the mean latitude (C{bool}). 

@kwarg wrap: Wrap lat-, wrap and unroll longitudes (C{bool}). 

 

@return: C{True} if B{C{points}} are clockwise, C{False} otherwise. 

 

@raise PointsError: Insufficient number of B{C{points}} 

 

@raise TypeError: Some B{C{points}} are not C{LatLon}. 

 

@raise ValueError: The B{C{points}} enclose a pole or zero area. 

 

@example: 

 

>>> f = LatLon(45,1), LatLon(45,2), LatLon(46,2), LatLon(46,1) 

>>> isclockwise(f) # False 

>>> isclockwise(reversed(f)) # True 

''' 

a, pts = _area2(points, adjust, wrap) 

if a > 0: # opposite of ellipsoidalExact and -Karney 

return True 

elif a < 0: 

return False 

# <https://blog.Element84.com/determining-if-a-spherical-polygon-contains-a-pole.html> 

raise _areaError(pts) 

 

 

def isconvex(points, adjust=False, wrap=True): 

'''Determine whether a polygon is convex. 

 

@arg points: The polygon points (C{LatLon}[]). 

@kwarg adjust: Adjust the wrapped, unrolled longitudinal delta 

by the cosine of the mean latitude (C{bool}). 

@kwarg wrap: Wrap lat-, wrap and unroll longitudes (C{bool}). 

 

@return: C{True} if B{C{points}} are convex, C{False} otherwise. 

 

@raise CrossError: Some B{C{points}} are colinear. 

 

@raise PointsError: Insufficient number of B{C{points}} 

 

@raise TypeError: Some B{C{points}} are not C{LatLon}. 

 

@example: 

 

>>> t = LatLon(45,1), LatLon(46,1), LatLon(46,2) 

>>> isconvex(t) # True 

 

>>> f = LatLon(45,1), LatLon(46,2), LatLon(45,2), LatLon(46,1) 

>>> isconvex(f) # False 

''' 

return bool(isconvex_(points, adjust=adjust, wrap=wrap)) 

 

 

def isconvex_(points, adjust=False, wrap=True): 

'''Determine whether a polygon is convex I{and clockwise}. 

 

@arg points: The polygon points (C{LatLon}[]). 

@kwarg adjust: Adjust the wrapped, unrolled longitudinal delta 

by the cosine of the mean latitude (C{bool}). 

@kwarg wrap: Wrap lat-, wrap and unroll longitudes (C{bool}). 

 

@return: C{+1} if B{C{points}} are convex clockwise, C{-1} for 

convex counter-clockwise B{C{points}}, C{0} otherwise. 

 

@raise CrossError: Some B{C{points}} are colinear. 

 

@raise PointsError: Insufficient number of B{C{points}} 

 

@raise TypeError: Some B{C{points}} are not C{LatLon}. 

 

@example: 

 

>>> t = LatLon(45,1), LatLon(46,1), LatLon(46,2) 

>>> isconvex_(t) # +1 

 

>>> f = LatLon(45,1), LatLon(46,2), LatLon(45,2), LatLon(46,1) 

>>> isconvex_(f) # 0 

''' 

def _unroll2(x1, y1, x2, y2, a, w): 

x21, x2 = unroll180(x1, x2, wrap=w) 

if a: 

y = radians(y1 + y2) * _0_5 

x21 *= cos(y) if abs(y) < PI_2 else _0_0 

return x21, x2 

 

c, s = crosserrors(), 0 

 

Ps = LatLon2PsxyIter(points, wrap=wrap, loop=2) 

x1, y1, _ = Ps[0] 

x2, y2, _ = Ps[1] 

x21, x2 = _unroll2(x1, y1, x2, y2, adjust, False) 

 

for i, p in Ps.enumerate(closed=True): 

x3, y3, ll = p 

x32, x3 = _unroll2(x2, y2, x3, y3, adjust, (wrap if i > 1 else False)) 

 

# get the sign of the distance from point 

# x3, y3 to the line from x1, y1 to x2, y2 

# <https://WikiPedia.org/wiki/Distance_from_a_point_to_a_line> 

s3 = fdot((x3, y3, x1, y1), y2 - y1, -x21, -y2, x2) 

if s3 > 0: # x3, y3 on the right 

if s < 0: # non-convex 

return 0 

s = +1 

 

elif s3 < 0: # x3, y3 on the left 

if s > 0: # non-convex 

return 0 

s = -1 

 

elif c and fdot((x32, y1 - y2), y3 - y2, -x21) < 0: # PYCHOK no cover 

# colinear u-turn: x3, y3 not on the 

# opposite side of x2, y2 as x1, y1 

t = Fmt.SQUARE(points=i) 

raise CrossError(t, ll, txt=_colinear_) 

 

x1, y1, x2, y2, x21 = x2, y2, x3, y3, x32 

 

return s # all points on the same side 

 

 

def isenclosedBy(point, points, wrap=False): # MCCABE 15 

'''Determine whether a point is enclosed by a polygon. 

 

@arg point: The point (C{LatLon} or 2-tuple C{(lat, lon)}). 

@arg points: The polygon points (C{LatLon}[]). 

@kwarg wrap: Wrap lat-, wrap and unroll longitudes (C{bool}). 

 

@return: C{True} if B{C{point}} is inside the polygon, C{False} 

otherwise. 

 

@raise PointsError: Insufficient number of B{C{points}} 

 

@raise TypeError: Some B{C{points}} are not C{LatLon}. 

 

@raise ValueError: Invalid B{C{point}}, lat- or longitude. 

 

@see: Functions L{pygeodesy.isconvex}, L{pygeodesy.isenclosedBy} and 

L{pygeodesy.ispolar} especially if the B{C{points}} may enclose 

a pole or wrap around the earth longitudinally, methods 

L{sphericalNvector.LatLon.isenclosedBy}, 

L{sphericalTrigonometry.LatLon.isenclosedBy} and 

U{MultiDop GeogContainPt<https://GitHub.com/NASA/MultiDop>} 

(U{Shapiro et al. 2009, JTECH 

<https://Journals.AMetSoc.org/doi/abs/10.1175/2009JTECHA1256.1>} 

and U{Potvin et al. 2012, JTECH 

<https://Journals.AMetSoc.org/doi/abs/10.1175/JTECH-D-11-00019.1>}). 

''' 

try: 

y0, x0 = point.lat, point.lon 

except AttributeError: 

try: 

y0, x0 = map1(float, *point[:2]) 

except (IndexError, TypeError, ValueError) as x: 

raise _ValueError(point=point, txt=str(x)) 

 

if wrap: 

x0, y0 = wrap180(x0), wrap90(y0) 

 

def _dxy3(x1, x2, y2, w): 

dx, x2 = unroll180(x1, x2, wrap=w) 

return dx, x2, y2 

 

else: 

x0 = fmod(x0, _360_0) # not x0 % 360! 

x0_180_ = x0 - _180_0 

x0_180 = x0 + _180_0 

 

def _dxy3(x1, x, y, unused): # PYCHOK expected 

x = _umod_360(float(x)) 

if x < x0_180_: 

x += _360_0 

elif x >= x0_180: 

x -= _360_0 

return (x - x1), x, y 

 

Ps = LatLon2PsxyIter(points, wrap=wrap, loop=1) 

p = Ps[0] 

e = m = False 

S = Fsum() 

 

_, x1, y1 = _dxy3(x0, p.x, p.y, False) 

for i, p in Ps.enumerate(closed=True): 

dx, x2, y2 = _dxy3(x1, p.x, p.y, (wrap if i else False)) 

# ignore duplicate and near-duplicate pts 

if max(abs(dx), abs(y2 - y1)) > EPS: 

# determine if polygon edge (x1, y1)..(x2, y2) straddles 

# point (lat, lon) or is on boundary, but do not count 

# edges on boundary as more than one crossing 

if abs(dx) < 180 and (x1 < x0 <= x2 or x2 < x0 <= x1): 

m = not m 

dy = (x0 - x1) * (y2 - y1) - (y0 - y1) * dx 

if (dy > 0 and dx >= 0) or (dy < 0 and dx <= 0): 

e = not e 

 

S += sin(radians(y2)) 

x1, y1 = x2, y2 

 

# An odd number of meridian crossings means, the polygon 

# contains a pole. Assume it is the pole on the hemisphere 

# containing the polygon mean point and if the polygon does 

# contain the North Pole, flip the result. 

if m and S.fsum() > 0: 

e = not e 

return e 

 

 

def ispolar(points, wrap=False): 

'''Check whether a polygon encloses a pole. 

 

@arg points: The polygon points (C{LatLon}[]). 

@kwarg wrap: Wrap and unroll longitudes (C{bool}). 

 

@return: C{True} if the polygon encloses a pole, C{False} 

otherwise. 

 

@raise PointsError: Insufficient number of B{C{points}} 

 

@raise TypeError: Some B{C{points}} are not C{LatLon} or don't 

have C{bearingTo2}, C{initialBearingTo} 

and C{finalBearingTo} methods. 

''' 

def _cds(points, wrap): # iterate over course deltas 

Ps = PointsIter(points, loop=2) 

p2, p1 = Ps[0:2] 

b1, _ = _bearingTo2(p2, p1, wrap=wrap) 

 

for p2 in Ps.iterate(closed=True): 

if not p2.isequalTo(p1, EPS): 

b, b2 = _bearingTo2(p1, p2, wrap=wrap) 

yield wrap180(b - b1) # (b - b1 + 540) % 360 - 180 

yield wrap180(b2 - b) # (b2 - b + 540) % 360 - 180 

p1, b1 = p2, b2 

 

# summation of course deltas around pole is 0° rather than normally ±360° 

# <https://blog.Element84.com/determining-if-a-spherical-polygon-contains-a-pole.html> 

s = fsum(_cds(points, wrap)) 

# XXX fix (intermittant) edge crossing pole - eg (85,90), (85,0), (85,-90) 

return abs(s) < 90 # "zero-ish" 

 

 

def luneOf(lon1, lon2, closed=False, LatLon=LatLon_, **LatLon_kwds): 

'''Generate an ellipsoidal or spherical U{lune 

<https://WikiPedia.org/wiki/Spherical_lune>}-shaped path or polygon. 

 

@arg lon1: Left longitude (C{degrees90}). 

@arg lon2: Right longitude (C{degrees90}). 

@kwarg closed: Optionally, close the path (C{bool}). 

@kwarg LatLon: Class to use (L{LatLon_}). 

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

keyword arguments. 

 

@return: A tuple of 4 or 5 B{C{LatLon}} instances outlining 

the lune shape. 

 

@see: U{Latitude-longitude quadrangle 

<https://www.MathWorks.com/help/map/ref/areaquad.html>}. 

''' 

t = (LatLon( _0_0, lon1, **LatLon_kwds), 

LatLon( _90_0, lon1, **LatLon_kwds), 

LatLon( _0_0, lon2, **LatLon_kwds), 

LatLon(_N_90_0, lon2, **LatLon_kwds)) 

if closed: 

t += t[:1] 

return t 

 

 

def nearestOn5(point, points, closed=False, wrap=False, LatLon=None, **options): 

'''Locate the point on a path or polygon closest to a reference point. 

 

The closest point is either on and within the extent of a polygon edge or 

the nearest of that edge's end points. 

 

@arg point: Reference point (C{LatLon}). 

@arg points: The path or polygon points (C{LatLon}[]). 

@kwarg closed: Optionally, close the path or polygon (C{bool}). 

@kwarg wrap: Wrap and L{pygeodesy.unroll180} longitudes and longitudinal 

delta (C{bool}) in function L{pygeodesy.equirectangular_}. 

@kwarg LatLon: Optional class to return the closest point (C{LatLon}) 

or C{None}. 

@kwarg options: Other keyword arguments for function 

L{pygeodesy.equirectangular_}. 

 

@return: A L{NearestOn3Tuple}C{(closest, distance, angle)} with the 

{closest} point (B{C{LatLon}}) or if C{B{LatLon} is None}, 

a L{NearestOn5Tuple}C{(lat, lon, distance, angle, height)}. 

The C{distance} is the L{pygeodesy.equirectangular} distance 

between the C{closest} and reference B{C{point}} in C{degrees}. 

The C{angle} from the reference B{C{point}} to the C{closest} 

is in compass C{degrees360}, like function 

L{pygeodesy.compassAngle}. 

 

@raise LimitError: Lat- and/or longitudinal delta exceeds the B{C{limit}}, 

see function L{pygeodesy.equirectangular_}. 

 

@raise PointsError: Insufficient number of B{C{points}} 

 

@raise TypeError: Some B{C{points}} are not C{LatLon}. 

 

@note: Distances are I{approximated} using function L{pygeodesy.equirectangular_}, 

subject to the supplied B{C{options}}. Method C{LatLon.nearestOn6} 

measures distances more accurately. 

 

@see: Function L{pygeodesy.nearestOn6} for cartesian points. Use function 

L{pygeodesy.degrees2m} to convert C{degrees} to C{meter}. 

''' 

def _d2yx(p2, p1, u, w): 

# w = wrap if (not closed or w < (n - 1)) else False 

# equirectangular_ returns a Distance4Tuple(distance 

# in degrees squared, delta lat, delta lon, p2.lon 

# unroll/wrap); the previous p2.lon unroll/wrap 

# is also applied to the next edge's p1.lon 

return equirectangular_(p1.lat, p1.lon + u, 

p2.lat, p2.lon, wrap=w, **options) 

 

def _h(p): # get height or default 0 

return getattr(p, _height_, 0) or 0 

 

# 3-D version used in .vector3d._nearestOn2 

# 

# point (x, y) on axis rotated ccw by angle a: 

# x' = y * sin(a) + x * cos(a) 

# y' = y * cos(a) - x * sin(a) 

# 

# distance (w) along and perpendicular (h) to 

# a line thru point (dx, dy) and the origin: 

# w = (y * dy + x * dx) / hypot(dx, dy) 

# h = (y * dx - x * dy) / hypot(dx, dy) 

# 

# closest point on that line thru (dx, dy): 

# xc = dx * w / hypot(dx, dy) 

# yc = dy * w / hypot(dx, dy) 

# or 

# xc = dx * f 

# yc = dy * f 

# with 

# f = w / hypot(dx, dy) 

# or 

# f = (y * dy + x * dx) / hypot2(dx, dy) 

# 

# i.e. no need for sqrt or hypot 

 

Ps = PointsIter(points, loop=1) 

p1 = c = Ps[0] 

u1 = u = _0_0 

d, dy, dx, _ = _d2yx(p1, point, u1, False) 

for i, p2 in Ps.enumerate(closed=closed): 

# iff wrapped, unroll lon1 (actually previous 

# lon2) like function unroll180/-PI would've 

w = False if closed and i == 0 else wrap 

d21, y21, x21, u2 = _d2yx(p2, p1, u1, w) 

if d21 > EPS: 

# distance point to p1, y01 and x01 inverted 

d2, y01, x01, _ = _d2yx(point, p1, u1, closed) 

if d2 > EPS: 

w2 = y01 * y21 + x01 * x21 

if w2 > 0: 

if w2 < d21: 

# closest is between p1 and p2, use 

# original delta's, not y21 and x21 

f = w2 / d21 

p1 = LatLon_(favg(p1.lat, p2.lat, f=f), 

favg(p1.lon, p2.lon + u2, f=f), 

height=favg(_h(p1), _h(p2), f=f)) 

u1 = _0_0 

else: # p2 is closest 

p1, u1 = p2, u2 

d2, y01, x01, _ = _d2yx(point, p1, u1, closed) 

if d2 < d: # p1 is closer, y01 and x01 negated 

c, u, d, dy, dx = p1, u1, d2, -y01, -x01 

p1, u1 = p2, u2 

 

d, a, h = hypot(dx, dy), atan2b(dx, dy), _h(c) 

if LatLon is None: 

r = NearestOn5Tuple(c.lat, c.lon + u, d, a, h) 

else: 

r = LatLon(c.lat, c.lon + u, height=h) 

r = NearestOn3Tuple(r, d, a) 

return _xnamed(r, nameof(point)) 

 

 

def perimeterOf(points, closed=False, adjust=True, radius=R_M, wrap=True): 

'''Approximate the perimeter of a path or polygon. 

 

@arg points: The path or polygon points (C{LatLon}[]). 

@kwarg closed: Optionally, close the path or polygon (C{bool}). 

@kwarg adjust: Adjust the wrapped, unrolled longitudinal delta 

by the cosine of the mean latitude (C{bool}). 

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

@kwarg wrap: Wrap lat-, wrap and unroll longitudes (C{bool}). 

 

@return: Approximate perimeter (C{meter}, same units as 

B{C{radius}}). 

 

@raise PointsError: Insufficient number of B{C{points}} 

 

@raise TypeError: Some B{C{points}} are not C{LatLon}. 

 

@raise ValueError: Invalid B{C{radius}}. 

 

@note: This perimeter is based on the L{pygeodesy.equirectangular_} 

distance approximation and is ill-suited for regions exceeding 

several hundred Km or Miles or with near-polar latitudes. 

 

@see: Functions L{sphericalTrigonometry.perimeterOf} and 

L{ellipsoidalKarney.perimeterOf}. 

''' 

def _degs(points, closed, wrap): # angular edge lengths in degrees 

Ps = LatLon2PsxyIter(points, wrap=wrap, loop=1) 

p1, u = Ps[0], _0_0 # previous x2's unroll/wrap 

for i, p2 in Ps.enumerate(closed=closed): 

w = False if closed and i == 0 else wrap 

# apply previous x2's unroll/wrap to new x1 

_, dy, dx, u = equirectangular_(p1.y, p1.x + u, p2.y, p2.x, 

adjust=adjust, 

limit=None, 

wrap=w) # PYCHOK non-sequence 

yield hypot(dx, dy) 

p1 = p2 

 

d = fsum(_degs(points, closed, wrap)) 

return degrees2m(d, radius=radius) 

 

 

def quadOf(latS, lonW, latN, lonE, closed=False, LatLon=LatLon_, **LatLon_kwds): 

'''Generate a quadrilateral path or polygon from two points. 

 

@arg latS: Southernmost latitude (C{degrees90}). 

@arg lonW: Westernmost longitude (C{degrees180}). 

@arg latN: Northernmost latitude (C{degrees90}). 

@arg lonE: Easternmost longitude (C{degrees180}). 

@kwarg closed: Optionally, close the path (C{bool}). 

@kwarg LatLon: Class to use (L{LatLon_}). 

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

keyword arguments. 

 

@return: Return a tuple of 4 or 5 B{C{LatLon}} instances 

outlining the quadrilateral. 

 

@see: Function L{boundsOf}. 

''' 

t = (LatLon(latS, lonW, **LatLon_kwds), 

LatLon(latN, lonW, **LatLon_kwds), 

LatLon(latN, lonE, **LatLon_kwds), 

LatLon(latS, lonE, **LatLon_kwds)) 

if closed: 

t += t[:1] 

return t 

 

 

__all__ += _ALL_DOCS(_Array2LatLon, _Basequence) 

 

# **) MIT License 

# 

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

# 

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

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

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

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

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

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

# 

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

# in all copies or substantial portions of the Software. 

# 

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

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

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

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

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

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

# OTHER DEALINGS IN THE SOFTWARE.