anondatasets commited on
Commit
03d3c0c
·
verified ·
1 Parent(s): d160794

Update experiments code - 2025-09-25T15:16:05.109591

Browse files
light_subspace_removal/.DS_Store ADDED
Binary file (6.15 kB). View file
 
light_subspace_removal/sbatch/train_vpct_spatial_cv.sbatch ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ #SBATCH --job-name=chm_cv_vpct_spatial
3
+ #SBATCH --partition=general
4
+ #SBATCH --gres=gpu:A6000:1
5
+ #SBATCH --cpus-per-task=8
6
+ #SBATCH --mem=32G
7
+ #SBATCH --time=24:00:00
8
+ #SBATCH --array=0-7%8
9
+ #SBATCH --output=/home/anonymous/logs/light_subspace_removal/%x_%A_%a.out
10
+ #SBATCH --error=/home/anonymous/logs/light_subspace_removal/%x_%A_%a.err
11
+
12
+ cd /home/anonymous/imageomics-2025
13
+
14
+ # Env
15
+ source ~/.bashrc
16
+ mamba activate light-stable
17
+
18
+ export PYTHONUNBUFFERED=1
19
+
20
+ # Grid parameters (spatial-only CV with variance targets)
21
+ TOTAL_CONFIGS=110 # 11 var levels × 5 folds × 2 model_configs
22
+ TOTAL_JOBS=8 # matches --array 0-7
23
+ OUT_SIZE=224 # supervision size (must be integer multiple of token grid)
24
+
25
+ echo "Node: $(hostname)"
26
+ echo "CUDA_VISIBLE_DEVICES=${CUDA_VISIBLE_DEVICES:-unset}"
27
+ echo "Job ${SLURM_ARRAY_TASK_ID}/${TOTAL_JOBS} over ${TOTAL_CONFIGS} configs"
28
+
29
+ # Run
30
+ python -u light_subspace_removal/scripts/train_vpct_spatial_cv.py \
31
+ --job_id ${SLURM_ARRAY_TASK_ID} \
32
+ --total_jobs ${TOTAL_JOBS} \
33
+ --total_configs ${TOTAL_CONFIGS} \
34
+ --outdir results/light_subspace_removal \
35
+ --epochs 50 \
36
+ --batch_size 32 \
37
+ --out_size ${OUT_SIZE}
light_subspace_removal/scripts/.DS_Store ADDED
Binary file (6.15 kB). View file
 
light_subspace_removal/scripts/aggregate_cv_results.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Aggregate spatial 5-fold CV results into side-by-side model comparison plots.
4
+
5
+ Directory structure expected:
6
+ results/{model_config}/simple_decoder/cv_s{fold}_v{vvv}.json
7
+ where vvv is zero-padded integer percent (e.g., 000, 005, 010, 025, 050, 100)
8
+
9
+ Each JSON should include:
10
+ - val_rmse_history (list[float])
11
+ - var_pct_target (float)
12
+ - k_chosen (int)
13
+ - cum_evr_at_k (float)
14
+ """
15
+
16
+ import argparse, json, os, glob
17
+ import numpy as np
18
+ import matplotlib.pyplot as plt
19
+ from scipy import stats
20
+ from pathlib import Path
21
+
22
+ # --------------------------
23
+ # IO
24
+ # --------------------------
25
+ def _safe_load_json(path):
26
+ try:
27
+ with open(path, "r") as f:
28
+ return json.load(f)
29
+ except Exception as e:
30
+ print(f"Error loading {path}: {e}")
31
+ return None
32
+
33
+ def load_results_for_model(base_dir, model_config):
34
+ """
35
+ Returns: dict[var_pct] -> list[result_dict]
36
+ """
37
+ model_dir = os.path.join(base_dir, model_config, "simple_decoder")
38
+ if not os.path.exists(model_dir):
39
+ print(f"Directory not found: {model_dir}")
40
+ return {}
41
+
42
+ # New naming: cv_s{fold}_v{vvv}.json
43
+ paths = sorted(glob.glob(os.path.join(model_dir, "cv_s*_v*.json")))
44
+ if not paths:
45
+ print(f"No result files found in {model_dir}")
46
+ return {}
47
+
48
+ print(f"Found {len(paths)} result files for {model_config}/simple_decoder")
49
+
50
+ by_var = {}
51
+ for p in paths:
52
+ r = _safe_load_json(p)
53
+ if not r:
54
+ continue
55
+ if "val_rmse_history" not in r:
56
+ print(f"Warning: {p} missing val_rmse_history, skipping")
57
+ continue
58
+
59
+ # Prefer explicit field; fallback to filename parse if needed
60
+ if "var_pct_target" in r:
61
+ vp = float(r["var_pct_target"])
62
+ else:
63
+ # Fallback: parse ..._v{vvv}.json
64
+ stem = Path(p).stem
65
+ try:
66
+ vtag = stem.split("_v")[-1]
67
+ vp = float(int(vtag))
68
+ except Exception:
69
+ print(f"Warning: could not infer var_pct from {p}; skipping")
70
+ continue
71
+
72
+ by_var.setdefault(vp, []).append(r)
73
+
74
+ return by_var
75
+
76
+ # --------------------------
77
+ # CV metrics
78
+ # --------------------------
79
+ def compute_cv_metrics(fold_results):
80
+ """
81
+ Given a list of result dicts (one per fold), compute:
82
+ mean RMSE at the epoch minimizing the mean RMSE across folds,
83
+ plus 95% t-CI across folds at that epoch.
84
+ """
85
+ if not fold_results:
86
+ return None, None, None
87
+
88
+ histories = []
89
+ for r in fold_results:
90
+ h = r.get("val_rmse_history", [])
91
+ if h:
92
+ histories.append(h)
93
+
94
+ if not histories:
95
+ return None, None, None
96
+
97
+ min_len = min(len(h) for h in histories)
98
+ H = np.array([h[:min_len] for h in histories]) # [n_folds, n_epochs]
99
+ n_folds = H.shape[0]
100
+
101
+ mean_per_epoch = H.mean(axis=0)
102
+ best_epoch = int(np.argmin(mean_per_epoch))
103
+
104
+ fold_rmses = H[:, best_epoch]
105
+ mean_rmse = float(fold_rmses.mean())
106
+ std_rmse = float(fold_rmses.std(ddof=1)) if n_folds > 1 else 0.0
107
+
108
+ if n_folds > 1:
109
+ t_crit = stats.t.ppf(0.975, df=n_folds - 1)
110
+ margin = float(t_crit * std_rmse / np.sqrt(n_folds))
111
+ ci_lower, ci_upper = mean_rmse - margin, mean_rmse + margin
112
+ else:
113
+ ci_lower = ci_upper = mean_rmse
114
+
115
+ return mean_rmse, ci_lower, ci_upper
116
+
117
+ # --------------------------
118
+ # Plot
119
+ # --------------------------
120
+ def create_comparison_plot(dinov2_results, dinov3_results, output_path):
121
+ """
122
+ Combined comparison of DINOv2 vs DINOv3 across % variance removed.
123
+ X-axis: percent variance removed (0..100).
124
+ """
125
+ v2_keys = set(dinov2_results.keys()) if dinov2_results else set()
126
+ v3_keys = set(dinov3_results.keys()) if dinov3_results else set()
127
+ all_vps = sorted(v2_keys | v3_keys)
128
+
129
+ if not all_vps:
130
+ print("No variance-percent keys found; nothing to plot.")
131
+ return
132
+
133
+ vps = np.array(all_vps, dtype=float)
134
+
135
+ def collect(model_dict):
136
+ means, lows, ups = [], [], []
137
+ for vp in all_vps:
138
+ fr = model_dict.get(vp, [])
139
+ m, lo, up = compute_cv_metrics(fr)
140
+ means.append(np.nan if m is None else m)
141
+ lows.append(np.nan if lo is None else lo)
142
+ ups.append(np.nan if up is None else up)
143
+ return np.array(means), np.array(lows), np.array(ups)
144
+
145
+ v2_mean, v2_low, v2_up = collect(dinov2_results)
146
+ v3_mean, v3_low, v3_up = collect(dinov3_results)
147
+
148
+ fig, ax = plt.subplots(1, 1, figsize=(10, 6))
149
+
150
+ # DINOv2 - Python blue (C0)
151
+ mask2 = ~np.isnan(v2_mean)
152
+ if np.any(mask2):
153
+ ax.plot(vps[mask2], v2_mean[mask2], color='C0', linewidth=2, marker='o',
154
+ label='DINOv2-base')
155
+ ax.fill_between(vps[mask2], v2_low[mask2], v2_up[mask2], color='C0', alpha=0.25)
156
+
157
+ # DINOv3 - Python orange (C1)
158
+ mask3 = ~np.isnan(v3_mean)
159
+ if np.any(mask3):
160
+ ax.plot(vps[mask3], v3_mean[mask3], color='C1', linewidth=2, marker='o',
161
+ label='DINOv3-sat')
162
+ ax.fill_between(vps[mask3], v3_low[mask3], v3_up[mask3], color='C1', alpha=0.25)
163
+
164
+ ax.set_xlabel('Percent of lighting subspace variance removed')
165
+ ax.set_ylabel('Plant canopy height RMSE (cm)')
166
+ ax.grid(True, alpha=0.3)
167
+ ax.set_xlim(-2, 102)
168
+
169
+ # Set y-limits based on available data
170
+ if np.any(mask2) or np.any(mask3):
171
+ all_lows = []
172
+ all_ups = []
173
+ if np.any(mask2):
174
+ all_lows.extend(v2_low[mask2])
175
+ all_ups.extend(v2_up[mask2])
176
+ if np.any(mask3):
177
+ all_lows.extend(v3_low[mask3])
178
+ all_ups.extend(v3_up[mask3])
179
+
180
+ y_min = np.nanmin(all_lows)
181
+ y_max = np.nanmax(all_ups)
182
+ pad = 0.05 * (y_max - y_min) if y_max > y_min else 0.1
183
+ ax.set_ylim(y_min - pad, y_max + pad)
184
+
185
+ # Legend in lower left with Model title
186
+ legend = ax.legend(title='Model', loc='upper left', framealpha=0.9)
187
+ legend.get_title().set_fontweight('bold')
188
+
189
+ # Main title
190
+ plt.tight_layout()
191
+
192
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
193
+ plt.savefig(output_path, dpi=300, bbox_inches='tight')
194
+ plt.close()
195
+ print(f"Saved comparison plot: {output_path}")
196
+
197
+ # --------------------------
198
+ # Main
199
+ # --------------------------
200
+ def main():
201
+ parser = argparse.ArgumentParser(description="Aggregate spatial CV results into model comparison plots")
202
+ parser.add_argument("--results_dir", type=str, default="results/light_subspace_removal",
203
+ help="Base results directory")
204
+ parser.add_argument("--output_dir", type=str, default="plots",
205
+ help="Output directory for plots")
206
+ args = parser.parse_args()
207
+
208
+ model_configs = ["dinov2_base", "dinov3_sat"]
209
+
210
+ # Load results
211
+ dinov2_results = load_results_for_model(args.results_dir, "dinov2_base")
212
+ dinov3_results = load_results_for_model(args.results_dir, "dinov3_sat")
213
+
214
+ if not dinov2_results and not dinov3_results:
215
+ print("No results found for either model; nothing to plot.")
216
+ return
217
+
218
+ # Plot
219
+ out_path = os.path.join(args.output_dir, "cv_comparison_variance_pct.png")
220
+ create_comparison_plot(dinov2_results, dinov3_results, out_path)
221
+
222
+ # Console summary
223
+ print("\nSummary by % variance removed:")
224
+ for mc, res in zip(model_configs, [dinov2_results, dinov3_results]):
225
+ if not res:
226
+ print(f" {mc}: No results")
227
+ continue
228
+ print(f" {mc}:")
229
+ for vp in sorted(res.keys()):
230
+ m, lo, up = compute_cv_metrics(res[vp])
231
+ if m is not None:
232
+ n_folds = len(res[vp])
233
+ ci = (up - lo) / 2.0 if up is not None and lo is not None else np.nan
234
+ print(f" v={int(vp):3d}%: {m:.2f} ± {ci:.2f} cm (n={n_folds})")
235
+ else:
236
+ print(f" v={int(vp):3d}%: No valid results")
237
+
238
+ if __name__ == "__main__":
239
+ main()
light_subspace_removal/scripts/train_vpct_spatial_cv.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Patch-agnostic dense CHM regression from pre-encoded DINOv2/DINOv3 patch tokens.
4
+
5
+ Spatial-only 5-fold CV:
6
+ - Train: ~80% of tiles, all timepoints (t0,t1,t2)
7
+ - Val : held-out ~20% tiles, all timepoints (t0,t1,t2)
8
+
9
+ Lighting subspace removal by TARGET VARIANCE EXPLAINED:
10
+ - --var_pct in range(0, 110, 10)
11
+ - Chooses minimal k with cumulative EVR >= var_pct/100 on TRAIN-ONLY residuals
12
+ (per-patch, per-tile residuals z_{i,p,t} - mean_t z_{i,p,·}, T=3).
13
+
14
+ Writes:
15
+ results/{model_config}/simple_decoder/cv_s{fold}_v{vvv}.json
16
+ """
17
+
18
+ import argparse, json, os, random, math
19
+ from collections import defaultdict
20
+ import numpy as np
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from torch import nn
24
+ from torch.utils.data import Dataset, DataLoader
25
+ from datasets import load_dataset
26
+ from sklearn.model_selection import KFold
27
+
28
+ # ---------------------------
29
+ # Small helpers
30
+ # ---------------------------
31
+ def _is_pow2(x: int) -> bool:
32
+ return x > 0 and (x & (x - 1)) == 0
33
+
34
+ def _next_pow2(x: int) -> int:
35
+ return 1 << (x - 1).bit_length()
36
+
37
+ def set_seed(seed=42):
38
+ random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
39
+ torch.cuda.manual_seed_all(seed)
40
+ torch.backends.cudnn.deterministic = True
41
+ torch.backends.cudnn.benchmark = False
42
+
43
+ # ---------------------------
44
+ # Grid / targets
45
+ # ---------------------------
46
+ def infer_token_grid(X_patch: np.ndarray):
47
+ assert X_patch.ndim == 3, f"Expected [M,Np,D], got {X_patch.shape}"
48
+ _, Np, D = X_patch.shape
49
+ side = int(round(Np ** 0.5))
50
+ assert side * side == Np, f"Tokens not square: Np={Np}"
51
+ return side, side, D
52
+
53
+ def tokens_to_chw(tokens: np.ndarray, H: int, W: int):
54
+ D = tokens.shape[-1]
55
+ return tokens.reshape(H, W, D).transpose(2, 0, 1)
56
+
57
+ def make_target(y, H_out: int, W_out: int):
58
+ if np.isscalar(y):
59
+ return torch.full((1, H_out, W_out), float(y), dtype=torch.float32)
60
+ arr = np.array(y)
61
+ t = torch.from_numpy(arr).float()
62
+ if t.ndim == 2:
63
+ t = t[None, None, ...]
64
+ else:
65
+ t = t.view(1, 1, *t.shape[-2:])
66
+ return F.interpolate(t, size=(H_out, W_out), mode='bilinear', align_corners=False)[0]
67
+
68
+ # ---------------------------
69
+ # tcSVD with variance target
70
+ # ---------------------------
71
+ @torch.no_grad()
72
+ def svd_rank_for_var_explained(D: torch.Tensor, target_pct: float):
73
+ target_pct = float(target_pct)
74
+ if target_pct <= 0: return None, 0, np.array([]), np.array([])
75
+ U, S, Vh = torch.linalg.svd(D.cpu(), full_matrices=False) # Vh: [r,d]
76
+ var = S**2
77
+ total = var.sum().item()
78
+ if total <= 0: return None, 0, np.array([]), np.array([])
79
+ evr = (var / total).cpu().numpy()
80
+ cum = np.cumsum(evr)
81
+ k = int(np.searchsorted(cum, target_pct/100.0) + 1)
82
+ k = max(0, min(k, Vh.shape[0]))
83
+ if k == 0: return None, 0, evr, cum
84
+ Vk = Vh[:k].T.contiguous()
85
+ Q, _ = torch.linalg.qr(Vk) # [d,k]
86
+ return Q, k, evr, cum
87
+
88
+ @torch.no_grad()
89
+ def estimate_Q_train_only_patchwise_vpct(X_patch: np.ndarray, ids: list[str], T=3, var_pct: float = 0.0):
90
+ """Compute residual matrix D from TRAIN tiles only, across all patches/time,
91
+ with z_{i,p,t} - mean_t z_{i,p,·}. Then pick k by target EVR."""
92
+ if var_pct <= 0: return None, 0, np.array([]), np.array([])
93
+ groups = defaultdict(list)
94
+ for i, tid in enumerate(ids): groups[tid].append(i)
95
+ diffs = []
96
+ for tid, idxs in groups.items():
97
+ if len(idxs) != T: # expect all three times in train
98
+ continue
99
+ Z = torch.tensor(X_patch[idxs], dtype=torch.float32) # [T,Np,D]
100
+ mu = Z.mean(dim=0, keepdim=True)
101
+ diffs.append(Z - mu)
102
+ if not diffs: return None, 0, np.array([]), np.array([])
103
+ D_mat = torch.cat(diffs, dim=0).reshape(-1, X_patch.shape[-1]) # [T*Ntiles*Np, D]
104
+ return svd_rank_for_var_explained(D_mat, var_pct)
105
+
106
+ def apply_projection_np(X_patch: np.ndarray, Q: torch.Tensor | None):
107
+ X = torch.from_numpy(X_patch).float()
108
+ if (Q is None) or (Q.numel() == 0): return X.numpy().astype(np.float32)
109
+ P = Q @ Q.T
110
+ return (X - X @ P).numpy().astype(np.float32)
111
+
112
+ # ---------------------------
113
+ # Data (HF): load ALL times
114
+ # ---------------------------
115
+ def load_all_times_from_hf(model_config: str, H_out: int, W_out: int):
116
+ """Return arrays containing ALL timepoints for every tile."""
117
+ ds_embed = load_dataset("anondatasets/imageomics-2025", model_config, split='train')
118
+ ds_default = load_dataset("anondatasets/imageomics-2025", "default", split='train')
119
+ canopy_map = {ex['idx']: ex['canopy_height'] for ex in ds_default}
120
+
121
+ X_all, ids_all, Y_all = [], [], []
122
+ for ex in ds_embed:
123
+ idx = ex['idx']
124
+ target = make_target(canopy_map[idx], H_out, W_out).numpy()
125
+ for key in ('t0', 't1', 't2'):
126
+ tokens = np.array(ex[f'patch_{key}'], dtype=np.float32) # [Np,D]
127
+ X_all.append(tokens); ids_all.append(idx); Y_all.append(target)
128
+
129
+ return np.stack(X_all, 0), ids_all, np.stack(Y_all, 0) # [3*Ntiles, Np/D or 1/H/W]
130
+
131
+ class DenseSplit(Dataset):
132
+ def __init__(self, X_patch, Y, H, W):
133
+ self.Xp = X_patch; self.Y = Y; self.H, self.W = H, W
134
+ def __len__(self): return len(self.Xp)
135
+ def __getitem__(self, i):
136
+ x = tokens_to_chw(self.Xp[i], self.H, self.W) # [D,H,W]
137
+ y = torch.from_numpy(self.Y[i]).float() # [1,H_out,W_out]
138
+ return torch.from_numpy(x).float(), y
139
+
140
+ # ---------------------------
141
+ # Decoder
142
+ # ---------------------------
143
+ class UpBlock(nn.Module):
144
+ def __init__(self, c_in, c_out):
145
+ super().__init__()
146
+ self.conv1 = nn.Conv2d(c_in, c_out, 3, padding=1)
147
+ self.gn1 = nn.GroupNorm(8, c_out)
148
+ self.conv2 = nn.Conv2d(c_out, c_out, 3, padding=1)
149
+ self.gn2 = nn.GroupNorm(8, c_out)
150
+ def forward(self, x):
151
+ x = F.gelu(self.gn1(self.conv1(x)))
152
+ x = F.gelu(self.gn2(self.conv2(x)))
153
+ return x
154
+
155
+ class GenericDenseDecoder(nn.Module):
156
+ def __init__(self, c_in: int, H: int, W: int, H_out: int, W_out: int,
157
+ base: int = 256, dropout: float = 0.05):
158
+ super().__init__()
159
+ assert (H_out % H == 0) and (W_out % W == 0)
160
+ sx = H_out // H; sy = W_out // W
161
+ assert sx == sy
162
+ self.H_out, self.W_out = H_out, W_out
163
+ self.stem = nn.Sequential(
164
+ nn.Conv2d(c_in, base, 1),
165
+ nn.GELU(),
166
+ nn.Dropout2d(dropout),
167
+ UpBlock(base, base),
168
+ )
169
+ sx_p2 = sx if _is_pow2(sx) else _next_pow2(sx)
170
+ n_ups = int(math.log2(sx_p2))
171
+ ups, blks = [], []
172
+ c = base
173
+ for _ in range(n_ups):
174
+ ups.append(nn.ConvTranspose2d(c, c // 2, 2, 2))
175
+ blks.append(UpBlock(c // 2, c // 2))
176
+ c //= 2
177
+ self.ups = nn.ModuleList(ups)
178
+ self.blks = nn.ModuleList(blks)
179
+ self.head_mid = nn.Conv2d(c, 1, 1)
180
+ self.need_final_resize = (sx_p2 != sx)
181
+
182
+ def forward(self, x):
183
+ x = self.stem(x)
184
+ for up, blk in zip(self.ups, self.blks):
185
+ x = blk(up(x))
186
+ x = self.head_mid(x)
187
+ if self.need_final_resize:
188
+ x = F.interpolate(x, size=(self.H_out, self.W_out),
189
+ mode='bilinear', align_corners=False, antialias=True)
190
+ return x
191
+
192
+ # ---------------------------
193
+ # Train / Eval
194
+ # ---------------------------
195
+ def rmse_map(y_true, y_pred):
196
+ return torch.sqrt(torch.mean((y_true - y_pred)**2))
197
+
198
+ def train_epoch(model, opt, loader, device):
199
+ model.train()
200
+ for xb, yb in loader:
201
+ xb, yb = xb.to(device), yb.to(device)
202
+ opt.zero_grad(set_to_none=True)
203
+ pred = model(xb)
204
+ loss = F.mse_loss(pred, yb)
205
+ loss.backward(); opt.step()
206
+
207
+ @torch.no_grad()
208
+ def eval_epoch(model, loader, device):
209
+ model.eval()
210
+ rmses = []
211
+ for xb, yb in loader:
212
+ xb, yb = xb.to(device), yb.to(device)
213
+ pred = model(xb)
214
+ rmses.append(rmse_map(yb, pred).cpu())
215
+ return float(torch.stack(rmses).mean())
216
+
217
+ # ---------------------------
218
+ # Main
219
+ # ---------------------------
220
+ def main():
221
+ ap = argparse.ArgumentParser()
222
+ ap.add_argument("--spatial_fold", type=int, default=None, help="fold index in [0..4] (single-exp mode)")
223
+ ap.add_argument("--var_pct", type=float, default=None, help="target % variance explained to remove [0..100]")
224
+ ap.add_argument("--model_config", type=str, default=None, help="dinov2_base or dinov3_sat")
225
+
226
+ ap.add_argument("--job_id", type=int, default=None)
227
+ ap.add_argument("--total_jobs", type=int, default=8)
228
+ ap.add_argument("--total_configs", type=int, default=110) # 11 var levels × 5 folds × 2 configs
229
+
230
+ ap.add_argument("--outdir", type=str, default="results/light_subspace_removal")
231
+ ap.add_argument("--seed", type=int, default=42)
232
+ ap.add_argument("--batch_size", type=int, default=32)
233
+ ap.add_argument("--epochs", type=int, default=50)
234
+ ap.add_argument("--base", type=int, default=256)
235
+ ap.add_argument("--dropout", type=float, default=0.05)
236
+ ap.add_argument("--out_size", type=int, default=224)
237
+ args = ap.parse_args()
238
+
239
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
240
+ set_seed(args.seed)
241
+
242
+ if args.job_id is not None:
243
+ VAR_PCTS = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
244
+ FOLDS = [0,1,2,3,4]
245
+ MODEL_CONFIGS = ['dinov2_base', 'dinov3_sat']
246
+ all_configs = [(vp, f, mc) for mc in MODEL_CONFIGS for f in FOLDS for vp in VAR_PCTS]
247
+ assert len(all_configs) == args.total_configs, f"Expected {args.total_configs}, got {len(all_configs)}"
248
+ per_job = args.total_configs // args.total_jobs
249
+ extra = args.total_configs % args.total_jobs
250
+ if args.job_id < extra:
251
+ start = args.job_id * (per_job + 1); end = start + per_job + 1
252
+ else:
253
+ start = extra * (per_job + 1) + (args.job_id - extra) * per_job
254
+ end = start + per_job
255
+ job_configs = all_configs[start:end]
256
+ print(f"Job {args.job_id} handling {len(job_configs)} configs")
257
+ else:
258
+ if args.spatial_fold is None or args.var_pct is None or args.model_config is None:
259
+ raise ValueError("Provide --job_id ... or all of: --spatial_fold --var_pct --model_config")
260
+ job_configs = [(float(args.var_pct), int(args.spatial_fold), args.model_config)]
261
+
262
+ for var_pct, spatial_fold, model_config in job_configs:
263
+ vtag = f"{int(round(var_pct)):03d}"
264
+ print(f"\n=== v={var_pct}%, spatial_fold={spatial_fold}, model_config={model_config} ===")
265
+
266
+ model_outdir = os.path.join(args.outdir, model_config, 'simple_decoder')
267
+ os.makedirs(model_outdir, exist_ok=True)
268
+ out_path = os.path.join(model_outdir, f"cv_s{spatial_fold}_v{vtag}.json")
269
+ if os.path.exists(out_path):
270
+ print(f"Exists: {out_path} — skipping.")
271
+ continue
272
+
273
+ # Load all times, all tiles
274
+ X_all, ids_all, Y_all = load_all_times_from_hf(model_config, args.out_size, args.out_size)
275
+ H, W, D = infer_token_grid(X_all)
276
+ print(f"Inferred token grid: H={H}, W={W}, D={D}; supervising at {args.out_size}x{args.out_size}")
277
+
278
+ # Group by tile id (each tile should have exactly 3 rows: t0,t1,t2)
279
+ groups = defaultdict(list)
280
+ for i, tid in enumerate(ids_all):
281
+ groups[tid].append(i)
282
+ tiles = sorted(groups.keys())
283
+
284
+ # Spatial 5-fold over tiles
285
+ kf = KFold(n_splits=5, shuffle=True, random_state=args.seed)
286
+ folds = list(kf.split(tiles))
287
+ tr_idx, va_idx = folds[spatial_fold]
288
+ tr_tiles = [tiles[i] for i in tr_idx]
289
+ va_tiles = [tiles[i] for i in va_idx]
290
+ tr_rows = [j for t in tr_tiles for j in groups.get(t, [])]
291
+ va_rows = [j for t in va_tiles for j in groups.get(t, [])]
292
+
293
+ # Prepare arrays
294
+ Xtr, Ytr = X_all[tr_rows], Y_all[tr_rows]
295
+ Xva, Yva = X_all[va_rows], Y_all[va_rows]
296
+ id_tr = [ids_all[j] for j in tr_rows]
297
+
298
+ # Fit tcSVD on TRAIN-ONLY residuals (T=3)
299
+ Q, k_chosen, evr, cum = estimate_Q_train_only_patchwise_vpct(Xtr, id_tr, T=3, var_pct=var_pct)
300
+
301
+ # Project train/val
302
+ XtrP = apply_projection_np(Xtr, Q)
303
+ XvaP = apply_projection_np(Xva, Q)
304
+
305
+ # Datasets / loaders
306
+ train_ds = DenseSplit(XtrP, Ytr, H, W)
307
+ val_ds = DenseSplit(XvaP, Yva, H, W)
308
+ train_loader = DataLoader(train_ds, batch_size=args.batch_size, shuffle=True, num_workers=0, pin_memory=True)
309
+ val_loader = DataLoader(val_ds, batch_size=args.batch_size, shuffle=False, num_workers=0, pin_memory=True)
310
+
311
+ # Model + optimizer
312
+ model = GenericDenseDecoder(c_in=D, H=H, W=W, H_out=args.out_size, W_out=args.out_size,
313
+ base=args.base, dropout=args.dropout).to(device)
314
+ opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
315
+
316
+ # Train
317
+ val_rmse_history = []
318
+ for epoch in range(1, args.epochs+1):
319
+ train_epoch(model, opt, train_loader, device)
320
+ rm = eval_epoch(model, val_loader, device)
321
+ val_rmse_history.append(rm)
322
+ print(f"[s{spatial_fold}_v{var_pct:.0f}% (k={k_chosen})] epoch {epoch:03d} VAL RMSE@{args.out_size} = {rm:.3f} cm")
323
+
324
+ # Save
325
+ evr_head = [float(x) for x in evr[:10]] if evr.size else []
326
+ cum_head = [float(x) for x in cum[:10]] if cum.size else []
327
+ achieved_cum = float(cum[k_chosen-1]) if (k_chosen > 0 and cum.size >= k_chosen) else 0.0
328
+
329
+ out = {
330
+ "spatial_fold": spatial_fold,
331
+ "var_pct_target": float(var_pct),
332
+ "k_chosen": int(k_chosen),
333
+ "cum_evr_at_k": achieved_cum,
334
+ "evr_head": evr_head,
335
+ "cum_evr_head": cum_head,
336
+ "model_config": model_config,
337
+ "seed": args.seed,
338
+ "epochs": args.epochs,
339
+ "val_rmse_history": [round(x, 6) for x in val_rmse_history],
340
+ "token_grid": [H, W, D],
341
+ "out_size": args.out_size,
342
+ "n_train_rows": len(tr_rows),
343
+ "n_val_rows": len(va_rows),
344
+ "train_tiles": tr_tiles,
345
+ "val_tiles": va_tiles,
346
+ }
347
+ with open(out_path, "w") as f:
348
+ json.dump(out, f, indent=2)
349
+ print(f"Saved {out_path}")
350
+
351
+ print("Done.")
352
+
353
+ if __name__ == "__main__":
354
+ main()
light_subspace_removal/scripts/view_subspace_removal.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Visualize a single tile across time with shadow-subspace removal + local PCA.
4
+
5
+ Layout (3 rows × 4 columns):
6
+ - Column 1: RGB at t0, t1, t2 (rows: t0→t2)
7
+ - Column 2: False color composite after 0% variance removal
8
+ - Column 3: False color composite after 90% variance removal
9
+ - Column 4: False color composite after 100% variance removal
10
+
11
+ Shadow/lighting basis (Q) is fit on ALL tiles (no fold-based splitting),
12
+ using variance thresholds of 0%, 90%, and 100%. False color composites map the top 3
13
+ PCA components directly to RGB channels for visualization.
14
+
15
+ Processes both models (dinov2_base, dinov3_sat) automatically, generating separate outputs.
16
+
17
+ Embeddings source:
18
+ load_dataset("mpg-ranch/drone-lsr", {model_config}, split="train")
19
+
20
+ RGB source:
21
+ - Tries to read from the "default" HF config using common key patterns
22
+ - Or pass --rgb_template like "/path/to/rgb/{tile_idx}_{time}.png" with time in {t0,t1,t2}
23
+
24
+ Example:
25
+ python view_subspace_removal.py --tile_idx "137_45"
26
+ # Outputs auto-generated as:
27
+ # supporting/processed/dinov2_base_subspace_removal.png
28
+ # supporting/processed/dinov3_sat_subspace_removal.png
29
+ """
30
+
31
+ import argparse, os
32
+ from collections import defaultdict
33
+ from pathlib import Path
34
+
35
+ import numpy as np
36
+ import torch
37
+ import matplotlib.pyplot as plt
38
+ import matplotlib as mpl
39
+ from sklearn.decomposition import PCA
40
+ from datasets import load_dataset
41
+ from PIL import Image
42
+ from scipy.linalg import orthogonal_procrustes
43
+
44
+ # --- display prefs
45
+ mpl.rcParams["figure.dpi"] = 120
46
+ PRGN = "PRGn" # Diverging for signed PCA scores (user preference)
47
+
48
+ def set_seed(seed=42):
49
+ import random
50
+ random.seed(seed); np.random.seed(seed)
51
+ torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
52
+ torch.backends.cudnn.deterministic = True
53
+ torch.backends.cudnn.benchmark = False
54
+
55
+ def infer_token_grid(X_patch: np.ndarray):
56
+ """X_patch: [M, Np, D] -> returns (H, W, D), with Np = H*W a perfect square."""
57
+ assert X_patch.ndim == 3, f"Expected [M,Np,D], got {X_patch.shape}"
58
+ _, Np, D = X_patch.shape
59
+ side = int(round(Np ** 0.5))
60
+ assert side * side == Np, f"Tokens not square: Np={Np}"
61
+ return side, side, D
62
+
63
+ @torch.no_grad()
64
+ def svd_rank_for_var_explained(D: torch.Tensor, target_pct: float):
65
+ """
66
+ SVD on residual matrix D [N, d]. Choose minimal k s.t. cumEVR >= target_pct/100.
67
+ Returns (Q [d,k] or None, k, evr np.array, cum np.array).
68
+ """
69
+ target_pct = float(target_pct)
70
+ if target_pct <= 0:
71
+ return None, 0, np.array([]), np.array([])
72
+ U, S, Vh = torch.linalg.svd(D.cpu(), full_matrices=False) # Vh: [r,d]
73
+ var = S ** 2
74
+ total = var.sum().item()
75
+ if total <= 0:
76
+ return None, 0, np.array([]), np.array([])
77
+ evr = (var / total).cpu().numpy()
78
+ cum = np.cumsum(evr)
79
+ k = int(np.searchsorted(cum, target_pct / 100.0) + 1)
80
+ k = max(0, min(k, Vh.shape[0]))
81
+ if k == 0:
82
+ return None, 0, evr, cum
83
+ Vk = Vh[:k].T.contiguous()
84
+ Q, _ = torch.linalg.qr(Vk) # [d,k]
85
+ return Q, k, evr, cum
86
+
87
+ @torch.no_grad()
88
+ def estimate_Q_train_only_patchwise_vpct(Xtr_patch: np.ndarray, tr_ids: list[str], T=3, var_pct: float = 0.0):
89
+ """
90
+ Build residuals per (tile, patch, time): z_{i,p,t} - mean_t z_{i,p,·} for TRAIN tiles (expect T=3).
91
+ Stack across tiles/patches -> D_mat [T*Ntiles*Np, D], then choose k by target EVR.
92
+ """
93
+ if var_pct <= 0:
94
+ return None, 0, np.array([]), np.array([])
95
+ groups = defaultdict(list)
96
+ for i, tid in enumerate(tr_ids):
97
+ groups[tid].append(i)
98
+ diffs = []
99
+ for tid, idxs in groups.items():
100
+ if len(idxs) != T:
101
+ continue
102
+ Z = torch.tensor(Xtr_patch[idxs], dtype=torch.float32) # [T,Np,D]
103
+ mu = Z.mean(dim=0, keepdim=True)
104
+ diffs.append(Z - mu)
105
+ if not diffs:
106
+ return None, 0, np.array([]), np.array([])
107
+ D_mat = torch.cat(diffs, dim=0).reshape(-1, Xtr_patch.shape[-1]) # [T*Ntiles*Np, D]
108
+ return svd_rank_for_var_explained(D_mat, var_pct)
109
+
110
+ def apply_projection_np(X_patch: np.ndarray, Q: torch.Tensor | None):
111
+ """Project out columns of Q from last-dim of X_patch [M,Np,D]."""
112
+ X = torch.from_numpy(X_patch).float()
113
+ if (Q is None) or (Q.numel() == 0):
114
+ return X.numpy().astype(np.float32)
115
+ P = Q @ Q.T # [D,D]
116
+ return (X - X @ P).numpy().astype(np.float32)
117
+
118
+ def align_components(target_components: np.ndarray, reference_components: np.ndarray) -> np.ndarray:
119
+ """Align target PCA components to reference using Procrustes rotation.
120
+
121
+ Args:
122
+ target_components: [n_components, n_features] array to be aligned
123
+ reference_components: [n_components, n_features] reference array
124
+
125
+ Returns:
126
+ aligned_components: [n_components, n_features] rotated target components
127
+ """
128
+ # Components are [3, D]. We want to rotate in 3D component space, not D-dimensional feature space
129
+ # Transpose to [D, 3] so we find 3x3 rotation matrix R
130
+ target_T = target_components.T # [D, 3]
131
+ reference_T = reference_components.T # [D, 3]
132
+
133
+ # Find 3x3 rotation R such that target_T @ R ≈ reference_T
134
+ R, _ = orthogonal_procrustes(target_T, reference_T)
135
+
136
+ # Apply rotation and transpose back to [3, D]
137
+ aligned_components = (target_T @ R).T
138
+ return aligned_components
139
+
140
+ def make_false_color_composite(Xt_proj: np.ndarray, H: int, W: int, target_height: int = 1024,
141
+ target_width: int = 1024, seed: int = 42,
142
+ reference_pca=None) -> tuple[np.ndarray, object]:
143
+ """Convert projected embeddings [3, Np, D] to false color RGB [3, target_H, target_W, 3].
144
+ Uses PCA to get top 3 components and maps them to RGB channels.
145
+
146
+ Args:
147
+ Xt_proj: Projected embeddings [3, Np, D]
148
+ H, W: Patch grid dimensions
149
+ target_height, target_width: Output image dimensions (default 1024x1024)
150
+ seed: Random seed for PCA
151
+ reference_pca: Optional reference PCA object for component alignment
152
+
153
+ Returns:
154
+ (false_colors, pca): False color images [3, target_H, target_W, 3] and fitted PCA object
155
+ """
156
+ # Flatten across time and patches for PCA
157
+ D = Xt_proj.shape[-1]
158
+ Xtile_cat = Xt_proj.reshape(-1, D) # [3*Np, D]
159
+
160
+ if float(Xtile_cat.var()) == 0.0:
161
+ # If no variance, return black images
162
+ return np.zeros((3, target_height, target_width, 3), dtype=np.uint8), None
163
+
164
+ # PCA to get top 3 components
165
+ pca = PCA(n_components=3, svd_solver="auto", random_state=seed)
166
+ scores = pca.fit_transform(Xtile_cat) # [3*Np, 3]
167
+
168
+ # Align with reference PCA if provided
169
+ if reference_pca is not None:
170
+ # Align current PCA components to reference
171
+ aligned_components = align_components(pca.components_, reference_pca.components_)
172
+ # Re-orthonormalize to eliminate numerical drift
173
+ U, _, Vt = np.linalg.svd(aligned_components, full_matrices=False)
174
+ aligned_components = (U @ Vt)
175
+ # Recompute scores using aligned components (must center first!)
176
+ scores = (Xtile_cat - pca.mean_) @ aligned_components.T
177
+
178
+ # Split back by time and reshape to spatial grid
179
+ Np = H * W
180
+ false_colors = []
181
+ for t in range(3):
182
+ pc_scores = scores[t*Np:(t+1)*Np, :].reshape(H, W, 3) # [H, W, 3]
183
+
184
+ # Create RGB image: PC1→Red, PC2→Green, PC3→Blue
185
+ rgb_img = np.zeros((H, W, 3), dtype=np.uint8)
186
+
187
+ # PC1 → Red channel
188
+ red_channel = pc_scores[:, :, 0]
189
+ r_low, r_high = np.nanpercentile(red_channel, [1, 99])
190
+ if r_high > r_low:
191
+ red_norm = np.clip((red_channel - r_low) / (r_high - r_low), 0, 1)
192
+ else:
193
+ red_norm = np.zeros_like(red_channel)
194
+ rgb_img[:, :, 0] = (red_norm * 255).astype(np.uint8)
195
+
196
+ # PC2 → Green channel
197
+ green_channel = pc_scores[:, :, 1]
198
+ g_low, g_high = np.nanpercentile(green_channel, [1, 99])
199
+ if g_high > g_low:
200
+ green_norm = np.clip((green_channel - g_low) / (g_high - g_low), 0, 1)
201
+ else:
202
+ green_norm = np.zeros_like(green_channel)
203
+ rgb_img[:, :, 1] = (green_norm * 255).astype(np.uint8)
204
+
205
+ # PC3 → Blue channel
206
+ blue_channel = pc_scores[:, :, 2]
207
+ b_low, b_high = np.nanpercentile(blue_channel, [1, 99])
208
+ if b_high > b_low:
209
+ blue_norm = np.clip((blue_channel - b_low) / (b_high - b_low), 0, 1)
210
+ else:
211
+ blue_norm = np.zeros_like(blue_channel)
212
+ rgb_img[:, :, 2] = (blue_norm * 255).astype(np.uint8)
213
+
214
+ # Upsample to target resolution using PIL
215
+ if (H, W) != (target_height, target_width):
216
+ pil_img = Image.fromarray(rgb_img, mode='RGB')
217
+ rgb_img_upsampled = np.array(pil_img.resize((target_width, target_height), Image.LANCZOS))
218
+ else:
219
+ rgb_img_upsampled = rgb_img
220
+
221
+ false_colors.append(rgb_img_upsampled)
222
+
223
+ return np.stack(false_colors, 0), pca # [3, target_H, target_W, 3]
224
+
225
+ def load_embeddings(model_config: str):
226
+ """Return (tile_idxs list, dict tile_idx -> {'t0','t1','t2': np.ndarray[Np,D]})"""
227
+ ds = load_dataset("mpg-ranch/drone-lsr", model_config, split="train")
228
+ tiles, X_by_tile = [], {}
229
+ for ex in ds:
230
+ tid = ex["idx"]
231
+ X_by_tile[tid] = {
232
+ "t0": np.array(ex["patch_t0"], dtype=np.float32),
233
+ "t1": np.array(ex["patch_t1"], dtype=np.float32),
234
+ "t2": np.array(ex["patch_t2"], dtype=np.float32),
235
+ }
236
+ tiles.append(tid)
237
+ return tiles, X_by_tile
238
+
239
+
240
+ def load_rgb_triplet(tile_idx: str, rgb_template: str | None):
241
+ # Try user template first
242
+ if rgb_template:
243
+ frames = []
244
+ for tk in ("t0","t1","t2"):
245
+ p = Path(rgb_template.format(tile_idx=tile_idx, time=tk))
246
+ if not p.exists():
247
+ raise FileNotFoundError(f"RGB template path not found: {p}")
248
+ frames.append(Image.open(p).convert("RGB"))
249
+ return frames
250
+
251
+ # Try HF default config with common key patterns
252
+ ds_def = load_dataset("mpg-ranch/drone-lsr", "default", split="train")
253
+ by_id = {ex["idx"]: ex for ex in ds_def}
254
+ if tile_idx not in by_id:
255
+ raise KeyError(f"Tile {tile_idx} not found in default config")
256
+ ex = by_id[tile_idx]
257
+ candidates = [
258
+ ("rgb_t0","rgb_t1","rgb_t2"),
259
+ ("image_t0","image_t1","image_t2"),
260
+ ("t0","t1","t2"),
261
+ ]
262
+ for t0k,t1k,t2k in candidates:
263
+ if t0k in ex and t1k in ex and t2k in ex:
264
+ def to_img(x):
265
+ return x if isinstance(x, Image.Image) else Image.fromarray(np.array(x))
266
+ return [to_img(ex[t0k]).convert("RGB"), to_img(ex[t1k]).convert("RGB"), to_img(ex[t2k]).convert("RGB")]
267
+ raise KeyError(f"No RGB keys found for tile {tile_idx}. Provide --rgb_template.")
268
+
269
+
270
+ def tile_rows_for_idxs(X_by_tile, tile_idxs):
271
+ rows, ids = [], []
272
+ for tidx in tile_idxs:
273
+ for tk in ("t0","t1","t2"):
274
+ rows.append(X_by_tile[tidx][tk])
275
+ ids.append(tidx)
276
+ return np.stack(rows, 0), ids # [3*Nt, Np, D]
277
+
278
+ def process_model(model_config: str, tile_idx: str, rgb_template: str | None, seed: int = 42):
279
+ """Process a single model and generate visualization."""
280
+ print(f"[info] Processing model: {model_config}")
281
+
282
+ # Load embeddings for all tiles
283
+ all_tiles, X_by_tile = load_embeddings(model_config)
284
+ if tile_idx not in X_by_tile:
285
+ raise KeyError(f"Tile '{tile_idx}' not found in embeddings for {model_config}")
286
+
287
+ # Shape info
288
+ sample = X_by_tile[tile_idx]["t0"]
289
+ H, W, D = infer_token_grid(np.stack([sample], 0))
290
+ Np = H * W
291
+
292
+ # Use ALL tiles for fitting Q matrices (no fold-based splitting)
293
+ # Fit Q matrices for 0%, 90%, 100% variance removal
294
+ Xtr, id_tr = tile_rows_for_idxs(X_by_tile, all_tiles) # [3*Nt, Np, D]
295
+ var_levels = [0.0, 90.0, 100.0]
296
+ Q_matrices = []
297
+ k_values = []
298
+
299
+ for var_pct in var_levels:
300
+ Q, k_chosen, evr, cum = estimate_Q_train_only_patchwise_vpct(Xtr, id_tr, T=3, var_pct=var_pct)
301
+ Q_matrices.append(Q)
302
+ k_values.append(k_chosen)
303
+ if Q is None:
304
+ print(f"[info] {model_config} var_pct={var_pct}% → k=0 (no removal)")
305
+ else:
306
+ cumk = (cum[k_chosen-1] if len(cum) >= k_chosen and k_chosen > 0 else 0.0)
307
+ print(f"[info] {model_config} var_pct={var_pct}% → k={k_chosen}, cumEVR≈{cumk:.3f}")
308
+
309
+ # Pull this tile's 3 timepoints
310
+ Xt_tile = np.stack([X_by_tile[tile_idx][tk] for tk in ("t0","t1","t2")], 0) # [3, Np, D]
311
+
312
+ # Generate false color composites for each variance level
313
+ false_color_imgs = []
314
+ reference_pca = None
315
+
316
+ for i, Q in enumerate(Q_matrices):
317
+ Xt_proj = apply_projection_np(Xt_tile, Q) # [3, Np, D]
318
+
319
+ if i == 0:
320
+ # First level (0%) - establish reference
321
+ fc_rgb, reference_pca = make_false_color_composite(
322
+ Xt_proj, H, W, target_height=1024, target_width=1024,
323
+ seed=seed, reference_pca=None)
324
+ else:
325
+ # Subsequent levels (90%, 100%) - align to reference
326
+ fc_rgb, _ = make_false_color_composite(
327
+ Xt_proj, H, W, target_height=1024, target_width=1024,
328
+ seed=seed, reference_pca=reference_pca)
329
+
330
+ false_color_imgs.append(fc_rgb)
331
+
332
+ # Load RGB triplet
333
+ rgb_imgs = load_rgb_triplet(tile_idx, rgb_template) # list[PIL] length 3
334
+
335
+ # === Plot 3x4 grid: rows t0,t1,t2; col1 RGB, col2-4 false color at 0%,90%,100% ===
336
+ fig, axes = plt.subplots(3, 4, figsize=(16, 12))
337
+ times = ["t0","t1","t2"]
338
+ col_headers = ["RGB", "0%", "90%", "100%"]
339
+
340
+ # Add column headers at the top
341
+ for c, header in enumerate(col_headers):
342
+ axes[0, c].text(0.5, 1.05, header, transform=axes[0, c].transAxes,
343
+ ha='center', va='bottom', fontsize=14, fontweight='bold')
344
+
345
+ for r in range(3):
346
+ # Column 1: RGB
347
+ ax = axes[r,0]
348
+ ax.imshow(rgb_imgs[r])
349
+ ax.set_axis_off()
350
+
351
+ # Add time label on the left
352
+ ax.text(-0.1, 0.5, times[r], transform=ax.transAxes,
353
+ ha='right', va='center', fontsize=12, rotation=90)
354
+
355
+ # Columns 2-4: False color composites for 0%, 90%, 100%
356
+ for c in range(1, 4):
357
+ var_idx = c - 1 # 0, 1, 2 for 0%, 90%, 100%
358
+ ax = axes[r, c]
359
+ ax.imshow(false_color_imgs[var_idx][r]) # [time_idx][H, W, 3]
360
+ ax.set_axis_off()
361
+
362
+ plt.tight_layout()
363
+
364
+ # Auto-generate output path
365
+ out_path = f"supporting/processed/{model_config}_subspace_removal.png"
366
+ out = Path(out_path)
367
+ out.parent.mkdir(parents=True, exist_ok=True)
368
+ plt.savefig(out, dpi=300)
369
+ plt.close()
370
+ print(f"Saved {out}")
371
+
372
+ def main():
373
+ ap = argparse.ArgumentParser()
374
+ ap.add_argument("--tile_idx", type=str, required=True, help="Tile identifier")
375
+ ap.add_argument("--rgb_template", type=str, default=None,
376
+ help="e.g., '/data/rgb/{tile_idx}_{time}.png' with time in {t0,t1,t2}'")
377
+ ap.add_argument("--seed", type=int, default=42)
378
+ args = ap.parse_args()
379
+
380
+ set_seed(args.seed)
381
+
382
+ # Validate tile_idx is provided
383
+ if not args.tile_idx:
384
+ raise ValueError("Provide --tile_idx")
385
+
386
+ # Process both models
387
+ models = ["dinov2_base", "dinov3_sat"]
388
+ for model_config in models:
389
+ try:
390
+ process_model(model_config, args.tile_idx, args.rgb_template, args.seed)
391
+ except Exception as e:
392
+ print(f"[error] Failed to process {model_config}: {e}")
393
+ continue
394
+
395
+ if __name__ == "__main__":
396
+ main()