585 lines
20 KiB
Python
585 lines
20 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
|
|
|
|
from . import points, style
|
|
from .i18n import tr
|
|
|
|
Field = Tuple[str, str]
|
|
Row = Dict[str, Any]
|
|
|
|
|
|
def _row(geometry: Optional[Mapping[str, Any]], spec: Sequence[Field],
|
|
values: Mapping[str, Any]) -> Row:
|
|
return {
|
|
"geometry": geometry,
|
|
"attrs": {name: values.get(name) for name, _kind in spec},
|
|
}
|
|
|
|
|
|
def _point(lon: Any, lat: Any) -> Optional[Dict[str, Any]]:
|
|
try:
|
|
x, y = float(lon), float(lat)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
return {"type": "Point", "coordinates": [x, y]}
|
|
|
|
|
|
def _line(a: Sequence[float], b: Sequence[float]) -> Dict[str, Any]:
|
|
return {"type": "LineString",
|
|
"coordinates": [[float(a[0]), float(a[1])],
|
|
[float(b[0]), float(b[1])]]}
|
|
|
|
|
|
def _number(value: Any) -> Optional[float]:
|
|
if value is None or isinstance(value, bool):
|
|
return None
|
|
try:
|
|
return float(value)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
def _text(value: Any) -> Optional[str]:
|
|
if value is None:
|
|
return None
|
|
if isinstance(value, (list, tuple)):
|
|
return ", ".join(str(item) for item in value if item is not None) or None
|
|
if isinstance(value, Mapping):
|
|
return json.dumps(value, ensure_ascii=False, sort_keys=True)
|
|
text = str(value)
|
|
return text or None
|
|
|
|
|
|
def _integer(value: Any) -> Optional[int]:
|
|
number = _number(value)
|
|
return None if number is None else int(number)
|
|
|
|
|
|
def metadata(payload: Mapping[str, Any]) -> Dict[str, Any]:
|
|
meta = payload.get("metadata") if isinstance(payload, Mapping) else None
|
|
return dict(meta) if isinstance(meta, Mapping) else {}
|
|
|
|
|
|
ISOCHRONE_FIELDS: Sequence[Field] = (
|
|
("contour", "double"),
|
|
("unit", "string"),
|
|
("label", "string"),
|
|
("metric", "string"),
|
|
("mode", "string"),
|
|
("color", "string"),
|
|
)
|
|
|
|
|
|
def isochrone_rows(payload: Mapping[str, Any]) -> List[Row]:
|
|
rows: List[Row] = []
|
|
for feature in (payload or {}).get("features") or []:
|
|
if not isinstance(feature, Mapping):
|
|
continue
|
|
props = feature.get("properties")
|
|
props = props if isinstance(props, Mapping) else {}
|
|
contour = _number(props.get("contour"))
|
|
unit = _text(props.get("unit")) or ""
|
|
label = "%s %s" % (points.fmt(contour), unit) if contour is not None else ""
|
|
rows.append(_row(feature.get("geometry"), ISOCHRONE_FIELDS, {
|
|
"contour": contour,
|
|
"unit": unit,
|
|
"label": label.strip(),
|
|
"metric": _text(props.get("metric")),
|
|
"mode": _text(props.get("mode")),
|
|
"color": _text(props.get("color")),
|
|
}))
|
|
return rows
|
|
|
|
|
|
ROUTE_LEG_FIELDS: Sequence[Field] = (
|
|
("leg", "integer"),
|
|
("from_point", "integer"),
|
|
("to_point", "integer"),
|
|
("km", "double"),
|
|
("minutes", "double"),
|
|
("directions", "string"),
|
|
("color", "string"),
|
|
)
|
|
|
|
ROUTE_STOP_FIELDS: Sequence[Field] = (
|
|
("stop", "integer"),
|
|
("input", "integer"),
|
|
("role", "string"),
|
|
("lon", "double"),
|
|
("lat", "double"),
|
|
("snapped_lon", "double"),
|
|
("snapped_lat", "double"),
|
|
("color", "string"),
|
|
)
|
|
|
|
|
|
def _directions(steps: Any) -> Optional[str]:
|
|
if not isinstance(steps, (list, tuple)):
|
|
return None
|
|
parts = []
|
|
for entry in steps:
|
|
if not isinstance(entry, Mapping):
|
|
continue
|
|
text = _text(entry.get("instruction"))
|
|
if text:
|
|
parts.append(text)
|
|
return " · ".join(parts) or None
|
|
|
|
|
|
def route_rows(payload: Mapping[str, Any]) -> Tuple[List[Row], List[Row]]:
|
|
legs = [leg for leg in (payload or {}).get("legs") or [] if isinstance(leg, Mapping)]
|
|
by_leg = {_integer(leg.get("leg")): leg for leg in legs}
|
|
|
|
collection = (payload or {}).get("routes")
|
|
features = (collection or {}).get("features") or [] if isinstance(collection, Mapping) else []
|
|
|
|
leg_rows: List[Row] = []
|
|
for index, feature in enumerate(features):
|
|
if not isinstance(feature, Mapping):
|
|
continue
|
|
props = feature.get("properties")
|
|
props = props if isinstance(props, Mapping) else {}
|
|
number = _integer(props.get("leg"))
|
|
number = index if number is None else number
|
|
leg = by_leg.get(number) or {}
|
|
leg_rows.append(_row(feature.get("geometry"), ROUTE_LEG_FIELDS, {
|
|
"leg": number,
|
|
"from_point": _integer(props.get("from")),
|
|
"to_point": _integer(props.get("to")),
|
|
"km": _number(props.get("km")),
|
|
"minutes": _number(props.get("min")),
|
|
"directions": _directions(leg.get("steps")),
|
|
"color": style.leg_color(number),
|
|
}))
|
|
|
|
stops = [stop for stop in (payload or {}).get("points") or []
|
|
if isinstance(stop, Mapping)]
|
|
stop_rows: List[Row] = []
|
|
for position, stop in enumerate(stops):
|
|
snapped = stop.get("snapped")
|
|
snapped = snapped if isinstance(snapped, (list, tuple)) and len(snapped) == 2 else None
|
|
if position == 0:
|
|
role = tr("start")
|
|
elif position == len(stops) - 1:
|
|
role = tr("destination")
|
|
else:
|
|
role = tr("stopover")
|
|
order = _integer(stop.get("order")) if stop.get("order") is not None else position
|
|
stop_rows.append(_row(_point(stop.get("lon"), stop.get("lat")),
|
|
ROUTE_STOP_FIELDS, {
|
|
"stop": order,
|
|
"input": _integer(stop.get("index")),
|
|
"role": role,
|
|
"lon": _number(stop.get("lon")),
|
|
"lat": _number(stop.get("lat")),
|
|
"snapped_lon": _number(snapped[0]) if snapped else None,
|
|
"snapped_lat": _number(snapped[1]) if snapped else None,
|
|
"color": style.leg_color(min(order if order is not None else position,
|
|
max(len(leg_rows) - 1, 0))),
|
|
}))
|
|
return leg_rows, stop_rows
|
|
|
|
|
|
def route_summary(payload: Mapping[str, Any]) -> str:
|
|
total = (payload or {}).get("total")
|
|
total = total if isinstance(total, Mapping) else {}
|
|
km = _number(total.get("km")) or 0.0
|
|
minutes = _number(total.get("min")) or 0.0
|
|
return tr("{km} km · {minutes} minutes").format(
|
|
km=points.fmt(round(km, 1)), minutes=points.fmt(round(minutes, 1)))
|
|
|
|
|
|
PROFILE_FIELDS: Sequence[Field] = (
|
|
("point", "integer"),
|
|
("distance", "double"),
|
|
("elevation", "double"),
|
|
("source", "string"),
|
|
("state", "string"),
|
|
)
|
|
|
|
|
|
def profile_rows(payload: Mapping[str, Any]) -> List[Row]:
|
|
rows: List[Row] = []
|
|
for index, point in enumerate((payload or {}).get("points") or []):
|
|
if not isinstance(point, Mapping):
|
|
continue
|
|
rows.append(_row(_point(point.get("lon"), point.get("lat")),
|
|
PROFILE_FIELDS, {
|
|
"point": index,
|
|
"distance": _number(point.get("distance")),
|
|
"elevation": _number(point.get("elevation")),
|
|
"source": _text(point.get("attribution")),
|
|
"state": _text(point.get("state")),
|
|
}))
|
|
return rows
|
|
|
|
|
|
PROFILE_SEGMENT_FIELDS: Sequence[Field] = (
|
|
("segment", "integer"),
|
|
("from_distance", "double"),
|
|
("to_distance", "double"),
|
|
("length", "double"),
|
|
("rise", "double"),
|
|
("slope", "double"),
|
|
("slope_class", "string"),
|
|
("color", "string"),
|
|
)
|
|
|
|
|
|
def _slope(run: Optional[float], low: Optional[float],
|
|
high: Optional[float]) -> Optional[float]:
|
|
if run is None or run <= 0 or low is None or high is None:
|
|
return None
|
|
return round((high - low) / run * 100.0, 2)
|
|
|
|
|
|
def _direction(rise: Optional[float]) -> str:
|
|
if rise is None:
|
|
return "none"
|
|
if rise > 0:
|
|
return "up"
|
|
if rise < 0:
|
|
return "down"
|
|
return "level"
|
|
|
|
|
|
def profile_segment_rows(payload: Mapping[str, Any]) -> List[Row]:
|
|
samples = []
|
|
for point in (payload or {}).get("points") or []:
|
|
if not isinstance(point, Mapping):
|
|
continue
|
|
distance = _number(point.get("distance"))
|
|
lon, lat = _number(point.get("lon")), _number(point.get("lat"))
|
|
if distance is None or lon is None or lat is None:
|
|
continue
|
|
samples.append((distance, lon, lat, _number(point.get("elevation"))))
|
|
|
|
runs: List[Dict[str, Any]] = []
|
|
for index in range(1, len(samples)):
|
|
start, finish = samples[index - 1], samples[index]
|
|
slope = _slope(finish[0] - start[0], start[3], finish[3])
|
|
name = style.slope_class(slope)
|
|
key = (name, _direction(None if slope is None else finish[3] - start[3]))
|
|
if runs and runs[-1]["key"] == key:
|
|
runs[-1]["points"].append(finish)
|
|
else:
|
|
runs.append({"key": key, "class": name,
|
|
"points": [start, finish]})
|
|
|
|
rows: List[Row] = []
|
|
for number, run in enumerate(runs):
|
|
chain = run["points"]
|
|
first, last = chain[0], chain[-1]
|
|
length = last[0] - first[0]
|
|
rise = None if first[3] is None or last[3] is None else round(last[3] - first[3], 2)
|
|
rows.append(_row({"type": "LineString",
|
|
"coordinates": [[p[1], p[2]] for p in chain]},
|
|
PROFILE_SEGMENT_FIELDS, {
|
|
"segment": number,
|
|
"from_distance": round(first[0], 2),
|
|
"to_distance": round(last[0], 2),
|
|
"length": round(length, 2),
|
|
"rise": rise,
|
|
"slope": _slope(length, first[3], last[3]),
|
|
"slope_class": run["class"],
|
|
"color": style.SLOPE_COLORS[run["class"]],
|
|
}))
|
|
return rows
|
|
|
|
|
|
def collection(rows: Sequence[Row]) -> Dict[str, Any]:
|
|
return {
|
|
"type": "FeatureCollection",
|
|
"features": [{"type": "Feature",
|
|
"geometry": row.get("geometry"),
|
|
"properties": dict(row.get("attrs") or {})}
|
|
for row in rows],
|
|
}
|
|
|
|
|
|
def profile_series(payload: Mapping[str, Any]) -> List[Tuple[float, Optional[float]]]:
|
|
out: List[Tuple[float, Optional[float]]] = []
|
|
for point in (payload or {}).get("points") or []:
|
|
if not isinstance(point, Mapping):
|
|
continue
|
|
distance = _number(point.get("distance"))
|
|
if distance is None:
|
|
continue
|
|
out.append((distance, _number(point.get("elevation"))))
|
|
return out
|
|
|
|
|
|
def profile_coordinates(payload: Mapping[str, Any]) -> List[Tuple[float, float]]:
|
|
out: List[Tuple[float, float]] = []
|
|
for point in (payload or {}).get("points") or []:
|
|
if not isinstance(point, Mapping):
|
|
continue
|
|
if _number(point.get("distance")) is None:
|
|
continue
|
|
lon = _number(point.get("lon"))
|
|
lat = _number(point.get("lat"))
|
|
out.append((float("nan") if lon is None else lon,
|
|
float("nan") if lat is None else lat))
|
|
return out
|
|
|
|
|
|
def profile_summary(payload: Mapping[str, Any]) -> str:
|
|
rows = [_number(p.get("elevation")) for p in (payload or {}).get("points") or []
|
|
if isinstance(p, Mapping)]
|
|
known = [value for value in rows if value is not None]
|
|
meta = metadata(payload)
|
|
length = _number(meta.get("length")) or 0.0
|
|
if not known:
|
|
return tr("{count} points, no elevation data").format(count=len(rows))
|
|
return tr("{count} points over {length} m · {low} to {high} m above sea level").format(
|
|
count=len(rows), length=points.fmt(round(length, 1)),
|
|
low=points.fmt(round(min(known), 1)), high=points.fmt(round(max(known), 1)))
|
|
|
|
|
|
ELEVATION_FIELDS: Sequence[Field] = (
|
|
("elevation", "double"),
|
|
("ele_source", "string"),
|
|
("ele_state", "string"),
|
|
)
|
|
|
|
|
|
def elevation_values(payload: Mapping[str, Any]) -> List[Dict[str, Any]]:
|
|
out: List[Dict[str, Any]] = []
|
|
for point in (payload or {}).get("points") or []:
|
|
if not isinstance(point, Mapping):
|
|
out.append({"elevation": None, "ele_source": None, "ele_state": None})
|
|
continue
|
|
out.append({
|
|
"elevation": _number(point.get("elevation")),
|
|
"ele_source": _text(point.get("attribution")),
|
|
"ele_state": _text(point.get("state")),
|
|
})
|
|
return out
|
|
|
|
|
|
ELEVATION_POINT_FIELDS: Sequence[Field] = (
|
|
("point", "integer"),
|
|
("lon", "double"),
|
|
("lat", "double"),
|
|
("elevation", "double"),
|
|
("ele_source", "string"),
|
|
("ele_state", "string"),
|
|
)
|
|
|
|
|
|
def elevation_point_rows(payload: Mapping[str, Any],
|
|
coordinates: Sequence[Sequence[float]]) -> List[Row]:
|
|
values = elevation_values(payload)
|
|
rows: List[Row] = []
|
|
for index, pair in enumerate(coordinates or []):
|
|
try:
|
|
lon, lat = float(pair[0]), float(pair[1])
|
|
except (TypeError, ValueError, IndexError):
|
|
continue
|
|
found = values[index] if index < len(values) else {}
|
|
rows.append(_row(_point(lon, lat), ELEVATION_POINT_FIELDS, {
|
|
"point": index,
|
|
"lon": lon,
|
|
"lat": lat,
|
|
"elevation": found.get("elevation"),
|
|
"ele_source": found.get("ele_source"),
|
|
"ele_state": found.get("ele_state"),
|
|
}))
|
|
return rows
|
|
|
|
|
|
SIGHT_FIELDS: Sequence[Field] = (
|
|
("visible", "boolean"),
|
|
("length", "double"),
|
|
("air_line", "double"),
|
|
("height_a", "double"),
|
|
("height_b", "double"),
|
|
("terrain_a", "double"),
|
|
("terrain_b", "double"),
|
|
("min_clearance", "double"),
|
|
("min_clearance_at", "double"),
|
|
("raise_a", "double"),
|
|
("raise_b", "double"),
|
|
("obstacles", "integer"),
|
|
)
|
|
|
|
OBSTACLE_FIELDS: Sequence[Field] = (
|
|
("obstacle", "integer"),
|
|
("distance", "double"),
|
|
("from_distance", "double"),
|
|
("to_distance", "double"),
|
|
("height", "double"),
|
|
("terrain", "double"),
|
|
)
|
|
|
|
SAMPLE_FIELDS: Sequence[Field] = (
|
|
("point", "integer"),
|
|
("distance", "double"),
|
|
("terrain", "double"),
|
|
("sight", "double"),
|
|
("clearance", "double"),
|
|
("drop", "double"),
|
|
("blocked", "boolean"),
|
|
)
|
|
|
|
SIGHT_SEGMENT_FIELDS: Sequence[Field] = (
|
|
("segment", "integer"),
|
|
("visible", "boolean"),
|
|
("from_distance", "double"),
|
|
("to_distance", "double"),
|
|
("length", "double"),
|
|
("min_clearance", "double"),
|
|
("color", "string"),
|
|
)
|
|
|
|
|
|
def _ends(payload: Mapping[str, Any],
|
|
fallback_start: Sequence[float],
|
|
fallback_end: Sequence[float]) -> Tuple[points.Point, points.Point]:
|
|
out = []
|
|
for key, fallback in (("from", fallback_start), ("to", fallback_end)):
|
|
entry = (payload or {}).get(key)
|
|
entry = entry if isinstance(entry, Mapping) else {}
|
|
lon = _number(entry.get("lon"))
|
|
lat = _number(entry.get("lat"))
|
|
if lon is None or lat is None:
|
|
out.append((float(fallback[0]), float(fallback[1])))
|
|
else:
|
|
out.append((lon, lat))
|
|
return out[0], out[1]
|
|
|
|
|
|
def _placer(payload: Mapping[str, Any], start: Sequence[float],
|
|
end: Sequence[float]):
|
|
a, b = _ends(payload, start, end)
|
|
length = _number((payload or {}).get("length")) or 0.0
|
|
|
|
def place(distance: Any) -> Optional[Tuple[float, float]]:
|
|
metres = _number(distance)
|
|
if metres is None:
|
|
return None
|
|
fraction = metres / length if length > 0 else 0.0
|
|
return points.along(a, b, fraction)
|
|
|
|
return a, b, length, place
|
|
|
|
|
|
def sight_segment_rows(payload: Mapping[str, Any], start: Sequence[float],
|
|
end: Sequence[float]) -> List[Row]:
|
|
_a, _b, _length, place = _placer(payload, start, end)
|
|
|
|
samples = []
|
|
for entry in (payload or {}).get("samples") or []:
|
|
if not isinstance(entry, Mapping):
|
|
continue
|
|
distance = _number(entry.get("distance"))
|
|
spot = place(distance)
|
|
if distance is None or spot is None:
|
|
continue
|
|
samples.append((distance, spot, _number(entry.get("clearance"))))
|
|
|
|
runs: List[Dict[str, Any]] = []
|
|
for index in range(1, len(samples)):
|
|
before, now = samples[index - 1], samples[index]
|
|
blocked = now[2] is not None and now[2] < 0
|
|
if runs and runs[-1]["blocked"] == blocked:
|
|
runs[-1]["points"].append(now)
|
|
else:
|
|
runs.append({"blocked": blocked, "points": [before, now]})
|
|
|
|
rows: List[Row] = []
|
|
for number, run in enumerate(runs):
|
|
chain = run["points"]
|
|
clearances = [entry[2] for entry in chain if entry[2] is not None]
|
|
visible = not run["blocked"]
|
|
rows.append(_row({"type": "LineString",
|
|
"coordinates": [[spot[0], spot[1]] for _d, spot, _c in chain]},
|
|
SIGHT_SEGMENT_FIELDS, {
|
|
"segment": number,
|
|
"visible": visible,
|
|
"from_distance": round(chain[0][0], 2),
|
|
"to_distance": round(chain[-1][0], 2),
|
|
"length": round(chain[-1][0] - chain[0][0], 2),
|
|
"min_clearance": round(min(clearances), 2) if clearances else None,
|
|
"color": style.sight_color(run["blocked"]),
|
|
}))
|
|
return rows
|
|
|
|
|
|
def sight_rows(payload: Mapping[str, Any], start: Sequence[float],
|
|
end: Sequence[float]) -> Tuple[List[Row], List[Row], List[Row]]:
|
|
a, b, length, spot = _placer(payload, start, end)
|
|
|
|
def place(distance: Any) -> Optional[Dict[str, Any]]:
|
|
found = spot(distance)
|
|
return None if found is None else _point(found[0], found[1])
|
|
|
|
first = (payload or {}).get("from")
|
|
first = first if isinstance(first, Mapping) else {}
|
|
last = (payload or {}).get("to")
|
|
last = last if isinstance(last, Mapping) else {}
|
|
obstacles = [o for o in (payload or {}).get("obstacles") or [] if isinstance(o, Mapping)]
|
|
|
|
line = _row(_line(a, b), SIGHT_FIELDS, {
|
|
"visible": bool((payload or {}).get("visible")),
|
|
"length": length,
|
|
"air_line": _number((payload or {}).get("air_line")),
|
|
"height_a": _number(first.get("height")),
|
|
"height_b": _number(last.get("height")),
|
|
"terrain_a": _number(first.get("terrain")),
|
|
"terrain_b": _number(last.get("terrain")),
|
|
"min_clearance": _number((payload or {}).get("min_clearance")),
|
|
"min_clearance_at": _number((payload or {}).get("min_clearance_distance")),
|
|
"raise_a": _number((payload or {}).get("required_extra_a")),
|
|
"raise_b": _number((payload or {}).get("required_extra_b")),
|
|
"obstacles": len(obstacles),
|
|
})
|
|
|
|
obstacle_rows = [
|
|
_row(place(entry.get("distance")), OBSTACLE_FIELDS, {
|
|
"obstacle": index,
|
|
"distance": _number(entry.get("distance")),
|
|
"from_distance": _number(entry.get("from")),
|
|
"to_distance": _number(entry.get("to")),
|
|
"height": _number(entry.get("height")),
|
|
"terrain": _number(entry.get("terrain")),
|
|
})
|
|
for index, entry in enumerate(obstacles)
|
|
]
|
|
|
|
sample_rows = []
|
|
for index, entry in enumerate((payload or {}).get("samples") or []):
|
|
if not isinstance(entry, Mapping):
|
|
continue
|
|
clearance = _number(entry.get("clearance"))
|
|
sample_rows.append(_row(place(entry.get("distance")), SAMPLE_FIELDS, {
|
|
"point": index,
|
|
"distance": _number(entry.get("distance")),
|
|
"terrain": _number(entry.get("terrain")),
|
|
"sight": _number(entry.get("sight")),
|
|
"clearance": clearance,
|
|
"drop": _number(entry.get("drop")),
|
|
"blocked": None if clearance is None else clearance < 0,
|
|
}))
|
|
|
|
return [line], obstacle_rows, sample_rows
|
|
|
|
|
|
def sight_summary(payload: Mapping[str, Any]) -> str:
|
|
length = _number((payload or {}).get("length")) or 0.0
|
|
if (payload or {}).get("visible"):
|
|
clearance = _number((payload or {}).get("min_clearance"))
|
|
if clearance is None:
|
|
return tr("Clear line of sight over {length} m.").format(
|
|
length=points.fmt(round(length, 1)))
|
|
return tr("Clear line of sight over {length} m · {clearance} m to spare.").format(
|
|
length=points.fmt(round(length, 1)),
|
|
clearance=points.fmt(round(clearance, 1)))
|
|
obstacles = [o for o in (payload or {}).get("obstacles") or [] if isinstance(o, Mapping)]
|
|
raise_a = _number((payload or {}).get("required_extra_a")) or 0.0
|
|
return tr("Blocked by {count} obstacle(s) · {raise_a} m more height at the "
|
|
"first point would clear it.").format(
|
|
count=len(obstacles), raise_a=points.fmt(round(raise_a, 1)))
|