scalecov 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.
- scalecov-0.1.0/.github/workflows/tests.yml +22 -0
- scalecov-0.1.0/.gitignore +11 -0
- scalecov-0.1.0/.readthedocs.yaml +12 -0
- scalecov-0.1.0/CHANGELOG.md +15 -0
- scalecov-0.1.0/CITATION.cff +19 -0
- scalecov-0.1.0/CONTRIBUTING.md +21 -0
- scalecov-0.1.0/LICENSE.txt +21 -0
- scalecov-0.1.0/PKG-INFO +134 -0
- scalecov-0.1.0/README.md +68 -0
- scalecov-0.1.0/docs/api.md +9 -0
- scalecov-0.1.0/docs/faq.md +13 -0
- scalecov-0.1.0/docs/index.md +22 -0
- scalecov-0.1.0/docs/installation.md +16 -0
- scalecov-0.1.0/docs/javascripts/mathjax.js +5 -0
- scalecov-0.1.0/docs/methods.md +37 -0
- scalecov-0.1.0/docs/settings.md +23 -0
- scalecov-0.1.0/docs/tutorial.md +44 -0
- scalecov-0.1.0/examples/barc/features.py +83 -0
- scalecov-0.1.0/examples/barc/get_data.py +57 -0
- scalecov-0.1.0/examples/barc/model.py +71 -0
- scalecov-0.1.0/examples/barc/prepare.py +131 -0
- scalecov-0.1.0/examples/barc/requirements.txt +7 -0
- scalecov-0.1.0/examples/barc/run_scalecov.py +66 -0
- scalecov-0.1.0/examples/barc/run_sensitivity.py +82 -0
- scalecov-0.1.0/examples/quickstart.py +32 -0
- scalecov-0.1.0/mkdocs.yml +29 -0
- scalecov-0.1.0/pyproject.toml +52 -0
- scalecov-0.1.0/src/scalecov/__init__.py +37 -0
- scalecov-0.1.0/src/scalecov/_version.py +3 -0
- scalecov-0.1.0/src/scalecov/aggregate_only.py +91 -0
- scalecov-0.1.0/src/scalecov/conformal.py +100 -0
- scalecov-0.1.0/src/scalecov/diagnostics.py +104 -0
- scalecov-0.1.0/src/scalecov/metrics.py +75 -0
- scalecov-0.1.0/src/scalecov/simulate.py +53 -0
- scalecov-0.1.0/src/scalecov/units.py +162 -0
- scalecov-0.1.0/src/scalecov/variogram.py +128 -0
- scalecov-0.1.0/tests/test_aggregate_only.py +44 -0
- scalecov-0.1.0/tests/test_conformal.py +62 -0
- scalecov-0.1.0/tests/test_diagnostics.py +35 -0
- scalecov-0.1.0/tests/test_metrics.py +38 -0
- scalecov-0.1.0/tests/test_simulate.py +20 -0
- scalecov-0.1.0/tests/test_units.py +77 -0
- scalecov-0.1.0/tests/test_variogram.py +46 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
name: tests
|
|
2
|
+
on:
|
|
3
|
+
push:
|
|
4
|
+
pull_request:
|
|
5
|
+
jobs:
|
|
6
|
+
test:
|
|
7
|
+
runs-on: ${{ matrix.os }}
|
|
8
|
+
strategy:
|
|
9
|
+
fail-fast: false
|
|
10
|
+
matrix:
|
|
11
|
+
os: [ubuntu-24.04, macos-latest, windows-latest]
|
|
12
|
+
python: ["3.9", "3.12"]
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v4
|
|
15
|
+
- uses: actions/setup-python@v5
|
|
16
|
+
with:
|
|
17
|
+
python-version: ${{ matrix.python }}
|
|
18
|
+
- run: python -m pip install --upgrade pip
|
|
19
|
+
- run: pip install -e ".[test]" ruff
|
|
20
|
+
- run: ruff check src tests examples
|
|
21
|
+
- run: pytest -q
|
|
22
|
+
- run: python examples/quickstart.py
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes are documented here. The project follows [Semantic Versioning](https://semver.org).
|
|
4
|
+
|
|
5
|
+
## [0.1.0] - 2026-11-12
|
|
6
|
+
|
|
7
|
+
First public release.
|
|
8
|
+
|
|
9
|
+
- `PixelConformal`: pixel intervals by hierarchical (grouped) conformal prediction, every calibration unit with equal weight.
|
|
10
|
+
- `UnitIntervals`: intervals for unit and group means with five constructions (`independent`, `full`, `variogram`, `variogram_re`, `direct`).
|
|
11
|
+
- `fit_within_unit_covariance`, `mean_error_variance`: within-unit exponential covariance with nugget and the variance of unit means it implies.
|
|
12
|
+
- `cross_calibrate`, `summarise`, `pixel_coverage_by_unit`: cross-fold calibration on out-of-fold residuals and coverage by scale.
|
|
13
|
+
- `kappa`, `unit_quantile`, `coverage_vs_kappa`, `k_dense_coverage`: pixel intervals when only aggregates or a few dense units are available.
|
|
14
|
+
- `r2_within`, `rho_within`, `r2_unit_means`, `block_bootstrap_r2_within`: skill inside units with block-bootstrap intervals.
|
|
15
|
+
- `simulate.nested_field`: simulated maps with group, unit, spatial and nugget error components.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
cff-version: 1.2.0
|
|
2
|
+
message: "If you use this software, please cite it as below."
|
|
3
|
+
title: "ScaleCov: calibrating and checking prediction intervals of spatial maps across nested scales"
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
date-released: "2026-11-12"
|
|
6
|
+
license: MIT
|
|
7
|
+
repository-code: "https://github.com/vubcfe/scalecov"
|
|
8
|
+
keywords: [conformal prediction, uncertainty quantification, spatial aggregation, change of support, remote sensing, map accuracy]
|
|
9
|
+
authors:
|
|
10
|
+
- family-names: Bui
|
|
11
|
+
given-names: Cao Vu
|
|
12
|
+
email: vubc@fe.edu.vn
|
|
13
|
+
affiliation: "Department of Artificial Intelligence, FPT University, Da Nang, Vietnam"
|
|
14
|
+
- family-names: Nguyen
|
|
15
|
+
given-names: Hoang-Anh-Vu
|
|
16
|
+
affiliation: "Department of Computer Fundamentals, FPT University, Da Nang, Vietnam"
|
|
17
|
+
- family-names: Nguyen
|
|
18
|
+
given-names: Van-Nam
|
|
19
|
+
affiliation: "Department of Software Engineering, FPT University, Da Nang, Vietnam"
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
Bug reports, questions and pull requests are welcome on the [issue tracker](https://github.com/vubcfe/scalecov/issues).
|
|
4
|
+
|
|
5
|
+
## Development setup
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
git clone https://github.com/vubcfe/scalecov && cd scalecov
|
|
9
|
+
pip install -e ".[dev]"
|
|
10
|
+
pytest # tests (offline, a few seconds)
|
|
11
|
+
ruff check src tests examples # style
|
|
12
|
+
mkdocs serve # documentation preview
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Guidelines
|
|
16
|
+
|
|
17
|
+
- Every new feature comes with a test. Prefer property tests on `scalecov.simulate`, where the correct answer is known (for example, a construction that must reach nominal coverage).
|
|
18
|
+
- Keep the package free of heavy dependencies: numpy, pandas and scipy only; plotting stays optional.
|
|
19
|
+
- Document user-visible changes in `CHANGELOG.md`.
|
|
20
|
+
- Start every source file with the SPDX licence header used in the existing files.
|
|
21
|
+
- Be respectful; we follow the [Contributor Covenant](https://www.contributor-covenant.org/version/2/1/code_of_conduct/).
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cao Vu Bui and the scalecov 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.
|
scalecov-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: scalecov
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: ScaleCov (coverage across scales): calibrate and check prediction intervals of spatial maps for pixels, units and groups of units
|
|
5
|
+
Project-URL: Homepage, https://github.com/vubcfe/scalecov
|
|
6
|
+
Project-URL: Documentation, https://scalecov.readthedocs.io
|
|
7
|
+
Project-URL: Issues, https://github.com/vubcfe/scalecov/issues
|
|
8
|
+
Author: Hoang-Anh-Vu Nguyen, Van-Nam Nguyen
|
|
9
|
+
Author-email: Cao Vu Bui <vubc@fe.edu.vn>
|
|
10
|
+
License: MIT License
|
|
11
|
+
|
|
12
|
+
Copyright (c) 2026 Cao Vu Bui and the scalecov contributors
|
|
13
|
+
|
|
14
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
15
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
16
|
+
in the Software without restriction, including without limitation the rights
|
|
17
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
18
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
19
|
+
furnished to do so, subject to the following conditions:
|
|
20
|
+
|
|
21
|
+
The above copyright notice and this permission notice shall be included in all
|
|
22
|
+
copies or substantial portions of the Software.
|
|
23
|
+
|
|
24
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
25
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
26
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
27
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
28
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
29
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
30
|
+
SOFTWARE.
|
|
31
|
+
License-File: LICENSE.txt
|
|
32
|
+
Keywords: change of support,conformal prediction,remote sensing,spatial aggregation,uncertainty
|
|
33
|
+
Classifier: Development Status :: 4 - Beta
|
|
34
|
+
Classifier: Intended Audience :: Science/Research
|
|
35
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
36
|
+
Classifier: Operating System :: OS Independent
|
|
37
|
+
Classifier: Programming Language :: Python :: 3
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
42
|
+
Classifier: Topic :: Scientific/Engineering :: GIS
|
|
43
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
44
|
+
Requires-Python: >=3.9
|
|
45
|
+
Requires-Dist: numpy>=1.22
|
|
46
|
+
Requires-Dist: pandas>=2.2
|
|
47
|
+
Requires-Dist: scipy>=1.8
|
|
48
|
+
Provides-Extra: dev
|
|
49
|
+
Requires-Dist: build; extra == 'dev'
|
|
50
|
+
Requires-Dist: matplotlib>=3.5; extra == 'dev'
|
|
51
|
+
Requires-Dist: mkdocs-material<10,>=9; extra == 'dev'
|
|
52
|
+
Requires-Dist: mkdocs<2,>=1.5; extra == 'dev'
|
|
53
|
+
Requires-Dist: mkdocstrings[python]>=0.24; extra == 'dev'
|
|
54
|
+
Requires-Dist: pytest>=7; extra == 'dev'
|
|
55
|
+
Requires-Dist: ruff>=0.4; extra == 'dev'
|
|
56
|
+
Requires-Dist: twine; extra == 'dev'
|
|
57
|
+
Provides-Extra: docs
|
|
58
|
+
Requires-Dist: mkdocs-material<10,>=9; extra == 'docs'
|
|
59
|
+
Requires-Dist: mkdocs<2,>=1.5; extra == 'docs'
|
|
60
|
+
Requires-Dist: mkdocstrings[python]>=0.24; extra == 'docs'
|
|
61
|
+
Provides-Extra: plot
|
|
62
|
+
Requires-Dist: matplotlib>=3.5; extra == 'plot'
|
|
63
|
+
Provides-Extra: test
|
|
64
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
65
|
+
Description-Content-Type: text/markdown
|
|
66
|
+
|
|
67
|
+
# ScaleCov
|
|
68
|
+
|
|
69
|
+
**ScaleCov** (coverage across scales) calibrates and checks prediction intervals of spatial maps across nested scales: pixels, units (for example fields or plots) and groups of units (for example farms or districts).
|
|
70
|
+
|
|
71
|
+
A map with valid pixel intervals does not automatically give valid intervals for the means of fields or farms, because pixel errors inside a unit share a common component. `scalecov` makes this checkable. It takes predictions, observations and the identifiers of nested units, and works with any model.
|
|
72
|
+
|
|
73
|
+
## Features
|
|
74
|
+
|
|
75
|
+
- **Pixel intervals:** hierarchical conformal prediction, in which every calibration unit has the same total weight.
|
|
76
|
+
- **Intervals for unit and group means**, with five constructions:
|
|
77
|
+
- `independent`: pixel errors treated as independent;
|
|
78
|
+
- `full`: pixel errors treated as fully correlated;
|
|
79
|
+
- `variogram`: a within-unit exponential covariance;
|
|
80
|
+
- `variogram_re`: the same plus a unit random effect;
|
|
81
|
+
- `direct`: conformal calibration at the scale of use.
|
|
82
|
+
- **Coverage diagnostics by scale**, with cross-fold calibration on out-of-fold residuals.
|
|
83
|
+
- **Calibration from aggregates only:**
|
|
84
|
+
- the ratio κ of pixel to unit-mean quantiles;
|
|
85
|
+
- the pixel coverage reached with a borrowed κ;
|
|
86
|
+
- calibration on a few densely measured units.
|
|
87
|
+
- **Skill inside units:** within-unit R² and Spearman correlation, with block-bootstrap intervals.
|
|
88
|
+
- **Simulated maps** with a known nested error structure, for testing and teaching.
|
|
89
|
+
|
|
90
|
+
`scalecov` depends only on numpy, pandas and scipy.
|
|
91
|
+
|
|
92
|
+
## Installation
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
pip install scalecov # after the first release
|
|
96
|
+
pip install -e ".[dev]" # from a clone, with test tools
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Quick start
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
import scalecov as sc
|
|
103
|
+
|
|
104
|
+
d = sc.simulate.nested_field(n_groups=200, units_per_group=3, sigma_group=0.4, sigma_unit=0.6, random_state=0)
|
|
105
|
+
d["fold"] = d.group % 5
|
|
106
|
+
|
|
107
|
+
res = sc.cross_calibrate(d, fold="fold", levels=["unit", "group"], alphas=(0.1,))
|
|
108
|
+
print(sc.summarise(res))
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
The input is one row per pixel, with these columns:
|
|
112
|
+
- the residual `error = observation - prediction`, out of fold;
|
|
113
|
+
- one column per nested level, finest first (here `unit`, then `group`);
|
|
114
|
+
- pixel coordinates `x` and `y`, needed only for the variogram constructions;
|
|
115
|
+
- the fold.
|
|
116
|
+
|
|
117
|
+
Folds should keep dependent units together: for example, all fields of a farm, or farms that share land.
|
|
118
|
+
|
|
119
|
+
In the simulated example, nominal 90 % intervals for unit means cover 13 % of units when pixel errors are treated as independent, 27 % with a within-unit variogram, and 90 % with direct calibration. For group means, adding a unit random effect is not enough (81 %), because units of a group share errors too. See [examples/quickstart.py](examples/quickstart.py).
|
|
120
|
+
|
|
121
|
+
## Notes on the constructions
|
|
122
|
+
|
|
123
|
+
- **`direct`** is the only construction that adapts to error shared at every level, because it is calibrated at that level. It needs only the unit aggregates (mean residuals of calibration units).
|
|
124
|
+
- **`variogram`** fits the covariance to residuals centred on their unit means. It cannot see an error shared by all pixels of a unit. When the correlation range is not small relative to the unit size, it is also biased low.
|
|
125
|
+
- **`variogram_re`** adds the unit-level variance that the within-unit covariance does not explain. It treats units of the same group as independent.
|
|
126
|
+
- **Conformal guarantees are marginal** over exchangeable calibration and test units. Cross-fold calibration is cross-conformal, so the finite-sample guarantee of split conformal prediction does not apply exactly. Always check coverage empirically, which is what this package is for.
|
|
127
|
+
|
|
128
|
+
## Citation
|
|
129
|
+
|
|
130
|
+
If you use ScaleCov, please cite the software (see `CITATION.cff`; DOI to be added on release).
|
|
131
|
+
|
|
132
|
+
## License
|
|
133
|
+
|
|
134
|
+
MIT
|
scalecov-0.1.0/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# ScaleCov
|
|
2
|
+
|
|
3
|
+
**ScaleCov** (coverage across scales) calibrates and checks prediction intervals of spatial maps across nested scales: pixels, units (for example fields or plots) and groups of units (for example farms or districts).
|
|
4
|
+
|
|
5
|
+
A map with valid pixel intervals does not automatically give valid intervals for the means of fields or farms, because pixel errors inside a unit share a common component. `scalecov` makes this checkable. It takes predictions, observations and the identifiers of nested units, and works with any model.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Pixel intervals:** hierarchical conformal prediction, in which every calibration unit has the same total weight.
|
|
10
|
+
- **Intervals for unit and group means**, with five constructions:
|
|
11
|
+
- `independent`: pixel errors treated as independent;
|
|
12
|
+
- `full`: pixel errors treated as fully correlated;
|
|
13
|
+
- `variogram`: a within-unit exponential covariance;
|
|
14
|
+
- `variogram_re`: the same plus a unit random effect;
|
|
15
|
+
- `direct`: conformal calibration at the scale of use.
|
|
16
|
+
- **Coverage diagnostics by scale**, with cross-fold calibration on out-of-fold residuals.
|
|
17
|
+
- **Calibration from aggregates only:**
|
|
18
|
+
- the ratio κ of pixel to unit-mean quantiles;
|
|
19
|
+
- the pixel coverage reached with a borrowed κ;
|
|
20
|
+
- calibration on a few densely measured units.
|
|
21
|
+
- **Skill inside units:** within-unit R² and Spearman correlation, with block-bootstrap intervals.
|
|
22
|
+
- **Simulated maps** with a known nested error structure, for testing and teaching.
|
|
23
|
+
|
|
24
|
+
`scalecov` depends only on numpy, pandas and scipy.
|
|
25
|
+
|
|
26
|
+
## Installation
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install scalecov # after the first release
|
|
30
|
+
pip install -e ".[dev]" # from a clone, with test tools
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Quick start
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import scalecov as sc
|
|
37
|
+
|
|
38
|
+
d = sc.simulate.nested_field(n_groups=200, units_per_group=3, sigma_group=0.4, sigma_unit=0.6, random_state=0)
|
|
39
|
+
d["fold"] = d.group % 5
|
|
40
|
+
|
|
41
|
+
res = sc.cross_calibrate(d, fold="fold", levels=["unit", "group"], alphas=(0.1,))
|
|
42
|
+
print(sc.summarise(res))
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The input is one row per pixel, with these columns:
|
|
46
|
+
- the residual `error = observation - prediction`, out of fold;
|
|
47
|
+
- one column per nested level, finest first (here `unit`, then `group`);
|
|
48
|
+
- pixel coordinates `x` and `y`, needed only for the variogram constructions;
|
|
49
|
+
- the fold.
|
|
50
|
+
|
|
51
|
+
Folds should keep dependent units together: for example, all fields of a farm, or farms that share land.
|
|
52
|
+
|
|
53
|
+
In the simulated example, nominal 90 % intervals for unit means cover 13 % of units when pixel errors are treated as independent, 27 % with a within-unit variogram, and 90 % with direct calibration. For group means, adding a unit random effect is not enough (81 %), because units of a group share errors too. See [examples/quickstart.py](examples/quickstart.py).
|
|
54
|
+
|
|
55
|
+
## Notes on the constructions
|
|
56
|
+
|
|
57
|
+
- **`direct`** is the only construction that adapts to error shared at every level, because it is calibrated at that level. It needs only the unit aggregates (mean residuals of calibration units).
|
|
58
|
+
- **`variogram`** fits the covariance to residuals centred on their unit means. It cannot see an error shared by all pixels of a unit. When the correlation range is not small relative to the unit size, it is also biased low.
|
|
59
|
+
- **`variogram_re`** adds the unit-level variance that the within-unit covariance does not explain. It treats units of the same group as independent.
|
|
60
|
+
- **Conformal guarantees are marginal** over exchangeable calibration and test units. Cross-fold calibration is cross-conformal, so the finite-sample guarantee of split conformal prediction does not apply exactly. Always check coverage empirically, which is what this package is for.
|
|
61
|
+
|
|
62
|
+
## Citation
|
|
63
|
+
|
|
64
|
+
If you use ScaleCov, please cite the software (see `CITATION.cff`; DOI to be added on release).
|
|
65
|
+
|
|
66
|
+
## License
|
|
67
|
+
|
|
68
|
+
MIT
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# FAQ
|
|
2
|
+
|
|
3
|
+
**Does ScaleCov fit a model?**
|
|
4
|
+
No. It works on residuals of any model. Residuals must be out of sample: produced by a model that did not see the pixel's unit, for example out-of-fold predictions.
|
|
5
|
+
|
|
6
|
+
**My units are polygons of different sizes. Is that a problem?**
|
|
7
|
+
No. Unit means are area weighted, every calibration unit has equal weight in the pixel quantile, and variances use each unit's own pixel geometry.
|
|
8
|
+
|
|
9
|
+
**Why does `variogram` under-cover even on my simulated data without shared errors?**
|
|
10
|
+
If the correlation range is comparable to the unit size, removing unit means hides part of the correlation. See [Recommended settings](settings.md).
|
|
11
|
+
|
|
12
|
+
**Can I use ScaleCov for non-agricultural maps?**
|
|
13
|
+
Yes. Nothing is specific to crops: any map of a continuous variable with nested units works, for example forest biomass by stand and district, or soil carbon by field and farm.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# ScaleCov
|
|
2
|
+
|
|
3
|
+
**ScaleCov** (coverage across scales) calibrates and checks prediction intervals of spatial maps for pixels, units (fields, plots, stands) and groups of units (farms, districts).
|
|
4
|
+
|
|
5
|
+
A map often comes with pixel intervals, while users need statements about field or farm means. Pixel errors inside a unit share a common component, so pixel intervals do not aggregate into valid unit intervals by themselves. ScaleCov makes this explicit:
|
|
6
|
+
|
|
7
|
+
- **calibrate** intervals at every level of a nested structure;
|
|
8
|
+
- **compare** the usual ways of aggregating pixel uncertainty;
|
|
9
|
+
- **check** coverage at each scale on held-out units.
|
|
10
|
+
|
|
11
|
+
It works with any model; the input is one row per pixel with an out-of-fold residual and the identifiers of the nested units.
|
|
12
|
+
|
|
13
|
+
| Problem in practice | What ScaleCov provides |
|
|
14
|
+
|---|---|
|
|
15
|
+
| Large units dominate pixel calibration | `PixelConformal`: every calibration unit has equal weight |
|
|
16
|
+
| Field means need intervals, but pixel errors are correlated | `UnitIntervals`: five constructions, from independent errors to direct calibration |
|
|
17
|
+
| It is unclear which construction is valid | `cross_calibrate` and `summarise`: coverage by level and method on held-out folds |
|
|
18
|
+
| Only aggregates are reported in the target region | `kappa`, `coverage_vs_kappa`, `k_dense_coverage` |
|
|
19
|
+
| Pixel or field scores hide whether a map has any within-field pattern | `r2_within`, `rho_within`, `block_bootstrap_r2_within` |
|
|
20
|
+
| A method needs testing where the answer is known | `simulate.nested_field` |
|
|
21
|
+
|
|
22
|
+
See the [Tutorial](tutorial.md) for a complete example and [Methods](methods.md) for the definitions.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Installation
|
|
2
|
+
|
|
3
|
+
```bash
|
|
4
|
+
pip install scalecov # after the first release
|
|
5
|
+
pip install "scalecov[plot]" # with matplotlib for plots
|
|
6
|
+
```
|
|
7
|
+
|
|
8
|
+
From source:
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
git clone https://github.com/vubcfe/scalecov && cd scalecov
|
|
12
|
+
pip install -e ".[dev]"
|
|
13
|
+
pytest
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Requirements: Python 3.9 or later, numpy, pandas 2.2 or later and scipy. Linux, macOS and Windows are supported. No compiled code is involved.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
window.MathJax = {
|
|
2
|
+
tex: { inlineMath: [["\\(", "\\)"]], displayMath: [["\\[", "\\]"]], processEscapes: true, processEnvironments: true },
|
|
3
|
+
options: { ignoreHtmlClass: ".*|", processHtmlClass: "arithmatex" }
|
|
4
|
+
};
|
|
5
|
+
document$.subscribe(() => { MathJax.typesetPromise(); });
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Methods
|
|
2
|
+
|
|
3
|
+
Notation: pixel residual $e_i = y_i - \hat y_i$; unit $u$ with $n_u$ pixels; group $g$; nominal miscoverage $\alpha$.
|
|
4
|
+
|
|
5
|
+
## Conformal quantile
|
|
6
|
+
|
|
7
|
+
Without weights, the half-width is the $\lceil (n+1)(1-\alpha) \rceil$-th smallest of the $n$ absolute calibration scores. It is infinite if this exceeds $n$. With weights $w_j$, it is the smallest score $r$ such that $\sum_{r_j \le r} w_j / (\sum_j w_j + \max_j w_j) \ge 1-\alpha$, which gives the test point the largest calibration weight.
|
|
8
|
+
|
|
9
|
+
`PixelConformal` weights each calibration pixel by $1/n_u$, so that every calibration unit has the same total weight (hierarchical or grouped conformal prediction). Its guarantee is marginal over exchangeable units. With cross-fold calibration (`cross_calibrate`), the residuals come from models fitted on other folds. The scheme is then cross-conformal, so coverage should be checked empirically, which this package does.
|
|
10
|
+
|
|
11
|
+
## Intervals for unit and group means
|
|
12
|
+
|
|
13
|
+
The error of a unit mean is $\bar e_u = n_u^{-1}\sum_{i\in u} e_i$. With $q$ the pixel conformal quantile and $z = \Phi^{-1}(1-\alpha/2)$:
|
|
14
|
+
|
|
15
|
+
| Method | Half-width for unit $u$ |
|
|
16
|
+
|---|---|
|
|
17
|
+
| `independent` | $q / \sqrt{n_u}$ |
|
|
18
|
+
| `full` | $q$ |
|
|
19
|
+
| `variogram` | $z\,\sqrt{V_u}$, with $V_u$ from the within-unit covariance |
|
|
20
|
+
| `variogram_re` | $z\,\sqrt{V_u + \sigma^2_U}$ |
|
|
21
|
+
| `direct` | conformal quantile of $\lvert\bar e_u\rvert$ over calibration units |
|
|
22
|
+
|
|
23
|
+
**Within-unit covariance.** $C(h) = s\,e^{-h/a}$ for $h>0$, and $C(0) = s + \tau^2$. It is fitted by least squares to binned products of residuals centred on their unit means, over pairs of pixels in the same unit. The sum $s + \tau^2$ equals the within-unit residual variance.
|
|
24
|
+
|
|
25
|
+
**Variance of a unit mean.** $V_u = \bar C_u + (C(0) - \bar C_u)/n_u$, where $\bar C_u$ is the mean covariance over distinct pixel pairs of $u$. For large units it is estimated on a random subsample.
|
|
26
|
+
|
|
27
|
+
**Unit random effect.** $\sigma^2_U = \max\{0,\ \overline{\bar e_u^2} - \overline{V_u}\}$ over calibration units. This is the variance of unit-mean errors that the within-unit covariance does not explain.
|
|
28
|
+
|
|
29
|
+
**Groups.** For a group, $\bar e_g = \sum_u w_u \bar e_u$ with area weights $w_u = n_u / \sum_{u\in g} n_u$. `variogram` and `variogram_re` use $\sum_u w_u^2 V_u$ and $\sum_u w_u^2 (V_u + \sigma^2_U)$, so they treat units of a group as independent. `direct` calibrates on group means.
|
|
30
|
+
|
|
31
|
+
## Calibration from aggregates
|
|
32
|
+
|
|
33
|
+
With aggregates only, $\bar e_u$ is observable, so $q_U$, the conformal quantile of $\lvert\bar e_u\rvert$, can be calibrated, but the pixel quantile $q$ cannot. $\kappa = q / q_U$ is estimated where dense data exist (`kappa`). The coverage that a borrowed $\kappa$ gives in a target region is read from `coverage_vs_kappa`. `k_dense_coverage` calibrates $q$ on $k$ randomly drawn dense units, repeatedly, and reports the spread of the resulting coverage.
|
|
34
|
+
|
|
35
|
+
## Skill inside units
|
|
36
|
+
|
|
37
|
+
$R^2_w = 1 - \sum_i [(y_i-\bar y_u)-(\hat y_i-\bar{\hat y}_u)]^2 / \sum_i (y_i-\bar y_u)^2$. It is unchanged when predictions are shifted per unit, for example to match a known aggregate. $\rho_w$ is the median over units of the within-unit Spearman correlation. `block_bootstrap_r2_within` resamples blocks of units with replacement and recomputes the pooled $R^2_w$.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Recommended settings
|
|
2
|
+
|
|
3
|
+
These are starting points, checked on simulated data with known answers and on harvester yield maps from four countries. Check them on your own data with `cross_calibrate`.
|
|
4
|
+
|
|
5
|
+
## Folds
|
|
6
|
+
|
|
7
|
+
Folds must keep dependent units together: all fields of a farm, and farms that share land. Otherwise calibration and test units are not exchangeable, and coverage looks better than it is.
|
|
8
|
+
|
|
9
|
+
## Which construction to use
|
|
10
|
+
|
|
11
|
+
- **Use `direct` at the scale at which an interval is used.** It is the only construction that adapts to error shared at every level, and it needs only the aggregates at that level. It needs at least $(1-\alpha)/\alpha$ calibration units at that level (9 for 90 % intervals); with fewer, its quantile is infinite.
|
|
12
|
+
- **Treat `independent` as a warning, not an interval.** With any error shared within units, it under-covers badly.
|
|
13
|
+
- **Use `variogram_re` with care for groups.** It is valid for unit means when the unit effect is the main shared error, but it under-covers group means when units of a group share errors.
|
|
14
|
+
- **Use `variogram` only when the correlation range is short relative to the unit size.** Removing unit means hides correlation at the scale of the unit, so the fitted range and the variance of unit means are biased low. This happens even when there is no shared unit error.
|
|
15
|
+
|
|
16
|
+
## Pixel intervals without dense data in the target
|
|
17
|
+
|
|
18
|
+
A borrowed $\kappa$ can give pixel intervals that cover much less than the nominal level when error structures differ between regions. A few dense calibration units are more reliable: compare the spread reported by `k_dense_coverage` for `k = 1, 5, 20`.
|
|
19
|
+
|
|
20
|
+
## Size and speed
|
|
21
|
+
|
|
22
|
+
- `max_per_unit=1000` pixels per calibration unit bounds memory, with little effect on the quantile.
|
|
23
|
+
- The covariance fit uses up to 300 pixels per unit (`max_pixels_per_unit`) and pairs up to `max_lag`. Set `max_lag` and `bin_width` in the units of your coordinates, for example 400 and 20 m for 10 m pixels.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Tutorial
|
|
2
|
+
|
|
3
|
+
The full script is [`examples/quickstart.py`](https://github.com/vubcfe/scalecov/blob/main/examples/quickstart.py); it runs in a few seconds.
|
|
4
|
+
|
|
5
|
+
## 1. Input
|
|
6
|
+
|
|
7
|
+
One row per pixel with:
|
|
8
|
+
- an **out-of-fold residual** (`error = observation - prediction`): the model that produced the prediction must not have seen the pixel's unit;
|
|
9
|
+
- one column per **nested level**, finest first (for example `field`, then `farm`);
|
|
10
|
+
- pixel **coordinates** in a metric unit (needed only for the variogram constructions);
|
|
11
|
+
- a **fold** column that keeps dependent units together, for example all fields of a farm.
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import scalecov as sc
|
|
15
|
+
|
|
16
|
+
d = sc.simulate.nested_field(n_groups=200, units_per_group=3, unit_shape=(12, 12), sigma_group=0.4,
|
|
17
|
+
sigma_unit=0.6, sigma_spatial=0.6, range_m=30.0, nugget=0.4, random_state=0)
|
|
18
|
+
d["fold"] = d.group % 5
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## 2. Coverage by scale
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
res = sc.cross_calibrate(d, fold="fold", levels=["unit", "group"], alphas=(0.1,))
|
|
25
|
+
print(sc.summarise(res))
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
For each fold, everything is calibrated on the other folds and evaluated on the fold itself. The summary gives, for the pixel level and for every unit level and construction, the coverage of nominal 90 % intervals and their mean width. In this example, independent pixel errors give about 13 % coverage for unit means and a within-unit variogram about 27 %, while direct calibration reaches about 90 %.
|
|
29
|
+
|
|
30
|
+
## 3. Only aggregates in the target region
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
cal, test = d[d.fold != 0], d[d.fold == 0]
|
|
34
|
+
k = sc.kappa(cal.error, cal.unit, alpha=0.1) # where dense data exist
|
|
35
|
+
q_unit = sc.unit_quantile(cal.error, cal.unit, alpha=0.1) # needs aggregates only
|
|
36
|
+
sc.coverage_vs_kappa(test.error, q_unit, [k["kappa"]]) # coverage with a borrowed kappa
|
|
37
|
+
sc.k_dense_coverage(cal.error, cal.unit, test.error, alpha=0.1, ks=(1, 5, 20))
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## 4. Skill inside units
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
r = sc.block_bootstrap_r2_within(d.truth, d.pred, d.unit, d.group)
|
|
44
|
+
```
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 Cao Vu Bui and the scalecov contributors
|
|
3
|
+
"""Monthly Sentinel-2 composites for every yield pixel, from the S2Cube cubes of each season.
|
|
4
|
+
|
|
5
|
+
For each harvest record of ``pixels.parquet`` (from ``prepare.py``) and the cube of its year, the
|
|
6
|
+
median reflectance of clear observations (Scene Classification Layer 4 vegetation or 5 bare soil) is
|
|
7
|
+
computed per month from April to November, for the ten bands and NDVI. Pixel coordinates are used only
|
|
8
|
+
to find the pixel in the cube; they are not features.
|
|
9
|
+
|
|
10
|
+
python features.py --data data --cubes data/s2 --out data/features.parquet
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import pathlib
|
|
16
|
+
|
|
17
|
+
import h5py
|
|
18
|
+
import numpy as np
|
|
19
|
+
import pandas as pd
|
|
20
|
+
|
|
21
|
+
MONTHS = range(4, 12)
|
|
22
|
+
CLEAR = (4, 5)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def site_features(f: h5py.File, sid: str, months: np.ndarray, bands: list[str]):
|
|
26
|
+
"""(H, W, n_features) monthly medians and the grid origin of one site."""
|
|
27
|
+
g = f["sites"][sid]
|
|
28
|
+
X = g["X"][()].astype(np.float32) / 10000.0 # (T, B, H, W)
|
|
29
|
+
scl = g["SCL"][()]
|
|
30
|
+
ok = np.isin(scl, CLEAR) & (X.min(axis=1) > 0) # (T, H, W)
|
|
31
|
+
b4, b8 = bands.index("B04"), bands.index("B08")
|
|
32
|
+
ndvi = (X[:, b8] - X[:, b4]) / np.maximum(X[:, b8] + X[:, b4], 1e-6)
|
|
33
|
+
stack = np.concatenate([X, ndvi[:, None]], axis=1) # (T, B+1, H, W)
|
|
34
|
+
stack = np.where(ok[:, None], stack, np.nan)
|
|
35
|
+
feats = []
|
|
36
|
+
for m in MONTHS:
|
|
37
|
+
sel = months == m
|
|
38
|
+
with np.errstate(all="ignore"):
|
|
39
|
+
feats.append(np.nanmedian(stack[sel], axis=0) if sel.any() else np.full(stack.shape[1:], np.nan))
|
|
40
|
+
F = np.stack(feats, 0) # (M, B+1, H, W)
|
|
41
|
+
F = F.reshape(-1, *F.shape[2:]).transpose(1, 2, 0) # (H, W, M*(B+1))
|
|
42
|
+
return F, float(g.attrs["x0"]), float(g.attrs["y1"]), float(g.attrs["res_m"])
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main():
|
|
46
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
47
|
+
ap.add_argument("--data", default="data")
|
|
48
|
+
ap.add_argument("--cubes", default="data/s2")
|
|
49
|
+
ap.add_argument("--out", default="data/features.parquet")
|
|
50
|
+
a = ap.parse_args()
|
|
51
|
+
pix = pd.read_parquet(pathlib.Path(a.data) / "pixels.parquet")
|
|
52
|
+
out = []
|
|
53
|
+
for year, py in pix.groupby("year"):
|
|
54
|
+
path = pathlib.Path(a.cubes) / f"cube_{year}.h5"
|
|
55
|
+
if not path.exists():
|
|
56
|
+
print(f"{year}: no cube, skipped")
|
|
57
|
+
continue
|
|
58
|
+
with h5py.File(path, "r") as f:
|
|
59
|
+
b = f.attrs["bands"]
|
|
60
|
+
bands = b.split(",") if isinstance(b, str) else [x.decode() if isinstance(x, bytes) else x for x in b]
|
|
61
|
+
dates = pd.to_datetime([d.decode() for d in f["dates"][()]])
|
|
62
|
+
months = dates.month.to_numpy()
|
|
63
|
+
names = [f"{b}_m{m:02d}" for m in MONTHS for b in [*bands, "NDVI"]]
|
|
64
|
+
for field, pf in py.groupby("field"):
|
|
65
|
+
sid = field.replace(" ", "_")
|
|
66
|
+
if sid not in f["sites"]:
|
|
67
|
+
print(f"{year} {field}: no site, skipped")
|
|
68
|
+
continue
|
|
69
|
+
F, x0, y1, res = site_features(f, sid, months, bands)
|
|
70
|
+
c = np.round((pf.x.to_numpy() - x0) / res - 0.5).astype(int)
|
|
71
|
+
r = np.round((y1 - pf.y.to_numpy()) / res - 0.5).astype(int)
|
|
72
|
+
inside = (r >= 0) & (r < F.shape[0]) & (c >= 0) & (c < F.shape[1])
|
|
73
|
+
vals = np.full((len(pf), F.shape[2]), np.nan, np.float32)
|
|
74
|
+
vals[inside] = F[r[inside], c[inside]]
|
|
75
|
+
out.append(pd.concat([pf.reset_index(drop=True), pd.DataFrame(vals, columns=names)], axis=1))
|
|
76
|
+
print(f"{year}: done")
|
|
77
|
+
res = pd.concat(out, ignore_index=True)
|
|
78
|
+
res.to_parquet(a.out, index=False)
|
|
79
|
+
print(len(res), "pixels,", res.filter(like="_m").shape[1], "features")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
if __name__ == "__main__":
|
|
83
|
+
main()
|