-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaviris_fixed_shape_experiment_v4.py
More file actions
1863 lines (1520 loc) · 76.1 KB
/
Copy pathaviris_fixed_shape_experiment_v4.py
File metadata and controls
1863 lines (1520 loc) · 76.1 KB
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
AVIRIS Fixed Shape Experiment (v4)
----------------------------
This script extends the original AVIRIS compression model to:
1. Record important shapes from Stage 1 (initial, lowest condition number, lowest test MSE)
2. Run Stage 2 with fixed shapes from Stage 1, optimizing only the decoder
3. Compare performance of different fixed shapes
4. Includes filter evolution visualization from the original compression pipeline
Usage:
# Run both stages
python aviris_fixed_shape_experiment_v4.py --use_fsf --model awan --tile_size 100 --epochs 100
--stage2_epochs 100 --batch_size 64 --encoder_lr 1e-3 --decoder_lr 5e-4 --min_snr 10 --max_snr 40
--shape2filter_path "outputs_three_stage_20250322_145925/stageA/shape2spec_stageA.pt"
--filter2shape_path "outputs_three_stage_20250322_145925/stageC/spec2shape_stageC.pt"
--filter_scale_factor 10.0
# Skip stage 1 and only run stage 2
python aviris_fixed_shape_experiment_v4.py --use_fsf --model awan --tile_size 100
--stage2_epochs 100 --batch_size 64 --decoder_lr 5e-4 --min_snr 10 --max_snr 40
--shape2filter_path "outputs_three_stage_20250322_145925/stageA/shape2spec_stageA.pt"
--skip_stage1 --load_shapes_dir results_fixed_shape_awan_20250402_052223/recorded_shapes/
--filter_scale_factor 10.0
"""
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader, random_split
import numpy as np
import matplotlib.pyplot as plt
import os
import argparse
from tqdm import tqdm
import random
from datetime import datetime
import numpy.linalg as LA
# Import filter visualization functions from aviris_compression_diff_lr_dual_fsf_corr
try:
from aviris_compression_diff_lr_dual_fsf_corr import (
plot_shape_with_c4,
visualize_filter,
visualize_filter_with_shape,
calculate_condition_number
)
print("Successfully imported filter visualization functions")
except ImportError:
# Define the functions here if import fails
def plot_shape_with_c4(shape, title, save_path=None, show=False, ax=None):
"""Plot shape with C4 symmetry replication in a minimal academic style"""
if ax is None:
fig, ax = plt.subplots(figsize=(5, 5))
ax.set_xlim(-0.7, 0.7) # Fixed limits as requested
ax.set_ylim(-0.7, 0.7)
# Extract active points
presence = shape[:, 0] > 0.5
active_points = shape[presence, 1:3]
# Plot original Q1 points
ax.scatter(shape[presence, 1], shape[presence, 2], color='red', s=50)
# Apply C4 symmetry and plot the polygon
if len(active_points) > 0:
c4_points = replicate_c4(active_points)
sorted_points = sort_points_by_angle(c4_points)
# If we have enough points for a polygon
if len(sorted_points) >= 3:
# Close the polygon
polygon = np.vstack([sorted_points, sorted_points[0]])
ax.plot(polygon[:, 0], polygon[:, 1], 'k-', linewidth=1.5)
ax.fill(polygon[:, 0], polygon[:, 1], 'lightblue', alpha=0.5)
else:
# Just plot the points
ax.scatter(c4_points[:, 0], c4_points[:, 1], color='blue', alpha=0.4, s=30)
ax.set_title(title, fontsize=12)
ax.set_aspect('equal')
ax.grid(True)
if save_path and ax is None:
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches='tight')
if show and ax is None:
plt.show()
elif ax is None:
plt.close()
return ax
def calculate_condition_number(filters):
"""
Calculate condition number of the spectral filters matrix.
Parameters:
filters: Tensor or ndarray of shape [11, 100] representing the spectral filters
Returns:
float: Condition number
"""
# Convert to numpy for condition number calculation
if isinstance(filters, torch.Tensor):
filters_np = filters.detach().cpu().numpy()
else:
filters_np = filters
# Use singular value decomposition to calculate condition number
u, s, vh = LA.svd(filters_np)
# Condition number is the ratio of largest to smallest singular value
# Add small epsilon to prevent division by zero
condition_number = s[0] / (s[-1] + 1e-10)
return condition_number
def visualize_filter_with_shape(filter_A, shape_pred, filter_output, save_path):
"""
Visualize the filter matrix, its corresponding shape, and reconstructed filter
Parameters:
filter_A: Original filter parameter (numpy array or tensor)
shape_pred: Predicted shape from filter2shape (numpy array or tensor)
filter_output: Reconstructed filter from shape2filter (numpy array or tensor)
save_path: Path to save the visualization
"""
# Convert to numpy if needed
if isinstance(filter_A, torch.Tensor):
filter_A_np = filter_A.detach().cpu().numpy()
else:
filter_A_np = filter_A
if isinstance(shape_pred, torch.Tensor):
shape_pred_np = shape_pred.detach().cpu().numpy()
else:
shape_pred_np = shape_pred
if isinstance(filter_output, torch.Tensor):
filter_output_np = filter_output.detach().cpu().numpy()
else:
filter_output_np = filter_output
# Calculate condition numbers
filter_cond = calculate_condition_number(filter_A_np)
recon_cond = calculate_condition_number(filter_output_np)
# Create a 2x2 grid
fig = plt.figure(figsize=(18, 10))
# Plot original filter (top left)
ax1 = plt.subplot2grid((2, 2), (0, 0))
for i in range(filter_A_np.shape[0]):
ax1.plot(filter_A_np[i], label=f"Filter {i+1}" if i % 3 == 0 else None)
ax1.set_title(f"Original Filter (Condition Number: {filter_cond:.4f})")
ax1.set_xlabel("Wavelength Index")
ax1.set_ylabel("Filter Value")
ax1.grid(True, alpha=0.3)
if filter_A_np.shape[0] <= 11: # Only show legend for small number of filters
ax1.legend()
# Plot the shape (top right)
ax2 = plt.subplot2grid((2, 2), (0, 1))
plot_shape_with_c4(shape_pred_np, "Predicted Shape", show=False, ax=ax2)
# Plot reconstructed filter (bottom left)
ax3 = plt.subplot2grid((2, 2), (1, 0))
for i in range(filter_output_np.shape[0]):
ax3.plot(filter_output_np[i], label=f"Filter {i+1}" if i % 3 == 0 else None)
ax3.set_title(f"Reconstructed Filter (Condition Number: {recon_cond:.4f})")
ax3.set_xlabel("Wavelength Index")
ax3.set_ylabel("Filter Value")
ax3.grid(True, alpha=0.3)
if filter_output_np.shape[0] <= 11: # Only show legend for small number of filters
ax3.legend()
# Plot the difference (bottom right)
ax4 = plt.subplot2grid((2, 2), (1, 1))
diff = np.abs(filter_A_np - filter_output_np)
for i in range(diff.shape[0]):
ax4.plot(diff[i], label=f"Filter {i+1}" if i % 3 == 0 else None)
mse = np.mean(diff**2)
ax4.set_title(f"Difference (MSE: {mse:.6f})")
ax4.set_xlabel("Wavelength Index")
ax4.set_ylabel("Absolute Difference")
ax4.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches="tight")
plt.close()
def visualize_filter(filter_A, save_path, include_shape=False, shape_pred=None, filter_output=None):
"""Visualize the filter matrix as individual subplots"""
# Ensure filter_A is numpy if it's a tensor
if isinstance(filter_A, torch.Tensor):
filter_A_np = filter_A.detach().cpu().numpy()
else:
filter_A_np = filter_A
latent_dim, in_channels = filter_A_np.shape
# Create a figure with subplots
fig, axes = plt.subplots(latent_dim, 1, figsize=(12, 2*latent_dim), sharex=True)
# Handle the case where latent_dim=1
axes = [axes] if latent_dim == 1 else axes
# Plot each row of the filter matrix in a separate subplot
for i in range(latent_dim):
axes[i].plot(filter_A_np[i], 'b-')
axes[i].set_title(f"Filter {i+1}")
axes[i].grid(True, alpha=0.3)
axes[i].set_ylabel("Value")
# Set common labels
axes[-1].set_xlabel("Input Channel (0-99)")
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches="tight")
plt.close()
# Also create a combined plot for easy comparison
plt.figure(figsize=(12, 8))
# Plot each row of the filter matrix as a line
for i in range(latent_dim):
plt.plot(filter_A_np[i], label=f"Filter {i+1}")
plt.title("Filter Matrix Visualization")
plt.xlabel("Input Channel (0-99)")
plt.ylabel("Filter Value")
plt.legend()
plt.grid(True, alpha=0.3)
# Save the combined plot
combined_path = save_path.replace('.png', '_combined.png')
plt.savefig(combined_path, dpi=300, bbox_inches="tight")
plt.close()
# If shape_pred and filter_output are provided, also visualize the filter2shape2filter results
if include_shape and shape_pred is not None and filter_output is not None:
fsf_path = save_path.replace('.png', '_with_shape.png')
visualize_filter_with_shape(filter_A_np, shape_pred, filter_output, fsf_path)
print("Defined local filter visualization functions")
# Import AWAN if you have it
try:
from AWAN import AWAN
except ImportError:
print("Warning: Could not import AWAN, only CNN decoder will be available.")
# Import filter2shape2filter models and utilities
try:
from filter2shape2filter_pipeline import (
Shape2FilterModel, Filter2ShapeVarLen, create_pipeline, load_models,
replicate_c4, sort_points_by_angle
)
except ImportError:
print("Warning: Could not import filter2shape2filter_pipeline.")
# Set random seed for reproducibility
def set_seed(seed=42):
"""Set random seed for reproducibility across Python, NumPy, PyTorch and CUDA"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
os.environ["PYTHONHASHSEED"] = str(seed)
print(f"Random seed set to {seed}")
# Set seed at the beginning of your script
set_seed(42)
def save_data_to_csv(data, headers, save_path):
"""
Save data to CSV file
Parameters:
data: List of lists or numpy array with data to save
headers: List of headers for each column
save_path: Path to save the CSV file
"""
import csv
import os
# Ensure directory exists
os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
# Convert data to list format if it's a numpy array
if isinstance(data, np.ndarray):
# If it's a 1D array, convert to 2D column
if len(data.shape) == 1:
data = np.column_stack([np.arange(len(data)), data])
data_list = data.tolist()
else:
data_list = data
# Write data to CSV
with open(save_path, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(data_list)
print(f"Saved data to CSV: {save_path}")
class AvirisDataset(Dataset):
"""Dataset for AVIRIS tiles"""
def __init__(self, tiles):
self.tiles = tiles
def __len__(self):
return len(self.tiles)
def __getitem__(self, idx):
return self.tiles[idx]
class LinearEncoder(nn.Module):
"""Linear encoder that multiplies input with filter matrix A,
integrating the filter2shape2filter pipeline"""
def __init__(self, in_dim=100, out_dim=11, use_fsf=True,
shape2filter_path=None, filter2shape_path=None,
filter_scale_factor=50.0):
super(LinearEncoder, self).__init__()
self.filter_H = nn.Parameter(torch.randn(out_dim, in_dim))
# Initialize with values between 0 and 1
nn.init.uniform_(self.filter_H, 0., 1.)
self.use_fsf = use_fsf
self.filter_scale_factor = filter_scale_factor
self.pipeline = None
self.current_shape = None
self.filter_output = None
# Initialize the filter2shape2filter pipeline if requested
if use_fsf and shape2filter_path and filter2shape_path:
try:
device = torch.device("cpu") # Will be moved to the right device later
self.shape2filter, self.filter2shape = load_models(
shape2filter_path, filter2shape_path, device)
self.pipeline = create_pipeline(self.shape2filter, self.filter2shape, no_grad_frozen=False)
print("FSF pipeline initialized in LinearEncoder")
except Exception as e:
print(f"Error initializing FSF pipeline: {e}")
self.use_fsf = False
self.pipeline = None
else:
self.use_fsf = False
self.pipeline = None
@property
def filter_A(self):
# Get normalized filter through pipeline if available
if self.use_fsf and self.pipeline is not None:
_, filter_norm = self.pipeline(self.filter_H.unsqueeze(0))
return filter_norm[0]
return self.filter_H
def to(self, device):
# Override to method to move pipeline models to the same device
super().to(device)
if self.pipeline is not None:
self.shape2filter.to(device)
self.filter2shape.to(device)
# Recreate pipeline with models on the correct device
self.pipeline = create_pipeline(self.shape2filter, self.filter2shape, no_grad_frozen=False)
return self
def forward(self, x):
# Input shape: (batch, channels, height, width)
batch, C, H, W = x.shape
# Reshape to (batch*height*width, channels)
x_flat = x.permute(0, 2, 3, 1).reshape(-1, C)
if self.use_fsf and self.pipeline is not None:
# Run filter through pipeline to get shape and reconstructed filter
shape_pred, filter_output = self.pipeline(self.filter_A.unsqueeze(0))
# Store for visualization
self.current_shape = shape_pred[0].detach().cpu()
self.filter_output = filter_output[0].detach().cpu()
# Use the filter output from the pipeline, scaled by the factor
z = torch.matmul(x_flat, filter_output[0].t() / self.filter_scale_factor)
else:
# Use the learnable filter directly
z = torch.matmul(x_flat, self.filter_A.t())
# Reshape back to (batch, out_dim, height, width)
z = z.reshape(batch, H, W, -1).permute(0, 3, 1, 2)
return z
class SimpleCNNDecoder(nn.Module):
"""Simple 3-layer CNN decoder"""
def __init__(self, in_channels=11, out_channels=100):
super(SimpleCNNDecoder, self).__init__()
# Define intermediate channel sizes
mid_channels = 64
# First layer: in_channels -> mid_channels
self.layer1 = nn.Sequential(
nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(mid_channels),
nn.ReLU(inplace=True)
)
# Second layer: mid_channels -> mid_channels
self.layer2 = nn.Sequential(
nn.Conv2d(mid_channels, mid_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(mid_channels),
nn.ReLU(inplace=True)
)
# Third layer: mid_channels -> out_channels
self.layer3 = nn.Sequential(
nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1),
nn.Sigmoid() # Sigmoid to ensure output in [0,1] range
)
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
return x
class CompressionModel(nn.Module):
"""Compression model with linear encoder and selectable decoder"""
def __init__(self, in_channels=100, latent_dim=11, decoder_type='awan',
use_fsf=True, shape2filter_path=None, filter2shape_path=None,
filter_scale_factor=50.0):
super(CompressionModel, self).__init__()
self.encoder = LinearEncoder(
in_dim=in_channels,
out_dim=latent_dim,
use_fsf=use_fsf,
shape2filter_path=shape2filter_path,
filter2shape_path=filter2shape_path,
filter_scale_factor=filter_scale_factor
)
# Select decoder based on type
if decoder_type.lower() == 'awan':
self.decoder = AWAN(inplanes=latent_dim, planes=in_channels, channels=128, n_DRBs=2)
elif decoder_type.lower() == 'cnn':
self.decoder = SimpleCNNDecoder(in_channels=latent_dim, out_channels=in_channels)
else:
raise ValueError(f"Unknown decoder type: {decoder_type}. Choose 'awan' or 'cnn'.")
def add_noise(self, z, min_snr_db=10, max_snr_db=40):
"""Add random noise with SNR between min_snr_db and max_snr_db"""
batch_size = z.shape[0]
# Random SNR for each image in batch
snr_db = torch.rand(batch_size, 1, 1, 1, device=z.device) * (max_snr_db - min_snr_db) + min_snr_db
snr = 10 ** (snr_db / 10)
# Calculate signal power
signal_power = torch.mean(z ** 2, dim=(1, 2, 3), keepdim=True)
# Calculate noise power based on SNR
noise_power = signal_power / snr
# Generate Gaussian noise (reparameterization trick)
noise = torch.randn_like(z) * torch.sqrt(noise_power)
# Add noise to signal
z_noisy = z + noise
return z_noisy
def forward(self, x, add_noise=True, min_snr_db=10, max_snr_db=40):
# Encode
z = self.encoder(x)
# Add noise if specified (during training)
if add_noise:
z = self.add_noise(z, min_snr_db, max_snr_db)
# Decode
x_recon = self.decoder(z)
return x_recon, z
class FixedShapeEncoder(nn.Module):
"""Simple fixed shape encoder that directly uses precomputed filters"""
def __init__(self, shape, in_dim=100, filter_scale_factor=50.0, device=None):
super(FixedShapeEncoder, self).__init__()
if device is None:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.filter_scale_factor = filter_scale_factor
self.shape = shape.to(device)
# Load shape2filter model
try:
self.shape2filter = Shape2FilterModel().to(device)
self.shape2filter.eval() # Set to evaluation mode
# Precompute filter from shape, store as buffer (not parameter)
with torch.no_grad():
self.register_buffer(
'fixed_filter',
self.shape2filter(self.shape.unsqueeze(0))[0]
)
print(f"Fixed shape encoder initialized with filter of shape {self.fixed_filter.shape}")
except Exception as e:
print(f"Error initializing shape2filter model: {e}")
raise
def forward(self, x):
# Input shape: (batch, channels, height, width)
batch, C, H, W = x.shape
# Reshape to (batch*height*width, channels)
x_flat = x.permute(0, 2, 3, 1).reshape(-1, C)
# Use the fixed filter
z = torch.matmul(x_flat, self.fixed_filter.t() / self.filter_scale_factor)
# Reshape back to (batch, out_dim, height, width)
z = z.reshape(batch, H, W, -1).permute(0, 3, 1, 2)
return z
class FixedShapeModel(nn.Module):
"""Model with fixed shape encoder and trainable decoder"""
def __init__(self, shape, in_channels=100, decoder_type='awan', filter_scale_factor=50.0, device=None):
super(FixedShapeModel, self).__init__()
if device is None:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Create encoder with fixed filter
self.encoder = FixedShapeEncoder(
shape=shape,
in_dim=in_channels,
filter_scale_factor=filter_scale_factor,
device=device
)
# Number of latent dimensions equals number of rows in filter
latent_dim = self.encoder.fixed_filter.shape[0]
# Create decoder based on type
if decoder_type.lower() == 'awan':
self.decoder = AWAN(inplanes=latent_dim, planes=in_channels, channels=128, n_DRBs=2)
elif decoder_type.lower() == 'cnn':
self.decoder = SimpleCNNDecoder(in_channels=latent_dim, out_channels=in_channels)
else:
raise ValueError(f"Unknown decoder type: {decoder_type}. Choose 'awan' or 'cnn'.")
def add_noise(self, z, min_snr_db=10, max_snr_db=40):
"""Add random noise with SNR between min_snr_db and max_snr_db"""
batch_size = z.shape[0]
# Random SNR for each image in batch
snr_db = torch.rand(batch_size, 1, 1, 1, device=z.device) * (max_snr_db - min_snr_db) + min_snr_db
snr = 10 ** (snr_db / 10)
# Calculate signal power
signal_power = torch.mean(z ** 2, dim=(1, 2, 3), keepdim=True)
# Calculate noise power based on SNR
noise_power = signal_power / snr
# Generate Gaussian noise
noise = torch.randn_like(z) * torch.sqrt(noise_power)
# Add noise to signal
z_noisy = z + noise
return z_noisy
def forward(self, x, add_noise=True, min_snr_db=10, max_snr_db=40):
# Encode
z = self.encoder(x)
# Add noise if specified (during training)
if add_noise:
z = self.add_noise(z, min_snr_db, max_snr_db)
# Decode
x_recon = self.decoder(z)
return x_recon, z
def visualize_shape(shape, save_path):
"""Visualize shape with C4 symmetry replication and save to file"""
# Convert shape to numpy if it's a tensor
if isinstance(shape, torch.Tensor):
shape_np = shape.detach().cpu().numpy()
else:
shape_np = shape
# Create figure
plt.figure(figsize=(5, 5))
plt.xlim(-0.7, 0.7) # Fixed limits
plt.ylim(-0.7, 0.7)
# Extract active points (where presence > 0.5)
presence = shape_np[:, 0] > 0.5
active_points = shape_np[presence, 1:3]
# Plot original points
plt.scatter(shape_np[presence, 1], shape_np[presence, 2], color='red', s=50)
# Apply C4 symmetry and plot
if len(active_points) > 0:
# Replicate with C4 symmetry
c4_points = []
for i in range(len(active_points)):
x, y = active_points[i]
c4_points.append([x, y]) # Q1: original
c4_points.append([-y, x]) # Q2: rotate 90°
c4_points.append([-x, -y]) # Q3: rotate 180°
c4_points.append([y, -x]) # Q4: rotate 270°
c4_points = np.array(c4_points)
# Sort points by angle for polygon drawing
if len(c4_points) >= 3:
center = np.mean(c4_points, axis=0)
angles = np.arctan2(c4_points[:, 1] - center[1], c4_points[:, 0] - center[0])
idx = np.argsort(angles)
sorted_points = c4_points[idx]
# Close the polygon
polygon = np.vstack([sorted_points, sorted_points[0]])
plt.plot(polygon[:, 0], polygon[:, 1], 'k-', linewidth=1.5)
plt.fill(polygon[:, 0], polygon[:, 1], 'lightblue', alpha=0.5)
else:
# Just plot the points
plt.scatter(c4_points[:, 0], c4_points[:, 1], color='blue', alpha=0.4, s=30)
# Format plot
plt.title('Shape Visualization with C4 Replication')
plt.axis('equal')
plt.grid(True)
plt.tight_layout()
# Save the plot
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Saved shape visualization to: {save_path}")
plt.close()
def create_tiles(data, tile_size=256, overlap=0):
"""Create tiles from a large image"""
# Check data shape and convert if necessary
if data.shape[0] < data.shape[1] and data.shape[0] < data.shape[2]:
# Data is in (C, H, W) format, convert to (H, W, C)
data = data.permute(1, 2, 0)
H, W, C = data.shape
tiles = []
stride = tile_size - overlap
for i in range(0, H - tile_size + 1, stride):
for j in range(0, W - tile_size + 1, stride):
tile = data[i:i+tile_size, j:j+tile_size, :]
# Convert to (C, H, W) format for PyTorch
tile = tile.permute(2, 0, 1)
tiles.append(tile)
return tiles
def process_and_cache_data(args):
"""Process AVIRIS data and cache tiles"""
# Define cache directory and file
cache_dir = args.use_cache
tile_size = args.tile_size
os.makedirs(cache_dir, exist_ok=True)
# Cache filename includes tile size
cache_file = os.path.join(cache_dir, f"tiles_{tile_size}.pt")
# Use existing cache if available
if os.path.exists(cache_file) and not args.force_cache:
print(f"Using existing cache: {cache_file}")
return cache_file
# Get input directories
base_dir = "AVIRIS_SIMPLE_SELECT"
if args.folder == "all":
subfolders = [f for f in os.listdir(base_dir) if os.path.isdir(os.path.join(base_dir, f))]
else:
subfolders = [args.folder]
print(f"Processing {len(subfolders)} folders: {', '.join(subfolders)}")
# Process each subfolder
all_tiles = []
for subfolder in subfolders:
torch_dir = os.path.join(base_dir, subfolder, "torch")
if not os.path.exists(torch_dir):
print(f"Skipping {subfolder}: torch directory not found")
continue
# Load data
data_file = os.path.join(torch_dir, "aviris_selected.pt")
if not os.path.exists(data_file):
print(f"Skipping {subfolder}: data file not found")
continue
print(f"Loading data from {data_file}")
data = torch.load(data_file)
print(f"Data shape: {data.shape}")
# Create tiles
print(f"Creating {tile_size}x{tile_size} tiles...")
tiles = create_tiles(data, tile_size=tile_size)
print(f"Created {len(tiles)} tiles from {subfolder}")
all_tiles.extend(tiles)
# Convert to tensor and save
all_tiles_tensor = torch.stack(all_tiles)
print(f"Total tiles: {len(all_tiles)}, Shape: {all_tiles_tensor.shape}")
# Save to cache
torch.save(all_tiles_tensor, cache_file)
print(f"Saved tiles to: {cache_file}")
return cache_file
def visualize_reconstruction(model, data_loader, device, save_path, num_samples=4):
"""Visualize original and reconstructed images with consistent colorbar scaling"""
model.eval()
# Get samples from data loader
x = next(iter(data_loader))[:num_samples].to(device)
# Get reconstructions
with torch.no_grad():
x_recon, z = model(x, add_noise=False)
# Move to CPU for visualization
x = x.cpu()
x_recon = x_recon.cpu()
# Use fixed channels for consistency instead of random channels
channels = []
for i in range(num_samples):
# Use evenly spaced channels
channel_idx = (i * (x.shape[1] // num_samples)) % x.shape[1]
channels.append(channel_idx)
# Find global min and max for consistent colorbar scaling
global_min = float('inf')
global_max = float('-inf')
for i in range(num_samples):
channel = channels[i]
global_min = min(global_min, x[i, channel].min().item(), x_recon[i, channel].min().item())
global_max = max(global_max, x[i, channel].max().item(), x_recon[i, channel].max().item())
# Also find global min/max for difference images
diff_min = float('inf')
diff_max = float('-inf')
for i in range(num_samples):
channel = channels[i]
diff = torch.abs(x[i, channel] - x_recon[i, channel])
diff_min = min(diff_min, diff.min().item())
diff_max = max(diff_max, diff.max().item())
# Create visualization
fig, axes = plt.subplots(num_samples, 3, figsize=(15, 4*num_samples))
for i in range(num_samples):
channel = channels[i]
# Original
im0 = axes[i, 0].imshow(x[i, channel], cmap='viridis', vmin=global_min, vmax=global_max)
axes[i, 0].set_title(f"Original (Ch {channel})")
axes[i, 0].axis('off')
plt.colorbar(im0, ax=axes[i, 0], fraction=0.046, pad=0.04)
# Reconstructed
im1 = axes[i, 1].imshow(x_recon[i, channel], cmap='viridis', vmin=global_min, vmax=global_max)
axes[i, 1].set_title(f"Reconstructed (Ch {channel})")
axes[i, 1].axis('off')
plt.colorbar(im1, ax=axes[i, 1], fraction=0.046, pad=0.04)
# Difference - use consistent scaling across all difference images
diff = torch.abs(x[i, channel] - x_recon[i, channel])
im2 = axes[i, 2].imshow(diff, cmap='hot', vmin=diff_min, vmax=diff_max)
mse = torch.mean(diff**2).item()
axes[i, 2].set_title(f"Difference (MSE: {mse:.6f})")
axes[i, 2].axis('off')
plt.colorbar(im2, ax=axes[i, 2], fraction=0.046, pad=0.04)
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches="tight")
print(f"Saved reconstruction visualization to: {save_path}")
plt.close()
def plot_loss_curves(train_losses, test_losses, save_path):
"""Plot training and test loss curves"""
plt.figure(figsize=(10, 6))
epochs = range(1, len(train_losses) + 1)
plt.plot(epochs, train_losses, 'b-', label='Training Loss')
plt.plot(epochs, test_losses, 'r-', label='Test Loss')
plt.title('Training and Test Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss (MSE)')
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig(save_path, dpi=300, bbox_inches="tight")
print(f"Saved loss curves to: {save_path}")
plt.close()
def train_model_stage1(model, train_loader, test_loader, args):
"""Train model in stage 1 and record key shapes"""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
model = model.to(device)
# Define separate optimizers for encoder and decoder
encoder_optimizer = optim.Adam(model.encoder.parameters(), lr=args.encoder_lr)
decoder_optimizer = optim.Adam(model.decoder.parameters(), lr=args.decoder_lr)
# Define loss function
criterion = nn.MSELoss()
# Initialize lists to store losses and condition numbers
train_losses = []
test_losses = []
condition_numbers = []
# Create directories for visualizations and recorded shapes
filter_dir = os.path.join(args.output_dir, "filter_evolution")
recon_dir = os.path.join(args.output_dir, "reconstructions")
shapes_dir = os.path.join(args.output_dir, "recorded_shapes")
csv_dir = os.path.join(args.output_dir, "csv_data")
os.makedirs(filter_dir, exist_ok=True)
os.makedirs(recon_dir, exist_ok=True)
os.makedirs(shapes_dir, exist_ok=True)
os.makedirs(csv_dir, exist_ok=True)
print(f"Created output directories:\n- {filter_dir}\n- {recon_dir}\n- {shapes_dir}\n- {csv_dir}")
# Dictionary to store recorded shapes
recorded_shapes = {}
recorded_metrics = {
'initial': {'condition_number': float('inf'), 'test_mse': float('inf')},
'lowest_condition_number': {'condition_number': float('inf'), 'test_mse': float('inf')},
'lowest_test_mse': {'condition_number': float('inf'), 'test_mse': float('inf')},
'final': {'condition_number': float('inf'), 'test_mse': float('inf')}
}
# Run a dummy forward pass to initialize shape
if args.use_fsf and model.encoder.pipeline is not None:
dummy_input = next(iter(train_loader))[:1].to(device)
with torch.no_grad():
model.encoder(dummy_input)
# Record initial shape
initial_shape = model.encoder.current_shape.clone()
initial_filter_output = model.encoder.filter_output.clone()
recorded_shapes['initial'] = initial_shape
# Calculate condition number
condition_number = calculate_condition_number(initial_filter_output)
condition_numbers.append(condition_number)
recorded_metrics['initial']['condition_number'] = condition_number
# Save initial shape
np_save_path = os.path.join(shapes_dir, "initial_shape.npy")
np.save(np_save_path, initial_shape.detach().cpu().numpy())
print(f"Saved initial shape to: {np_save_path}")
# Save visualization of initial shape
viz_save_path = os.path.join(shapes_dir, "initial_shape.png")
visualize_shape(initial_shape, viz_save_path)
# Save visualization of initial filter
filter_viz_path = os.path.join(filter_dir, "filter_initial.png")
visualize_filter(
model.encoder.filter_A.detach().cpu(),
filter_viz_path,
include_shape=True,
shape_pred=model.encoder.current_shape,
filter_output=model.encoder.filter_output
)
print(f"Saved initial filter visualization to: {filter_viz_path}")
print(f"Recorded initial shape with condition number: {condition_number:.4f}")
# Train for the specified number of epochs
best_test_loss = float('inf')
for epoch in range(args.epochs):
# Training phase
model.train()
epoch_loss = 0
with tqdm(train_loader, desc=f"Stage 1 Epoch {epoch+1}/{args.epochs}") as pbar:
for batch_idx, x in enumerate(pbar):
x = x.to(device)
# Forward pass
x_recon, z = model(x, add_noise=True, min_snr_db=args.min_snr, max_snr_db=args.max_snr)
# Calculate loss
loss = criterion(x_recon, x)
# Backward pass and optimization
encoder_optimizer.zero_grad()
decoder_optimizer.zero_grad()
loss.backward()
encoder_optimizer.step()
decoder_optimizer.step()
# Update progress bar
epoch_loss += loss.item()
pbar.set_postfix({"Loss": epoch_loss / (batch_idx + 1)})
# Calculate average epoch loss
avg_train_loss = epoch_loss / len(train_loader)
train_losses.append(avg_train_loss)
# Evaluation phase
model.eval()
test_loss = 0
with torch.no_grad():
for x in test_loader:
x = x.to(device)
x_recon, z = model(x, add_noise=False)
loss = criterion(x_recon, x)
test_loss += loss.item()
# Calculate average test loss
avg_test_loss = test_loss / len(test_loader)
test_losses.append(avg_test_loss)
# Get updated shape and filter output
if args.use_fsf and model.encoder.pipeline is not None:
with torch.no_grad():
dummy_input = next(iter(train_loader))[:1].to(device)
model.encoder(dummy_input)
current_shape = model.encoder.current_shape.clone()
current_filter_output = model.encoder.filter_output.clone()
# Calculate condition number
current_condition_number = calculate_condition_number(current_filter_output)
condition_numbers.append(current_condition_number)
# Visualize filter periodically
if (epoch + 1) % args.viz_interval == 0 or epoch == args.epochs - 1:
filter_viz_path = os.path.join(filter_dir, f"filter_epoch_{epoch+1}.png")
visualize_filter(
model.encoder.filter_A.detach().cpu(),
filter_viz_path,
include_shape=True,
shape_pred=model.encoder.current_shape,
filter_output=model.encoder.filter_output
)
print(f"Saved filter visualization to: {filter_viz_path}")
# Check for lowest condition number
if current_condition_number < recorded_metrics['lowest_condition_number']['condition_number']:
recorded_shapes['lowest_condition_number'] = current_shape
recorded_metrics['lowest_condition_number']['condition_number'] = current_condition_number
recorded_metrics['lowest_condition_number']['test_mse'] = avg_test_loss
# Save shape
np_save_path = os.path.join(shapes_dir, "lowest_condition_number_shape.npy")
np.save(np_save_path, current_shape.detach().cpu().numpy())
print(f"Saved lowest condition number shape to: {np_save_path}")
# Save visualization
viz_save_path = os.path.join(shapes_dir, "lowest_condition_number_shape.png")
visualize_shape(current_shape, viz_save_path)
# Save filter visualization
filter_viz_path = os.path.join(filter_dir, "lowest_condition_number_filter.png")
visualize_filter(
model.encoder.filter_A.detach().cpu(),
filter_viz_path,
include_shape=True,
shape_pred=current_shape,
filter_output=current_filter_output
)
print(f"New lowest condition number: {current_condition_number:.4f}")
# Check for lowest test MSE
if avg_test_loss < recorded_metrics['lowest_test_mse']['test_mse']:
recorded_shapes['lowest_test_mse'] = current_shape
recorded_metrics['lowest_test_mse']['condition_number'] = current_condition_number