Skip to content

Commit 07dcc1a

Browse files
streamline the surrogate modeling within fimserve; published new PyPi version
1 parent 7e767a8 commit 07dcc1a

53 files changed

Lines changed: 5213 additions & 1136 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import warnings
2+
3+
warnings.simplefilter("ignore")
4+
5+
from .xycoord import subsetFIM
6+
7+
__all__ = ["subsetFIM"]
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import os
2+
import glob
3+
import rasterio
4+
from rasterio.mask import mask
5+
from pathlib import Path
6+
import geopandas as gpd
7+
8+
from ..datadownload import setup_directories
9+
10+
11+
def checkSHP(input_file):
12+
if isinstance(input_file, Path):
13+
input_file = str(input_file)
14+
15+
if input_file.endswith(".shp"):
16+
gdf = gpd.read_file(input_file)
17+
elif input_file.endswith(".gpkg"):
18+
gdf = gpd.read_file(input_file)
19+
elif input_file.endswith(".geojson"):
20+
gdf = gpd.read_file(input_file)
21+
elif input_file.endswith(".kml"):
22+
gdf = gpd.read_file(input_file)
23+
else:
24+
raise ValueError(
25+
"Unsupported file format. Please provide a shapefile GeoPackage, GeoJSON, or KML."
26+
)
27+
return gdf
28+
29+
30+
def clipFIMforboundary(inundation_raster, shapefile_geom, output_directory, huc):
31+
with rasterio.open(inundation_raster) as src:
32+
geometries = shapefile_geom.geometry.tolist()
33+
if src.crs != shapefile_geom.crs:
34+
print("CRS mismatch. Reprojecting geometry to match raster.")
35+
geometries = [geom.to_crs(src.crs) for geom in geometries]
36+
37+
out_image, out_transform = mask(src, geometries, crop=True)
38+
out_meta = src.meta.copy()
39+
out_meta.update(
40+
{
41+
"driver": "GTiff",
42+
"count": 1,
43+
"crs": src.crs,
44+
"transform": out_transform,
45+
"width": out_image.shape[2],
46+
"height": out_image.shape[1],
47+
}
48+
)
49+
50+
output_directory = os.path.join(output_directory, "subsetFIM")
51+
if not os.path.exists(output_directory):
52+
os.makedirs(output_directory)
53+
54+
file_basename = os.path.basename(inundation_raster).split("_")[0]
55+
output_file = os.path.join(output_directory, f"{file_basename}_subsetFIM.tif")
56+
57+
if not os.path.exists(output_directory):
58+
os.makedirs(output_directory)
59+
with rasterio.open(output_file, "w", **out_meta) as dest:
60+
dest.write(out_image)
61+
print(f"Clipped raster saved to {output_file}")
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import os
2+
import glob
3+
import geopandas as gpd
4+
from shapely.geometry import Point
5+
from pyproj import CRS
6+
import rasterio
7+
from rasterio.mask import mask
8+
9+
from ..datadownload import setup_directories
10+
from .shpsubset import checkSHP, clipFIMforboundary
11+
12+
13+
def checkifWGS(x, y):
14+
"""Check if coordinates are in WGS84 (EPSG:4326) range."""
15+
if -180 <= x <= 180 and -90 <= y <= 90:
16+
return True
17+
else:
18+
return False
19+
20+
21+
def reproject_coordinates(x, y, target_crs="EPSG:5070"):
22+
"""Reproject coordinates to target CRS."""
23+
if checkifWGS(x, y):
24+
from pyproj import CRS, Transformer
25+
26+
crs_wgs84 = CRS("EPSG:4326")
27+
crs_target = CRS(target_crs)
28+
transformer = Transformer.from_crs(crs_wgs84, crs_target, always_xy=True)
29+
x_new, y_new = transformer.transform(x, y)
30+
return x_new, y_new
31+
else:
32+
return x, y
33+
34+
35+
def clipFIM(inundation_raster, shapefile_geom, output_directory, huc):
36+
with rasterio.open(inundation_raster) as src:
37+
out_image, out_transform = mask(src, [shapefile_geom], crop=True)
38+
out_meta = src.meta.copy()
39+
out_meta.update(
40+
{
41+
"driver": "GTiff",
42+
"count": 1,
43+
"crs": src.crs,
44+
"transform": out_transform,
45+
"width": out_image.shape[2],
46+
"height": out_image.shape[1],
47+
}
48+
)
49+
file_basename = os.path.basename(inundation_raster).split("_")[0]
50+
output_file = os.path.join(output_directory, f"{file_basename}_subsetFIM.tif")
51+
52+
if not os.path.exists(output_directory):
53+
os.makedirs(output_directory)
54+
55+
with rasterio.open(output_file, "w", **out_meta) as dest:
56+
dest.write(out_image)
57+
58+
print(f"Clipped raster saved to {output_file}")
59+
return out_image, out_transform
60+
61+
62+
def withininWatershed(x, y, geopackage_path, inundation_raster, huc, output_directory):
63+
point = Point(x, y)
64+
watersheds = gpd.read_file(geopackage_path)
65+
66+
# Watershed containing the point
67+
watershed_containing_point = None
68+
for _, watershed in watersheds.iterrows():
69+
if watershed["geometry"].contains(point):
70+
watershed_containing_point = watershed
71+
break
72+
output_directory = os.path.join(output_directory, "subsetFIM")
73+
if not os.path.exists(output_directory):
74+
os.makedirs(output_directory)
75+
76+
if watershed_containing_point is None:
77+
raise ValueError(f"Point is not within any watershed boundary for {huc}")
78+
return clipFIM(
79+
inundation_raster, watershed_containing_point["geometry"], output_directory, huc
80+
)
81+
82+
83+
def subsetFIM(location, huc, method):
84+
code_dir, data_dir, output_dir = setup_directories()
85+
gpkg_path = os.path.join(
86+
output_dir, f"flood_{huc}", huc, "nwm_catchments_proj_subset.gpkg"
87+
)
88+
out_dir = os.path.join(output_dir, f"flood_{huc}", f"{huc}_inundation")
89+
inundation_rasters = os.path.join(out_dir, "*_inundation.tif")
90+
print(inundation_rasters)
91+
files = glob.glob(inundation_rasters)
92+
if method == "xy":
93+
x, y = location
94+
print("point", x, y)
95+
x, y = reproject_coordinates(x, y)
96+
for file in files:
97+
print(f"Clipping {file} to watershed containing point {x}, {y}")
98+
withininWatershed(x, y, gpkg_path, file, huc, out_dir)
99+
elif method == "boundary":
100+
shapefile = checkSHP(location)
101+
for file in files:
102+
clipFIMforboundary(file, shapefile, out_dir, huc)

build/lib/fimserve/__init__.py

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import warnings
2+
3+
from fimserve.fimevaluation.fims_setup import fim_lookup
4+
5+
warnings.simplefilter("ignore")
6+
7+
from .datadownload import DownloadHUC8
8+
from .streamflowdata.nwmretrospective import getNWMretrospectivedata
9+
from .runFIM import runOWPHANDFIM
10+
11+
from .streamflowdata.forecasteddata import getNWMForecasteddata
12+
from .streamflowdata.geoglows import getGEOGLOWSstreamflow
13+
14+
# plots
15+
from .plot.nwmfid import plotNWMStreamflow
16+
from .streamflowdata.usgsdata import getUSGSsitedata
17+
from .plot.comparestreamflow import CompareNWMnUSGSStreamflow
18+
from .plot.usgs import plotUSGSStreamflow
19+
from .plot.src import plotSRC
20+
21+
# For table
22+
from .plot.usgsandfid import GetUSGSIDandCorrFID
23+
24+
# subsetting
25+
from .FIMsubset.xycoord import subsetFIM
26+
27+
# Fim visualization
28+
from .vizualizationFIM import vizualizeFIM
29+
30+
31+
# Statistics
32+
from .statistics.calculatestatistics import CalculateStatistics
33+
34+
# For intersected HUC8 boundary
35+
from .intersectedHUC import getIntersectedHUC8ID
36+
37+
38+
# evaluation of FIM
39+
from .fimevaluation.fims_setup import FIMService, fim_lookup
40+
from .fimevaluation.run_fimeval import run_evaluation
41+
42+
43+
#Enhancement using surrogate models [Importing those only if they are called]
44+
def prepare_FORCINGs(*args, **kwargs):
45+
from .enhancement_withSM.preprocessFIM import prepare_FORCINGs as _impl
46+
return _impl(*args, **kwargs)
47+
48+
def predict_SM(*args, **kwargs):
49+
from .enhancement_withSM.SM_prediction import predict_SM as _impl
50+
return _impl(*args, **kwargs)
51+
52+
def get_building_exposure(*args, **kwargs):
53+
from .enhancement_withSM.building_exposure import get_building_exposure as _impl
54+
return _impl(*args, **kwargs)
55+
56+
def get_population_exposure(*args, **kwargs):
57+
from .enhancement_withSM.pop_exposure import get_population_exposure as _impl
58+
return _impl(*args, **kwargs)
59+
60+
61+
__all__ = [
62+
"DownloadHUC8",
63+
"getNWMRetrospectivedata",
64+
"runOWPHANDFIM",
65+
"getNWMForecasteddata",
66+
"getGEOGLOWSstreamflow",
67+
"plotNWMStreamflow",
68+
"getUSGSsitedata",
69+
"CompareNWMnUSGSStreamflow",
70+
"plotUSGSStreamflow",
71+
"plotSRC",
72+
"GetUSGSIDandCorrFID",
73+
"subsetFIM",
74+
"vizualizeFIM",
75+
"CalculateStatistics",
76+
"getIntersectedHUC8ID",
77+
"FIMService",
78+
"fim_lookup",
79+
"run_evaluation",
80+
"prepare_FORCINGs",
81+
"predict_SM",
82+
"get_building_exposure",
83+
"get_population_exposure",
84+
]

0 commit comments

Comments
 (0)