erp-gpt-eu / data_utils.py
Kuangdai
Initial release of ERP-GPT-EU
b8bc5ba
Raw
History Blame Contribute Delete
16.5 kB
import json
import pickle
from typing import Tuple, Optional, List, Dict, Any
import numpy as np
import pandas as pd
from geopy.distance import geodesic
from gadm_utils import GADMHandler
from geo_utils import resolve_place
from plot_utils import scatter_plot
import ast
class LUCASSoilData:
def __init__(self, table_path: str, dict_path: str,
column_names_path: str,
gadm_handler: GADMHandler) -> None:
self.df = pd.read_csv(table_path, low_memory=False)
self.df["LAT_LONG"] = self.df["LAT_LONG"].apply(
lambda x: ast.literal_eval(x) if isinstance(x, str) else x
)
with open(column_names_path, 'r') as f:
self.column_names = json.load(f)["column_names"]
self.property_map = {}
for full_name in self.column_names:
base, unit = full_name.split("(", maxsplit=1) if "(" in full_name else (full_name, None)
if unit is not None:
unit = unit[:-1].strip() # remove trailing ")"
theme, prop = [x.strip() for x in base.split(":", 1)]
self.property_map[prop] = (full_name, theme, unit)
with open(dict_path, 'rb') as f:
self.sample_dict = pickle.load(f)
self.gadm_handler = gadm_handler
def resolve_theme_property_unit(self, input_string: str) -> Tuple[str, str, str, Optional[str]]:
"""
Resolve and return (full_name, theme, property, unit) from a user input string.
The user may provide:
- full form: "theme:property (unit)"
- partial form: "theme:property"
- property only: "property"
"""
input_string = input_string.strip()
# Extract unit if present
if "(" in input_string:
base, input_unit = input_string.split("(", maxsplit=1)
input_unit = input_unit[:-1].strip() # remove trailing ")"
else:
base, input_unit = input_string, None
# Extract theme + property
if ":" in base:
input_theme, input_property = [x.strip() for x in base.split(":", 1)]
else:
input_theme, input_property = None, base.strip()
# Property must exist
if input_property not in self.property_map:
raise ValueError(f"Property '{input_property}' not found in dataset.")
full_name, expected_theme, expected_unit = self.property_map[input_property]
# Validate theme if user supplied one
if input_theme is not None and input_theme != expected_theme:
raise ValueError(f"Theme mismatch: expected '{expected_theme}', got '{input_theme}'.")
# Validate unit if user supplied one
if input_unit is not None and input_unit != expected_unit:
raise ValueError(f"Unit mismatch for '{input_property}': expected '{expected_unit}', got '{input_unit}'.")
return full_name, expected_theme, input_property, expected_unit
def get_point(self,
place: str | tuple[float, float],
properties: List[str],
distance_top_k: int = 20,
distance_limit: float = 200000,
session_name: Optional[str] = None) -> Dict[str, Any]:
"""
Retrieve soil data near a place, selecting the best among top-k nearest samples.
Rules:
1) Find top-k nearest samples (by squared distance, then geodesic meters).
2) Exclude samples farther than `distance_limit` (meters).
3) From remaining samples, choose the one with the most valid properties.
(valid = property exists AND sample[...] has non-None "value").
Tie-break: smaller distance wins.
4) If all survivors have zero valid properties, return Failed.
5) Resolver is strict: if user requests an unknown property, immediate Failed.
Output always contains `query_input` and `query_status`. Sample data is
included only for success or partial success cases.
"""
# always include input record in response
query_input = {
"place": place,
"properties": properties,
"distance_limit": distance_limit,
"distance_top_k": distance_top_k,
}
# ---------- Resolve place → (lat, lon) ----------
try:
if isinstance(place, str):
if place not in self.gadm_handler.tree:
resolved = resolve_place(place, session_name=session_name, gadm_handler=self.gadm_handler)
gid = resolved.get("gid")
if gid is None:
return {
"query_input": query_input,
"query_status": f"Failed. Cannot resolve place: {place}",
"query_output": {}
}
else:
gid = place
geom_info = self.gadm_handler.get_geometry_info(gid)
if geom_info is None:
return {
"query_input": query_input,
"query_status": f"Failed. Cannot get geometry for place (GID): {place} ({gid})",
"query_output": {}
}
lat, lon = geom_info["latitude"], geom_info["longitude"]
else:
lat, lon = place
except Exception as e:
return {
"query_input": query_input,
"query_status": f"Failed. {str(e)}",
"query_output": {}
}
# ---------- Strict property resolution (fail if any invalid) ----------
resolved_props = []
try:
for input_prop in properties:
full_name, theme, prop, unit = self.resolve_theme_property_unit(input_prop)
resolved_props.append((theme, prop, input_prop))
except Exception as e:
return {
"query_input": query_input,
"query_status": f"Failed. {str(e)}",
"query_output": {}
}
# ---------- Find top-k nearest candidates ----------
try:
latlon = np.vstack(self.df["LAT_LONG"].values).astype(float) # (N, 2)
d2 = (latlon[:, 0] - lat) ** 2 + (latlon[:, 1] - lon) ** 2
k = max(1, min(distance_top_k, len(d2)))
idx_k = np.argpartition(d2, kth=k - 1)[:k]
candidates = []
for idx in idx_k:
sample_lat, sample_lon = latlon[idx]
dist_m = geodesic((lat, lon), (sample_lat, sample_lon)).meters
candidates.append((idx, dist_m))
survivors = [(idx, dist_m) for (idx, dist_m) in candidates if dist_m <= distance_limit]
if not survivors:
return {
"query_input": query_input,
"query_status": f"Failed. No nearby samples within {distance_limit:g} m.",
"query_output": {}
}
except Exception as e:
return {
"query_input": query_input,
"query_status": f"Failed. Error during nearest-point search: {str(e)}",
"query_output": {}
}
# ---------- Score survivors by valid property count, then distance ----------
def count_valid(idx: int) -> int:
row = self.df.iloc[idx]
src = self.sample_dict.get(row["id"], {})
valid = 0
for theme, prop, _orig in resolved_props:
try:
val = src[theme][prop]["value"]
if val is not None:
valid += 1
except Exception:
pass
return valid
scored = [(idx, dist, count_valid(idx)) for idx, dist in survivors]
scored.sort(key=lambda x: (-x[2], x[1])) # most valid props, then nearest
best_idx, best_dist, best_valid = scored[0]
if best_valid == 0:
return {
"query_input": query_input,
"query_status": (
"Failed. No sample within "
f"{distance_limit:g} m contains any of the requested properties."
),
"query_output": {}
}
# ---------- Build result for best candidate ----------
try:
row = self.df.iloc[best_idx]
source = self.sample_dict[row["id"]]
except Exception:
return {
"query_input": query_input,
"query_status": f"Failed. Sample data missing for best candidate.",
"query_output": {}
}
result = {}
for key in ["LAT_LONG", "GADM_IDS", "GADM_NAMES", "COUNTRY_CODE",
"SAMPLE_DATE", "SAMPLE_DEPTH_RANGE_CM", "SAMPLE_SOURCE_DATASET"]:
result[key] = source.get(key)
failed_props = []
for theme, prop, original_input in resolved_props:
try:
val = source[theme][prop]["value"]
if val is not None:
if theme not in result:
result[theme] = {}
result[theme][prop] = val
else:
failed_props.append(original_input)
except Exception:
failed_props.append(original_input)
if failed_props and len(failed_props) < len(resolved_props):
status = (
"Partial success. Some properties were not available: "
+ ", ".join(failed_props)
+ f". Distance to nearest sample (m): {best_dist:.1f}."
)
else:
status = f"Success. Distance to nearest sample (m): {best_dist:.1f}."
result["entry_key"] = row["id"]
return {
"query_output": result,
"query_input": query_input,
"query_status": status,
}
def get_map(self,
place: str | tuple[float, float, float],
properties: List[str],
session_name: Optional[str] = None,
**kwargs) -> Dict[str, Any]:
"""
Generate scatter plots for the specified properties around a GADM region.
Returns:
{
"query_output": { "<full_name>": "<url or warning string>", ... },
"query_input": { "place": ..., "properties": [...] },
"query_status": "Success. N plot(s) generated." | "Failed. <reason>"
}
"""
# Always include the input
query_input = {"place": place, "properties": properties}
# ---------- Resolve place → gid (and lat/lon if needed) ----------
try:
if isinstance(place, str):
if place not in self.gadm_handler.tree:
resolved = resolve_place(place, session_name=session_name, gadm_handler=self.gadm_handler)
gid = resolved.get("gid")
if gid is None:
return {"query_input": query_input,
"query_status": f"Failed. Cannot resolve place: {place}",
"query_output": {}}
else:
gid = place
else:
# tuple expected: (lat, lon, bbox_area)
if len(place) != 3:
return {"query_input": query_input,
"query_status": "Failed. Tuple `place` must be (lat, lon, bbox_area).",
"query_output": {}}
lat, lon, bbox_area = place
gid = self.gadm_handler.find_gid(lat, lon, bbox_area)
if gid is None:
return {"query_input": query_input,
"query_status": "Failed. No matching GADM region found for given coordinates.",
"query_output": {}}
geom_info = self.gadm_handler.get_geometry_info(gid)
if geom_info is None:
return {"query_input": query_input,
"query_status": f"Failed. Cannot get geometry for place (GID): {gid}",
"query_output": {}}
except Exception as e:
return {"query_input": query_input, "query_status": f"Failed. {str(e)}",
"query_output": {}}
# ---------- Strict property resolution (fail if any invalid) ----------
resolved = []
try:
for input_prop in properties:
full_name, theme, prop, unit = self.resolve_theme_property_unit(input_prop)
resolved.append((full_name, theme, prop, unit))
except Exception as e:
return {"query_input": query_input, "query_status": f"Failed. {str(e)}", "query_output": {}}
if len(resolved) > 5:
return {"query_input": query_input,
"query_status": "Failed. API does not accept more than 5 properties.",
"query_output": {}}
# ---------- Compute map extent using gid + siblings ----------
try:
siblings = self.gadm_handler.get_tree_info(gid)["siblings"]
gids = [gid] + siblings
polygon = self.gadm_handler.get_polygon(gid)
minx, miny, maxx, maxy = polygon.bounds
# 100% margin
dlat = (maxy - miny) or 1.0
dlon = (maxx - minx) or 1.0
lat_min, lat_max = miny - dlat, maxy + dlat
lon_min, lon_max = minx - dlon, maxx + dlon
except Exception as e:
return {"query_input": query_input, "query_status": f"Failed. {str(e)}", "query_output": {}}
# ---------- Region filter using LAT_LONG ----------
try:
latlon = np.vstack(self.df["LAT_LONG"].values).astype(float) # shape (N,2)
lats, lons = latlon[:, 0], latlon[:, 1]
mask = (lats >= lat_min) & (lats <= lat_max) & (lons >= lon_min) & (lons <= lon_max)
df_region = self.df[mask]
except Exception as e:
return {"query_input": query_input, "query_status": f"Failed. {str(e)}", "query_output": {}}
# ---------- Plot helper (returns URL or warning string) ----------
def plot_one(full_name: str, prop: str) -> str:
try:
if full_name not in df_region.columns:
return "Skipped. No valid data."
# Build [lat, lon, value]
values = pd.to_numeric(df_region[full_name], errors="coerce")
ok = values.notna()
if not ok.any():
return "Skipped. No valid data."
# extract lat/lon for the same rows
latlon_sub = np.vstack(df_region.loc[ok, "LAT_LONG"].values).astype(float)
data = np.column_stack([latlon_sub[:, 0], latlon_sub[:, 1], values.loc[ok].astype(float).values])
# numeric vs categorical: if after coercion we have floats, treat as numeric.
# If you need categorical, you can branch by dtype before coercion.
img_path = scatter_plot(
gadm_handler=self.gadm_handler,
data=data,
is_categorical=False,
short_name=prop,
long_name=full_name,
map_boundary_gadm_gids=gids,
map_limits="gadm_first",
session_name=session_name,
**kwargs
)
return img_path
except Exception:
return "Skipped. No valid data."
# ---------- Generate outputs (flat) ----------
query_output: Dict[str, str] = {}
for full_name, theme, prop, unit in resolved:
query_output[full_name] = plot_one(full_name, prop)
# ---------- Status ----------
n_plots = sum(1 for v in query_output.values() if isinstance(v, str) and v.endswith(".png"))
if n_plots >= 1:
status = f"Success. {n_plots} plot{'s' if n_plots != 1 else ''} generated."
else:
status = "Failed. No plots generated."
return {
"query_output": query_output,
"query_input": query_input,
"query_status": status,
}