hazardfuse 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.
- hazardfuse-0.1.0/LICENSE +21 -0
- hazardfuse-0.1.0/PKG-INFO +36 -0
- hazardfuse-0.1.0/pyproject.toml +58 -0
- hazardfuse-0.1.0/setup.cfg +4 -0
- hazardfuse-0.1.0/src/hazardfuse/__init__.py +39 -0
- hazardfuse-0.1.0/src/hazardfuse/__main__.py +3 -0
- hazardfuse-0.1.0/src/hazardfuse/calibration.py +64 -0
- hazardfuse-0.1.0/src/hazardfuse/cli.py +129 -0
- hazardfuse-0.1.0/src/hazardfuse/config.py +47 -0
- hazardfuse-0.1.0/src/hazardfuse/groups.py +21 -0
- hazardfuse-0.1.0/src/hazardfuse/io.py +80 -0
- hazardfuse-0.1.0/src/hazardfuse/metrics.py +76 -0
- hazardfuse-0.1.0/src/hazardfuse/model.py +348 -0
- hazardfuse-0.1.0/src/hazardfuse/nn.py +87 -0
- hazardfuse-0.1.0/src/hazardfuse/site.py +145 -0
- hazardfuse-0.1.0/src/hazardfuse/split.py +80 -0
- hazardfuse-0.1.0/src/hazardfuse/synthetic.py +24 -0
- hazardfuse-0.1.0/src/hazardfuse.egg-info/PKG-INFO +36 -0
- hazardfuse-0.1.0/src/hazardfuse.egg-info/SOURCES.txt +24 -0
- hazardfuse-0.1.0/src/hazardfuse.egg-info/dependency_links.txt +1 -0
- hazardfuse-0.1.0/src/hazardfuse.egg-info/entry_points.txt +2 -0
- hazardfuse-0.1.0/src/hazardfuse.egg-info/requires.txt +12 -0
- hazardfuse-0.1.0/src/hazardfuse.egg-info/top_level.txt +1 -0
- hazardfuse-0.1.0/tests/test_cli.py +9 -0
- hazardfuse-0.1.0/tests/test_core.py +82 -0
- hazardfuse-0.1.0/tests/test_model.py +52 -0
hazardfuse-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Salman Karim
|
|
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.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hazardfuse
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Hazard-index-guided band attention and spatial embedding fusion for mapping leached-metal-associated hazard from satellite and geospatial data
|
|
5
|
+
Author-email: Salman Karim <salmankarim@vt.edu>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/salmansust/hazardfuse
|
|
8
|
+
Project-URL: Source, https://github.com/salmansust/hazardfuse
|
|
9
|
+
Project-URL: Issues, https://github.com/salmansust/hazardfuse/issues
|
|
10
|
+
Keywords: band attention,deep learning,remote sensing,Sentinel-2,groundwater,hazard mapping,coal combustion residuals,leached metals,GeoAI
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: GIS
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: numpy>=1.23
|
|
26
|
+
Requires-Dist: pandas>=1.5
|
|
27
|
+
Requires-Dist: scipy>=1.9
|
|
28
|
+
Requires-Dist: scikit-learn>=1.2
|
|
29
|
+
Requires-Dist: tensorflow>=2.12
|
|
30
|
+
Requires-Dist: rasterio>=1.3
|
|
31
|
+
Requires-Dist: pyyaml>=6.0
|
|
32
|
+
Provides-Extra: dev
|
|
33
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
34
|
+
Requires-Dist: build>=1.0; extra == "dev"
|
|
35
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
36
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=64", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "hazardfuse"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Hazard-index-guided band attention and spatial embedding fusion for mapping leached-metal-associated hazard from satellite and geospatial data"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "Salman Karim", email = "salmankarim@vt.edu" }]
|
|
13
|
+
keywords = [
|
|
14
|
+
"band attention", "deep learning", "remote sensing", "Sentinel-2", "groundwater", "hazard mapping",
|
|
15
|
+
"coal combustion residuals", "leached metals", "GeoAI",
|
|
16
|
+
]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 4 - Beta",
|
|
19
|
+
"Intended Audience :: Science/Research",
|
|
20
|
+
"License :: OSI Approved :: MIT License",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3.9",
|
|
24
|
+
"Programming Language :: Python :: 3.10",
|
|
25
|
+
"Programming Language :: Python :: 3.11",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Topic :: Scientific/Engineering :: GIS",
|
|
28
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
29
|
+
]
|
|
30
|
+
dependencies = [
|
|
31
|
+
"numpy>=1.23",
|
|
32
|
+
"pandas>=1.5",
|
|
33
|
+
"scipy>=1.9",
|
|
34
|
+
"scikit-learn>=1.2",
|
|
35
|
+
"tensorflow>=2.12",
|
|
36
|
+
"rasterio>=1.3",
|
|
37
|
+
"pyyaml>=6.0",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
[project.optional-dependencies]
|
|
41
|
+
dev = ["pytest>=7", "build>=1.0", "twine>=5"]
|
|
42
|
+
|
|
43
|
+
[project.scripts]
|
|
44
|
+
hazardfuse = "hazardfuse.cli:main"
|
|
45
|
+
|
|
46
|
+
[project.urls]
|
|
47
|
+
Homepage = "https://github.com/salmansust/hazardfuse"
|
|
48
|
+
Source = "https://github.com/salmansust/hazardfuse"
|
|
49
|
+
Issues = "https://github.com/salmansust/hazardfuse/issues"
|
|
50
|
+
|
|
51
|
+
[tool.setuptools.dynamic]
|
|
52
|
+
version = { attr = "hazardfuse.__version__" }
|
|
53
|
+
|
|
54
|
+
[tool.setuptools.packages.find]
|
|
55
|
+
where = ["src"]
|
|
56
|
+
|
|
57
|
+
[tool.pytest.ini_options]
|
|
58
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""HazardFuse: hazard-index-guided band attention and spatial embedding fusion for mapping leached-metal-associated
|
|
2
|
+
hazard from satellite and geospatial data.
|
|
3
|
+
|
|
4
|
+
Quick start::
|
|
5
|
+
|
|
6
|
+
from hazardfuse import HazardFuse, Site
|
|
7
|
+
|
|
8
|
+
site = Site.from_folder("data/glen_lyn", features="glen_lyn_Features", labels="glen_lyn_Label",
|
|
9
|
+
hi="glen_lyn_HI", name="Glen Lyn")
|
|
10
|
+
model = HazardFuse(seed=42).fit(site)
|
|
11
|
+
print(model.report()) # accuracy, kappa, class-wise precision, recall and F1
|
|
12
|
+
print(model.confusion_matrix(split="test"))
|
|
13
|
+
print(model.band_attention().head(15))
|
|
14
|
+
model.to_geotiffs("results/glen_lyn")
|
|
15
|
+
model.save("results/glen_lyn/HazardFuse")
|
|
16
|
+
|
|
17
|
+
new = Site.from_folder("data/bremo", features="bremo_Features", reference=model.schema, name="Bremo")
|
|
18
|
+
model.to_geotiffs("results/bremo", site=new)
|
|
19
|
+
"""
|
|
20
|
+
__version__ = "0.1.0"
|
|
21
|
+
|
|
22
|
+
from .config import DEFAULT_DATA, DEFAULT_MODEL, DEFAULT_SPLIT # noqa: E402
|
|
23
|
+
from .groups import FEATURE_GROUPS, group_of # noqa: E402
|
|
24
|
+
from .metrics import evaluate # noqa: E402
|
|
25
|
+
from .site import Site # noqa: E402
|
|
26
|
+
from .split import block_split # noqa: E402
|
|
27
|
+
|
|
28
|
+
__all__ = ["HazardFuse", "build_hazardfuse", "Site", "block_split", "evaluate", "FEATURE_GROUPS", "group_of",
|
|
29
|
+
"DEFAULT_MODEL", "DEFAULT_DATA", "DEFAULT_SPLIT", "__version__"]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def __getattr__(name): # TensorFlow is imported only when the model is used
|
|
33
|
+
if name == "HazardFuse":
|
|
34
|
+
from .model import HazardFuse
|
|
35
|
+
return HazardFuse
|
|
36
|
+
if name == "build_hazardfuse":
|
|
37
|
+
from .nn import build_hazardfuse
|
|
38
|
+
return build_hazardfuse
|
|
39
|
+
raise AttributeError(f"module 'hazardfuse' has no attribute {name!r}")
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Calibration of the class-1 score (notebook section 4, `calibrate`).
|
|
2
|
+
|
|
3
|
+
The score is oriented with the training labels (class-1 pixels must score higher), converted to its rank among the
|
|
4
|
+
valid pixels and mapped piecewise-linearly so that the training cut rank becomes 0.5. The cut rank follows the rule:
|
|
5
|
+
"prevalence" (1 - class-1 share of the labelled pixels), "balanced_acc" (cut that maximises balanced accuracy on the
|
|
6
|
+
labelled pixels) or "fixed" (0.5). The map is therefore a calibrated rank score with the decision threshold at 0.5."""
|
|
7
|
+
import numpy as np
|
|
8
|
+
from sklearn.metrics import balanced_accuracy_score
|
|
9
|
+
|
|
10
|
+
from .config import THRESHOLD
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _rank_to_prob(r, cut):
|
|
14
|
+
return np.where(r < cut, 0.5 * r / cut, 0.5 + 0.5 * (r - cut) / (1.0 - cut))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def calibrate(score_map, Y, valid, label_mask, rule="prevalence", orient=True):
|
|
18
|
+
"""Calibrated map (NaN outside `valid`) and its parameters {"flipped", "train_cut_rank", "rule"}."""
|
|
19
|
+
lm = np.asarray(label_mask, dtype=bool)
|
|
20
|
+
s = np.array(score_map, dtype=np.float64, copy=True)
|
|
21
|
+
y_tr = Y[lm]
|
|
22
|
+
if orient:
|
|
23
|
+
flipped = bool(np.nanmean(s[lm][y_tr == 1]) < np.nanmean(s[lm][y_tr == 0]))
|
|
24
|
+
else:
|
|
25
|
+
flipped = bool((s[valid] > np.nanmedian(s[valid])).mean() > 0.5)
|
|
26
|
+
if flipped:
|
|
27
|
+
s = -s
|
|
28
|
+
ranks = np.full(valid.shape, np.nan, dtype=np.float64)
|
|
29
|
+
v = s[valid]
|
|
30
|
+
ranks[valid] = np.argsort(np.argsort(v)) / max(len(v) - 1, 1)
|
|
31
|
+
p_tr = ranks[lm]
|
|
32
|
+
if rule == "balanced_acc":
|
|
33
|
+
cut = float(max(np.linspace(0.02, 0.98, 97), key=lambda t: balanced_accuracy_score(y_tr, (p_tr >= t).astype(int))))
|
|
34
|
+
elif rule == "prevalence":
|
|
35
|
+
cut = float(np.clip(1.0 - y_tr.mean(), 0.02, 0.98))
|
|
36
|
+
else:
|
|
37
|
+
cut = float(THRESHOLD)
|
|
38
|
+
prob = np.full(valid.shape, np.nan, dtype=np.float32)
|
|
39
|
+
prob[valid] = _rank_to_prob(ranks[valid], cut)
|
|
40
|
+
return prob, {"flipped": flipped, "train_cut_rank": cut, "rule": rule}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def apply_calibration(score_valid, valid, info, rule="source_cut", prevalence=None):
|
|
44
|
+
"""Map of a new site from its raw scores at the valid pixels (row-major order).
|
|
45
|
+
|
|
46
|
+
rule "raw": the model probability itself (oriented); "source_cut": ranks at this site, cut at the training cut rank
|
|
47
|
+
of the source site; "prevalence": cut at 1 - `prevalence` (expected class-1 share at this site)."""
|
|
48
|
+
s_valid = np.asarray(score_valid, dtype=np.float64)
|
|
49
|
+
prob = np.full(valid.shape, np.nan, dtype=np.float32)
|
|
50
|
+
if rule == "raw":
|
|
51
|
+
prob[valid] = 1.0 - s_valid if info["flipped"] else s_valid
|
|
52
|
+
return prob
|
|
53
|
+
s = -s_valid if info["flipped"] else s_valid
|
|
54
|
+
r = np.argsort(np.argsort(s)) / max(len(s) - 1, 1)
|
|
55
|
+
if rule == "source_cut":
|
|
56
|
+
cut = info["train_cut_rank"]
|
|
57
|
+
elif rule == "prevalence":
|
|
58
|
+
if prevalence is None:
|
|
59
|
+
raise ValueError("rule='prevalence' needs the expected class-1 share `prevalence`")
|
|
60
|
+
cut = float(np.clip(1.0 - prevalence, 0.02, 0.98))
|
|
61
|
+
else:
|
|
62
|
+
raise ValueError(f"unknown rule {rule!r}")
|
|
63
|
+
prob[valid] = _rank_to_prob(r, cut)
|
|
64
|
+
return prob
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Command-line interface.
|
|
2
|
+
|
|
3
|
+
hazardfuse fit CONFIG.yaml [--out DIR] [--seed N] [--smoke]
|
|
4
|
+
hazardfuse predict MODEL_DIR SITE.yaml [--out DIR] [--rule source_cut|prevalence|raw] [--prevalence P]
|
|
5
|
+
[--normalisation source|target]
|
|
6
|
+
hazardfuse info MODEL_DIR
|
|
7
|
+
|
|
8
|
+
CONFIG.yaml (fit) has the section `site` (arguments of Site.from_folder) and optionally `data`, `split`, `model`, `seed`
|
|
9
|
+
and `output`. SITE.yaml (predict) has the section `site` and optionally `output`. See configs/ in the repository."""
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
SMOKE = dict(epochs=2, patience=2)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _yaml(path):
|
|
19
|
+
import yaml
|
|
20
|
+
with open(path) as f:
|
|
21
|
+
return yaml.safe_load(f) or {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _site(cfg, reference=None, base=None):
|
|
25
|
+
from .site import Site
|
|
26
|
+
s = dict(cfg["site"])
|
|
27
|
+
folder = Path(s.pop("folder"))
|
|
28
|
+
if not folder.is_absolute() and base is not None:
|
|
29
|
+
folder = (base / folder).resolve()
|
|
30
|
+
data = {} if reference is not None else (cfg.get("data") or {})
|
|
31
|
+
return Site.from_folder(folder, reference=reference, **s, **data)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _out(a, cfg, base):
|
|
35
|
+
if a.out:
|
|
36
|
+
return Path(a.out)
|
|
37
|
+
o = Path(cfg.get("output") or "results")
|
|
38
|
+
return o if o.is_absolute() else (base / o).resolve()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _json(obj, path):
|
|
42
|
+
Path(path).write_text(json.dumps(obj, indent=2, default=lambda o: o.item() if hasattr(o, "item") else str(o)))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _line(name, e):
|
|
46
|
+
s = (f"{name}: accuracy {e['Accuracy']:.4f} | kappa {e['Kappa']:.4f}")
|
|
47
|
+
if "Kappa_lo" in e:
|
|
48
|
+
s += f" [{e['Kappa_lo']:.3f}, {e['Kappa_hi']:.3f}]"
|
|
49
|
+
return s + f" | F1 class 0 {e['F1_0']:.4f} | F1 class 1 {e['F1_1']:.4f}"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def cmd_fit(a):
|
|
53
|
+
from .model import HazardFuse
|
|
54
|
+
cfg = _yaml(a.config)
|
|
55
|
+
base = Path(a.config).resolve().parent
|
|
56
|
+
out = _out(a, cfg, base)
|
|
57
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
settings = dict(cfg.get("model") or {})
|
|
59
|
+
if a.smoke:
|
|
60
|
+
settings.update(SMOKE)
|
|
61
|
+
split = dict(cfg.get("split") or {})
|
|
62
|
+
if "frac" in split:
|
|
63
|
+
split["frac"] = tuple(split["frac"])
|
|
64
|
+
site = _site(cfg, base=base)
|
|
65
|
+
print(site)
|
|
66
|
+
model = HazardFuse(seed=a.seed if a.seed is not None else cfg.get("seed", 42), **settings)
|
|
67
|
+
model.fit(site, split=split)
|
|
68
|
+
model.save(out / "HazardFuse")
|
|
69
|
+
model.to_geotiffs(out)
|
|
70
|
+
model.split_summary().to_csv(out / "split_summary.csv")
|
|
71
|
+
model.history_.to_csv(out / "history.csv", index=False)
|
|
72
|
+
scores = {s: model.evaluate(split=s) for s in ("train", "val", "test") if model.masks_[s].any()}
|
|
73
|
+
_json(scores, out / "metrics.json")
|
|
74
|
+
model.report().to_csv(out / "metrics.csv")
|
|
75
|
+
model.confusion_matrix(split="test").to_csv(out / "confusion_matrix_test.csv")
|
|
76
|
+
if model.cfg["band_attention"] and model.cfg["center_branch"]:
|
|
77
|
+
model.band_attention(split="test").to_csv(out / "band_attention.csv", index=False)
|
|
78
|
+
print(f"Saved to {out}: HazardFuse/, HazardFuse_score.tif, HazardFuse_class.tif, metrics.json, metrics.csv")
|
|
79
|
+
if "test" in scores:
|
|
80
|
+
print(_line("test", scores["test"]))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def cmd_predict(a):
|
|
84
|
+
from .model import HazardFuse
|
|
85
|
+
model = HazardFuse.load(a.model)
|
|
86
|
+
cfg = _yaml(a.site)
|
|
87
|
+
base = Path(a.site).resolve().parent
|
|
88
|
+
site = _site(cfg, reference=model.schema, base=base)
|
|
89
|
+
print(site)
|
|
90
|
+
out = _out(a, cfg, base)
|
|
91
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
kw = dict(rule=a.rule, prevalence=a.prevalence, normalisation=a.normalisation)
|
|
93
|
+
paths = model.to_geotiffs(out, site=site, **kw)
|
|
94
|
+
print("Written:", ", ".join(str(p) for p in paths))
|
|
95
|
+
if site.Y is not None:
|
|
96
|
+
e = model.evaluate(site=site, **kw)
|
|
97
|
+
_json(e, out / "metrics.json")
|
|
98
|
+
print(_line(site.name, e))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def cmd_info(a):
|
|
102
|
+
from .model import HazardFuse
|
|
103
|
+
print(json.dumps(HazardFuse.load(a.model, verbose=False).summary(), indent=2, default=str))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def main(argv=None):
|
|
107
|
+
p = argparse.ArgumentParser(prog="hazardfuse", description="HazardFuse: band attention and spatial embedding "
|
|
108
|
+
"fusion for hazard mapping")
|
|
109
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
110
|
+
f = sub.add_parser("fit", help="fit on a labelled site and write the model, maps and scores")
|
|
111
|
+
f.add_argument("config"); f.add_argument("--out"); f.add_argument("--seed", type=int)
|
|
112
|
+
f.add_argument("--smoke", action="store_true", help="two epochs: checks the pipeline in minutes")
|
|
113
|
+
f.set_defaults(func=cmd_fit)
|
|
114
|
+
q = sub.add_parser("predict", help="map hazard at a site with a fitted model")
|
|
115
|
+
q.add_argument("model", help="folder written by `hazardfuse fit` (or HazardFuse.save)")
|
|
116
|
+
q.add_argument("site"); q.add_argument("--out")
|
|
117
|
+
q.add_argument("--rule", default="source_cut", choices=["source_cut", "prevalence", "raw"])
|
|
118
|
+
q.add_argument("--prevalence", type=float, help="expected class-1 share at the site (rule prevalence)")
|
|
119
|
+
q.add_argument("--normalisation", default="source", choices=["source", "target"])
|
|
120
|
+
q.set_defaults(func=cmd_predict)
|
|
121
|
+
i = sub.add_parser("info", help="settings, size and scores of a saved model")
|
|
122
|
+
i.add_argument("model")
|
|
123
|
+
i.set_defaults(func=cmd_info)
|
|
124
|
+
a = p.parse_args(argv)
|
|
125
|
+
a.func(a)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
if __name__ == "__main__":
|
|
129
|
+
sys.exit(main())
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Default settings. They reproduce the HazardFuse model of the paper notebook (section 0: `HAZARDFUSE`, the band
|
|
2
|
+
cleaning and the split settings). Override any of them through the keyword arguments of :class:`hazardfuse.HazardFuse`
|
|
3
|
+
and :class:`hazardfuse.Site`, or through a YAML configuration file of the command-line interface."""
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
|
|
6
|
+
# ---- model: architecture and training protocol (notebook HAZARDFUSE)
|
|
7
|
+
DEFAULT_MODEL = dict(
|
|
8
|
+
# architecture
|
|
9
|
+
patch=21, # patch size (pixels); the class is predicted for the center pixel
|
|
10
|
+
dropout=0.30, # dropout of the center, spatial and joint embeddings
|
|
11
|
+
band_attention=True, # sigmoid band-attention weights on the center-pixel spectrum
|
|
12
|
+
fusion_gate=True, # gated fusion of the center and spatial embeddings
|
|
13
|
+
center_branch=True, # ablation switches: remove one branch
|
|
14
|
+
spatial_branch=True,
|
|
15
|
+
drop_bands=["QA60"], # bands left out of the model input (after the band cleaning)
|
|
16
|
+
# training
|
|
17
|
+
epochs=100, batch=256, lr=1e-3,
|
|
18
|
+
patience=20, # early stopping on the validation loss; learning rate halved after max(patience // 3, 2)
|
|
19
|
+
early_stop_on="val", # "val": early stopping on the validation blocks; "none": fixed `epochs`
|
|
20
|
+
predict_batch=2048,
|
|
21
|
+
# calibration of the class-1 score: "prevalence" (cut rank = 1 - class-1 share of the training labels),
|
|
22
|
+
# "balanced_acc" (cut that maximises balanced accuracy on the training pixels) or "fixed" (0.5)
|
|
23
|
+
threshold_rule="prevalence",
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
# ---- input data: band cleaning (notebook section 0 and section 2)
|
|
27
|
+
DEFAULT_DATA = dict(
|
|
28
|
+
feature_cleaning=True,
|
|
29
|
+
drop_bands=["QA60", "DW_LandCover"], # QA band and the land-cover class code (the class probabilities stay)
|
|
30
|
+
circular_bands=["Aspect_deg"], # replaced by sine and cosine
|
|
31
|
+
near_constant_share=0.99, # bands where one value covers this share of the valid pixels are removed
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
# ---- spatial block split with buffer (notebook section 3)
|
|
35
|
+
DEFAULT_SPLIT = dict(block_size=32, frac=(0.70, 0.15, 0.15), buffer_px=8, n_trials=500, seed=42)
|
|
36
|
+
|
|
37
|
+
THRESHOLD = 0.5
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def merged(defaults, overrides=None):
|
|
41
|
+
"""Copy of `defaults` updated with `overrides` (nested dictionaries are merged one level deep)."""
|
|
42
|
+
out = deepcopy(defaults)
|
|
43
|
+
for k, v in (overrides or {}).items():
|
|
44
|
+
if k not in out:
|
|
45
|
+
raise KeyError(f"unknown setting {k!r}; valid settings: {sorted(out)}")
|
|
46
|
+
out[k] = {**out[k], **v} if isinstance(out[k], dict) and isinstance(v, dict) else v
|
|
47
|
+
return out
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Feature groups of the static stack (notebook section 11: band attention and feature-group ablation)."""
|
|
2
|
+
_INDICES = ("NDVI", "MTCI", "SAVI", "CIRE", "NDRE1", "NDRE2", "LAI", "LCC", "CCC")
|
|
3
|
+
|
|
4
|
+
FEATURE_GROUPS = {
|
|
5
|
+
"Sentinel-2 bands": ["B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B8A", "B9", "B11", "B12"],
|
|
6
|
+
"Vegetation indices": list(_INDICES),
|
|
7
|
+
"CSTV": [f"CSTV_{v}_Diff" for v in _INDICES],
|
|
8
|
+
"Rate of change": [f"{v}_Rate" for v in _INDICES],
|
|
9
|
+
"Topographic": ["DEM", "Slope_deg", "Aspect_deg", "Aspect_deg_sin", "Aspect_deg_cos", "Curvature"],
|
|
10
|
+
"Soil": ["Moisture", "pH", "Sand_pct_0_5cm", "Silt_pct_0_5cm", "Clay_pct_0_5cm"],
|
|
11
|
+
"Climate": ["Temperature", "Humidity"],
|
|
12
|
+
"Hydrologic": ["PrecipJJA_mm_mean", "UpstreamArea_km2", "HAND_m", "TWI"],
|
|
13
|
+
"Land cover": ["DW_Vegetation", "DW_LandCover", "DW_Snow", "DW_Built", "DW_Shrubs", "DW_Bare", "DW_Crops",
|
|
14
|
+
"DW_FloodedVeg", "DW_Grass", "DW_Trees", "DW_Water"],
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def group_of(names, groups=None, other="Other"):
|
|
19
|
+
"""Feature group of every band name (case-insensitive); bands of no group get `other`."""
|
|
20
|
+
low = {b.lower(): g for g, bs in (groups or FEATURE_GROUPS).items() for b in bs}
|
|
21
|
+
return [low.get(str(n).lower(), other) for n in names]
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Raster input and output, band cleaning and band alignment."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def find_tif(folder, stem):
|
|
8
|
+
"""Path of `<stem>.tif` (or .tiff) in `folder`."""
|
|
9
|
+
for ext in (".tif", ".tiff", ".TIF", ".TIFF"):
|
|
10
|
+
p = Path(folder) / f"{stem}{ext}"
|
|
11
|
+
if p.exists():
|
|
12
|
+
return p
|
|
13
|
+
raise FileNotFoundError(f"No {stem}.tif/.tiff in {folder}")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def read_raster(path):
|
|
17
|
+
"""(bands, rows, cols) float32 array with nodata as NaN, the raster profile and the band descriptions."""
|
|
18
|
+
import rasterio
|
|
19
|
+
with rasterio.open(path) as src:
|
|
20
|
+
return src.read(masked=True).astype("float32").filled(np.nan), src.profile.copy(), list(src.descriptions)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def write_geotiff(path, arr, profile, dtype="float32", nodata=np.nan):
|
|
24
|
+
"""Single-band GeoTIFF on the grid of `profile` (LZW compressed)."""
|
|
25
|
+
import rasterio
|
|
26
|
+
meta = {"driver": "GTiff", "height": arr.shape[0], "width": arr.shape[1], "count": 1, "dtype": dtype,
|
|
27
|
+
"crs": profile.get("crs"), "transform": profile.get("transform"), "nodata": nodata, "compress": "lzw"}
|
|
28
|
+
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
29
|
+
with rasterio.open(path, "w", **meta) as dst:
|
|
30
|
+
dst.write(np.asarray(arr).astype(dtype), 1)
|
|
31
|
+
return Path(path)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def clean_bands(arrays, names, valid, drop_bands, circular_bands, near_constant_share):
|
|
35
|
+
"""The same cleaning for a list of (H, W, B) arrays with common band names: drop `drop_bands`, drop bands where one
|
|
36
|
+
value covers >= `near_constant_share` of the valid pixels (pooled over the arrays), replace `circular_bands` (degrees)
|
|
37
|
+
by their sine and cosine. Returns (arrays, names, log)."""
|
|
38
|
+
log = {"bands_in": len(names), "dropped": [], "near_constant": [], "circular": []}
|
|
39
|
+
low = [str(n).lower() for n in names]
|
|
40
|
+
keep = np.ones(len(names), dtype=bool)
|
|
41
|
+
for n in drop_bands:
|
|
42
|
+
if n.lower() in low:
|
|
43
|
+
keep[low.index(n.lower())] = False
|
|
44
|
+
log["dropped"].append(names[low.index(n.lower())])
|
|
45
|
+
for i in np.flatnonzero(keep):
|
|
46
|
+
v = np.concatenate([a[..., i][valid] for a in arrays])
|
|
47
|
+
v = v[np.isfinite(v)]
|
|
48
|
+
if v.size == 0 or np.unique(v, return_counts=True)[1].max() / v.size >= near_constant_share:
|
|
49
|
+
keep[i] = False
|
|
50
|
+
log["near_constant"].append(names[i])
|
|
51
|
+
out_names = [names[i] for i in np.flatnonzero(keep)]
|
|
52
|
+
out, nm = [], list(out_names)
|
|
53
|
+
for a in arrays:
|
|
54
|
+
cols = [a[..., i] for i in np.flatnonzero(keep)]
|
|
55
|
+
nm = list(out_names)
|
|
56
|
+
for n in circular_bands:
|
|
57
|
+
if n in nm:
|
|
58
|
+
j = nm.index(n)
|
|
59
|
+
rad = np.deg2rad(cols.pop(j)); nm.pop(j)
|
|
60
|
+
cols += [np.sin(rad), np.cos(rad)]; nm += [f"{n}_sin", f"{n}_cos"]
|
|
61
|
+
out.append(np.stack(cols, axis=-1).astype("float32"))
|
|
62
|
+
log["circular"] = [n for n in circular_bands if n in out_names]
|
|
63
|
+
return out, nm, log
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def align_bands(arr, names, wanted):
|
|
67
|
+
"""(H, W, B) bands of `arr` in the order `wanted` (matched by name, case-insensitive); `<band>_sin` / `<band>_cos`
|
|
68
|
+
are derived from `<band>` in degrees; absent bands are NaN. Returns (array, missing names)."""
|
|
69
|
+
low = {str(n).lower(): i for i, n in enumerate(names)}
|
|
70
|
+
out, missing = [], []
|
|
71
|
+
for w in wanted:
|
|
72
|
+
wl = str(w).lower()
|
|
73
|
+
if wl in low:
|
|
74
|
+
out.append(arr[..., low[wl]])
|
|
75
|
+
elif wl.endswith(("_sin", "_cos")) and wl[:-4] in low:
|
|
76
|
+
rad = np.deg2rad(arr[..., low[wl[:-4]]])
|
|
77
|
+
out.append(np.sin(rad) if wl.endswith("_sin") else np.cos(rad))
|
|
78
|
+
else:
|
|
79
|
+
out.append(np.full(arr.shape[:2], np.nan, dtype=np.float32)); missing.append(w)
|
|
80
|
+
return np.stack(out, axis=-1).astype(np.float32), missing
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Evaluation metrics (notebook section 1): accuracy, Cohen's kappa and class-wise precision, recall and F1, with the
|
|
2
|
+
threshold-free ROC-AUC and PR-AUC, and a block-bootstrap interval for kappa."""
|
|
3
|
+
import numpy as np
|
|
4
|
+
from sklearn.metrics import average_precision_score, roc_auc_score
|
|
5
|
+
|
|
6
|
+
from .config import THRESHOLD
|
|
7
|
+
|
|
8
|
+
MAIN_METRICS = ["Accuracy", "Kappa", "Precision_0", "Recall_0", "F1_0", "Precision_1", "Recall_1", "F1_1"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def metrics_from_counts(tn, fp, fn, tp):
|
|
12
|
+
"""Threshold metrics from confusion counts (vectorised)."""
|
|
13
|
+
tn, fp, fn, tp = (np.asarray(v, dtype=float) for v in (tn, fp, fn, tp))
|
|
14
|
+
n = tn + fp + fn + tp
|
|
15
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
16
|
+
rec1, rec0 = tp / (tp + fn), tn / (tn + fp)
|
|
17
|
+
pre1, pre0 = tp / (tp + fp), tn / (tn + fn)
|
|
18
|
+
f1_1, f1_0 = 2 * tp / (2 * tp + fp + fn), 2 * tn / (2 * tn + fn + fp)
|
|
19
|
+
po = (tp + tn) / n
|
|
20
|
+
pe = ((tp + fp) * (tp + fn) + (tn + fn) * (tn + fp)) / n ** 2
|
|
21
|
+
kappa = (po - pe) / (1 - pe)
|
|
22
|
+
iou1, iou0 = tp / (tp + fp + fn), tn / (tn + fn + fp)
|
|
23
|
+
return {"Accuracy": po, "Balanced_Acc": (rec0 + rec1) / 2,
|
|
24
|
+
"Precision_0": pre0, "Recall_0": rec0, "F1_0": f1_0, "Precision_1": pre1, "Recall_1": rec1, "F1_1": f1_1,
|
|
25
|
+
"Macro_Precision": (pre0 + pre1) / 2, "Macro_Recall": (rec0 + rec1) / 2, "Macro_F1": (f1_0 + f1_1) / 2,
|
|
26
|
+
"Kappa": kappa, "IoU_0": iou0, "IoU_1": iou1, "mIoU": (iou0 + iou1) / 2}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def kappa_se(tn, fp, fn, tp):
|
|
30
|
+
"""Large-sample SE of Cohen's kappa (Fleiss, Cohen and Everitt, 1969)."""
|
|
31
|
+
p = np.array([[tn, fp], [fn, tp]], dtype=float)
|
|
32
|
+
n = p.sum()
|
|
33
|
+
if n == 0:
|
|
34
|
+
return np.nan
|
|
35
|
+
p /= n
|
|
36
|
+
row, col = p.sum(1), p.sum(0)
|
|
37
|
+
po, pe = np.trace(p), float(row @ col)
|
|
38
|
+
if np.isclose(pe, 1.0):
|
|
39
|
+
return np.nan
|
|
40
|
+
k = (po - pe) / (1 - pe)
|
|
41
|
+
A = np.sum(np.diag(p) * (1 - (row + col) * (1 - k)) ** 2)
|
|
42
|
+
B = (1 - k) ** 2 * np.sum(p * (1 - np.eye(2)) * (col[None, :] + row[:, None]) ** 2)
|
|
43
|
+
var = (A + B - (k - pe * (1 - k)) ** 2) / (n * (1 - pe) ** 2)
|
|
44
|
+
return float(np.sqrt(var)) if var > 0 else (0.0 if var > -1e-12 else np.nan)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def evaluate(y, prob, threshold=THRESHOLD):
|
|
48
|
+
"""Scores of a calibrated probability against 0/1 labels (decision: prob >= threshold)."""
|
|
49
|
+
y, p = np.asarray(y).astype(int), np.asarray(prob, dtype=float)
|
|
50
|
+
pred = p >= threshold
|
|
51
|
+
tn, fp, fn, tp = (int(((y == a) & (pred == b)).sum()) for a, b in ((0, 0), (0, 1), (1, 0), (1, 1)))
|
|
52
|
+
m = {k: float(v) for k, v in metrics_from_counts(tn, fp, fn, tp).items()}
|
|
53
|
+
two = len(np.unique(y)) == 2
|
|
54
|
+
m.update(Kappa_SE=kappa_se(tn, fp, fn, tp),
|
|
55
|
+
ROC_AUC=roc_auc_score(y, p) if two else np.nan,
|
|
56
|
+
PR_AUC_1=average_precision_score(y, p) if two else np.nan,
|
|
57
|
+
PR_AUC_0=average_precision_score(1 - y, 1 - p) if two else np.nan,
|
|
58
|
+
Pred_Pos_Rate=float(pred.mean()), Ref_Pos_Rate=float(y.mean()), TN=tn, FP=fp, FN=fn, TP=tp, N=len(y))
|
|
59
|
+
return m
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def block_counts(y, pred, blocks):
|
|
63
|
+
"""TN, FP, FN, TP per block."""
|
|
64
|
+
ub, inv = np.unique(blocks, return_inverse=True)
|
|
65
|
+
out = np.zeros((len(ub), 4))
|
|
66
|
+
for j, cond in enumerate([(y == 0) & ~pred, (y == 0) & pred, (y == 1) & ~pred, (y == 1) & pred]):
|
|
67
|
+
out[:, j] = np.bincount(inv, weights=cond.astype(float), minlength=len(ub))
|
|
68
|
+
return ub, out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def block_bootstrap(y, prob, blocks, n_boot=2000, seed=42, threshold=THRESHOLD, metrics=("Kappa",)):
|
|
72
|
+
"""95% block-bootstrap interval (2.5th, 97.5th percentile) of each metric: blocks resampled with replacement."""
|
|
73
|
+
counts = block_counts(np.asarray(y).astype(int), np.asarray(prob) >= threshold, blocks)[1]
|
|
74
|
+
draws = np.random.default_rng(seed).integers(0, len(counts), size=(n_boot, len(counts)))
|
|
75
|
+
boot = metrics_from_counts(*counts[draws].sum(1).T)
|
|
76
|
+
return {m: tuple(np.nanpercentile(boot[m], [2.5, 97.5])) for m in metrics}
|