File size: 11,810 Bytes
3656aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
"""Image checks, resize, train-only normalization, and train-only augmentation.

Southern Hemisphere frames stay as stored. ``leave_unflipped`` records a
hemisphere label and does not mirror the array.
"""

from __future__ import annotations

from dataclasses import dataclass

import numpy as np
from PIL import Image

from src.config import parse_image_size
from src.splits import LeakageError

# A missing-pixel fraction above this value fails closed. It does not warn.
MAX_MISSING_FRACTION = 0.30


@dataclass(frozen=True)
class NormStats:
    mean: float
    std: float
    source_split: str


# Pixel units stay on the dataset that produced them. NASA chips are 8-bit
# counts. TCIR IR1 is brightness temperature in kelvin. They are never
# pooled into one mean and std. A later dataset gets its own entry.
PIXEL_KIND = {
    "nasa": "uint8",
    "tcir": "brightness_temperature_k",
    "incyde": "jpeg_uncalibrated",
    "smoke": "synthetic",
}


def pixel_kind(dataset: str) -> str:
    """Unit label for one dataset. Unknown datasets stay unspecified."""
    return PIXEL_KIND.get(str(dataset).strip().lower(), "unspecified")


def norm_by_dataset(dataset: str, stats: NormStats) -> dict:
    """One dataset's train-split stats. The map has that key only."""
    if stats.source_split != "train":
        raise LeakageError("normalization stats may be fit on the train split only")
    name = str(dataset).strip().lower()
    if not name:
        raise ValueError("dataset name is required for normalization stats")
    return {
        name: {
            "mean": float(stats.mean),
            "std": float(stats.std),
            "source_split": "train",
            "pixel_kind": pixel_kind(name),
        }
    }


def norm_stats_from_checkpoint(payload: dict) -> NormStats:
    """Stats for the checkpoint's own dataset. Mixed maps are refused.

    A checkpoint written before per-dataset stats still uses ``norm_mean``
    and ``norm_std``. A map with two datasets, or a key that is not the
    checkpoint dataset, is not applied.
    """
    grouped = payload.get("norm_by_dataset")
    dataset = payload.get("dataset")
    if isinstance(grouped, dict) and grouped:
        if len(grouped) != 1:
            raise ValueError(
                "checkpoint mixes normalization stats across datasets; refusing to apply them"
            )
        name = None if dataset is None else str(dataset)
        if name not in grouped:
            raise ValueError(
                "checkpoint norm_by_dataset does not match the checkpoint dataset; "
                "refusing to mix normalization stats"
            )
        entry = grouped[name]
        if str(entry.get("source_split")) != "train":
            raise ValueError("checkpoint normalization was not fit on train")
        return NormStats(
            mean=float(entry["mean"]),
            std=float(entry["std"]),
            source_split="train",
        )
    if "norm_mean" not in payload or "norm_std" not in payload:
        raise ValueError("checkpoint is missing normalization stats")
    source = payload.get("norm_source_split")
    if source is not None and str(source) != "train":
        raise ValueError("checkpoint normalization was not fit on train")
    return NormStats(
        mean=float(payload["norm_mean"]),
        std=float(payload["norm_std"]),
        source_split="train",
    )


def as_channel_first(image: np.ndarray) -> np.ndarray:
    array = np.asarray(image, dtype=np.float32)
    if array.ndim == 2:
        return array[None, ...]
    if array.ndim != 3:
        raise ValueError(f"expected a 2D or 3D image, got {array.shape}")
    if array.shape[0] <= 4 and array.shape[1] > 4 and array.shape[2] > 4:
        return array
    if array.shape[-1] <= 4:
        return np.moveaxis(array, -1, 0)
    raise ValueError(f"cannot infer the channel axis for shape {array.shape}")


def missing_fraction(image: np.ndarray) -> float:
    return float((~np.isfinite(image)).mean())


def fit_norm_stats(images: list[np.ndarray], source_split: str) -> NormStats:
    """Fit mean and std. Refuses anything other than the train split."""
    if source_split != "train":
        raise LeakageError("normalization stats may be fit on the train split only")
    if not images:
        raise ValueError("need at least one train image")
    values = [np.asarray(image, dtype=np.float32) for image in images]
    finite = np.concatenate([image[np.isfinite(image)].ravel() for image in values])
    if finite.size == 0:
        raise ValueError("train images have no finite pixels")
    std = float(finite.std())
    if std < 1e-6:
        std = 1.0
    return NormStats(mean=float(finite.mean()), std=std, source_split=source_split)


def stack_prepared(images: list[np.ndarray]) -> np.ndarray:
    """Stack chips that have already been prepared.

    A native ``image_size`` does not resize, so every chip in the stack
    must already share a height and width.
    """
    if not images:
        raise ValueError("no images to stack")
    try:
        return np.stack(images)
    except ValueError as exc:
        shapes = sorted({tuple(np.shape(image)) for image in images})
        raise ValueError(
            "prepared chips do not share a height and width "
            f"{shapes}. A native image_size does not resize them onto one grid."
        ) from exc


def _resize(image: np.ndarray, size: int) -> np.ndarray:
    channels = []
    for channel in image:
        picture = Image.fromarray(channel.astype(np.float32), mode="F")
        picture = picture.resize((size, size), Image.Resampling.BILINEAR)
        channels.append(np.asarray(picture, dtype=np.float32))
    return np.stack(channels, axis=0)


def prepare_image(
    image: np.ndarray,
    image_size: int | str | None,
    stats: NormStats | None,
    max_missing_fraction: float = MAX_MISSING_FRACTION,
) -> np.ndarray:
    """Return ``(C, H, W)`` float32. Does not invent brightness temperature.

    ``image_size`` ``None`` or ``native`` keeps the chip's height and width.
    An integer resizes to that square. ``max_missing_fraction`` is
    ``data.max_missing_fraction`` when the caller has a config.
    A missing-pixel fraction above ``max_missing_fraction`` raises. Raw
    digital numbers stay pixel values; this function does not name them Tb.
    """
    array = as_channel_first(image)
    fraction = missing_fraction(array)
    if fraction > max_missing_fraction:
        raise ValueError(
            f"missing fraction {fraction:.2f} exceeds {max_missing_fraction:.2f}"
        )
    filled = array.copy()
    for index in range(filled.shape[0]):
        finite = np.isfinite(filled[index])
        fill = float(np.median(filled[index][finite])) if finite.any() else 0.0
        filled[index][~finite] = fill
    side = parse_image_size(image_size)
    output = filled if side is None else _resize(filled, side)
    if stats is not None:
        output = (output - stats.mean) / stats.std
    return output


def dn_to_brightness_temperature(dn: np.ndarray, gain: float, offset: float) -> np.ndarray:
    """Apply a caller-supplied calibration. This does not look up a sensor table."""
    return np.asarray(dn, dtype=np.float32) * float(gain) + float(offset)


def leave_unflipped(image: np.ndarray, hemisphere: str | None = None) -> np.ndarray:
    """Use the frame as stored.

    Southern Hemisphere TCIR imagery is not mirrored. ``hemisphere`` records
    the caller's label and does not change the array.
    """
    del hemisphere
    return np.asarray(image)


def as_grey_plane(image: np.ndarray) -> np.ndarray:
    """One plane. Identical RGB channels collapse. Differing channels raise.

    PIL JPEGs are often ``(H, W, C)`` even when every channel is the same
    grey IR value. A leading singleton channel is accepted too.
    """
    array = np.asarray(image, dtype=np.float32)
    if array.ndim == 2:
        return array
    if array.ndim != 3:
        raise ValueError(f"expected one grey plane, got {array.shape}")
    channel_last = (
        array.shape[-1] <= 4
        and array.shape[0] > array.shape[-1]
        and array.shape[1] > array.shape[-1]
    )
    channel_first = (
        array.shape[0] <= 4
        and array.shape[1] > array.shape[0]
        and array.shape[2] > array.shape[0]
    )
    if channel_last:
        count = int(array.shape[-1])
        if count == 1 or all(np.array_equal(array[..., 0], array[..., index]) for index in range(1, count)):
            return array[..., 0]
        raise ValueError(f"expected grey IR, channels differ, shape {array.shape}")
    if channel_first:
        count = int(array.shape[0])
        if count == 1 or all(np.array_equal(array[0], array[index]) for index in range(1, count)):
            return array[0]
        raise ValueError(f"expected grey IR, channels differ, shape {array.shape}")
    raise ValueError(f"expected grey IR, got {array.shape}")


def rotate_with_circular_mask(image: np.ndarray, angle_deg: float) -> np.ndarray:
    """Rotate about the centre and drop pixels outside the inscribed circle.

    There is no flip. A square rotation otherwise paints the corners from
    empty space, and those bars must not enter training. The disk of
    diameter equal to the short side stays inside the original chip for
    any angle, so the kept pixels are source pixels. Outside the disk the
    values are NaN. Callers that already normalized fill those NaNs with 0.
    Channel-last grey JPEGs are accepted and returned as one plane.
    """
    plane = as_grey_plane(image)
    finite = np.isfinite(plane)
    filled = plane.copy()
    filled[~finite] = 0.0
    picture = Image.fromarray(filled, mode="F")
    rotated = np.asarray(
        picture.rotate(
            float(angle_deg),
            resample=Image.Resampling.BILINEAR,
            fillcolor=0.0,
        ),
        dtype=np.float32,
    )
    height, width = rotated.shape
    yy, xx = np.ogrid[:height, :width]
    center_y = (height - 1) / 2.0
    center_x = (width - 1) / 2.0
    radius = min(height, width) / 2.0
    disk = (yy - center_y) ** 2 + (xx - center_x) ** 2 <= radius**2
    out = rotated.copy()
    out[~disk] = np.nan
    return out


def prepare_training_chip(
    image: np.ndarray,
    image_size: int | str | None,
    angle: float | None,
    stats: NormStats | None,
    max_missing_fraction: float = MAX_MISSING_FRACTION,
) -> np.ndarray:
    """Prepare one training chip, then optionally rotate on that grid.

    The missing-pixel gate sees the source image, before the circular mask.
    A configured square resize happens first, so the mask is the inscribed
    circle of the training grid (about a fifth of the square) and not the
    corners of a wide native crop. Masked pixels are 0 after normalization,
    which is the training mean, not a black bar.
    """
    prepared = prepare_image(as_grey_plane(image), image_size, stats, max_missing_fraction)
    if angle is None:
        return prepared
    masked = rotate_with_circular_mask(prepared, float(angle))
    if masked.ndim == 2:
        masked = masked[None, ...]
    return np.where(np.isfinite(masked), masked, np.float32(0.0)).astype(np.float32)


def augment_image(image: np.ndarray, split: str, rng: np.random.Generator) -> np.ndarray:
    """Flip or rotate a train image. Refuses every other split.

    Classical features do not call this. A later training loop may, and only
    on rows whose split is ``train``.
    """
    if split != "train":
        raise LeakageError("augmentation is allowed on the train split only")
    array = as_channel_first(image)
    choice = int(rng.integers(0, 3))
    if choice == 0:
        return np.flip(array, axis=-1).copy()
    if choice == 1:
        return np.rot90(array, k=1, axes=(-2, -1)).copy()
    return array.copy()