Repository navigation
Expand file tree
/
Copy pathfetch_cables.py
More file actions
185 lines (165 loc) · 7.08 KB
/
Copy pathfetch_cables.py
File metadata and controls
185 lines (165 loc) · 7.08 KB
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
"""
H@N Submarine Cable Fetcher
Builds cables.json (submarine telecom cables) for the hackatnight.com globe from OpenStreetMap via the
Overpass API. Data (c) OpenStreetMap contributors, licensed under the ODbL (https://www.openstreetmap.org/copyright);
the site shows that attribution whenever cables are drawn.
Runs from the telemetry workflow but only refetches once a day. Keeps the previous file on any failure.
"""
import json
import math
import os
import sys
import time
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone
OUTPUT = "cables.json"
MAX_AGE = timedelta(hours=23)
ENDPOINTS = ["https://overpass-api.de/api/interpreter", "https://overpass.private.coffee/api/interpreter",
"https://overpass.kumi.systems/api/interpreter"]
QUERY = """
[out:json][timeout:110];
(
way["communication"="line"]["submarine"="yes"];
way["communication"="line"]["location"~"^(underwater|submarine)$"];
way["telecom"="line"]["submarine"="yes"];
way["telecom"="line"]["location"~"^(underwater|submarine)$"];
way["seamark:type"="cable_submarine"]["seamark:cable_submarine:category"~"tele|communication",i];
);
out tags geom;
"""
# US fiber on land (not underwater), only runs of 20 km or more; lower 48 bounding box
LAND_QUERY = """
[out:json][timeout:110];
(
way["communication"="line"]["location"!~"^(underwater|submarine)$"]["submarine"!="yes"](if: length() > 20000)(24.3,-125.0,49.5,-66.8);
way["telecom"="line"]["location"!~"^(underwater|submarine)$"]["submarine"!="yes"](if: length() > 20000)(24.3,-125.0,49.5,-66.8);
);
out tags geom;
"""
UA = "H@N-Cable-Map/1.1 (+https://hackatnight.com)"
def now():
return datetime.now(timezone.utc)
def dp(pts, tol):
"""Douglas-Peucker line simplification (degrees)."""
if len(pts) < 3:
return pts
ax, ay = pts[0]
bx, by = pts[-1]
dx, dy = bx - ax, by - ay
norm = math.hypot(dx, dy) or 1e-12
dmax, idx = 0.0, 0
for i in range(1, len(pts) - 1):
px, py = pts[i]
d = abs(dy * px - dx * py + bx * ay - by * ax) / norm if (dx or dy) else math.hypot(px - ax, py - ay)
if d > dmax:
dmax, idx = d, i
if dmax > tol:
return dp(pts[: idx + 1], tol)[:-1] + dp(pts[idx:], tol)
return [pts[0], pts[-1]]
def length_km(pts):
total = 0.0
for (x1, y1), (x2, y2) in zip(pts, pts[1:]):
p1, p2 = math.radians(y1), math.radians(y2)
dl = math.radians(x2 - x1)
c = math.sin(p1) * math.sin(p2) + math.cos(p1) * math.cos(p2) * math.cos(dl)
total += 6371 * math.acos(max(-1.0, min(1.0, c)))
return total
def overpass(query, label):
for url in ENDPOINTS:
try:
req = urllib.request.Request(url, data=urllib.parse.urlencode({"data": query}).encode(),
headers={"User-Agent": UA})
with urllib.request.urlopen(req, timeout=120) as res:
data = json.loads(res.read().decode("utf-8"))
print(f"[cables] {label} via {url}: {len(data.get('elements', []))} ways")
return data
except Exception as e:
print(f"[cables] {label} via {url} failed: {e}")
time.sleep(5)
return None
def land_lines(data):
out = []
for el in (data or {}).get("elements", []):
pts = [(round(g["lon"], 3), round(g["lat"], 3)) for g in (el.get("geometry") or []) if "lon" in g]
if len(pts) < 2:
continue
tags = el.get("tags") or {}
s = dp(pts, 0.02)
out.append({"n": (tags.get("name") or "").strip()[:80], "op": (tags.get("operator") or tags.get("owner") or "").strip()[:80],
"km": int(length_km(pts)), "p": [[round(x, 2), round(y, 2)] for x, y in s]})
return out
def main():
previous = None
if os.path.exists(OUTPUT):
try:
with open(OUTPUT, encoding="utf-8") as f:
previous = json.load(f)
updated = datetime.strptime(previous.get("updated", ""), "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
if now() - updated < MAX_AGE and "land" in previous and not os.environ.get("CABLES_FORCE"):
print("[cables] fetched within the last day, skipping")
return 0
except Exception:
pass
data = overpass(QUERY, "submarine")
land_data = overpass(LAND_QUERY, "US land")
if not data and not land_data:
print("[cables] all endpoints failed; keeping previous file (retries next run)")
return 0
if not data:
# Undersea query failed but the land one worked: keep the previous undersea set, update land only
if not previous or not previous.get("cables"):
return 0
previous["land"] = land_lines(land_data)
with open(OUTPUT, "w", encoding="utf-8") as f:
json.dump(previous, f, separators=(",", ":"), ensure_ascii=False)
print(f"[cables] undersea fetch failed; updated US land only ({len(previous['land'])} lines)")
return 0
# Group segments by cable name; unnamed bits are kept only if they are long (real cable spans)
groups = {}
for el in data.get("elements", []):
geom = el.get("geometry") or []
pts = [(round(g["lon"], 3), round(g["lat"], 3)) for g in geom if "lon" in g and "lat" in g]
if len(pts) < 2:
continue
tags = el.get("tags") or {}
name = (tags.get("name") or tags.get("name:en") or tags.get("seamark:name") or "").strip()
km = length_km(pts)
if not name and km < 150:
continue
key = name or f"Unnamed cable {el.get('id')}"
g = groups.setdefault(key, {"n": key, "op": "", "km": 0.0, "lines": []})
if not g["op"]:
g["op"] = (tags.get("operator") or tags.get("owner") or "").strip()[:80]
g["km"] += km
g["lines"].append(pts)
cables, total_pts = [], 0
for g in sorted(groups.values(), key=lambda x: -x["km"]):
if g["km"] < 20:
continue
lines = []
for pts in g["lines"]:
s = dp(pts, 0.03)
if len(s) >= 2:
lines.append([[round(x, 2), round(y, 2)] for x, y in s])
if not lines:
continue
total_pts += sum(len(l) for l in lines)
cables.append({"n": g["n"][:80], "op": g["op"], "km": int(g["km"]), "p": lines})
if len(cables) < 20:
print(f"[cables] only {len(cables)} cables parsed; keeping previous file")
return 0
out = {
"source": "OpenStreetMap contributors (ODbL), https://www.openstreetmap.org/copyright",
"updated": now().strftime("%Y-%m-%dT%H:%M:%SZ"),
"count": len(cables),
"cables": cables,
# Keep the previous land set if this run's land query failed
"land": land_lines(land_data) if land_data else (previous or {}).get("land", []),
}
with open(OUTPUT, "w", encoding="utf-8") as f:
json.dump(out, f, separators=(",", ":"), ensure_ascii=False)
print(f"[cables] wrote {OUTPUT}: {len(cables)} cables, {total_pts} points, {len(out['land'])} US land lines, {os.path.getsize(OUTPUT) // 1024} KB")
return 0
if __name__ == "__main__":
sys.exit(main())