Datasets:
Download plot_utils.py from earthroverprogram/erp-gpt-eu: direct link, hf CLI and curl.
- Browser
- Download file 9 kB
-
https://huggingface.co/datasets/earthroverprogram/erp-gpt-eu/resolve/main/plot_utils.py
- Command line
-
hf download hf://datasets/earthroverprogram/erp-gpt-eu/plot_utils.py
-
curl -L -o plot_utils.py https://huggingface.co/datasets/earthroverprogram/erp-gpt-eu/resolve/main/plot_utils.py
9 kB
| import os | |
| import re | |
| from typing import List, Tuple, Literal | |
| import cartopy.crs as ccrs | |
| import cartopy.feature as cfeature | |
| import geopandas as gpd | |
| import matplotlib | |
| matplotlib.use("Agg") # Use non-GUI backend for image generation | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| from matplotlib.colors import ListedColormap | |
| from gadm_utils import GADMHandler | |
| def get_boundingbox(lats: np.ndarray, lons: np.ndarray) -> tuple[float, float, float, float]: | |
| """ | |
| Compute the bounding box of a set of latitudes and longitudes, | |
| returning in Nominatim convention: (lat_min, lat_max, lon_min, lon_max). | |
| Handles wraparound at the 0/360 meridian for longitudes. | |
| """ | |
| lat_min, lat_max = lats.min(), lats.max() | |
| lons_360 = np.mod(lons, 360) | |
| span_regular = lons.max() - lons.min() | |
| span_wrapped = lons_360.max() - lons_360.min() | |
| lons_used = lons_360 if span_wrapped < span_regular else lons | |
| lon_min, lon_max = lons_used.min(), lons_used.max() | |
| return lat_min, lat_max, lon_min, lon_max | |
| def scatter_plot(gadm_handler: GADMHandler, | |
| data: np.ndarray = None, is_categorical: bool = None, | |
| short_name: str = "plot", long_name: str = "", save_dir: str = "plots", | |
| session_name: str = None, cmap_float: str = "turbo", cmap_str: str = "tab20", | |
| scatter_size: float | Literal["auto"] = "auto", | |
| map_boundary_gadm_gids: List[str] = None, | |
| map_limits: Tuple[float, float, float, float] | Literal["data", "gadm_all", "gadm_first"] = "data", | |
| map_margin_ratio: float = 0.2, | |
| map_borders: bool = False, map_coastline: bool = False) -> str: | |
| """ | |
| Generate a scatter plot with optional GADM boundaries and save to file. | |
| """ | |
| # Validate and prepare data | |
| if data is not None: | |
| if data.ndim != 2 or data.shape[1] != 3: | |
| raise ValueError("`data` must be an Nx3 array: [lat, lon, value].") | |
| lats, lons, values = data[:, 0], data[:, 1], data[:, 2] | |
| else: | |
| lats = lons = values = np.array([]) | |
| has_data = data is not None and len(data) > 0 | |
| # Fail early if nothing to plot | |
| if not has_data and not map_boundary_gadm_gids: | |
| raise ValueError("Nothing to plot: both `data` and `map_boundary_gadm_gids` are empty.") | |
| # Determine map limits | |
| if map_limits == "data": | |
| if not has_data: | |
| raise ValueError("`map_limits='data'` requires `data` to be provided.") | |
| lat0, lat1, lon0, lon1 = get_boundingbox(lats, lons) | |
| elif "gadm" in map_limits: | |
| if not map_boundary_gadm_gids: | |
| raise ValueError("`map_boundary_gadm_gids` is required for GADM-based limits.") | |
| all_lats, all_lons = [], [] | |
| index_for_limits = 1 if map_limits == "gadm_first" else len(map_boundary_gadm_gids) | |
| for gid in map_boundary_gadm_gids[:index_for_limits]: | |
| polygon = gadm_handler.get_polygon(gid) | |
| if polygon is not None: | |
| min_x, min_y, max_x, max_y = polygon.bounds | |
| all_lons.extend([min_x, max_x]) | |
| all_lats.extend([min_y, max_y]) | |
| lat0, lat1, lon0, lon1 = get_boundingbox(np.array(all_lats), np.array(all_lons)) | |
| else: | |
| lat0, lat1, lon0, lon1 = map_limits | |
| # If data exists, expand map extent so scatter points are always visible | |
| if has_data: | |
| data_lat0 = float(np.min(lats)) | |
| data_lat1 = float(np.max(lats)) | |
| data_lon0 = float(np.min(lons)) | |
| data_lon1 = float(np.max(lons)) | |
| lat0 = min(lat0, data_lat0) | |
| lat1 = max(lat1, data_lat1) | |
| lon0 = min(lon0, data_lon0) | |
| lon1 = max(lon1, data_lon1) | |
| # Add margins | |
| if isinstance(map_limits, str): | |
| dlat = (lat1 - lat0) * map_margin_ratio or 1.0 | |
| dlon = (lon1 - lon0) * map_margin_ratio or 1.0 | |
| lat0, lat1 = lat0 - dlat, lat1 + dlat | |
| lon0, lon1 = lon0 - dlon, lon1 + dlon | |
| # Setup figure | |
| base = 6 | |
| width = lon1 - lon0 | |
| height = lat1 - lat0 | |
| plt.figure(figsize=(base * (width / height), base), dpi=200) | |
| ax = plt.axes(projection=ccrs.PlateCarree()) | |
| ax.set_extent([lon0, lon1, lat0, lat1], crs=ccrs.PlateCarree()) | |
| ax.set_aspect("equal", adjustable="box") | |
| tick_font = 8 if has_data else 10 | |
| title_font = 10 if has_data else 12 | |
| # Gridlines | |
| gl = ax.gridlines(draw_labels=True, linewidth=0.3, color='gray', alpha=0.7, linestyle='--') | |
| gl.top_labels = False | |
| gl.right_labels = False | |
| gl.xlabel_style = {'size': tick_font} | |
| gl.ylabel_style = {'size': tick_font} | |
| # Base map | |
| if map_coastline: | |
| ax.add_feature(cfeature.COASTLINE, linewidth=1.0, color="k") | |
| if map_borders: | |
| ax.add_feature(cfeature.BORDERS, linewidth=0.8, color="k") | |
| ax.add_feature(cfeature.LAND, facecolor="ivory") | |
| ax.add_feature(cfeature.OCEAN, facecolor="lightblue") | |
| # GADM boundaries | |
| if map_boundary_gadm_gids: | |
| for gid in map_boundary_gadm_gids: | |
| polygon = gadm_handler.get_polygon(gid) | |
| if polygon is not None: | |
| gpd.GeoSeries([polygon]).plot(ax=ax, facecolor='none', edgecolor='gray', linewidth=0.3) | |
| if map_limits == "gadm_first": | |
| gid = map_boundary_gadm_gids[0] | |
| polygon = gadm_handler.get_polygon(gid) | |
| if polygon is not None: | |
| gpd.GeoSeries([polygon]).plot(ax=ax, facecolor='none', edgecolor='black', linewidth=0.6) | |
| info = gadm_handler.get_full_info(gid) | |
| if info: | |
| lat_c = info["geometry"]["latitude"] | |
| lon_c = info["geometry"]["longitude"] | |
| name = info["full_name"].split(";")[0] | |
| plt.text(lon_c, lat_c, name, fontsize=tick_font, ha="center", va="center") | |
| # Scatter plot | |
| if has_data: | |
| if scatter_size == "auto": | |
| count = len(lats) | |
| base_size = 40 | |
| scatter_size = base_size / (np.log10(count + 1) + 1) | |
| scatter_size = np.clip(scatter_size, 5, 30) | |
| if is_categorical is None: | |
| is_categorical = np.issubdtype(values.dtype, np.str_) | |
| rasterize = len(lats) > 10000 | |
| if is_categorical: | |
| categories, values_encoded = np.unique(values.astype(str), return_inverse=True) | |
| num_categories = len(categories) | |
| cmap_base = plt.get_cmap(cmap_str) | |
| if hasattr(cmap_base, 'colors'): | |
| cmap_colors = cmap_base.colors[:num_categories] | |
| cmap_used = ListedColormap(cmap_colors) | |
| else: | |
| cmap_used = cmap_base | |
| sc = ax.scatter(lons, lats, c=values_encoded, cmap=cmap_used, s=scatter_size, | |
| linewidth=0.0, transform=ccrs.PlateCarree(), zorder=2, | |
| rasterized=rasterize, edgecolors='none') | |
| single_color_width = (num_categories - 1) / num_categories | |
| cbar = plt.colorbar(sc, ax=ax, orientation='vertical', shrink=0.6, | |
| ticks=np.linspace(single_color_width / 2, | |
| num_categories - 1 - single_color_width / 2, | |
| num_categories)) | |
| cbar.ax.set_yticklabels(categories) | |
| cbar.set_label(long_name, fontsize=tick_font) | |
| cbar.ax.tick_params(labelsize=tick_font) | |
| else: | |
| try: | |
| vmin = float(np.percentile(values, 1)) | |
| vmax = float(np.percentile(values, 99)) | |
| except Exception: # noqa | |
| vmin = vmax = None | |
| norm = plt.Normalize(vmin=vmin, vmax=vmax) if vmin is not None and vmax is not None else None | |
| sc = ax.scatter(lons, lats, c=values, cmap=cmap_float, s=scatter_size, | |
| linewidth=0.0, transform=ccrs.PlateCarree(), zorder=2, norm=norm, | |
| rasterized=rasterize, edgecolors='none') | |
| cbar = plt.colorbar(sc, ax=ax, orientation='vertical', shrink=0.6) | |
| cbar.set_label(long_name, fontsize=tick_font) | |
| cbar.ax.tick_params(labelsize=tick_font) | |
| ax.set_title(long_name, fontsize=title_font) | |
| # Save figure with safe filename | |
| if session_name is None or session_name == "": | |
| session_name = "default_session" | |
| safe_session = re.sub(r'[^a-zA-Z0-9_-]', '_', session_name) | |
| save_dir = os.path.join(save_dir, safe_session) | |
| os.makedirs(save_dir, exist_ok=True) | |
| # build base filename | |
| base_name = re.sub(r'[^a-zA-Z0-9_-]', '_', short_name) | |
| ext = ".png" | |
| filepath = os.path.join(save_dir, f"{base_name}{ext}") | |
| # if exists, append -1, -2, ... | |
| if os.path.exists(filepath): | |
| i = 1 | |
| while True: | |
| filepath = os.path.join(save_dir, f"{base_name}-{i}{ext}") | |
| if not os.path.exists(filepath): | |
| break | |
| i += 1 | |
| plt.savefig(filepath, bbox_inches="tight") | |
| plt.close() | |
| return filepath | |