-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmultiple_task_analysis.py
More file actions
2076 lines (1730 loc) · 104 KB
/
multiple_task_analysis.py
File metadata and controls
2076 lines (1730 loc) · 104 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 numpy as np
from numpy.linalg import norm
import sys
import random
from pathlib import Path
import json
import time
import psutil
import copy
import pickle
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
ticker.Locator.MAXTICKS = 10000
import seaborn as sns
from scipy.cluster.hierarchy import dendrogram, cophenet
from scipy.stats import spearmanr
from sklearn.metrics.pairwise import cosine_similarity
from scipy.spatial.distance import cdist, pdist, squareform
from sklearn.decomposition import PCA
import torch
from torch.serialization import add_safe_globals
import scienceplots
plt.style.use('science')
plt.style.use(['no-latex'])
import helper
import clustering
import clustering_metric
import color_func
import mpn
import mpn_tasks
clean = True
if clean:
dir_path = Path("./multiple_tasks/")
for p in dir_path.glob("*.png"):
if p.is_file() and not (p.name.startswith("loss") or p.name.startswith("lowD")):
p.unlink()
c_vals = [
"#e53e3e", # red
"#3182ce", # blue
"#38a169", # green
"#d69e2e", # yellow-gold
"#d53f8c", # pink-magenta
"#4c51bf", # indigo
"#dd6b20", # orange
"#0ea5e9", # sky blue
"#22c55e", # bright green
"#a855f7", # purple
"#f43f5e", # red-pink
"#0f766e", # teal
"#b83280", # magenta-violet
"#ca8a04", # amber
"#2b6cb0", # deep blue
] * 10
c_vals_l = [
"#feb2b2", # light red
"#90cdf4", # light blue
"#9ae6b4", # light green
"#faf089", # light yellow-gold
"#fbb6ce", # light magenta
"#c3dafe", # light indigo
"#fed7aa", # light orange
"#bae6fd", # light sky blue
"#bbf7d0", # light bright green
"#e9d5ff", # light purple
"#fecdd3", # light red-pink
"#a7f3d0", # light teal
"#f9a8d4", # light violet-magenta
"#fde68a", # light amber
"#bfdbfe", # light deep blue
] * 10
c_vals_d = [
"#9b2c2c", # dark red
"#2c5282", # dark blue
"#276749", # dark green
"#975a16", # dark golden
"#97266d", # dark magenta
"#4338ca", # dark indigo
"#7b341e", # dark orange
"#0369a1", # dark sky blue
"#15803d", # dark bright green
"#6b21a8", # dark purple
"#9f1239", # dark red-pink
"#0f4c3a", # dark teal
"#702459", # dark violet-magenta
"#854d0e", # dark amber
"#1e3a8a", # dark deep blue
] * 10
l_vals = ['solid', 'dashed', 'dotted', 'dashdot', '-', '--', '-.', ':', (0, (3, 1, 1, 1)), (0, (5, 10))]
markers_vals = ['o', 'v', '*', '+', '>', '1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_']
linestyles = ["-", "--", "-."]
cs = "coolwarm"
# %%
mem = psutil.virtual_memory()
print(f"Total: {mem.total / 1e9:.2f} GB")
print(f"Available: {mem.available / 1e9:.2f} GB")
print(f"Used: {mem.used / 1e9:.2f} GB")
print(f"Percentage: {mem.percent}%")
# %%
# load and unpack parameters
# make sure to change out_path and out_param_path simultaneously
seed = "749"
task = "everything"
hidden = "300"
batch = "128"
feature = "L21e4"
accfeature = "+angle"
aname = f"{task}_seed{seed}_{feature}+hidden{hidden}+batch{batch}{accfeature}"
out_path_name = "multiple_tasks/" + f"param_{aname}_result.npz"
out_path = Path(out_path_name)
size_bytes = out_path.stat().st_size
size_gb = size_bytes / 1024**3
print(f"{out_path} = {size_gb:.3f} GiB")
with np.load(out_path_name, allow_pickle=True) as data:
rules_epochs = data["rules_epochs"].item()
hyp_dict = data["hyp_dict"].item()
all_rules = data["all_rules"]
test_task = data["test_task"]
# Ms = data["Ms"]
Ms_orig = data["Ms_orig"]
hs = data["hs"]
bs = data["bs"]
xs = data["xs"]
print(f"Ms_orig: {Ms_orig.shape}")
print(f"hs: {hs.shape}")
print(f"xs: {xs.shape}")
print(f"bs: {bs.shape}")
print(f"test_task: {test_task.shape}")
print(f"all_rules: {all_rules}")
out_param_path = "multiple_tasks/" + f"param_{aname}_param.json"
out_param_path = Path(out_param_path)
with out_param_path.open() as f:
raw_cfg_param = json.load(f)
task_params, train_params, net_params = raw_cfg_param["task_params"], raw_cfg_param["train_params"], raw_cfg_param["net_params"]
savefigure_name = f"{hyp_dict['ruleset']}_seed{seed}_{hyp_dict['addon_name']}"
# %%
# 2025-11-19: make sure the bias is only cell-dependent but not time- or trail-dependent
ref = bs[0, 0, :]
same_per_k = np.all(bs == ref, axis=(0, 1))
all_k_constant = np.all(same_per_k)
# %%
add_safe_globals([np.core.multiarray._reconstruct])
netpathname = "multiple_tasks/" + f"savednet_{aname}.pt"
checkpoint = torch.load(netpathname, map_location="cpu")
state_dict = checkpoint["state_dict"]
print(state_dict.keys())
load_net_params = checkpoint["net_params"]
print(load_net_params)
# reload the network
model = mpn.DeepMultiPlasticNet(load_net_params, verbose=False, forzihan=True)
missing, unexpected = model.load_state_dict(checkpoint["state_dict"], strict=True)
print("missing:", missing)
print("unexpected:", unexpected)
model.eval()
task_params_c, train_params_c, net_params_c = mpn_tasks.convert_and_init_multitask_params(
(task_params, train_params, net_params)
)
def shared_run(addtask):
"""
Trying to replicate Fig 3D-E in Driscoll etal 2024
"""
assert addtask in ("dmcgo", "delaydm1", )
task_params_dmcgo = copy.deepcopy(task_params_c)
if addtask == "dmcgo":
task_params_dmcgo["rules"] = ["dmcgo", "dmcnogo"]
elif addtask == "delaydm1":
task_params_dmcgo["rules"] = ["delaydm1", "delaydm2"]
test_n_batch = 100
task_params_dmcgo['hp']['batch_size_train'] = test_n_batch
task_params_dmcgo["long_delay"] = "normal"
test_data, test_trials_extra = mpn_tasks.generate_trials_wrap(task_params_dmcgo,
test_n_batch,
rules=task_params_dmcgo['rules'],
mode_input="random",
fix=True,
device="cpu",
verbose=True)
test_input, test_output, _ = test_data
print(f"test_input.shape: {test_input.shape}")
test_task = helper.find_task(task_params_dmcgo, test_input.detach().cpu().numpy(), 0)
test_task = [int(test_task_ - min(test_task)) for test_task_ in test_task]
_, test_trials, test_rule_idxs = test_trials_extra
stim1_choices = np.concatenate([test_trials[0].meta["stim1"], test_trials[1].meta["stim1"]])
print(f"stim1_choices: {stim1_choices}")
epochs = test_trials[0].epochs
if addtask in ("dmcgo", "delaydm1", ):
delay_period = epochs["delay1"]
# is delay period start inclusive and end exclusive?
print(f"delay_period: {delay_period}")
assert len(test_task) == len(stim1_choices)
net_out, _, db_test = model.iterate_sequence_batch(test_input, run_mode='track_states')
if addtask in ("dmcgo", "delaydm1", ):
hidden_test = db_test["hidden1"][:, delay_period[0]:delay_period[1]-1, :]
em_test = (db_test["M1"][:, delay_period[0]:delay_period[1]-1, :, :] * state_dict["mp_layer1.W"]).cpu().numpy()
m_test = db_test["M1"][:, delay_period[0]:delay_period[1]-1, :, :].cpu().numpy()
print(f"hidden_test: {hidden_test.shape}; em_test: {em_test.shape}; m_test: {m_test.shape}")
fig, axs = plt.subplots(5,2,figsize=(5*2,5*2))
for i in range(5):
for inp in range(test_input.shape[2]):
axs[i,0].plot(test_input[i,:,inp].detach().cpu().numpy(), color=c_vals[inp], alpha=0.5)
for inp in range(net_out.shape[2]):
axs[i,1].plot(net_out[i,:,inp].detach().cpu().numpy(), color=c_vals[inp], alpha=0.5)
for outp in range(test_output.shape[2]):
axs[i,1].plot(test_output[i,:,outp].detach().cpu().numpy(), color=c_vals[outp],
alpha=0.5, linestyle="--")
fig.tight_layout()
fig.savefig(f"./multiple_tasks/{addtask}_{savefigure_name}.png", dpi=300)
def combo_indices_16(A, B):
A = np.asarray(A)
B = np.asarray(B)
if A.shape != B.shape:
raise ValueError(f"Length mismatch: A{A.shape} vs B{B.shape}")
out = {}
for a in (0, 1):
for b in range(8):
out[(a, b)] = np.flatnonzero((A == a) & (B == b)).tolist()
return out
idx_map = combo_indices_16(test_task, stim1_choices)
stacked_inputs = [[], []]
stacked_inputs_labels = [[], []]
for i in range(2):
for b in range(8):
# add multiple trials of the same kind of stimulus
trial_num = 5
for trial_idx in range(trial_num):
# for trials that are considered to have the same stim1 and same task
# their input should be identical (quantified via sum) up to the end
# of the delay period; only check for dmcgo since for delaydm1, the magnitude
# might be different across batches even the stim identity is the same
if addtask == "dmcgo":
input_check = []
for key in idx_map[(i,b)]:
input_check.append(torch.sum(test_input[key,:delay_period[1],:]).item())
input_check = np.array(input_check, dtype=float)
ok = np.all(np.isclose(input_check, input_check[0]))
print(f"input_check: {input_check}")
assert ok
idxs = idx_map[(i, b)][trial_idx]
test_input_chosen = test_input[idxs]
stacked_inputs[i].append(test_input_chosen)
# add the stim1 label (for this trial) as well
stacked_inputs_labels[i].append(b)
xs = stacked_inputs[i]
stacked_inputs[i] = torch.stack(
[x if isinstance(x, torch.Tensor) else torch.as_tensor(x) for x in xs],
dim=0
)
assert stacked_inputs_labels[0] == stacked_inputs_labels[1], "The two conditions should have the same set of stimuli for interpolation to make sense"
# common delay period PCA
as_hidden_wantperiod = hidden_test.reshape(-1, hidden_test.shape[-1])
pca_delay_h = PCA(n_components=3, random_state=np.random.randint(0, 10000), svd_solver="auto")
pca_delay_h.fit(as_hidden_wantperiod)
as_em_wantperiod = em_test.reshape(-1, em_test.shape[-1] * em_test.shape[-2])
pca_delay_em = PCA(n_components=3, random_state=np.random.randint(0, 10000), svd_solver="auto")
pca_delay_em.fit(as_em_wantperiod)
as_m_wantperiod = m_test.reshape(-1, m_test.shape[-1] * m_test.shape[-2])
pca_delay_m = PCA(n_components=3, random_state=np.random.randint(0, 10000), svd_solver="auto")
pca_delay_m.fit(as_m_wantperiod)
plot_all = [["hidden", pca_delay_h], ["e_modulation", pca_delay_em], ["m_modulation", pca_delay_m]]
for plot_name, pca_delay in plot_all:
# interpolate between the two conditions (stim1 and stim2) in the input space,
# and track how the fixed points evolve in the PCA space of the delay period activity
alpha_lst = np.linspace(0,1,20)
interpolate_inputs = [(1-a) * stacked_inputs[0] + a * stacked_inputs[1] for a in alpha_lst]
fixed_points_all = []
traj_all = []
for idx, interpolate_input in enumerate(interpolate_inputs):
_, _, db = model.iterate_sequence_batch(interpolate_input, run_mode="track_states", save_to_cpu=True, detach_saved=True)
if plot_name == "hidden":
data = db["hidden1"]
as_flat = data.reshape(-1, data.shape[-1])
elif plot_name == "e_modulation":
data = (db["M1"] * state_dict["mp_layer1.W"]).cpu().numpy()
as_flat = data.reshape(-1, data.shape[-1] * data.shape[-2])
elif plot_name == "m_modulation":
data = db["M1"]
as_flat = data.reshape(-1, data.shape[-1] * data.shape[-2])
hidden_tf = pca_delay.transform(as_flat)
projected_data = hidden_tf.reshape(data.shape[0], data.shape[1], -1)
if addtask in ("dmcgo", "delaydm1", ):
fixed_points_all.append(projected_data[:,delay_period[1]-1,:])
if idx in (0, len(interpolate_inputs) - 1, ):
if addtask in ("dmcgo", "delaydm1", ):
traj_all.append(projected_data[:, delay_period[0]:delay_period[1], :])
fixed_points_all_arr = np.stack(fixed_points_all, axis=0) # (n_alpha, n_stim, n_pc)
print(f"fixed_points_all_arr: {fixed_points_all_arr.shape}")
n_alpha, n_stim, n_pc = fixed_points_all_arr.shape
figmap, axsmap = plt.subplots(1,3,figsize=(5*3,5))
pcs = [[0,1],[0,2],[1,2]]
for pc_idx, (pc_x, pc_y) in enumerate(pcs):
for stim in range(n_stim):
traj_fp = fixed_points_all_arr[:, stim, :]
axsmap[pc_idx].plot(traj_fp[:, pc_x], traj_fp[:, pc_y], "-o",
color=c_vals[stacked_inputs_labels[0][stim]], linewidth=1.5, markersize=4,
alpha=0.5,
label=f"stim {(stim // trial_num + 1)}" if stim % trial_num == 0 else None)
axsmap[pc_idx].scatter(traj_fp[0, pc_x], traj_fp[0, pc_y], color=c_vals[stacked_inputs_labels[0][stim]],
marker="s", s=50, zorder=3)
axsmap[pc_idx].scatter(traj_fp[-1, pc_x], traj_fp[-1, pc_y], color=c_vals[stacked_inputs_labels[0][stim]],
marker="^", s=50, zorder=3)
# plot the trajectory during the delay period for the first and last alpha (i.e. the two original conditions)
delay_traj = False
if delay_traj:
for be in range(len(traj_all)):
proj = traj_all[be]
for stim in range(proj.shape[0]):
xs = proj[stim, :, pc_x]
ys = proj[stim, :, pc_y]
axsmap[pc_idx].plot(xs, ys, color=c_vals[stacked_inputs_labels[0][stim]],
alpha=0.3, linewidth=1.0, linestyle=l_vals[be+1])
axsmap[pc_idx].scatter(xs[0], ys[0], color=c_vals[stacked_inputs_labels[0][stim]],
marker="o", s=35, zorder=4, alpha=0.9)
axsmap[pc_idx].set_xlabel(f"Memory State PC{pc_x+1}", fontsize=12)
axsmap[pc_idx].set_ylabel(f"Memory State PC{pc_y+1}", fontsize=12)
axsmap[pc_idx].legend(frameon=True)
# axsmap[pc_idx].set_xscale("symlog", linthresh=1e-3)
# axsmap[pc_idx].set_yscale("symlog", linthresh=1e-3)
figmap.tight_layout()
figmap.savefig(f"./multiple_tasks/{addtask}_fixed_points_{plot_name}_{savefigure_name}.png", dpi=300)
# shared_run("delaydm1")
# shared_run("dmcgo")
# analyze the fitted weight matrices; we focus on the first layer of modulation and the output layer, since they are more interpretable than the hidden layer
output_W = state_dict["W_output"].cpu().numpy()
input_W = state_dict["W_initial_linear.weight"].cpu().numpy()
modulation_W = state_dict["mp_layer1.W"].cpu().numpy()
def heatmap_with_top_left_marginals(
M,
ax,
cmap="coolwarm",
center=0,
vmin=None,
vmax=None,
xlabel="",
ylabel="",
label_fs=15,
tick_fs=10,
marginal_frac=0.18, # thickness of top/left strips (in ax coords)
marginal_pad=0.03, # gap between heatmap and strips (in ax coords)
marginal_lw=1.2,
cbar=True,
square=False
):
"""
Heatmap on `ax` + marginals:
- top inset: col-wise sum(abs(M)) (length = n_cols)
- left inset: row-wise sum(abs(M)) (length = n_rows), plotted vertically
Layout: col-sum at top, row-sum at left. No child dirs, no extra axes elsewhere.
"""
M = np.asarray(M)
n_rows, n_cols = M.shape
if vmin is None:
vmin = np.nanmin(M)
if vmax is None:
vmax = np.nanmax(M)
# ---- main heatmap
sns.heatmap(
M,
ax=ax,
cmap=cmap,
vmin=vmin,
vmax=vmax,
center=center,
cbar=cbar,
square=square,
)
ax.set_xlabel(xlabel, fontsize=label_fs)
ax.set_ylabel(ylabel, fontsize=label_fs)
ax.tick_params(labelsize=tick_fs)
# ---- marginals
col_sum = np.nansum(np.abs(M), axis=0) # (n_cols,)
row_sum = np.nansum(np.abs(M), axis=1) # (n_rows,)
# inset axes positions are in the parent ax's coordinate system
top_rect = [0.0, 1.0 + marginal_pad, 1.0, marginal_frac]
left_rect = [-(marginal_frac + marginal_pad), 0.0, marginal_frac, 1.0]
ax_top = ax.inset_axes(top_rect, transform=ax.transAxes)
ax_left = ax.inset_axes(left_rect, transform=ax.transAxes)
# ---- top: col sums (aligned with heatmap columns)
x = np.arange(n_cols)
ax_top.plot(x, col_sum, lw=marginal_lw)
ax_top.set_xlim(-0.5, n_cols - 0.5)
ax_top.set_xticks([])
ax_top.tick_params(axis="y", labelsize=tick_fs)
ax_top.spines["top"].set_visible(False)
ax_top.spines["right"].set_visible(False)
# ---- left: row sums (vertical, aligned with heatmap rows)
y = np.arange(n_rows)
ax_left.plot(row_sum, y, lw=marginal_lw) # x=row_sum, y=row index
ax_left.set_ylim(n_rows - 0.5, -0.5) # match heatmap's y-direction (top row at top)
ax_left.set_yticks([])
ax_left.tick_params(axis="x", labelsize=tick_fs)
ax_left.spines["top"].set_visible(False)
ax_left.spines["right"].set_visible(False)
ax.set_xticks([]); ax.set_yticks([])
return ax, ax_top, ax_left
def plot_weight_triplet_with_top_left_marginals(
output_W,
input_W,
modulation_W,
aname,
cs="coolwarm",
save_dir="./multiple_tasks",
):
figoutput, axsoutput = plt.subplots(1,1,figsize=(10, 12))
heatmap_with_top_left_marginals(
output_W,
ax=axsoutput,
cmap=cs,
center=0,
vmin=np.nanmin(output_W),
vmax=np.nanmax(output_W),
xlabel="Hidden 2 Index",
ylabel="Output Index",
square=False
)
figinput, axsinput = plt.subplots(1,1,figsize=(10, 12))
heatmap_with_top_left_marginals(
input_W.T,
ax=axsinput,
cmap=cs,
center=0,
vmin=np.nanmin(input_W),
vmax=np.nanmax(input_W),
xlabel="Hidden 1 Index",
ylabel="Input Index",
square=False
)
figmodulation, axsmodulation = plt.subplots(1,1,figsize=(10, 12))
heatmap_with_top_left_marginals(
modulation_W.T,
ax=axsmodulation,
cmap=cs,
center=0,
vmin=np.nanmin(modulation_W),
vmax=np.nanmax(modulation_W),
xlabel="Hidden 1 Index",
ylabel="Hidden 2 Index",
square=False
)
figoutput.tight_layout()
figoutput.savefig(f"{save_dir}/weight_matrices_{aname}.png", dpi=300)
plt.close(figoutput)
figinput.tight_layout()
figinput.savefig(f"{save_dir}/weight_matrices_input_{aname}.png", dpi=300)
plt.close(figinput)
figmodulation.tight_layout()
figmodulation.savefig(f"{save_dir}/weight_matrices_modulation_{aname}.png", dpi=300)
plt.close(figmodulation)
return
plot_weight_triplet_with_top_left_marginals(
output_W=output_W,
input_W=input_W,
modulation_W=modulation_W,
aname=aname,
cs=cs,
save_dir="./multiple_tasks",
)
all_input = ["Fix On", "Fix Off", "Stim 1 Cos", "Stim 1 Sin", "Stim 2 Cos", "Stim 2 Sin"] + task_params_c["rules"]
input_corr = np.corrcoef(input_W.T)
mask = np.triu(np.ones_like(input_corr, dtype=bool), k=1)
fig, ax = plt.subplots(1,1,figsize=(5,5))
sns.heatmap(input_corr, ax=ax, cmap=cs, center=0, mask=mask, vmin=-1, vmax=1, square=True, cbar_kws={"shrink": 0.5})
ax.set_xticks(np.arange(len(all_input)) + 0.5, labels=all_input, rotation=90)
ax.set_yticks(np.arange(len(all_input)) + 0.5, labels=all_input, rotation=0)
ax.set_xlabel("Input Index", fontsize=12)
ax.set_ylabel("Input Index", fontsize=12)
fig.tight_layout()
fig.savefig(f"./multiple_tasks/input_weight_correlation_{aname}.png", dpi=300)
plt.close(fig)
# should we re-evaluate the result?
reevaluate = True
if reevaluate:
test_n_batch = 100
task_params_c['hp']['batch_size_train'] = test_n_batch
test_data, test_trials_extra = mpn_tasks.generate_trials_wrap(
task_params_c, test_n_batch, rules=task_params_c['rules'],
mode_input="random", fix=True, device="cpu", verbose=False
)
test_input, test_output, test_mask = test_data
_, test_trials, test_rule_idxs = test_trials_extra
with torch.no_grad():
net_out, _, db_test = model.iterate_sequence_batch(test_input, run_mode='track_states')
Ms_orig = db_test["M1"].cpu().numpy()
xs = db_test["input1"].cpu().numpy()
hs = db_test["hidden1"].cpu().numpy()
print(f"Ms_orig: {Ms_orig.shape}; xs: {xs.shape}; hs: {hs.shape}")
all_rules = np.array(task_params["rules"])
def generate_response_stimulus(task_params, test_trials):
"""
"""
labels_resp, labels_stim1, labels_stim2 = [], [], []
rules_epochs = {}
for rule_idx, rule in enumerate(task_params['rules']):
rules_epochs[rule] = test_trials[rule_idx].epochs
# print(test_trials[rule_idx].meta.keys())
if rule in ('dmsgo','dmcgo','dmsnogo','dmcnogo',):
labels_resp.append(test_trials[rule_idx].meta['matches'])
else:
labels_resp.append(test_trials[rule_idx].meta['resp1'])
labels_stim1.append(test_trials[rule_idx].meta['stim1'])
try:
labels_stim2.append(test_trials[rule_idx].meta['stim2'])
except KeyError:
labels_stim2.append(np.full_like(test_trials[rule_idx].meta['stim1'], np.nan))
labels_resp = np.concatenate(labels_resp, axis=0).reshape(-1,1)
labels_stim1 = np.concatenate(labels_stim1, axis=0).reshape(-1,1)
labels_stim2 = np.concatenate(labels_stim2, axis=0).reshape(-1,1)
return labels_resp, labels_stim1, labels_stim2, rules_epochs
labels_resp, labels_stim1, labels_stim2, rules_epochs = generate_response_stimulus(task_params, test_trials)
# print(labels_stim1.shape)
# print(labels_stim2.shape)
test_task = helper.find_task(task_params, test_input.detach().cpu().numpy(), 0)
test_task = np.array([int(c) for c in test_task]).flatten()
# %%
weighted_Ms_orig = Ms_orig * modulation_W
print(f"weighted_Ms_orig: {weighted_Ms_orig.shape}")
clustering_data_analysis = [xs, hs, Ms_orig]
clustering_data_analysis_names = ["input", "hidden", "modulation_all"]
clustering_data_hierarchy = {}
clustering_corr_info = []
col_clusters_all, row_clusters_all = [], []
row_cluster_breaker_all = []
input_hidden_comparison = []
base_data = []
metrics_all_all = []
rbreaks_all, cbreaks_all = [], []
selection_key = ["CH_blocks", "DB_blocks"]
upper_cluster = 300
lower_cluster = 5
silhouette_tol = 0.00
cluster_info_save = {}
for clustering_index in range(len(clustering_data_analysis)):
print("======================================================")
clustering_data = clustering_data_analysis[clustering_index]
clustering_name = clustering_data_analysis_names[clustering_index]
print(f"clustering_name: {clustering_name}")
print(f"clustering_data: {clustering_data.shape}")
if hyp_dict['ruleset'] == "everything":
phase_to_indices = [
("stim1", [0, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),
("stim2", [6, 7, 8, 9, 10]),
("delay1", [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),
("delay2", [6, 7, 8, 9, 10]),
("go1", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
]
tb_break = [
[idx, rules_epochs[all_rules[idx]][phase]]
for phase, indices in phase_to_indices
for idx in indices
]
tb_break_name = [
f"{all_rules[idx]}-{phase}"
for phase, indices in phase_to_indices
for idx in indices
]
tb_break_name = np.array(tb_break_name)
cell_vars_rules = []
for el in range(len(tb_break)):
n_rules = len(task_params['rules'])
n_cells = clustering_data.shape[-1]
rule_idx, period_time = tb_break[el][0], tb_break[el][1]
# print('Rule {} (idx {}), {}'.format(all_rules[rule_idx], rule_idx, period_time))
# print(f"tb_break_name[el]: {tb_break_name[el]}")
labels_stim = labels_stim1
labels_stim = labels_stim2 if ("stim2" in tb_break_name[el] or "delay2" in tb_break_name[el]) else labels_stim1
if len(clustering_data.shape) == 3:
# 2025-11-19: if period_time[1] is None, then go until the end along that axis
rule_cluster = clustering_data[test_task == rule_idx, period_time[0]:period_time[1], :]
# varval = np.var(rule_cluster, axis=(0, 1))
varval = helper.task_variance_period_numpy(rule_cluster, labels_stim[test_task == rule_idx].flatten())
cell_vars_rules.append(varval)
else:
clustering_data_old = clustering_data
if "pre" in clustering_name: # outdated
rule_cluster = clustering_data[test_task == rule_idx, period_time[0]:period_time[1]]
mean_var = np.var(rule_cluster, axis=(0, 1)).mean(axis=0)
cell_vars_rules.append(mean_var)
elif "post" in clustering_name: # outdated
rule_cluster = clustering_data[test_task == rule_idx, period_time[0]:period_time[1]]
mean_var = np.var(rule_cluster, axis=(0, 1)).mean(axis=1)
cell_vars_rules.append(mean_var)
elif "all" in clustering_name:
clustering_data = clustering_data.reshape(clustering_data.shape[0], clustering_data.shape[1], -1)
rule_cluster = clustering_data[test_task == rule_idx, period_time[0]:period_time[1], :]
# varval = np.var(rule_cluster, axis=(0, 1))
varval = helper.task_variance_period_numpy(rule_cluster, labels_stim[test_task == rule_idx].flatten())
cell_vars_rules.append(varval)
cell_vars_rules = np.array(cell_vars_rules)
cell_vars_rules_norm = np.zeros_like(cell_vars_rules)
print(f"cell_vars_rules.shape: {cell_vars_rules.shape}")
# normalize
cell_max_var = np.max(cell_vars_rules, axis=0) # Across rules
print(f"cell_max_var.shape: {cell_max_var.shape}")
for period_idx in range(len(tb_break)):
cell_vars_rules_norm[period_idx] = np.where(
cell_max_var > 0., cell_vars_rules[period_idx] / cell_max_var, 0.
)
# modulation only, reshape to (N, pre, post) shape after calculating the variance
# N here as the number of sessions after breakdown
if "all" in clustering_name:
N, MM = cell_vars_rules_norm.shape
M = int(np.sqrt(MM))
cell_vars_rules_norm_keepshape = cell_vars_rules_norm.reshape(N, M, M)
# build rule-wise value lists and corresponding field names dynamically
rule_vals = [cell_vars_rules_norm[i].tolist() for i in range(n_rules)]
# print(f"rule_vals: {rule_vals}")
rule_names = [f"rule{i}" for i in range(n_rules)]
# structured array whose fields are rule0, rule1, …, rule{n_rules-1}
dtype = np.dtype([(name, float) for name in rule_names])
rules_struct = np.array(list(zip(*rule_vals)), dtype=dtype)
# sort_idxs = np.argsort(rules_struct, order=rule_names)[::-1] # descending lexicographic sort across all rule columns
sort_idxs = np.arange(rules_struct.shape[0], dtype=np.intp) # identity map for better interpretability
# 2025-07-07: first sorting based on the normalized magnitude
# all the following should be aligned with this change
# 2025-08-22: sort based on the variance ordering OR using an identity map (i.e. do nothing)
cell_vars_rules_sorted_norm = cell_vars_rules_norm[:, sort_idxs]
base_data.append(cell_vars_rules_sorted_norm)
print(f"cell_vars_rules_sorted_norm: {cell_vars_rules_sorted_norm.shape}")
# analyze input and hidden
if not ("all" in clustering_name):
# clustering & grouping & re-ordering
# first loop on input, second loop in hidden
result = clustering.cluster_variance_matrix_repeat(cell_vars_rules_sorted_norm,
k_min=lower_cluster,
k_max=upper_cluster,
metric="euclidean",
method="ward",
n_repeats=100,
silhouette_tol=silhouette_tol)
# sanity check to make sure no undesirable bug happens with in the clustering code
assert sorted(result["row_order"]) == list(range(cell_vars_rules_sorted_norm.shape[0]))
assert sorted(result["col_order"]) == list(range(cell_vars_rules_sorted_norm.shape[1]))
assert len(result["row_labels"]) == cell_vars_rules_sorted_norm.shape[0]
assert len(result["col_labels"]) == cell_vars_rules_sorted_norm.shape[1]
assert np.unique(result["row_labels"]).size == result["row_k"]
assert np.unique(result["col_labels"]).size == result["col_k"]
eval_res = clustering_metric.evaluate_bicluster_clustering(
cell_vars_rules_sorted_norm, row_labels=result["row_tol_labels"], col_labels=result["col_tol_labels"]
)
eval_metrics = eval_res["metrics"]
eval_blocks = eval_res["blocks"]
eval_stdmean = np.nanmedian(eval_blocks["std"] / eval_blocks["means"])
eval_random_metrics_all = []
eval_random_blocks_all = []
for repeat in range(1000):
rng = np.random.default_rng(seed=np.random.randint(0, 10000))
row_arr = rng.permutation(result["row_tol_labels"])
col_arr = rng.permutation(result["col_tol_labels"])
eval_res_random = clustering_metric.evaluate_bicluster_clustering(
cell_vars_rules_sorted_norm, row_labels=row_arr, col_labels=col_arr
)
eval_random_metrics_all.append(eval_res_random["metrics"])
eval_random_blocks_all.append(eval_res_random["blocks"])
eval_random_stdmean = [np.nanmedian(eval_random_blocks["std"] / eval_random_blocks["means"]) \
for eval_random_blocks in eval_random_blocks_all]
metrics_all = {}
for metric_key in selection_key:
optimized_value = eval_metrics[metric_key]
random_values = [eval_random_metrics[metric_key] for eval_random_metrics in eval_random_metrics_all]
metrics_all[metric_key] = [optimized_value, np.mean(random_values), np.std(random_values, ddof=1)/np.sqrt(len(random_values))]
metrics_all["std/mean"] = [eval_stdmean, np.mean(eval_random_stdmean), np.std(eval_random_stdmean, ddof=1)/np.sqrt(len(eval_random_stdmean))]
# registeration
metrics_all_all.append(metrics_all)
input_hidden_comparison.append([result, cell_vars_rules_sorted_norm])
# reorder the original matrix based on the clustering result
cell_vars_rules_sorted_norm_ordered = cell_vars_rules_sorted_norm[np.ix_(result["row_order"], result["col_order"])]
rl = np.asarray(result["row_tol_labels"])[result["row_order"]]
cl = np.asarray(result["col_tol_labels"])[result["col_order"]]
rbreaks = clustering._breaks(rl)
cbreaks = clustering._breaks(cl)
rbreaks_all.append(rbreaks); cbreaks_all.append(cbreaks)
best_k_row, best_k_col = result["row_k"], result["col_k"]
best_alt_k_row, best_alt_k_col = result["row_tol_k"], result["col_tol_k"]
print(f"best_k_row: {best_k_row}; best_k_col: {best_k_col}")
print(f"best_alt_k_row: {best_alt_k_row}; best_alt_k_col: {best_alt_k_col}")
row_t, col_t = result["row_cut_threshold"], result["col_cut_threshold"]
# extract the grouping information, i.e. which neuron belong to which cluster
# instead of the view of dendrogram
# 2025-10-20: we register the tolerant version of optimal cluster selection
col_labels, col_k = result["col_tol_labels"], result["col_tol_k"]
# group the neuron based on the labels
col_clusters = {int(lab): np.where(col_labels == lab)[0] for lab in np.unique(col_labels)}
# 2025-11-04: do similar things for row separation
# we checked so that the cluster label (name) is monotonically increasing
# i.e. near by cluster (e.g. cluster 1 and cluster 2) should be more similiar in population
# as well, since increasing the cutoff threshold in dendrogram will "merge" these clusters
row_labels, row_k = result["row_tol_labels"], result["row_tol_k"]
row_clusters = {int(lab): np.where(row_labels == lab)[0] for lab in np.unique(row_labels)}
# registeration
col_clusters_all.append(col_clusters)
row_clusters_all.append(row_clusters)
cluster_info_save[clustering_name] = {
"col_clusters": col_clusters,
"row_clusters": row_clusters,
"tb_break_name": tb_break_name,
}
# plot the optimization score as a function of number of clustering
# also plot the indicator for the optimal number of cluster (and with tolerance version)
figscore, axscore = plt.subplots(1,1,figsize=(5,3))
axscore.plot(result["row_score_recording_mean"].keys(),
result["row_score_recording_mean"].values(),
label="row", color=c_vals[0])
axscore.axvline(best_k_row, color=c_vals[0], linestyle="-")
axscore.axvline(best_alt_k_row, color=c_vals[0], linestyle="--")
axscore.plot(result["col_score_recording_mean"].keys(), result["col_score_recording_mean"].values(),
label="col", color=c_vals[1])
axscore.axvline(best_k_col, color=c_vals[1], linestyle="-")
axscore.axvline(best_alt_k_col, color=c_vals[1], linestyle="--")
axscore.set_xlabel("Number of Cluster")
axscore.set_ylabel("Silhouette Score")
axscore.legend()
axscore.set_title(f"{clustering_name}", fontsize=15)
figscore.tight_layout()
figscore.savefig(f"./multiple_tasks/{clustering_name}_variance_cluster_score_{savefigure_name}.png", dpi=300)
plt.close(figscore)
#
ordered_row_name = tb_break_name[result["row_order"]]
row_breakers = [0]
for row_group in row_clusters.values():
row_breakers.append(row_breakers[-1] + len(row_group))
row_breakers = row_breakers[1:]
print(f"row_breakers: {row_breakers}")
row_cluster_breaker_all.append(row_breakers)
# pearson correlation matrix
figcorr, axcorrs = plt.subplots(1,3,figsize=(8*3,8))
metrics = ["Correlation", "Cosine Similarity", "L2 Distance"]
cell_vars_rules_sorted_norm_ordered_measure = np.corrcoef(cell_vars_rules_sorted_norm_ordered, rowvar=True)
cell_vars_rules_sorted_norm_ordered_measure_cos = cosine_similarity(cell_vars_rules_sorted_norm_ordered)
cell_vars_rules_sorted_norm_ordered_measure_L2 = squareform(pdist(cell_vars_rules_sorted_norm_ordered, metric='euclidean'))
# set uniform colorbar to cross-compare between analysis
sns.heatmap(cell_vars_rules_sorted_norm_ordered_measure, cmap=cs, square=True, vmin=-0.5, vmax=1.0, ax=axcorrs[0])
sns.heatmap(cell_vars_rules_sorted_norm_ordered_measure_cos, cmap=cs, square=True, vmin=-0.5, vmax=1.0, ax=axcorrs[1])
sns.heatmap(cell_vars_rules_sorted_norm_ordered_measure_L2, cmap=cs, square=True, ax=axcorrs[2])
for axcorr_index in range(len(axcorrs)):
axcorr = axcorrs[axcorr_index]
# plot the group information (delimiter between different cluster)
nn = cell_vars_rules_sorted_norm_ordered_measure.shape[0]
boundaries = row_breakers
for b in boundaries:
axcorr.axvline(b, 0, 1, color="k", linewidth=1.2)
axcorr.axhline(b, 0, 1, color="k", linewidth=1.2)
axcorr.set_xticks(np.arange(len(tb_break_name)))
axcorr.set_xticklabels(tb_break_name[result["row_order"]], rotation=45, ha='right', va='center', \
rotation_mode='anchor', fontsize=9)
axcorr.set_yticks(np.arange(len(tb_break_name)))
axcorr.set_yticklabels(tb_break_name[result["row_order"]], rotation=0, ha='right', va='center', \
rotation_mode='anchor', fontsize=9)
axcorr.tick_params(axis="both", length=0)
axcorr.set_title(f"{clustering_name}-{metrics[axcorr_index]}", fontsize=15)
figcorr.tight_layout()
figcorr.savefig(f"./multiple_tasks/{clustering_name}_variance_cluster_corr_{savefigure_name}.png", dpi=300)
plt.close(figcorr)
# register correlation information
clustering_corr_info.append([
cell_vars_rules_sorted_norm_ordered_measure, ordered_row_name, result["col_order"]
])
# plot the effect of grouping & ordering through the feature axis
fig, ax = plt.subplots(2,1,figsize=(24,8*2))
sns.heatmap(cell_vars_rules_sorted_norm, ax=ax[0], cmap=cs, cbar=True, vmin=0, vmax=1)
sns.heatmap(cell_vars_rules_sorted_norm_ordered, ax=ax[1], cmap=cs, cbar=True, vmin=0, vmax=1)
for rb in rbreaks:
ax[1].axhline(rb, color="k", lw=0.6)
for cb in cbreaks:
ax[1].axvline(cb, color="k", lw=0.6)
ax[0].set_title(f"Before Clustering; best k row: {best_alt_k_row}; best k col: {best_alt_k_col}", fontsize=15)
ax[0].set_ylabel('Rule / Break-name', fontsize=12, labelpad=12)
ax[0].set_yticks(np.arange(len(tb_break_name)))
ax[0].set_yticklabels(tb_break_name, rotation=0, ha='right', va='center', fontsize=9)
ax[1].set_title(f"After Clustering; best k row: {best_alt_k_row}; best k col: {best_alt_k_col}", fontsize=15)
ax[1].set_ylabel('Rule / Break-name', fontsize=12, labelpad=12)
ax[1].set_yticks(np.arange(len(tb_break_name)))
ax[1].set_yticklabels(tb_break_name[result["row_order"]], rotation=0, ha='right', va='center', fontsize=9)
fig.savefig(f"./multiple_tasks/{clustering_name}_variance_cluster_{savefigure_name}.png", dpi=300)
plt.close(fig)
# 2025-11-04: for plotting purpose
rbreaks_ = [0] + rbreaks + [cell_vars_rules_sorted_norm_ordered.shape[0]]
cbreaks_ = [0] + cbreaks + [cell_vars_rules_sorted_norm_ordered.shape[1]]
figvarmean, axsvarmean = plt.subplots(1,2,figsize=(4*2,4))
varmean = np.zeros((len(rbreaks_) - 1, len(cbreaks_) - 1))
for rr in range(len(rbreaks_) - 1):
for cc in range(len(cbreaks_) - 1):
# 2025-11-04: mean covariance in this bicluster
varmean_ = np.mean(cell_vars_rules_sorted_norm_ordered[rbreaks_[rr]:rbreaks_[rr+1], cbreaks_[cc]:cbreaks_[cc+1]])
varmean[rr,cc] = varmean_
sns.heatmap(varmean, ax=axsvarmean[0], cmap=cs, cbar=True, vmin=0, vmax=1)
axsvarmean[0].set_ylabel("Session Clusters", fontsize=15)
axsvarmean[0].set_xlabel("Neuron Clusters", fontsize=15)
# 2025-11-04: for sanity check; since the neuron clusters are ordered so that the adjacent ones
# are more similar to each other than the ones that are further, therefore the correlation matrix
# should have larger value near the diagonal
varmeanC = np.corrcoef(varmean, rowvar=False)
sns.heatmap(varmeanC, ax=axsvarmean[1], cmap=cs, cbar=True, vmin=0, vmax=1)
axsvarmean[1].set_xlabel("Neuron Clusters", fontsize=15)
axsvarmean[1].set_ylabel("Neuron Clusters", fontsize=15)
figvarmean.tight_layout()
figvarmean.savefig(f"./multiple_tasks/{clustering_name}_variance_cluster_mean_{savefigure_name}.png", dpi=300)
plt.close(figvarmean)
# plot the norm of normalized variance of each session (across the neuron dimension)
session_norm = cell_vars_rules_sorted_norm_ordered.sum(axis=1)
norm_order = np.argsort(-session_norm)
session_norm = session_norm[norm_order]
session_norm_name = (tb_break_name[result["row_order"]])[norm_order]
fig, ax = plt.subplots(1,1,figsize=(15,5))
ax.plot([i for i in range(len(session_norm))], session_norm, "-o")
ax.set_xticks([i for i in range(len(session_norm))])
ax.set_xticklabels(session_norm_name, rotation=45, ha="right")
ax.set_ylabel("Summation of Normalized Variance", fontsize=15)
fig.tight_layout()
fig.savefig(f"./multiple_tasks/{clustering_name}_variance_norm_{savefigure_name}.png", dpi=300)
plt.close(fig)
# # plot hierarchy of grouping
# fig, axs = plt.subplots(2,1,figsize=(25,4*2))
# dendrogram(result["row_linkage"], ax=axs[0], labels=tb_break_name[result["row_order"]], leaf_rotation=45)
# axs[0].axhline(row_t, linestyle="--", color="black")
# axs[0].set_title(f"Row hierarchy (k = {result['row_k']})", fontsize=15)
# dendrogram(result["col_linkage"], ax=axs[1], labels=np.array([i for i in range(cell_vars_rules_sorted_norm_ordered.shape[1])]), leaf_rotation=45)
# axs[1].set_title(f"Col hierarchy (k = {result['col_k']})", fontsize=15)
# axs[1].axhline(col_t, linestyle="--", color="black")
# fig.suptitle(clustering_name, fontsize=15)
# fig.tight_layout()
# fig.savefig(f"./multiple_tasks/{clustering_name}_variance_hierarchy_{savefigure_name}.png", dpi=300)
# register hierarchy clustering
clustering_data_hierarchy[clustering_name] = result["col_linkage"]