Skip to content

Introduction

Each of the main four wrapper functions are built off individual functions, which can be found here.

Each of the files are written as so: def_[wrapper function its used within][descriptor][descriptor]

Descriptions of the functions can be found on the right hand side table of contents.







def_open_qf_path

Validate a measurement path and locate its quality raster.

Parameters:

Name Type Description Default
measurement_path str or Path

Measurement raster that must already exist on disk.

required
quality_path str or Path

Explicit quality raster. When None (default) a sibling file with a _qf or _qa suffix is looked for alongside the measurement raster.

None

Returns:

Name Type Description
measurement Path

The validated measurement raster.

quality Path

The quality raster to pair with it.

Raises:

Type Description
FileNotFoundError

If the measurement raster does not exist, or if no quality raster could be found or the one given is missing.

Examples:

Both paths are checked on disk, so this is shown rather than executed:

>>> resolve_quality_path("KONA/KONA_fluxCo2_20260101.tif")
(PosixPath('KONA/KONA_fluxCo2_20260101.tif'),
 PosixPath('KONA/KONA_fluxCo2_20260101_qf.tif'))
Source code in src/fluxmappy/def_open_qf_path.py
 8
 9
10
11
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
def resolve_quality_path(
    measurement_path: str | Path,
    quality_path: str | Path | None = None,
) -> tuple[Path, Path]:
    """Validate a measurement path and locate its quality raster.

    Parameters
    ----------
    measurement_path : str or pathlib.Path
        Measurement raster that must already exist on disk.
    quality_path : str or pathlib.Path, optional
        Explicit quality raster. When ``None`` (default) a sibling file
        with a ``_qf`` or ``_qa`` suffix is looked for alongside the
        measurement raster.

    Returns
    -------
    measurement : pathlib.Path
        The validated measurement raster.
    quality : pathlib.Path
        The quality raster to pair with it.

    Raises
    ------
    FileNotFoundError
        If the measurement raster does not exist, or if no quality raster
        could be found or the one given is missing.

    Examples
    --------
    Both paths are checked on disk, so this is shown rather than
    executed:

    >>> resolve_quality_path("KONA/KONA_fluxCo2_20260101.tif")  # doctest: +SKIP
    (PosixPath('KONA/KONA_fluxCo2_20260101.tif'),
     PosixPath('KONA/KONA_fluxCo2_20260101_qf.tif'))
    """
    measurement = Path(measurement_path)
    if not measurement.is_file():
        raise FileNotFoundError(
            f"Measurement raster does not exist: {measurement}"
        )

    record = parse_raster_path(measurement)
    if record is None:
        raise ValueError(
            f"Could not parse site, flux type, and date from {measurement.name}"
        )
    if record.is_quality:
        raise ValueError(
            f"Expected a measurement raster, received quality raster: "
            f"{measurement}"
        )

    if quality_path is not None:
        quality = Path(quality_path)
        if not quality.is_file():
            raise FileNotFoundError(f"Quality raster does not exist: {quality}")
        return measurement, quality

    matches: list[Path] = []
    for candidate in measurement.parent.iterdir():
        if (
            not candidate.is_file()
            or candidate.suffix.lower() not in {".tif", ".tiff"}
        ):
            continue
        candidate_record = parse_raster_path(candidate)
        if candidate_record is None or not candidate_record.is_quality:
            continue
        if (
            candidate_record.site.casefold() == record.site.casefold()
            and candidate_record.flux_type.casefold()
            == record.flux_type.casefold()
            and candidate_record.date == record.date
        ):
            matches.append(candidate)

    if not matches:
        raise FileNotFoundError(
            f"No matching _qa or _qf raster was found for {measurement}"
        )
    if len(matches) > 1:
        paths = "\n  ".join(str(path) for path in sorted(matches))
        raise ValueError(
            "More than one matching quality raster was found; pass "
            f"quality_path explicitly:\n  {paths}"
        )
    return measurement, matches[0]




def_filt_rast_pair

Recursively find and pair measurement and quality TIFFs.

Walks data_dir, parses every filename, and matches each measurement raster to the quality raster sharing its site, flux type and date.

Parameters:

Name Type Description Default
data_dir Path

Directory to search, including subdirectories.

required
flux_type str

Flux type to keep, e.g. "fluxCo2".

required

Returns:

Type Description
list of RasterPair

One entry per matched measurement/quality pair, ordered by date.

Raises:

Type Description
FileNotFoundError

If data_dir is not a directory.

ValueError

If no measurement rasters of flux_type are found, or a measurement raster has no matching quality raster.

Examples:

Requires rasters on disk, so this is shown rather than executed:

>>> from pathlib import Path
>>> pairs = find_raster_pairs(Path("KONA"), "fluxCo2")
>>> len(pairs)
12
Source code in src/fluxmappy/def_filt_rast_pair.py
  9
 10
 11
 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
102
103
104
105
106
def find_raster_pairs(
    data_dir: Path,
    flux_type: str,
) -> list[RasterPair]:
    """Recursively find and pair measurement and quality TIFFs.

    Walks ``data_dir``, parses every filename, and matches each
    measurement raster to the quality raster sharing its site, flux type
    and date.

    Parameters
    ----------
    data_dir : pathlib.Path
        Directory to search, including subdirectories.
    flux_type : str
        Flux type to keep, e.g. ``"fluxCo2"``.

    Returns
    -------
    list of RasterPair
        One entry per matched measurement/quality pair, ordered by date.

    Raises
    ------
    FileNotFoundError
        If ``data_dir`` is not a directory.
    ValueError
        If no measurement rasters of ``flux_type`` are found, or a
        measurement raster has no matching quality raster.

    Examples
    --------
    Requires rasters on disk, so this is shown rather than executed:

    >>> from pathlib import Path
    >>> pairs = find_raster_pairs(Path("KONA"), "fluxCo2")  # doctest: +SKIP
    >>> len(pairs)  # doctest: +SKIP
    12
    """
    if not data_dir.is_dir():
        raise FileNotFoundError(f"Data directory does not exist: {data_dir}")

    records: list[RasterRecord] = []
    for path in sorted(data_dir.rglob("*")):
        if not path.is_file() or path.suffix.lower() not in {".tif", ".tiff"}:
            continue
        record = parse_raster_path(path)
        if (
            record is not None
            and record.flux_type.casefold() == flux_type.casefold()
        ):
            records.append(record)

    quality_by_key = {
        (
            record.path.parent,
            record.site.casefold(),
            record.flux_type.casefold(),
            record.date,
        ): record.path
        for record in records
        if record.is_quality
    }

    pairs: list[RasterPair] = []
    missing_quality: list[Path] = []
    for record in records:
        if record.is_quality:
            continue
        key = (
            record.path.parent,
            record.site.casefold(),
            record.flux_type.casefold(),
            record.date,
        )
        quality_path = quality_by_key.get(key)
        if quality_path is None:
            missing_quality.append(record.path)
        else:
            pairs.append(
                RasterPair(
                    measurement=record,
                    quality_path=quality_path,
                )
            )

    if missing_quality:
        missing = "\n  ".join(str(path) for path in missing_quality)
        raise FileNotFoundError(
            "No matching _qa or _qf raster was found for:\n"
            f"  {missing}"
        )
    if not pairs:
        raise FileNotFoundError(
            f"No measurement/quality pairs for {flux_type} were found "
            f"below {data_dir}"
        )
    return pairs




def_filt_rast_name

Parse site, flux type, date and quality suffix from a filename.

Parameters:

Name Type Description Default
path Path

Raster path whose filename follows <site>_<flux_type>_<YYYYMMDD>[_qf].tif.

required

Returns:

Type Description
RasterRecord or None

The parsed record, or None if the filename does not match the expected pattern.

Examples:

>>> from pathlib import Path
>>> record = parse_raster_path(Path("KONA_fluxCo2_20260101.tif"))
>>> record.site, record.flux_type, record.date
('KONA', 'fluxCo2', '20260101')
>>> record.is_quality
False

A _qf suffix marks the quality-flag raster of the same day:

>>> parse_raster_path(Path("KONA_fluxCo2_20260101_qf.tif")).is_quality
True

Names that do not match return None rather than raising:

>>> parse_raster_path(Path("notes.txt")) is None
True
Source code in src/fluxmappy/def_filt_rast_name.py
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
def parse_raster_path(path: Path) -> RasterRecord | None:
    """Parse site, flux type, date and quality suffix from a filename.

    Parameters
    ----------
    path : pathlib.Path
        Raster path whose filename follows
        ``<site>_<flux_type>_<YYYYMMDD>[_qf].tif``.

    Returns
    -------
    RasterRecord or None
        The parsed record, or ``None`` if the filename does not match the
        expected pattern.

    Examples
    --------
    >>> from pathlib import Path
    >>> record = parse_raster_path(Path("KONA_fluxCo2_20260101.tif"))
    >>> record.site, record.flux_type, record.date
    ('KONA', 'fluxCo2', '20260101')
    >>> record.is_quality
    False

    A ``_qf`` suffix marks the quality-flag raster of the same day:

    >>> parse_raster_path(Path("KONA_fluxCo2_20260101_qf.tif")).is_quality
    True

    Names that do not match return ``None`` rather than raising:

    >>> parse_raster_path(Path("notes.txt")) is None
    True
    """
    match = TIF_NAME_PATTERN.search(path.name)
    if match is None:
        return None

    return RasterRecord(
        site=match.group("site"),
        flux_type=match.group("flux_type"),
        date=match.group("date"),
        is_quality=match.group("quality") is not None,
        path=path,
    )




def_filt_qf_mask

Return True where a measurement pixel passes the quality rule.

Parameters:

Name Type Description Default
quality_data MaskedArray

Quality-flag bands, shaped either like measurement_shape or with a single band to broadcast across all of them.

required
measurement_shape tuple of int

Shape (bands, rows, columns) of the measurement raster the mask will be applied to.

required
qf_threshold float

Quality-flag threshold, on the 0-5 FluxMap scale.

required
qf_keep (lte, gte)

Which side of the threshold passes. "lte" passes flags at or below the threshold; "gte" passes those at or above it.

"lte"

Returns:

Type Description
ndarray

Boolean array of measurement_shape. Masked or non-finite quality values never pass.

Raises:

Type Description
ValueError

If qf_keep is not "lte" or "gte", or if the quality band count is neither 1 nor equal to the measurement band count.

Examples:

>>> import numpy as np
>>> quality = np.ma.array([[[0, 1], [2, 3]]])
>>> quality_pass_mask(quality, (1, 2, 2), qf_threshold=1, qf_keep="lte")
array([[[ True,  True],
        [False, False]]])

Keeping the other side of the same threshold inverts the result:

>>> quality_pass_mask(quality, (1, 2, 2), qf_threshold=1, qf_keep="gte")
array([[[False,  True],
        [ True,  True]]])

A single quality band broadcasts across every measurement band:

>>> quality_pass_mask(quality, (48, 2, 2), qf_threshold=1, qf_keep="lte").shape
(48, 2, 2)
>>> quality_pass_mask(quality, (1, 2, 2), qf_threshold=1, qf_keep="eq")
Traceback (most recent call last):
    ...
ValueError: qf_keep must be either 'lte' or 'gte'
Source code in src/fluxmappy/def_filt_qf_mask.py
 7
 8
 9
10
11
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
def quality_pass_mask(
    quality_data: np.ma.MaskedArray,
    measurement_shape: tuple[int, int, int],
    qf_threshold: float,
    qf_keep: str,
) -> np.ndarray:
    """Return ``True`` where a measurement pixel passes the quality rule.

    Parameters
    ----------
    quality_data : numpy.ma.MaskedArray
        Quality-flag bands, shaped either like ``measurement_shape`` or
        with a single band to broadcast across all of them.
    measurement_shape : tuple of int
        Shape ``(bands, rows, columns)`` of the measurement raster the
        mask will be applied to.
    qf_threshold : float
        Quality-flag threshold, on the 0-5 FluxMap scale.
    qf_keep : {"lte", "gte"}
        Which side of the threshold passes. ``"lte"`` passes flags at or
        below the threshold; ``"gte"`` passes those at or above it.

    Returns
    -------
    numpy.ndarray
        Boolean array of ``measurement_shape``. Masked or non-finite
        quality values never pass.

    Raises
    ------
    ValueError
        If ``qf_keep`` is not ``"lte"`` or ``"gte"``, or if the quality
        band count is neither 1 nor equal to the measurement band count.

    Examples
    --------
    >>> import numpy as np
    >>> quality = np.ma.array([[[0, 1], [2, 3]]])
    >>> quality_pass_mask(quality, (1, 2, 2), qf_threshold=1, qf_keep="lte")
    array([[[ True,  True],
            [False, False]]])

    Keeping the other side of the same threshold inverts the result:

    >>> quality_pass_mask(quality, (1, 2, 2), qf_threshold=1, qf_keep="gte")
    array([[[False,  True],
            [ True,  True]]])

    A single quality band broadcasts across every measurement band:

    >>> quality_pass_mask(quality, (48, 2, 2), qf_threshold=1, qf_keep="lte").shape
    (48, 2, 2)

    >>> quality_pass_mask(quality, (1, 2, 2), qf_threshold=1, qf_keep="eq")
    Traceback (most recent call last):
        ...
    ValueError: qf_keep must be either 'lte' or 'gte'
    """
    quality_data = np.ma.masked_invalid(quality_data.astype("float32"))

    if qf_keep == "lte":
        quality_passes = quality_data <= qf_threshold
    elif qf_keep == "gte":
        quality_passes = quality_data >= qf_threshold
    else:
        raise ValueError("qf_keep must be either 'lte' or 'gte'")

    quality_passes = np.asarray(quality_passes.filled(False), dtype=bool)
    if quality_passes.shape == measurement_shape:
        return quality_passes
    if (
        quality_passes.shape[0] == 1
        and quality_passes.shape[1:] == measurement_shape[1:]
    ):
        return np.broadcast_to(quality_passes, measurement_shape)

    raise ValueError(
        "Quality raster band count must be 1 or match the measurement "
        "raster band count."
    )




def_filt_pair

Read and quality-filter one raster pair entirely in memory.

Opens both rasters, checks they share a grid, and masks every measurement pixel whose quality flag fails the rule. Nothing is written to disk.

Parameters:

Name Type Description Default
pair RasterPair

Measurement and quality rasters for a single day.

required
qf_threshold float

Quality-flag threshold, on the 0-5 FluxMap scale.

1
qf_keep (lte, gte)

Which side of the threshold to keep.

"lte"

Returns:

Type Description
FilteredFluxRaster

Carrying the masked bands, the originating record, the profile and the quality settings applied.

Raises:

Type Description
ValueError

If the measurement and quality rasters do not share a grid, or if the quality band count is neither 1 nor equal to the measurement band count.

Notes

A measurement raster that does not hold 48 bands prints a warning to stdout and is filtered anyway.

Examples:

Requires rasters on disk, so this is shown rather than executed:

>>> filtered = filter_raster_pair(pair, qf_threshold=1)
>>> filtered.filtered_bands.shape
(48, 64, 64)
Source code in src/fluxmappy/def_filt_pair.py
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
def filter_raster_pair(
    pair: RasterPair,
    qf_threshold: float = 1,
    qf_keep: str = "lte",
) -> FilteredFluxRaster:
    """Read and quality-filter one raster pair entirely in memory.

    Opens both rasters, checks they share a grid, and masks every
    measurement pixel whose quality flag fails the rule. Nothing is
    written to disk.

    Parameters
    ----------
    pair : RasterPair
        Measurement and quality rasters for a single day.
    qf_threshold : float, default 1
        Quality-flag threshold, on the 0-5 FluxMap scale.
    qf_keep : {"lte", "gte"}, default "lte"
        Which side of the threshold to keep.

    Returns
    -------
    FilteredFluxRaster
        Carrying the masked bands, the originating ``record``, the
        ``profile`` and the quality settings applied.

    Raises
    ------
    ValueError
        If the measurement and quality rasters do not share a grid, or if
        the quality band count is neither 1 nor equal to the measurement
        band count.

    Notes
    -----
    A measurement raster that does not hold 48 bands prints a warning to
    stdout and is filtered anyway.

    Examples
    --------
    Requires rasters on disk, so this is shown rather than executed:

    >>> filtered = filter_raster_pair(pair, qf_threshold=1)  # doctest: +SKIP
    >>> filtered.filtered_bands.shape  # doctest: +SKIP
    (48, 64, 64)
    """
    with rasterio.open(pair.measurement.path) as measurement_src:
        if measurement_src.count != EXPECTED_BANDS_PER_DAY:
            print(
                f"Warning: {pair.measurement.path} has "
                f"{measurement_src.count} bands; "
                f"expected {EXPECTED_BANDS_PER_DAY}."
            )

        measurement_data = np.ma.masked_invalid(
            measurement_src.read(masked=True).astype("float32")
        )
        profile = measurement_src.profile.copy()
        band_descriptions = tuple(measurement_src.descriptions)
        tags = measurement_src.tags().copy()

        with rasterio.open(pair.quality_path) as quality_src:
            assert_same_grid(
                measurement_path=pair.measurement.path,
                measurement_profile=measurement_src.profile,
                quality_path=pair.quality_path,
                quality_profile=quality_src.profile,
            )
            passes = quality_pass_mask(
                quality_data=quality_src.read(masked=True),
                measurement_shape=measurement_data.shape,
                qf_threshold=qf_threshold,
                qf_keep=qf_keep,
            )

    return FilteredFluxRaster(
        record=pair.measurement,
        quality_path=pair.quality_path,
        filtered_bands=np.ma.masked_where(~passes, measurement_data),
        profile=profile,
        band_descriptions=band_descriptions,
        tags=tags,
        qf_threshold=qf_threshold,
        qf_keep=qf_keep,
    )




def_filt_grid_vali

Require measurement and quality rasters to share a spatial grid.

Parameters:

Name Type Description Default
measurement_path Path

Path to the measurement raster, used in the error message.

required
measurement_profile dict

Rasterio profile of the measurement raster.

required
quality_path Path

Path to the quality raster, used in the error message.

required
quality_profile dict

Rasterio profile of the quality raster.

required

Returns:

Type Description
None

Returns nothing when the grids match.

Raises:

Type Description
ValueError

If width, height, transform or crs differ, naming every field that disagrees.

Examples:

>>> from pathlib import Path
>>> grid = {"width": 64, "height": 64, "transform": None, "crs": "EPSG:4326"}
>>> assert_same_grid(Path("a.tif"), grid, Path("a_qf.tif"), dict(grid)) is None
True
>>> other = dict(grid, width=32)
>>> assert_same_grid(Path("a.tif"), grid, Path("a_qf.tif"), other)
Traceback (most recent call last):
    ...
ValueError: a_qf.tif does not match a.tif for: width
Source code in src/fluxmappy/def_filt_grid_vali.py
 6
 7
 8
 9
10
11
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
def assert_same_grid(
    measurement_path: Path,
    measurement_profile: dict,
    quality_path: Path,
    quality_profile: dict,
) -> None:
    """Require measurement and quality rasters to share a spatial grid.

    Parameters
    ----------
    measurement_path : pathlib.Path
        Path to the measurement raster, used in the error message.
    measurement_profile : dict
        Rasterio profile of the measurement raster.
    quality_path : pathlib.Path
        Path to the quality raster, used in the error message.
    quality_profile : dict
        Rasterio profile of the quality raster.

    Returns
    -------
    None
        Returns nothing when the grids match.

    Raises
    ------
    ValueError
        If ``width``, ``height``, ``transform`` or ``crs`` differ,
        naming every field that disagrees.

    Examples
    --------
    >>> from pathlib import Path
    >>> grid = {"width": 64, "height": 64, "transform": None, "crs": "EPSG:4326"}
    >>> assert_same_grid(Path("a.tif"), grid, Path("a_qf.tif"), dict(grid)) is None
    True

    >>> other = dict(grid, width=32)
    >>> assert_same_grid(Path("a.tif"), grid, Path("a_qf.tif"), other)
    Traceback (most recent call last):
        ...
    ValueError: a_qf.tif does not match a.tif for: width
    """
    fields = ("width", "height", "transform", "crs")
    mismatched = [
        field
        for field in fields
        if measurement_profile.get(field) != quality_profile.get(field)
    ]
    if mismatched:
        raise ValueError(
            f"{quality_path} does not match {measurement_path} for: "
            f"{', '.join(mismatched)}"
        )




def_diu_tz_vali

Return an IANA timezone, or raise a clear configuration error.

Parameters:

Name Type Description Default
name str

IANA timezone name, such as "UTC" or "America/Chicago".

required
parameter str

Name of the calling argument, used to make the error message point at the right place.

required

Returns:

Type Description
ZoneInfo

The resolved timezone.

Raises:

Type Description
ValueError

If name is not a known IANA timezone.

Examples:

>>> resolve_timezone("America/Chicago", "out_tz")
zoneinfo.ZoneInfo(key='America/Chicago')
>>> resolve_timezone("Mars/Olympus", "out_tz")
Traceback (most recent call last):
    ...
ValueError: Unknown out_tz 'Mars/Olympus'; use an IANA timezone name such as 'UTC', 'Europe/Madrid', or 'America/Chicago'
Source code in src/fluxmappy/def_diu_tz_vali.py
 7
 8
 9
10
11
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
def resolve_timezone(name: str, parameter: str) -> ZoneInfo:
    """Return an IANA timezone, or raise a clear configuration error.

    Parameters
    ----------
    name : str
        IANA timezone name, such as ``"UTC"`` or ``"America/Chicago"``.
    parameter : str
        Name of the calling argument, used to make the error message
        point at the right place.

    Returns
    -------
    zoneinfo.ZoneInfo
        The resolved timezone.

    Raises
    ------
    ValueError
        If ``name`` is not a known IANA timezone.

    Examples
    --------
    >>> resolve_timezone("America/Chicago", "out_tz")
    zoneinfo.ZoneInfo(key='America/Chicago')

    >>> resolve_timezone("Mars/Olympus", "out_tz")
    Traceback (most recent call last):
        ...
    ValueError: Unknown out_tz 'Mars/Olympus'; use an IANA timezone name such as 'UTC', 'Europe/Madrid', or 'America/Chicago'
    """
    try:
        return ZoneInfo(name)
    except ZoneInfoNotFoundError as exc:
        raise ValueError(
            f"Unknown {parameter} {name!r}; use an IANA timezone name such "
            "as 'UTC', 'Europe/Madrid', or 'America/Chicago'"
        ) from exc




def_diu_lt

Return the UTC half-hour instants making up one full local day.

Used to decide whether a local day is fully covered by the source rasters once a timezone shift has been applied.

Parameters:

Name Type Description Default
local_date str

Local date in YYYYMMDD form.

required
target_timezone ZoneInfo

Timezone the local day is measured in.

required

Returns:

Type Description
set of datetime.datetime

Every half-hour instant of that local day, in UTC. Normally 48 instants, but 46 or 50 across a daylight-saving transition.

Examples:

>>> from zoneinfo import ZoneInfo
>>> len(expected_local_day_instants("20260101", ZoneInfo("UTC")))
48

A spring-forward day is an hour shorter, so two slots do not exist:

>>> len(expected_local_day_instants("20260308", ZoneInfo("America/Chicago")))
46

A fall-back day gains an hour:

>>> len(expected_local_day_instants("20261101", ZoneInfo("America/Chicago")))
50
Source code in src/fluxmappy/def_diu_lt.py
11
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
def expected_local_day_instants(
    local_date: str,
    target_timezone: ZoneInfo,
) -> set[datetime]:
    """Return the UTC half-hour instants making up one full local day.

    Used to decide whether a local day is fully covered by the source
    rasters once a timezone shift has been applied.

    Parameters
    ----------
    local_date : str
        Local date in ``YYYYMMDD`` form.
    target_timezone : zoneinfo.ZoneInfo
        Timezone the local day is measured in.

    Returns
    -------
    set of datetime.datetime
        Every half-hour instant of that local day, in UTC. Normally 48
        instants, but 46 or 50 across a daylight-saving transition.

    Examples
    --------
    >>> from zoneinfo import ZoneInfo
    >>> len(expected_local_day_instants("20260101", ZoneInfo("UTC")))
    48

    A spring-forward day is an hour shorter, so two slots do not exist:

    >>> len(expected_local_day_instants("20260308", ZoneInfo("America/Chicago")))
    46

    A fall-back day gains an hour:

    >>> len(expected_local_day_instants("20261101", ZoneInfo("America/Chicago")))
    50
    """
    local_midnight = parse_cycle_date(local_date).replace(
        tzinfo=target_timezone
    )
    next_local_midnight = (
        parse_cycle_date(local_date) + timedelta(days=1)
    ).replace(tzinfo=target_timezone)

    instant = local_midnight.astimezone(timezone.utc)
    end_utc = next_local_midnight.astimezone(timezone.utc)
    expected: set[datetime] = set()
    while instant < end_utc:
        expected.add(instant)
        instant += timedelta(minutes=30)
    return expected




Regroup daily cycles from source dates into local dates.

Each band is timestamped from its source date and timezone, converted into output_timezone, and filed under the local date and half-hour slot it lands in. Slots receiving more than one value, as happens on a fall-back day, are averaged.

Parameters:

Name Type Description Default
dated_cycles list of (str, numpy.ndarray)

Source date in YYYYMMDD form paired with that day's 48 half-hourly values.

required
input_timezone ZoneInfo

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

required
output_timezone ZoneInfo

Timezone to regroup into.

required
incomplete_local_days (drop, include, error)

What to do with local days the source data only partly covers.

"drop"

Returns:

Name Type Description
dates tuple of str

Local dates retained, in ascending order.

daily_cycles ndarray

Array of shape (len(dates), 48). Slots with no contributing value are nan.

Raises:

Type Description
ValueError

If incomplete_local_days is "error" and any local day is incomplete, or if no local days survive the policy.

Examples:

>>> import numpy as np
>>> from zoneinfo import ZoneInfo
>>> cycles = [(d, np.arange(48, dtype=float))
...           for d in ("20260101", "20260102", "20260103")]
>>> dates, values = localize_daily_cycles(
...     cycles, ZoneInfo("UTC"), ZoneInfo("America/Chicago"), "drop"
... )
>>> values.shape
(2, 48)
>>> dates
('20260101', '20260102')
Source code in src/fluxmappy/def_diu_lt.py
 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
def localize_daily_cycles(
    dated_cycles: list[tuple[str, np.ndarray]],
    input_timezone: ZoneInfo,
    output_timezone: ZoneInfo,
    incomplete_local_days: str,
) -> tuple[tuple[str, ...], np.ndarray]:
    """Regroup daily cycles from source dates into local dates.

    Each band is timestamped from its source date and timezone, converted
    into ``output_timezone``, and filed under the local date and
    half-hour slot it lands in. Slots receiving more than one value, as
    happens on a fall-back day, are averaged.

    Parameters
    ----------
    dated_cycles : list of (str, numpy.ndarray)
        Source date in ``YYYYMMDD`` form paired with that day's 48
        half-hourly values.
    input_timezone : zoneinfo.ZoneInfo
        Timezone in which band 1 of each source day is midnight.
    output_timezone : zoneinfo.ZoneInfo
        Timezone to regroup into.
    incomplete_local_days : {"drop", "include", "error"}
        What to do with local days the source data only partly covers.

    Returns
    -------
    dates : tuple of str
        Local dates retained, in ascending order.
    daily_cycles : numpy.ndarray
        Array of shape ``(len(dates), 48)``. Slots with no contributing
        value are ``nan``.

    Raises
    ------
    ValueError
        If ``incomplete_local_days`` is ``"error"`` and any local day is
        incomplete, or if no local days survive the policy.

    Examples
    --------
    >>> import numpy as np
    >>> from zoneinfo import ZoneInfo
    >>> cycles = [(d, np.arange(48, dtype=float))
    ...           for d in ("20260101", "20260102", "20260103")]
    >>> dates, values = localize_daily_cycles(
    ...     cycles, ZoneInfo("UTC"), ZoneInfo("America/Chicago"), "drop"
    ... )
    >>> values.shape
    (2, 48)
    >>> dates
    ('20260101', '20260102')
    """
    values_by_date: dict[str, list[list[float]]] = {}
    instants_by_date: dict[str, set[datetime]] = {}

    for source_date, values in dated_cycles:
        source_midnight = parse_cycle_date(source_date).replace(
            tzinfo=input_timezone
        )
        source_start_utc = source_midnight.astimezone(timezone.utc)

        for band_index, value in enumerate(values):
            instant_utc = source_start_utc + timedelta(
                minutes=30 * band_index
            )
            local_timestamp = instant_utc.astimezone(output_timezone)
            local_date = local_timestamp.strftime("%Y%m%d")
            local_slot = local_timestamp.hour * 2 + local_timestamp.minute // 30
            date_values = values_by_date.setdefault(
                local_date,
                [[] for _ in range(48)],
            )
            date_values[local_slot].append(float(value))
            instants_by_date.setdefault(local_date, set()).add(instant_utc)

    incomplete_dates = {
        local_date
        for local_date, observed_instants in instants_by_date.items()
        if not expected_local_day_instants(
            local_date,
            output_timezone,
        ).issubset(observed_instants)
    }
    if incomplete_local_days == "error" and incomplete_dates:
        dates = ", ".join(sorted(incomplete_dates))
        raise ValueError(
            f"Timezone conversion produced incomplete local days: {dates}"
        )

    selected_dates = tuple(
        local_date
        for local_date in sorted(values_by_date)
        if incomplete_local_days == "include"
        or local_date not in incomplete_dates
    )
    if not selected_dates:
        raise ValueError(
            "No complete local days remained after timezone conversion; "
            "provide adjacent UTC dates or use "
            "incomplete_local_days='include'"
        )

    daily_cycles = np.full((len(selected_dates), 48), np.nan, dtype=float)
    for day_index, local_date in enumerate(selected_dates):
        for local_slot, slot_values in enumerate(values_by_date[local_date]):
            if not slot_values:
                continue
            masked_values = np.ma.masked_invalid(
                np.asarray(slot_values, dtype=float)
            )
            if masked_values.count() > 0:
                daily_cycles[day_index, local_slot] = float(
                    np.ma.mean(masked_values)
                )

    return selected_dates, daily_cycles




def_diu_coll

Collect 48 spatial means for every region and source date.

Runs the statistics pass over every raster and files each day's 48 half-hourly means under its (feature_id, site, flux_type) group, ready for averaging into a diurnal cycle.

Parameters:

Name Type Description Default
filtered_rasters iterable of FilteredFluxRaster

Quality-filtered rasters, one per day.

required
vector_path Path or None

Polygon vector file to summarise within, or None to summarise each raster whole.

required
id_field str or None

Vector attribute identifying each polygon, or None to use the feature index.

required
all_touched bool

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

required

Returns:

Type Description
dict

Keyed by (feature_id, site, flux_type). Each value holds the feature properties and a dated_cycles list of (date, values) pairs.

Raises:

Type Description
ValueError

If any raster does not yield exactly 48 half-hourly means, or if no statistics were available at all.

Examples:

>>> rasters = [_example_raster(d) for d in ("20260101", "20260102")]
>>> grouped = collect_dated_cycles(rasters, None, None, False)
>>> list(grouped)
[('whole_raster', 'KONA', 'fluxCo2')]
>>> len(grouped[('whole_raster', 'KONA', 'fluxCo2')]["dated_cycles"])
2
Source code in src/fluxmappy/def_diu_coll.py
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
def collect_dated_cycles(
    filtered_rasters: Iterable[FilteredFluxRasterLike],
    vector_path: Path | None,
    id_field: str | None,
    all_touched: bool,
) -> CycleGroups:
    """Collect 48 spatial means for every region and source date.

    Runs the statistics pass over every raster and files each day's 48
    half-hourly means under its ``(feature_id, site, flux_type)`` group,
    ready for averaging into a diurnal cycle.

    Parameters
    ----------
    filtered_rasters : iterable of FilteredFluxRaster
        Quality-filtered rasters, one per day.
    vector_path : pathlib.Path or None
        Polygon vector file to summarise within, or ``None`` to
        summarise each raster whole.
    id_field : str or None
        Vector attribute identifying each polygon, or ``None`` to use the
        feature index.
    all_touched : bool
        Include every pixel touched by a polygon, not only those whose
        centre falls inside it.

    Returns
    -------
    dict
        Keyed by ``(feature_id, site, flux_type)``. Each value holds the
        feature ``properties`` and a ``dated_cycles`` list of
        ``(date, values)`` pairs.

    Raises
    ------
    ValueError
        If any raster does not yield exactly 48 half-hourly means, or if
        no statistics were available at all.

    Examples
    --------
    >>> rasters = [_example_raster(d) for d in ("20260101", "20260102")]
    >>> grouped = collect_dated_cycles(rasters, None, None, False)
    >>> list(grouped)
    [('whole_raster', 'KONA', 'fluxCo2')]
    >>> len(grouped[('whole_raster', 'KONA', 'fluxCo2')]["dated_cycles"])
    2
    """
    grouped: CycleGroups = {}
    for statistics in iter_polygon_statistics(
        filtered_rasters=filtered_rasters,
        vector=vector_path,
        product="half-hourly",
        id_field=id_field,
        all_touched=all_touched,
    ):
        mean_values = np.asarray(statistics.mean, dtype=float)
        if mean_values.shape != (48,):
            raise ValueError(
                f"Expected 48 half-hourly means for feature "
                f"{statistics.feature_id!r} on {statistics.date}; "
                f"received shape {mean_values.shape}"
            )

        key = (
            statistics.feature_id,
            statistics.site,
            statistics.flux_type,
        )
        group = grouped.setdefault(
            key,
            {
                "properties": statistics.properties.copy(),
                "dated_cycles": [],
            },
        )
        dated_cycles = group["dated_cycles"]
        assert isinstance(dated_cycles, list)
        dated_cycles.append((statistics.date, mean_values))

    if not grouped:
        raise ValueError("No polygon statistics were available to aggregate")
    return grouped




def_diu_calc

Summarise stacked daily cycles into mean, spread, counts and totals.

Parameters:

Name Type Description Default
daily_cycles ndarray

Array of shape (n_days, 48) holding one spatial mean per half-hour slot for each day.

required
timestep_seconds float or None

Seconds represented by each slot, used to scale the cumulative cycle. None leaves the cumulative sum unscaled.

required

Returns:

Name Type Description
mean_cycle ndarray

Per-slot mean across days, shape (48,).

standard_deviation ndarray

Per-slot standard deviation across days, not across pixels.

valid_day_count ndarray

Number of finite observations contributing to each slot.

cumulative_cycle ndarray

Running total of mean_cycle scaled by timestep_seconds.

Examples:

>>> import numpy as np
>>> days = np.array([[1.0, 2.0], [3.0, 4.0]])
>>> mean, sd, n, cum = summarize_daily_cycles(days, 1800.0)
>>> mean
array([2., 3.])
>>> sd
array([1., 1.])
>>> n
array([2, 2])
>>> cum
array([3600., 9000.])

A day missing one slot is skipped for that slot only:

>>> days = np.array([[1.0, np.nan], [3.0, 4.0]])
>>> mean, sd, n, cum = summarize_daily_cycles(days, None)
>>> mean
array([2., 4.])
>>> n
array([2, 1])
Source code in src/fluxmappy/def_diu_calc.py
 8
 9
10
11
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
def summarize_daily_cycles(
    daily_cycles: np.ndarray,
    timestep_seconds: float | None,
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
    """Summarise stacked daily cycles into mean, spread, counts and totals.

    Parameters
    ----------
    daily_cycles : numpy.ndarray
        Array of shape ``(n_days, 48)`` holding one spatial mean per
        half-hour slot for each day.
    timestep_seconds : float or None
        Seconds represented by each slot, used to scale the cumulative
        cycle. ``None`` leaves the cumulative sum unscaled.

    Returns
    -------
    mean_cycle : numpy.ndarray
        Per-slot mean across days, shape ``(48,)``.
    standard_deviation : numpy.ndarray
        Per-slot standard deviation *across days*, not across pixels.
    valid_day_count : numpy.ndarray
        Number of finite observations contributing to each slot.
    cumulative_cycle : numpy.ndarray
        Running total of ``mean_cycle`` scaled by ``timestep_seconds``.

    Examples
    --------
    >>> import numpy as np
    >>> days = np.array([[1.0, 2.0], [3.0, 4.0]])
    >>> mean, sd, n, cum = summarize_daily_cycles(days, 1800.0)
    >>> mean
    array([2., 3.])
    >>> sd
    array([1., 1.])
    >>> n
    array([2, 2])
    >>> cum
    array([3600., 9000.])

    A day missing one slot is skipped for that slot only:

    >>> days = np.array([[1.0, np.nan], [3.0, 4.0]])
    >>> mean, sd, n, cum = summarize_daily_cycles(days, None)
    >>> mean
    array([2., 4.])
    >>> n
    array([2, 1])
    """
    masked_cycles = np.ma.masked_invalid(daily_cycles)
    mean_cycle = np.asarray(
        np.ma.mean(masked_cycles, axis=0).filled(np.nan),
        dtype=float,
    )
    standard_deviation = np.asarray(
        np.ma.std(masked_cycles, axis=0).filled(np.nan),
        dtype=float,
    )
    valid_day_count = np.sum(np.isfinite(daily_cycles), axis=0)

    interval_scale = 1.0 if timestep_seconds is None else timestep_seconds
    increments = np.ma.masked_invalid(mean_cycle * interval_scale)
    cumulative_cycle = np.asarray(
        np.ma.cumsum(increments).filled(np.nan),
        dtype=float,
    )
    return (
        mean_cycle,
        standard_deviation,
        valid_day_count,
        cumulative_cycle,
    )




def_stat_vect

Read polygon features, preserving a unique ID for each.

Parameters:

Name Type Description Default
vector_path Path

Vector file to read, in any format Fiona can open.

required
id_field str

Attribute to use as each feature's identifier. When None (default) the feature index is used.

None

Returns:

Type Description
VectorLayer

Carrying the layer crs and a tuple of features, each with its feature_id, geometry and properties.

Raises:

Type Description
FileNotFoundError

If vector_path does not exist.

ValueError

If the file holds no features, if id_field is absent from the schema, or if its values are not unique.

Examples:

Requires a vector file on disk, so this is shown rather than executed:

>>> from pathlib import Path
>>> layer = read_vector_layer(Path("sites.shp"), id_field="name")
>>> len(layer.features)
3
Source code in src/fluxmappy/def_stat_vect.py
 10
 11
 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
102
103
104
105
106
107
108
def read_vector_layer(
    vector_path: Path,
    id_field: str | None = None,
) -> VectorLayer:
    """Read polygon features, preserving a unique ID for each.

    Parameters
    ----------
    vector_path : pathlib.Path
        Vector file to read, in any format Fiona can open.
    id_field : str, optional
        Attribute to use as each feature's identifier. When ``None``
        (default) the feature index is used.

    Returns
    -------
    VectorLayer
        Carrying the layer ``crs`` and a tuple of ``features``, each with
        its ``feature_id``, ``geometry`` and ``properties``.

    Raises
    ------
    FileNotFoundError
        If ``vector_path`` does not exist.
    ValueError
        If the file holds no features, if ``id_field`` is absent from the
        schema, or if its values are not unique.

    Examples
    --------
    Requires a vector file on disk, so this is shown rather than
    executed:

    >>> from pathlib import Path
    >>> layer = read_vector_layer(Path("sites.shp"), id_field="name")  # doctest: +SKIP
    >>> len(layer.features)  # doctest: +SKIP
    3
    """
    if not vector_path.is_file():
        raise FileNotFoundError(f"Vector file does not exist: {vector_path}")

    with fiona.open(vector_path) as vector_src:
        vector_crs = vector_src.crs_wkt or vector_src.crs
        available_fields = tuple(vector_src.schema.get("properties", {}))
        if id_field is not None and id_field not in available_fields:
            raise ValueError(
                f"ID field {id_field!r} is not in {vector_path}. "
                f"Available fields: {available_fields}"
            )

        features: list[VectorFeature] = []
        seen_ids: set[object] = set()
        for feature_number, feature in enumerate(vector_src, start=1):
            geometry = feature["geometry"]
            if geometry is None:
                raise ValueError(
                    f"Feature {feature_number} in {vector_path} has no geometry"
                )

            geometry_mapping = geometry.__geo_interface__
            geometry_type = geometry_mapping.get("type")
            if geometry_type not in {"Polygon", "MultiPolygon"}:
                raise ValueError(
                    f"Feature {feature_number} has geometry type "
                    f"{geometry_type!r}; expected Polygon or MultiPolygon"
                )

            properties = dict(feature["properties"])
            feature_id = (
                properties[id_field] if id_field is not None else feature_number
            )
            if feature_id is None:
                raise ValueError(
                    f"Feature {feature_number} has no value for {id_field!r}"
                )
            if feature_id in seen_ids:
                raise ValueError(
                    f"Vector feature ID {feature_id!r} is not unique"
                )
            seen_ids.add(feature_id)
            features.append(
                VectorFeature(
                    feature_id=feature_id,
                    properties=properties,
                    geometry=geometry_mapping,
                )
            )

    if not vector_crs:
        raise ValueError(f"Vector has no CRS: {vector_path}")
    if not features:
        raise ValueError(f"Vector contains no polygon features: {vector_path}")

    return VectorLayer(
        path=vector_path,
        crs=vector_crs,
        features=tuple(features),
        id_field=id_field,
    )




def_stat_mask

Yield one independently masked raster per vector feature.

Parameters:

Name Type Description Default
filtered_raster FilteredFluxRaster

Raster to clip, which must carry crs and transform in its profile.

required
vector_layer VectorLayer

Polygons to clip to, reprojected to the raster CRS as needed.

required
all_touched bool

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

False

Yields:

Type Description
GeofencedRaster

One per polygon that overlaps the raster. Polygons with no overlapping pixels are skipped.

Raises:

Type Description
ValueError

If the raster lacks the spatial metadata needed to apply a vector.

Source code in src/fluxmappy/def_stat_mask.py
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
def geofence_raster(
    filtered_raster: FilteredFluxRasterLike,
    vector_layer: VectorLayer,
    all_touched: bool = False,
) -> Iterator[GeofencedRaster]:
    """Yield one independently masked raster per vector feature.

    Parameters
    ----------
    filtered_raster : FilteredFluxRaster
        Raster to clip, which must carry ``crs`` and ``transform`` in its
        profile.
    vector_layer : VectorLayer
        Polygons to clip to, reprojected to the raster CRS as needed.
    all_touched : bool, default False
        Include every pixel touched by a polygon, not only those whose
        centre falls inside it.

    Yields
    ------
    GeofencedRaster
        One per polygon that overlaps the raster. Polygons with no
        overlapping pixels are skipped.

    Raises
    ------
    ValueError
        If the raster lacks the spatial metadata needed to apply a
        vector.
    """
    raster_crs = filtered_raster.profile.get("crs")
    raster_transform = filtered_raster.profile.get("transform")
    height = filtered_raster.profile.get("height")
    width = filtered_raster.profile.get("width")

    if raster_crs is None:
        raise ValueError(
            f"Filtered raster has no CRS: {filtered_raster.record.path}"
        )
    if raster_transform is None or height is None or width is None:
        raise ValueError(
            "Filtered raster has incomplete spatial metadata: "
            f"{filtered_raster.record.path}"
        )

    for feature in vector_layer.features:
        raster_geometry = transform_geom(
            vector_layer.crs,
            raster_crs,
            feature.geometry,
        )
        inside_polygon = geometry_mask(
            [raster_geometry],
            out_shape=(height, width),
            transform=raster_transform,
            invert=True,
            all_touched=all_touched,
        )
        outside_polygon = np.broadcast_to(
            ~inside_polygon[np.newaxis, :, :],
            filtered_raster.filtered_bands.shape,
        )

        yield GeofencedRaster(
            source=filtered_raster,
            feature_id=feature.feature_id,
            properties=feature.properties.copy(),
            masked_bands=np.ma.masked_where(
                outside_polygon,
                filtered_raster.filtered_bands,
            ),
            polygon_pixel_count=int(inside_polygon.sum()),
            vector_path=vector_layer.path,
        )




Yield polygon regions, or one whole region per raster.

Parameters:

Name Type Description Default
filtered_rasters iterable of FilteredFluxRaster

Rasters to geofence.

required
vector_path Path

Polygon vector file. When None (default) each raster is yielded whole, as a single region with feature_id 0.

None
id_field str

Vector attribute identifying each polygon.

None
all_touched bool

Include every pixel touched by a polygon.

False

Yields:

Type Description
GeofencedRaster

One per raster and polygon, or one per raster when no vector is given.

Examples:

With no vector, each raster passes through as a single whole region:

>>> rasters = [_example_raster("20260101")]
>>> regions = list(iter_geofenced_rasters(rasters))
>>> len(regions)
1
>>> regions[0].feature_id
'whole_raster'
>>> regions[0].masked_bands.shape
(48, 1, 1)
Source code in src/fluxmappy/def_stat_mask.py
 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
def iter_geofenced_rasters(
    filtered_rasters: Iterable[FilteredFluxRasterLike],
    vector_path: Path | None = None,
    id_field: str | None = None,
    all_touched: bool = False,
) -> Iterator[GeofencedRaster]:
    """Yield polygon regions, or one whole region per raster.

    Parameters
    ----------
    filtered_rasters : iterable of FilteredFluxRaster
        Rasters to geofence.
    vector_path : pathlib.Path, optional
        Polygon vector file. When ``None`` (default) each raster is
        yielded whole, as a single region with ``feature_id`` 0.
    id_field : str, optional
        Vector attribute identifying each polygon.
    all_touched : bool, default False
        Include every pixel touched by a polygon.

    Yields
    ------
    GeofencedRaster
        One per raster and polygon, or one per raster when no vector is
        given.

    Examples
    --------
    With no vector, each raster passes through as a single whole region:

    >>> rasters = [_example_raster("20260101")]
    >>> regions = list(iter_geofenced_rasters(rasters))
    >>> len(regions)
    1
    >>> regions[0].feature_id
    'whole_raster'
    >>> regions[0].masked_bands.shape
    (48, 1, 1)
    """
    if vector_path is None:
        if id_field is not None:
            raise ValueError("id_field requires a vector_path")
        for filtered_raster in filtered_rasters:
            spatial_shape = filtered_raster.filtered_bands.shape[-2:]
            yield GeofencedRaster(
                source=filtered_raster,
                feature_id="whole_raster",
                properties={},
                masked_bands=filtered_raster.filtered_bands.copy(),
                polygon_pixel_count=int(np.prod(spatial_shape)),
                vector_path=None,
            )
        return

    vector_layer = read_vector_layer(vector_path, id_field=id_field)
    for filtered_raster in filtered_rasters:
        yield from geofence_raster(
            filtered_raster,
            vector_layer,
            all_touched=all_touched,
        )




def_stat_calc

Calculate spatial statistics for one masked or whole raster.

Reduces a region's pixels to summary values, either per half-hourly band or collapsed to a single daily layer first.

Parameters:

Name Type Description Default
region GeofencedRaster

Raster already masked to a polygon, or kept whole.

required
product (half - hourly, daily)

Temporal resolution. "half-hourly" returns one value per band; "daily" averages the bands first and returns scalars.

"half-hourly"

Returns:

Type Description
PolygonStatistics

Holding count, mean, minimum, maximum and standard_deviation. These are 48-element arrays for "half-hourly" and Python scalars for "daily".

Raises:

Type Description
ValueError

If product is neither "half-hourly" nor "daily".

Notes

standard_deviation is computed across the spatial axes, so it describes variation between pixels within the region at each timestep.

Examples:

A 2x2 region with two half-hourly bands:

>>> region = _example_region()
>>> stats = calculate_region_statistics(region, product="half-hourly")
>>> stats.mean
array([2.5, 6.5])
>>> stats.minimum
array([1., 5.])
>>> stats.count
array([4, 4])

Collapsing the bands to one daily layer instead:

>>> daily = calculate_region_statistics(region, product="daily")
>>> float(daily.mean)
4.5
>>> daily.product
'daily'
Source code in src/fluxmappy/def_stat_calc.py
 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
102
103
104
105
106
107
108
109
110
def calculate_region_statistics(
    region: GeofencedRaster,
    product: str = "half-hourly",
) -> PolygonStatistics:
    """Calculate spatial statistics for one masked or whole raster.

    Reduces a region's pixels to summary values, either per half-hourly
    band or collapsed to a single daily layer first.

    Parameters
    ----------
    region : GeofencedRaster
        Raster already masked to a polygon, or kept whole.
    product : {"half-hourly", "daily"}, default "half-hourly"
        Temporal resolution. ``"half-hourly"`` returns one value per
        band; ``"daily"`` averages the bands first and returns scalars.

    Returns
    -------
    PolygonStatistics
        Holding ``count``, ``mean``, ``minimum``, ``maximum`` and
        ``standard_deviation``. These are 48-element arrays for
        ``"half-hourly"`` and Python scalars for ``"daily"``.

    Raises
    ------
    ValueError
        If ``product`` is neither ``"half-hourly"`` nor ``"daily"``.

    Notes
    -----
    ``standard_deviation`` is computed across the spatial axes, so it
    describes variation between pixels within the region at each
    timestep.

    Examples
    --------
    A 2x2 region with two half-hourly bands:

    >>> region = _example_region()
    >>> stats = calculate_region_statistics(region, product="half-hourly")
    >>> stats.mean
    array([2.5, 6.5])
    >>> stats.minimum
    array([1., 5.])
    >>> stats.count
    array([4, 4])

    Collapsing the bands to one daily layer instead:

    >>> daily = calculate_region_statistics(region, product="daily")
    >>> float(daily.mean)
    4.5
    >>> daily.product
    'daily'
    """
    if product in {"half-hourly", "half_hourly"}:
        values = region.masked_bands
        product_name = "half-hourly"
    elif product == "daily":
        values = region.daily_mean[np.newaxis, ...]
        product_name = "daily"
    else:
        raise ValueError("product must be 'half-hourly' or 'daily'")

    axes = (-2, -1)
    count = np.asarray(np.ma.count(values, axis=axes), dtype=int)
    mean = _filled_statistic(np.ma.mean(values, axis=axes))
    minimum = _filled_statistic(np.ma.min(values, axis=axes))
    maximum = _filled_statistic(np.ma.max(values, axis=axes))
    standard_deviation = _filled_statistic(np.ma.std(values, axis=axes))

    if product_name == "daily":
        count_output: np.ndarray | int = int(count[0])
        mean_output: np.ndarray | float = float(mean[0])
        minimum_output: np.ndarray | float = float(minimum[0])
        maximum_output: np.ndarray | float = float(maximum[0])
        deviation_output: np.ndarray | float = float(standard_deviation[0])
    else:
        count_output = count
        mean_output = mean
        minimum_output = minimum
        maximum_output = maximum
        deviation_output = standard_deviation

    return PolygonStatistics(
        feature_id=region.feature_id,
        properties=region.properties.copy(),
        site=region.source.record.site,
        flux_type=region.source.record.flux_type,
        date=region.source.record.date,
        product=product_name,
        count=count_output,
        mean=mean_output,
        minimum=minimum_output,
        maximum=maximum_output,
        standard_deviation=deviation_output,
    )




def_stat_iter

Yield spatial statistics one region at a time.

The streaming form behind :func:~fluxmappy.wrap_stat, which collects the results into a list. Unlike wrap_stat, vector must already be a :class:~pathlib.Path.

Parameters:

Name Type Description Default
filtered_rasters iterable of FilteredFluxRaster

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

required
vector 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 one value per band; "daily" first averages the bands into a single daily layer.

"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

Yields:

Type Description
PolygonStatistics

One entry per raster and region.

See Also

wrap_stat : Collect the same statistics into a list.

Examples:

>>> from fluxmappy.wrap_stat import _example_raster
>>> rasters = [_example_raster(d) for d in ("20260101", "20260102")]
>>> stats = list(iter_polygon_statistics(rasters, product="daily"))
>>> len(stats)
2
>>> float(stats[0].mean)
23.5
Source code in src/fluxmappy/def_stat_iter.py
11
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
def iter_polygon_statistics(
    filtered_rasters: Iterable[FilteredFluxRasterLike],
    vector: Path | None = None,
    product: str = "half-hourly",
    id_field: str | None = None,
    all_touched: bool = False,
) -> Iterator[PolygonStatistics]:
    """Yield spatial statistics one region at a time.

    The streaming form behind :func:`~fluxmappy.wrap_stat`, which collects
    the results into a list. Unlike ``wrap_stat``, ``vector`` must already
    be a :class:`~pathlib.Path`.

    Parameters
    ----------
    filtered_rasters : iterable of FilteredFluxRaster
        Quality-filtered rasters, typically the output of
        :func:`~fluxmappy.wrap_filt_qf`.
    vector : 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
        one value per band; ``"daily"`` first averages the bands into a
        single daily layer.
    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.

    Yields
    ------
    PolygonStatistics
        One entry per raster and region.

    See Also
    --------
    wrap_stat : Collect the same statistics into a list.

    Examples
    --------
    >>> from fluxmappy.wrap_stat import _example_raster
    >>> rasters = [_example_raster(d) for d in ("20260101", "20260102")]
    >>> stats = list(iter_polygon_statistics(rasters, product="daily"))
    >>> len(stats)
    2
    >>> float(stats[0].mean)
    23.5
    """
    for region in iter_geofenced_rasters(
        filtered_rasters=filtered_rasters,
        vector_path=vector,
        id_field=id_field,
        all_touched=all_touched,
    ):
        yield calculate_region_statistics(region, product=product)