|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Create tiled mean-intensity rasters from an EPT dataset using PyForestScan.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import argparse |
| 7 | +import os |
| 8 | +from typing import Tuple |
| 9 | + |
| 10 | +import geopandas as gpd |
| 11 | +import numpy as np |
| 12 | +from numpy.lib import recfunctions as rfn |
| 13 | +from scipy.interpolate import griddata |
| 14 | + |
| 15 | +from pyforestscan.calculate import calculate_voxel_stat |
| 16 | +from pyforestscan.handlers import create_geotiff, read_lidar |
| 17 | +from pyforestscan.utils import get_bounds_from_ept, get_srs_from_ept |
| 18 | + |
| 19 | +DEFAULT_EPT = "/mnt/x/PROJECTS_2/Big_Island/ChangeHI_Trees/Dry_Forest/Data/Lidar/ept-full/ept.json" |
| 20 | +DEFAULT_POLYGON = "/mnt/x/PROJECTS_2/Big_Island/ChangeHI_Trees/Puuwaawaa/Extents/Ahupuaa_Laupahoehoe/laupahoehoe.gpkg" |
| 21 | + |
| 22 | + |
| 23 | +def ensure_height_above_ground(arr: np.ndarray) -> np.ndarray: |
| 24 | + """Ensure HeightAboveGround exists (required by calculate_voxel_stat).""" |
| 25 | + if "HeightAboveGround" in arr.dtype.names: |
| 26 | + return arr |
| 27 | + if "Z" not in arr.dtype.names: |
| 28 | + raise ValueError("Point cloud must contain either 'HeightAboveGround' or 'Z'.") |
| 29 | + |
| 30 | + # Fallback for datasets without precomputed HAG. |
| 31 | + hag = arr["Z"] - np.nanmin(arr["Z"]) |
| 32 | + return rfn.append_fields(arr, "HeightAboveGround", hag, usemask=False) |
| 33 | + |
| 34 | + |
| 35 | +def interpolate_nans(grid: np.ndarray, method: str = "linear") -> np.ndarray: |
| 36 | + """Fill NaN cells using scipy interpolation over valid neighboring cells.""" |
| 37 | + out = np.array(grid, dtype=float, copy=True) |
| 38 | + nan_mask = np.isnan(out) |
| 39 | + if not np.any(nan_mask): |
| 40 | + return out |
| 41 | + |
| 42 | + valid_mask = ~nan_mask |
| 43 | + if np.count_nonzero(valid_mask) < 3: |
| 44 | + return out |
| 45 | + |
| 46 | + x_idx, y_idx = np.indices(out.shape) |
| 47 | + points = np.column_stack((x_idx[valid_mask], y_idx[valid_mask])) |
| 48 | + values = out[valid_mask] |
| 49 | + targets = np.column_stack((x_idx[nan_mask], y_idx[nan_mask])) |
| 50 | + |
| 51 | + interp_vals = griddata(points, values, targets, method=method) |
| 52 | + if method != "nearest" and np.any(np.isnan(interp_vals)): |
| 53 | + # Fill extrapolation gaps with nearest values. |
| 54 | + nearest_vals = griddata(points, values, targets[np.isnan(interp_vals)], method="nearest") |
| 55 | + interp_vals[np.isnan(interp_vals)] = nearest_vals |
| 56 | + |
| 57 | + out[nan_mask] = interp_vals |
| 58 | + return out |
| 59 | + |
| 60 | + |
| 61 | +def load_polygon_wkt_and_bounds(polygon_path: str) -> Tuple[str, Tuple[float, float, float, float]]: |
| 62 | + """Load polygon file, dissolve all features, and return WKT + bounds.""" |
| 63 | + gdf = gpd.read_file(polygon_path) |
| 64 | + if gdf.empty: |
| 65 | + raise ValueError(f"Polygon file has no features: {polygon_path}") |
| 66 | + |
| 67 | + geom = gdf.geometry.unary_union |
| 68 | + if geom.is_empty: |
| 69 | + raise ValueError(f"Polygon geometry is empty after dissolve: {polygon_path}") |
| 70 | + |
| 71 | + min_x, min_y, max_x, max_y = geom.bounds |
| 72 | + return geom.wkt, (min_x, max_x, min_y, max_y) |
| 73 | + |
| 74 | + |
| 75 | +def parse_args() -> argparse.Namespace: |
| 76 | + parser = argparse.ArgumentParser(description=__doc__) |
| 77 | + parser.add_argument("--ept", default=DEFAULT_EPT, help="Path/URL to ept.json") |
| 78 | + parser.add_argument( |
| 79 | + "--polygon", |
| 80 | + default=DEFAULT_POLYGON, |
| 81 | + help="Polygon file (e.g., .gpkg) used to clip lidar reads", |
| 82 | + ) |
| 83 | + parser.add_argument("--output-dir", default="mean_intensity_tiles", help="Output directory for GeoTIFF tiles") |
| 84 | + parser.add_argument("--tile-size", type=float, default=1000.0, help="Tile size in map units (x and y)") |
| 85 | + parser.add_argument("--xy-res", type=float, default=0.5, help="XY voxel/grid resolution") |
| 86 | + parser.add_argument("--z-res", type=float, default=1.0, help="Z voxel resolution") |
| 87 | + parser.add_argument( |
| 88 | + "--interpolation", |
| 89 | + default="linear", |
| 90 | + choices=["nearest", "linear", "cubic", "none"], |
| 91 | + help="Interpolation method for filling NaN cells in output rasters", |
| 92 | + ) |
| 93 | + return parser.parse_args() |
| 94 | + |
| 95 | + |
| 96 | +def main() -> None: |
| 97 | + args = parse_args() |
| 98 | + os.makedirs(args.output_dir, exist_ok=True) |
| 99 | + |
| 100 | + ept_min_x, ept_max_x, ept_min_y, ept_max_y, min_z, max_z = get_bounds_from_ept(args.ept) |
| 101 | + srs = get_srs_from_ept(args.ept) |
| 102 | + if not srs: |
| 103 | + raise ValueError("Could not determine SRS from EPT metadata.") |
| 104 | + |
| 105 | + polygon_wkt, (poly_min_x, poly_max_x, poly_min_y, poly_max_y) = load_polygon_wkt_and_bounds(args.polygon) |
| 106 | + min_x = max(ept_min_x, poly_min_x) |
| 107 | + max_x = min(ept_max_x, poly_max_x) |
| 108 | + min_y = max(ept_min_y, poly_min_y) |
| 109 | + max_y = min(ept_max_y, poly_max_y) |
| 110 | + |
| 111 | + if max_x <= min_x or max_y <= min_y: |
| 112 | + raise ValueError("Polygon bounds do not overlap EPT bounds.") |
| 113 | + |
| 114 | + tile_w = tile_h = args.tile_size |
| 115 | + num_tiles_x = int(np.ceil((max_x - min_x) / tile_w)) |
| 116 | + num_tiles_y = int(np.ceil((max_y - min_y) / tile_h)) |
| 117 | + |
| 118 | + processed = 0 |
| 119 | + skipped = 0 |
| 120 | + |
| 121 | + for i in range(num_tiles_x): |
| 122 | + for j in range(num_tiles_y): |
| 123 | + tile_min_x = min_x + i * tile_w |
| 124 | + tile_max_x = min(max_x, tile_min_x + tile_w) |
| 125 | + tile_min_y = min_y + j * tile_h |
| 126 | + tile_max_y = min(max_y, tile_min_y + tile_h) |
| 127 | + |
| 128 | + bounds = ([tile_min_x, tile_max_x], [tile_min_y, tile_max_y], [min_z, max_z]) |
| 129 | + arrays = read_lidar(args.ept, srs=srs, bounds=bounds, crop_poly=True, poly=polygon_wkt) |
| 130 | + if not arrays or arrays[0].size == 0: |
| 131 | + skipped += 1 |
| 132 | + continue |
| 133 | + |
| 134 | + points = ensure_height_above_ground(arrays[0]) |
| 135 | + mean_intensity, extent = calculate_voxel_stat( |
| 136 | + points, |
| 137 | + voxel_resolution=(args.xy_res, args.xy_res, args.z_res), |
| 138 | + dimension="Intensity", |
| 139 | + stat="mean", |
| 140 | + z_index_range=None, |
| 141 | + ) |
| 142 | + |
| 143 | + if args.interpolation != "none": |
| 144 | + mean_intensity = interpolate_nans(mean_intensity, method=args.interpolation) |
| 145 | + |
| 146 | + out_tif = os.path.join(args.output_dir, f"tile_{i}_{j}_mean_intensity.tif") |
| 147 | + create_geotiff(mean_intensity, out_tif, srs, extent) |
| 148 | + processed += 1 |
| 149 | + |
| 150 | + print(f"Finished. Wrote {processed} tiles, skipped {skipped} empty tiles.") |
| 151 | + |
| 152 | + |
| 153 | +if __name__ == "__main__": |
| 154 | + main() |
0 commit comments