Datasets:
File size: 16,501 Bytes
b8bc5ba | 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 | 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,
}
|