Matthias Nott
2 days ago 9d577bcc3774a70d7dfb53cb9ba68a995dfb208b
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
#!/usr/bin/env python3
"""
Generate enhanced Swiss ICAO chart maps with scale bars, location circles,
and route lines for Glidr exam questions.
Only processes confirmed geographic ICAO chart maps in subjects 10, 30, 60.
"""
import os
import math
import urllib.request
from PIL import Image, ImageDraw, ImageFont
import io
# ── paths ──────────────────────────────────────────────────────────────────
BASE = "/Users/i052341/Daten/Cloud/04 - Ablage/Ablage 2020 - 2029/Ablage 2025/Hobbies 2025/Segelflug/Theorie/Glidr"
DIRS = {
    "FR": os.path.join(BASE, "SPL Exam Questions FR/figures"),
    "EN": os.path.join(BASE, "SPL Exam Questions EN/figures"),
    "DE": os.path.join(BASE, "SPL Exam Questions DE/figures"),
}
WMS_URL = (
    "https://wms.geo.admin.ch/?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap"
    "&LAYERS=ch.bazl.luftfahrtkarten-icao"
    "&CRS=EPSG:4326"
    "&BBOX={lat_min},{lon_min},{lat_max},{lon_max}"
    "&WIDTH=1200&HEIGHT=900&FORMAT=image/png"
)
W, H = 1200, 900
# ── helpers ────────────────────────────────────────────────────────────────
def fetch_wms(lat_min, lon_min, lat_max, lon_max):
    url = WMS_URL.format(
        lat_min=lat_min, lon_min=lon_min,
        lat_max=lat_max, lon_max=lon_max
    )
    print(f"  Fetching WMS bbox=({lat_min},{lon_min},{lat_max},{lon_max}) ...", end="", flush=True)
    req = urllib.request.Request(url, headers={"User-Agent": "GlidrMapGen/1.0"})
    with urllib.request.urlopen(req, timeout=30) as resp:
        data = resp.read()
    img = Image.open(io.BytesIO(data)).convert("RGBA")
    print(f" {img.size[0]}x{img.size[1]}")
    return img
def ll_to_px(lat, lon, lat_min, lon_min, lat_max, lon_max, w=W, h=H):
    px = (lon - lon_min) / (lon_max - lon_min) * w
    py = (1 - (lat - lat_min) / (lat_max - lat_min)) * h
    return int(round(px)), int(round(py))
def draw_circle(draw, cx, cy, r=40, color="red", width=4):
    draw.ellipse([cx - r, cy - r, cx + r, cy + r], outline=color, width=width)
def draw_route(draw, points_px, color="red", width=4):
    if len(points_px) >= 2:
        draw.line(points_px, fill=color, width=width)
def draw_scale_bar(draw, lat_min, lon_min, lat_max, lon_max,
                   km=20, x=40, y=None, w=W, h=H):
    """Draw a scale bar in bottom-left corner."""
    if y is None:
        y = h - 50
    center_lat = (lat_min + lat_max) / 2
    km_per_deg_lon = 111.32 * math.cos(math.radians(center_lat))
    km_per_deg_lat = 111.32
    # use longitude span for the bar width
    deg_per_km = 1.0 / km_per_deg_lon
    bar_px = int(km * deg_per_km / (lon_max - lon_min) * w)
    if bar_px < 10:
        bar_px = 10
    half = bar_px // 2
    # white background
    pad = 8
    draw.rectangle([x - pad, y - 16, x + bar_px + pad, y + 24], fill="white")
    # left half black, right half white with border
    draw.rectangle([x, y, x + half, y + 12], fill="black", outline="black")
    draw.rectangle([x + half, y, x + bar_px, y + 12], fill="white", outline="black")
    # tick marks
    draw.line([(x, y - 4), (x, y + 12)], fill="black", width=2)
    draw.line([(x + half, y - 4), (x + half, y + 12)], fill="black", width=2)
    draw.line([(x + bar_px, y - 4), (x + bar_px, y + 12)], fill="black", width=2)
    # labels
    try:
        font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 14)
        font_sm = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 12)
    except Exception:
        font = ImageFont.load_default()
        font_sm = font
    draw.text((x - 2, y + 14), "0", fill="black", font=font_sm)
    draw.text((x + half - 8, y + 14), f"{km//2}", fill="black", font=font_sm)
    draw.text((x + bar_px - 4, y + 14), f"{km}", fill="black", font=font_sm)
    draw.text((x + bar_px + 6, y + 4), "km", fill="black", font=font)
def save_to_all_langs(img, filename):
    """Save PNG to FR, EN and DE figures directories."""
    # convert to RGB for saving as PNG (remove alpha if any)
    if img.mode == "RGBA":
        bg = Image.new("RGB", img.size, (255, 255, 255))
        bg.paste(img, mask=img.split()[3])
        img_save = bg
    else:
        img_save = img.convert("RGB")
    for lang, d in DIRS.items():
        out = os.path.join(d, filename)
        img_save.save(out, "PNG")
        print(f"    Saved → {out}")
def make_map(tag, lat_min, lon_min, lat_max, lon_max,
             circles=None, routes=None, scale_km=20, note=""):
    """
    Generate one map image with circles, optional route lines, and scale bar.
    circles: list of (lat, lon)
    routes: list of [(lat, lon), (lat, lon), ...]  — each route is a polyline
    """
    print(f"\n[{tag}] {note}")
    img = fetch_wms(lat_min, lon_min, lat_max, lon_max)
    draw = ImageDraw.Draw(img)
    # draw route lines first (under circles)
    if routes:
        for route in routes:
            pts = [ll_to_px(lat, lon, lat_min, lon_min, lat_max, lon_max)
                   for lat, lon in route]
            draw_route(draw, pts, color="red", width=4)
    # draw circles
    if circles:
        for lat, lon in circles:
            cx, cy = ll_to_px(lat, lon, lat_min, lon_min, lat_max, lon_max)
            draw_circle(draw, cx, cy, r=40, color="red", width=4)
    # scale bar
    draw_scale_bar(draw, lat_min, lon_min, lat_max, lon_max, km=scale_km)
    filename = f"{tag}.png"
    save_to_all_langs(img, filename)
    return True
# ── map definitions ────────────────────────────────────────────────────────
# Each entry: tag, bbox, circles [(lat,lon)], routes [[(lat,lon),...]], scale_km, note
#
# Aspect ratio rule: lon_span / lat_span ≈ 1.333 (= 1200/900)
# BUT we also need lon_span / lat_span * cos(lat) ≈ 1.333 to avoid stretching
# At lat=47: km_per_deg_lon = 111.32*cos(47°) ≈ 75.95
# km_per_deg_lat = 111.32
# So for equal-area: lon_span / lat_span = (111.32 / 75.95) * (W/H)
#                                        = 1.466 * 1.333 = 1.954
# That is, lon_span ≈ lat_span * 1.954
MAPS = [
    # ── t30_q19 / t30_q91: LO R 16 airspace upper limit (Austria/Swiss border area)
    # The existing map shows LO N16 / LO R area near Austrian border (Vorarlberg region)
    # Question: upper limit of LO R 16 = 1500 ft MSL
    # This is actually an Austrian VFR chart segment; the existing image shows ~Austrian/Vorarlberg
    # The map shows Sopron/Austria area — coordinates approx lat 47.5-48.2, lon 16.2-17.2
    # Skip: this is NOT a Swiss ICAO chart — it's Austrian. Leave as-is.
    # ── t30_q20 / t30_q92: LO R 4 upper limit
    # Same map family (Austrian). Skip.
    # ── t30_q21 / t30_q93: NOTAM altitude restriction
    # Text NOTAM, not a geographic map. Skip.
    # ── t30_q42: Morat → Neuchâtel route crossing Payerne TMA
    # Morat ≈ N46°56'/E007°07', Neuchâtel ≈ N46°57'/E006°52'
    # bbox: lat 46.80-47.10, lon 6.70-7.40 → lon_span=0.70, lat_span=0.30 → ratio=2.33 > target
    # Adjust: lat_span=0.35, lon_span=0.35*1.954=0.683 → use lon 6.75-7.43, lat 46.82-47.17
    dict(
        tag="t30_q42",
        lat_min=46.82, lon_min=6.75, lat_max=47.17, lon_max=7.43,
        circles=[(46 + 56/60, 7 + 7/60), (46 + 57/60, 6 + 52/60)],
        routes=[[(46 + 56/60, 7 + 7/60), (46 + 57/60, 6 + 52/60)]],
        scale_km=20,
        note="Morat→Neuchâtel route crossing Payerne TMA; at what altitude need clearance?"
    ),
    # ── t30_q43: Birrfeld airspace class above 1400m AMSL
    # Birrfeld: 47°25'36"N / 007°14'02"E
    # Show region around Birrfeld; lat 47.20-47.55, lon 6.95-7.65
    # lat_span=0.35, lon_span=0.35*1.954=0.684 → use lon 6.98-7.66
    dict(
        tag="t30_q43",
        lat_min=47.20, lon_min=6.98, lat_max=47.55, lon_max=7.66,
        circles=[(47 + 25.6/60, 7 + 14/60)],
        routes=None,
        scale_km=20,
        note="Birrfeld (LSZF): airspace class at 1400m AMSL — Class E"
    ),
    # ── t30_q44: Schwyz route, DABS active zones
    # Route toward Schwyz, W0957/15 = HINWIL (~47°17'N 8°49'E), W0912/15 = MORGARTEN (~47°05'N 8°38'E)
    # Show central Switzerland: lat 46.95-47.45, lon 8.30-9.20
    # lat_span=0.50, lon_span=0.50*1.954=0.977 → use lon 8.32-9.30, lat 47.00-47.50
    dict(
        tag="t30_q44",
        lat_min=47.00, lon_min=8.32, lat_max=47.50, lon_max=9.30,
        circles=[(47 + 5/60, 8 + 38/60), (47 + 17/60, 8 + 49/60)],
        routes=None,
        scale_km=25,
        note="Schwyz route: MORGARTEN (W0912) and HINWIL (W0957) DABS zones"
    ),
    # ── t30_q45: Schwyz, Class C floor (FL90)
    # Schwyz: ~47°01'N, 8°39'E
    # Show region: lat 46.80-47.25, lon 8.25-9.13
    # lat_span=0.45, lon_span=0.45*1.954=0.879 → use lon 8.28-9.16, lat 46.82-47.27
    dict(
        tag="t30_q45",
        lat_min=46.82, lon_min=8.28, lat_max=47.27, lon_max=9.16,
        circles=[(47 + 1/60, 8 + 39/60)],
        routes=None,
        scale_km=20,
        note="Schwyz: Class C floor = FL90 (sector A9.1)"
    ),
    # ── t30_q53: Langenthal airspace at 2000m AMSL — Class E
    # Langenthal: 47°10'58"N / 007°44'29"E
    # Show Mittelland: lat 47.00-47.40, lon 7.42-7.42+0.39*1.954=7.42+0.762=8.18
    dict(
        tag="t30_q53",
        lat_min=47.00, lon_min=7.42, lat_max=47.40, lon_max=8.18,
        circles=[(47 + 10.97/60, 7 + 44.48/60)],
        routes=None,
        scale_km=20,
        note="Langenthal (LSZQ): airspace at 2000m AMSL = Class E"
    ),
    # ── t30_q59: Appenzell → Muotathal route with DABS
    # Appenzell: ~47°20'N, 9°24'E; Muotathal: ~47°00'N, 8°45'E
    # Route goes roughly NE to SW
    # lat_span=0.50, lon_span=0.50*1.954=0.977 → lat 46.90-47.40, lon 8.60-9.58
    dict(
        tag="t30_q59",
        lat_min=46.90, lon_min=8.60, lat_max=47.40, lon_max=9.58,
        circles=[(47 + 20/60, 9 + 24/60), (47 + 0/60, 8 + 45/60)],
        routes=[[(47 + 20/60, 9 + 24/60), (47 + 0/60, 8 + 45/60)]],
        scale_km=25,
        note="Appenzell → Muotathal VFR route (winter, DABS)"
    ),
    # ── t30_q63: Cham → Hitzkirch crossing Emmen TMA floor at 3500ft
    # Cham: ~47°11'N, 8°28'E; Hitzkirch: ~47°14'N, 8°16'E
    # Show Emmen/Luzern area: lat 47.00-47.35, lon 7.95-7.95+0.34*1.954=7.95+0.664=8.61
    dict(
        tag="t30_q63",
        lat_min=47.00, lon_min=7.95, lat_max=47.35, lon_max=8.61,
        circles=[(47 + 11/60, 8 + 28/60), (47 + 14/60, 8 + 16/60)],
        routes=[[(47 + 11/60, 8 + 28/60), (47 + 14/60, 8 + 16/60)]],
        scale_km=15,
        note="Cham→Hitzkirch: Emmen TMA floor = 3500ft AMSL (Class C)"
    ),
    # ── t30_q88: Münster (Wallis) → Amsteg route, R-8/R-8A active
    # Münster VS: ~46°29'N, 8°17'E; Amsteg UR: ~46°47'N, 8°43'E
    # lat_span=0.40, lon_span=0.40*1.954=0.782 → lat 46.35-46.75, lon 8.05-8.83
    dict(
        tag="t30_q88",
        lat_min=46.35, lon_min=8.05, lat_max=46.75, lon_max=8.83,
        circles=[(46 + 29/60, 8 + 17/60), (46 + 47/60, 8 + 43/60)],
        routes=[[(46 + 29/60, 8 + 17/60), (46 + 47/60, 8 + 43/60)]],
        scale_km=20,
        note="Münster VS → Amsteg alpine VFR route; R-8/R-8A active"
    ),
    # ── t60_q91: Erstfeld → Fricktal-Schupfart glide; 3rd CTR freq
    # Erstfeld: 46°49'N, 8°38'E; Fricktal-Schupfart: 47°30'32"N, 7°57'E
    # Long route N-NW through central Switzerland
    # lat_span=0.75, lon_span=0.75*1.954=1.466 → lat 46.70-47.45, lon 7.70-9.17
    dict(
        tag="t60_q91",
        lat_min=46.70, lon_min=7.70, lat_max=47.55, lon_max=9.37,
        circles=[(46 + 49/60, 8 + 38/60), (47 + 30.53/60, 7 + 57/60)],
        routes=[[(46 + 49/60, 8 + 38/60), (47 + 30.53/60, 7 + 57/60)]],
        scale_km=30,
        note="Erstfeld→Fricktal-Schupfart glide: 3rd CTR = 120.425 MHz"
    ),
    # ── t60_q94: Saanen (LSGK) — radio frequency 119.430
    # Saanen: 46°29'11"N / 007°14'55"E
    # Show Gstaad/Saanenland: lat 46.35-46.70, lon 6.90-6.90+0.34*1.954=6.90+0.664=7.56
    dict(
        tag="t60_q94",
        lat_min=46.35, lon_min=6.90, lat_max=46.70, lon_max=7.56,
        circles=[(46 + 29.18/60, 7 + 14.92/60)],
        routes=None,
        scale_km=15,
        note="Saanen LSGK location; radio freq 119.430 MHz"
    ),
    # ── t60_q99: Birrfeld → Courtelary → Grenchen distance ~115km
    # Birrfeld: 47°26'N, 008°13'E; Courtelary: 47°10'N, 007°05'E; Grenchen: 47°10'N, 007°25'E
    # Show broad area: lat 47.00-47.55, lon 6.90-8.40
    # lat_span=0.55, lon_span=0.55*1.954=1.075 → lon 6.90-7.975, lat 47.00-47.55
    # Widen a bit to show all 3 points well:
    dict(
        tag="t60_q99",
        lat_min=46.95, lon_min=6.80, lat_max=47.55, lon_max=8.40,
        circles=[
            (47 + 26/60, 8 + 13/60),   # Birrfeld
            (47 + 10/60, 7 + 5/60),    # Courtelary
            (47 + 10/60, 7 + 25/60),   # Grenchen
        ],
        routes=[
            [(47 + 26/60, 8 + 13/60), (47 + 10/60, 7 + 5/60)],   # Birrfeld → Courtelary
            [(47 + 10/60, 7 + 5/60), (47 + 10/60, 7 + 25/60)],   # Courtelary → Grenchen
        ],
        scale_km=30,
        note="Birrfeld→Courtelary→Grenchen; total distance ≈115 km"
    ),
    # ── t60_q140: Saanen location question (same area as t60_q94)
    # "Comment s'appelle le lieu aux coordonnées 46°29'N / 007°15'E ?" → Saanen
    # Same bbox as t60_q94 but slightly different tag
    dict(
        tag="t60_q140",
        lat_min=46.35, lon_min=6.90, lat_max=46.70, lon_max=7.56,
        circles=[(46 + 29/60, 7 + 15/60)],
        routes=None,
        scale_km=15,
        note="Location at 46°29'N/007°15'E = Saanen (LSGK)"
    ),
]
# ── main ───────────────────────────────────────────────────────────────────
if __name__ == "__main__":
    results = []
    skipped = []
    for m in MAPS:
        tag = m["tag"]
        try:
            ok = make_map(
                tag=tag,
                lat_min=m["lat_min"], lon_min=m["lon_min"],
                lat_max=m["lat_max"], lon_max=m["lon_max"],
                circles=m.get("circles"),
                routes=m.get("routes"),
                scale_km=m.get("scale_km", 20),
                note=m.get("note", ""),
            )
            added = []
            if m.get("circles"):
                added.append(f"{len(m['circles'])} circle(s)")
            if m.get("routes"):
                added.append("route line(s)")
            added.append("scale bar")
            results.append((tag, ", ".join(added), m.get("note", "")))
        except Exception as e:
            print(f"  ERROR: {e}")
            skipped.append((tag, str(e)))
    print("\n" + "=" * 70)
    print("RESULTS SUMMARY")
    print("=" * 70)
    print(f"\nUpdated ({len(results)}):")
    for tag, what, note in results:
        print(f"  {tag:15s}  +{what}")
        print(f"               {note}")
    print(f"\nSkipped (defined in script as NOT Swiss ICAO charts):")
    not_maps = [
        ("t10_q70",  "Ground signal diagram — two dumbbells"),
        ("t10_q77",  "Ground signal diagram — gliding in progress"),
        ("t10_q88",  "Ground signal diagram — landing prohibited"),
        ("t10_q94",  "Ground signal diagram"),
        ("t10_q114", "Airport sign diagram"),
        ("t30_q19",  "Austrian VFR chart (LO R16), not Swiss ICAO"),
        ("t30_q20",  "Austrian VFR chart (LO R4), not Swiss ICAO"),
        ("t30_q21",  "NOTAM text block — no geographic map"),
        ("t30_q36",  "Weight & balance table — no map"),
        ("t30_q40",  "Speed polar diagram"),
        ("t30_q41",  "Speed polar diagram"),
        ("t30_q44",  "DABS table + small route sketch — composite, not regenerated"),
        ("t30_q46",  "Aerodrome info card (LSGP La Côte) — not a chart map"),
        ("t30_q47",  "Visual approach chart LSGT Gruyères — not ICAO 1:500k"),
        ("t30_q57",  "NOTAM text block — no geographic map"),
        ("t30_q58",  "Speed polar diagram"),
        ("t30_q61",  "Speed polar diagram"),
        ("t30_q62",  "Aerodrome layout chart (Amlikon) — not ICAO 1:500k"),
        ("t30_q68",  "Visual approach chart BEX — not ICAO 1:500k"),
        ("t30_q69",  "Visual approach chart Bex/Bern — not ICAO 1:500k"),
        ("t30_q72",  "Aerodrome layout chart (Schänis) — not ICAO 1:500k"),
        ("t30_q75",  "Speed polar diagram"),
        ("t30_q77",  "Speed polar diagram"),
        ("t30_q80",  "NOTAM text block — no geographic map"),
        ("t30_q81",  "Bern-Belp visual approach chart — not ICAO 1:500k"),
        ("t30_q82",  "Bern-Belp visual approach chart — not ICAO 1:500k"),
        ("t30_q83",  "Speed polar diagram"),
        ("t30_q91",  "Duplicate of t30_q19 (Austrian VFR chart)"),
        ("t30_q92",  "Duplicate of t30_q20 (Austrian VFR chart)"),
        ("t30_q93",  "Duplicate of t30_q21 (NOTAM text)"),
        ("t30_q94",  "ICAO symbol diagram (obstacle groups) — not geographic"),
        ("t30_q95",  "ICAO symbol diagram (airport symbols) — not geographic"),
        ("t30_q96",  "ICAO symbol diagram (spot elevations) — not geographic"),
        ("t60_q46",  "German/NE-German ICAO chart — not Swiss, leave as-is"),
        ("t60_q153", "Globe/Earth diagram — not a chart"),
        ("t60_q161", "German chart — duplicate of t60_q46"),
        ("t60_q164", "Navigation calculation table — not a chart"),
        ("t60_q167", "German chart — not Swiss"),
        ("t60_q171", "German chart — not Swiss"),
    ]
    for tag, reason in not_maps:
        print(f"  {tag:15s}  {reason}")
    if skipped:
        print(f"\nErrors ({len(skipped)}):")
        for tag, err in skipped:
            print(f"  {tag}: {err}")