|
| 1 | +import os |
| 2 | +import rasterio |
| 3 | +import shutil |
| 4 | +from pathlib import Path |
| 5 | +from rasterio.mask import mask |
| 6 | +import fimserve as fm |
| 7 | + |
| 8 | +from .utilis import * |
| 9 | + |
| 10 | + |
| 11 | +# GET LOW FIDELITY USING FIMSERVE |
| 12 | +def get_HANDFIM( |
| 13 | + huc_id, |
| 14 | + event_date=None, |
| 15 | + data="retrospective", |
| 16 | + forecast_range=None, |
| 17 | + forecast_date=None, |
| 18 | + sort_by=None, |
| 19 | +): |
| 20 | + original_cwd = os.getcwd() |
| 21 | + try: |
| 22 | + createCWD("owp_fim") |
| 23 | + fm.DownloadHUC8(huc_id) |
| 24 | + |
| 25 | + # For retrospective event |
| 26 | + if data == "retrospective": |
| 27 | + if not event_date: |
| 28 | + raise ValueError("event_date is required for retrospective analysis.") |
| 29 | + huc_event_dict = initialize_huc_event(huc_id, event_date) |
| 30 | + fm.getNWMretrospectivedata(huc_event_dict=huc_event_dict) |
| 31 | + |
| 32 | + # For forecasting event |
| 33 | + elif data == "forecast": |
| 34 | + if not forecast_range: |
| 35 | + raise ValueError( |
| 36 | + "forecast_range ('short_range', 'medium_range', or 'long_range') is required for forecast." |
| 37 | + ) |
| 38 | + |
| 39 | + if forecast_range in ["medium_range", "long_range"]: |
| 40 | + if not sort_by: |
| 41 | + sort_by = "maximum" |
| 42 | + fm.getNWMForecasteddata( |
| 43 | + huc_id=huc_id, |
| 44 | + forecast_range=forecast_range, |
| 45 | + forecast_date=forecast_date, |
| 46 | + sort_by=sort_by, |
| 47 | + ) |
| 48 | + else: |
| 49 | + fm.getNWMForecasteddata( |
| 50 | + huc_id=huc_id, |
| 51 | + forecast_range=forecast_range, |
| 52 | + forecast_date=forecast_date, |
| 53 | + ) |
| 54 | + else: |
| 55 | + raise ValueError("data_type must be either 'retrospective' or 'forecast'.") |
| 56 | + |
| 57 | + # Run the FIM |
| 58 | + fm.runOWPHANDFIM(huc_id) |
| 59 | + |
| 60 | + finally: |
| 61 | + os.chdir(original_cwd) |
| 62 | + |
| 63 | + |
| 64 | +# Raster to binary |
| 65 | +def raster2binary(input_raster_path, geometry, final_raster_path): |
| 66 | + # Mask the raster with the geometry |
| 67 | + with rasterio.open(input_raster_path) as src: |
| 68 | + out_image, out_transform = mask(src, geometry, crop=True, filled=True, nodata=0) |
| 69 | + out_meta = src.meta.copy() |
| 70 | + out_meta.update( |
| 71 | + { |
| 72 | + "driver": "GTiff", |
| 73 | + "height": out_image.shape[1], |
| 74 | + "width": out_image.shape[2], |
| 75 | + "transform": out_transform, |
| 76 | + "crs": src.crs, |
| 77 | + "nodata": 0, |
| 78 | + } |
| 79 | + ) |
| 80 | + |
| 81 | + # Convert to binary (HAND logic: flooded if value > 0) |
| 82 | + binary_image = (out_image > 0).astype("uint8") |
| 83 | + |
| 84 | + # Save the binary raster |
| 85 | + with rasterio.open(final_raster_path, "w", **out_meta) as dst: |
| 86 | + dst.write(binary_image) |
0 commit comments