File size: 6,657 Bytes
7aae553
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
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
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
#!/usr/bin/env python3
"""Deterministic finite-nodata GeoTIFF conversions used by C10."""

from __future__ import annotations

import os
from pathlib import Path
from typing import Any

import numpy as np
import rasterio


S1_PORTABLE_NODATA = -9999.0
BINARY_PORTABLE_NODATA = 255


def valid_pixels(data: np.ndarray, nodata: float | int | None) -> np.ndarray:
    """Return pixels valid in every band, including a finite nodata value."""
    bands = data if data.ndim == 3 else data[np.newaxis, ...]
    valid = np.logical_and.reduce([np.isfinite(band) for band in bands])
    if nodata is not None and np.isfinite(float(nodata)):
        valid &= np.logical_and.reduce([band != float(nodata) for band in bands])
    return valid


def _copy_tags(source: rasterio.io.DatasetReader, target: rasterio.io.DatasetWriter) -> None:
    target.update_tags(**source.tags())
    for index in range(1, source.count + 1):
        target.update_tags(index, **source.tags(index))
        if source.descriptions[index - 1]:
            target.set_band_description(index, source.descriptions[index - 1])


def _atomic_raster_write(destination: Path, writer: Any) -> None:
    destination.parent.mkdir(parents=True, exist_ok=True)
    temporary = destination.with_name(f".{destination.stem}.tmp.{os.getpid()}{destination.suffix}")
    try:
        writer(temporary)
        os.replace(temporary, destination)
    finally:
        if temporary.exists():
            temporary.unlink()


def write_portable_s1(source: Path, destination: Path) -> dict[str, Any]:
    """Preserve finite S1 values and encode invalid pixels as finite -9999."""
    source = source.resolve()
    destination = destination.resolve()
    with rasterio.open(source) as dataset:
        data = dataset.read().astype("float32")
        valid = valid_pixels(data, dataset.nodata)
        if np.any(data[:, valid] == S1_PORTABLE_NODATA):
            raise ValueError(f"valid source pixels collide with {S1_PORTABLE_NODATA}: {source}")
        converted = data.copy()
        converted[:, ~valid] = S1_PORTABLE_NODATA
        profile = dataset.profile.copy()
        profile.update(dtype="float32", nodata=S1_PORTABLE_NODATA, compress="deflate", predictor=3)

        def writer(path: Path) -> None:
            with rasterio.open(path, "w", **profile) as output:
                output.write(converted)
                _copy_tags(dataset, output)

        _atomic_raster_write(destination, writer)
        return {
            "bands": int(dataset.count),
            "height": int(dataset.height),
            "width": int(dataset.width),
            "valid_spatial_pixels": int(valid.sum()),
            "invalid_spatial_pixels": int(valid.size - valid.sum()),
            "source_nodata": str(dataset.nodata),
            "portable_nodata": S1_PORTABLE_NODATA,
        }


def verify_portable_s1(source: Path, destination: Path) -> dict[str, Any]:
    """Prove a portable S1 raster is a value-preserving source derivative."""
    if not destination.is_file():
        raise FileNotFoundError(destination)
    with rasterio.open(source) as upstream, rasterio.open(destination) as portable:
        original = upstream.read().astype("float32")
        derived = portable.read().astype("float32")
        valid = valid_pixels(original, upstream.nodata)
        if original.shape != derived.shape:
            raise ValueError(f"shape mismatch: {source} vs {destination}")
        if portable.nodata != S1_PORTABLE_NODATA:
            raise ValueError(f"unexpected portable nodata {portable.nodata}: {destination}")
        if upstream.crs != portable.crs or upstream.transform != portable.transform:
            raise ValueError(f"georeferencing mismatch: {source} vs {destination}")
        if not np.array_equal(original[:, valid], derived[:, valid]):
            raise ValueError(f"valid values changed: {source} vs {destination}")
        if not np.all(derived[:, ~valid] == S1_PORTABLE_NODATA):
            raise ValueError(f"invalid values were not normalized: {destination}")
        return {
            "valid_spatial_pixels": int(valid.sum()),
            "invalid_spatial_pixels": int(valid.size - valid.sum()),
            "valid_values_identical": True,
            "georeferencing_identical": True,
            "nodata": S1_PORTABLE_NODATA,
        }


def normalize_binary_mask_in_place(path: Path) -> dict[str, Any]:
    """Convert one binary mask to uint8 0/1 with nodata 255, preserving validity."""
    path = path.resolve()
    with rasterio.open(path) as dataset:
        if dataset.count != 1:
            raise ValueError(f"binary mask must have one band: {path}")
        source = dataset.read(1)
        valid = valid_pixels(source, dataset.nodata)
        positive = valid & (source > 0)
        converted = np.full(source.shape, BINARY_PORTABLE_NODATA, dtype="uint8")
        converted[valid] = positive[valid].astype("uint8")
        profile = dataset.profile.copy()
        profile.update(
            dtype="uint8",
            count=1,
            nodata=BINARY_PORTABLE_NODATA,
            compress="deflate",
            predictor=2,
        )
        source_nodata = dataset.nodata

        def writer(destination: Path) -> None:
            with rasterio.open(destination, "w", **profile) as output:
                output.write(converted, 1)
                _copy_tags(dataset, output)

        _atomic_raster_write(path, writer)
        return {
            "valid_pixels": int(valid.sum()),
            "invalid_pixels": int(valid.size - valid.sum()),
            "positive_pixels": int(positive.sum()),
            "source_nodata": str(source_nodata),
            "portable_nodata": BINARY_PORTABLE_NODATA,
        }


def verify_portable_binary_mask(path: Path) -> dict[str, Any]:
    with rasterio.open(path) as dataset:
        values = dataset.read(1)
        if dataset.count != 1 or dataset.dtypes[0] != "uint8":
            raise ValueError(f"portable binary raster must be one uint8 band: {path}")
        if dataset.nodata != BINARY_PORTABLE_NODATA:
            raise ValueError(f"unexpected binary nodata {dataset.nodata}: {path}")
        unique = set(int(value) for value in np.unique(values))
        if not unique <= {0, 1, BINARY_PORTABLE_NODATA}:
            raise ValueError(f"non-binary values {sorted(unique)}: {path}")
        valid = values != BINARY_PORTABLE_NODATA
        return {
            "valid_pixels": int(valid.sum()),
            "invalid_pixels": int(valid.size - valid.sum()),
            "positive_pixels": int((values == 1).sum()),
            "values": sorted(unique),
            "nodata": BINARY_PORTABLE_NODATA,
        }