Skip to content

fluxmapPy           alt text

fluxmapPy is a python package that allows users to easily analyze FluxMaps. FluxMaps are spatialized eddy covariance rasters developed by AtmoFacts. fluxmapPy allows for users to visualize single bands of FluxMap rasters, filter out FluxMap raster pixels using a quality threshold, and compute diurnal cycles and spatial statistics for whole raster or within specific polygons.

While there are multiple functions that allow for the analysis of FluxMaps, fluxmapPy offers 4 main wrapper functions that are described below. Additional functions that make up the wrapper functions, can be located in the API Reference tab.

*Disclaimer - fluxmapPy is in early stages (0.6.0), so function names may change before the 1.0.0 release. Function name changes could break code.




fluxmapPy tutorial:

Contributing:




fluxmapPy License

Copyright (c) 2026 AtmoFacts, LLC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.




wrap_open_fm(raster_path,     qf_path = None,    band = 0,    qf_thsh = 4,    qf_keep = 'lte'):

Open one band of a FluxMap with low-quality pixels masked out.

Reads a single band from a measurement raster, applies the matching quality-flag raster, and returns the masked band together with its spatial metadata, ready for plotting.

Parameters:

Name Type Description Default
raster_path str or Path

Measurement FluxMap raster to open.

required
band int

Which band to read, 1-based: band 1 is midnight, band 48 the final half-hour of the day.

required
qf_thsh float

Quality-flag threshold. Flags run 0-5, where 0 carries the least uncertainty.

4
qf_keep (lte, gte)

Which side of the threshold to keep. "lte" keeps pixels at or below qf_thsh; "gte" keeps those at or above it.

"lte"
qf_path str or Path

Quality-flag raster. When None (default) it is located alongside raster_path by naming convention.

None

Returns:

Type Description
OpenedFluxMap

With data (the masked 2-D band), band, description, profile, tags, record and quality_path, plus the qf_threshold and qf_keep that were applied.

Raises:

Type Description
ValueError

If band is not a positive 1-based integer, if it exceeds the band count of the raster, or if the measurement and quality rasters do not share the same grid.

See Also

wrap_filt_qf : Filter a whole directory of FluxMaps at once.

Examples:

Bands are numbered from 1, so band 0 is rejected before any file is read:

>>> wrap_open_fm("KONA/fluxCo2_20260101.tif", band=0)
Traceback (most recent call last):
    ...
ValueError: band must be a positive 1-based integer

Opening a real FluxMap requires the raster on disk, so this is shown rather than executed:

>>> fluxmap = wrap_open_fm(
...     "KONA/fluxCo2_20260101.tif", band=20, qf_thsh=1
... )
>>> fluxmap.data.shape
(64, 64)
Source code in src/fluxmappy/wrap_open_fm.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def wrap_open_fm(
    raster_path: str | Path,
    band: int,
    *,
    qf_thsh: float = 4,
    qf_keep: str = "lte",
    qf_path: str | Path | None = None,
) -> OpenedFluxMap:
    """Open one band of a FluxMap with low-quality pixels masked out.

    Reads a single band from a measurement raster, applies the matching
    quality-flag raster, and returns the masked band together with its
    spatial metadata, ready for plotting.

    Parameters
    ----------
    raster_path : str or pathlib.Path
        Measurement FluxMap raster to open.
    band : int
        Which band to read, **1-based**: band 1 is midnight, band 48 the
        final half-hour of the day.
    qf_thsh : float, default 4
        Quality-flag threshold. Flags run 0-5, where 0 carries the least
        uncertainty.
    qf_keep : {"lte", "gte"}, default "lte"
        Which side of the threshold to keep. ``"lte"`` keeps pixels at or
        below ``qf_thsh``; ``"gte"`` keeps those at or above it.
    qf_path : str or pathlib.Path, optional
        Quality-flag raster. When ``None`` (default) it is located
        alongside ``raster_path`` by naming convention.

    Returns
    -------
    OpenedFluxMap
        With ``data`` (the masked 2-D band), ``band``, ``description``,
        ``profile``, ``tags``, ``record`` and ``quality_path``, plus the
        ``qf_threshold`` and ``qf_keep`` that were applied.

    Raises
    ------
    ValueError
        If ``band`` is not a positive 1-based integer, if it exceeds the
        band count of the raster, or if the measurement and quality
        rasters do not share the same grid.

    See Also
    --------
    wrap_filt_qf : Filter a whole directory of FluxMaps at once.

    Examples
    --------
    Bands are numbered from 1, so band 0 is rejected before any file is
    read:

    >>> wrap_open_fm("KONA/fluxCo2_20260101.tif", band=0)
    Traceback (most recent call last):
        ...
    ValueError: band must be a positive 1-based integer

    Opening a real FluxMap requires the raster on disk, so this is shown
    rather than executed:

    >>> fluxmap = wrap_open_fm(
    ...     "KONA/fluxCo2_20260101.tif", band=20, qf_thsh=1
    ... )  # doctest: +SKIP
    >>> fluxmap.data.shape  # doctest: +SKIP
    (64, 64)
    """
    if isinstance(band, bool) or not isinstance(band, int) or band < 1:
        raise ValueError("band must be a positive 1-based integer")

    measurement_path, resolved_quality_path = resolve_quality_path(
        raster_path,
        qf_path,
    )
    record = parse_raster_path(measurement_path)
    assert record is not None

    with rasterio.open(measurement_path) as measurement_src:
        if band > measurement_src.count:
            raise ValueError(
                f"Band {band} does not exist in {measurement_path}; "
                f"available bands are 1-{measurement_src.count}"
            )

        measurement_data = np.ma.masked_invalid(
            measurement_src.read(band, masked=True).astype("float32")
        )
        profile = measurement_src.profile.copy()
        profile.update(count=1)
        description = measurement_src.descriptions[band - 1]
        tags = measurement_src.tags(band).copy()

        with rasterio.open(resolved_quality_path) as quality_src:
            assert_same_grid(
                measurement_path=measurement_path,
                measurement_profile=measurement_src.profile,
                quality_path=resolved_quality_path,
                quality_profile=quality_src.profile,
            )
            if quality_src.count == 1:
                quality_band = 1
            elif quality_src.count == measurement_src.count:
                quality_band = band
            else:
                raise ValueError(
                    "Quality raster band count must be 1 or match the "
                    "measurement raster band count."
                )

            quality_data = quality_src.read(quality_band, masked=True)
            passes = quality_pass_mask(
                quality_data=quality_data[np.newaxis, ...],
                measurement_shape=(1, *measurement_data.shape),
                qf_threshold=qf_thsh,
                qf_keep=qf_keep,
            )[0]

    return OpenedFluxMap(
        record=record,
        quality_path=resolved_quality_path,
        band=band,
        data=np.ma.masked_where(~passes, measurement_data),
        profile=profile,
        description=description,
        tags=tags,
        qf_threshold=qf_thsh,
        qf_keep=qf_keep,
    )




wrap_filt_qf(data,     flux = 'fluxCo2',    qf_thsh = 4,    qf_keep = 'lte'):

Yield FluxMaps with low-quality pixels masked out.

Scans data for measurement and quality-flag raster pairs, masks every pixel whose quality flag fails the threshold, and yields the results one day at a time without writing any files.

Parameters:

Name Type Description Default
data str or Path

Directory holding both the measurement rasters and their quality-flag rasters.

required
flux str

Flux type to read. "fluxCo2" for carbon flux, "fluxTempEngy" for sensible heat, "fluxH2oEngy" for latent heat.

"fluxTempEngy"
qf_thsh float

Quality-flag threshold. Flags run 0-5, where 0 carries the least uncertainty.

1
qf_keep ('lte', 'gte')

Which side of the threshold to keep. "lte" keeps pixels at or below qf_thsh; "gte" keeps those at or above it.

"lte"
limit int

Stop after this many raster pairs. None (default) processes every pair found.

None

Yields:

Type Description
FilteredFluxRaster

One per measurement/quality pair, carrying the masked bands and the originating record.

Raises:

Type Description
ValueError

If data holds no matching raster pairs, or if a measurement raster and its quality raster do not share the same grid.

See Also

wrap_diu : Diurnal cycles from these rasters. wrap_stat : Spatial statistics from these rasters.

Examples:

The defaults are exposed as module constants:

>>> DEFAULT_FLUX_TYPE
'fluxTempEngy'
>>> DEFAULT_QF_THRESHOLD
1
>>> DEFAULT_QF_KEEP
'lte'

Filtering a directory of FluxMaps requires raster files on disk, so the call below is shown rather than executed:

>>> filtered = wrap_filt_qf(
...     "KONA", flux="fluxCo2", qf_thsh=1, qf_keep="lte"
... )
>>> cycles = wrap_diu(filtered, out_tz="America/Chicago")
Source code in src/fluxmappy/wrap_filt_qf.py
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def wrap_filt_qf(
    data: str | Path,
    flux: str = DEFAULT_FLUX_TYPE,
    qf_thsh: float = DEFAULT_QF_THRESHOLD,
    qf_keep: str = DEFAULT_QF_KEEP,
    limit: int | None = None,
) -> Iterator[FilteredFluxRaster]:
    """Yield FluxMaps with low-quality pixels masked out.

    Scans ``data`` for measurement and quality-flag raster pairs, masks
    every pixel whose quality flag fails the threshold, and yields the
    results one day at a time without writing any files.

    Parameters
    ----------
    data : str or pathlib.Path
        Directory holding both the measurement rasters and their
        quality-flag rasters.
    flux : str, default "fluxTempEngy"
        Flux type to read. ``"fluxCo2"`` for carbon flux,
        ``"fluxTempEngy"`` for sensible heat, ``"fluxH2oEngy"`` for
        latent heat.
    qf_thsh : float, default 1
        Quality-flag threshold. Flags run 0-5, where 0 carries the least
        uncertainty.
    qf_keep : {"lte", "gte"}, default "lte"
        Which side of the threshold to keep. ``"lte"`` keeps pixels at or
        below ``qf_thsh``; ``"gte"`` keeps those at or above it.
    limit : int, optional
        Stop after this many raster pairs. ``None`` (default) processes
        every pair found.

    Yields
    ------
    FilteredFluxRaster
        One per measurement/quality pair, carrying the masked bands and
        the originating record.

    Raises
    ------
    ValueError
        If ``data`` holds no matching raster pairs, or if a measurement
        raster and its quality raster do not share the same grid.

    See Also
    --------
    wrap_diu : Diurnal cycles from these rasters.
    wrap_stat : Spatial statistics from these rasters.

    Examples
    --------
    The defaults are exposed as module constants:

    >>> DEFAULT_FLUX_TYPE
    'fluxTempEngy'
    >>> DEFAULT_QF_THRESHOLD
    1
    >>> DEFAULT_QF_KEEP
    'lte'

    Filtering a directory of FluxMaps requires raster files on disk, so
    the call below is shown rather than executed:

    >>> filtered = wrap_filt_qf(
    ...     "KONA", flux="fluxCo2", qf_thsh=1, qf_keep="lte"
    ... )  # doctest: +SKIP
    >>> cycles = wrap_diu(filtered, out_tz="America/Chicago")  # doctest: +SKIP
    """
    pairs = find_raster_pairs(data_dir=Path(data), flux_type=flux)
    if limit is not None:
        pairs = pairs[:limit]

    for pair in pairs:
        yield filter_raster_pair(
            pair=pair,
            qf_threshold=qf_thsh,
            qf_keep=qf_keep,
        )




wrap_diu(filtered_rasters,     vector = None,    in_tz = 'UTC',     out_tz = 'None'):

Return mean and cumulative diurnal cycles for polygons or rasters.

Groups quality-filtered rasters by region, site and flux type, converts each day's 48 half-hourly spatial means into the requested timezone, and averages them into one diurnal cycle per region.

Parameters:

Name Type Description Default
filtered_rasters iterable of FilteredFluxRaster

Quality-filtered rasters, typically the output of :func:~fluxmappy.wrap_filt_qf. Each supplies 48 half-hourly bands for one day, with band 1 at midnight in in_tz.

required
vector str or Path

Polygon vector file to summarise within. When None (default) each raster is summarised as a whole.

None
id_field str

Vector attribute identifying each polygon. When None the feature index is used.

None
all_touched bool

Include every pixel touched by a polygon, not only those whose centre falls inside it.

False
timestep_seconds float

Seconds represented by each slot, used to scale the cumulative cycle. None leaves the cumulative sum unscaled. Half-hourly FluxMaps use 1800.

None
in_tz str

Timezone in which band 1 of each source raster is midnight.

"UTC"
out_tz str

Timezone to convert into before daily cycles are averaged. None keeps the cycles in in_tz.

None
incomplete_local_days (drop, include, error)

How to treat local days left partially covered once out_tz has shifted the source days. "drop" discards them, "include" keeps them, "error" raises.

"drop"

Returns:

Type Description
list of PolygonDiurnalCycle

One entry per (feature_id, site, flux_type) group. Each holds mean_cycle, standard_deviation, valid_day_count and cumulative_cycle as 48-element arrays, alongside the contributing dates and the resulting timezone.

Raises:

Type Description
ValueError

If incomplete_local_days is not one of the three accepted values, if a timezone name cannot be resolved, or if no statistics were available to aggregate.

See Also

wrap_filt_qf : Produce the filtered rasters this function consumes. wrap_stat : Spatial statistics for the same rasters.

Notes

standard_deviation measures variability across days at each half-hour slot, not variability across pixels. For spatial spread within a region, use :func:~fluxmappy.wrap_stat.

Examples:

Two days of synthetic single-pixel rasters, summarised whole:

>>> import numpy as np
>>> rasters = [_example_raster(d) for d in ("20260101", "20260102")]
>>> cycles = wrap_diu(rasters)
>>> len(cycles)
1
>>> cycle = cycles[0]
>>> cycle.timezone
'UTC'
>>> cycle.dates
('20260101', '20260102')
>>> cycle.mean_cycle[:4]
array([0., 1., 2., 3.])
>>> cycle.valid_day_count[:4]
array([2, 2, 2, 2])

Scaling the cumulative cycle by the half-hourly timestep:

>>> cycles = wrap_diu(rasters, timestep_seconds=1800.0)
>>> cycles[0].cumulative_cycle[:4]
array([    0.,  1800.,  5400., 10800.])

Converting to a local timezone before averaging:

>>> dates = ("20260101", "20260102", "20260103")
>>> cycles = wrap_diu(
...     [_example_raster(d) for d in dates],
...     out_tz="America/Chicago",
... )
>>> cycles[0].timezone
'America/Chicago'
Source code in src/fluxmappy/wrap_diu.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def wrap_diu(
    filtered_rasters: Iterable[FilteredFluxRasterLike],
    vector: str | Path | None = None,
    id_field: str | None = None,
    all_touched: bool = False,
    timestep_seconds: float | None = None,
    in_tz: str = "UTC",
    out_tz: str | None = None,
    incomplete_local_days: str = "drop",
) -> list[PolygonDiurnalCycle]:
    """Return mean and cumulative diurnal cycles for polygons or rasters.

    Groups quality-filtered rasters by region, site and flux type,
    converts each day's 48 half-hourly spatial means into the requested
    timezone, and averages them into one diurnal cycle per region.

    Parameters
    ----------
    filtered_rasters : iterable of FilteredFluxRaster
        Quality-filtered rasters, typically the output of
        :func:`~fluxmappy.wrap_filt_qf`. Each supplies 48 half-hourly
        bands for one day, with band 1 at midnight in ``in_tz``.
    vector : str or pathlib.Path, optional
        Polygon vector file to summarise within. When ``None`` (default)
        each raster is summarised as a whole.
    id_field : str, optional
        Vector attribute identifying each polygon. When ``None`` the
        feature index is used.
    all_touched : bool, default False
        Include every pixel touched by a polygon, not only those whose
        centre falls inside it.
    timestep_seconds : float, optional
        Seconds represented by each slot, used to scale the cumulative
        cycle. ``None`` leaves the cumulative sum unscaled. Half-hourly
        FluxMaps use ``1800``.
    in_tz : str, default "UTC"
        Timezone in which band 1 of each source raster is midnight.
    out_tz : str, optional
        Timezone to convert into before daily cycles are averaged.
        ``None`` keeps the cycles in ``in_tz``.
    incomplete_local_days : {"drop", "include", "error"}, default "drop"
        How to treat local days left partially covered once ``out_tz`` has
        shifted the source days. ``"drop"`` discards them, ``"include"``
        keeps them, ``"error"`` raises.

    Returns
    -------
    list of PolygonDiurnalCycle
        One entry per ``(feature_id, site, flux_type)`` group. Each holds
        ``mean_cycle``, ``standard_deviation``, ``valid_day_count`` and
        ``cumulative_cycle`` as 48-element arrays, alongside the
        contributing ``dates`` and the resulting ``timezone``.

    Raises
    ------
    ValueError
        If ``incomplete_local_days`` is not one of the three accepted
        values, if a timezone name cannot be resolved, or if no statistics
        were available to aggregate.

    See Also
    --------
    wrap_filt_qf : Produce the filtered rasters this function consumes.
    wrap_stat : Spatial statistics for the same rasters.

    Notes
    -----
    ``standard_deviation`` measures variability *across days* at each
    half-hour slot, not variability across pixels. For spatial spread
    within a region, use :func:`~fluxmappy.wrap_stat`.

    Examples
    --------
    Two days of synthetic single-pixel rasters, summarised whole:

    >>> import numpy as np
    >>> rasters = [_example_raster(d) for d in ("20260101", "20260102")]
    >>> cycles = wrap_diu(rasters)
    >>> len(cycles)
    1
    >>> cycle = cycles[0]
    >>> cycle.timezone
    'UTC'
    >>> cycle.dates
    ('20260101', '20260102')
    >>> cycle.mean_cycle[:4]
    array([0., 1., 2., 3.])
    >>> cycle.valid_day_count[:4]
    array([2, 2, 2, 2])

    Scaling the cumulative cycle by the half-hourly timestep:

    >>> cycles = wrap_diu(rasters, timestep_seconds=1800.0)
    >>> cycles[0].cumulative_cycle[:4]
    array([    0.,  1800.,  5400., 10800.])

    Converting to a local timezone before averaging:

    >>> dates = ("20260101", "20260102", "20260103")
    >>> cycles = wrap_diu(
    ...     [_example_raster(d) for d in dates],
    ...     out_tz="America/Chicago",
    ... )
    >>> cycles[0].timezone
    'America/Chicago'
    """
    if incomplete_local_days not in {"drop", "include", "error"}:
        raise ValueError(
            "incomplete_local_days must be 'drop', 'include', or 'error'"
        )

    source_timezone = resolve_timezone(in_tz, "in_tz")
    target_timezone = (
        None
        if out_tz is None
        else resolve_timezone(out_tz, "out_tz")
    )
    result_timezone = out_tz or in_tz
    resolved_path = None if vector is None else Path(vector)
    grouped = collect_dated_cycles(
        filtered_rasters,
        resolved_path,
        id_field,
        all_touched,
    )

    results: list[PolygonDiurnalCycle] = []
    for (feature_id, site, flux_type), group in grouped.items():
        dated_cycles = group["dated_cycles"]
        assert isinstance(dated_cycles, list)
        dated_cycles.sort(key=lambda item: item[0])

        if target_timezone is None:
            dates = tuple(date for date, _ in dated_cycles)
            daily_cycles = np.vstack(
                [values for _, values in dated_cycles]
            ).astype(float)
        else:
            dates, daily_cycles = localize_daily_cycles(
                dated_cycles,
                source_timezone,
                target_timezone,
                incomplete_local_days,
            )

        (
            mean_cycle,
            standard_deviation,
            valid_day_count,
            cumulative_cycle,
        ) = summarize_daily_cycles(daily_cycles, timestep_seconds)
        properties = group["properties"]
        assert isinstance(properties, dict)
        results.append(
            PolygonDiurnalCycle(
                feature_id=feature_id,
                properties=properties.copy(),
                site=site,
                flux_type=flux_type,
                dates=dates,
                daily_cycles=daily_cycles,
                mean_cycle=mean_cycle,
                standard_deviation=standard_deviation,
                valid_day_count=valid_day_count,
                cumulative_cycle=cumulative_cycle,
                timestep_seconds=timestep_seconds,
                timezone=result_timezone,
            )
        )
    return results




wrap_stat(filtered_rasters,     vector = None,    product = 'Daily')

Return spatial statistics for whole FluxMaps or polygons within them.

Reads quality-filtered FluxMaps and computes pixel statistics across each raster, or within each polygon of a vector file when one is supplied.

Parameters:

Name Type Description Default
filtered_rasters iterable of FilteredFluxRaster

Quality-filtered rasters, typically the output of :func:~fluxmappy.wrap_filt_qf.

required
vector str or Path

Polygon vector file to summarise within. When None (default) each raster is summarised as a whole.

None
product (half - hourly, daily)

Temporal resolution of the statistics. "half-hourly" returns 48-element arrays, one value per band. "daily" averages the bands into a single daily layer first and returns scalars.

"half-hourly"
id_field str

Vector attribute identifying each polygon. When None the feature index is used.

None
all_touched bool

Include every pixel touched by a polygon, not only those whose centre falls inside it.

False

Returns:

Type Description
list of PolygonStatistics

One entry per raster and region, each holding count, mean, minimum, maximum and standard_deviation alongside the identifying feature_id, site, flux_type and date.

Raises:

Type Description
ValueError

If product is neither "half-hourly" nor "daily", or if a raster lacks the spatial metadata needed to apply a vector.

See Also

wrap_filt_qf : Produce the filtered rasters this function consumes. wrap_diu : Diurnal cycles from the same rasters.

Notes

standard_deviation here is spatial — the spread across pixels within the region at each timestep. This differs from the field of the same name on :class:~fluxmappy.PolygonDiurnalCycle, which measures variability across days.

Examples:

Two days of synthetic single-pixel rasters, summarised whole:

>>> rasters = [_example_raster(d) for d in ("20260101", "20260102")]
>>> stats = wrap_stat(rasters)
>>> len(stats)
2
>>> stats[0].product
'half-hourly'
>>> stats[0].mean[:4]
array([0., 1., 2., 3.])

Collapsing each day to a single value instead:

>>> daily = wrap_stat(rasters, product="daily")
>>> daily[0].product
'daily'
>>> float(daily[0].mean)
23.5
>>> int(daily[0].count)
1
Source code in src/fluxmappy/wrap_stat.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def wrap_stat(
    filtered_rasters: Iterable[FilteredFluxRasterLike],
    vector: str | Path | None = None,
    product: str = "half-hourly",
    id_field: str | None = None,
    all_touched: bool = False,
) -> list[PolygonStatistics]:
    """Return spatial statistics for whole FluxMaps or polygons within them.

    Reads quality-filtered FluxMaps and computes pixel statistics across
    each raster, or within each polygon of a vector file when one is
    supplied.

    Parameters
    ----------
    filtered_rasters : iterable of FilteredFluxRaster
        Quality-filtered rasters, typically the output of
        :func:`~fluxmappy.wrap_filt_qf`.
    vector : str or pathlib.Path, optional
        Polygon vector file to summarise within. When ``None`` (default)
        each raster is summarised as a whole.
    product : {"half-hourly", "daily"}, default "half-hourly"
        Temporal resolution of the statistics. ``"half-hourly"`` returns
        48-element arrays, one value per band. ``"daily"`` averages the
        bands into a single daily layer first and returns scalars.
    id_field : str, optional
        Vector attribute identifying each polygon. When ``None`` the
        feature index is used.
    all_touched : bool, default False
        Include every pixel touched by a polygon, not only those whose
        centre falls inside it.

    Returns
    -------
    list of PolygonStatistics
        One entry per raster and region, each holding ``count``, ``mean``,
        ``minimum``, ``maximum`` and ``standard_deviation`` alongside the
        identifying ``feature_id``, ``site``, ``flux_type`` and ``date``.

    Raises
    ------
    ValueError
        If ``product`` is neither ``"half-hourly"`` nor ``"daily"``, or if
        a raster lacks the spatial metadata needed to apply a vector.

    See Also
    --------
    wrap_filt_qf : Produce the filtered rasters this function consumes.
    wrap_diu : Diurnal cycles from the same rasters.

    Notes
    -----
    ``standard_deviation`` here is *spatial* — the spread across pixels
    within the region at each timestep. This differs from the field of the
    same name on :class:`~fluxmappy.PolygonDiurnalCycle`, which measures
    variability across days.

    Examples
    --------
    Two days of synthetic single-pixel rasters, summarised whole:

    >>> rasters = [_example_raster(d) for d in ("20260101", "20260102")]
    >>> stats = wrap_stat(rasters)
    >>> len(stats)
    2
    >>> stats[0].product
    'half-hourly'
    >>> stats[0].mean[:4]
    array([0., 1., 2., 3.])

    Collapsing each day to a single value instead:

    >>> daily = wrap_stat(rasters, product="daily")
    >>> daily[0].product
    'daily'
    >>> float(daily[0].mean)
    23.5
    >>> int(daily[0].count)
    1
    """
    resolved_path = None if vector is None else Path(vector)
    return list(
        iter_polygon_statistics(
            filtered_rasters=filtered_rasters,
            vector=resolved_path,
            product=product,
            id_field=id_field,
            all_touched=all_touched,
        )
    )