Spaces:
Running

File size: 4,923 Bytes
d1ffd83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Create fold-specific PCA tile sets using training tiles only."""

from __future__ import annotations

import argparse
import csv
import json
from pathlib import Path

import numpy as np
import rasterio
from sklearn.decomposition import PCA


def split_image_names(path: Path) -> list[str]:
    with path.open(encoding="utf-8") as handle:
        reader = csv.DictReader(handle, delimiter="\t")
        return [row["image_file"] for row in reader]


def read_training_samples(paths: list[Path], max_samples: int, seed: int) -> tuple[np.ndarray, np.ndarray]:
    rng = np.random.default_rng(seed)
    samples: list[np.ndarray] = []
    valid_total = 0
    for path in paths:
        with rasterio.open(path) as source:
            image = source.read().astype(np.float32, copy=False)
            nodata = source.nodata
        spectra = image.reshape(image.shape[0], -1).T
        valid = np.isfinite(spectra).all(axis=1)
        if nodata is not None:
            valid &= np.any(spectra != nodata, axis=1)
        valid_indices = np.flatnonzero(valid)
        valid_total += int(valid_indices.size)
        if valid_indices.size == 0:
            continue
        take = min(valid_indices.size, max_samples // max(len(paths), 1))
        chosen = rng.choice(valid_indices, size=take, replace=False)
        samples.append(spectra[chosen])
    if not samples:
        raise ValueError("No valid spectra were found in the training tiles.")
    fit = np.concatenate(samples, axis=0)
    if len(fit) > max_samples:
        fit = fit[rng.choice(len(fit), size=max_samples, replace=False)]
    means = np.nanmean(fit, axis=0).astype(np.float32)
    fit = np.where(np.isfinite(fit), fit, means)
    return fit, np.array([valid_total], dtype=np.int64)


def transform_tile(source_path: Path, destination_path: Path, pca: PCA, means: np.ndarray) -> None:
    with rasterio.open(source_path) as source:
        profile = source.profile.copy()
        image = source.read().astype(np.float32, copy=False)
        nodata = source.nodata
    height, width = image.shape[1:]
    spectra = image.reshape(image.shape[0], -1).T
    valid = np.isfinite(spectra).all(axis=1)
    if nodata is not None:
        valid &= np.any(spectra != nodata, axis=1)
    spectra = np.where(np.isfinite(spectra), spectra, means)
    transformed = pca.transform(spectra).astype(np.float32, copy=False)
    transformed[~valid] = 0
    profile.update(driver="ENVI", count=pca.n_components, dtype="float32", nodata=0)
    destination_path.parent.mkdir(parents=True, exist_ok=True)
    with rasterio.open(destination_path, "w", **profile) as destination:
        destination.write(transformed.T.reshape(pca.n_components, height, width))


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--source-dir", type=Path, required=True)
    parser.add_argument("--split-dir", type=Path, required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--components", type=int, choices=(3, 10), default=10)
    parser.add_argument("--max-fit-samples", type=int, default=143_998)
    args = parser.parse_args()

    all_paths = sorted(args.source_dir.glob("*.dat"))
    if not all_paths:
        raise FileNotFoundError(f"No ENVI .dat tiles found in {args.source_dir}")
    by_name = {path.name: path for path in all_paths}
    for fold in range(3):
        train_names = split_image_names(args.split_dir / f"block_{fold}_train_tiles.txt")
        train_paths = [by_name[name] for name in train_names]
        fit, valid_total = read_training_samples(train_paths, args.max_fit_samples, 42 + fold)
        pca = PCA(n_components=args.components, svd_solver="randomized", random_state=42 + fold)
        pca.fit(fit)
        fold_dir = args.output_dir / f"fold_{fold}"
        fold_dir.mkdir(parents=True, exist_ok=True)
        for source_path in all_paths:
            transform_tile(source_path, fold_dir / source_path.name, pca, pca.mean_.astype(np.float32))
        np.savez(
            fold_dir / "pca_model.npz",
            components=pca.components_,
            mean=pca.mean_,
            explained_variance_ratio=pca.explained_variance_ratio_,
        )
        (fold_dir / "pca_metadata.json").write_text(
            json.dumps(
                {
                    "fit_tile_count": len(train_paths),
                    "fit_sample_count": len(fit),
                    "observed_valid_pixels": int(valid_total[0]),
                    "components": args.components,
                    "source_dir": str(args.source_dir),
                },
                indent=2,
            )
            + "\n",
            encoding="utf-8",
        )
        print(
            f"fold {fold}: fitted PCA-{args.components} on {len(train_paths)} training tiles "
            f"and wrote {len(all_paths)} PCA tiles"
        )


if __name__ == "__main__":
    main()