Data: Stations and pumping (the tracked stations, their position, pump.sh from the app); the weather of the station at Load
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
eaa124f9f5
commit
c8c8c1587a
8 files changed
+260
-13
No files matched your search
@@ -14,6 +14,9 @@ The tool of the manual diagnostic: a single page, **Data**.
|
|||||||
- **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`).
|
||||||
|
|
||||||
|
- **Stations and pumping** (button of the selector): the tracked stations, `extraction/stations.txt` of `~/aimsight-data` (`SERIAL [position]`), to edit (serial, position: `lat,lon` or a Swiss place), and the checked ones pumped (`extraction/pump.sh`, `--delay 300`) over a range (by default from 3 days before the range shown, the history of the detectors) or, without dates, their missing days up to now; the end of `out/pump.log` follows, and the page loads again at the end of the pumping.
|
||||||
|
- **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 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 Analysis tab
|
## The Analysis tab
|
||||||
|
|||||||
+21
-1
@@ -255,7 +255,27 @@ def check_analysis():
|
|||||||
analysis.analyses.clear()
|
analysis.analyses.clear()
|
||||||
|
|
||||||
|
|
||||||
CHECKS = [check_server, check_station, check_optimization, check_analysis]
|
def check_pumping():
|
||||||
|
# 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
|
||||||
|
|||||||
@@ -77,6 +77,26 @@ def detectors(station_: str = Query(alias="station"), start: str = "", end: str
|
|||||||
return station.detectors(station_, start, end, targets)
|
return station.detectors(station_, start, end, targets)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/tracked")
|
||||||
|
def tracked():
|
||||||
|
return [{"serial": s, "position": p} for s, p in station.tracked().items()]
|
||||||
|
|
||||||
|
|
||||||
|
@app.put("/api/tracked")
|
||||||
|
def save_tracked(body: dict):
|
||||||
|
return station.save_tracked(body.get("stations") or [])
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/pump")
|
||||||
|
def pumping():
|
||||||
|
return station.pumping()
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/pump")
|
||||||
|
def pump(body: dict):
|
||||||
|
return station.pump(body)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/labels")
|
@app.get("/api/labels")
|
||||||
def labels(station_: str = Query(alias="station"), folder: str = "manual"):
|
def labels(station_: str = Query(alias="station"), folder: str = "manual"):
|
||||||
try:
|
try:
|
||||||
|
|||||||
+127
-3
@@ -1,23 +1,27 @@
|
|||||||
"""The data of the Data page: a station's images, its curves, its labels.
|
"""The data of the Data page: a station's images, its curves, its labels.
|
||||||
|
|
||||||
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/; writes only in labeling/{auto,manual}/.
|
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).
|
||||||
"""
|
"""
|
||||||
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")]
|
sys.path[:0] = [str(ROOT / "tools" / "scripts"), str(ROOT / "detectors" / "scripts"), str(ROOT / "weather")]
|
||||||
import data # noqa: E402
|
import data # noqa: E402
|
||||||
|
import meteoswiss # 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/
|
||||||
@@ -179,7 +183,127 @@ def curves(station, start, end):
|
|||||||
"line": {"width": 1.2, "color": COLORS[0]}}]})
|
"line": {"width": 1.2, "color": COLORS[0]}}]})
|
||||||
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")
|
||||||
return {"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
|
||||||
|
try:
|
||||||
|
label, times, plots = weather(place, a, b)
|
||||||
|
T.update(times)
|
||||||
|
out += plots
|
||||||
|
result["weather"] = label
|
||||||
|
except Refusal as e:
|
||||||
|
result["weather"] = f"unavailable ({e})"
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
# --- the Data page, the weather at a place (weather/meteoswiss.py): plots "Weather: …" on the range of the curves
|
||||||
|
|
||||||
|
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"),
|
||||||
|
("Pressure (hPa)", "pressure_hpa"), ("Sunshine (min/h)", "sunshine_min"),
|
||||||
|
("Global radiation (W/m²)", "global_radiation_wm2"), ("Snow depth (cm)", "snow_depth_cm"))
|
||||||
|
|
||||||
|
|
||||||
|
def weather(place, a, b):
|
||||||
|
"""-> (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."""
|
||||||
|
try:
|
||||||
|
lat, lon, name = meteoswiss.locate(place)
|
||||||
|
st = meteoswiss.nearest_station(lat, lon)
|
||||||
|
rows = meteoswiss.read_rows(meteoswiss.files_for(st["station_abbr"], a, b), a, b)
|
||||||
|
except LookupError as e:
|
||||||
|
raise Refusal(str(e))
|
||||||
|
except OSError as e:
|
||||||
|
raise Refusal(f"MeteoSwiss unreachable: {e}")
|
||||||
|
param = {c: p for p, c in meteoswiss.PARAMETERS.items()}
|
||||||
|
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 = []
|
||||||
|
for title, *columns in WEATHER:
|
||||||
|
traces = [{"name": c.rsplit("_", 1)[0].replace("_", " "), "t": "system:weather", "y": y,
|
||||||
|
"mode": "markers" if "direction" in c else "lines",
|
||||||
|
"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)]
|
||||||
|
if traces:
|
||||||
|
plots.append({"title": "Weather: " + title, "traces": traces})
|
||||||
|
if not plots:
|
||||||
|
raise Refusal(f"no MeteoSwiss measurement at {st['station_name']} in this range")
|
||||||
|
return (f"{name} → MeteoSwiss {st['station_abbr']} {st['station_name']}, {st['distance_km']:.1f} km, "
|
||||||
|
f"{float(st['station_height_masl']):.0f} m",
|
||||||
|
{"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
|
||||||
|
# station per line, "SERIAL [position]" (position: "lat,lon" or a Swiss place, for the weather); extraction/pump.sh
|
||||||
|
|
||||||
|
PUMPING = DATA.resolve().parent
|
||||||
|
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):
|
||||||
|
"""rows: [{serial, position}] -> the new stations.txt."""
|
||||||
|
out = {}
|
||||||
|
for r in rows:
|
||||||
|
serial, position = str(r.get("serial", "")).strip(), " ".join(str(r.get("position", "")).split())
|
||||||
|
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():
|
||||||
|
"""{running, log}: a pumping running (the app's, the scheduler's or by hand: the lock of pump.sh), the end of
|
||||||
|
out/pump.log. The end of the app's pumping empties the cache of the detectors' events."""
|
||||||
|
global pump_process
|
||||||
|
if pump_process and pump_process.poll() is not None:
|
||||||
|
pump_process = None
|
||||||
|
detectors.cache_clear()
|
||||||
|
try:
|
||||||
|
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):
|
||||||
|
"""{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
|
||||||
|
stations, start, end = body.get("stations") or [], body.get("start") or "", body.get("end") or ""
|
||||||
|
if not stations or not all(isinstance(s, str) and SERIAL.match(s) for s in stations):
|
||||||
|
raise Refusal("no station, or not a serial number")
|
||||||
|
if bool(start) != bool(end) or (start and not (DAY.match(start) and DAY.match(end) and start < end)):
|
||||||
|
raise Refusal("a range: From and To, YYYY-MM-DD, From before To")
|
||||||
|
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
|
||||||
|
|||||||
+2
-1
@@ -113,7 +113,8 @@ export default function App() {
|
|||||||
return () => removeEventListener("hashchange", follow);
|
return () => removeEventListener("hashchange", follow);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const choose = s => { location.hash = address(page, s); };
|
// the same address again (Load, the end of a pumping): read again, a new selection loads the data again
|
||||||
|
const choose = s => { const a = address(page, s); if (location.hash === a) setPlace(readAddress()); else location.hash = a; };
|
||||||
// An analysis of the sidebar: Data on its station, days that cover its range (unless the range shown already covers them)
|
// An analysis of the sidebar: Data on its station, days that cover its range (unless the range shown already covers them)
|
||||||
function openAnalysis(a) {
|
function openAnalysis(a) {
|
||||||
const s = selection, covers = s.station === a.station && s.start <= a.start.slice(0, 10) && a.end < s.end;
|
const s = selection, covers = s.station === a.station && s.start <= a.start.slice(0, 10) && a.end < s.end;
|
||||||
|
|||||||
+79
-5
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { Button, Card, Group, Select, TextInput } from "@mantine/core";
|
import { ActionIcon, Button, Card, Checkbox, Code, Group, Modal, ScrollArea, Select, Stack, Table, Text, TextInput } from "@mantine/core";
|
||||||
import { notifications } from "@mantine/notifications";
|
import { notifications } from "@mantine/notifications";
|
||||||
|
import { IconPlus, IconX } from "@tabler/icons-react";
|
||||||
|
|
||||||
// A request to the API; a refusal of the server shows as a notification -> the JSON returned, or null
|
// A request to the API; a refusal of the server shows as a notification -> the JSON returned, or null
|
||||||
export async function call(path, method = "GET", body) {
|
export async function call(path, method = "GET", body) {
|
||||||
@@ -18,9 +19,9 @@ export async function call(path, method = "GET", body) {
|
|||||||
|
|
||||||
// The station and the range (UTC, To excluded; empty: the whole period), shared by the pages through the address
|
// The station and the range (UTC, To excluded; empty: the whole period), shared by the pages through the address
|
||||||
export function Selector({ selection, choose }) {
|
export function Selector({ selection, choose }) {
|
||||||
const [stations, setStations] = useState([]), [s, setS] = useState(selection);
|
const [stations, setStations] = useState([]), [s, setS] = useState(selection), [editing, setEditing] = useState(false);
|
||||||
useEffect(() => { call("/api/stations").then(l => l && setStations(l)); }, []);
|
useEffect(() => { call("/api/stations").then(l => l && setStations(l)); }, [selection]); // a pumping may add one
|
||||||
useEffect(() => setS(selection), [selection.station, selection.start, selection.end]);
|
useEffect(() => setS(selection), [selection]); // a new object at each change of the address, or at each Load
|
||||||
return (
|
return (
|
||||||
<Card shadow="sm" withBorder>
|
<Card shadow="sm" withBorder>
|
||||||
<Group align="flex-end" gap="md">
|
<Group align="flex-end" gap="md">
|
||||||
@@ -29,7 +30,80 @@ export function Selector({ selection, choose }) {
|
|||||||
<TextInput label="From (UTC)" type="date" value={s.start} onChange={e => setS({ ...s, start: e.currentTarget.value })} />
|
<TextInput label="From (UTC)" type="date" value={s.start} onChange={e => setS({ ...s, start: e.currentTarget.value })} />
|
||||||
<TextInput label="To (excluded)" type="date" value={s.end} onChange={e => setS({ ...s, end: e.currentTarget.value })} />
|
<TextInput label="To (excluded)" type="date" value={s.end} onChange={e => setS({ ...s, end: e.currentTarget.value })} />
|
||||||
<Button onClick={() => choose(s)} disabled={!s.station}>Load</Button>
|
<Button onClick={() => choose(s)} disabled={!s.station}>Load</Button>
|
||||||
|
<Button variant="default" onClick={() => setEditing(true)}>Stations and pumping</Button>
|
||||||
</Group>
|
</Group>
|
||||||
|
<Stations opened={editing} close={() => setEditing(false)} selection={s} reload={() => choose(selection)} />
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const shift = (d, n) => (d ? new Date(Date.parse(d) + n * 864e5).toISOString().slice(0, 10) : "");
|
||||||
|
|
||||||
|
// The tracked stations (extraction/stations.txt of ~/aimsight-data): serial and position (for the weather of the Data page);
|
||||||
|
// the checked ones pumped (extraction/pump.sh) over a range, or without range their missing days up to now. The state of
|
||||||
|
// the pumping read every 2 s while the window is open or a pumping runs; at its end, the page loads again
|
||||||
|
function Stations({ opened, close, selection, reload }) {
|
||||||
|
const [rows, setRows] = useState([]), [checked, setChecked] = useState([]), [range, setRange] = useState({});
|
||||||
|
const [images, setImages] = useState(true), [state, setState] = useState(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!opened) return;
|
||||||
|
call("/api/tracked").then(l => l && setRows(l));
|
||||||
|
setChecked(selection.station ? [selection.station] : []);
|
||||||
|
setRange({ start: shift(selection.start, -3), end: selection.end }); // 3 days before: the history of the detectors
|
||||||
|
}, [opened]);
|
||||||
|
const watch = opened || !!state?.running;
|
||||||
|
useEffect(() => {
|
||||||
|
if (!watch) return;
|
||||||
|
const read = () => fetch("/api/pump").then(r => r.ok && r.json()).then(p => p && setState(p)).catch(() => {}); // silently
|
||||||
|
read();
|
||||||
|
const timer = setInterval(read, 2000);
|
||||||
|
return () => clearInterval(timer);
|
||||||
|
}, [watch]);
|
||||||
|
const running = !!state?.running, was = useRef(false);
|
||||||
|
useEffect(() => { if (was.current && !running) reload(); was.current = running; }, [running]);
|
||||||
|
|
||||||
|
const set = (i, k, v) => setRows(rows.map((r, n) => (n === i ? { ...r, [k]: v } : r)));
|
||||||
|
const save = () => call("/api/tracked", "PUT", { stations: rows.filter(r => r.serial) }).then(l => l && setRows(l));
|
||||||
|
const pump = () => call("/api/pump", "POST", { stations: checked, ...range, images }).then(p => p && setState(p));
|
||||||
|
return (
|
||||||
|
<Modal opened={opened} onClose={close} title="Stations and pumping" size="xl">
|
||||||
|
<Stack gap="md">
|
||||||
|
<Table withRowBorders={false} verticalSpacing={4}>
|
||||||
|
<Table.Thead><Table.Tr><Table.Th w={40}>Pump</Table.Th><Table.Th>Serial</Table.Th>
|
||||||
|
<Table.Th>Position (lat,lon or a Swiss place, for the weather)</Table.Th><Table.Th w={40} /></Table.Tr></Table.Thead>
|
||||||
|
<Table.Tbody>
|
||||||
|
{rows.map((r, i) => (
|
||||||
|
<Table.Tr key={i}>
|
||||||
|
<Table.Td><Checkbox checked={checked.includes(r.serial)} disabled={!r.serial} aria-label={`Pump ${r.serial}`}
|
||||||
|
onChange={e => setChecked(e.currentTarget.checked ? [...checked, r.serial] : checked.filter(c => c !== r.serial))} /></Table.Td>
|
||||||
|
<Table.Td><TextInput size="xs" value={r.serial} onChange={e => set(i, "serial", e.currentTarget.value.trim())} /></Table.Td>
|
||||||
|
<Table.Td><TextInput size="xs" value={r.position} placeholder="46.6895,7.7790"
|
||||||
|
onChange={e => set(i, "position", e.currentTarget.value)} /></Table.Td>
|
||||||
|
<Table.Td><ActionIcon variant="subtle" color="gray" aria-label="Remove" onClick={() => setRows(rows.filter((_, n) => n !== i))}>
|
||||||
|
<IconX size={16} /></ActionIcon></Table.Td>
|
||||||
|
</Table.Tr>
|
||||||
|
))}
|
||||||
|
</Table.Tbody>
|
||||||
|
</Table>
|
||||||
|
<Group gap="sm">
|
||||||
|
<Button size="xs" variant="default" leftSection={<IconPlus size={14} />}
|
||||||
|
onClick={() => setRows([...rows, { serial: "", position: "" }])}>Add a station</Button>
|
||||||
|
<Button size="xs" onClick={save}>Save the list</Button>
|
||||||
|
</Group>
|
||||||
|
<Group align="flex-end" gap="md">
|
||||||
|
<TextInput label="From (UTC)" type="date" value={range.start || ""} onChange={e => setRange({ ...range, start: e.currentTarget.value })} />
|
||||||
|
<TextInput label="To (excluded)" type="date" value={range.end || ""} onChange={e => setRange({ ...range, end: e.currentTarget.value })} />
|
||||||
|
<Checkbox label="Images" checked={images} onChange={e => setImages(e.currentTarget.checked)} mb={8} />
|
||||||
|
<Button onClick={pump} loading={running} disabled={!checked.length}>Pump {checked.length || ""}</Button>
|
||||||
|
</Group>
|
||||||
|
<Text size="xs" c="dimmed">From is 3 days before the range shown (the history of the detectors); without dates, the missing days of
|
||||||
|
each station up to now. Read-only on the platform; a long range, outside busy hours.</Text>
|
||||||
|
{state?.log?.length > 0 && (
|
||||||
|
<ScrollArea h={220} viewportRef={v => v && (v.scrollTop = v.scrollHeight)}>
|
||||||
|
<Code block>{state.log.join("\n")}</Code>
|
||||||
|
</ScrollArea>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -52,7 +52,7 @@ export default function Data({ selection, choose, analysis, setAnalysis }) {
|
|||||||
if (!station) return;
|
if (!station) return;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
call(`/api/curves?${new URLSearchParams({ station, start, end })}`).then(d => { setData(d); setLoading(false); });
|
call(`/api/curves?${new URLSearchParams({ station, start, end })}`).then(d => { setData(d); setLoading(false); });
|
||||||
}, [station, start, end]);
|
}, [selection]);
|
||||||
// The columns slide (style.css); Plotly only follows the window: at the end of the slide, the plots refit to their
|
// The columns slide (style.css); Plotly only follows the window: at the end of the slide, the plots refit to their
|
||||||
// new width (redrawing them at every frame of the slide would be too heavy)
|
// new width (redrawing them at every frame of the slide would be too heavy)
|
||||||
const slideEnd = e => { if (e.target === left.current && e.propertyName === "max-width") dispatchEvent(new Event("resize")); };
|
const slideEnd = e => { if (e.target === left.current && e.propertyName === "max-width") dispatchEvent(new Event("resize")); };
|
||||||
@@ -66,6 +66,7 @@ export default function Data({ selection, choose, analysis, setAnalysis }) {
|
|||||||
opens it.</Text>
|
opens it.</Text>
|
||||||
</div>
|
</div>
|
||||||
<Selector selection={selection} choose={choose} />
|
<Selector selection={selection} choose={choose} />
|
||||||
|
{data?.weather && <Text size="xs" c="dimmed" mt={-8}>Weather: {data.weather}.</Text>}
|
||||||
{loading && <Loader />}
|
{loading && <Loader />}
|
||||||
{data && <TargetFilter d={data} hidden={hidden} setHidden={setHidden} />}
|
{data && <TargetFilter d={data} hidden={hidden} setHidden={setHidden} />}
|
||||||
{data && <Curves key={`${station}${start}${end}`} selection={selection} d={data} setImage={(t, nearest) => setMoment({ t, nearest })}
|
{data && <Curves key={`${station}${start}${end}`} selection={selection} d={data} setImage={(t, nearest) => setMoment({ t, nearest })}
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import csv
|
|||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
import math
|
import math
|
||||||
|
import re
|
||||||
import sys
|
import sys
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
@@ -70,9 +71,9 @@ def locate(place):
|
|||||||
query = urllib.parse.urlencode({"searchText": place, "type": "locations", "limit": 1, "sr": 4326})
|
query = urllib.parse.urlencode({"searchText": place, "type": "locations", "limit": 1, "sr": 4326})
|
||||||
results = json.loads(fetch(f"{GEOCODER}?{query}"))["results"]
|
results = json.loads(fetch(f"{GEOCODER}?{query}"))["results"]
|
||||||
if not results:
|
if not results:
|
||||||
sys.exit(f"place not found: {place}")
|
raise LookupError(f"place not found: {place}")
|
||||||
attrs = results[0]["attrs"]
|
attrs = results[0]["attrs"]
|
||||||
label = attrs["label"].replace("<b>", "").replace("</b>", "").split("\n")[0].strip()
|
label = re.sub(r"<[^>]+>", "", attrs["label"]).split("\n")[0].strip()
|
||||||
return attrs["lat"], attrs["lon"], label
|
return attrs["lat"], attrs["lon"], label
|
||||||
|
|
||||||
|
|
||||||
@@ -137,7 +138,10 @@ def main():
|
|||||||
if args.start >= datetime.now(timezone.utc):
|
if args.start >= datetime.now(timezone.utc):
|
||||||
sys.exit("the range must be in the past")
|
sys.exit("the range must be in the past")
|
||||||
|
|
||||||
|
try:
|
||||||
lat, lon, label = locate(args.place)
|
lat, lon, label = locate(args.place)
|
||||||
|
except LookupError as e:
|
||||||
|
sys.exit(str(e))
|
||||||
station = nearest_station(lat, lon)
|
station = nearest_station(lat, lon)
|
||||||
abbr = station["station_abbr"]
|
abbr = station["station_abbr"]
|
||||||
print(f"{label} ({lat:.4f}, {lon:.4f}) -> station {abbr} {station['station_name']}, "
|
print(f"{label} ({lat:.4f}, {lon:.4f}) -> station {abbr} {station['station_name']}, "
|
||||||
|
|||||||
Reference in new issue
Block a user