-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGNN_PlotFigure.py
More file actions
executable file
·9865 lines (8506 loc) · 467 KB
/
GNN_PlotFigure.py
File metadata and controls
executable file
·9865 lines (8506 loc) · 467 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
import os
import umap
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.ticker import FormatStrFormatter
from matplotlib.animation import FFMpegWriter
from torch_geometric.loader import DataLoader
import torch_geometric.data as data
import imageio.v2 as imageio
from matplotlib import rc
from scipy.optimize import curve_fit
from sklearn.mixture import GaussianMixture
from sklearn.decomposition import TruncatedSVD
import scipy.sparse
from shutil import copyfile
from collections import defaultdict
import scipy
import logging
import re
import matplotlib
import pandas as pd
# os.environ["PATH"] += os.pathsep + '/usr/local/texlive/2023/bin/x86_64-linux'
# from data_loaders import *
from NeuralGraph.fitting_models import linear_model
from NeuralGraph.sparsify import EmbeddingCluster, sparsify_cluster, clustering_gmm
from NeuralGraph.models.utils import (
choose_training_model,
get_in_features,
get_in_features_update,
get_index_particles,
analyze_odor_responses_by_neuron,
plot_odor_heatmaps,
analyze_data_svd,
compute_normalization_value,
)
from NeuralGraph.models.plot_utils import (
analyze_mlp_edge_lines,
analyze_mlp_edge_lines_weighted_with_max,
analyze_mlp_phi_synaptic,
find_top_responding_pairs,
run_neural_architecture_pipeline,
)
from NeuralGraph.utils import (
to_numpy,
CustomColorMap,
sort_key,
fig_init,
get_equidistant_points,
map_matrix,
create_log_dir,
find_suffix_pairs_with_index,
add_pre_folder
)
from NeuralGraph.models.Siren_Network import Siren, Siren_Network
from NeuralGraph.models.Signal_Propagation_FlyVis import Signal_Propagation_FlyVis
from NeuralGraph.models.Signal_Propagation_Zebra import Signal_Propagation_Zebra
from NeuralGraph.models.graph_trainer import data_test
from NeuralGraph.generators.utils import choose_model
from NeuralGraph.config import NeuralGraphConfig
from NeuralGraph.models.Ising_analysis import analyze_ising_model
from scipy import stats
from scipy.linalg import orthogonal_procrustes
from io import StringIO
import sys
import warnings
import seaborn as sns
import glob
import numpy as np
import pickle
import json
from tqdm import tqdm, trange
import time
from sklearn import metrics
from tifffile import imread
import matplotlib.ticker as ticker
import shutil
# Suppress matplotlib/PDF warnings
warnings.filterwarnings('ignore', category=UserWarning, module='matplotlib')
warnings.filterwarnings('ignore', message='.*Glyph.*')
warnings.filterwarnings('ignore', message='.*Missing.*')
# Suppress fontTools logging (PDF font subsetting messages)
logging.getLogger('fontTools').setLevel(logging.ERROR)
logging.getLogger('fontTools.subset').setLevel(logging.ERROR)
# Configure matplotlib for Helvetica-style fonts (no LaTeX)
plt.rcParams.update({
'font.family': 'sans-serif',
'font.sans-serif': ['Nimbus Sans', 'Arial', 'Helvetica', 'DejaVu Sans'],
'text.usetex': False,
'mathtext.fontset': 'dejavusans', # sans-serif math text
})
# Optional dependency
# try:
# from pysr import PySRRegressor
# except (ImportError, subprocess.CalledProcessError):
# PySRRegressor = None
def get_model_W(model):
"""Get the weight matrix from a model, handling low-rank factorization."""
if hasattr(model, 'W'):
return model.W
elif hasattr(model, 'WL') and hasattr(model, 'WR'):
return model.WL @ model.WR
else:
raise AttributeError("Model has neither 'W' nor 'WL'/'WR' attributes")
def get_training_files(log_dir, n_runs):
files = glob.glob(f"{log_dir}/models/best_model_with_{n_runs - 1}_graphs_*.pt")
if len(files) == 0:
return [], np.array([])
files.sort(key=sort_key)
# Find the first file with positive sort_key
file_id = 0
while file_id < len(files) and sort_key(files[file_id]) <= 0:
file_id += 1
# If all files have non-positive sort_key, use all files
if file_id >= len(files):
file_id = 0
files = files[file_id:]
# Filter based on the Y value (number after "graphs")
files_with_0 = [file for file in files if int(file.split('_')[-2]) == 0]
files_without_0 = [file for file in files if int(file.split('_')[-2]) != 0]
# Generate 50 evenly spaced indices for each list
# indices_with_0 = np.linspace(0, len(files_with_0) - 1, dtype=int)
indices_with_0 = np.arange(0, len(files_with_0) - 1, dtype=int)
indices_without_0 = np.linspace(0, len(files_without_0) - 1, 50, dtype=int)
# Select the files using the generated indices
selected_files_with_0 = [files_with_0[i] for i in indices_with_0]
if len(files_without_0) > 0:
selected_files_without_0 = [files_without_0[i] for i in indices_without_0]
selected_files = selected_files_with_0 + selected_files_without_0
else:
selected_files = selected_files_with_0
return selected_files, np.arange(0, len(selected_files), 1)
# len_files = len(files)
# print(len_files, len_files//10, len_files//500, len_files//10, len_files, len_files//50)
# file_id_list0 = np.arange(0, len_files//10, len_files//500)
# file_id_list1 = np.arange(len_files//10, len_files, len_files//50)
# file_id_list = np.concatenate((file_id_list0, file_id_list1))
# # file_id_list = np.arange(0, len(files), (len(files) / 100)).astype(int)
# return files, file_id_list
def load_training_data(dataset_name, n_runs, log_dir, device):
x_list = []
y_list = []
print('load data ...')
time.sleep(0.5)
for run in trange(n_runs, ncols=90):
# check if path exists
if os.path.exists(f'graphs_data/{dataset_name}/x_list_{run}.pt'):
x = torch.load(f'graphs_data/{dataset_name}/x_list_{run}.pt', map_location=device)
y = torch.load(f'graphs_data/{dataset_name}/y_list_{run}.pt', map_location=device)
else:
x = np.load(f'graphs_data/{dataset_name}/x_list_{run}.npy')
x = torch.tensor(x, dtype=torch.float32, device=device)
y = np.load(f'graphs_data/{dataset_name}/y_list_{run}.npy')
y = torch.tensor(y, dtype=torch.float32, device=device)
x_list.append(x)
y_list.append(y)
vnorm = torch.load(os.path.join(log_dir, 'vnorm.pt'), map_location=device).squeeze()
ynorm = torch.load(os.path.join(log_dir, 'ynorm.pt'), map_location=device).squeeze()
print("vnorm:{:.2e}, ynorm:{:.2e}".format(to_numpy(vnorm), to_numpy(ynorm)))
x = []
y = []
return x_list, y_list, vnorm, ynorm
def plot_confusion_matrix(index, true_labels, new_labels, n_neuron_types, epoch, it, fig, ax, style):
# print(f'plot confusion matrix epoch:{epoch} it: {it}')
plt.text(-0.25, 1.1, f'{index}', ha='left', va='top', transform=ax.transAxes, fontsize=12)
confusion_matrix = metrics.confusion_matrix(true_labels, new_labels) # , normalize='true')
cm_display = metrics.ConfusionMatrixDisplay(confusion_matrix=confusion_matrix)
if n_neuron_types > 8:
cm_display.plot(ax=fig.gca(), cmap='Blues', include_values=False, colorbar=False)
else:
cm_display.plot(ax=fig.gca(), cmap='Blues', include_values=True, values_format='d', colorbar=False)
accuracy = metrics.accuracy_score(true_labels, new_labels)
plt.title(f'accuracy: {np.round(accuracy, 2)}', fontsize=12)
# print(f'accuracy: {np.round(accuracy,3)}')
plt.xticks(fontsize=10.0)
plt.yticks(fontsize=10.0)
plt.xlabel(r'Predicted label', fontsize=12)
plt.ylabel(r'True label', fontsize=12)
return accuracy
# =============================================================================
# Movie generation functions for plot_signal
# =============================================================================
def determine_plot_limits_signal(config, log_dir, n_runs, device, n_neurons, type_list, cmap, connectivity, xnorm, ynorm, n_samples=5, true_model=None, n_neuron_types=1):
"""
Sample a few models to determine stable xlim/ylim for movies.
Returns dict with limits for each plot type.
Args:
true_model: Ground truth model for computing true MLP limits (optional)
n_neuron_types: Number of neuron types for true curve computation
"""
files, file_id_list = get_training_files(log_dir, n_runs)
if len(file_id_list) == 0:
return None
model, bc_pos, bc_dpos = choose_training_model(config, device)
# Sample indices evenly distributed
sample_indices = np.linspace(0, len(file_id_list) - 1, min(n_samples, len(file_id_list)), dtype=int)
# Collect ranges
weight_min, weight_max = [], []
embedding_min, embedding_max = [], []
lin_edge_min, lin_edge_max = [], []
lin_phi_min, lin_phi_max = [], []
# Compute true model limits first if available
rr = torch.linspace(-xnorm.squeeze(), xnorm.squeeze(), 100).to(device)
if true_model is not None:
with torch.no_grad():
for n in range(n_neuron_types):
# True lin_edge (phi) limits
true_func = true_model.func(rr, n, 'phi')
lin_edge_min.append(to_numpy(true_func).min())
lin_edge_max.append(to_numpy(true_func).max())
# True lin_phi (update) limits
true_func = true_model.func(rr, n, 'update')
lin_phi_min.append(to_numpy(true_func).min())
lin_phi_max.append(to_numpy(true_func).max())
with torch.no_grad():
for idx in sample_indices:
file_id = file_id_list[idx]
epoch = files[file_id].split('graphs')[1][1:-3]
net = f"{log_dir}/models/best_model_with_{n_runs-1}_graphs_{epoch}.pt"
state_dict = torch.load(net, map_location=device)
model.load_state_dict(state_dict['model_state_dict'])
model.eval()
# Weight comparison limits
gt_weight = to_numpy(connectivity).flatten()
pred_weight = to_numpy(get_model_W(model)).flatten()
weight_min.extend([gt_weight.min(), pred_weight.min()])
weight_max.extend([gt_weight.max(), pred_weight.max()])
# Embedding limits
amax = torch.max(model.a, dim=0).values
amin = torch.min(model.a, dim=0).values
model_a = (model.a - amin) / (amax - amin)
embedding_min.append(0)
embedding_max.append(1)
# Lin_edge limits
model_name = config.graph_model.signal_model_name
if model_name in ['PDE_N2', 'PDE_N3', 'PDE_N6']:
# Simple models: single input
in_features = rr[:, None]
func = model.lin_edge(in_features.float())
if config.graph_model.lin_edge_positive:
func = func ** 2
lin_edge_min.append(to_numpy(func).min())
lin_edge_max.append(to_numpy(func).max())
else:
# Models with embeddings (PDE_N4, PDE_N5, PDE_N7, PDE_N8, PDE_N11, etc.)
for n in range(min(10, n_neurons)):
embedding_ = model.a[n, :] * torch.ones((100, config.graph_model.embedding_dim), device=device)
if model_name in ['PDE_N4', 'PDE_N7', 'PDE_N11']:
in_features = torch.cat((rr[:, None], embedding_), dim=1)
elif model_name == 'PDE_N5':
in_features = torch.cat((rr[:, None], embedding_, embedding_), dim=1)
elif model_name == 'PDE_N8':
in_features = torch.cat((rr[:, None]*0, rr[:, None], embedding_, embedding_), dim=1)
else:
in_features = torch.cat((rr[:, None], embedding_), dim=1)
func = model.lin_edge(in_features.float())
if config.graph_model.lin_edge_positive:
func = func ** 2
lin_edge_min.append(to_numpy(func).min())
lin_edge_max.append(to_numpy(func).max())
# Lin_phi limits
for n in range(min(10, n_neurons)):
embedding_ = model.a[n, :] * torch.ones((100, config.graph_model.embedding_dim), device=device)
in_features = get_in_features_update(rr[:, None], model, embedding_, device)
func = model.lin_phi(in_features.float())
lin_phi_min.append(to_numpy(func).min() * to_numpy(ynorm))
lin_phi_max.append(to_numpy(func).max() * to_numpy(ynorm))
# Add margins
margin = 0.1
limits = {
'weight': (min(weight_min) * (1 + margin), max(weight_max) * (1 + margin)),
'embedding': (-0.1, 1.1),
'lin_edge': (min(lin_edge_min) * (1 + margin) - 0.1, max(lin_edge_max) * (1 + margin) + 0.1),
'lin_phi': (min(lin_phi_min) * (1 + margin) - 0.5, max(lin_phi_max) * (1 + margin) + 0.5),
}
return limits
def create_signal_weight_subplot(fig, ax, model, connectivity, mc, epoch, iteration, config, limits, second_correction=1.0, apply_weight_correction=False, xnorm=None, device=None):
"""Create weight comparison scatter plot for signal models.
Args:
second_correction: Correction factor to apply to predicted weights (default 1.0 = no correction)
apply_weight_correction: Compute and apply per-neuron correction on the fly (default False)
xnorm: Normalization value for computing correction (required if apply_weight_correction=True)
device: Torch device (required if apply_weight_correction=True)
"""
n_neurons = connectivity.shape[0]
n_plot = n_neurons
A = get_model_W(model)[:n_plot, :n_plot].clone().detach()
A.fill_diagonal_(0)
# compute and apply per-neuron correction on the fly
if apply_weight_correction and xnorm is not None and device is not None:
# compute correction from MLP1 at high x values (same as 'best' option)
rr = torch.linspace(0, xnorm.squeeze() * 4, 1000).to(device)
func_list = []
model_config = config.graph_model
for n in range(n_plot):
if model_config.signal_model_name in ['PDE_N4', 'PDE_N5', 'PDE_N7', 'PDE_N11']:
embedding_ = model.a[n, :] * torch.ones((1000, config.graph_model.embedding_dim), device=device)
if model_config.signal_model_name in ['PDE_N4', 'PDE_N7', 'PDE_N11']:
in_features = torch.cat((rr[:, None], embedding_), dim=1)
elif model_config.signal_model_name == 'PDE_N5':
in_features = torch.cat((rr[:, None], embedding_, embedding_), dim=1)
else:
in_features = torch.cat((rr[:, None], embedding_), dim=1)
else:
in_features = rr[:, None]
with torch.no_grad():
func = model.lin_edge(in_features.float())
if config.graph_model.lin_edge_positive:
func = func ** 2
func_list.append(func)
func_list = torch.stack(func_list).squeeze()
upper = torch.median(func_list[:, 850:1000], dim=1)[0]
correction = 1 / (upper + 1E-16)
# apply correction: transpose, apply row-wise, transpose back
A_t = A.t()
correction_np = to_numpy(correction[:n_plot])
pred_weight = to_numpy(A_t)
for row in range(n_plot):
pred_weight[row, :] = pred_weight[row, :] / correction_np[row]
pred_weight = pred_weight.T.flatten()
else:
pred_weight = to_numpy(A).flatten() / second_correction
gt_weight = to_numpy(connectivity[:n_plot, :n_plot]).flatten()
# adjust scatter plot parameters based on number of neurons (consistent with 'best' mode)
if n_neurons < 1000:
scatter_size = 1
scatter_alpha = 1.0
else:
scatter_size = 0.1
scatter_alpha = 0.1
# plot green diagonal line (y=x, perfect correlation) first
weight_max = np.max(np.abs(gt_weight)) * 1.1
weight_lim = (-weight_max, weight_max)
ax.plot(weight_lim, weight_lim, c='g', linewidth=4, zorder=1)
ax.scatter(gt_weight, pred_weight, s=scatter_size, c=mc, alpha=scatter_alpha, zorder=2)
# compute R² and slope
lin_fit, _ = curve_fit(linear_model, gt_weight, pred_weight)
residuals = pred_weight - linear_model(gt_weight, *lin_fit)
ss_res = np.sum(residuals ** 2)
ss_tot = np.sum((pred_weight - np.mean(pred_weight)) ** 2)
r_squared = 1 - (ss_res / ss_tot) if ss_tot > 0 else 0
# variable names based on model type
if 'PDE_N11' in config.graph_model.signal_model_name:
true_weight_var = '$J_{ij}$'
learned_weight_var = '$J_{ij}^*$'
else:
true_weight_var = '$W_{ij}$'
learned_weight_var = '$W_{ij}^*$'
ax.set_xlabel(f'true {true_weight_var}', fontsize=32)
ax.set_ylabel(f'learned {learned_weight_var}', fontsize=32)
# ax.set_xlim(weight_lim)
# ax.set_ylim(weight_lim)
ax.tick_params(labelsize=16)
# add R² and slope text
ax.text(0.05, 0.95, f'$R^2$: {r_squared:.3f}', transform=ax.transAxes,
fontsize=20, verticalalignment='top')
ax.text(0.05, 0.87, f'slope: {lin_fit[0]:.2f}', transform=ax.transAxes,
fontsize=20, verticalalignment='top')
ax.text(0.05, 0.79, f'epoch: {epoch}', transform=ax.transAxes,
fontsize=16, verticalalignment='top')
return r_squared, lin_fit[0]
def create_signal_embedding_subplot(fig, ax, model, type_list, n_neuron_types, cmap, limits):
"""Create embedding scatter plot for signal models."""
# amax = torch.max(model.a, dim=0).values
# amin = torch.min(model.a, dim=0).values
# model_a = (model.a - amin) / (amax - amin + 1E-8)
for n in range(n_neuron_types - 1, -1, -1):
pos = torch.argwhere(type_list == n).squeeze()
if pos.numel() > 0:
ax.scatter(to_numpy(model.a[pos, 0]), to_numpy(model.a[pos, 1]),
s=30, color=cmap.color(n), alpha=0.8, edgecolors='none')
ax.set_xlabel(r'$\mathbf{a}_0$', fontsize=32)
ax.set_ylabel(r'$\mathbf{a}_1$', fontsize=32)
# ax.set_xlim([-0.2, 1.2])
# ax.set_ylim([-0.2, 1.2])
ax.tick_params(labelsize=16)
def create_signal_lin_edge_subplot(fig, ax, model, config, n_neurons, type_list, cmap, device, xnorm, limits, mc, label_style='MLP', true_model=None, n_neuron_types=1, apply_weight_correction=False):
"""Create lin_edge function plot for signal models.
Args:
label_style: 'MLP' for MLP_0, MLP_1 labels; 'greek' for phi, f labels
true_model: Ground truth model for plotting true curves (optional)
n_neuron_types: Number of neuron types for true curve plotting
apply_weight_correction: Compute and apply per-neuron correction on the fly (default False)
"""
rr = torch.linspace(-xnorm.squeeze(), xnorm.squeeze(), 1000).to(device)
model_name = config.graph_model.signal_model_name
# Compute normalization factor from true model at x > 6 (asymptotic region)
norm_factor = 1.0
if true_model is not None:
with torch.no_grad():
# Evaluate at x > 6 to get true asymptotic value (well into saturation for tanh)
rr_asymptotic = torch.linspace(6.0, 10.0, 100).to(device)
true_max = 0.0
for n in range(n_neuron_types):
true_func = true_model.func(rr_asymptotic, n, 'phi')
# Get mean absolute value in asymptotic region
true_asymptotic = torch.abs(true_func).mean().item()
true_max = max(true_max, true_asymptotic)
if true_max > 0:
norm_factor = true_max
# Plot true curves first (green, thick) if true_model is provided
# Plot one curve per neuron, colored by neuron type
if true_model is not None:
neuron_types = to_numpy(type_list).astype(int)
for n in range(n_neurons):
neuron_type = int(neuron_types[n])
true_func = true_model.func(rr, neuron_type, 'phi')
ax.plot(to_numpy(rr), to_numpy(true_func) / norm_factor, color=cmap.color(neuron_type), linewidth=8, alpha=1.0)
max_radius = config.simulation.max_radius
if model_name in ['PDE_N2', 'PDE_N3', 'PDE_N6']:
# Simple models: single line, single input
in_features = rr[:, None]
with torch.no_grad():
func = model.lin_edge(in_features.float())
if config.graph_model.lin_edge_positive:
func = func ** 2
ax.plot(to_numpy(rr), to_numpy(func) / norm_factor, color='w', linewidth=4)
else:
# Models with embeddings: multiple lines per type (PDE_N4, PDE_N5, PDE_N7, PDE_N8, PDE_N11, etc.)
if apply_weight_correction:
# First pass: compute per-neuron correction
rr = torch.linspace(0 , xnorm.squeeze() * 4 , 1000).to(device)
func_list = []
for n in range(0,n_neurons):
if config.graph_model.signal_model_name in ['PDE_N4', 'PDE_N5', 'PDE_N7', 'PDE_N11']:
embedding_ = model.a[n, :] * torch.ones((1000, config.graph_model.embedding_dim), device=device)
if config.graph_model.signal_model_name in ['PDE_N4', 'PDE_N7', 'PDE_N11']:
in_features = torch.cat((rr[:, None], embedding_), dim=1)
elif config.graph_model.signal_model_name == 'PDE_N5':
in_features = torch.cat((rr[:, None], embedding_, embedding_), dim=1)
else:
in_features = get_in_features(rr, embedding_, model, model_config.signal_model_name, max_radius) # noqa: F821
else:
in_features = rr[:,None]
with torch.no_grad():
func = model.lin_edge(in_features.float())
if config.graph_model.lin_edge_positive:
func = func ** 2
func_list.append(func)
func_list = torch.stack(func_list).squeeze()
# Use compute_normalization_value with config parameters
xnorm_val = xnorm.squeeze().item()
norm_method = getattr(config.plotting, 'norm_method', 'median')
norm_x_start = getattr(config.plotting, 'norm_x_start', None)
norm_x_stop = getattr(config.plotting, 'norm_x_stop', None)
# Default: use 85%-100% of the rr range (which goes to 4*xnorm)
x_start = norm_x_start * xnorm_val if norm_x_start is not None else 0.85 * xnorm_val * 4
x_stop = norm_x_stop * xnorm_val if norm_x_stop is not None else xnorm_val * 4
upper = compute_normalization_value(func_list, rr, method=norm_method,
x_start=x_start,
x_stop=x_stop,
per_neuron=True)
correction = 1 / (upper + 1E-16)
# Second pass: plot with correction applied
rr = torch.linspace(-xnorm.squeeze(), xnorm.squeeze(), 1500).to(device)
for n in range(0,n_neurons):
if config.graph_model.signal_model_name in ['PDE_N4', 'PDE_N5', 'PDE_N7', 'PDE_N11']:
embedding_ = model.a[n, :] * torch.ones((1500, config.graph_model.embedding_dim), device=device)
in_features = get_in_features(rr, embedding_, model, config.graph_model.signal_model_name, max_radius)
else:
in_features = rr[:, None]
with torch.no_grad():
if config.graph_model.lin_edge_positive:
func = model.lin_edge(in_features.float()) ** 2 * correction[n]
else:
func = model.lin_edge(in_features.float()) * correction[n]
plt.plot(to_numpy(rr), to_numpy(func), color='w', linewidth=1, alpha=0.25)
else:
# No correction: plot raw functions
for n in range(n_neurons):
embedding_ = model.a[n, :] * torch.ones((1000, config.graph_model.embedding_dim), device=device)
in_features = get_in_features(rr, embedding_, model, model_name, max_radius)
with torch.no_grad():
func = model.lin_edge(in_features.float())
if config.graph_model.lin_edge_positive:
func = func ** 2
ax.plot(to_numpy(rr), to_numpy(func),
color='w', linewidth=1, alpha=0.25)
# variable names
if 'PDE_N11' in model_name:
signal_var = '$h_j$'
else:
signal_var = '$v_j$'
# label style
if label_style == 'MLP':
ylabel = r'$\mathrm{MLP_1}(\mathbf{a}_j, h_j)$'
else:
ylabel = r'$f$'
ax.set_xlabel(signal_var, fontsize=32)
ax.set_ylabel(ylabel, fontsize=32)
ax.set_xlim(config.plotting.mlp1_xlim)
ax.set_ylim(config.plotting.mlp1_ylim)
ax.tick_params(labelsize=16)
def create_signal_lin_phi_subplot(fig, ax, model, config, n_neurons, type_list, cmap, device, xnorm, ynorm, limits, label_style='MLP', true_model=None, n_neuron_types=1):
"""Create lin_phi function plot for signal models.
Args:
label_style: 'MLP' for MLP_0, MLP_1 labels; 'greek' for phi, f labels
true_model: Ground truth model for plotting true curves (optional)
n_neuron_types: Number of neuron types for true curve plotting
"""
rr = torch.linspace(-xnorm.squeeze(), xnorm.squeeze(), 1000).to(device)
# Plot true curves first (one curve per neuron, colored by neuron type)
if true_model is not None:
neuron_types = to_numpy(type_list).astype(int)
for n in range(n_neurons):
neuron_type = int(neuron_types[n])
true_func = true_model.func(rr, neuron_type, 'update')
ax.plot(to_numpy(rr), to_numpy(true_func), color=cmap.color(neuron_type), linewidth=8, alpha=1.0)
for n in range(n_neurons):
embedding_ = model.a[n, :] * torch.ones((1000, config.graph_model.embedding_dim), device=device)
in_features = get_in_features_update(rr[:, None], model, embedding_, device)
with torch.no_grad():
func = model.lin_phi(in_features.float())
func = func[:, 0]
ax.plot(to_numpy(rr), to_numpy(func) * to_numpy(ynorm),
color='w', linewidth=1, alpha=0.3)
# Variable names and labels
if 'PDE_N11' in config.graph_model.signal_model_name:
signal_var = '$h_i$'
else:
signal_var = '$v_i$'
# Label style
if label_style == 'MLP':
if config.training.training_single_type:
ylabel = rf'$\mathrm{{MLP_0}}({signal_var[1:-1]})$'
else:
ylabel = rf'$\mathrm{{MLP_0}}(\mathbf{{a}}_i, {signal_var[1:-1]})$'
else:
if config.training.training_single_type:
ylabel = rf'$\phi({signal_var[1:-1]})$'
else:
ylabel = rf'$\phi(\mathbf{{a}}_i, {signal_var[1:-1]})$'
ax.set_xlabel(signal_var, fontsize=32)
ax.set_ylabel(ylabel, fontsize=32)
ax.set_xlim(config.plotting.mlp0_xlim)
ax.set_ylim(config.plotting.mlp0_ylim)
ax.tick_params(labelsize=16)
def create_signal_excitation_subplot(fig, ax, model, config, n_frames, mc, device,
connectivity=None, second_correction=1.0):
"""Create excitation function plot for signal models.
Shows learned oscillation excitation function vs ground truth cosine.
Args:
connectivity: Connectivity matrix (used for computing e_i slope correction)
second_correction: Correction factor from weight comparison (default 1.0)
"""
simulation_config = config.simulation
with torch.no_grad():
kk = torch.arange(0, n_frames, dtype=torch.float32, device=device) / model.NNR_f_T_period
excitation_field = model.NNR_f(kk[:, None])
model_a = model.a[-1] * torch.ones((n_frames, 1), device=device)
in_features = torch.cat([excitation_field, model_a], dim=1)
msg = model.lin_edge(in_features)
msg_raw = to_numpy(msg.squeeze())
frame_ = np.arange(0, len(msg_raw)) / len(msg_raw)
# Ground truth uses oscillation_max_amplitude from config
gt_max_amplitude = getattr(simulation_config, 'oscillation_max_amplitude', 1.0)
gt_excitation = gt_max_amplitude * np.cos((2 * np.pi) * simulation_config.oscillation_frequency * frame_)
# Compute exc_slope from e_i weights (if connectivity provided)
exc_slope = 1.0
if connectivity is not None:
gt_weight_exc = to_numpy(connectivity[:-1, -1])
pred_weight_exc = -to_numpy(get_model_W(model)[:-1, -1]) / second_correction
# Simple linear regression for slope
x_mean = np.mean(gt_weight_exc)
y_mean = np.mean(pred_weight_exc)
denom = np.sum((gt_weight_exc - x_mean) ** 2)
if denom > 1e-10:
exc_slope = np.sum((gt_weight_exc - x_mean) * (pred_weight_exc - y_mean)) / denom
if abs(exc_slope) < 0.01:
exc_slope = 1.0 # Avoid division by very small number
# e_i is corrected by: / second_correction / exc_slope
# f(t) should be corrected by: / exc_slope (to match e_i scale)
excitation = -msg_raw / exc_slope
# Plot ground truth (green, thick)
ax.plot(gt_excitation, c='g', linewidth=8, alpha=0.75, label='ground truth')
# Plot learned (marker color, thinner)
ax.plot(excitation, c=mc, linewidth=1, label='learned')
ax.set_xlabel('$t$', fontsize=32)
ax.set_ylabel('$\\mathrm{INR}(t)$', fontsize=32)
ax.tick_params(labelsize=16)
ax.set_xlim([0, 2000]) # Zoom into first 2000 frames
# Set ylim based on ground truth amplitude
ax.set_ylim([-gt_max_amplitude * 1.2, gt_max_amplitude * 1.2])
ax.legend(fontsize=16, loc='upper right')
# ============================================================================
# Shared Movie Creation Helpers
# ============================================================================
def setup_movies_directory(log_dir):
"""Create and return movies directory path.
Args:
log_dir: Log directory path
Returns:
movies_dir: Path to movies directory
"""
movies_dir = f'{log_dir}/results/movies'
os.makedirs(movies_dir, exist_ok=True)
return movies_dir
def create_movie(mp4_path, jpg_path, figsize, fps, metadata, file_id_list, frame_callback, dpi=100):
"""Generic movie creation loop.
Args:
mp4_path: Path for output MP4 file
jpg_path: Path for first frame JPG (can be None to skip)
figsize: Figure size tuple
fps: Frames per second
metadata: Metadata dict for FFMpegWriter
file_id_list: List of file indices to iterate
frame_callback: Function(fig, file_id_) that creates each frame
dpi: DPI for movie frames
Returns:
Result from frame_callback if any (e.g., r_squared_list)
"""
writer = FFMpegWriter(fps=fps, metadata=metadata)
fig = plt.figure(figsize=figsize)
first_frame_saved = False
results = []
with writer.saving(fig, mp4_path, dpi=dpi):
for file_id_ in tqdm(range(len(file_id_list)), desc=os.path.basename(mp4_path).replace('.mp4', ''), ncols=90):
plt.clf()
result = frame_callback(fig, file_id_)
if result is not None:
results.append(result)
plt.tight_layout()
writer.grab_frame()
if jpg_path and not first_frame_saved:
plt.savefig(jpg_path, dpi=150, bbox_inches='tight')
first_frame_saved = True
plt.close(fig)
return results if results else None
def load_model_state(model, net_path, device):
"""Load model state from checkpoint.
Args:
model: Model instance to load state into
net_path: Path to checkpoint file
device: Torch device
Returns:
model: Model with loaded state in eval mode
"""
state_dict = torch.load(net_path, map_location=device)
model.load_state_dict(state_dict['model_state_dict'])
model.eval()
return model
def get_epoch_from_file(file_path, n_runs):
"""Extract epoch number from model file path.
Args:
file_path: Path to model file
n_runs: Number of training runs
Returns:
epoch: Epoch string
"""
return file_path.split('graphs')[1][1:-3]
# ============================================================================
def create_signal_movies(config, log_dir, n_runs, device, n_neurons, n_neuron_types, type_list,
cmap, connectivity, xnorm, ynorm, mc, fps=10,
true_model=None, apply_weight_correction=False):
"""
Create movies for signal model training visualization.
Args:
config: Configuration object
log_dir: Log directory path
n_runs: Number of training runs
device: Torch device
n_neurons: Number of neurons
n_neuron_types: Number of neuron types
type_list: Tensor of neuron types
cmap: Color map
connectivity: Ground truth connectivity matrix
xnorm, ynorm: Normalization values
mc: Marker color ('k' or 'w')
fps: Frames per second for movies
true_model: Ground truth model for plotting true curves (optional)
apply_weight_correction: Apply per-neuron correction from correction.pt (default False)
"""
# Get label_style from config (default to 'MLP')
label_style = getattr(config.plotting, 'label_style', 'MLP')
n_frames = config.simulation.n_frames
# Extract just the base name from dataset (may contain path like 'signal/signal_N11_1')
dataset_name = os.path.basename(config.dataset)
movies_dir = setup_movies_directory(log_dir)
# get training files
files, file_id_list = get_training_files(log_dir, n_runs)
if len(file_id_list) == 0:
print('no training files found for movie creation')
return
# determine stable plot limits
print('determining plot limits...')
limits = determine_plot_limits_signal(config, log_dir, n_runs, device, n_neurons, type_list,
cmap, connectivity, xnorm, ynorm,
true_model=true_model, n_neuron_types=n_neuron_types)
if limits is None:
print('could not determine plot limits')
return
model, bc_pos, bc_dpos = choose_training_model(config, device)
# load second_correction if available (computed in 'best' mode)
second_correction_path = f'{log_dir}/second_correction.npy'
if os.path.exists(second_correction_path):
second_correction = float(np.load(second_correction_path))
else:
second_correction = 1.0
metadata = {'title': f'{dataset_name} training', 'artist': 'NeuralGraph'}
# movie configurations: (name, figsize, create_function)
movie_configs = [
('weights', (8, 8), 'weight'),
('embedding', (8, 8), 'embedding'),
('lin_edge', (8, 8), 'lin_edge'),
('lin_phi', (8, 8), 'lin_phi'),
]
r_squared_list = []
slope_list = []
# add 'without' suffix if correction is not applied
suffix = '' if apply_weight_correction else '_without'
for movie_name, figsize, plot_type in movie_configs:
mp4_path = f'{movies_dir}/{movie_name}_{dataset_name}{suffix}.mp4'
jpg_path = f'{movies_dir}/{movie_name}_{dataset_name}{suffix}.jpg'
writer = FFMpegWriter(fps=fps, metadata=metadata)
fig = plt.figure(figsize=figsize)
first_frame_saved = False
with writer.saving(fig, mp4_path, dpi=100):
for file_id_ in tqdm(range(len(file_id_list)), desc=f'{movie_name}', ncols=90):
plt.clf()
ax = fig.add_subplot(111)
file_id = file_id_list[file_id_]
epoch = get_epoch_from_file(files[file_id], n_runs)
net = f"{log_dir}/models/best_model_with_{n_runs-1}_graphs_{epoch}.pt"
load_model_state(model, net, device)
with torch.no_grad():
if plot_type == 'weight':
r2, slope = create_signal_weight_subplot(fig, ax, model, connectivity, mc,
epoch, file_id_, config, limits, second_correction,
apply_weight_correction=apply_weight_correction,
xnorm=xnorm, device=device)
if movie_name == 'weights':
r_squared_list.append(r2)
slope_list.append(slope)
elif plot_type == 'embedding':
create_signal_embedding_subplot(fig, ax, model, type_list, n_neuron_types, cmap, limits)
elif plot_type == 'lin_edge':
create_signal_lin_edge_subplot(fig, ax, model, config, n_neurons, type_list,
cmap, device, xnorm, limits, mc, label_style,
true_model=true_model, n_neuron_types=n_neuron_types,
apply_weight_correction=apply_weight_correction)
elif plot_type == 'lin_phi':
create_signal_lin_phi_subplot(fig, ax, model, config, n_neurons, type_list,
cmap, device, xnorm, ynorm, limits, label_style,
true_model=true_model, n_neuron_types=n_neuron_types)
plt.tight_layout()
writer.grab_frame()
# Save first frame as JPG
if not first_frame_saved:
plt.savefig(jpg_path, dpi=150, bbox_inches='tight')
first_frame_saved = True
plt.close(fig)
# create combined 2x2 movie
mp4_path_combined = f'{movies_dir}/combined_{dataset_name}{suffix}.mp4'
jpg_path_combined = f'{movies_dir}/combined_{dataset_name}{suffix}.jpg'
# check if training_single_type is enabled (skip embedding panel if so)
training_single_type = getattr(config.training, 'training_single_type', False) or getattr(config.training, 'init_training_single_type', False)
writer = FFMpegWriter(fps=fps, metadata=metadata)
fig = plt.figure(figsize=(16, 16))
first_frame_saved = False
with writer.saving(fig, mp4_path_combined, dpi=100):
for file_id_ in tqdm(range(len(file_id_list)), desc='combined', ncols=90):
plt.clf()
file_id = file_id_list[file_id_]
epoch = get_epoch_from_file(files[file_id], n_runs)
net = f"{log_dir}/models/best_model_with_{n_runs-1}_graphs_{epoch}.pt"
load_model_state(model, net, device)
with torch.no_grad():
# Weights subplot (top-left)
ax1 = fig.add_subplot(2, 2, 1)
create_signal_weight_subplot(fig, ax1, model, connectivity, mc, epoch, file_id_, config, limits, second_correction,
apply_weight_correction=apply_weight_correction,
xnorm=xnorm, device=device)
# Top-right panel: embedding
ax2 = fig.add_subplot(2, 2, 2)
create_signal_embedding_subplot(fig, ax2, model, type_list, n_neuron_types, cmap, limits)
# Lin_phi subplot (bottom-left) - MLP0
ax3 = fig.add_subplot(2, 2, 3)
create_signal_lin_phi_subplot(fig, ax3, model, config, n_neurons, type_list,
cmap, device, xnorm, ynorm, limits, label_style,
true_model=true_model, n_neuron_types=n_neuron_types)
# Lin_edge subplot (bottom-right) - MLP1
ax4 = fig.add_subplot(2, 2, 4)
create_signal_lin_edge_subplot(fig, ax4, model, config, n_neurons, type_list,
cmap, device, xnorm, limits, mc, label_style,
true_model=true_model, n_neuron_types=n_neuron_types,
apply_weight_correction=apply_weight_correction)
plt.tight_layout()
writer.grab_frame()
if not first_frame_saved:
plt.savefig(jpg_path_combined, dpi=150, bbox_inches='tight')
first_frame_saved = True
plt.close(fig)
# create two-panel connectivity comparison movie (true vs learned heatmaps)
mp4_path_connectivity = f'{movies_dir}/connectivity_{dataset_name}{suffix}.mp4'
jpg_path_connectivity = f'{movies_dir}/connectivity_{dataset_name}{suffix}.jpg'
writer = FFMpegWriter(fps=fps, metadata=metadata)
fig = plt.figure(figsize=(16, 8))
# prepare true connectivity heatmap data
n_plot = n_neurons
true_connectivity_plot = to_numpy(connectivity[:n_plot, :n_plot])
first_frame_saved = False
with writer.saving(fig, mp4_path_connectivity, dpi=100):
for file_id_ in tqdm(range(len(file_id_list)), desc='connectivity', ncols=90):
plt.clf()
file_id = file_id_list[file_id_]
epoch = get_epoch_from_file(files[file_id], n_runs)
net = f"{log_dir}/models/best_model_with_{n_runs-1}_graphs_{epoch}.pt"
load_model_state(model, net, device)
with torch.no_grad():
# Get learned weights
A = get_model_W(model)[:n_plot, :n_plot]
learned_connectivity_plot = to_numpy(A)
# Left panel: true connectivity
ax1 = fig.add_subplot(1, 2, 1)
sns.heatmap(true_connectivity_plot, center=0, square=True, cmap='bwr',
cbar=False, vmin=-0.5, vmax=0.5, ax=ax1)
ax1.set_title('true connectivity', fontsize=20)
ax1.set_xticks([])
ax1.set_yticks([])
# Right panel: learned connectivity (raw)
ax2 = fig.add_subplot(1, 2, 2)
sns.heatmap(learned_connectivity_plot, center=0, square=True, cmap='bwr',
cbar=False, vmin=-0.5, vmax=0.5, ax=ax2)
ax2.set_title('learned connectivity', fontsize=20)
ax2.set_xticks([])
ax2.set_yticks([])
plt.tight_layout()
writer.grab_frame()
if not first_frame_saved:
plt.savefig(jpg_path_connectivity, dpi=150, bbox_inches='tight')
first_frame_saved = True