Spaces:
Running
Running
Download workflow/scripts/generate_fold_specific_pca10.py from lauransotomayor/hyperFVC: direct link, hf CLI and curl.
- Browser
- Download file 4.92 kB
-
https://huggingface.co/spaces/lauransotomayor/hyperFVC/resolve/main/workflow/scripts/generate_fold_specific_pca10.py
- Command line
-
hf download hf://spaces/lauransotomayor/hyperFVC/workflow/scripts/generate_fold_specific_pca10.py
-
curl -L -o generate_fold_specific_pca10.py https://huggingface.co/spaces/lauransotomayor/hyperFVC/resolve/main/workflow/scripts/generate_fold_specific_pca10.py
4.92 kB
| #!/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() | |