turkgrid 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- turkgrid/__init__.py +85 -0
- turkgrid/__main__.py +7 -0
- turkgrid/_backend.py +74 -0
- turkgrid/_turkiye.py +122 -0
- turkgrid/cli.py +302 -0
- turkgrid/crs.py +293 -0
- turkgrid/detect.py +268 -0
- turkgrid/ellipsoids.py +85 -0
- turkgrid/geojson.py +181 -0
- turkgrid/helmert.py +205 -0
- turkgrid/py.typed +0 -0
- turkgrid/tm.py +158 -0
- turkgrid/transformer.py +215 -0
- turkgrid-0.1.0.dist-info/METADATA +293 -0
- turkgrid-0.1.0.dist-info/RECORD +19 -0
- turkgrid-0.1.0.dist-info/WHEEL +5 -0
- turkgrid-0.1.0.dist-info/entry_points.txt +2 -0
- turkgrid-0.1.0.dist-info/licenses/LICENSE +21 -0
- turkgrid-0.1.0.dist-info/top_level.txt +1 -0
turkgrid/__init__.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""turkgrid: zero-dependency coordinate reference toolkit for Türkiye.
|
|
2
|
+
|
|
3
|
+
Converts between the grids used for Turkish maps, plans and cadastre - TUREF and ED50
|
|
4
|
+
3-degree Transverse Mercator (TM27 ... TM45), zone-prefixed 3-degree Gauss-Krüger,
|
|
5
|
+
WGS 84 and ED50 UTM 35N-38N, geographic WGS 84 / TUREF / ED50 and Web Mercator - in
|
|
6
|
+
pure Python (NumPy optional for vectorised arrays), and guesses the CRS of
|
|
7
|
+
coordinates of unknown origin.
|
|
8
|
+
|
|
9
|
+
>>> import turkgrid
|
|
10
|
+
>>> lon, lat = turkgrid.to_wgs84((465000.0, 4545000.0), 5254)
|
|
11
|
+
>>> round(lon, 6), round(lat, 6)
|
|
12
|
+
(29.583757, 41.039109)
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from .crs import (
|
|
16
|
+
TURKISH_CENTRAL_MERIDIANS,
|
|
17
|
+
TURKISH_UTM_ZONES,
|
|
18
|
+
CRSInfo,
|
|
19
|
+
UnsupportedCRSError,
|
|
20
|
+
epsg_for_lon,
|
|
21
|
+
epsg_info,
|
|
22
|
+
parse_epsg,
|
|
23
|
+
supported_epsg_codes,
|
|
24
|
+
utm_zone_for_lon,
|
|
25
|
+
zone_for_lon,
|
|
26
|
+
)
|
|
27
|
+
from .detect import Candidate, detect_crs
|
|
28
|
+
from .ellipsoids import GRS80, INTERNATIONAL_1924, WGS84, Datum, Ellipsoid
|
|
29
|
+
from .geojson import geojson_crs, reproject_geojson
|
|
30
|
+
from .helmert import (
|
|
31
|
+
EPSG_1784,
|
|
32
|
+
Helmert7,
|
|
33
|
+
ed50_to_wgs84,
|
|
34
|
+
geocentric_to_geodetic,
|
|
35
|
+
geodetic_to_geocentric,
|
|
36
|
+
wgs84_to_ed50,
|
|
37
|
+
)
|
|
38
|
+
from .tm import TransverseMercator, WebMercator
|
|
39
|
+
from .transformer import (
|
|
40
|
+
Transformer,
|
|
41
|
+
from_wgs84,
|
|
42
|
+
get_transformer,
|
|
43
|
+
to_wgs84,
|
|
44
|
+
transform,
|
|
45
|
+
transform_xy,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
__version__ = "0.1.0"
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
"EPSG_1784",
|
|
52
|
+
"GRS80",
|
|
53
|
+
"INTERNATIONAL_1924",
|
|
54
|
+
"TURKISH_CENTRAL_MERIDIANS",
|
|
55
|
+
"TURKISH_UTM_ZONES",
|
|
56
|
+
"WGS84",
|
|
57
|
+
"CRSInfo",
|
|
58
|
+
"Candidate",
|
|
59
|
+
"Datum",
|
|
60
|
+
"Ellipsoid",
|
|
61
|
+
"Helmert7",
|
|
62
|
+
"TransverseMercator",
|
|
63
|
+
"Transformer",
|
|
64
|
+
"UnsupportedCRSError",
|
|
65
|
+
"WebMercator",
|
|
66
|
+
"__version__",
|
|
67
|
+
"detect_crs",
|
|
68
|
+
"ed50_to_wgs84",
|
|
69
|
+
"epsg_for_lon",
|
|
70
|
+
"epsg_info",
|
|
71
|
+
"from_wgs84",
|
|
72
|
+
"geocentric_to_geodetic",
|
|
73
|
+
"geodetic_to_geocentric",
|
|
74
|
+
"geojson_crs",
|
|
75
|
+
"get_transformer",
|
|
76
|
+
"parse_epsg",
|
|
77
|
+
"reproject_geojson",
|
|
78
|
+
"supported_epsg_codes",
|
|
79
|
+
"to_wgs84",
|
|
80
|
+
"transform",
|
|
81
|
+
"transform_xy",
|
|
82
|
+
"utm_zone_for_lon",
|
|
83
|
+
"wgs84_to_ed50",
|
|
84
|
+
"zone_for_lon",
|
|
85
|
+
]
|
turkgrid/__main__.py
ADDED
turkgrid/_backend.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Math backends: one implementation of every formula, run on floats or NumPy arrays.
|
|
2
|
+
|
|
3
|
+
The projection and datum code calls elementary functions through a backend object
|
|
4
|
+
instead of :mod:`math` directly. :data:`SCALAR` wraps :mod:`math` (pure Python, no
|
|
5
|
+
dependencies); :func:`numpy_backend` wraps NumPy's ufuncs so the very same code
|
|
6
|
+
vectorises over arrays. Every loop in the formulas runs a fixed number of times, so
|
|
7
|
+
no step depends on the values of the data.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class _ScalarBackend:
|
|
17
|
+
"""Elementary functions on Python floats (the :mod:`math` module)."""
|
|
18
|
+
|
|
19
|
+
name = "math"
|
|
20
|
+
sin = staticmethod(math.sin)
|
|
21
|
+
cos = staticmethod(math.cos)
|
|
22
|
+
tan = staticmethod(math.tan)
|
|
23
|
+
sinh = staticmethod(math.sinh)
|
|
24
|
+
cosh = staticmethod(math.cosh)
|
|
25
|
+
asin = staticmethod(math.asin)
|
|
26
|
+
atan = staticmethod(math.atan)
|
|
27
|
+
atan2 = staticmethod(math.atan2)
|
|
28
|
+
atanh = staticmethod(math.atanh)
|
|
29
|
+
asinh = staticmethod(math.asinh)
|
|
30
|
+
sqrt = staticmethod(math.sqrt)
|
|
31
|
+
hypot = staticmethod(math.hypot)
|
|
32
|
+
exp = staticmethod(math.exp)
|
|
33
|
+
log = staticmethod(math.log)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _NumpyBackend:
|
|
37
|
+
"""Elementary functions on NumPy arrays (element-wise ufuncs)."""
|
|
38
|
+
|
|
39
|
+
name = "numpy"
|
|
40
|
+
|
|
41
|
+
def __init__(self, np: Any) -> None:
|
|
42
|
+
self.sin = np.sin
|
|
43
|
+
self.cos = np.cos
|
|
44
|
+
self.tan = np.tan
|
|
45
|
+
self.sinh = np.sinh
|
|
46
|
+
self.cosh = np.cosh
|
|
47
|
+
self.asin = np.arcsin
|
|
48
|
+
self.atan = np.arctan
|
|
49
|
+
self.atan2 = np.arctan2
|
|
50
|
+
self.atanh = np.arctanh
|
|
51
|
+
self.asinh = np.arcsinh
|
|
52
|
+
self.sqrt = np.sqrt
|
|
53
|
+
self.hypot = np.hypot
|
|
54
|
+
self.exp = np.exp
|
|
55
|
+
self.log = np.log
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
SCALAR: Any = _ScalarBackend()
|
|
59
|
+
_NUMPY: Any = None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def numpy_backend() -> Any:
|
|
63
|
+
"""Return the NumPy backend, importing NumPy on first use."""
|
|
64
|
+
global _NUMPY
|
|
65
|
+
if _NUMPY is None:
|
|
66
|
+
import numpy as np
|
|
67
|
+
|
|
68
|
+
_NUMPY = _NumpyBackend(np)
|
|
69
|
+
return _NUMPY
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def is_ndarray(value: Any) -> bool:
|
|
73
|
+
"""True when *value* is a NumPy array, without importing NumPy."""
|
|
74
|
+
return type(value).__module__ == "numpy" and type(value).__name__ == "ndarray"
|
turkgrid/_turkiye.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Coarse reference geography of Türkiye used by :func:`turkgrid.detect_crs`.
|
|
2
|
+
|
|
3
|
+
The outline is a hand-simplified land border and coastline (about 140 vertices,
|
|
4
|
+
lon/lat degrees, roughly 5-15 km generalisation, islands of Gökçeada and Bozcaada
|
|
5
|
+
folded in). It only has to tell "inside or near Türkiye" from "somewhere else", so
|
|
6
|
+
detection adds a buffer of :data:`OUTLINE_BUFFER_DEG` around it. Province centres
|
|
7
|
+
are approximate (about 0.05 degrees) and only label results for humans.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
|
|
14
|
+
OUTLINE_BUFFER_DEG = 0.2
|
|
15
|
+
|
|
16
|
+
# (lon, lat), clockwise from the mouth of the Meriç/Evros.
|
|
17
|
+
TURKIYE_OUTLINE: tuple[tuple[float, float], ...] = (
|
|
18
|
+
(26.03, 40.73), (26.33, 40.95), (26.60, 41.33), (26.63, 41.60), (26.36, 41.72),
|
|
19
|
+
(26.60, 41.92), (27.20, 42.09), (27.60, 41.97), (28.03, 41.98), (28.60, 41.60),
|
|
20
|
+
(28.68, 41.35), (29.10, 41.23), (29.60, 41.18), (30.25, 41.17), (30.65, 41.12),
|
|
21
|
+
(31.10, 41.09), (31.45, 41.29), (31.80, 41.46), (32.39, 41.75), (33.00, 41.90),
|
|
22
|
+
(33.77, 41.98), (34.95, 42.10), (35.15, 42.03), (35.20, 41.80), (35.95, 41.73),
|
|
23
|
+
(36.33, 41.29), (36.90, 41.35), (37.28, 41.13), (37.88, 40.98), (38.39, 40.92),
|
|
24
|
+
(38.80, 41.00), (39.73, 41.00), (40.27, 40.95), (40.52, 41.02), (40.90, 41.18),
|
|
25
|
+
(41.43, 41.40), (41.55, 41.52), (42.50, 41.60), (42.90, 41.50), (43.45, 41.15),
|
|
26
|
+
(43.60, 40.75), (43.73, 40.45), (43.60, 40.10), (44.35, 40.03), (44.77, 39.71),
|
|
27
|
+
(44.81, 39.63), (44.40, 39.38), (44.20, 38.95), (44.33, 38.33), (44.50, 38.00),
|
|
28
|
+
(44.50, 37.75), (44.80, 37.30), (44.79, 37.14), (44.20, 37.28), (43.50, 37.25),
|
|
29
|
+
(42.80, 37.33), (42.36, 37.11), (41.22, 37.07), (40.05, 36.83), (38.95, 36.71),
|
|
30
|
+
(38.00, 36.83), (37.10, 36.63), (36.70, 36.67), (36.65, 36.83), (36.55, 36.27),
|
|
31
|
+
(36.07, 35.90), (35.92, 35.90), (35.95, 36.08), (35.88, 36.40), (36.17, 36.60),
|
|
32
|
+
(36.20, 36.85), (35.79, 36.77), (35.38, 36.57), (34.63, 36.80), (34.30, 36.60),
|
|
33
|
+
(33.88, 36.32), (33.30, 36.14), (32.80, 36.02), (32.30, 36.27), (32.00, 36.54),
|
|
34
|
+
(31.45, 36.75), (30.70, 36.88), (30.57, 36.60), (30.47, 36.30), (30.15, 36.30),
|
|
35
|
+
(29.64, 36.20), (29.30, 36.25), (29.10, 36.63), (28.80, 36.70), (28.27, 36.85),
|
|
36
|
+
(28.05, 36.68), (27.40, 36.70), (27.43, 37.03), (27.60, 37.24), (27.27, 37.38),
|
|
37
|
+
(27.25, 37.86), (26.85, 38.18), (26.30, 38.32), (26.50, 38.65), (26.75, 38.67),
|
|
38
|
+
(26.88, 39.07), (26.68, 39.32), (26.60, 39.55), (26.07, 39.48), (25.95, 39.85),
|
|
39
|
+
(25.65, 40.10), (25.65, 40.28),
|
|
40
|
+
) # fmt: skip
|
|
41
|
+
|
|
42
|
+
# Province centres (lon, lat).
|
|
43
|
+
PROVINCES: tuple[tuple[str, float, float], ...] = (
|
|
44
|
+
("Adana", 35.32, 37.00), ("Adıyaman", 38.28, 37.76), ("Afyonkarahisar", 30.54, 38.76),
|
|
45
|
+
("Ağrı", 43.05, 39.72), ("Aksaray", 34.03, 38.37), ("Amasya", 35.83, 40.65),
|
|
46
|
+
("Ankara", 32.85, 39.93), ("Antalya", 30.70, 36.89), ("Ardahan", 42.70, 41.11),
|
|
47
|
+
("Artvin", 41.82, 41.18), ("Aydın", 27.84, 37.85), ("Balıkesir", 27.88, 39.65),
|
|
48
|
+
("Bartın", 32.34, 41.63), ("Batman", 41.13, 37.89), ("Bayburt", 40.23, 40.26),
|
|
49
|
+
("Bilecik", 29.98, 40.14), ("Bingöl", 40.50, 38.88), ("Bitlis", 42.11, 38.40),
|
|
50
|
+
("Bolu", 31.61, 40.74), ("Burdur", 30.29, 37.72), ("Bursa", 29.06, 40.19),
|
|
51
|
+
("Çanakkale", 26.41, 40.15), ("Çankırı", 33.62, 40.60), ("Çorum", 34.95, 40.55),
|
|
52
|
+
("Denizli", 29.09, 37.78), ("Diyarbakır", 40.22, 37.91), ("Düzce", 31.16, 40.84),
|
|
53
|
+
("Edirne", 26.56, 41.68), ("Elazığ", 39.22, 38.68), ("Erzincan", 39.49, 39.75),
|
|
54
|
+
("Erzurum", 41.27, 39.90), ("Eskişehir", 30.52, 39.78), ("Gaziantep", 37.38, 37.07),
|
|
55
|
+
("Giresun", 38.39, 40.91), ("Gümüşhane", 39.48, 40.46), ("Hakkari", 43.74, 37.58),
|
|
56
|
+
("Hatay", 36.16, 36.20), ("Iğdır", 44.04, 39.92), ("Isparta", 30.55, 37.76),
|
|
57
|
+
("İstanbul", 28.98, 41.01), ("İzmir", 27.14, 38.42), ("Kahramanmaraş", 36.94, 37.58),
|
|
58
|
+
("Karabük", 32.62, 41.20), ("Karaman", 33.22, 37.18), ("Kars", 43.10, 40.60),
|
|
59
|
+
("Kastamonu", 33.78, 41.38), ("Kayseri", 35.49, 38.72), ("Kilis", 37.12, 36.72),
|
|
60
|
+
("Kırıkkale", 33.52, 39.85), ("Kırklareli", 27.23, 41.73), ("Kırşehir", 34.17, 39.15),
|
|
61
|
+
("Kocaeli", 29.92, 40.77), ("Konya", 32.48, 37.87), ("Kütahya", 29.98, 39.42),
|
|
62
|
+
("Malatya", 38.31, 38.35), ("Manisa", 27.43, 38.61), ("Mardin", 40.74, 37.31),
|
|
63
|
+
("Mersin", 34.64, 36.81), ("Muğla", 28.36, 37.22), ("Muş", 41.49, 38.74),
|
|
64
|
+
("Nevşehir", 34.71, 38.62), ("Niğde", 34.68, 37.97), ("Ordu", 37.88, 40.98),
|
|
65
|
+
("Osmaniye", 36.25, 37.07), ("Rize", 40.52, 41.02), ("Sakarya", 30.40, 40.78),
|
|
66
|
+
("Samsun", 36.33, 41.29), ("Siirt", 41.94, 37.93), ("Sinop", 35.15, 42.03),
|
|
67
|
+
("Sivas", 37.02, 39.75), ("Şanlıurfa", 38.79, 37.16), ("Şırnak", 42.46, 37.52),
|
|
68
|
+
("Tekirdağ", 27.51, 40.98), ("Tokat", 36.55, 40.31), ("Trabzon", 39.72, 41.00),
|
|
69
|
+
("Tunceli", 39.55, 39.11), ("Uşak", 29.40, 38.68), ("Van", 43.38, 38.50),
|
|
70
|
+
("Yalova", 29.27, 40.65), ("Yozgat", 34.81, 39.82), ("Zonguldak", 31.79, 41.45),
|
|
71
|
+
) # fmt: skip
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _point_in_polygon(lon: float, lat: float) -> bool:
|
|
75
|
+
"""Even-odd ray casting against :data:`TURKIYE_OUTLINE`."""
|
|
76
|
+
inside = False
|
|
77
|
+
pts = TURKIYE_OUTLINE
|
|
78
|
+
j = len(pts) - 1
|
|
79
|
+
for i in range(len(pts)):
|
|
80
|
+
xi, yi = pts[i]
|
|
81
|
+
xj, yj = pts[j]
|
|
82
|
+
if (yi > lat) != (yj > lat) and lon < (xj - xi) * (lat - yi) / (yj - yi) + xi:
|
|
83
|
+
inside = not inside
|
|
84
|
+
j = i
|
|
85
|
+
return inside
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _distance_to_outline_deg(lon: float, lat: float) -> float:
|
|
89
|
+
"""Shortest distance (in degrees of latitude) from a point to the outline edges."""
|
|
90
|
+
scale = math.cos(math.radians(lat))
|
|
91
|
+
px, py = lon * scale, lat
|
|
92
|
+
best = math.inf
|
|
93
|
+
pts = TURKIYE_OUTLINE
|
|
94
|
+
for i in range(len(pts)):
|
|
95
|
+
ax, ay = pts[i - 1][0] * scale, pts[i - 1][1]
|
|
96
|
+
bx, by = pts[i][0] * scale, pts[i][1]
|
|
97
|
+
dx, dy = bx - ax, by - ay
|
|
98
|
+
t = ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)
|
|
99
|
+
t = min(1.0, max(0.0, t))
|
|
100
|
+
best = min(best, math.hypot(px - ax - t * dx, py - ay - t * dy))
|
|
101
|
+
return best
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def in_turkiye(lon: float, lat: float, buffer_deg: float = OUTLINE_BUFFER_DEG) -> bool:
|
|
105
|
+
"""True when ``(lon, lat)`` lies in Türkiye or within *buffer_deg* of its outline."""
|
|
106
|
+
if not (24.5 <= lon <= 46.0 and 35.0 <= lat <= 43.0):
|
|
107
|
+
return False
|
|
108
|
+
return _point_in_polygon(lon, lat) or _distance_to_outline_deg(lon, lat) <= buffer_deg
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def distance_km(lon1: float, lat1: float, lon2: float, lat2: float) -> float:
|
|
112
|
+
"""Great-circle distance on a sphere of radius 6 371 km."""
|
|
113
|
+
p1, p2 = math.radians(lat1), math.radians(lat2)
|
|
114
|
+
dl = math.radians(lon2 - lon1)
|
|
115
|
+
h = math.sin((p2 - p1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
|
|
116
|
+
return 2 * 6371.0 * math.asin(min(1.0, math.sqrt(h)))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def nearest_province(lon: float, lat: float) -> tuple[str, float]:
|
|
120
|
+
"""``(name, distance_km)`` of the province centre closest to ``(lon, lat)``."""
|
|
121
|
+
name, plon, plat = min(PROVINCES, key=lambda p: distance_km(lon, lat, p[1], p[2]))
|
|
122
|
+
return name, distance_km(lon, lat, plon, plat)
|
turkgrid/cli.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""Command line interface: ``turkgrid convert | detect | geojson | info``.
|
|
2
|
+
|
|
3
|
+
Examples::
|
|
4
|
+
|
|
5
|
+
turkgrid convert --from 5254 --to 4326 465000 4545000
|
|
6
|
+
echo "465000 4545000" | turkgrid convert --from 5254 --to 2320
|
|
7
|
+
turkgrid detect points.csv
|
|
8
|
+
turkgrid geojson plan.geojson --from 5254 --to 4326 -o plan_wgs84.geojson
|
|
9
|
+
turkgrid info 5254
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import csv
|
|
16
|
+
import io
|
|
17
|
+
import json
|
|
18
|
+
import re
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Optional, Sequence, TextIO
|
|
22
|
+
|
|
23
|
+
from . import __version__
|
|
24
|
+
from .crs import epsg_info, supported_epsg_codes
|
|
25
|
+
from .detect import detect_crs
|
|
26
|
+
from .geojson import reproject_geojson
|
|
27
|
+
from .transformer import get_transformer
|
|
28
|
+
|
|
29
|
+
_NUMBER = re.compile(r"^[+-]?(\d+([.,]\d*)?|[.,]\d+)([eE][+-]?\d+)?$")
|
|
30
|
+
_X_NAMES = ("x", "easting", "east", "e", "saga", "sağa", "lon", "lng", "longitude", "boylam")
|
|
31
|
+
_Y_NAMES = ("y", "northing", "north", "n", "yukari", "yukarı", "lat", "latitude", "enlem")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _epsg_arg(value: str) -> int:
|
|
35
|
+
"""argparse type: a supported EPSG reference."""
|
|
36
|
+
try:
|
|
37
|
+
return epsg_info(value).epsg
|
|
38
|
+
except ValueError as exc:
|
|
39
|
+
raise argparse.ArgumentTypeError(str(exc)) from None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _to_float(text: str) -> float:
|
|
43
|
+
"""Parse a number, accepting a decimal comma."""
|
|
44
|
+
return float(text.strip().replace(",", "."))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _format(value: float, precision: int) -> str:
|
|
48
|
+
return f"{value:.{precision}f}"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _convert(args: argparse.Namespace, stdin: TextIO, stdout: TextIO) -> int:
|
|
52
|
+
transformer = get_transformer(args.src, args.dst)
|
|
53
|
+
precision = args.precision
|
|
54
|
+
if precision is None:
|
|
55
|
+
precision = 8 if transformer.target.is_geographic else 3
|
|
56
|
+
if args.coords:
|
|
57
|
+
if len(args.coords) % 2:
|
|
58
|
+
print("error: give x y pairs", file=sys.stderr)
|
|
59
|
+
return 2
|
|
60
|
+
rows = [args.coords[i : i + 2] for i in range(0, len(args.coords), 2)]
|
|
61
|
+
else:
|
|
62
|
+
rows = [re.split(r"[\s,;]+", line.strip()) for line in stdin if line.strip()]
|
|
63
|
+
status = 0
|
|
64
|
+
for row in rows:
|
|
65
|
+
try:
|
|
66
|
+
values = [_to_float(v) for v in row]
|
|
67
|
+
if len(values) < 2:
|
|
68
|
+
raise ValueError("need at least two numbers")
|
|
69
|
+
x, y = (values[1], values[0]) if args.swap_input else (values[0], values[1])
|
|
70
|
+
rx, ry = transformer.transform_xy(x, y)
|
|
71
|
+
except ValueError as exc:
|
|
72
|
+
print(f"error: {' '.join(row)}: {exc}", file=sys.stderr)
|
|
73
|
+
status = 1
|
|
74
|
+
continue
|
|
75
|
+
out = [ry, rx] if args.swap_output else [rx, ry]
|
|
76
|
+
extra = [str(v) for v in row[2:]]
|
|
77
|
+
print(" ".join([_format(v, precision) for v in out] + extra), file=stdout)
|
|
78
|
+
return status
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _read_table(text: str, delimiter: Optional[str]) -> list[list[str]]:
|
|
82
|
+
"""Split CSV/TXT text into rows, sniffing the delimiter when not given."""
|
|
83
|
+
lines = [line for line in text.splitlines() if line.strip() and not line.startswith("#")]
|
|
84
|
+
if not lines:
|
|
85
|
+
return []
|
|
86
|
+
if delimiter is None:
|
|
87
|
+
sample = "\n".join(lines[:20])
|
|
88
|
+
try:
|
|
89
|
+
delimiter = csv.Sniffer().sniff(sample, delimiters=";,\t |").delimiter
|
|
90
|
+
except csv.Error:
|
|
91
|
+
delimiter = None
|
|
92
|
+
if delimiter is None or delimiter == " ":
|
|
93
|
+
return [line.split() for line in lines]
|
|
94
|
+
reader = csv.reader(io.StringIO("\n".join(lines)), delimiter=delimiter)
|
|
95
|
+
return [[cell.strip() for cell in row] for row in reader]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _pick_columns(
|
|
99
|
+
rows: list[list[str]], x_col: Optional[str], y_col: Optional[str]
|
|
100
|
+
) -> tuple[list[list[str]], int, int]:
|
|
101
|
+
"""Return the data rows and the indexes of the x and y columns."""
|
|
102
|
+
header: Optional[list[str]] = None
|
|
103
|
+
if rows and not all(_NUMBER.match(c) for c in rows[0] if c):
|
|
104
|
+
header, rows = [c.lower() for c in rows[0]], rows[1:]
|
|
105
|
+
|
|
106
|
+
def resolve(spec: Optional[str], names: Sequence[str]) -> Optional[int]:
|
|
107
|
+
if spec is not None:
|
|
108
|
+
if spec.isdigit():
|
|
109
|
+
return int(spec)
|
|
110
|
+
if header is not None and spec.lower() in header:
|
|
111
|
+
return header.index(spec.lower())
|
|
112
|
+
raise ValueError(f"column {spec!r} not found")
|
|
113
|
+
if header is not None:
|
|
114
|
+
for name in names:
|
|
115
|
+
if name in header:
|
|
116
|
+
return header.index(name)
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
xi, yi = resolve(x_col, _X_NAMES), resolve(y_col, _Y_NAMES)
|
|
120
|
+
if xi is None or yi is None:
|
|
121
|
+
width = max((len(r) for r in rows), default=0)
|
|
122
|
+
numeric = [
|
|
123
|
+
i
|
|
124
|
+
for i in range(width)
|
|
125
|
+
if sum(1 for r in rows if i < len(r) and _NUMBER.match(r[i])) > len(rows) / 2
|
|
126
|
+
]
|
|
127
|
+
# Use the last two mostly-numeric columns: point-id columns usually come first.
|
|
128
|
+
numeric = [i for i in numeric if i not in (xi, yi)]
|
|
129
|
+
if xi is None and yi is None and len(numeric) >= 2:
|
|
130
|
+
xi, yi = numeric[-2], numeric[-1]
|
|
131
|
+
elif xi is None and yi is not None and numeric:
|
|
132
|
+
before = [i for i in numeric if i < yi]
|
|
133
|
+
xi = before[-1] if before else numeric[0]
|
|
134
|
+
elif yi is None and xi is not None and numeric:
|
|
135
|
+
after = [i for i in numeric if i > xi]
|
|
136
|
+
yi = after[0] if after else numeric[-1]
|
|
137
|
+
if xi is None or yi is None:
|
|
138
|
+
raise ValueError("could not find two numeric coordinate columns; use --x-col/--y-col")
|
|
139
|
+
return rows, xi, yi
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _detect(args: argparse.Namespace, stdin: TextIO, stdout: TextIO) -> int:
|
|
143
|
+
text = stdin.read() if args.file == "-" else Path(args.file).read_text(encoding="utf-8-sig")
|
|
144
|
+
try:
|
|
145
|
+
rows, xi, yi = _pick_columns(_read_table(text, args.delimiter), args.x_col, args.y_col)
|
|
146
|
+
except ValueError as exc:
|
|
147
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
148
|
+
return 2
|
|
149
|
+
points = []
|
|
150
|
+
for row in rows:
|
|
151
|
+
try:
|
|
152
|
+
points.append((_to_float(row[xi]), _to_float(row[yi])))
|
|
153
|
+
except (ValueError, IndexError):
|
|
154
|
+
continue
|
|
155
|
+
if not points:
|
|
156
|
+
print("error: no numeric coordinates found", file=sys.stderr)
|
|
157
|
+
return 2
|
|
158
|
+
near = None
|
|
159
|
+
if args.near:
|
|
160
|
+
lon_text, lat_text = args.near.split(",")
|
|
161
|
+
near = (float(lon_text), float(lat_text))
|
|
162
|
+
found = detect_crs(points, near=near, near_tolerance_m=args.tolerance)[: args.top]
|
|
163
|
+
if args.json:
|
|
164
|
+
payload = [
|
|
165
|
+
{
|
|
166
|
+
"epsg": c.epsg,
|
|
167
|
+
"name": c.name,
|
|
168
|
+
"score": c.score,
|
|
169
|
+
"axes_swapped": c.axes_swapped,
|
|
170
|
+
"centroid": list(c.centroid),
|
|
171
|
+
"place": c.place,
|
|
172
|
+
"reasons": list(c.reasons),
|
|
173
|
+
}
|
|
174
|
+
for c in found
|
|
175
|
+
]
|
|
176
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2), file=stdout)
|
|
177
|
+
return 0 if found else 1
|
|
178
|
+
if not found:
|
|
179
|
+
print("no plausible Turkish CRS found", file=stdout)
|
|
180
|
+
return 1
|
|
181
|
+
print(f"{len(points)} points; columns {xi} (x) and {yi} (y)", file=stdout)
|
|
182
|
+
for c in found:
|
|
183
|
+
swap = " [axes swapped]" if c.axes_swapped else ""
|
|
184
|
+
print(f"{c.score:5.2f} EPSG:{c.epsg:<6} {c.name}{swap} ~ {c.place}", file=stdout)
|
|
185
|
+
if args.verbose:
|
|
186
|
+
for reason in c.reasons:
|
|
187
|
+
print(f" - {reason}", file=stdout)
|
|
188
|
+
return 0
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _geojson(args: argparse.Namespace, stdin: TextIO, stdout: TextIO) -> int:
|
|
192
|
+
text = stdin.read() if args.input == "-" else Path(args.input).read_text(encoding="utf-8-sig")
|
|
193
|
+
try:
|
|
194
|
+
result = reproject_geojson(
|
|
195
|
+
json.loads(text),
|
|
196
|
+
args.dst,
|
|
197
|
+
args.src,
|
|
198
|
+
axes_swapped=args.swap_input,
|
|
199
|
+
precision=args.precision,
|
|
200
|
+
)
|
|
201
|
+
except ValueError as exc:
|
|
202
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
203
|
+
return 1
|
|
204
|
+
output = json.dumps(result, ensure_ascii=False, indent=args.indent)
|
|
205
|
+
if args.output:
|
|
206
|
+
Path(args.output).write_text(output + "\n", encoding="utf-8")
|
|
207
|
+
else:
|
|
208
|
+
print(output, file=stdout)
|
|
209
|
+
return 0
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _info(args: argparse.Namespace, stdout: TextIO) -> int:
|
|
213
|
+
codes = [args.code] if args.code is not None else supported_epsg_codes()
|
|
214
|
+
for code in codes:
|
|
215
|
+
info = epsg_info(code)
|
|
216
|
+
if args.code is None:
|
|
217
|
+
print(f"EPSG:{info.epsg:<6} {info.name}", file=stdout)
|
|
218
|
+
continue
|
|
219
|
+
print(f"EPSG:{info.epsg} {info.name}", file=stdout)
|
|
220
|
+
print(f" family: {info.family}", file=stdout)
|
|
221
|
+
print(f" datum: {info.datum.name} ({info.datum.ellipsoid.name})", file=stdout)
|
|
222
|
+
if info.central_meridian is not None:
|
|
223
|
+
print(
|
|
224
|
+
f" CM {info.central_meridian:g}E k0 {info.scale_factor:g} "
|
|
225
|
+
f"FE {info.false_easting:.0f} FN {info.false_northing:.0f}",
|
|
226
|
+
file=stdout,
|
|
227
|
+
)
|
|
228
|
+
print(f" area: {info.area}", file=stdout)
|
|
229
|
+
print(f" proj4: {info.to_proj4()}", file=stdout)
|
|
230
|
+
return 0
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
234
|
+
"""The argument parser (exposed for documentation tools)."""
|
|
235
|
+
parser = argparse.ArgumentParser(
|
|
236
|
+
prog="turkgrid",
|
|
237
|
+
description="Coordinate conversion and CRS detection for Türkiye (TUREF, ED50, UTM).",
|
|
238
|
+
)
|
|
239
|
+
parser.add_argument("--version", action="version", version=f"turkgrid {__version__}")
|
|
240
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
241
|
+
|
|
242
|
+
conv = sub.add_parser("convert", help="convert coordinates between EPSG codes")
|
|
243
|
+
conv.add_argument("--from", dest="src", type=_epsg_arg, required=True, help="source EPSG")
|
|
244
|
+
conv.add_argument("--to", dest="dst", type=_epsg_arg, required=True, help="target EPSG")
|
|
245
|
+
conv.add_argument(
|
|
246
|
+
"coords", nargs="*", help="x y pairs; read from stdin (one point per line) if omitted"
|
|
247
|
+
)
|
|
248
|
+
conv.add_argument("--swap-input", action="store_true", help="input is northing/lat first")
|
|
249
|
+
conv.add_argument("--swap-output", action="store_true", help="write northing/lat first")
|
|
250
|
+
conv.add_argument("--precision", type=int, default=None, help="decimals (default 8 / 3)")
|
|
251
|
+
|
|
252
|
+
det = sub.add_parser("detect", help="guess the CRS of a CSV/TXT point file")
|
|
253
|
+
det.add_argument("file", help="CSV or whitespace-separated file ('-' for stdin)")
|
|
254
|
+
det.add_argument("--x-col", help="x column name or 0-based index")
|
|
255
|
+
det.add_argument("--y-col", help="y column name or 0-based index")
|
|
256
|
+
det.add_argument("--delimiter", help="field delimiter (sniffed by default)")
|
|
257
|
+
det.add_argument("--near", help="known location 'lon,lat' (WGS 84) to break ties")
|
|
258
|
+
det.add_argument("--tolerance", type=float, default=25_000.0, help="near tolerance (m)")
|
|
259
|
+
det.add_argument("--top", type=int, default=10, help="number of candidates to show")
|
|
260
|
+
det.add_argument("--json", action="store_true", help="machine-readable output")
|
|
261
|
+
det.add_argument("-v", "--verbose", action="store_true", help="print the reasons")
|
|
262
|
+
|
|
263
|
+
gj = sub.add_parser("geojson", help="reproject a GeoJSON file")
|
|
264
|
+
gj.add_argument("input", help="GeoJSON file ('-' for stdin)")
|
|
265
|
+
gj.add_argument("--to", dest="dst", type=_epsg_arg, default=4326, help="target EPSG")
|
|
266
|
+
gj.add_argument(
|
|
267
|
+
"--from", dest="src", type=_epsg_arg, default=None, help="source EPSG (default: crs member)"
|
|
268
|
+
)
|
|
269
|
+
gj.add_argument("-o", "--output", help="output file (default stdout)")
|
|
270
|
+
gj.add_argument("--swap-input", action="store_true", help="positions are northing first")
|
|
271
|
+
gj.add_argument("--precision", type=int, default=None, help="decimals (default 8 / 3)")
|
|
272
|
+
gj.add_argument("--indent", type=int, default=None, help="JSON indentation")
|
|
273
|
+
|
|
274
|
+
inf = sub.add_parser("info", help="list supported EPSG codes or describe one")
|
|
275
|
+
inf.add_argument("code", nargs="?", type=_epsg_arg, help="EPSG code")
|
|
276
|
+
return parser
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def main(
|
|
280
|
+
argv: Optional[Sequence[str]] = None,
|
|
281
|
+
stdin: Optional[TextIO] = None,
|
|
282
|
+
stdout: Optional[TextIO] = None,
|
|
283
|
+
) -> int:
|
|
284
|
+
"""Entry point of the ``turkgrid`` command; returns the exit status."""
|
|
285
|
+
args = build_parser().parse_args(argv)
|
|
286
|
+
stdin = stdin if stdin is not None else sys.stdin
|
|
287
|
+
if stdout is None:
|
|
288
|
+
stdout = sys.stdout
|
|
289
|
+
reconfigure = getattr(stdout, "reconfigure", None)
|
|
290
|
+
if reconfigure is not None: # keep Turkish place names printable on legacy consoles
|
|
291
|
+
reconfigure(errors="replace")
|
|
292
|
+
if args.command == "convert":
|
|
293
|
+
return _convert(args, stdin, stdout)
|
|
294
|
+
if args.command == "detect":
|
|
295
|
+
return _detect(args, stdin, stdout)
|
|
296
|
+
if args.command == "geojson":
|
|
297
|
+
return _geojson(args, stdin, stdout)
|
|
298
|
+
return _info(args, stdout)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
if __name__ == "__main__": # pragma: no cover
|
|
302
|
+
sys.exit(main())
|