-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpaper_plot.py
More file actions
5557 lines (4825 loc) · 245 KB
/
Copy pathpaper_plot.py
File metadata and controls
5557 lines (4825 loc) · 245 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
"""
Paper figure generation for the MultiTaskMPN project.
Each public function produces one publication-ready figure and saves it
to the `paper_plot/` directory. Run the script directly to generate all
figures, or import individual functions as needed.
Figures are grouped into modes by the experiment they depend on:
one_task single-task training analyses
multiple_tasks full multi-task network (clustering, lesion, state space)
two_in_multiple two-task probes within the multi-task network (DMC memory)
pretraining pretraining → post-training transfer analyses
two_task two-task network (cross-task / cross-period PCA)
Usage:
python paper_plot.py # generate every mode
python paper_plot.py all # same as above
python paper_plot.py one_task # only the one-task figures
python paper_plot.py multiple_tasks # only the multi-task figures
python paper_plot.py two_in_multiple # only the two-in-multiple figures
python paper_plot.py pretraining # only the pretraining figures
python paper_plot.py two_task # only the two-task figures
python paper_plot.py --only input # generate a single figure
"""
import pickle
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import seaborn as sns
from pathlib import Path
from scipy.cluster.hierarchy import fcluster
# ─── Global style ────────────────────────────────────────────────────────────
mpl.rcParams.update({
"font.family": "sans-serif",
"font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans"],
"font.size": 8,
"axes.labelsize": 9,
"axes.titlesize": 10,
"xtick.labelsize": 7,
"ytick.labelsize": 7,
"pdf.fonttype": 42,
"ps.fonttype": 42,
})
# ─── Global figure options ────────────────────────────────────────────────────
# Master toggle for legends across every figure. Set False to suppress all
# legends (useful for panels where the legend is documented in the caption).
# All figures route their legend calls through _legend(), so this one flag
# controls them uniformly.
SHOW_LEGEND = True
def _legend(ax, *args, **kwargs):
"""Draw a legend on `ax` only if the global SHOW_LEGEND flag is set.
Drop-in replacement for ax.legend(...); returns the Legend or None. Any
per-figure gating (e.g. a local show_legend) should be checked by the caller
before calling this, so both conditions must hold for a legend to appear.
"""
if not SHOW_LEGEND:
return None
return ax.legend(*args, **kwargs)
# ─── Shared label / IO helpers ────────────────────────────────────────────────
def _wrap(text, width=16):
"""Insert line breaks into `text` so no line exceeds ~`width` characters.
Wraps on word boundaries (never mid-word), so long axis labels / tick labels
stack onto multiple lines instead of running off the panel or overlapping a
neighbor. Accepts a single string or an iterable of strings (returns a list
for the latter). Non-string items pass through unchanged."""
import textwrap
if isinstance(text, str):
return "\n".join(textwrap.wrap(text, width=width)) or text
return [_wrap(t, width) if isinstance(t, str) else t for t in text]
def _save_fig(fig, out_path, extra=""):
"""Save `fig` at the standard dpi / tight bbox, close it, and print a line.
`extra` appends to the "Saved: {out_path}" message (e.g. counts/params).
When legends are enabled (SHOW_LEGEND), an `_n` suffix is appended to the
filename stem so the legended figure does not overwrite the no-legend one
(e.g. `foo.png` → `foo_n.png`)."""
out_path = Path(out_path)
if SHOW_LEGEND:
out_path = out_path.with_name(f"{out_path.stem}_n{out_path.suffix}")
fig.savefig(out_path, dpi=300, bbox_inches="tight")
plt.close(fig)
print(f"Saved: {out_path}{extra}")
def _load_pkl_or_skip(pkl_path, hint="", use_name=False):
"""Return the unpickled object at `pkl_path`, or None (with a "Skipped"
message) if it does not exist. `hint` is appended to the message (e.g.
"Run one_task_analysis.py first."); `use_name` prints only the filename."""
if not pkl_path.exists():
shown = pkl_path.name if use_name else pkl_path
print(f" Skipped: {shown} not found.{(' ' + hint) if hint else ''}")
return None
with open(pkl_path, "rb") as f:
return pickle.load(f)
def _load_twotask_glob_or_skip(pattern):
"""Load the first pickle matching `pattern` under the configured two-task run
dir, or return None (with a "Skipped" message) if none match."""
run_dir = TWOTASKS_DIR / TWOTASK_ANAME
matches = sorted(run_dir.glob(pattern))
if not matches:
print(f" Skipped: no {pattern} in {run_dir}. "
f"Run two_task_analysis.py first.")
return None
with open(matches[0], "rb") as f:
return pickle.load(f)
# ─── Paths & run identifiers ──────────────────────────────────────────────────
# All figure output goes here; the run identifiers ("aname") below select which
# trained run each mode's figures are drawn from. They are grouped by experiment
# family so a run can be swapped in one place.
OUT_DIR = Path("paper_plot")
# ── Multi-task (one full multi-task network) ──
ANAME = "everything_seed749_L21e4+hidden300+batch128+angle"
DATA_DIR = Path("multiple_tasks") / ANAME
# DMC category-memory probe (two_in_multiple mode). May differ from ANAME — set
# independently so the attractor figure can come from a different
# seed/regularization than the clustering/lesion figures.
DMC_ANAME = "everything_seed299_L21e3+hidden300+batch128+angle"
# delayDM integration-memory probe (two_in_multiple mode). Independent of
# ANAME/DMC_ANAME; matching data written by multiple_task_analysis.py's
# shared_run("delaydm1") into
# multiple_tasks/{DELAYDM_ANAME}/delaydm1_fixed_points_{DELAYDM_ANAME}.pkl.
DELAYDM_ANAME = "everything_seed408_L21e4+hidden300+batch128+angle"
# ── Two-task network ──
TWOTASKS_DIR = Path("twotasks")
# Cross-task / cross-period PCA figure (d_combine); data written by
# two_task_analysis.py into twotasks/{TWOTASK_ANAME}/d_combine_{TWOTASK_ANAME}.pkl.
TWOTASK_ANAME = "delaygofamily_seed21_reg1e3+hidden200"
# Attractor first-subplot figure (independent of TWOTASK_ANAME so it can come
# from a different seed/regularization).
TWOTASK_ATTRACTOR_ANAME = "delaygofamily_seed21_reg1e3+hidden200"
# ── Single-task network ──
ONETASK_DIR = Path("onetask")
# Default single-task run for the one-task figures (aname under onetask/{aname}/).
# Used by onetask_show, onetask_modulation_snapshot, onetask_long_fixed_points, etc.
ONETASK_ANAME = "delaygo_seed395_hidden200+batch128+angle"
# Runs used for the example-trial illustration. Set to ONETASK_ANAME so the
# input/output illustration comes from the SAME network as onetask_show; can be
# pointed at a different seed here if desired (they read separate example_trial
# pickles).
ONETASK_INPUT_ANAME = ONETASK_ANAME
ONETASK_OUTPUT_ANAME = ONETASK_ANAME
def _twotask_seed_tag():
"""Seed substring of TWOTASK_ANAME (e.g. 'seed894'), for figure filenames.
Falls back to the full aname if no 'seed<N>' token is present."""
import re as _re
m = _re.search(r"seed\d+", TWOTASK_ANAME)
return m.group(0) if m else TWOTASK_ANAME
def _read_twotask_n_stim(default=8):
"""Trained ring-direction count (n_eachring) for the configured two-task run,
read from its saved param json; used only for the dashed trained-direction
guide lines in the interp / stability figures. Falls back to `default`."""
try:
import json as _json
p = TWOTASKS_DIR / TWOTASK_ANAME / f"param_{TWOTASK_ANAME}_param.json"
if p.exists():
cfg = _json.load(open(p))
return int(cfg.get("task_params", {}).get("n_eachring", default))
except Exception:
pass
return default
def _read_twotask_dt(default=40):
"""Simulation time step (ms) for the configured two-task run, read from its
saved param json (see SCHEME.md); used to relabel step-index x-axes in ms.
Falls back to `default`."""
try:
import json as _json
p = TWOTASKS_DIR / TWOTASK_ANAME / f"param_{TWOTASK_ANAME}_param.json"
if p.exists():
cfg = _json.load(open(p))
return int(cfg.get("task_params", {}).get("dt", default))
except Exception:
pass
return default
def _twotask_grad_fp_paths():
"""(rule, path) for every gradient fixed-point pickle of the configured
two-task run — one per task rule, written by two_task_analysis.py as
twotasks/{aname}/fixed_points_grad_{aname}_{rule}.pkl. Sorted by rule name."""
run_dir = TWOTASKS_DIR / TWOTASK_ANAME
prefix = f"fixed_points_grad_{TWOTASK_ANAME}_"
out = []
for p in sorted(run_dir.glob(f"{prefix}*.pkl")):
rule = p.name[len(prefix):-len(".pkl")]
out.append((rule, p))
return out
TWOTASK_N_STIM = _read_twotask_n_stim()
# Categorical color cycle (matches multiple_task_analysis.py). Used for
# NON-stimulus categorical coloring (components, series, periods, tasks).
c_vals = [
"#e53e3e", "#3182ce", "#38a169", "#d69e2e", "#d53f8c",
"#4c51bf", "#dd6b20", "#0ea5e9", "#22c55e", "#a855f7",
"#f43f5e", "#0f766e", "#b83280", "#ca8a04", "#2b6cb0",
] * 10
# Number of TRAINED ring stimulus directions (n_eachring in the task config) for
# the configured one-task run. Read from that run's saved param json so figures
# adapt to each experiment (e.g. the default 8 vs a `morestimulus` run's 1024),
# falling back to 8 if the json is unavailable. NB: this is the *trained*
# direction count — the dense fixed-point interpolation grid (n_interp) is
# separate and read per-figure from the pickle's own `stim`/`angles`.
def _read_onetask_n_stim(default=8):
try:
import json as _json
p = ONETASK_DIR / f"param_{ONETASK_ANAME}_param.json"
if p.exists():
cfg = _json.load(open(p))
return int(cfg.get("task_params", {}).get("n_eachring", default))
except Exception:
pass
return default
ONETASK_N_STIM = _read_onetask_n_stim()
def _read_onetask_dt(default=40):
"""Simulation time step (ms) for the configured one-task run, read from its
saved param json (see SCHEME.md). Used to relabel step-index x-axes in ms for
figures whose pickle predates the saved `dt` (e.g. the onetask_show traces)."""
try:
import json as _json
p = ONETASK_DIR / f"param_{ONETASK_ANAME}_param.json"
if p.exists():
cfg = _json.load(open(p))
return int(cfg.get("task_params", {}).get("dt", default))
except Exception:
pass
return default
# ─── Stimulus color scheme ────────────────────────────────────────────────────
# A continuous rainbow ramp from red to purple, used ONLY to color by stimulus
# direction (ring index). Stimulus k of N maps to a hue sweeping from red
# (hue 0) through the spectrum to purple, so adjacent stimuli are adjacent
# colors and the ring reads as a smooth gradient. Use stim_color(k, n).
def stim_color(k, n=ONETASK_N_STIM):
"""Color for stimulus index k of n, on a red→purple rainbow ramp."""
n = max(int(n), 1)
# Sweep hue from 0 (red) to ~0.83 (purple/violet) across the n stimuli.
frac = (k % n) / max(n - 1, 1)
hue = 0.83 * frac
return mpl.colors.hsv_to_rgb((hue, 0.85, 0.9))
def stim_colors(n=ONETASK_N_STIM):
"""List of n stimulus colors on the red→purple rainbow ramp."""
return [stim_color(k, n) for k in range(n)]
def _shade(color, frac):
"""Shade `color` by `frac` in [-1, 1]: frac<0 darkens toward BLACK (frac=-1
→ black), frac=0 is the original, frac>0 lightens toward WHITE (frac=+1 →
white). Used to shade a trajectory dark→bright along a sweep."""
r, g, b = mpl.colors.to_rgb(color)
if frac >= 0:
return (r + (1 - r) * frac, g + (1 - g) * frac, b + (1 - b) * frac)
f = 1.0 + frac # frac in [-1,0] -> multiplier in [0,1]
return (r * f, g * f, b * f)
def _fixed_point_mask(entry, n):
"""Boolean (n,) mask of which gradient fixed points converged.
Reads the `is_fixed` array saved by one_task_analysis.py (relative-step <=
rel_tol). Older pickles lack it — treat every point as converged so figures
from those still render unchanged."""
mask = entry.get("is_fixed")
if mask is None:
return np.ones(int(n), dtype=bool)
return np.asarray(mask, dtype=bool)
# ─── Helpers ─────────────────────────────────────────────────────────────────
def _ensure_out_dir():
OUT_DIR.mkdir(parents=True, exist_ok=True)
def _breaks(lbls):
"""Cluster boundary positions from an ordered label array."""
idx = np.nonzero(np.diff(lbls))[0] + 1
return idx.tolist()
# Task name → Driscoll et al. 2024 display name
_TASK_DISPLAY = {
"fdgo": "DelayPro",
"fdanti": "DelayAnti",
"delaygo": "MemoryPro",
"delayanti": "MemoryAnti",
"reactgo": "ReactGo",
"reactanti": "ReactAnti",
"delaydm1": "IntegrationModality1",
"delaydm2": "IntegrationModality2",
"contextdelaydm1": "ContextIntModality1",
"contextdelaydm2": "ContextIntModality2",
"multidelaydm": "IntegrationMultimodal",
"dmsgo": "ReactMatch2Sample",
"dmsnogo": "ReactNonMatch2Sample",
"dmcgo": "ReactCategoryPro",
"dmcnogo": "ReactCategoryAnti",
}
# Task → computation-category motif and color (matches state_space_shift.py)
_RULE_MOTIF = {
"fdgo": ("Pro Delayed", "#3182ce"), # blue
"fdanti": ("Anti Delayed", "#e53e3e"), # red
"delaygo": ("Pro Delayed", "#3182ce"),
"delayanti": ("Anti Delayed", "#e53e3e"),
"reactgo": ("Pro Reaction", "#38a169"), # green
"reactanti": ("Anti Reaction", "#dd6b20"), # orange
"contextdelaydm1": ("Pro Integration", "#4682b4"), # steelblue
"contextdelaydm2": ("Pro Integration", "#4682b4"),
"delaydm1": ("Pro Integration", "#4682b4"),
"delaydm2": ("Pro Integration", "#4682b4"),
"multidelaydm": ("Pro Integration", "#4682b4"),
"dmsgo": ("Categorization", "#38a169"),
"dmsnogo": ("Categorization", "#dd6b20"),
"dmcgo": ("Categorization", "#ff1493"), # deeppink
"dmcnogo": ("Categorization", "#ff1493"),
}
# Phase suffix → display name and background color
_PHASE_DISPLAY = {
"stim1": "Stimulus 1",
"stim2": "Stimulus 2",
"delay1": "Memory 1",
"delay2": "Memory 2",
"go1": "Response",
}
_PHASE_COLORS = {
"stim1": "#c3b1e1", # purple
"stim2": "#bfdbfe", # light blue
"delay1": "#bbf7d0", # light green
"delay2": "#fed7aa", # light orange
"go1": "#d1d5db", # light gray
}
# Period colorbar palette for the one-task / two-task period strip, ordered
# Fixation → Stimulus → Memory → Response. Stimulus/Memory/Response reuse the
# multi-task heatmap phase colors (_PHASE_COLORS stim1/delay1/go1) so the period
# bar is color-consistent with those figures; Fixation has no heatmap
# counterpart, so it gets a new pastel yellow in the same soft-pastel family.
_ONETASK_PERIOD_COLORS = [
"#fef08a", # Fixation — new (pale yellow)
_PHASE_COLORS["stim1"], # Stimulus — matches heatmap Stimulus 1 (purple)
_PHASE_COLORS["delay1"], # Memory — matches heatmap Memory 1 (light green)
_PHASE_COLORS["go1"], # Response — matches heatmap Response (light gray)
]
# ─── Input / output channel colors ────────────────────────────────────────────
# Colors for the example-trial input and output traces. A muted qualitative set,
# deliberately distinct from the vivid stimulus rainbow (stim_color) and the pale
# period-bar pastels (_ONETASK_PERIOD_COLORS). Within a modality the cos/sin
# channels share a hue as a (dark, light) pair. Fixation↔Fixation shares a color
# across the input and output figures. The response Cos/Sin get their OWN hue
# (purple), deliberately distinct from the stimulus modalities so the readout is
# not confused with an input modality.
_IO_FIXATION = "#555555" # dark gray
# Mod1 and Mod2 share the SAME green cos/sin pair, so cos↔cos and sin↔sin match
# across the two stimulus modalities (they are the same physical channel, just a
# different modality). Within the pair the cos/sin keeps the (dark, light)
# convention.
_IO_MOD2 = ("#1b9e77", "#6fceae") # green (cos dark, sin light) = stimulus cos/sin
_IO_MOD1 = _IO_MOD2 # Modality 1 shares Modality 2's cos/sin colors
_IO_TASK = "#d95f02" # orange (single channel)
_IO_TASK2 = "#fdae6b" # light orange = second (inactive) task cue
_IO_RESPONSE = ("#7e3ff2", "#c4a3f5") # purple (cos dark, sin light) = readout
def _relabel_tb_name(name):
"""Convert '{rule}-{phase}' to '{DisplayRule}-{DisplayPhase}'."""
for phase, disp in _PHASE_DISPLAY.items():
if name.endswith(f"-{phase}"):
rule = name[: -(len(phase) + 1)]
rule_disp = _TASK_DISPLAY.get(rule, rule)
return f"{rule_disp}-{disp}"
return name
def _phase_of(name):
"""Return the phase suffix of a '{rule}-{phase}' label, or None."""
for phase in _PHASE_DISPLAY:
if name.endswith(f"-{phase}"):
return phase
return None
def _task_display_name(name):
"""Task-only display label for a '{rule}-{phase}' tick.
Drops the phase/session suffix (e.g. 'Response', 'Memory1') and returns
just the task display name (e.g. 'DelayPro'). Falls back to the full
relabeled name if no phase suffix is present.
"""
phase = _phase_of(name)
if phase is not None:
rule = name[: -(len(phase) + 1)]
return _TASK_DISPLAY.get(rule, rule)
return _relabel_tb_name(name)
def _color_phase_ticklabels(ax, ordered_names, axis="y"):
"""Set a background highlight on each tick label based on its phase."""
labels = ax.get_yticklabels() if axis == "y" else ax.get_xticklabels()
for lab, name in zip(labels, ordered_names):
phase = _phase_of(name)
if phase is not None:
lab.set_bbox(dict(facecolor=_PHASE_COLORS[phase], edgecolor="none",
boxstyle="round,pad=0.15", alpha=0.8))
def _color_motif_ticklabels(ax, task_names, axis="y"):
"""Set a background highlight on each tick label based on its task's
computation-category motif (see _RULE_MOTIF). `task_names` is the list of
raw rule names in tick order."""
labels = ax.get_yticklabels() if axis == "y" else ax.get_xticklabels()
for lab, task in zip(labels, task_names):
color = _RULE_MOTIF.get(task, (None, None))[1]
if color is not None:
lab.set_bbox(dict(facecolor=color, edgecolor="none",
boxstyle="round,pad=0.15", alpha=0.5))
def _load_cluster_info():
"""Load the cluster_info pickle for the target model."""
pkl_path = DATA_DIR / f"cluster_info_{ANAME}.pkl"
if not pkl_path.exists():
raise FileNotFoundError(f"Cluster info not found: {pkl_path}")
with open(pkl_path, "rb") as f:
return pickle.load(f)
# ─── Figure: Clustered variance matrix ───────────────────────────────────────
def _recut_labels(linkage, k, original_labels):
"""
Re-cut a dendrogram at a different k.
The linkage matrix was built on the "active" subset (excluding any
unresponsive neurons marked with label = original_k + 1). This
function cuts the linkage at the new k, then maps back to the full
label array preserving the unresponsive label if present.
"""
original_k = linkage.shape[0] # n_obs - 1 gives linkage rows
n_obs = linkage.shape[0] + 1
original_labels = np.asarray(original_labels)
unique_orig = np.unique(original_labels)
# Detect unresponsive cluster (label > original_k stored in result)
max_label = unique_orig.max()
# If there's an unresponsive cluster, its label = col_tol_k + 1
# which equals n_obs + 1 (since linkage has n_obs - 1 rows → n_obs active neurons)
has_unresponsive = (max_label > n_obs)
unres_mask = original_labels == max_label if has_unresponsive else np.zeros(len(original_labels), dtype=bool)
new_active_labels = fcluster(linkage, t=k, criterion="maxclust")
full_labels = np.zeros(len(original_labels), dtype=int)
full_labels[~unres_mask] = new_active_labels
if has_unresponsive:
full_labels[unres_mask] = k + 1
return full_labels
def _compute_order_from_labels(linkage, labels):
"""
Compute a display order that groups neurons by cluster label,
with within-cluster ordering derived from the dendrogram leaf order.
"""
from scipy.cluster.hierarchy import leaves_list
leaf_order = leaves_list(linkage)
labels = np.asarray(labels)
n = len(labels)
# Map from linkage leaf order (active neurons only) to full array
unique_labels = np.unique(labels)
active_mask = labels <= labels.max() # all are active in this context
# Build order: group by cluster, within each cluster use dendrogram order
ordered = []
for lab in sorted(unique_labels):
members = set(np.where(labels == lab)[0])
# Keep dendrogram order among members
for idx in leaf_order:
if idx in members:
ordered.append(idx)
# Any members not in leaf_order (e.g. unresponsive) appended at end
remaining = members - set(ordered)
ordered.extend(sorted(remaining))
return np.array(ordered, dtype=int)
def _add_col_cluster_strip(ax, cl_ordered, cbreaks):
"""Add a thin colored strip below the heatmap, one color per column cluster,
to visually group the x-axis columns by their cluster assignment."""
n_cols = len(cl_ordered)
# Cluster boundaries as [start, end) spans
bounds = [0] + list(cbreaks) + [n_cols]
n_clusters = len(bounds) - 1
strip = ax.inset_axes([0, -0.06, 1, 0.04], transform=ax.transAxes)
cmap_clusters = plt.get_cmap("tab20")
for ci in range(n_clusters):
start, end = bounds[ci], bounds[ci + 1]
strip.axvspan(start, end, color=cmap_clusters(ci % 20), lw=0)
strip.set_xlim(0, n_cols)
strip.set_ylim(0, 1)
strip.set_xticks([])
strip.set_yticks([])
for s in strip.spines.values():
s.set_visible(False)
return strip
def _add_row_cluster_strip(ax, rl_ordered, rbreaks):
"""Add a thin colored strip to the right of the heatmap, one color per row
cluster, to visually group the y-axis rows by their cluster assignment."""
n_rows = len(rl_ordered)
bounds = [0] + list(rbreaks) + [n_rows]
n_clusters = len(bounds) - 1
strip = ax.inset_axes([1.01, 0, 0.025, 1], transform=ax.transAxes)
cmap_clusters = plt.get_cmap("tab20")
for ci in range(n_clusters):
start, end = bounds[ci], bounds[ci + 1]
strip.axhspan(start, end, color=cmap_clusters(ci % 20), lw=0)
# Heatmap rows increase downward; match that orientation
strip.set_ylim(n_rows, 0)
strip.set_xlim(0, 1)
strip.set_xticks([])
strip.set_yticks([])
for s in strip.spines.values():
s.set_visible(False)
return strip
def _add_period_strip(ax, spans, xmax, height=0.05, pad=0.02):
"""Add a thin colored strip above `ax` marking trial periods, matching the
cluster-strip style used in the multi-task heatmaps (colors only, no text).
`spans` is a list of (start, end, color, ...) tuples in the parent axis's
data-x coordinates; a trailing `end` of None runs to `xmax`. The strip is an
inset axis placed just above the parent, spanning its full x-range so the
period boundaries line up with the traces below.
"""
strip = ax.inset_axes([0, 1.0 + pad, 1, height], transform=ax.transAxes)
for span in spans:
start, end, color = span[0], span[1], span[2]
end = xmax if end is None else min(end, xmax)
strip.axvspan(start, end, color=color, lw=0)
strip.set_xlim(0, xmax)
strip.set_ylim(0, 1)
strip.set_xticks([])
strip.set_yticks([])
for s in strip.spines.values():
s.set_visible(False)
return strip
def _plot_clustered_variance(
cell_vars, result, tb_break_name,
title="", cmap="magma", vmin=0, vmax=1,
figsize=(8, 7),
row_k_override=None,
col_k_override=None,
):
"""
Create a single-panel figure of the clustered task-variance matrix
with cluster boundaries.
Parameters
----------
row_k_override : int, optional
Override the number of row (session) clusters by re-cutting the
stored dendrogram at this k.
col_k_override : int, optional
Override the number of col (neuron) clusters by re-cutting the
stored dendrogram at this k.
Returns (fig, ax).
"""
# Determine row labels and order
if row_k_override is not None:
rl_full = _recut_labels(result["row_linkage"], row_k_override, result["row_tol_labels"])
row_order = _compute_order_from_labels(result["row_linkage"], rl_full)
row_k = row_k_override
else:
rl_full = np.asarray(result["row_tol_labels"])
row_order = result["row_order"]
row_k = result["row_tol_k"]
# Determine col labels and order
if col_k_override is not None:
cl_full = _recut_labels(result["col_linkage"], col_k_override, result["col_tol_labels"])
col_order = _compute_order_from_labels(result["col_linkage"], cl_full)
col_k = col_k_override
else:
cl_full = np.asarray(result["col_tol_labels"])
col_order = result["col_order"]
col_k = result["col_tol_k"]
ordered = cell_vars[np.ix_(row_order, col_order)]
rl = rl_full[row_order]
cl = cl_full[col_order]
rbreaks = _breaks(rl)
cbreaks = _breaks(cl)
fig, ax = plt.subplots(1, 1, figsize=figsize)
hm = sns.heatmap(
ordered, ax=ax, cmap=cmap, vmin=vmin, vmax=vmax,
cbar=True, cbar_kws={"shrink": 0.4, "label": "Normalized variance"},
)
cbar = hm.collections[0].colorbar
cbar.set_ticks([vmin, vmax])
cbar.set_ticklabels([f"{vmin:.0f}", f"{vmax:.0f}"])
cbar.ax.tick_params(labelsize=12)
for rb in rbreaks:
ax.axhline(rb, color="0.6", lw=0.5, zorder=3, alpha=0.6)
for cb in cbreaks:
ax.axvline(cb, color="0.6", lw=0.5, zorder=3, alpha=0.6)
ordered_names = tb_break_name[row_order]
display_names = [_task_display_name(nm) for nm in ordered_names]
ax.set_yticks(np.arange(len(ordered_names)) + 0.5)
ax.set_yticklabels(display_names, rotation=0, ha="right", va="center", fontsize=6)
_color_phase_ticklabels(ax, ordered_names, axis="y")
ax.set_xticks([])
# Column-cluster grouping strip beneath the x-axis
_add_col_cluster_strip(ax, cl, cbreaks)
# Row-cluster grouping strip to the right of the y-axis
_add_row_cluster_strip(ax, rl, rbreaks)
fig.tight_layout()
return fig, ax
def plot_clustered_input():
"""
Figure: Clustered normalized task-variance matrix for the INPUT layer.
"""
_ensure_out_dir()
cluster_info = _load_cluster_info()
data = cluster_info["input_normalized"]
fig, _ = _plot_clustered_variance(
cell_vars=data["cell_vars_rules_sorted_norm"],
result=data["result"],
tb_break_name=data["tb_break_name"],
title="Input Layer — Normalized Task Variance",
)
out_path = OUT_DIR / "clustered_input_normalized.png"
_save_fig(fig, out_path)
def plot_clustered_hidden(col_k_override=20):
"""
Figure: Clustered normalized task-variance matrix for the HIDDEN layer.
"""
_ensure_out_dir()
cluster_info = _load_cluster_info()
data = cluster_info["hidden_normalized"]
fig, _ = _plot_clustered_variance(
cell_vars=data["cell_vars_rules_sorted_norm"],
result=data["result"],
tb_break_name=data["tb_break_name"],
title="Hidden Layer — Normalized Task Variance",
col_k_override=col_k_override,
)
out_path = OUT_DIR / "clustered_hidden_normalized.png"
_save_fig(fig, out_path)
# ─── Figure: Clustered modulation variance matrix ────────────────────────────
def _load_cluster_info_mod():
"""Load the modulation cluster_info pickle for the target model."""
pkl_path = DATA_DIR / f"cluster_info_mod_{ANAME}.pkl"
if not pkl_path.exists():
raise FileNotFoundError(f"Modulation cluster info not found: {pkl_path}")
with open(pkl_path, "rb") as f:
return pickle.load(f)
def plot_clustered_modulation(G_index=1):
"""
Figure: Clustered normalized task-variance matrix for MODULATION synapses.
Uses the G=300 KMeans pre-grouping result (index 1 in result_all_lst).
The figure is 2x wider than input/hidden figures to accommodate the
90,000 synapse columns.
"""
_ensure_out_dir()
mod_info = _load_cluster_info_mod()
mod_data = mod_info["modulation_all_normalized"]
cell_vars = mod_data["cell_vars_rules_sorted_norm"]
tb_break_name = mod_data["tb_break_name"]
result = mod_data["result_all_lst"][G_index]
row_order = result["row_order"]
col_order = result["col_order"]
ordered = cell_vars[np.ix_(row_order, col_order)]
rl = np.asarray(result["row_tol_labels"])[row_order]
cl = np.asarray(result["col_tol_labels"])[col_order]
rbreaks = _breaks(rl)
cbreaks = _breaks(cl)
row_k = result["row_tol_k"]
col_k = result["col_tol_k"]
fig, ax = plt.subplots(1, 1, figsize=(16, 7))
hm = sns.heatmap(
ordered, ax=ax, cmap="magma", vmin=0, vmax=1,
cbar=True, cbar_kws={"shrink": 0.4, "label": "Normalized variance"},
)
cbar = hm.collections[0].colorbar
cbar.set_ticks([0, 1])
cbar.set_ticklabels(["0", "1"])
cbar.ax.tick_params(labelsize=12)
for rb in rbreaks:
ax.axhline(rb, color="0.6", lw=0.5, zorder=3, alpha=0.6)
for cb in cbreaks:
ax.axvline(cb, color="0.6", lw=0.5, zorder=3, alpha=0.6)
ordered_names = tb_break_name[row_order]
display_names = [_task_display_name(nm) for nm in ordered_names]
ax.set_yticks(np.arange(len(ordered_names)) + 0.5)
ax.set_yticklabels(display_names, rotation=0, ha="right", va="center", fontsize=6)
_color_phase_ticklabels(ax, ordered_names, axis="y")
ax.set_xticks([])
# Column-cluster grouping strip beneath the x-axis
_add_col_cluster_strip(ax, cl, cbreaks)
# Row-cluster grouping strip to the right of the y-axis
_add_row_cluster_strip(ax, rl, rbreaks)
fig.tight_layout()
out_path = OUT_DIR / "clustered_modulation_normalized.png"
_save_fig(fig, out_path)
# ─── Figure: L2 vs Accuracy ──────────────────────────────────────────────────
PERF_RESULT_PATH = Path("multiple_tasks_perf") / "performance_results.json"
def plot_l2_vs_accuracy():
"""Figure: Test accuracy (%) vs L2 regularization strength."""
import json as _json
_ensure_out_dir()
if not PERF_RESULT_PATH.exists():
print(f" Skipped: {PERF_RESULT_PATH} not found. Run multiple_task_performance.py first.")
return
with open(PERF_RESULT_PATH) as f:
result_dict = _json.load(f)
l2_vals = np.array([e["l2_info"] for e in result_dict.values()])
acc_vals = np.array([e["acc"] for e in result_dict.values()]) * 100
fig, ax = plt.subplots(1, 1, figsize=(2.3, 3))
ax.scatter(l2_vals, acc_vals, color="#3182ce", edgecolors="k",
linewidths=0.5, s=40, alpha=0.8, zorder=3)
ax.set_xscale("log")
ax.set_xlabel("L2 regularization strength")
ax.set_ylabel("Test accuracy (%)")
# Adaptive y-range: pad the observed accuracy span by 5% of its extent
# (min 2 pts), clamped to the valid [0, 100] accuracy interval.
lo, hi = float(acc_vals.min()), float(acc_vals.max())
pad = max((hi - lo) * 0.05, 2.0)
ax.set_ylim(max(0.0, lo - pad), min(100.0, hi + pad))
ax.spines[["top", "right"]].set_visible(False)
ax.yaxis.grid(True, linestyle=":", linewidth=0.5, color="0.8", zorder=0)
fig.tight_layout()
out_path = OUT_DIR / "l2_vs_accuracy.png"
_save_fig(fig, out_path)
# ─── Figure: State space PCA ─────────────────────────────────────────────────
STATE_SPACE_DIR = Path("state_space")
def _plot_state_space_pca(X_2d, ctx_rule_labels, all_rules, rule_motif_mapping,
title="", figsize=(2.5, 2.5), show_legend=True):
"""
Scatter of context-endpoint PCA colored by computation category.
Returns (fig, ax).
"""
category_order = [
"Pro Delayed",
"Anti Delayed",
"Pro Reaction",
"Anti Reaction",
"Pro Integration",
"Categorization",
]
category_to_color = {cat: col for _, (cat, col) in rule_motif_mapping.items()}
fig, ax = plt.subplots(1, 1, figsize=figsize)
for cat in category_order:
rule_idxs_in_cat = [
idx for idx, rule in enumerate(all_rules)
if rule_motif_mapping[rule][0] == cat
]
sel = np.isin(ctx_rule_labels, rule_idxs_in_cat)
ax.scatter(
X_2d[sel, 0], X_2d[sel, 1],
label=cat, color=category_to_color[cat],
alpha=0.5, s=18, edgecolors="none",
)
ax.set_xlabel("PC1")
ax.set_ylabel("PC2")
ax.set_title(title, fontsize=10, pad=6)
if show_legend:
_legend(ax, frameon=True, loc="best", fontsize=5, markerscale=1.0)
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
return fig, ax
def _load_state_space_pca():
"""Load the PCA pickle for the target model."""
pattern = f"state_space_pca_{ANAME}_noise*.pkl"
matches = list(STATE_SPACE_DIR.glob(pattern))
if not matches:
return None
return pickle.load(open(matches[0], "rb"))
def plot_state_space_combined():
"""Figure: Context-end PCA for hidden (top) and eff_mod (bottom) stacked vertically."""
_ensure_out_dir()
data = _load_state_space_pca()
if data is None:
print(" Skipped: state_space PCA pickle not found. Run state_space_shift.py first.")
return
all_rules = data["all_rules"]
rule_motif_mapping = data["rule_motif_mapping"]
category_order = [
"Pro Delayed", "Anti Delayed", "Pro Reaction",
"Anti Reaction", "Pro Integration", "Categorization",
]
category_to_color = {cat: col for _, (cat, col) in rule_motif_mapping.items()}
fig, axes = plt.subplots(2, 1, figsize=(2.5, 4.5), sharex=True)
panels = [
("hidden", "Hidden state", False),
("eff_mod", "Eff. modulation", True),
]
for ax, (key, ylabel_prefix, show_legend) in zip(axes, panels):
pca = data["pca_results"][key]
X_2d = pca["X_2d"]
ctx_rule_labels = pca["ctx_rule_labels"]
for cat in category_order:
rule_idxs_in_cat = [
idx for idx, rule in enumerate(all_rules)
if rule_motif_mapping[rule][0] == cat
]
sel = np.isin(ctx_rule_labels, rule_idxs_in_cat)
ax.scatter(
X_2d[sel, 0], X_2d[sel, 1],
label=cat, color=category_to_color[cat],
alpha=0.5, s=14, edgecolors="none",
)
ax.set_ylabel(f"{ylabel_prefix}\nPC2", fontsize=8)
ax.spines[["top", "right"]].set_visible(False)
ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(integer=True))
ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(integer=True))
if show_legend:
_legend(ax, frameon=True, loc="best", fontsize=5, markerscale=1.0)
axes[1].set_xlabel("PC1", fontsize=8)
axes[0].tick_params(labelbottom=False)
fig.tight_layout()
out_path = OUT_DIR / "state_space_combined.png"
_save_fig(fig, out_path)
RVAL_RESULT_PATH = STATE_SPACE_DIR / "initial_condition_distance_vs_angle_results.pkl"
def plot_state_space_r_values():
"""Figure: Mean R-values (initial-condition distance vs trajectory angle) for hidden & eff_mod."""
_ensure_out_dir()
result_dict = _load_pkl_or_skip(RVAL_RESULT_PATH, "Run state_space_shift.py first.")
if result_dict is None:
return
data_types = ["hidden", "mod", "eff_mod"]
labels = ["Hidden", "Mod.", "Eff. Mod."]
colors = ["#3182ce", "#dd6b20", "#38a169"]
r_values = {dt: [] for dt in data_types}
for results in result_dict.values():
for dt in data_types:
if dt in results["rval_dict"]:
r_values[dt].append(results["rval_dict"][dt][0])
fig, ax = plt.subplots(1, 1, figsize=(2.5, 3))
positions = np.arange(len(data_types))
r_means = [np.mean(r_values[dt]) for dt in data_types]
r_stds = [np.std(r_values[dt]) for dt in data_types]
ax.bar(positions, r_means, yerr=r_stds, capsize=4,
color=colors, edgecolor="k", linewidth=0.6, width=0.6)
for dt_idx, dt in enumerate(data_types):
jitter = np.random.default_rng(42).uniform(-0.12, 0.12, len(r_values[dt]))
ax.scatter(positions[dt_idx] + jitter, r_values[dt],
color="k", s=15, alpha=0.5, zorder=5)
ax.set_xticks(positions)
ax.set_xticklabels(labels, fontsize=8)
ax.set_ylabel("R-value")
ax.set_ylim(0, 1.05)
ax.spines[["top", "right"]].set_visible(False)
ax.yaxis.grid(True, linestyle=":", linewidth=0.5, color="0.8", zorder=0)
fig.tight_layout()
out_path = OUT_DIR / "state_space_r_values.png"
_save_fig(fig, out_path)
# ─── Figure: Over-membership ─────────────────────────────────────────────────
def _find_experiment_dirs():
"""Return all experiment subfolders under multiple_tasks/ matching the
same feature/hidden/batch signature as ANAME (any seed)."""
import re as _re
# ANAME = everything_seed{seed}_{feature}+hidden{h}+batch{b}+angle
m = _re.match(r"everything_seed\d+_(.+)$", ANAME)
suffix = m.group(1) if m else ""
base = Path("multiple_tasks")
dirs = sorted(base.glob(f"everything_seed*_{suffix}"))
return [d for d in dirs if d.is_dir()]
def _plot_overmembership_single(pkl_template, out_filename):