hls-burn 0.1.0__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.
- hls_burn-0.1.0/LICENSE +21 -0
- hls_burn-0.1.0/PKG-INFO +187 -0
- hls_burn-0.1.0/README.md +133 -0
- hls_burn-0.1.0/__init__.py +3 -0
- hls_burn-0.1.0/data/__init__.py +3 -0
- hls_burn-0.1.0/data/fire_data.py +329 -0
- hls_burn-0.1.0/hls_burn.egg-info/PKG-INFO +187 -0
- hls_burn-0.1.0/hls_burn.egg-info/SOURCES.txt +38 -0
- hls_burn-0.1.0/hls_burn.egg-info/dependency_links.txt +1 -0
- hls_burn-0.1.0/hls_burn.egg-info/requires.txt +39 -0
- hls_burn-0.1.0/hls_burn.egg-info/top_level.txt +1 -0
- hls_burn-0.1.0/pyproject.toml +88 -0
- hls_burn-0.1.0/segmenters/__init__.py +3 -0
- hls_burn-0.1.0/segmenters/classical_segmenter.py +141 -0
- hls_burn-0.1.0/segmenters/deep_segmenter.py +288 -0
- hls_burn-0.1.0/segmenters/default_xgb_tree/metadata.json +101 -0
- hls_burn-0.1.0/segmenters/default_xgb_tree/model.ubj +0 -0
- hls_burn-0.1.0/segmenters/scikit_segmenter.py +249 -0
- hls_burn-0.1.0/segmenters/segmenter.py +454 -0
- hls_burn-0.1.0/setup.cfg +4 -0
- hls_burn-0.1.0/utils/__init__.py +1 -0
- hls_burn-0.1.0/utils/geom_utils.py +329 -0
- hls_burn-0.1.0/utils/nbr_utils.py +782 -0
- hls_burn-0.1.0/utils/pc_config.yaml +94 -0
- hls_burn-0.1.0/utils/pc_utils.py +401 -0
hls_burn-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 hls-burn contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
hls_burn-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hls-burn
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Burn scar mapping from pre/post-fire HLS (Harmonized Landsat Sentinel-2) scenes
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: U-Net model, https://huggingface.co/hughbertlongshanks/unet-burn-hls
|
|
7
|
+
Keywords: wildfire,burn scar,dNBR,HLS,Landsat,Sentinel-2,remote sensing,segmentation
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: GIS
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Image Recognition
|
|
15
|
+
Requires-Python: >=3.11
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: numpy>=2.5
|
|
19
|
+
Requires-Dist: scipy>=1.18
|
|
20
|
+
Requires-Dist: pandas>=3.0
|
|
21
|
+
Requires-Dist: xarray>=2026.9
|
|
22
|
+
Requires-Dist: rioxarray>=0.19
|
|
23
|
+
Requires-Dist: rasterio>=1.5
|
|
24
|
+
Requires-Dist: geopandas>=1.1
|
|
25
|
+
Requires-Dist: shapely>=2.1
|
|
26
|
+
Requires-Dist: pyproj>=3.7
|
|
27
|
+
Requires-Dist: pyogrio>=0.13
|
|
28
|
+
Requires-Dist: opencv-python-headless>=5.0
|
|
29
|
+
Requires-Dist: odc-stac>=0.5
|
|
30
|
+
Requires-Dist: odc-geo>=0.5
|
|
31
|
+
Requires-Dist: pystac>=1.16
|
|
32
|
+
Requires-Dist: pystac-client>=0.9
|
|
33
|
+
Requires-Dist: planetary-computer>=1.0
|
|
34
|
+
Requires-Dist: requests>=2.34
|
|
35
|
+
Requires-Dist: PyYAML>=6.0
|
|
36
|
+
Requires-Dist: matplotlib>=3.11
|
|
37
|
+
Requires-Dist: xgboost>=3.2
|
|
38
|
+
Provides-Extra: deep
|
|
39
|
+
Requires-Dist: torch>=2.13; extra == "deep"
|
|
40
|
+
Requires-Dist: segmentation-models-pytorch>=0.5; extra == "deep"
|
|
41
|
+
Requires-Dist: huggingface-hub>=1.29; extra == "deep"
|
|
42
|
+
Requires-Dist: safetensors>=0.8; extra == "deep"
|
|
43
|
+
Provides-Extra: map
|
|
44
|
+
Requires-Dist: ipyleaflet>=0.20; extra == "map"
|
|
45
|
+
Requires-Dist: ipywidgets>=8.1; extra == "map"
|
|
46
|
+
Requires-Dist: xyzservices>=2026.9; extra == "map"
|
|
47
|
+
Requires-Dist: folium>=0.20; extra == "map"
|
|
48
|
+
Requires-Dist: pillow>=12.3; extra == "map"
|
|
49
|
+
Provides-Extra: sklearn
|
|
50
|
+
Requires-Dist: scikit-learn>=1.9; extra == "sklearn"
|
|
51
|
+
Provides-Extra: all
|
|
52
|
+
Requires-Dist: hls-burn[deep,map,sklearn]; extra == "all"
|
|
53
|
+
Dynamic: license-file
|
|
54
|
+
|
|
55
|
+
# hls-burn
|
|
56
|
+
|
|
57
|
+
Map burn scars from a pre-fire and a post-fire scene of NASA's Harmonized Landsat
|
|
58
|
+
Sentinel-2 (HLS, 30 m). Scenes are searched and read from Microsoft Planetary Computer,
|
|
59
|
+
so all you need is an area and the fire's dates.
|
|
60
|
+
|
|
61
|
+
There are three segmenters, and they all work the same way: `segment()` gives a class
|
|
62
|
+
raster, `polygonize()` gives a GeoDataFrame.
|
|
63
|
+
|
|
64
|
+
| segmenter | method | classes |
|
|
65
|
+
|---|---|---|
|
|
66
|
+
| `ThresholdSegmenter` | thresholds on a burn index (dNBR by default) | USGS-style severity, or your own bins |
|
|
67
|
+
| `SklearnSegmenter` | bundled XGBoost model on burn indices, trained on ~1,000 US fires | burned / unburned |
|
|
68
|
+
| `DeepSegmenter` | 24M-param [U-Net](https://huggingface.co/hughbertlongshanks/unet-burn-hls), trained on ~6,000 US pre/post pairs | burned / unburned |
|
|
69
|
+
|
|
70
|
+
## Install
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
pip install hls-burn # threshold + XGBoost
|
|
74
|
+
pip install "hls-burn[deep]" # + U-Net (PyTorch)
|
|
75
|
+
pip install "hls-burn[map]" # + polygon editor for notebooks
|
|
76
|
+
pip install "hls-burn[all]"
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Python 3.11+.
|
|
80
|
+
|
|
81
|
+
## Usage
|
|
82
|
+
|
|
83
|
+
The steps below follow `examples.ipynb`, which maps a February 2026 fire near Lake
|
|
84
|
+
Okeechobee.
|
|
85
|
+
|
|
86
|
+
### Get scenes
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
import shapely
|
|
90
|
+
from hls_burn.data.fire_data import HLSFireData
|
|
91
|
+
|
|
92
|
+
fire = HLSFireData()
|
|
93
|
+
fire.get_clearest_hls_scenes_pre_post(
|
|
94
|
+
search_area=shapely.Point(-80.88, 27.11).buffer(0.1), # lon/lat; a shapely geom or WKT
|
|
95
|
+
start_date="2026-02-12",
|
|
96
|
+
end_date="2026-02-15",
|
|
97
|
+
pre_offset_days=30, # search this far before start_date for a clear scene
|
|
98
|
+
post_offset_days=30, # and this far after end_date
|
|
99
|
+
)
|
|
100
|
+
fire.show_scenes() # true colour
|
|
101
|
+
fire.show_scenes(bands=("swir2", "nir", "red")) # false colour: burns show up red
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
If either scene is mostly cloud, shadow or snow you get a warning.
|
|
105
|
+
|
|
106
|
+
### Burn index
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
fire.calc_dnbr()
|
|
110
|
+
fire.plot_computed_index(vmin=0, vmax=0.5)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
There are other indices too. Some of them need a perimeter or an unburned reference
|
|
114
|
+
area.
|
|
115
|
+
|
|
116
|
+
### Threshold segmentation
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
from hls_burn.segmenters.classical_segmenter import ThresholdSegmenter
|
|
120
|
+
|
|
121
|
+
seg = ThresholdSegmenter(index="dnbr") # default bins: 6 USGS-style severity classes
|
|
122
|
+
seg.segment(fire)
|
|
123
|
+
seg.plot_segmentation()
|
|
124
|
+
|
|
125
|
+
seg.bins = (0.1,) # binary: dNBR > 0.1 is burned
|
|
126
|
+
seg.segment(fire)
|
|
127
|
+
seg.export_raster("mask.tif", crs=5070)
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
You'll usually have to tune the thresholds for each fire. The pretrained models don't
|
|
131
|
+
need that.
|
|
132
|
+
|
|
133
|
+
### Pretrained models
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
from hls_burn.segmenters.scikit_segmenter import SklearnSegmenter
|
|
137
|
+
from hls_burn.segmenters.deep_segmenter import DeepSegmenter # needs [deep]
|
|
138
|
+
|
|
139
|
+
xgb = SklearnSegmenter() # bundled model; or pass your own scikit-learn estimator
|
|
140
|
+
xgb.segment(fire)
|
|
141
|
+
|
|
142
|
+
unet = DeepSegmenter(cutoff=0.6) # probability threshold
|
|
143
|
+
unet.segment(fire)
|
|
144
|
+
unet.plot_segmentation()
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Unusable pixels (cloud, nodata) come back as 255.
|
|
148
|
+
|
|
149
|
+
### Polygons
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
gdf = unet.polygonize() # one row per connected patch
|
|
153
|
+
gdf.explore(tiles="Esri.WorldImagery") # it's a plain GeoDataFrame
|
|
154
|
+
unet.export_polygons("burned.fgb", crs=5070)
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
The polygons are also stored on the segmenter, and every call replaces them.
|
|
158
|
+
|
|
159
|
+
### Edit polygons in a notebook (`[map]`)
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
unet.edit_polygons(fire=fire, window="post") # false colour by default
|
|
163
|
+
unet.edit_polygons(fire=fire, bands=("red", "green", "blue"))
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
This opens a map with the scene under the polygons. You can move vertices, reshape
|
|
167
|
+
polygons or delete them, then call `export_polygons()` when you're done.
|
|
168
|
+
|
|
169
|
+
## Model Performance
|
|
170
|
+
The library currently ships with access to two pretrained models as shown above.
|
|
171
|
+
|
|
172
|
+
The XGBoost model performs better than un tuned threshholding in
|
|
173
|
+
most cases and has an IOU of ~70%. It tends to fail in scenes where having a lot of context would be beneficial.
|
|
174
|
+
e.g. fields. It's reliance on computed features (dnbr, rbr, etc...)
|
|
175
|
+
also limit it. A good model, and cheap to run.
|
|
176
|
+
|
|
177
|
+
The UNET was trained on multi temporal image pairs.
|
|
178
|
+
(3 best pairs within ~90-120 days pre/post and all thier valid permutations)
|
|
179
|
+
It tends to perform very well and was measured with a ~90% IOU
|
|
180
|
+
on held out fires. it was only trained on fires greater than 250 acres.
|
|
181
|
+
|
|
182
|
+
Both models used refined WFIGS permiters. by taking a rough final perimeter and
|
|
183
|
+
refining it using dnbr we can more readily isolate the positve burn signal and reduce unburned island noise inherent in field perimeters.
|
|
184
|
+
|
|
185
|
+
## License
|
|
186
|
+
|
|
187
|
+
MIT
|
hls_burn-0.1.0/README.md
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# hls-burn
|
|
2
|
+
|
|
3
|
+
Map burn scars from a pre-fire and a post-fire scene of NASA's Harmonized Landsat
|
|
4
|
+
Sentinel-2 (HLS, 30 m). Scenes are searched and read from Microsoft Planetary Computer,
|
|
5
|
+
so all you need is an area and the fire's dates.
|
|
6
|
+
|
|
7
|
+
There are three segmenters, and they all work the same way: `segment()` gives a class
|
|
8
|
+
raster, `polygonize()` gives a GeoDataFrame.
|
|
9
|
+
|
|
10
|
+
| segmenter | method | classes |
|
|
11
|
+
|---|---|---|
|
|
12
|
+
| `ThresholdSegmenter` | thresholds on a burn index (dNBR by default) | USGS-style severity, or your own bins |
|
|
13
|
+
| `SklearnSegmenter` | bundled XGBoost model on burn indices, trained on ~1,000 US fires | burned / unburned |
|
|
14
|
+
| `DeepSegmenter` | 24M-param [U-Net](https://huggingface.co/hughbertlongshanks/unet-burn-hls), trained on ~6,000 US pre/post pairs | burned / unburned |
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install hls-burn # threshold + XGBoost
|
|
20
|
+
pip install "hls-burn[deep]" # + U-Net (PyTorch)
|
|
21
|
+
pip install "hls-burn[map]" # + polygon editor for notebooks
|
|
22
|
+
pip install "hls-burn[all]"
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Python 3.11+.
|
|
26
|
+
|
|
27
|
+
## Usage
|
|
28
|
+
|
|
29
|
+
The steps below follow `examples.ipynb`, which maps a February 2026 fire near Lake
|
|
30
|
+
Okeechobee.
|
|
31
|
+
|
|
32
|
+
### Get scenes
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import shapely
|
|
36
|
+
from hls_burn.data.fire_data import HLSFireData
|
|
37
|
+
|
|
38
|
+
fire = HLSFireData()
|
|
39
|
+
fire.get_clearest_hls_scenes_pre_post(
|
|
40
|
+
search_area=shapely.Point(-80.88, 27.11).buffer(0.1), # lon/lat; a shapely geom or WKT
|
|
41
|
+
start_date="2026-02-12",
|
|
42
|
+
end_date="2026-02-15",
|
|
43
|
+
pre_offset_days=30, # search this far before start_date for a clear scene
|
|
44
|
+
post_offset_days=30, # and this far after end_date
|
|
45
|
+
)
|
|
46
|
+
fire.show_scenes() # true colour
|
|
47
|
+
fire.show_scenes(bands=("swir2", "nir", "red")) # false colour: burns show up red
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
If either scene is mostly cloud, shadow or snow you get a warning.
|
|
51
|
+
|
|
52
|
+
### Burn index
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
fire.calc_dnbr()
|
|
56
|
+
fire.plot_computed_index(vmin=0, vmax=0.5)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
There are other indices too. Some of them need a perimeter or an unburned reference
|
|
60
|
+
area.
|
|
61
|
+
|
|
62
|
+
### Threshold segmentation
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from hls_burn.segmenters.classical_segmenter import ThresholdSegmenter
|
|
66
|
+
|
|
67
|
+
seg = ThresholdSegmenter(index="dnbr") # default bins: 6 USGS-style severity classes
|
|
68
|
+
seg.segment(fire)
|
|
69
|
+
seg.plot_segmentation()
|
|
70
|
+
|
|
71
|
+
seg.bins = (0.1,) # binary: dNBR > 0.1 is burned
|
|
72
|
+
seg.segment(fire)
|
|
73
|
+
seg.export_raster("mask.tif", crs=5070)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
You'll usually have to tune the thresholds for each fire. The pretrained models don't
|
|
77
|
+
need that.
|
|
78
|
+
|
|
79
|
+
### Pretrained models
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from hls_burn.segmenters.scikit_segmenter import SklearnSegmenter
|
|
83
|
+
from hls_burn.segmenters.deep_segmenter import DeepSegmenter # needs [deep]
|
|
84
|
+
|
|
85
|
+
xgb = SklearnSegmenter() # bundled model; or pass your own scikit-learn estimator
|
|
86
|
+
xgb.segment(fire)
|
|
87
|
+
|
|
88
|
+
unet = DeepSegmenter(cutoff=0.6) # probability threshold
|
|
89
|
+
unet.segment(fire)
|
|
90
|
+
unet.plot_segmentation()
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Unusable pixels (cloud, nodata) come back as 255.
|
|
94
|
+
|
|
95
|
+
### Polygons
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
gdf = unet.polygonize() # one row per connected patch
|
|
99
|
+
gdf.explore(tiles="Esri.WorldImagery") # it's a plain GeoDataFrame
|
|
100
|
+
unet.export_polygons("burned.fgb", crs=5070)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
The polygons are also stored on the segmenter, and every call replaces them.
|
|
104
|
+
|
|
105
|
+
### Edit polygons in a notebook (`[map]`)
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
unet.edit_polygons(fire=fire, window="post") # false colour by default
|
|
109
|
+
unet.edit_polygons(fire=fire, bands=("red", "green", "blue"))
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
This opens a map with the scene under the polygons. You can move vertices, reshape
|
|
113
|
+
polygons or delete them, then call `export_polygons()` when you're done.
|
|
114
|
+
|
|
115
|
+
## Model Performance
|
|
116
|
+
The library currently ships with access to two pretrained models as shown above.
|
|
117
|
+
|
|
118
|
+
The XGBoost model performs better than un tuned threshholding in
|
|
119
|
+
most cases and has an IOU of ~70%. It tends to fail in scenes where having a lot of context would be beneficial.
|
|
120
|
+
e.g. fields. It's reliance on computed features (dnbr, rbr, etc...)
|
|
121
|
+
also limit it. A good model, and cheap to run.
|
|
122
|
+
|
|
123
|
+
The UNET was trained on multi temporal image pairs.
|
|
124
|
+
(3 best pairs within ~90-120 days pre/post and all thier valid permutations)
|
|
125
|
+
It tends to perform very well and was measured with a ~90% IOU
|
|
126
|
+
on held out fires. it was only trained on fires greater than 250 acres.
|
|
127
|
+
|
|
128
|
+
Both models used refined WFIGS permiters. by taking a rough final perimeter and
|
|
129
|
+
refining it using dnbr we can more readily isolate the positve burn signal and reduce unburned island noise inherent in field perimeters.
|
|
130
|
+
|
|
131
|
+
## License
|
|
132
|
+
|
|
133
|
+
MIT
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
import warnings
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
import xarray
|
|
9
|
+
from shapely.geometry.base import BaseGeometry
|
|
10
|
+
from shapely.io import from_wkt, to_wkt
|
|
11
|
+
|
|
12
|
+
from hls_burn.utils.nbr_utils import (
|
|
13
|
+
FMASK_WATER,
|
|
14
|
+
_inside,
|
|
15
|
+
_to_data_crs,
|
|
16
|
+
compute_dnbr,
|
|
17
|
+
compute_dnbr2,
|
|
18
|
+
compute_nbr,
|
|
19
|
+
compute_nbr2,
|
|
20
|
+
compute_offset_dnbr,
|
|
21
|
+
compute_rbr,
|
|
22
|
+
compute_rdnbr,
|
|
23
|
+
)
|
|
24
|
+
from hls_burn.utils.pc_utils import (
|
|
25
|
+
REFLECTANCE_NODATA,
|
|
26
|
+
DateLike,
|
|
27
|
+
clearest_hls_scenes,
|
|
28
|
+
open_scene,
|
|
29
|
+
save_scene,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
Window = Literal["pre", "post"]
|
|
33
|
+
GeomLike = str | BaseGeometry # WKT or shapely geometry, lon/lat (EPSG:4326)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _as_geom(geom: GeomLike | None) -> BaseGeometry | None:
|
|
37
|
+
"""WKT -> shapely; shapely geometries and None pass through."""
|
|
38
|
+
return from_wkt(geom) if isinstance(geom, str) else geom
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class HLSFireData:
|
|
42
|
+
"""A fire's pre- and post-fire HLS scene, burn indices, and optionally a perimeter.
|
|
43
|
+
|
|
44
|
+
The plain indices (calc_nbr, calc_dnbr, ...) need no perimeter. Offset
|
|
45
|
+
indices need a perimeter or an unburned `reference` area, and label_mask()
|
|
46
|
+
(training labels) needs a perimeter.
|
|
47
|
+
|
|
48
|
+
Every calc_* method returns a DataArray (NaN where invalid) and also stores
|
|
49
|
+
it in `computed_index`. Water is masked from the pre-fire scene only, since
|
|
50
|
+
Fmask often flags fresh char as water in the post-fire scene.
|
|
51
|
+
|
|
52
|
+
Example:
|
|
53
|
+
>>> d = HLSFireData()
|
|
54
|
+
>>> d.get_clearest_hls_scenes_pre_post(search_box, start, end)
|
|
55
|
+
>>> d.calc_dnbr()
|
|
56
|
+
>>> d.plot_computed_index()
|
|
57
|
+
>>> d.show_scenes()
|
|
58
|
+
|
|
59
|
+
>>> d = HLSFireData(perimeter=wkt)
|
|
60
|
+
>>> d.load_scenes("pre_1.tif", "post_1.tif")
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(self, perimeter: GeomLike | None = None):
|
|
64
|
+
self.perimeter: BaseGeometry | None = _as_geom(perimeter)
|
|
65
|
+
self.pre: xarray.Dataset | None = None
|
|
66
|
+
self.post: xarray.Dataset | None = None
|
|
67
|
+
self.computed_index: xarray.DataArray | None = None
|
|
68
|
+
|
|
69
|
+
# ------------------------------------------------------------------ scenes
|
|
70
|
+
def load_scenes(self, pre_path: str | Path, post_path: str | Path) -> None:
|
|
71
|
+
"""Load a pre and a post scene saved with save_scenes."""
|
|
72
|
+
self.pre, self.post = open_scene(pre_path), open_scene(post_path)
|
|
73
|
+
|
|
74
|
+
def save_scenes(self, pre_path: str | Path, post_path: str | Path) -> None:
|
|
75
|
+
"""Write the pre and post scenes as GeoTIFFs (see save_scene)."""
|
|
76
|
+
|
|
77
|
+
assert (self.pre is not None) and (
|
|
78
|
+
self.post is not None
|
|
79
|
+
), "Pre or post are undefined. Download the clearest available scenes within your timeframe first."
|
|
80
|
+
|
|
81
|
+
save_scene(self.pre, path=pre_path)
|
|
82
|
+
save_scene(self.post, path=post_path)
|
|
83
|
+
|
|
84
|
+
def get_clearest_hls_scenes_pre_post(
|
|
85
|
+
self,
|
|
86
|
+
start_date: DateLike,
|
|
87
|
+
end_date: DateLike,
|
|
88
|
+
search_area: GeomLike | None = None,
|
|
89
|
+
pre_offset_days: int = 30,
|
|
90
|
+
post_offset_days: int = 30,
|
|
91
|
+
max_nodata_frac: float = 0.25,
|
|
92
|
+
**kwargs,
|
|
93
|
+
) -> None:
|
|
94
|
+
"""Download the clearest pre and post scene.
|
|
95
|
+
If the fire has a perimeter from when you instsantiated it - that will be used to download.
|
|
96
|
+
Otherwise, pass an AOI polygon as a shapely geom or WKT string to search.
|
|
97
|
+
|
|
98
|
+
Pre window: [start_date - pre_offset_days, start_date].
|
|
99
|
+
Post window: [end_date, end_date + post_offset_days].
|
|
100
|
+
Among equally clear scenes, the one closest to the fire is chosen
|
|
101
|
+
(latest pre, earliest post). Warns when a chosen scene is more than
|
|
102
|
+
`max_nodata_frac` missing, cloud, shadow or snow (per Fmask) inside the
|
|
103
|
+
search area, so you can widen the window.
|
|
104
|
+
kwargs go to clearest_hls_scenes (collections, bad_bits, clip).
|
|
105
|
+
|
|
106
|
+
Raises:
|
|
107
|
+
ValueError: if a window has no scene.
|
|
108
|
+
"""
|
|
109
|
+
area = _as_geom(search_area)
|
|
110
|
+
|
|
111
|
+
if area is None and isinstance(self.perimeter, BaseGeometry):
|
|
112
|
+
area = self.perimeter.convex_hull
|
|
113
|
+
|
|
114
|
+
start, end = pd.Timestamp(start_date), pd.Timestamp(end_date)
|
|
115
|
+
windows = {
|
|
116
|
+
"pre": (start - datetime.timedelta(days=pre_offset_days), start),
|
|
117
|
+
"post": (end, end + datetime.timedelta(days=post_offset_days)),
|
|
118
|
+
}
|
|
119
|
+
for name, (a, b) in windows.items():
|
|
120
|
+
scenes, _ = clearest_hls_scenes(
|
|
121
|
+
to_wkt(area), a, b, n=1, prefer_latest=name == "pre", **kwargs
|
|
122
|
+
)
|
|
123
|
+
if not scenes:
|
|
124
|
+
raise ValueError(f"no {name} scene between {a} and {b}")
|
|
125
|
+
ds, info = scenes[0]
|
|
126
|
+
setattr(self, name, ds)
|
|
127
|
+
|
|
128
|
+
# nodata = missing pixels (Fmask fill / reflectance nodata), plus what
|
|
129
|
+
# clearest_hls_scenes counts as bad inside the search area (cloud,
|
|
130
|
+
# shadow, snow and missing)
|
|
131
|
+
missing = float(((ds.Fmask == 255) | (ds.nir == REFLECTANCE_NODATA)).mean())
|
|
132
|
+
unusable = max(missing, float(info["bad_frac"]))
|
|
133
|
+
if unusable > max_nodata_frac:
|
|
134
|
+
days = pre_offset_days if name == "pre" else post_offset_days
|
|
135
|
+
warnings.warn(
|
|
136
|
+
f"best {name} scene ({info['date']}, {info['collection']}) is "
|
|
137
|
+
f"{100 * unusable:.0f}% nodata/cloud ({100 * missing:.0f}% missing pixels) "
|
|
138
|
+
f"in the search area; window {a.date()} to {b.date()}. "
|
|
139
|
+
f"Consider a longer window, e.g. {name}_offset_days={2 * days}.",
|
|
140
|
+
stacklevel=2,
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
# ----------------------------------------------------------------- indices
|
|
144
|
+
def _store(self, result, name: str, diverging: bool) -> xarray.DataArray:
|
|
145
|
+
"""index.where(valid) -> computed_index; offset info (if any) into attrs."""
|
|
146
|
+
index, valid, *info = result
|
|
147
|
+
out = index.where(valid).rename(name)
|
|
148
|
+
if info: # compute_offset_dnbr's info dict
|
|
149
|
+
out.attrs.update(
|
|
150
|
+
{k: v for k, v in info[0].items() if k != "reference_mask"}
|
|
151
|
+
)
|
|
152
|
+
out.attrs["diverging"] = diverging
|
|
153
|
+
self.computed_index = out
|
|
154
|
+
return out
|
|
155
|
+
|
|
156
|
+
def _geom(self, perimeter, reference) -> dict:
|
|
157
|
+
"""perimeter/reference kwargs; self.perimeter when neither is given."""
|
|
158
|
+
perimeter, reference = _as_geom(perimeter), _as_geom(reference)
|
|
159
|
+
if perimeter is None and reference is None:
|
|
160
|
+
perimeter = self.perimeter
|
|
161
|
+
return {"perimeter": perimeter, "reference": reference}
|
|
162
|
+
|
|
163
|
+
def _single_scene(self, fn, window: Window, kwargs: dict):
|
|
164
|
+
"""NBR / NBR2 of one scene. For the post scene, water comes from the pre
|
|
165
|
+
scene (as in the dNBR family): Fmask often flags fresh char as water."""
|
|
166
|
+
if (
|
|
167
|
+
window == "pre"
|
|
168
|
+
or not kwargs.get("strip_water", True)
|
|
169
|
+
or not kwargs.get("mask_fmask", True)
|
|
170
|
+
):
|
|
171
|
+
return fn(getattr(self, window), **kwargs)
|
|
172
|
+
|
|
173
|
+
index, valid = fn(self.post, **{**kwargs, "strip_water": False})
|
|
174
|
+
fm = self.pre["Fmask"]
|
|
175
|
+
water_bits = sum(1 << b for b in kwargs.get("fmask_water", FMASK_WATER))
|
|
176
|
+
pre_water = (fm.where(fm != 255, 0).astype("uint8") & water_bits) != 0
|
|
177
|
+
valid = valid & ~pre_water
|
|
178
|
+
return index.where(valid), valid
|
|
179
|
+
|
|
180
|
+
def calc_nbr(self, window: Window = "post", **kwargs) -> xarray.DataArray:
|
|
181
|
+
"""NBR of the pre or post scene, named "nbr_<window>".
|
|
182
|
+
|
|
183
|
+
For the post scene, water is masked using the pre scene's Fmask.
|
|
184
|
+
kwargs go to compute_nbr.
|
|
185
|
+
"""
|
|
186
|
+
return self._store(
|
|
187
|
+
self._single_scene(compute_nbr, window, kwargs), f"nbr_{window}", False
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
def calc_nbr2(self, window: Window = "post", **kwargs) -> xarray.DataArray:
|
|
191
|
+
"""NBR2 of the pre or post scene, named "nbr2_<window>".
|
|
192
|
+
|
|
193
|
+
For the post scene, water is masked using the pre scene's Fmask.
|
|
194
|
+
kwargs go to compute_nbr2.
|
|
195
|
+
"""
|
|
196
|
+
return self._store(
|
|
197
|
+
self._single_scene(compute_nbr2, window, kwargs), f"nbr2_{window}", False
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
def calc_dnbr(self, **kwargs) -> xarray.DataArray:
|
|
201
|
+
"""dNBR = NBR_pre - NBR_post; water masked from the pre scene only.
|
|
202
|
+
|
|
203
|
+
kwargs go to compute_dnbr.
|
|
204
|
+
"""
|
|
205
|
+
return self._store(compute_dnbr((self.pre, self.post), **kwargs), "dnbr", True)
|
|
206
|
+
|
|
207
|
+
def calc_offset_dnbr(
|
|
208
|
+
self, perimeter=None, reference=None, **kwargs
|
|
209
|
+
) -> xarray.DataArray:
|
|
210
|
+
"""dNBR minus the median dNBR of an unburned reference area.
|
|
211
|
+
|
|
212
|
+
Uses `self.perimeter` unless `perimeter` or `reference` is given.
|
|
213
|
+
The offset and reference pixel count go into the result's attrs.
|
|
214
|
+
kwargs go to compute_offset_dnbr.
|
|
215
|
+
"""
|
|
216
|
+
result = compute_offset_dnbr(
|
|
217
|
+
(self.pre, self.post), **self._geom(perimeter, reference), **kwargs
|
|
218
|
+
)
|
|
219
|
+
return self._store(result, "offset_dnbr", True)
|
|
220
|
+
|
|
221
|
+
def calc_dnbr2(self, offset=False, perimeter=None, reference=None, **kwargs):
|
|
222
|
+
"""dNBR2 = NBR2_pre - NBR2_post, optionally offset-corrected.
|
|
223
|
+
|
|
224
|
+
With `offset=True`, uses `self.perimeter` unless `perimeter` or
|
|
225
|
+
`reference` is given. kwargs go to compute_dnbr2.
|
|
226
|
+
"""
|
|
227
|
+
geom = self._geom(perimeter, reference) if offset else {}
|
|
228
|
+
result = compute_dnbr2((self.pre, self.post), offset=offset, **geom, **kwargs)
|
|
229
|
+
return self._store(result, "dnbr2", True)
|
|
230
|
+
|
|
231
|
+
def calc_rbr(self, offset=False, perimeter=None, reference=None, **kwargs):
|
|
232
|
+
"""RBR = dNBR / (NBR_pre + 1.001), optionally offset-corrected.
|
|
233
|
+
|
|
234
|
+
With `offset=True`, uses `self.perimeter` unless `perimeter` or
|
|
235
|
+
`reference` is given. kwargs go to compute_rbr.
|
|
236
|
+
"""
|
|
237
|
+
geom = self._geom(perimeter, reference) if offset else {}
|
|
238
|
+
result = compute_rbr((self.pre, self.post), offset=offset, **geom, **kwargs)
|
|
239
|
+
return self._store(result, "rbr", True)
|
|
240
|
+
|
|
241
|
+
def calc_rdnbr(self, offset=False, perimeter=None, reference=None, **kwargs):
|
|
242
|
+
"""RdNBR = dNBR / sqrt(|NBR_pre|), optionally offset-corrected.
|
|
243
|
+
|
|
244
|
+
With `offset=True`, uses `self.perimeter` unless `perimeter` or
|
|
245
|
+
`reference` is given. kwargs go to compute_rdnbr.
|
|
246
|
+
"""
|
|
247
|
+
geom = self._geom(perimeter, reference) if offset else {}
|
|
248
|
+
result = compute_rdnbr((self.pre, self.post), offset=offset, **geom, **kwargs)
|
|
249
|
+
return self._store(result, "rdnbr", True)
|
|
250
|
+
|
|
251
|
+
# ------------------------------------------------------------------ labels
|
|
252
|
+
def label_mask(self, buffer_m: float = 0.0) -> xarray.DataArray:
|
|
253
|
+
"""True inside the perimeter (optionally buffered, meters) on the scene grid."""
|
|
254
|
+
if self.perimeter is None:
|
|
255
|
+
raise RuntimeError(
|
|
256
|
+
"label_mask needs a perimeter: HLSFireData(perimeter=...)"
|
|
257
|
+
)
|
|
258
|
+
like = self.post.nir
|
|
259
|
+
geom = _to_data_crs(self.perimeter, "EPSG:4326", like.rio.crs)
|
|
260
|
+
return _inside(geom.buffer(buffer_m) if buffer_m else geom, like).rename(
|
|
261
|
+
"label"
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
# ------------------------------------------------------------ visualization
|
|
265
|
+
def _outline(self, ax, crs, x, y, color):
|
|
266
|
+
"""Draw the perimeter (if any) on `ax` and fit the axes to the x/y grid."""
|
|
267
|
+
import geopandas as gpd
|
|
268
|
+
|
|
269
|
+
if self.perimeter is not None:
|
|
270
|
+
gpd.GeoSeries([self.perimeter], crs="EPSG:4326").to_crs(crs).boundary.plot(
|
|
271
|
+
ax=ax, color=color, linewidth=1
|
|
272
|
+
)
|
|
273
|
+
ax.set_xlim(x[0], x[-1])
|
|
274
|
+
ax.set_ylim(y[-1], y[0])
|
|
275
|
+
ax.set_axis_off()
|
|
276
|
+
|
|
277
|
+
def show_scenes(self, bands: tuple[str, str, str] = ("red", "green", "blue")):
|
|
278
|
+
"""Pre and post scene side by side (2-98% stretch).
|
|
279
|
+
|
|
280
|
+
Use bands=("swir2", "nir", "red") for a false-color burn view.
|
|
281
|
+
Returns the two axes (pre, post); save with axes[0].figure.savefig(...).
|
|
282
|
+
"""
|
|
283
|
+
import matplotlib.pyplot as plt
|
|
284
|
+
|
|
285
|
+
fig, axes = plt.subplots(1, 2, figsize=(16, 8))
|
|
286
|
+
for ax, (name, ds) in zip(axes, (("pre", self.pre), ("post", self.post))):
|
|
287
|
+
arr = np.stack([ds[b].values.astype("float32") for b in bands], -1)
|
|
288
|
+
ok = (arr != REFLECTANCE_NODATA).all(-1)
|
|
289
|
+
lo, hi = np.percentile(arr[ok], (2, 98)) if ok.any() else (0, 1)
|
|
290
|
+
img = np.clip((arr - lo) / max(hi - lo, 1e-6), 0, 1)
|
|
291
|
+
img[~ok] = 1 # nodata white
|
|
292
|
+
x, y = ds.x.values, ds.y.values
|
|
293
|
+
ax.imshow(img, extent=[x[0], x[-1], y[-1], y[0]])
|
|
294
|
+
ax.set_title(f"{name} {str(ds.time.values)[:10]}")
|
|
295
|
+
self._outline(ax, ds.rio.crs, x, y, "#ff00ff")
|
|
296
|
+
fig.tight_layout()
|
|
297
|
+
return axes # not the Figure: Jupyter would display a returned Figure twice
|
|
298
|
+
|
|
299
|
+
def plot_computed_index(self, vmin=None, vmax=None, cmap=None, ax=None):
|
|
300
|
+
"""Plot `computed_index`. NaN is grey; differenced indices use a diverging
|
|
301
|
+
map centred on 0 (burn red). Limits default to the 2-98th percentile."""
|
|
302
|
+
import matplotlib
|
|
303
|
+
import matplotlib.pyplot as plt
|
|
304
|
+
from matplotlib.colors import Normalize, TwoSlopeNorm
|
|
305
|
+
|
|
306
|
+
da = self.computed_index
|
|
307
|
+
values = da.values
|
|
308
|
+
diverging = da.attrs.get("diverging", False)
|
|
309
|
+
lo, hi = np.nanpercentile(values, [2, 98])
|
|
310
|
+
vmin = lo if vmin is None else vmin
|
|
311
|
+
vmax = hi if vmax is None else vmax
|
|
312
|
+
cm = matplotlib.colormaps[
|
|
313
|
+
cmap or ("RdYlGn_r" if diverging else "RdYlGn")
|
|
314
|
+
].copy()
|
|
315
|
+
cm.set_bad("#bdbdbd")
|
|
316
|
+
norm = (
|
|
317
|
+
TwoSlopeNorm(0, vmin, vmax)
|
|
318
|
+
if diverging and vmin < 0 < vmax
|
|
319
|
+
else Normalize(vmin, vmax)
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
if ax is None:
|
|
323
|
+
_, ax = plt.subplots(figsize=(9, 8))
|
|
324
|
+
x, y = da.x.values, da.y.values
|
|
325
|
+
im = ax.imshow(values, extent=[x[0], x[-1], y[-1], y[0]], cmap=cm, norm=norm)
|
|
326
|
+
ax.figure.colorbar(im, ax=ax, shrink=0.8, extend="both", label=da.name)
|
|
327
|
+
ax.set_title(f"{da.name} (median {np.nanmedian(values):.3f})")
|
|
328
|
+
self._outline(ax, da.rio.crs, x, y, "black")
|
|
329
|
+
return ax
|