fimeval 0.1.52__tar.gz → 0.1.53__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. fimeval-0.1.52/README.md → fimeval-0.1.53/PKG-INFO +83 -2
  2. fimeval-0.1.52/PKG-INFO → fimeval-0.1.53/README.md +56 -34
  3. fimeval-0.1.53/pyproject.toml +49 -0
  4. fimeval-0.1.53/setup.cfg +4 -0
  5. {fimeval-0.1.52 → fimeval-0.1.53}/src/fimeval/BuildingFootprint/evaluationwithBF.py +75 -28
  6. fimeval-0.1.53/src/fimeval/BuildingFootprint/microsoftBF.py +131 -0
  7. {fimeval-0.1.52 → fimeval-0.1.53}/src/fimeval/ContingencyMap/PWBs3.py +14 -13
  8. {fimeval-0.1.52 → fimeval-0.1.53}/src/fimeval/ContingencyMap/evaluationFIM.py +39 -16
  9. {fimeval-0.1.52 → fimeval-0.1.53}/src/fimeval/ContingencyMap/metrics.py +14 -14
  10. {fimeval-0.1.52 → fimeval-0.1.53}/src/fimeval/ContingencyMap/printcontingency.py +1 -1
  11. {fimeval-0.1.52 → fimeval-0.1.53}/src/fimeval/__init__.py +11 -2
  12. {fimeval-0.1.52 → fimeval-0.1.53}/src/fimeval/utilis.py +45 -38
  13. fimeval-0.1.53/src/fimeval.egg-info/PKG-INFO +233 -0
  14. fimeval-0.1.53/src/fimeval.egg-info/SOURCES.txt +21 -0
  15. fimeval-0.1.53/src/fimeval.egg-info/dependency_links.txt +1 -0
  16. fimeval-0.1.53/src/fimeval.egg-info/requires.txt +16 -0
  17. fimeval-0.1.53/src/fimeval.egg-info/top_level.txt +1 -0
  18. fimeval-0.1.53/tests/test_evaluationfim.py +51 -0
  19. fimeval-0.1.52/pyproject.toml +0 -37
  20. fimeval-0.1.52/src/fimeval/ContingencyMap/fix_permissions.sh +0 -23
  21. {fimeval-0.1.52 → fimeval-0.1.53}/LICENSE.txt +0 -0
  22. {fimeval-0.1.52 → fimeval-0.1.53}/src/fimeval/BuildingFootprint/__init__.py +0 -0
  23. {fimeval-0.1.52 → fimeval-0.1.53}/src/fimeval/ContingencyMap/__init__.py +0 -0
  24. {fimeval-0.1.52 → fimeval-0.1.53}/src/fimeval/ContingencyMap/methods.py +0 -0
  25. {fimeval-0.1.52 → fimeval-0.1.53}/src/fimeval/ContingencyMap/plotevaluationmetrics.py +0 -0
@@ -1,3 +1,30 @@
1
+ Metadata-Version: 2.4
2
+ Name: fimeval
3
+ Version: 0.1.53
4
+ Summary: A Framework for Automatic Evaluation of Flood Inundation Mapping Predictions Evaluation
5
+ Author: Surface Dynamics Modeling Lab
6
+ Author-email: Supath Dhital <sdhital@crimson.ua.edu>, Dipshika Devi <ddevi@ua.edu>
7
+ Maintainer-email: Supath Dhital <sdhital@crimson.ua.edu>, Dipshika Devi <ddevi@ua.edu>
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE.txt
11
+ Requires-Dist: rasterio<2.0.0,>=1.4.2
12
+ Requires-Dist: numpy>=2
13
+ Requires-Dist: geopandas<2.0.0,>=1.0.1
14
+ Requires-Dist: shapely<3.0.0,>=2.0.6
15
+ Requires-Dist: matplotlib<4.0.0,>=3.9.2
16
+ Requires-Dist: plotly<6.0.0,>=5.24.1
17
+ Requires-Dist: kaleido==0.2.1
18
+ Requires-Dist: nbformat<6.0.0,>=5.10.4
19
+ Requires-Dist: pyproj<4.0.0,>=3.7.0
20
+ Requires-Dist: notebook<8.0.0,>=7.3.2
21
+ Requires-Dist: boto3<2.0.0,>=1.36.16
22
+ Requires-Dist: geemap
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest; extra == "dev"
25
+ Requires-Dist: black; extra == "dev"
26
+ Dynamic: license-file
27
+
1
28
  ## Flood Inundation Mapping Predictions Evaluation Framework (FIMeval)
2
29
  <hr style="border: 1px solid black; margin: 0;">
3
30
 
@@ -34,6 +61,7 @@ fimeval/
34
61
  ├── src/
35
62
  │ └── fimeval/
36
63
  │ ├──BuildingFootprint/ # Contains the evaluation of model predicted FIM with microsoft building footprint
64
+ │ │ └── microsoftBF.py
37
65
  │ │ └── evaluationwithBF.py
38
66
  │ └── ContingencyMap/ # Contains all the metrics calculation and contingency map generation
39
67
  │ │ ├── evaluationFIM.py # main evaluation moodule
@@ -59,7 +87,8 @@ This framework is published as a python package in PyPI (https://pypi.org/projec
59
87
 
60
88
  ```bash
61
89
  #Install to use this framework
62
- pip install fimeval
90
+ pip install uv #Makes the downloading much faster
91
+ uv pip install fimeval
63
92
 
64
93
  #Use this framework in your workflows using poetry
65
94
  poetry add fimeval
@@ -132,7 +161,7 @@ Table 1: Modules in `fimeval` are in order of execution.
132
161
  | `EvaluateFIM` | It runs all the evaluation of FIM between B-FIM and M-FIMs. | `main_dir`: Main directory containing the case study folders, <br> `method_name`: How users wants to evaluate their FIM, <br> `outpur_dir`: Output directory where all the results and the intermidiate files will be saved for further calculation, <br> *`PWB_dir`*: The permanenet water bodies vectory file directory if user wants to user their own boundary, <br> *`target_crs`*: this fimeval framework needs the floodmaps to be in projected CRS so define the projected CRS in epsg code format, <br> *`target_resolution`*: sometime if the benchmark is very high resolution than candidate FIMs, it needs heavy computational time, so user can define the resolution if there FIMs are in different spatial resolution, else it will use the coarser resolution among all FIMS within that case. |The outputs includes generated files in TIFF, SHP, CSV, and PNG formats, all stored within the output folder. Users can visualize the TIFF files using any geospatial platform. The TIFF files consist of the binary Benchmark-FIM (Benchmark.tif), Model-FIM (Candidate.tif), and Agreement-FIM (Contingency.tif). The shp files contain the boundary of the generated flood extent.|
133
162
  | `PlotContingencyMap` | For better understanding, It will print the agreement maps derived in first step. | `main_dir`, `method_name`, `output_dir` : Based on the those arguments, once all the evaluation is done, it will dynamically get the corresponding contingency raster for printing.| This prints the contingency map showing different class of evaluation (TP, FP, no data, PWB etc). The outputs look like- Figure 4 first row.|
134
163
  | `PlotEvaluationMetrics` | For quick understanding of the evaluation metrics, to plot bar of evaluation scores. | `main_dir`, `method_name`, `output_dir` : Based on the those arguments, once all the evaluation is done, it will dynamically get the corresponding file for printing based on all those info.| This prints the bar plots which includes different performance metrics calculated by EvaluateFIM module. The outputs look like- Figure 4 second row.|
135
- | `EvaluationWithBuildingFootprint` | For Building Footprint Analysis, user can specify shapefile of building footprints as .shp or .gpkg format. By default it consider global Microsoft building footprint dataset. Those data are hosted in Google Earth Engine (GEE) so, It pops up to authenticate the GEE account, please allow it and it will download the data based on evaluation boundary and evaluation is done. | `main_dir`, `method_name`, `output_dir`: Those arguments are as it is, same as all other modules. <br> *`building_footprint`*: If user wants to use their own building footprint file then pass the directory here, *`country`*: It is the 3 letter based country ISO code (eg. 'USA', NEP' etc), for the building data automation using GEE based on the evaluation extent, *`shapefile_dir`*: this is the directory of user defined AOI if user is working with their own boundary and automatic Building footprint download and evaluation. | It will calculate the different metrics (e.g. TP, FP, CSI, F1, Accuracy etc) based on hit and miss of building on different M-FIM and B-FIM. Those all metrics will be saved as CSV format in `output_dir` and finally using that info it prints the counts of building foorpint in each FIMs as well as scenario on the evaluation end via bar plot.|
164
+ | `EvaluationWithBuildingFootprint` | For Building Footprint Analysis, user can specify shapefile of building footprints as .shp or .gpkg format. By default it consider global Microsoft building footprint dataset. Those data are hosted in Google Earth Engine (GEE) so, It pops up to authenticate the GEE account, please allow it and it will download the data based on evaluation boundary and evaluation is done. | `main_dir`, `method_name`, `output_dir`: Those arguments are as it is, same as all other modules. <br> *`building_footprint`*: If user wants to use their own building footprint file then pass the directory here, *`country`*: It is the 3 letter based country ISO code (eg. 'USA', NEP' etc), for the building data automation using GEE based on the evaluation extent, *`shapefile_dir`*: this is the directory of user defined AOI if user is working with their own boundary and automatic Building footprint download and evaluation, *`geeprojectID`*: this is the google earth engine google cloud project ID, which helps to access the GEE data and resources to work with building footprint download and process. | It will calculate the different metrics (e.g. TP, FP, CSI, F1, Accuracy etc) based on hit and miss of building on different M-FIM and B-FIM. Those all metrics will be saved as CSV format in `output_dir` and finally using that info it prints the counts of building foorpint in each FIMs as well as scenario on the evaluation end via bar plot.|
136
165
 
137
166
  <p align="center">
138
167
  <img src="./Images/methodsresults_combined.jpg" width="750" />
@@ -140,6 +169,58 @@ Table 1: Modules in `fimeval` are in order of execution.
140
169
 
141
170
  Figure 4: Combined raw output from framework for different two method. First row (subplot a and b) and second row (subplot c and d) is contingency maps and evaluation metrics of FIM derived using `PrintContingencyMaP` and `PlotEvaluationMetrics` module. Third row (subplot e and f) is the output after processing and calculating of evaluation with BF by unsing `EvaluateWithBuildingFoorprint` module.
142
171
 
172
+ ## Installation Instructions
173
+
174
+ ### 1. Prerequisites
175
+
176
+ Before installing `fimeval`, ensure the following software are installed:
177
+
178
+ - **Python**: Version 3.10 or higher
179
+ - **Anaconda**: For managing environments and dependencies
180
+ - **GIS Software**: For Visulalisation
181
+ - [ArcGIS](https://www.esri.com/en-us/arcgis/products/index) or [QGIS](https://qgis.org/en/site/)
182
+ - **Optional**:
183
+ - [Google Earth Engine](https://earthengine.google.com/) account
184
+ - Java Runtime Environment (for using GEE API)
185
+
186
+ ---
187
+
188
+ ### 2. Install Anaconda
189
+
190
+ If Anaconda is not installed, download and install it from the [official website](https://www.anaconda.com/products/distribution).
191
+
192
+ ---
193
+
194
+ ### 3. Set Up Virtual Environment
195
+
196
+ #### For Mac Users
197
+
198
+ Open **Terminal** and run:
199
+ ```bash
200
+ # Create a new environment named 'fimeval'
201
+ conda create --name fimeval python=3.10
202
+
203
+ # Activate the environment
204
+ conda activate fimeval
205
+
206
+ # Install fimeval package
207
+ pip install uv
208
+ uv pip install fimeval
209
+ ```
210
+
211
+ ### Google Colab Version
212
+
213
+ To use fimeval in Google Colab, follow the steps below:
214
+
215
+ ## Upload Files
216
+ Upload all necessary input files (e.g., raster, shapefiles, model outputs) to your Google Drive.
217
+ ## Open Google Colab
218
+ Go to Google Colab and sign in with a valid Google account.
219
+ ## Mount Google Drive
220
+ In a new Colab notebook, mount the Google Drive
221
+ ```bash
222
+ pip install fimeval
223
+ ```
143
224
  ### **Acknowledgements**
144
225
  | | |
145
226
  | --- | --- |
@@ -1,34 +1,3 @@
1
- Metadata-Version: 2.1
2
- Name: fimeval
3
- Version: 0.1.52
4
- Summary: A Framework for Automatic Evaluation of Flood Inundation Mapping Predictions Evaluation
5
- License: GPLv3
6
- Author: Surface Dynamics Modeling Lab
7
- Maintainer: Supath Dhital
8
- Maintainer-email: sdhital@crimson.ua.edu
9
- Requires-Python: >=3.10,<4.0
10
- Classifier: License :: Other/Proprietary License
11
- Classifier: Programming Language :: Python :: 3
12
- Classifier: Programming Language :: Python :: 3.10
13
- Classifier: Programming Language :: Python :: 3.11
14
- Classifier: Programming Language :: Python :: 3.12
15
- Classifier: Programming Language :: Python :: 3.13
16
- Requires-Dist: boto3 (>=1.36.16,<2.0.0)
17
- Requires-Dist: geopandas (>=1.0.1,<2.0.0)
18
- Requires-Dist: kaleido (==0.2.1)
19
- Requires-Dist: matplotlib (>=3.9.2,<4.0.0)
20
- Requires-Dist: msfootprint (>=0.1.27,<0.2.0)
21
- Requires-Dist: nbformat (>=5.10.4,<6.0.0)
22
- Requires-Dist: notebook (>=7.3.2,<8.0.0)
23
- Requires-Dist: numpy (<2)
24
- Requires-Dist: pathlib (>=1.0.1,<2.0.0)
25
- Requires-Dist: plotly (>=5.24.1,<6.0.0)
26
- Requires-Dist: pyproj (>=3.7.0,<4.0.0)
27
- Requires-Dist: pytest (>=8.3.3,<9.0.0)
28
- Requires-Dist: rasterio (>=1.4.2,<2.0.0)
29
- Requires-Dist: shapely (>=2.0.6,<3.0.0)
30
- Description-Content-Type: text/markdown
31
-
32
1
  ## Flood Inundation Mapping Predictions Evaluation Framework (FIMeval)
33
2
  <hr style="border: 1px solid black; margin: 0;">
34
3
 
@@ -65,6 +34,7 @@ fimeval/
65
34
  ├── src/
66
35
  │ └── fimeval/
67
36
  │ ├──BuildingFootprint/ # Contains the evaluation of model predicted FIM with microsoft building footprint
37
+ │ │ └── microsoftBF.py
68
38
  │ │ └── evaluationwithBF.py
69
39
  │ └── ContingencyMap/ # Contains all the metrics calculation and contingency map generation
70
40
  │ │ ├── evaluationFIM.py # main evaluation moodule
@@ -90,7 +60,8 @@ This framework is published as a python package in PyPI (https://pypi.org/projec
90
60
 
91
61
  ```bash
92
62
  #Install to use this framework
93
- pip install fimeval
63
+ pip install uv #Makes the downloading much faster
64
+ uv pip install fimeval
94
65
 
95
66
  #Use this framework in your workflows using poetry
96
67
  poetry add fimeval
@@ -163,7 +134,7 @@ Table 1: Modules in `fimeval` are in order of execution.
163
134
  | `EvaluateFIM` | It runs all the evaluation of FIM between B-FIM and M-FIMs. | `main_dir`: Main directory containing the case study folders, <br> `method_name`: How users wants to evaluate their FIM, <br> `outpur_dir`: Output directory where all the results and the intermidiate files will be saved for further calculation, <br> *`PWB_dir`*: The permanenet water bodies vectory file directory if user wants to user their own boundary, <br> *`target_crs`*: this fimeval framework needs the floodmaps to be in projected CRS so define the projected CRS in epsg code format, <br> *`target_resolution`*: sometime if the benchmark is very high resolution than candidate FIMs, it needs heavy computational time, so user can define the resolution if there FIMs are in different spatial resolution, else it will use the coarser resolution among all FIMS within that case. |The outputs includes generated files in TIFF, SHP, CSV, and PNG formats, all stored within the output folder. Users can visualize the TIFF files using any geospatial platform. The TIFF files consist of the binary Benchmark-FIM (Benchmark.tif), Model-FIM (Candidate.tif), and Agreement-FIM (Contingency.tif). The shp files contain the boundary of the generated flood extent.|
164
135
  | `PlotContingencyMap` | For better understanding, It will print the agreement maps derived in first step. | `main_dir`, `method_name`, `output_dir` : Based on the those arguments, once all the evaluation is done, it will dynamically get the corresponding contingency raster for printing.| This prints the contingency map showing different class of evaluation (TP, FP, no data, PWB etc). The outputs look like- Figure 4 first row.|
165
136
  | `PlotEvaluationMetrics` | For quick understanding of the evaluation metrics, to plot bar of evaluation scores. | `main_dir`, `method_name`, `output_dir` : Based on the those arguments, once all the evaluation is done, it will dynamically get the corresponding file for printing based on all those info.| This prints the bar plots which includes different performance metrics calculated by EvaluateFIM module. The outputs look like- Figure 4 second row.|
166
- | `EvaluationWithBuildingFootprint` | For Building Footprint Analysis, user can specify shapefile of building footprints as .shp or .gpkg format. By default it consider global Microsoft building footprint dataset. Those data are hosted in Google Earth Engine (GEE) so, It pops up to authenticate the GEE account, please allow it and it will download the data based on evaluation boundary and evaluation is done. | `main_dir`, `method_name`, `output_dir`: Those arguments are as it is, same as all other modules. <br> *`building_footprint`*: If user wants to use their own building footprint file then pass the directory here, *`country`*: It is the 3 letter based country ISO code (eg. 'USA', NEP' etc), for the building data automation using GEE based on the evaluation extent, *`shapefile_dir`*: this is the directory of user defined AOI if user is working with their own boundary and automatic Building footprint download and evaluation. | It will calculate the different metrics (e.g. TP, FP, CSI, F1, Accuracy etc) based on hit and miss of building on different M-FIM and B-FIM. Those all metrics will be saved as CSV format in `output_dir` and finally using that info it prints the counts of building foorpint in each FIMs as well as scenario on the evaluation end via bar plot.|
137
+ | `EvaluationWithBuildingFootprint` | For Building Footprint Analysis, user can specify shapefile of building footprints as .shp or .gpkg format. By default it consider global Microsoft building footprint dataset. Those data are hosted in Google Earth Engine (GEE) so, It pops up to authenticate the GEE account, please allow it and it will download the data based on evaluation boundary and evaluation is done. | `main_dir`, `method_name`, `output_dir`: Those arguments are as it is, same as all other modules. <br> *`building_footprint`*: If user wants to use their own building footprint file then pass the directory here, *`country`*: It is the 3 letter based country ISO code (eg. 'USA', NEP' etc), for the building data automation using GEE based on the evaluation extent, *`shapefile_dir`*: this is the directory of user defined AOI if user is working with their own boundary and automatic Building footprint download and evaluation, *`geeprojectID`*: this is the google earth engine google cloud project ID, which helps to access the GEE data and resources to work with building footprint download and process. | It will calculate the different metrics (e.g. TP, FP, CSI, F1, Accuracy etc) based on hit and miss of building on different M-FIM and B-FIM. Those all metrics will be saved as CSV format in `output_dir` and finally using that info it prints the counts of building foorpint in each FIMs as well as scenario on the evaluation end via bar plot.|
167
138
 
168
139
  <p align="center">
169
140
  <img src="./Images/methodsresults_combined.jpg" width="750" />
@@ -171,6 +142,58 @@ Table 1: Modules in `fimeval` are in order of execution.
171
142
 
172
143
  Figure 4: Combined raw output from framework for different two method. First row (subplot a and b) and second row (subplot c and d) is contingency maps and evaluation metrics of FIM derived using `PrintContingencyMaP` and `PlotEvaluationMetrics` module. Third row (subplot e and f) is the output after processing and calculating of evaluation with BF by unsing `EvaluateWithBuildingFoorprint` module.
173
144
 
145
+ ## Installation Instructions
146
+
147
+ ### 1. Prerequisites
148
+
149
+ Before installing `fimeval`, ensure the following software are installed:
150
+
151
+ - **Python**: Version 3.10 or higher
152
+ - **Anaconda**: For managing environments and dependencies
153
+ - **GIS Software**: For Visulalisation
154
+ - [ArcGIS](https://www.esri.com/en-us/arcgis/products/index) or [QGIS](https://qgis.org/en/site/)
155
+ - **Optional**:
156
+ - [Google Earth Engine](https://earthengine.google.com/) account
157
+ - Java Runtime Environment (for using GEE API)
158
+
159
+ ---
160
+
161
+ ### 2. Install Anaconda
162
+
163
+ If Anaconda is not installed, download and install it from the [official website](https://www.anaconda.com/products/distribution).
164
+
165
+ ---
166
+
167
+ ### 3. Set Up Virtual Environment
168
+
169
+ #### For Mac Users
170
+
171
+ Open **Terminal** and run:
172
+ ```bash
173
+ # Create a new environment named 'fimeval'
174
+ conda create --name fimeval python=3.10
175
+
176
+ # Activate the environment
177
+ conda activate fimeval
178
+
179
+ # Install fimeval package
180
+ pip install uv
181
+ uv pip install fimeval
182
+ ```
183
+
184
+ ### Google Colab Version
185
+
186
+ To use fimeval in Google Colab, follow the steps below:
187
+
188
+ ## Upload Files
189
+ Upload all necessary input files (e.g., raster, shapefiles, model outputs) to your Google Drive.
190
+ ## Open Google Colab
191
+ Go to Google Colab and sign in with a valid Google account.
192
+ ## Mount Google Drive
193
+ In a new Colab notebook, mount the Google Drive
194
+ ```bash
195
+ pip install fimeval
196
+ ```
174
197
  ### **Acknowledgements**
175
198
  | | |
176
199
  | --- | --- |
@@ -181,4 +204,3 @@ Contact <a href="https://geography.ua.edu/people/sagy-cohen/" target="_blank">Sa
181
204
  (sagy.cohen@ua.edu)
182
205
  Dipsikha Devi, (ddevi@ua.edu)
183
206
  Supath Dhital, (sdhital@crimson.ua.edu)
184
-
@@ -0,0 +1,49 @@
1
+ [project]
2
+ name = "fimeval"
3
+ version = "0.1.53"
4
+ description = "A Framework for Automatic Evaluation of Flood Inundation Mapping Predictions Evaluation"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = { file = "LICENSE" }
8
+
9
+ authors = [
10
+ { name = "Surface Dynamics Modeling Lab" },
11
+ { name = "Supath Dhital", email = "sdhital@crimson.ua.edu" },
12
+ { name = "Dipshika Devi", email = "ddevi@ua.edu" }
13
+ ]
14
+
15
+ maintainers = [
16
+ { name = "Supath Dhital", email = "sdhital@crimson.ua.edu" },
17
+ { name = "Dipshika Devi", email = "ddevi@ua.edu" }
18
+ ]
19
+
20
+ dependencies = [
21
+ "rasterio>=1.4.2,<2.0.0",
22
+ "numpy>=2",
23
+ "geopandas>=1.0.1,<2.0.0",
24
+ "shapely>=2.0.6,<3.0.0",
25
+ "matplotlib>=3.9.2,<4.0.0",
26
+ "plotly>=5.24.1,<6.0.0",
27
+ "kaleido==0.2.1",
28
+ "nbformat>=5.10.4,<6.0.0",
29
+ "pyproj>=3.7.0,<4.0.0",
30
+ "notebook>=7.3.2,<8.0.0",
31
+ "boto3>=1.36.16,<2.0.0",
32
+ "geemap"
33
+ ]
34
+
35
+ [project.optional-dependencies]
36
+ dev = [
37
+ "pytest",
38
+ "black"
39
+ ]
40
+
41
+ [tool.setuptools]
42
+ package-dir = { "" = "src" }
43
+
44
+ [tool.setuptools.packages.find]
45
+ where = ["src"]
46
+
47
+ [build-system]
48
+ requires = ["setuptools>=61.0"]
49
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -1,5 +1,4 @@
1
1
  import os
2
- import ee
3
2
  import glob
4
3
  import geopandas as gpd
5
4
  import rasterio
@@ -21,6 +20,7 @@ def Changeintogpkg(input_path, output_dir, layer_name):
21
20
  gdf.to_file(output_gpkg, driver="GPKG")
22
21
  return output_gpkg
23
22
 
23
+
24
24
  def GetFloodedBuildingCountInfo(
25
25
  building_fp_path,
26
26
  study_area_path,
@@ -85,7 +85,7 @@ def GetFloodedBuildingCountInfo(
85
85
  if "bm" in str(raster1_path).lower():
86
86
  count_centroids_in_raster(raster1_path, "Benchmark")
87
87
  count_centroids_in_raster(raster2_path, "Candidate")
88
-
88
+
89
89
  elif "candidate" in str(raster2_path).lower():
90
90
  count_centroids_in_raster(raster1_path, "Candidate")
91
91
  count_centroids_in_raster(raster2_path, "Benchmark")
@@ -106,9 +106,10 @@ def GetFloodedBuildingCountInfo(
106
106
  CSI = TP / (TP + FP + FN) if (TP + FP + FN) > 0 else 0
107
107
  FAR = FP / (TP + FP) if (TP + FP) > 0 else 0
108
108
  POD = TP / (TP + FN) if (TP + FN) > 0 else 0
109
-
110
-
111
- BDR = (centroid_counts["Candidate"]- centroid_counts["Benchmark"])/centroid_counts["Benchmark"]
109
+
110
+ BDR = (
111
+ centroid_counts["Candidate"] - centroid_counts["Benchmark"]
112
+ ) / centroid_counts["Benchmark"]
112
113
 
113
114
  counts_data = {
114
115
  "Category": [
@@ -223,6 +224,7 @@ def GetFloodedBuildingCountInfo(
223
224
  print(f"Performance metrics chart is saved as PNG at {output_path}")
224
225
  fig.show()
225
226
 
227
+
226
228
  def process_TIFF(
227
229
  tif_files, contingency_files, building_footprint, boundary, method_path
228
230
  ):
@@ -266,22 +268,46 @@ def process_TIFF(
266
268
  print("Warning: No benchmark file found.")
267
269
  elif not candidate_paths:
268
270
  print("Warning: No candidate files found.")
269
-
271
+
272
+
270
273
  def find_existing_footprint(out_dir):
271
274
  gpkg_files = list(Path(out_dir).glob("*.gpkg"))
272
275
  return gpkg_files[0] if gpkg_files else None
273
276
 
274
- #Incase user defined individual shapefile for each case study
277
+
278
+ # Incase user defined individual shapefile for each case study
275
279
  def detect_shapefile(folder):
276
- shapefile = None
277
- for ext in (".shp", ".gpkg", ".geojson", ".kml"):
278
- for file in os.listdir(folder):
279
- if file.lower().endswith(ext):
280
- shapefile = os.path.join(folder, file)
281
- print(f"Auto-detected shapefile: {shapefile}")
282
- return shapefile
283
- return None
284
-
280
+ shapefile = None
281
+ for ext in (".shp", ".gpkg", ".geojson", ".kml"):
282
+ for file in os.listdir(folder):
283
+ if file.lower().endswith(ext):
284
+ shapefile = os.path.join(folder, file)
285
+ print(f"Auto-detected shapefile: {shapefile}")
286
+ return shapefile
287
+ return None
288
+
289
+
290
+ def ensure_pyspark(version: str | None = "3.5.4") -> None:
291
+ """Install pyspark at runtime via `uv pip` into this env (no-op if present)."""
292
+ import importlib, shutil, subprocess, sys, re
293
+ try:
294
+ import importlib.util
295
+ if importlib.util.find_spec("pyspark"):
296
+ return
297
+ except Exception:
298
+ pass
299
+ uv = shutil.which("uv")
300
+ if not uv:
301
+ raise RuntimeError("`uv` not found on PATH. Please install uv or add it to PATH.")
302
+ if version is None:
303
+ spec = "pyspark"
304
+ else:
305
+ v = version.strip()
306
+ spec = f"pyspark{v}" if re.match(r"^[<>=!~]", v) else f"pyspark=={v}"
307
+ subprocess.check_call([uv, "pip", "install", "--python", sys.executable, spec])
308
+
309
+
310
+
285
311
  def EvaluationWithBuildingFootprint(
286
312
  main_dir,
287
313
  method_name,
@@ -289,6 +315,7 @@ def EvaluationWithBuildingFootprint(
289
315
  country=None,
290
316
  building_footprint=None,
291
317
  shapefile_dir=None,
318
+ geeprojectID=None,
292
319
  ):
293
320
  tif_files_main = glob.glob(os.path.join(main_dir, "*.tif"))
294
321
  if tif_files_main:
@@ -303,9 +330,7 @@ def EvaluationWithBuildingFootprint(
303
330
 
304
331
  if shapefile_dir:
305
332
  boundary = shapefile_dir
306
- elif os.path.exists(
307
- os.path.join(method_path, "BoundaryforEvaluation")
308
- ):
333
+ elif os.path.exists(os.path.join(method_path, "BoundaryforEvaluation")):
309
334
  boundary = os.path.join(
310
335
  method_path, "BoundaryforEvaluation", "FIMEvaluatedExtent.shp"
311
336
  )
@@ -313,9 +338,11 @@ def EvaluationWithBuildingFootprint(
313
338
  boundary = detect_shapefile(main_dir)
314
339
 
315
340
  building_footprintMS = building_footprint
341
+
316
342
  if building_footprintMS is None:
317
- import msfootprint as msf
318
-
343
+ ensure_pyspark()
344
+ from .microsoftBF import BuildingFootprintwithISO
345
+
319
346
  out_dir = os.path.join(method_path, "BuildingFootprint")
320
347
  if not os.path.exists(out_dir):
321
348
  os.makedirs(out_dir)
@@ -323,7 +350,15 @@ def EvaluationWithBuildingFootprint(
323
350
  if not EX_building_footprint:
324
351
  boundary_dir = shapefile_dir if shapefile_dir else boundary
325
352
 
326
- msf.BuildingFootprintwithISO(country, boundary_dir, out_dir)
353
+ if geeprojectID:
354
+ BuildingFootprintwithISO(
355
+ country,
356
+ boundary_dir,
357
+ out_dir,
358
+ geeprojectID=geeprojectID,
359
+ )
360
+ else:
361
+ BuildingFootprintwithISO(country, boundary_dir, out_dir)
327
362
  building_footprintMS = os.path.join(
328
363
  out_dir, f"building_footprint.gpkg"
329
364
  )
@@ -355,15 +390,19 @@ def EvaluationWithBuildingFootprint(
355
390
  os.path.join(method_path, "BoundaryforEvaluation")
356
391
  ):
357
392
  boundary = os.path.join(
358
- method_path, "BoundaryforEvaluation", "FIMEvaluatedExtent.shp"
393
+ method_path,
394
+ "BoundaryforEvaluation",
395
+ "FIMEvaluatedExtent.shp",
359
396
  )
360
397
  else:
361
398
  boundary = detect_shapefile(os.path.join(main_dir, folder))
362
399
 
363
400
  building_footprintMS = building_footprint
401
+
364
402
  if building_footprintMS is None:
365
- import msfootprint as msf
366
-
403
+ ensure_pyspark()
404
+ from .microsoftBF import BuildingFootprintwithISO
405
+
367
406
  out_dir = os.path.join(method_path, "BuildingFootprint")
368
407
  if not os.path.exists(out_dir):
369
408
  os.makedirs(out_dir)
@@ -372,9 +411,17 @@ def EvaluationWithBuildingFootprint(
372
411
  boundary_dir = (
373
412
  shapefile_dir if shapefile_dir else boundary
374
413
  )
375
- msf.BuildingFootprintwithISO(
376
- country, boundary_dir, out_dir
377
- )
414
+ if geeprojectID:
415
+ BuildingFootprintwithISO(
416
+ country,
417
+ boundary_dir,
418
+ out_dir,
419
+ geeprojectID=geeprojectID,
420
+ )
421
+ else:
422
+ BuildingFootprintwithISO(
423
+ country, boundary_dir, out_dir
424
+ )
378
425
  building_footprintMS = os.path.join(
379
426
  out_dir, f"building_footprint.gpkg"
380
427
  )
@@ -0,0 +1,131 @@
1
+ # Importing necessary libraries
2
+ import geemap
3
+ import ee
4
+ import os
5
+ from shapely.geometry import box
6
+ import pandas as pd
7
+ from pathlib import Path
8
+ import geopandas as gpd
9
+ from pyspark.sql import SparkSession
10
+ from shapely.wkt import loads
11
+ import shutil
12
+
13
+ # Suppress the warnings
14
+ import warnings
15
+
16
+ warnings.filterwarnings("ignore")
17
+
18
+ # Authenticate and initialize Earth Engine
19
+ ee.Authenticate()
20
+
21
+ # %%
22
+ def split_into_tiles(boundary, tile_size=0.1):
23
+ bounds = boundary.total_bounds
24
+ x_min, y_min, x_max, y_max = bounds
25
+ tiles = []
26
+ x = x_min
27
+ while x < x_max:
28
+ y = y_min
29
+ while y < y_max:
30
+ tile = box(x, y, x + tile_size, y + tile_size)
31
+ if tile.intersects(boundary.unary_union):
32
+ tiles.append(tile)
33
+ y += tile_size
34
+ x += tile_size
35
+ return gpd.GeoDataFrame(geometry=tiles, crs=boundary.crs)
36
+
37
+
38
+ # Merge the final geojson files
39
+ def mergeGeoJSONfiles(output_dir, merged_file):
40
+ output_dir = Path(output_dir)
41
+ files = list(output_dir.glob("*.geojson"))
42
+ gdfs = [gpd.read_file(file) for file in files]
43
+ merged_gdf = gpd.GeoDataFrame(pd.concat(gdfs, ignore_index=True), crs="EPSG:4326")
44
+ merged_gdf.to_file(merged_file, driver="GPKG")
45
+
46
+
47
+ # Process each batch with number of tiles
48
+ def process_batch(partition, collection_name, output_dir, boundary_wkt, projectID=None):
49
+ try:
50
+ if projectID:
51
+ ee.Initialize(project=projectID)
52
+ else:
53
+ ee.Initialize()
54
+
55
+ except Exception:
56
+ print("To initialize, please provide the earth engine project ID")
57
+
58
+ # Convert WKT boundary to geometry
59
+ boundary = loads(boundary_wkt)
60
+ results = []
61
+
62
+ for tile_wkt in partition:
63
+ try:
64
+ tile = loads(tile_wkt)
65
+ aoi = ee.Geometry(tile.__geo_interface__)
66
+ collection = ee.FeatureCollection(collection_name).filterBounds(aoi)
67
+
68
+ # Download features and filter by boundary
69
+ gdf = geemap.ee_to_gdf(collection)
70
+ gdf = gdf[gdf.geometry.intersects(boundary)]
71
+
72
+ # Save each tile as a GeoJSON file
73
+ tile_id = f"tile_{hash(tile)}"
74
+ output_file = Path(output_dir) / f"{tile_id}.geojson"
75
+ gdf.to_file(output_file, driver="GeoJSON")
76
+ results.append(f"Saved: {output_file}")
77
+ except Exception as e:
78
+ results.append(f"Error processing tile: {e}")
79
+
80
+ return results
81
+
82
+
83
+ def getBuildingFootprintSpark(
84
+ countryISO, boundary_file, out_dir, tile_size, projectID=None
85
+ ):
86
+ spark = SparkSession.builder.appName("BuildingFootprints").getOrCreate()
87
+
88
+ # Make temporary directory
89
+ temp_dir = out_dir / "temp"
90
+ temp_dir.mkdir(parents=True, exist_ok=True)
91
+
92
+ # Load and process boundary
93
+ boundary = gpd.read_file(boundary_file).to_crs("EPSG:4326")
94
+ tiles = split_into_tiles(boundary, tile_size)
95
+ boundary_wkt = boundary.unary_union.wkt
96
+
97
+ collection_names = [f"projects/sat-io/open-datasets/VIDA_COMBINED/{countryISO}"]
98
+
99
+ # Distribute processing
100
+ for collection_name in collection_names:
101
+ tiles_rdd = spark.sparkContext.parallelize(
102
+ tiles.geometry.apply(lambda x: x.wkt).tolist(), numSlices=10
103
+ )
104
+ results = tiles_rdd.mapPartitions(
105
+ lambda partition: process_batch(
106
+ partition, collection_name, str(temp_dir), boundary_wkt, projectID
107
+ )
108
+ ).collect()
109
+
110
+ # Merge GeoJSON files
111
+ mergeGeoJSONfiles(temp_dir, out_dir / "building_footprint.gpkg")
112
+
113
+ # Clean up the temp directory
114
+ shutil.rmtree(temp_dir, ignore_errors=True)
115
+
116
+ print(f"Building footprint data saved to {out_dir / 'building_footprint.gpkg'}")
117
+
118
+
119
+ # %%
120
+ # Export the building footprint
121
+ def BuildingFootprintwithISO(countryISO, ROI, out_dir, geeprojectID=None):
122
+ out_dir = Path(out_dir)
123
+ out_dir.mkdir(parents=True, exist_ok=True)
124
+ filename = out_dir / "building_footprint.gpkg"
125
+
126
+ if filename.exists():
127
+ os.remove(filename)
128
+
129
+ getBuildingFootprintSpark(
130
+ countryISO, ROI, out_dir, tile_size=0.05, projectID=geeprojectID
131
+ )