Metadata-Version: 2.5
Name: fractionalcover3
Version: 3.0.0rc1
Summary: Python package to produce land cover fractions from satellite imagery.
Project-URL: Homepage, https://gitlab.com/jrsrp/themes/cover/fractionalcover3
Project-URL: Documentation, https://jrsrp.gitlab.io/themes/cover/fractionalcover/
Author: Joint Remote Sensing Research Program
Maintainer-email: Robert Denham <robert.denham@uq.edu.au>
License-Expression: MIT
License-File: LICENSE.txt
Classifier: Development Status :: 4 - Beta
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python
Requires-Python: >=3.11
Requires-Dist: numpy
Provides-Extra: cli
Requires-Dist: eo-history[rasterio]>=0.2.5; extra == 'cli'
Requires-Dist: jrsrp-s2ard<0.3,>=0.2; extra == 'cli'
Requires-Dist: rasterio>=1.3.11; extra == 'cli'
Requires-Dist: rich>=13; extra == 'cli'
Requires-Dist: rio-cogeo>=5.4.2; extra == 'cli'
Requires-Dist: typer>=0.12.0; extra == 'cli'
Provides-Extra: cuda
Requires-Dist: keras>=3; extra == 'cuda'
Requires-Dist: tensorflow>=2.16; extra == 'cuda'
Requires-Dist: tensorflow[and-cuda]>=2.16; extra == 'cuda'
Provides-Extra: keras
Requires-Dist: keras>=3; extra == 'keras'
Requires-Dist: tensorflow>=2.16; extra == 'keras'
Description-Content-Type: text/markdown

# Fractionalcover version 3

Vegetation fractional cover package.


## Description

Vegetation fractional cover represents the exposed proportion of green, non-green, and bare cover within each pixel.
Landsat-scale ground cover information is important for soil erosion and nutrient flux estimates into the stream
network, as well as assessing the impact of human activities.

The fractional cover v3.0 model is a Multi Layer Perceptron (neural network) model architecture that uses surface
reflectance to estimate the three cover fractions of bare ground, photosynthetic vegetation (PV) and non-photosynthetic
vegetation (NPV). The MLP model was trained with Tensorflow using Landsat TM, ETM+ and OLI surface reflectance and
a collection of 4000 field observations of overstorey and ground cover. The field observations covered a wide
variety of vegetation, soil and climate types across Australia, collected between 1997 and 2018 following the
procedure outlined in:

Muir, J., Schmidt, M., Tindall, D., Trevithick, R., Scarth, P. and Stewart, J.B., 2011. _Field measurement of
fractional ground cover: a technical handbook supporting ground cover monitoring for Australia_.
Australian Bureau of Agricultural and Resource Economics and Sciences (ABARES): Canberra, Australia.



## Installation

The core package needs only [numpy](https://numpy.org/), which is installed
automatically:

```
python -m pip install fractionalcover3
```

This is all you need to use `unmix_fractional_cover` (see [Basic Usage](#basic-usage)).

To work with the models in [Keras](https://keras.io/), for example to build on
or retrain them, or to run your own models, install the `keras` extra (this
installs TensorFlow as the Keras backend), or the `cuda` extra for GPU support:

```
python -m pip install fractionalcover3[keras]
```

### Command line scripts

The package includes three scripts that produce fractional cover images as
Cloud Optimized GeoTIFFs, with processing history recorded in the metadata.
Their dependencies (`rasterio`, `rio-cogeo`, `typer`, `rich` and
`eo-history`) are provided by the `cli` extra. The rasterio wheels include GDAL,
so no system GDAL is needed:

```
python -m pip install fractionalcover3[cli]
```

- `fractionalcover_lsat.py INIMAGE OUTFILE` for JRSRP Landsat surface
  reflectance (stage dbg). Both 6 band TM/ETM+ and 7 band OLI images are
  supported; OLI reflectance is adjusted to look like ETM+ first.
- `fractionalcover_s2ard.py B03 B04 B08 B11 B12 OUTFILE` for JRSRP Sentinel-2
  ARD, given as separate band files. The 20m SWIR bands are resampled to
  10m, and the bands are adjusted to look like Landsat ETM+ using
  coefficients for each of Sentinel-2A, B and C. The satellite is worked out
  from the file name (`c[efg]msre_...`), or can be given with `--satellite`.
  The image is processed block by block, so memory use is small.
- `fractionalcover_s2l2a.py PRODUCT OUTFILE` for Sentinel-2 L2A products in
  SAFE format, either the zip file as downloaded or an unzipped `.SAFE`
  directory. The bands are read straight from the zip, and the satellite and
  reflectance scaling (including the offset added in processing baseline
  04.00) come from the product metadata. The reflectance is BRDF adjusted
  with the JRSRP gamma correction from
  [`jrsrp-s2ard`](https://pypi.org/project/jrsrp-s2ard/), using the sun and
  view angles in the product, so the result matches running `stac2ard` and
  then `fractionalcover_s2ard.py`. Processing is otherwise the same as
  `fractionalcover_s2ard.py`.

All take `--fc-model` to choose a bundled model by number (1-4), or a model
file (`.npz`, or `.keras` with the `keras` extra). Use `--help` for details.

The output has three bands (bare, green and dry), as percentages stored as
integers from 0 to 100, with 255 for no data.


## Basic Usage

The main function in the package is `unmix_fractional_cover`, which takes
a numpy 3d array for surface reflectance (scaled between 0 and 1), and
produces a 3d array of fractional cover. The output has 3 bands, one for
each bare, green and non-green components.

The unmixing uses a small neural network (multi layer perceptron), which is
evaluated directly with numpy, so no machine learning runtime is needed. The
model is supplied as a `fractionalcover3.model.MLPModel` object. With the
`keras` extra installed, `data.get_model(n, backend="keras")` gives the same
model as a `keras.Model`, which can also be passed to `unmix_fractional_cover`.
There are four models provided with the package,
each at varying levels of complexity. These can be selected by number, with 1
the simplest and 4 the most complex.

The simplest example might look like:

```python
from fractionalcover3.unmixcover import unmix_fractional_cover
from fractionalcover3 import data
import numpy as np

inref = np.array([562, 825, 1088, 2056, 2951, 2187]).reshape(6, 1, 1) * 0.0001

# use the default model provided
fractions = unmix_fractional_cover(inref, fc_model=data.get_model())
for i, fraction in enumerate(["bare", "green", "dry"]):
    print(fraction, fractions[i, 0, 0])
print("total", fractions.sum())
```

Output should be:

```python
bare 0.12142971
green 0.23126277
dry 0.64596075
total 0.99865323
```

## Migration from version 2.x

Version 3.0 introduces several breaking changes. If you're upgrading from version 2.x, review the following changes:

### Breaking Changes

1. **Python Version Requirement**: Now requires Python ≥3.11 (3.10 is end of life)
2. **Dependency Changes**:
   - **Core**: No TensorFlow Lite dependency (models run with plain numpy)
   - **CLI scripts**: Replaced GDAL+RIOS with `rasterio` (simplifies installation)
   - **CLI extra**: Now includes `eo-history`, `jrsrp-s2ard`, `rio-cogeo`, `typer`, `rich`
   - **Removed**: Private JRSRP package index and `rsc` extra (all dependencies public)
3. **Script Replacements**:
   - Old: `compute_fractionalcover.py` → New: `fractionalcover_lsat.py`
   - Old: `qv_fractionalcover_sentinel2.py` → New: `fractionalcover_s2ard.py` or `fractionalcover_s2l2a.py`
   - Removed: `compute_seasonalfcover.py` and `qv_seasonalfcover_sentinel2.py`
4. **Model Format Changes**:
   - Models are now `.npz` weights derived from `.keras` files
   - TensorFlow Lite models moved from package to `models/tflite/` in repository
   - `data.get_model()` returns numpy model by default (same results within float32 rounding)

### Migration Guide

#### API Changes
Code that only uses the core `unmix_fractional_cover` function remains compatible:

```python
# Still works unchanged:
from fractionalcover3.unmixcover import unmix_fractional_cover
from fractionalcover3 import data

fractions = unmix_fractional_cover(ref_data, fc_model=data.get_model())
```

In 2.x, `data.get_model()` returned a LiteRT `CompiledModel`. It now returns
a numpy `MLPModel`. Code that used the LiteRT model directly, or loaded a
`.tflite` file itself, needs updating:

```python
from fractionalcover3 import data

model = data.get_model()  # numpy model (default)
model = data.get_model(backend="keras")  # keras.Model, needs the "keras" extra
model = data.load_model("my_model.keras")  # your own .npz or .keras model
```

#### Script Migration
Replace command line usage:

```bash
# Old (version 2.x):
compute_fractionalcover.py -i input.img -o output.img

# New (version 3.0):
fractionalcover_lsat.py input.img output.tif
```

Sentinel-2 processing now has two options:

```bash
# For JRSRP Sentinel-2 ARD (separate band files):
fractionalcover_s2ard.py B03.tif B04.tif B08.tif B11.tif B12.tif output.tif

# For Sentinel-2 L2A SAFE products:
fractionalcover_s2l2a.py S2B_MSIL2A_20230101T012345_N0509_R123_T54HYD_20230101T023456.SAFE.zip output.tif
```

#### Installation Changes
Installation is simpler with rasterio (no separate GDAL needed):

```bash
# Version 3.0 (CLI installation):
python -m pip install fractionalcover3[cli]  # Includes rasterio with GDAL

# Compared to version 2.x (no longer needed):
# python -m pip install gdal[numpy]==$(gdal-config --version)
# python -m pip install git+https://github.com/ubarsc/rios@rios-2.1.1
```

### New Features
1. **Sentinel-2 ARD Support**: Direct processing from SAFE.ZIP with BRDF correction
2. **Cloud Optimized GeoTIFFs**: Output includes processing history metadata
3. **Block Processing**: Memory-efficient processing of large images
4. **Documentation**: Now uses MkDocs with Material theme

## Using the models outside Python

To run the models somewhere this package can't go, such as a mobile app or
an embedded device, LiteRT (formerly TensorFlow Lite) versions of the four
models are in [`models/tflite/`](https://gitlab.com/jrsrp/themes/cover/fractionalcover3/-/tree/master/models/tflite) in this repository. They are
not included in the Python package. They give the same results as the
bundled models (to within float32 rounding).

Each model takes a float32 array of shape `(n, 5)` and returns `(n, 3)`:

- **Input:** surface reflectance scaled between 0 and 1, for the green, red,
  NIR, SWIR1 and SWIR2 bands (Landsat ETM+ bands 2, 3, 4, 5 and 7), in that
  order. The blue band is not used. The models were fitted to Landsat
  TM/ETM+ reflectance, so other sensors (Landsat 8/9 OLI, Sentinel-2) should
  be adjusted to look like ETM+ first, as the scripts in this package do.
- **Output:** bare, green (photosynthetic) and dry (non-photosynthetic)
  fractions. These are not constrained, so values can fall outside 0 to 1
  and need not sum to 1. The scripts clip each fraction to between 0 and 2
  and then divide by the sum of the three.

The `.keras` files in `src/fractionalcover3/pkgdata/` are the source models.
To convert one (for example a retrained model) to LiteRT yourself, install the
`keras` extra and run:

```python
import keras
import tensorflow as tf

model = keras.models.load_model("fcModel_64x64x64.keras", compile=False)
converter = tf.lite.TFLiteConverter.from_keras_model(model)
with open("fcModel_64x64x64.tflite", "wb") as f:
    f.write(converter.convert())
```



## Development

This project uses [uv](https://docs.astral.sh/uv/). To run the full test
suite:

```
uv sync --extra cli --extra keras
uv run pytest
```

Tests for optional features are skipped if their extra is not installed.

The documentation is built with [MkDocs](https://www.mkdocs.org/). The home
page, changelog and licence pages include `README.md`, `CHANGELOG.md` and
`LICENSE.txt` directly, and the API reference is generated from the
docstrings (Google style). To preview it locally, or build it into `public/`:

```
uv run --group docs mkdocs serve
uv run --group docs mkdocs build --strict
```

## How to Cite this Package

You can cite this package using the DOI:

```
@misc{scarthp2022,
  title={JRSRP} {F}ractional {C}over 3.0,
  author={Peter Scarth, Robert Denham, Fiona Watson},
  year={2022},
  month={08},
  howpublished={\url{https://gitlab.com/jrsrp/themes/cover/fractionalcover3}},
  doi={10.5281/zenodo.7008343}
}
```
