The app only calls the methods of aimsight-data: extraction/pumping.py, weather/meteoswiss.py (weather/ moved there)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b2923d8d49
commit
d34828ab5e
7 files changed
+36
-279
No files matched your search
@@ -12,7 +12,6 @@ The architecture of the repositories, one responsibility each: `docs/architectur
|
|||||||
- `app/`: the web app (FastAPI server, React and Mantine page); its doc in `app/README.md`.
|
- `app/`: the web app (FastAPI server, React and Mantine page); its doc in `app/README.md`.
|
||||||
- `instructions/analyst.md`: what the app asks of the analyst (output folder, report, dialogue).
|
- `instructions/analyst.md`: what the app asks of the analyst (output folder, report, dialogue).
|
||||||
- `docs/`: the architecture of the repositories, the plans.
|
- `docs/`: the architecture of the repositories, the plans.
|
||||||
- `weather/`: the weather measured by MeteoSwiss at a place over a past range (`weather/meteoswiss.py <place> <start> <end>`); its doc in `weather/README.md`.
|
|
||||||
|
|
||||||
And seven links, ignored by git, to the neighbouring repositories (a single copy of each on the workstation):
|
And seven links, ignored by git, to the neighbouring repositories (a single copy of each on the workstation):
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -14,13 +14,13 @@ The tool of the manual diagnostic: two pages, **Data** and **Stations**.
|
|||||||
- **The camera images**, on the right, on the same station and the same range: slider, ◀ ▶ and keyboard arrows; wheel to zoom, drag to move, double click for the whole image; Names box; a range on the bar under the slider draws the displacement arrow of each sensor. An arrow at the top left enlarges the image and pushes the plots to the left; the reverse arrow brings it back.
|
- **The camera images**, on the right, on the same station and the same range: slider, ◀ ▶ and keyboard arrows; wheel to zoom, drag to move, double click for the whole image; Names box; a range on the bar under the slider draws the displacement arrow of each sensor. An arrow at the top left enlarges the image and pushes the plots to the left; the reverse arrow brings it back.
|
||||||
- **The diagnostic settings**, under the image: "Focus on event curves" (with an event open, the plots show only its sensors: those of the detectors, or those the text of a label names), the families shown and, for Detectors only, the targets considered, the others removed before the detectors ("Rerun the detectors", parameter `targets` of `/api/detectors`).
|
- **The diagnostic settings**, under the image: "Focus on event curves" (with an event open, the plots show only its sensors: those of the detectors, or those the text of a label names), the families shown and, for Detectors only, the targets considered, the others removed before the detectors ("Rerun the detectors", parameter `targets` of `/api/detectors`).
|
||||||
|
|
||||||
- **The weather**: a station with a position gets, at Load, the hourly measurements of the nearest MeteoSwiss station (`weather/meteoswiss.py`) as plots "Weather: …", next to the "System: …" ones; the place found and the station chosen are written under the selector (check them: the search of a place always returns its best match).
|
- **The weather**: a station with a position gets, at Load, the hourly measurements of the nearest MeteoSwiss station (`weather/meteoswiss.py` of `~/aimsight-data`, `hourly`) as plots "Weather: …", next to the "System: …" ones; the place found and the station chosen are written under the selector (check them: the search of a place always returns its best match).
|
||||||
|
|
||||||
The address keeps the station and the range (UTC, `end` excluded): `#/data?station=NIEDERHORN&start=2026-09-25&end=2026-10-08`; without dates, the last 5 UTC days, today included.
|
The address keeps the station and the range (UTC, `end` excluded): `#/data?station=NIEDERHORN&start=2026-09-25&end=2026-10-08`; without dates, the last 5 UTC days, today included.
|
||||||
|
|
||||||
## The Stations page
|
## The Stations page
|
||||||
|
|
||||||
The tracked stations, `extraction/stations.txt` of `~/aimsight-data` (`SERIAL [position]`), to edit (serial, position: `lat,lon` or a Swiss place, for the weather of Data; empty for an indoor site: no weather), and the checked ones pumped (`extraction/pump.sh`, `--delay 300`) over a range (by default every station, over the range of the address, from 3 days before: the history of the detectors) or, without dates, their missing days up to now; the end of `out/pump.log` follows. The end of a pumping launched by the app empties the cache of the detectors' events.
|
The tracked stations, `extraction/stations.txt` of `~/aimsight-data` (`SERIAL [position]`), to edit (serial, position: `lat,lon` or a Swiss place, for the weather of Data; empty for an indoor site: no weather), and the checked ones pumped (`extraction/pump.sh`, `--delay 300`; the list and the pumping through `extraction/pumping.py` of `~/aimsight-data`, the app only calls it) over a range (by default every station, over the range of the address, from 3 days before: the history of the detectors) or, without dates, their missing days up to now; the end of `out/pump.log` follows. The end of a pumping launched by the app empties the cache of the detectors' events.
|
||||||
|
|
||||||
## The Analysis tab
|
## The Analysis tab
|
||||||
|
|
||||||
|
|||||||
+2
-21
@@ -78,6 +78,7 @@ def check_station():
|
|||||||
assert station.message("A moved; nothing to do. The jump of 2 targets in this period has the same cause.") \
|
assert station.message("A moved; nothing to do. The jump of 2 targets in this period has the same cause.") \
|
||||||
== "A moved. The jump of 2 targets in this period has the same cause."
|
== "A moved. The jump of 2 targets in this period has the same cause."
|
||||||
assert all(e["end"] >= "2026-10-26T00:00Z" and e["start"] < "2026-10-27T00:00Z" for e in ev), [(e["start"], e["end"]) for e in ev]
|
assert all(e["end"] >= "2026-10-26T00:00Z" and e["start"] < "2026-10-27T00:00Z" for e in ev), [(e["start"], e["end"]) for e in ev]
|
||||||
|
refuses(station.pump, {"stations": ["A;rm"]}) # the pumping (extraction/pumping.py, checked there): a refusal
|
||||||
assert not any("SIM_CCID" in t or t.startswith("System: ip") for t in titles)
|
assert not any("SIM_CCID" in t or t.startswith("System: ip") for t in titles)
|
||||||
assert all(len(c["T"][tr["t"]]) == len(tr["y"]) for p in c["plots"] for tr in p["traces"])
|
assert all(len(c["T"][tr["t"]]) == len(tr["y"]) for p in c["plots"] for tr in p["traces"])
|
||||||
before, station.LABELS = station.LABELS, temp_folder()
|
before, station.LABELS = station.LABELS, temp_folder()
|
||||||
@@ -255,27 +256,7 @@ def check_analysis():
|
|||||||
analysis.analyses.clear()
|
analysis.analyses.clear()
|
||||||
|
|
||||||
|
|
||||||
def check_pumping():
|
CHECKS = [check_server, check_station, check_optimization, check_analysis]
|
||||||
# the tracked stations and the pumping, in a temporary copy of ~/aimsight-data (nothing pumped)
|
|
||||||
before, station.PUMPING = station.PUMPING, temp_folder()
|
|
||||||
try:
|
|
||||||
(station.PUMPING / "extraction").mkdir()
|
|
||||||
(station.PUMPING / "extraction" / "stations.txt").write_text("NORDEND\nNIEDERHORN 46.69,7.78\n\nNORDEND Zermatt\n")
|
|
||||||
assert station.tracked() == {"NORDEND": "", "NIEDERHORN": "46.69,7.78"}, station.tracked()
|
|
||||||
assert station.save_tracked([{"serial": "A", "position": " Interlaken BE "}, {"serial": "B"}, {"serial": "A"}]) \
|
|
||||||
== [{"serial": "A", "position": "Interlaken BE"}, {"serial": "B", "position": ""}]
|
|
||||||
assert (station.PUMPING / "extraction" / "stations.txt").read_text() == "A Interlaken BE\nB\n"
|
|
||||||
refuses(station.save_tracked, [{"serial": "../x"}])
|
|
||||||
assert station.pumping() == {"running": False, "log": []}
|
|
||||||
refuses(station.pump, {"stations": ["A;rm"]})
|
|
||||||
refuses(station.pump, {"stations": ["A"], "start": "2026-11-10"})
|
|
||||||
refuses(station.pump, {"stations": ["A"], "start": "2026-11-10", "end": "2026-11-09"})
|
|
||||||
finally:
|
|
||||||
shutil.rmtree(station.PUMPING)
|
|
||||||
station.PUMPING = before
|
|
||||||
|
|
||||||
|
|
||||||
CHECKS = [check_server, check_station, check_pumping, check_optimization, check_analysis]
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
name = sys.argv[1] if len(sys.argv) > 1 else None
|
name = sys.argv[1] if len(sys.argv) > 1 else None
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ def detectors(station_: str = Query(alias="station"), start: str = "", end: str
|
|||||||
|
|
||||||
@app.get("/api/tracked")
|
@app.get("/api/tracked")
|
||||||
def tracked():
|
def tracked():
|
||||||
return [{"serial": s, "position": p} for s, p in station.tracked().items()]
|
return [{"serial": s, "position": p} for s, p in station.pumping.tracked().items()]
|
||||||
|
|
||||||
|
|
||||||
@app.put("/api/tracked")
|
@app.put("/api/tracked")
|
||||||
@@ -88,8 +88,8 @@ def save_tracked(body: dict):
|
|||||||
|
|
||||||
|
|
||||||
@app.get("/api/pump")
|
@app.get("/api/pump")
|
||||||
def pumping():
|
def pump_state():
|
||||||
return station.pumping()
|
return station.pump_state()
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/pump")
|
@app.post("/api/pump")
|
||||||
|
|||||||
+29
-74
@@ -2,26 +2,29 @@
|
|||||||
|
|
||||||
Data are read as the agents read them, tools/scripts/data.py (the tools repository, through the tools/ link); the detectors'
|
Data are read as the agents read them, tools/scripts/data.py (the tools repository, through the tools/ link); the detectors'
|
||||||
events are those of detectors/scripts/categories.py (events). Read-only on data/, filled only by pump.sh; writes only in
|
events are those of detectors/scripts/categories.py (events). Read-only on data/, filled only by pump.sh; writes only in
|
||||||
labeling/{auto,manual}/ and in the list of the tracked stations (extraction/stations.txt of ~/aimsight-data).
|
labeling/{auto,manual}/. What brings data in (the pumping, the list of the tracked stations, the weather) is in
|
||||||
|
~/aimsight-data, called as it is (extraction/pumping.py, weather/meteoswiss.py).
|
||||||
"""
|
"""
|
||||||
import bisect
|
import bisect
|
||||||
import functools
|
import functools
|
||||||
import csv
|
import csv
|
||||||
import fcntl
|
|
||||||
import glob
|
import glob
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import statistics
|
import statistics
|
||||||
import subprocess
|
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[2]
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
sys.path[:0] = [str(ROOT / "tools" / "scripts"), str(ROOT / "detectors" / "scripts"), str(ROOT / "weather")]
|
# ~/aimsight-data, the repository of data/: the methods that bring data in (the pumping, the weather), called as they are
|
||||||
|
DATA_REPOSITORY = Path(os.environ.get("AIMSIGHT_DATA", ROOT / "data")).resolve().parent
|
||||||
|
sys.path[:0] = [str(ROOT / "tools" / "scripts"), str(ROOT / "detectors" / "scripts"),
|
||||||
|
str(DATA_REPOSITORY / "extraction"), str(DATA_REPOSITORY / "weather")]
|
||||||
import data # noqa: E402
|
import data # noqa: E402
|
||||||
import meteoswiss # noqa: E402
|
import meteoswiss # noqa: E402
|
||||||
|
import pumping # noqa: E402
|
||||||
from categories import events # noqa: E402
|
from categories import events # noqa: E402
|
||||||
|
|
||||||
# data/ and labeling/ are links to ~/aimsight-data/data and ~/aimsight-labeling: no resolve(), the agents see data/ and labeling/
|
# data/ and labeling/ are links to ~/aimsight-data/data and ~/aimsight-labeling: no resolve(), the agents see data/ and labeling/
|
||||||
@@ -184,7 +187,7 @@ def curves(station, start, end):
|
|||||||
if not out:
|
if not out:
|
||||||
raise Refusal(f"no measurement of {station} in this range")
|
raise Refusal(f"no measurement of {station} in this range")
|
||||||
result = {"A": data.iso(a), "B": data.iso(b), "T": T, "plots": out}
|
result = {"A": data.iso(a), "B": data.iso(b), "T": T, "plots": out}
|
||||||
if place := tracked().get(station): # the weather at the position of the station (stations.txt), if it has one
|
if place := pumping.tracked().get(station): # the weather at the position of the station (stations.txt), if it has one
|
||||||
try:
|
try:
|
||||||
label, times, plots = weather(place, a, b)
|
label, times, plots = weather(place, a, b)
|
||||||
T.update(times)
|
T.update(times)
|
||||||
@@ -195,7 +198,7 @@ def curves(station, start, end):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
# --- the Data page, the weather at a place (weather/meteoswiss.py): plots "Weather: …" on the range of the curves
|
# --- the Data page, the weather at a place (weather/meteoswiss.py of ~/aimsight-data): plots "Weather: …" on the range of the curves
|
||||||
|
|
||||||
WEATHER = (("Precipitation (mm/h)", "precipitation_mm"), ("Temperature (°C)", "temperature_c"), ("Humidity (%)", "humidity_pct"),
|
WEATHER = (("Precipitation (mm/h)", "precipitation_mm"), ("Temperature (°C)", "temperature_c"), ("Humidity (%)", "humidity_pct"),
|
||||||
("Wind (km/h)", "wind_speed_kmh", "wind_gust_kmh"), ("Wind direction (deg)", "wind_direction_deg"),
|
("Wind (km/h)", "wind_speed_kmh", "wind_gust_kmh"), ("Wind direction (deg)", "wind_direction_deg"),
|
||||||
@@ -207,103 +210,55 @@ def weather(place, a, b):
|
|||||||
"""-> (label, T, plots) as curves(): the hourly values of the MeteoSwiss station nearest to the place ("lat,lon" or
|
"""-> (label, T, plots) as curves(): the hourly values of the MeteoSwiss station nearest to the place ("lat,lon" or
|
||||||
a Swiss place name), over [a, b); their times under T["system:weather"], so that the target filters ignore them."""
|
a Swiss place name), over [a, b); their times under T["system:weather"], so that the target filters ignore them."""
|
||||||
try:
|
try:
|
||||||
lat, lon, name = meteoswiss.locate(place)
|
where, hours = meteoswiss.hourly(place, a, b)
|
||||||
st = meteoswiss.nearest_station(lat, lon)
|
|
||||||
rows = meteoswiss.read_rows(meteoswiss.files_for(st["station_abbr"], a, b), a, b)
|
|
||||||
except LookupError as e:
|
except LookupError as e:
|
||||||
raise Refusal(str(e))
|
raise Refusal(str(e))
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
raise Refusal(f"MeteoSwiss unreachable: {e}")
|
raise Refusal(f"MeteoSwiss unreachable: {e}")
|
||||||
param = {c: p for p, c in meteoswiss.PARAMETERS.items()}
|
times = list(hours)
|
||||||
times = sorted(rows)
|
|
||||||
value = lambda r, c: float(r[param[c]]) if r.get(param[c], "").replace(".", "", 1).lstrip("-").isdigit() else None # noqa: E731
|
|
||||||
plots = []
|
plots = []
|
||||||
for title, *columns in WEATHER:
|
for title, *columns in WEATHER:
|
||||||
traces = [{"name": c.rsplit("_", 1)[0].replace("_", " "), "t": "system:weather", "y": y,
|
traces = [{"name": c.rsplit("_", 1)[0].replace("_", " "), "t": "system:weather", "y": y,
|
||||||
"mode": "markers" if "direction" in c else "lines",
|
"mode": "markers" if "direction" in c else "lines",
|
||||||
"line": {"width": 1.2, "color": COLORS[i], "shape": "hv" if c == "precipitation_mm" else "linear"}}
|
"line": {"width": 1.2, "color": COLORS[i], "shape": "hv" if c == "precipitation_mm" else "linear"}}
|
||||||
for i, (c, y) in enumerate((c, [value(rows[t], c) for t in times]) for c in columns) if any(v is not None for v in y)]
|
for i, (c, y) in enumerate((c, [hours[t][c] for t in times]) for c in columns) if any(v is not None for v in y)]
|
||||||
if traces:
|
if traces:
|
||||||
plots.append({"title": "Weather: " + title, "traces": traces})
|
plots.append({"title": "Weather: " + title, "traces": traces})
|
||||||
if not plots:
|
if not plots:
|
||||||
raise Refusal(f"no MeteoSwiss measurement at {st['station_name']} in this range")
|
raise Refusal(f"no MeteoSwiss measurement at {where['name']} in this range")
|
||||||
return (f"{name} → MeteoSwiss {st['station_abbr']} {st['station_name']}, {st['distance_km']:.1f} km, "
|
return (f"{where['place']} → MeteoSwiss {where['station']} {where['name']}, {where['distance_km']:.1f} km, "
|
||||||
f"{float(st['station_height_masl']):.0f} m",
|
f"{where['height_m']:.0f} m",
|
||||||
{"system:weather": [t.strftime("%Y-%m-%d %H:%M") for t in times]}, plots)
|
{"system:weather": [t.strftime("%Y-%m-%d %H:%M") for t in times]}, plots)
|
||||||
|
|
||||||
|
|
||||||
# --- the tracked stations and the pumping, in ~/aimsight-data (the repository of data/): extraction/stations.txt, one
|
# --- the tracked stations and the pumping: extraction/pumping.py of ~/aimsight-data
|
||||||
# station per line, "SERIAL [position]" (position: "lat,lon" or a Swiss place, for the weather); extraction/pump.sh
|
|
||||||
|
|
||||||
PUMPING = DATA.resolve().parent
|
pump_process = None # the pumping launched by the app
|
||||||
SERIAL = re.compile(r"[A-Za-z0-9_-]+$") # it becomes an argument of pump.sh and a folder of data/
|
|
||||||
DAY = re.compile(r"\d{4}-\d{2}-\d{2}$")
|
|
||||||
pump_process = None
|
|
||||||
|
|
||||||
|
|
||||||
def tracked():
|
|
||||||
"""{serial: position ("" without)}, in the order of the file, without duplicates."""
|
|
||||||
f = PUMPING / "extraction" / "stations.txt"
|
|
||||||
lines = f.read_text().splitlines() if f.is_file() else []
|
|
||||||
out = {}
|
|
||||||
for line in lines:
|
|
||||||
serial, _, position = line.strip().partition(" ")
|
|
||||||
if serial:
|
|
||||||
out.setdefault(serial, position.strip())
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def save_tracked(rows):
|
def save_tracked(rows):
|
||||||
"""rows: [{serial, position}] -> the new stations.txt."""
|
try:
|
||||||
out = {}
|
return [{"serial": s, "position": p} for s, p in pumping.save(rows).items()]
|
||||||
for r in rows:
|
except ValueError as e:
|
||||||
serial, position = str(r.get("serial", "")).strip(), " ".join(str(r.get("position", "")).split())
|
raise Refusal(str(e))
|
||||||
if not SERIAL.match(serial):
|
|
||||||
raise Refusal(f"not a serial number: {serial!r}")
|
|
||||||
out.setdefault(serial, position)
|
|
||||||
(PUMPING / "extraction" / "stations.txt").write_text("".join(f"{s} {p}".rstrip() + "\n" for s, p in out.items()))
|
|
||||||
return [{"serial": s, "position": p} for s, p in out.items()]
|
|
||||||
|
|
||||||
|
|
||||||
def pumping():
|
def pump_state():
|
||||||
"""{running, log}: a pumping running (the app's, the scheduler's or by hand: the lock of pump.sh), the end of
|
"""{running, log}; the end of the app's pumping empties the cache of the detectors' events."""
|
||||||
out/pump.log. The end of the app's pumping empties the cache of the detectors' events."""
|
|
||||||
global pump_process
|
global pump_process
|
||||||
if pump_process and pump_process.poll() is not None:
|
if pump_process and pump_process.poll() is not None:
|
||||||
pump_process = None
|
pump_process = None
|
||||||
detectors.cache_clear()
|
detectors.cache_clear()
|
||||||
try:
|
return {"running": pumping.running() or pump_process is not None, "log": pumping.log()}
|
||||||
with open(PUMPING / "out" / "pump.lock") as lock:
|
|
||||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
||||||
running = False
|
|
||||||
except FileNotFoundError:
|
|
||||||
running = False
|
|
||||||
except BlockingIOError:
|
|
||||||
running = True
|
|
||||||
try:
|
|
||||||
with open(PUMPING / "out" / "pump.log", "rb") as f:
|
|
||||||
f.seek(max(0, f.seek(0, os.SEEK_END) - 8000))
|
|
||||||
log = f.read().decode(errors="replace").splitlines()[-40:]
|
|
||||||
except FileNotFoundError:
|
|
||||||
log = []
|
|
||||||
return {"running": running or pump_process is not None, "log": log}
|
|
||||||
|
|
||||||
|
|
||||||
def pump(body):
|
def pump(body):
|
||||||
"""{stations, start, end, images}: pump.sh in the background, with --from start --to end, or without (the missing
|
|
||||||
days of each station up to now)."""
|
|
||||||
global pump_process
|
global pump_process
|
||||||
stations, start, end = body.get("stations") or [], body.get("start") or "", body.get("end") or ""
|
try:
|
||||||
if not stations or not all(isinstance(s, str) and SERIAL.match(s) for s in stations):
|
pump_process = pumping.start(body.get("stations") or [], body.get("start") or "", body.get("end") or "", body.get("images"))
|
||||||
raise Refusal("no station, or not a serial number")
|
except ValueError as e:
|
||||||
if bool(start) != bool(end) or (start and not (DAY.match(start) and DAY.match(end) and start < end)):
|
raise Refusal(str(e))
|
||||||
raise Refusal("a range: From and To, YYYY-MM-DD, From before To")
|
return pump_state()
|
||||||
if pumping()["running"]:
|
|
||||||
raise Refusal("a pumping is already running")
|
|
||||||
args = ["--from", start, "--to", end] * bool(start) + ["--images"] * bool(body.get("images")) + ["--delay", "300", *stations]
|
|
||||||
pump_process = subprocess.Popen([str(PUMPING / "extraction" / "pump.sh"), *args], cwd=PUMPING,
|
|
||||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
||||||
return pumping()
|
|
||||||
|
|
||||||
|
|
||||||
# --- the Data page, "Detectors" labels: the events of the journal, read-only
|
# --- the Data page, "Detectors" labels: the events of the journal, read-only
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
# weather
|
|
||||||
|
|
||||||
The weather really measured at a place over a past range: the hourly values of the MeteoSwiss automatic weather station (SwissMetNet) nearest to the place. Measurements, not a model output.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python3 weather/meteoswiss.py <place> <start> <end> [--out FILE]
|
|
||||||
python3 weather/meteoswiss.py "Genève" 2026-11-15 2026-11-16 --out gve.csv
|
|
||||||
python3 weather/meteoswiss.py 46.52,6.63 2025-06-01T12:00 2025-06-01T18:00
|
|
||||||
```
|
|
||||||
|
|
||||||
- `place`: a Swiss place name, resolved by the swisstopo search (`api3.geo.admin.ch`), or coordinates `lat,lon` (WGS84). The resolved place and the chosen station (name, distance, altitude) are written on stderr: check them, the search always returns its best match.
|
|
||||||
- `start`, `end`: `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM`, in UTC, `end` excluded. The range is in the past.
|
|
||||||
- The output: a CSV, one row per hour, `time_utc` (start of the hour) and `station`, then `precipitation_mm`, `temperature_c`, `humidity_pct`, `wind_speed_kmh`, `wind_gust_kmh`, `wind_direction_deg`, `pressure_hpa` (at the station, QFE), `sunshine_min`, `global_radiation_wm2`, `snow_depth_cm`. An empty cell: not measured at this station or at this hour.
|
|
||||||
|
|
||||||
The source is the Open Data of MeteoSwiss, free, without key ([terms of use](https://opendatadocs.meteoswiss.ch/fr/general/terms-of-use), [documentation of the dataset](https://opendatadocs.meteoswiss.ch/a-data-groundbased/a1-automatic-weather-stations)); the files of a station are listed by the STAC API (`data.geo.admin.ch/api/stac/v1/collections/ch.meteoschweiz.ogd-smn/items/<station>`). The values are quality-checked by MeteoSwiss, except those of the current day (`now` file). Hourly series from 1980 at most, depending on the station. Standard library only.
|
|
||||||
@@ -1,163 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""The weather measured by MeteoSwiss at the station nearest to a place, over a past range.
|
|
||||||
|
|
||||||
python3 weather/meteoswiss.py <place> <start> <end> [--out FILE]
|
|
||||||
|
|
||||||
<place> is a Swiss place name ("Genève", "Lausanne") or coordinates "lat,lon" (WGS84);
|
|
||||||
<start> and <end> are dates YYYY-MM-DD or YYYY-MM-DDTHH:MM, in UTC, <end> excluded.
|
|
||||||
The output is an hourly CSV (stdout by default), one row per hour.
|
|
||||||
|
|
||||||
The source is the Open Data of MeteoSwiss: the automatic weather stations SwissMetNet,
|
|
||||||
the real measurements (not a model), quality-checked except for the current day
|
|
||||||
(https://opendatadocs.meteoswiss.ch/a-data-groundbased/a1-automatic-weather-stations).
|
|
||||||
The place name is resolved by the search service of swisstopo (api3.geo.admin.ch).
|
|
||||||
No key, no dependency outside the standard library.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import csv
|
|
||||||
import io
|
|
||||||
import json
|
|
||||||
import math
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
import urllib.parse
|
|
||||||
import urllib.request
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
|
|
||||||
BASE = "https://data.geo.admin.ch/ch.meteoschweiz.ogd-smn"
|
|
||||||
STAC_ITEM = "https://data.geo.admin.ch/api/stac/v1/collections/ch.meteoschweiz.ogd-smn/items/{}"
|
|
||||||
GEOCODER = "https://api3.geo.admin.ch/rest/services/api/SearchServer"
|
|
||||||
|
|
||||||
# MeteoSwiss parameter -> column of the output (hourly values).
|
|
||||||
PARAMETERS = {
|
|
||||||
"rre150h0": "precipitation_mm", # hourly total
|
|
||||||
"tre200h0": "temperature_c", # air at 2 m, hourly mean
|
|
||||||
"ure200h0": "humidity_pct", # relative, at 2 m, hourly mean
|
|
||||||
"fu3010h0": "wind_speed_kmh", # hourly mean
|
|
||||||
"fu3010h1": "wind_gust_kmh", # hourly max of the gusts
|
|
||||||
"dkl010h0": "wind_direction_deg", # hourly mean
|
|
||||||
"prestah0": "pressure_hpa", # at the station (QFE), hourly mean
|
|
||||||
"sre000h0": "sunshine_min", # hourly total
|
|
||||||
"gre000h0": "global_radiation_wm2", # hourly mean
|
|
||||||
"htoauths": "snow_depth_cm", # instantaneous, not at every station
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def fetch(url):
|
|
||||||
request = urllib.request.Request(url, headers={"User-Agent": "aimsight-weather"})
|
|
||||||
with urllib.request.urlopen(request, timeout=60) as response:
|
|
||||||
return response.read()
|
|
||||||
|
|
||||||
|
|
||||||
def parse_time(text):
|
|
||||||
for form in ("%Y-%m-%dT%H:%M", "%Y-%m-%d"):
|
|
||||||
try:
|
|
||||||
return datetime.strptime(text, form).replace(tzinfo=timezone.utc)
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
raise argparse.ArgumentTypeError(f"not a date YYYY-MM-DD[THH:MM]: {text}")
|
|
||||||
|
|
||||||
|
|
||||||
def locate(place):
|
|
||||||
"""(lat, lon, label) of a place name or of "lat,lon"."""
|
|
||||||
parts = place.split(",")
|
|
||||||
if len(parts) == 2:
|
|
||||||
try:
|
|
||||||
lat, lon = float(parts[0]), float(parts[1])
|
|
||||||
return lat, lon, f"{lat},{lon}"
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
query = urllib.parse.urlencode({"searchText": place, "type": "locations", "limit": 1, "sr": 4326})
|
|
||||||
results = json.loads(fetch(f"{GEOCODER}?{query}"))["results"]
|
|
||||||
if not results:
|
|
||||||
raise LookupError(f"place not found: {place}")
|
|
||||||
attrs = results[0]["attrs"]
|
|
||||||
label = re.sub(r"<[^>]+>", "", attrs["label"]).split("\n")[0].strip()
|
|
||||||
return attrs["lat"], attrs["lon"], label
|
|
||||||
|
|
||||||
|
|
||||||
def distance_km(lat1, lon1, lat2, lon2):
|
|
||||||
p1, p2 = math.radians(lat1), math.radians(lat2)
|
|
||||||
a = (math.sin((p2 - p1) / 2) ** 2
|
|
||||||
+ math.cos(p1) * math.cos(p2) * math.sin(math.radians(lon2 - lon1) / 2) ** 2)
|
|
||||||
return 2 * 6371 * math.asin(math.sqrt(a))
|
|
||||||
|
|
||||||
|
|
||||||
def nearest_station(lat, lon):
|
|
||||||
text = fetch(f"{BASE}/ogd-smn_meta_stations.csv").decode("latin-1")
|
|
||||||
stations = list(csv.DictReader(io.StringIO(text), delimiter=";"))
|
|
||||||
station = min(stations, key=lambda s: distance_km(
|
|
||||||
lat, lon, float(s["station_coordinates_wgs84_lat"]), float(s["station_coordinates_wgs84_lon"])))
|
|
||||||
station["distance_km"] = distance_km(
|
|
||||||
lat, lon, float(station["station_coordinates_wgs84_lat"]), float(station["station_coordinates_wgs84_lon"]))
|
|
||||||
return station
|
|
||||||
|
|
||||||
|
|
||||||
def files_for(station, start, end):
|
|
||||||
"""The hourly files of the station that cover [start, end): historical by decade, recent, now."""
|
|
||||||
item = json.loads(fetch(STAC_ITEM.format(station.lower())))
|
|
||||||
names = [n for n in item["assets"] if f"_{station.lower()}_h_" in n]
|
|
||||||
chosen = []
|
|
||||||
for name in names:
|
|
||||||
stem = name.rsplit(".", 1)[0]
|
|
||||||
if "_historical_" in stem:
|
|
||||||
first, last = (int(y) for y in stem.rsplit("_", 1)[1].split("-"))
|
|
||||||
if start.year <= last and end.year >= first:
|
|
||||||
chosen.append(name)
|
|
||||||
elif stem.endswith("_recent"): # from January 1 of the current year to yesterday
|
|
||||||
if end.year >= datetime.now(timezone.utc).year - 1:
|
|
||||||
chosen.append(name)
|
|
||||||
elif stem.endswith("_now"): # since midnight, not yet quality-checked
|
|
||||||
if end > datetime.now(timezone.utc) - timedelta(days=1):
|
|
||||||
chosen.append(name)
|
|
||||||
return [item["assets"][n]["href"] for n in sorted(chosen)]
|
|
||||||
|
|
||||||
|
|
||||||
def read_rows(urls, start, end):
|
|
||||||
"""{time: row} over [start, end); a later file (recent, now) completes an earlier one."""
|
|
||||||
rows = {}
|
|
||||||
for url in urls:
|
|
||||||
text = fetch(url).decode("latin-1")
|
|
||||||
for row in csv.DictReader(io.StringIO(text), delimiter=";"):
|
|
||||||
time = datetime.strptime(row["reference_timestamp"], "%d.%m.%Y %H:%M").replace(tzinfo=timezone.utc)
|
|
||||||
if start <= time < end:
|
|
||||||
rows.setdefault(time, row)
|
|
||||||
return rows
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
||||||
parser.add_argument("place", help='a Swiss place name, or "lat,lon" (WGS84)')
|
|
||||||
parser.add_argument("start", type=parse_time, help="YYYY-MM-DD[THH:MM], UTC, included")
|
|
||||||
parser.add_argument("end", type=parse_time, help="YYYY-MM-DD[THH:MM], UTC, excluded")
|
|
||||||
parser.add_argument("--out", help="the CSV file (stdout by default)")
|
|
||||||
args = parser.parse_args()
|
|
||||||
if args.end <= args.start:
|
|
||||||
sys.exit("the end must be after the start")
|
|
||||||
if args.start >= datetime.now(timezone.utc):
|
|
||||||
sys.exit("the range must be in the past")
|
|
||||||
|
|
||||||
try:
|
|
||||||
lat, lon, label = locate(args.place)
|
|
||||||
except LookupError as e:
|
|
||||||
sys.exit(str(e))
|
|
||||||
station = nearest_station(lat, lon)
|
|
||||||
abbr = station["station_abbr"]
|
|
||||||
print(f"{label} ({lat:.4f}, {lon:.4f}) -> station {abbr} {station['station_name']}, "
|
|
||||||
f"{station['distance_km']:.1f} km, {station['station_height_masl']} m", file=sys.stderr)
|
|
||||||
|
|
||||||
rows = read_rows(files_for(abbr, args.start, args.end), args.start, args.end)
|
|
||||||
out = open(args.out, "w", newline="", encoding="utf-8") if args.out else sys.stdout
|
|
||||||
writer = csv.writer(out)
|
|
||||||
writer.writerow(["time_utc", "station", *PARAMETERS.values()])
|
|
||||||
for time in sorted(rows):
|
|
||||||
row = rows[time]
|
|
||||||
writer.writerow([time.strftime("%Y-%m-%dT%H:%MZ"), abbr, *(row.get(p, "") for p in PARAMETERS)])
|
|
||||||
if args.out:
|
|
||||||
out.close()
|
|
||||||
print(f"{len(rows)} hours", file=sys.stderr)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
Reference in new issue
Block a user