-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotting.py
More file actions
1480 lines (1311 loc) · 62.2 KB
/
Copy pathplotting.py
File metadata and controls
1480 lines (1311 loc) · 62.2 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
# Plots for use in the App and beyond
import numpy as np
import matplotlib.pyplot as plt
import os
import math
import utilities
import model_core
from matplotlib.backends.backend_pdf import PdfPages
# some constants and indices
congr_upright_indices = [0, 3]
congr_updown_indices = [5, 6]
incongr_upright_indices = [1, 2]
incongr_updown_indices = [4, 7]
def _timesteps_transport_default():
"""Return the model transport duration, falling back to the current default."""
return getattr(model_core, "timesteps_transport", 100)
def plot_focus(trial_data):
"""Plot event focus values over one trial."""
# get relevant parts from the input data
timesteps_reach = trial_data[0,5]
# cut here, depending on timesteps_reach, etc.
F = trial_data[:(int(timesteps_reach+_timesteps_transport_default())),19:24] #(?)
fig, ax = plt.subplots()
ax.plot(F[:,1], label="F[1] (reach)")
ax.plot(F[:,2], label="F[2] (grasp)")
ax.plot(F[:,3], label="F[3] (transp.)")
ax.plot(F[:,4], label="F[4] (put-d.)")
ax.plot(F[:,0], label="F[0] (idle)")
ax.legend()
ax.set_xlabel("Timestep")
ax.set_ylabel("Focus value")
ax.axvline(timesteps_reach, color='grey', alpha=0.5)
return fig
def _focus_runs_by_condition(trials_data):
"""Reshape uncompressed trial data into run x condition x time x feature."""
trials_data = np.asarray(trials_data)
if trials_data.ndim != 3:
raise ValueError(
"Expected trials_data with shape (n_trials, n_timesteps, n_features)."
)
if trials_data.shape[0] < 8 or trials_data.shape[0] % 8 != 0:
raise ValueError(
"Expected uncompressed data ordered as 8 trial conditions per simulation run. "
"Use the *_all.npz res_data output, not the 8-condition averaged file."
)
return trials_data.reshape(
trials_data.shape[0] // 8,
8,
trials_data.shape[1],
trials_data.shape[2],
)
def _mean_and_band(values, band="sd"):
"""Return mean and symmetric uncertainty band across simulation runs."""
values = np.asarray(values, dtype=float)
mean = np.nanmean(values, axis=0)
n_runs = values.shape[0]
if n_runs < 2:
spread = np.zeros_like(mean)
else:
sd = np.nanstd(values, axis=0, ddof=1)
if band == "sd":
spread = sd
elif band == "sem":
spread = sd / np.sqrt(n_runs)
elif band in ("ci", "ci95", "95ci"):
spread = 1.96 * sd / np.sqrt(n_runs)
else:
raise ValueError("band must be one of 'sd', 'sem', or 'ci'.")
return mean, mean - spread, mean + spread
def plot_focus_uncertainty(
trials_data,
condition_groups=None,
focus_indices=(1, 2),
focus_labels=None,
band="sd",
colors=None,
font_size=None,
):
"""Plot mean focus weights with across-run uncertainty bands.
`trials_data` should be uncompressed `res_data`, where consecutive blocks
of 8 trials are the 8 trial configurations for one simulation run. The
default plot shows reach and grasp focus averaged over all trial conditions.
"""
if condition_groups is None:
condition_groups = [("All trials", list(range(8)))]
if focus_labels is None:
default_labels = {
0: "F[0] (idle)",
1: "F[1] (reach)",
2: "F[2] (grasp)",
3: "F[3] (transp.)",
4: "F[4] (put-d.)",
}
focus_labels = [default_labels.get(i, f"F[{i}]") for i in focus_indices]
if colors is None:
colors = {
0: "#9ecae1",
1: "#1f77b4",
2: "#ff7f0e",
3: "#2ca02c",
4: "#7f0000",
}
old_font_size = None
if font_size is not None:
old_font_size = plt.rcParams.get('font.size', None)
plt.rcParams.update({'font.size': font_size})
try:
runs_by_condition = _focus_runs_by_condition(trials_data)
n_groups = len(condition_groups)
fig, axs = plt.subplots(1, n_groups, figsize=(6 * n_groups, 4.5), sharey=True)
axs = np.atleast_1d(axs)
for ax, (title, condition_indices) in zip(axs, condition_groups):
condition_indices = list(condition_indices)
grouped = runs_by_condition[:, condition_indices, :, :]
timesteps_reach = int(np.round(np.nanmean(grouped[:, :, 0, 5])))
n_timesteps = min(
timesteps_reach + _timesteps_transport_default(),
grouped.shape[2],
)
x = np.arange(n_timesteps)
for focus_idx, label in zip(focus_indices, focus_labels):
values = grouped[:, :, :n_timesteps, 19 + focus_idx]
per_run = np.nanmean(values, axis=1)
mean, low, high = _mean_and_band(per_run, band=band)
color = colors.get(focus_idx, None)
ax.plot(x, mean, label=label, color=color, linewidth=2)
ax.fill_between(x, low, high, color=color, alpha=0.2, linewidth=0)
ax.axvline(timesteps_reach, color='grey', alpha=0.5)
ax.set_xlim(0, n_timesteps - 1)
ax.set_ylim(0, 1)
if n_groups > 1:
ax.set_title(title)
ax.set_xlabel("Timestep")
ax.set_ylabel("Focus value")
handles, labels = axs[0].get_legend_handles_labels()
fig.legend(
handles,
labels,
#loc="upper center",
#bbox_to_anchor=(0.5, 0.95),
loc = "right",
bbox_to_anchor=(0.95,0.85),
ncol=len(focus_indices),
#frameon=False,
)
band_labels = {
"sd": "SD",
"sem": "SEM",
"ci": "95% CI",
"ci95": "95% CI",
"95ci": "95% CI",
}
#fig.suptitle(
# f"Mean focus weights across simulation runs ({band_labels[band]} bands)",
# y=0.99,
#)
fig.tight_layout()#rect=(0, 0, 1, 0.9))
return fig
finally:
if font_size is not None and old_font_size is not None and old_font_size != font_size:
plt.rcParams.update({'font.size': old_font_size})
def plot_inf_event(trial_data):
"""Plot the inferred event sequence for one trial."""
timesteps_reach = trial_data[0,5]
fig, ax = plt.subplots()
ax.plot(trial_data[:(int(timesteps_reach)+_timesteps_transport_default()),18], label="inferred event", color="black")
ax.axhline(0, color="lightblue", linestyle="dotted")
ax.axhline(1, color="blue", linestyle="dotted")
ax.axhline(2, color="orange", linestyle="dotted")
ax.axhline(3, color="green", linestyle="dotted")
ax.axhline(4, color="purple", linestyle="dotted")
ax.set_xlabel("Timestep")
ax.set_yticks([0, 1, 2, 3, 4])
ax.set_yticklabels(["idle", "reach", "grasp", "transport", "put-down"], rotation=45)
ax.axvline(timesteps_reach, color='grey', alpha=0.5)
return fig
def plot_base(trial_data, timestep_bottle_appearance=None, timestep_stim=None, timesteps_reach=None):
"""Plot the main trial progression."""
if not timesteps_reach or timesteps_reach is None:
timesteps_reach = int(trial_data[0,5])
# possibly cut the data to the relevant timesteps
trial_data = trial_data[:(int(timesteps_reach)+_timesteps_transport_default()),:]
# other data points
x = trial_data[:,12] # position/distance
orient = trial_data[:,11] # orientation
if not timestep_bottle_appearance or timestep_bottle_appearance is None:
timestep_bottle_appearance = int(trial_data[0,3])
if not timestep_stim or timestep_stim is None:
timestep_stim = int(trial_data[0,4])
if trial_data[timestep_stim,1] == utilities.THUMB:
if trial_data[timestep_stim,2] == utilities.LEFT:
color = 'yellow'
else:
color = 'orange'
else:
if trial_data[timestep_stim,2] == utilities.LEFT:
color = 'red'
else:
color = 'purple'
fig, ax = plt.subplots()
ax.plot(x, color="black", label="Position/Distance")
ax.plot(orient, color="lightblue", linestyle="solid", label="Orientation")
ax.axvline(timestep_bottle_appearance, 0, 1, color='green',
linestyle='dashed' if trial_data[timestep_bottle_appearance,0] == utilities.UPRIGHT else 'dotted',
label="Bottle Appearance")
ax.axvline(timestep_stim, color=color, linestyle='dashed', label="Stimulation/Distractor")
try:
plt.axvline(np.where(trial_data[:,10] != 0)[0][0], color='purple', label="Response") # response
except:
pass
ax.plot(trial_data[:,6:8], color='grey', linestyle='dashed', label="Response density") # P_S
ax.plot(trial_data[:,8:10], color='grey', linestyle='dotted', label="Response-side density") # P_R
ax.set_xlabel("Timestep")
ax.axvline(timesteps_reach, color='grey', alpha=0.5, label="Object contact")
#ax.legend()
return fig
def plot_movement(trial_data, timestep_bottle_appearance=None, timesteps_reach=None, figsize=(10,6)):
"""Plot only the movement: position/distance, orientation, bottle appearance and object contact."""
if not timesteps_reach or timesteps_reach is None:
timesteps_reach = int(trial_data[0,5])
# possibly cut the data to the relevant timesteps
trial_data = trial_data[:(int(timesteps_reach)+_timesteps_transport_default()),:]
x = trial_data[:,12] # position/distance
orient = trial_data[:,11] # orientation
if timestep_bottle_appearance is None:
timestep_bottle_appearance = int(trial_data[0,3])
fig, ax = plt.subplots(figsize=figsize)
ax.plot(x, color="black", label="Position/Distance")
ax.plot(orient, color="lightblue", linestyle="solid", label="Orientation")
ax.axvline(timestep_bottle_appearance, 0, 1, color='green',
linestyle='dashed' if trial_data[timestep_bottle_appearance,0] == utilities.UPRIGHT else 'dotted',
label="Bottle Appearance")
ax.axvline(timesteps_reach, color='grey', alpha=0.5, label="Object contact")
ax.set_xlabel("Timestep")
#ax.set_title("Movement: position & orientation")
ax.legend()
return fig
def plot_stim_response(trial_data, timestep_stim=None, timesteps_reach=None, figsize=(10,6)):
"""Plot stimulation and response (P_Q, P_R)."""
if not timesteps_reach or timesteps_reach is None:
timesteps_reach = int(trial_data[0,5])
# cut to relevant timesteps
trial_data = trial_data[:(int(timesteps_reach)+_timesteps_transport_default()),:]
if timestep_stim is None:
timestep_stim = int(trial_data[0,4])
# determine stim color by finger and side
try:
if trial_data[timestep_stim,1] == utilities.THUMB:
color = 'yellow' if trial_data[timestep_stim,2] == utilities.LEFT else 'orange'
else:
color = 'red' if trial_data[timestep_stim,2] == utilities.LEFT else 'purple'
except Exception:
color = 'orange'
fig, ax = plt.subplots(figsize=figsize)
ax.axvline(timestep_stim, color=color, linestyle='dashed', label="Stimulation/Distractor")
try:
resp_idx = np.where(trial_data[:,10] != 0)[0][0]
ax.axvline(resp_idx, color='purple', label="Response")
except Exception:
resp_idx = None
# response densities: columns 6,7 (P_Q) and 8,9 (P_R)
try:
#ax.plot(trial_data[:,6], color='grey', linestyle='dashed', label="Response-side density (P_S)")
ax.plot(trial_data[:,6], color='grey', linestyle='dashed', label="Stimulus density (P_Q)")
ax.plot(trial_data[:,7], color='grey', linestyle='dashed')
ax.plot(trial_data[:,8], color='grey', linestyle='dotted', label="Response density (P_R)")
ax.plot(trial_data[:,9], color='grey', linestyle='dotted')
except Exception:
pass
ax.set_xlabel("Timestep")
#ax.set_title("Stimulation & Response")
ax.legend()
return fig
def plot_trial_progression(trial_data, timestep_bottle_appearance=None, timestep_stim=None, timesteps_reach=None):
"""Plot movement, stimulation, response, and response densities for one trial."""
if not timesteps_reach or timesteps_reach is None:
timesteps_reach = int(trial_data[0,5])
# possibly cut the data to the relevant timesteps
trial_data = trial_data[:(int(timesteps_reach)+_timesteps_transport_default()),:]
# other data points
x = trial_data[:,12] # position/distance
orient = trial_data[:,11] # orientation
if not timestep_bottle_appearance or timestep_bottle_appearance is None:
timestep_bottle_appearance = int(trial_data[0,3])
if not timestep_stim or timestep_stim is None:
timestep_stim = int(trial_data[0,4])
if trial_data[timestep_stim,1] == utilities.THUMB:
if trial_data[timestep_stim,2] == utilities.LEFT:
color = 'yellow'
else:
color = 'orange'
else:
if trial_data[timestep_stim,2] == utilities.LEFT:
color = 'red'
else:
color = 'purple'
fig, ax = plt.subplots()
ax.plot(x, color="black", label="Position/Distance")
ax.plot(orient, color="lightblue", linestyle="solid", label="Orientation")
ax.axvline(timestep_bottle_appearance, 0, 1, color='green',
linestyle='dashed' if trial_data[timestep_bottle_appearance,0] == utilities.UPRIGHT else 'dotted',
label="Bottle Appearance")
ax.axvline(timestep_stim, color=color, linestyle='dashed', label="Stimulation/Distractor")
try:
plt.axvline(np.where(trial_data[:,10] != 0)[0][0], color='purple', label="Response") # response
except:
pass
ax.plot(trial_data[:,6], color='grey', linestyle='dashed', label="Response density") # P_S
ax.plot(trial_data[:,7], color='grey', linestyle='dashed') # P_S
ax.plot(trial_data[:,8], color='grey', linestyle='dotted', label="Response-side density") # P_R
ax.plot(trial_data[:,9], color='grey', linestyle='dotted') # P_R
ax.set_xlabel("Timestep")
ax.axvline(timesteps_reach, color='grey', alpha=0.5, label="Object contact")
ax.legend()
return fig
def plot_entropies(entropies, timesteps_reach=100):
"""Plot entropy traces by component for one trial."""
# should be a 3D array of shape (timesteps, 5, 3)
entropies = entropies[:(timesteps_reach+_timesteps_transport_default()),:,:] # cut to the right size
# visualize
fig, axs = plt.subplots(1, 3)#, figsize=(15, 5))
for j in range(3):
axs[j].plot(entropies[:,1,j], label="Reach")
axs[j].plot(entropies[:,2,j], label="Grasp")
axs[j].plot(entropies[:,3,j], label="Transport")
axs[j].plot(entropies[:,4,j], label="Put-down")
axs[j].plot(entropies[:,0,j], label="Idle")
axs[j].set_xlabel("Timestep")
axs[j].legend()
axs[0].set_ylabel("Entropy value")
axs[0].set_title("Initiator")
axs[1].set_title("Dynamics")
axs[2].set_title("Outcome")
# tight layout
plt.tight_layout()
return fig
def rt_plot2(rt_data):
"""Plot RT condition means with error bars."""
data = utilities.get_rt_df_(rt_data)
fig, ax = plt.subplots()
plt.errorbar(
[0.2, 0.8],
[np.mean(data[data["Condition"] == "Congruent Upright"]["RT"]),
np.mean(data[data["Condition"] == "Incongruent Upright"]["RT"])],
yerr=[np.std(data[data["Condition"] == "Congruent Upright"]["RT"]),
np.std(data[data["Condition"] == "Incongruent Upright"]["RT"])],
fmt='d-', label="Upright"
)
plt.errorbar(
[0.203, 0.803],
[np.mean(data[data["Condition"] == "Congruent Upside-Down"]["RT"]),
np.mean(data[data["Condition"] == "Incongruent Upside-Down"]["RT"])],
yerr=[np.std(data[data["Condition"] == "Congruent Upside-Down"]["RT"]),
np.std(data[data["Condition"] == "Incongruent Upside-Down"]["RT"])],
fmt='d-', label="Upside-Down"
)
plt.legend(title="Bottle Orientation")
plt.ylabel("RT")
plt.xticks([0.2, 0.8], ["Congruent", "Incongruent"])
return fig
def single_event_over_trial_plot(densities, event_name="Event", bins=None, save=None, filetype="pdf",
max_timesteps=None, row_height=0.22, dim_names=None,
vmax_scale=1.05, rows_per_page=50, id=None):
"""Plot one event density over time as paged rows of small histograms."""
densities = np.asarray(densities)
if densities.ndim != 3:
raise ValueError("densities must be a 3D array (timesteps x 3 x bins) or (timesteps x bins x 3)")
# Normalize shape to (T, 3, B)
if densities.shape[1] == 3:
T_full, D, B = densities.shape
elif densities.shape[2] == 3:
T_full, B, D = densities.shape
densities = densities.transpose(0, 2, 1)
D = 3
elif densities.shape[0] == 3:
D, T_full, B = densities.shape
densities = densities.transpose(1, 0, 2)
D = 3
else:
raise ValueError("Expected one dimension to be 3 (the three columns per timestep)")
if D != 3:
raise ValueError("Plotting expects exactly 3 columns/dimensions per timestep")
# Respect max_timesteps as a hard cap
if max_timesteps is not None:
T_effective = min(T_full, int(max_timesteps))
densities = densities[:T_effective]
else:
T_effective = T_full
# Determine whether pagination/truncation is needed
do_paginate = (rows_per_page is not None) and (rows_per_page > 0) and (T_effective > rows_per_page)
# The figure we'll return should be the first page (possibly truncated)
T_return = min(T_effective, rows_per_page) if do_paginate else T_effective
if bins is None:
# B is the original bins value
bins = B
if dim_names is None:
dim_names = ["Dim 0", "Dim 1", "Dim 2"]
def make_page_figure(dens_page, page_index=0):
# dens_page has shape (T_page, 3, bins)
T_page = dens_page.shape[0]
fig_w = 9.0
fig_h = max(2.0, row_height * T_page)
fig = plt.figure(figsize=(fig_w, fig_h))
# reduce GridSpec hspace (we control final spacing with subplots_adjust)
gs = fig.add_gridspec(T_page, 3, hspace=0.02, wspace=0.22)
x = np.arange(bins)
global_ymax = dens_page.max() * vmax_scale if dens_page.size else 1.0
for t in range(T_page):
for j in range(3):
ax = fig.add_subplot(gs[t, j])
vals = dens_page[t, j]
ax.bar(x, vals, color=f"C{j}", width=0.9)
ax.set_xlim(-0.5, bins - 0.5)
ax.set_ylim(0, global_ymax)
ax.set_xticks([])
ax.set_yticks([])
# slightly smaller column title font to avoid collisions with suptitle
if t == 0:
ax.set_title(dim_names[j], fontsize=7)
if j == 0:
ax.text(-0.02, 0.5, f"t={t + page_index*rows_per_page}", transform=ax.transAxes,
ha="right", va="center", fontsize=7)
# Annotate if truncated
if do_paginate:
# Put the suptitle close to the top but leave extra room for column titles
fig.suptitle(f"{event_name} densities over time (showing {T_page}/{T_effective} timesteps; page {page_index+1})", fontsize=10, y=0.99)
else:
fig.suptitle(f"{event_name} densities over time (top: t=0)", fontsize=10, y=0.99)
# Move subplots down a bit (lower `top`) so column titles have space below the suptitle,
# while keeping hspace tight between rows. These values prevent suptitle/column-title overlap.
fig.subplots_adjust(top=0.97, left=0.03, right=0.98, hspace=0.02, wspace=0.18)
return fig
# Build the returned (first page) figure
dens_first_page = densities[:T_return]
fig_first = make_page_figure(dens_first_page, page_index=0)
# If saving, handle multipage PDF (or numbered parts for other filetypes)
if save:
outdir = save
if outdir and not os.path.exists(outdir):
os.makedirs(outdir, exist_ok=True)
safe_name = "".join(c if (c.isalnum() or c in (" ", "_", "-")) else "_" for c in event_name).strip().replace(" ", "_")
ext = str(filetype).lstrip('.') if filetype is not None else 'pdf'
if id is not None:
safe_name += f"_{id}"
filename = f"{safe_name}.{ext}"
fullpath = os.path.join(outdir, filename)
if ext.lower() == 'pdf' and do_paginate:
# write a multi-page PDF with PdfPages; iterate pages over the capped range (T_effective)
with PdfPages(fullpath) as pdf:
for i, start in enumerate(range(0, T_effective, rows_per_page)):
end = min(start + rows_per_page, T_effective)
dens_page = densities[start:end]
fig_page = make_page_figure(dens_page, page_index=i)
pdf.savefig(fig_page, bbox_inches='tight')
plt.close(fig_page)
else:
# For non-PDF or when no pagination needed: if pagination was desired but filetype != pdf,
# save numbered part files; otherwise save single file
if do_paginate and ext.lower() != 'pdf':
for i, start in enumerate(range(0, T_effective, rows_per_page)):
end = min(start + rows_per_page, T_effective)
dens_page = densities[start:end]
fig_page = make_page_figure(dens_page, page_index=i)
part_name = f"{safe_name}_part{i+1}.{ext}"
part_path = os.path.join(outdir, part_name)
fig_page.savefig(part_path, bbox_inches='tight')
plt.close(fig_page)
else:
# Save the single (possibly truncated) returned figure
fig_first.savefig(fullpath, bbox_inches='tight')
return fig_first
def events_over_trial_plot_all(events_densities, save=None, filetype="png", id=None, event_name="All_Events", font_size=None):
"""Plot all event/component density heatmaps in one figure."""
#plt.rc("font", 6)
#plt.rcParams.update({'font.size': 6})
if font_size is not None:
old_font_size = plt.rcParams["font.size"]
plt.rcParams["font.size"] = font_size
fig, axs = plt.subplots(5, 9, figsize=(15, 10), constrained_layout=True)
event_names = ["Idle", "Reach", "Grasp", "Transport", "Put-down"]
dim_names = ["Init-Orient", "Init-Pos", "Init-Angle", "Dyn-Orient", "Dyn-Pos", "Dyn-Angle",
"Out-Orient", "Out-Pos", "Out-Angle"]
for i, event in enumerate(event_names):
for j, dim_all in enumerate(dim_names):
dimension = dim_all.split("-")[1]
component = dim_all.split("-")[0]
comp = {"Init":0, "Dyn":1, "Out":2}[component]
dim = {"Orient":0, "Pos":1, "Angle":2}[dimension]
im = axs[i, j].imshow(events_densities[i, comp, dim, :, :], origin="lower", aspect="auto",
extent=[0.0, 1.0, 0, events_densities.shape[-2]],
cmap="viridis")
if i == 0:
axs[i, j].set_title(dim_all)
if j == 0:
axs[i, j].set_ylabel(event)
#fig.colorbar(im, ax=axs[i, j])
#fig.colorbar(im, cax=axs[i, j])
if save:
outdir = save
if outdir and not os.path.exists(outdir):
os.makedirs(outdir, exist_ok=True)
safe_name = "".join(c if (c.isalnum() or c in (" ", "_", "-")) else "_" for c in event_name).strip().replace(" ", "_")
ext = str(filetype).lstrip('.') if filetype is not None else 'pdf'
if id is not None:
safe_name += f"_{id}"
filename = f"{safe_name}.{ext}"
fullpath = os.path.join(outdir, filename)
fig.savefig(fullpath, bbox_inches='tight', dpi=300)
#return fig
if font_size is not None:
plt.rcParams["font.size"] = old_font_size
def plot_single_density(density, save=None, filetype="png", id=None, density_name="Density",
type="heatmap", rows_per_col=100, max_timesteps=None, show_title=True, font_size=None):
"""Plot one density over time as a heatmap or paged row plot."""
# Set font size if necessary
if font_size is not None:
old_font_size = plt.rcParams["font.size"]
plt.rcParams["font.size"] = font_size
data = np.asarray(density)
# cut timesteps if needed
if max_timesteps is not None:
data = data[:int(max_timesteps)]
# If it's not a heatmap but instead a set of histograms/barplots, as above
if type=="histograms":
# Make several columns depending on the length
n_cols = int(np.ceil(data.shape[0] / rows_per_col))
fig, axs = plt.subplots(rows_per_col, n_cols, figsize=(3*n_cols, 0.22*rows_per_col), constrained_layout=True)
for col in range(n_cols):
for row in range(rows_per_col):
t = col * rows_per_col + row
if t >= data.shape[0]:
break
ax = axs[row, col] if n_cols > 1 else axs[row]
ax.bar(np.arange(data.shape[1]), data[t], color="C0", width=0.9)
ax.set_xlim(-0.5, data.shape[1]-0.5)
ax.set_ylim(0, data.max()*1.05)
ax.set_xticks([])
ax.set_yticks([])
if row == 0:
ax.set_title(f"t={t}")
if density_name is not None and show_title is not False:
fig.suptitle(f"{density_name} over time", fontsize=10, y=0.99)
fig.subplots_adjust(top=0.97, left=0.03, right=0.98, hspace=0.02, wspace=0.18)
else:
# heatmap
fig, ax = plt.subplots(figsize=(9, 6))
im = ax.imshow(data, origin="lower", aspect="auto",
extent=[0.0, 1.0, 0, data.shape[0]],
cmap="viridis")
fig.colorbar(im, ax=ax)
ax.set_xlabel("Density Support")
ax.set_ylabel("Timestep")
if density_name is not None and show_title is not False:
ax.set_title(f"{density_name} over time")
if save:
outdir = save
if outdir and not os.path.exists(outdir):
os.makedirs(outdir, exist_ok=True)
safe_name = "".join(c if (c.isalnum() or c in (" ", "_", "-")) else "_" for c in density_name).strip().replace(" ", "_")
ext = str(filetype).lstrip('.') if filetype is not None else 'pdf'
if id is not None:
safe_name += f"_{id}"
filename = f"{safe_name}.{ext}"
fullpath = os.path.join(outdir, filename)
fig.savefig(fullpath, bbox_inches='tight', dpi=300)
if font_size is not None:
plt.rcParams["font.size"] = old_font_size
return fig
def plot_focus_fours(trials_data):
"""Plot focus values for congruent/incongruent and upright/upside-down trials."""
# getting parts here depending on the indices
congr_up_data = utilities.get_means_further_trials(trials_data[congr_upright_indices])
incongr_up_data = utilities.get_means_further_trials(trials_data[incongr_upright_indices])
congr_down_data = utilities.get_means_further_trials(trials_data[congr_updown_indices])
incongr_down_data = utilities.get_means_further_trials(trials_data[incongr_updown_indices])
# see if there are different timesteps_reach values or not, decide whether to share x row-wise or total
t_reachs = trials_data[:,0,5]
sharex = True if np.all(t_reachs == t_reachs[0]) else 'row'
fig, axs = plt.subplots(2, 2, figsize=(12, 10), sharex=sharex, sharey=True)
# helper function to plot the focus values
def plot_focus_subplot(ax, data, title):
timesteps_reach = int(data[0, 5])
F = data[:(timesteps_reach + _timesteps_transport_default()), 19:24]
ax.plot(F[:, 1], label="F[1] (reach)", alpha=0.7)
ax.plot(F[:, 2], label="F[2] (grasp)", alpha=0.7)
ax.plot(F[:, 3], label="F[3] (transp.)", alpha=0.7)
ax.plot(F[:, 4], label="F[4] (put-d.)", alpha=0.7)
ax.plot(F[:, 0], label="F[0] (idle)", alpha=0.7)
ax.axvline(timesteps_reach, color='grey', alpha=0.5)
ax.set_xlim(0, timesteps_reach + _timesteps_transport_default())
ax.set_title(title)
ax.set_xlabel("Timestep")
ax.set_ylabel("Focus value")
# Single subplots for each condition
plot_focus_subplot(axs[0, 0], congr_up_data, "Congruent Upright")
axs[0, 0].legend()
plot_focus_subplot(axs[0, 1], incongr_up_data, "Incongruent Upright")
plot_focus_subplot(axs[1, 0], congr_down_data, "Congruent Upside-Down")
plot_focus_subplot(axs[1, 1], incongr_down_data, "Incongruent Upside-Down")
# Layout
plt.tight_layout()
return fig
def plot_focus_subplot(ax, data, title):
"""Draw one focus subplot on an existing axis."""
timesteps_reach = int(data[0, 5])
F = data[:(timesteps_reach + _timesteps_transport_default()), 19:24]
ax.plot(F[:, 1], label="F[1] (reach)", alpha=0.7)
ax.plot(F[:, 2], label="F[2] (grasp)", alpha=0.7)
ax.plot(F[:, 3], label="F[3] (transp.)", alpha=0.7)
ax.plot(F[:, 4], label="F[4] (put-d.)", alpha=0.7)
ax.plot(F[:, 0], label="F[0] (idle)", alpha=0.7)
ax.axvline(timesteps_reach, color='grey', alpha=0.5)
ax.set_xlim(0, timesteps_reach + _timesteps_transport_default())
ax.set_title(title)
ax.set_xlabel("Timestep")
ax.set_ylabel("Focus value")
#return ax
def plot_focus_twos(trials_data, font_size=None):
"""Plot focus averaged by upright and upside-down orientation."""
if font_size is not None:
old_font_size = plt.rcParams.get('font.size', None)
plt.rcParams.update({'font.size': font_size})
try:
# getting parts here depending on the indices
upright_indices = congr_upright_indices + incongr_upright_indices
updown_indices = congr_updown_indices + incongr_updown_indices
upright_data = utilities.get_means_further_trials(trials_data[upright_indices])
updown_data = utilities.get_means_further_trials(trials_data[updown_indices])
# # see if there are different timesteps_reach values or not, decide whether to share x row-wise or total
# t_reachs = trials_data[:,0,5]
# sharex = True if np.all(t_reachs == t_reachs[0]) else 'row'
# (for now, make them horizontally, not vertically)
fig, axs = plt.subplots(1, 2, figsize=(12, 5), sharey=True)
# Single subplots for each condition
plot_focus_subplot(axs[0], upright_data, "Upright")
axs[0].legend()
plot_focus_subplot(axs[1], updown_data, "Upside-Down")
# Layout
plt.tight_layout()
return fig
finally:
# restore old font size if necessary
if font_size is not None and old_font_size is not None and old_font_size != font_size:
plt.rcParams.update({'font.size': old_font_size})
def plot_inf_event_fours(trials_data):
"""Plot inferred event traces for the four trial-condition groups."""
# getting parts here depending on the indices
congr_up_data = utilities.get_means_further_trials(trials_data[congr_upright_indices])
incongr_up_data = utilities.get_means_further_trials(trials_data[incongr_upright_indices])
congr_down_data = utilities.get_means_further_trials(trials_data[congr_updown_indices])
incongr_down_data = utilities.get_means_further_trials(trials_data[incongr_updown_indices])
# see if there are different timesteps_reach values or not, decide whether to share x row-wise or total
t_reachs = trials_data[:,0,5]
sharex = True if np.all(t_reachs == t_reachs[0]) else 'row'
fig, axs = plt.subplots(2, 2, figsize=(12, 10), sharex=sharex, sharey=True)
# helper function to plot the inferred event values
def plot_inf_event_subplot(ax, data, title):
timesteps_reach = int(data[0, 5])
ax.plot(data[:(timesteps_reach + _timesteps_transport_default()), 18], label="inferred event", color="black")
ax.axhline(0, color="lightblue", linestyle="dotted")
ax.axhline(1, color="blue", linestyle="dotted")
ax.axhline(2, color="orange", linestyle="dotted")
ax.axhline(3, color="green", linestyle="dotted")
ax.axhline(4, color="purple", linestyle="dotted")
ax.set_xlabel("Timestep")
ax.set_yticks([0, 1, 2, 3, 4])
ax.set_yticklabels(["idle", "reach", "grasp", "transport", "put-down"], rotation=45)
ax.axvline(timesteps_reach, color='grey', alpha=0.5)
ax.set_title(title)
# Single subplots for each condition
plot_inf_event_subplot(axs[0, 0], congr_up_data, "Congruent Upright")
plot_inf_event_subplot(axs[0, 1], incongr_up_data, "Incongruent Upright")
plot_inf_event_subplot(axs[1, 0], congr_down_data, "Congruent Upside-Down")
plot_inf_event_subplot(axs[1, 1], incongr_down_data, "Incongruent Upside-Down")
# Layout
plt.tight_layout()
return fig
def plot_multiple_conditions_focus(datasets,which_params, which_params_values, mod_name): # todo: for now, saving back where this is called? ...
"""Plot focus comparisons for a two-parameter condition grid."""
# Normalize inputs
if which_params is None:
which_params = []
if which_params_values is None:
which_params_values = []
# Determine grid dimensions
if len(which_params) >= 2:
param_row_name = which_params[0]
param_col_name = which_params[1]
row_vals = list(which_params_values[0])
col_vals = list(which_params_values[1])
rows = len(row_vals)
cols = len(col_vals)
elif len(which_params) == 1:
param_row_name = None
param_col_name = which_params[0]
row_vals = [None]
col_vals = list(which_params_values[0])
rows = 1
cols = len(col_vals)
else:
# fallback: place all datasets in a single row
param_row_name = None
param_col_name = None
row_vals = [None]
cols = len(datasets)
col_vals = [None] * cols
rows = 1
total_cells = rows * cols
# Ensure datasets is a list and has correct length
datasets_list = list(datasets)
if len(datasets_list) < total_cells:
datasets_list = datasets_list + [None] * (total_cells - len(datasets_list))
else:
datasets_list = datasets_list[:total_cells]
# Create figure and axes grid
fig, axs = plt.subplots(rows, cols, figsize=(max(15, cols*5), max(9, rows*3)), squeeze=False)
# For each cell, create two small axes and plot upright/upside-down using plot_focus_subplot
upright_indices = congr_upright_indices + incongr_upright_indices
updown_indices = congr_updown_indices + incongr_updown_indices
for r in range(rows):
for c in range(cols):
ax = axs[r][c]
idx = r * cols + c
cell_data = datasets_list[idx]
# create two inset axes side-by-side inside the cell axis
left_ax = ax.inset_axes([0.0, 0.0, 0.48, 1.0])
right_ax = ax.inset_axes([0.52, 0.0, 0.48, 1.0])
# hide the parent cell axis frame so only the inset axes are visible
ax.set_frame_on(False)
# ensure the parent axis has no ticks or background patch, but remains present
try:
ax.patch.set_alpha(0)
except Exception:
pass
ax.set_xticks([])
ax.set_yticks([])
if cell_data is None:
# no data: annotate blank cell
left_ax.text(0.5, 0.5, "no data", ha='center', va='center', color='red')
right_ax.axis('off')
left_ax.set_xticks([])
left_ax.set_yticks([])
else:
try:
# Expect cell_data to be an array-like with shape (N_trials, timesteps, features)
td = np.asarray(cell_data)
# select upright/upside-down trials using the standard indices
u_idxs = [i for i in upright_indices if i < td.shape[0]]
d_idxs = [i for i in updown_indices if i < td.shape[0]]
if len(u_idxs) > 0:
upright_data = utilities.get_means_further_trials(td[u_idxs])
else:
upright_data = None
if len(d_idxs) > 0:
updown_data = utilities.get_means_further_trials(td[d_idxs])
else:
updown_data = None
except Exception as e:
upright_data = None
updown_data = None
# plot into the small axes using existing helper
# We'll plot manually into the inset axes but avoid titles/axis labels
def _plot_focus_on_ax(ax_inner, data_inner):
if data_inner is None:
ax_inner.text(0.5, 0.5, "no data", ha='center', va='center', color='gray')
ax_inner.set_xticks([])
return
timesteps_reach = int(data_inner[0, 5])
F = data_inner[:(timesteps_reach + _timesteps_transport_default()), 19:24]
x = np.arange(F.shape[0])
# color mapping: 1->blue, 2->orange, 3->green, 4->purple, 0->lightblue
colmap = {1: 'tab:blue', 2: 'tab:orange', 3: 'tab:green', 4: 'tab:purple', 0: 'lightblue'}
ax_inner.plot(x, F[:, 1], color=colmap[1], alpha=0.8)
ax_inner.plot(x, F[:, 2], color=colmap[2], alpha=0.8)
ax_inner.plot(x, F[:, 3], color=colmap[3], alpha=0.8)
ax_inner.plot(x, F[:, 4], color=colmap[4], alpha=0.8)
ax_inner.plot(x, F[:, 0], color=colmap[0], alpha=0.8)
ax_inner.axvline(timesteps_reach, color='grey', alpha=0.5)
ax_inner.set_xlim(0, timesteps_reach + _timesteps_transport_default())
# do not set titles or y-labels here (outer labels are used)
# try and set them to none here ...
#ax_inner.set_yticks([])
_plot_focus_on_ax(left_ax, upright_data)
_plot_focus_on_ax(right_ax, updown_data)
# only show a legend once (top-left cell)
if r == 0 and c == 0:
# create legend in the left inset using labels
# build proxy lines for legend
lab_lines = []
lab_labels = ["F[1] (reach)", "F[2] (grasp)", "F[3] (transp.)", "F[4] (put-d.)", "F[0] (idle)"]
# match the same colors as the plots
colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:purple', 'lightblue']
for color, lab in zip(colors, lab_labels):
line, = left_ax.plot([], [], color=color, label=lab)
lab_lines.append(line)
left_ax.legend(handles=lab_lines, loc='upper right', fontsize='small')
# By default disable ticks and labels on both inset axes to avoid duplicates
left_ax.tick_params(axis='both', which='both', labelbottom=False, bottom=False)
right_ax.tick_params(axis='both', which='both', labelbottom=False, bottom=False)
# Enable x ticks/label only for the bottom row on the right inset
if r == rows - 1:
right_ax.tick_params(axis='x', which='both', labelbottom=True, bottom=True)
right_ax.set_xlabel('Timestep')
# Enable y ticks/label only for the leftmost column on the left inset
if c == 0:
left_ax.tick_params(axis='y', which='both', labelleft=True, left=True)
left_ax.set_ylabel('Focus value')
# Layout
plt.tight_layout()
return fig
def plot_multiple_conditions_focus_subfigures(datasets, which_params, which_params_values, mod_name=None, figsize=None):
"""Plot focus comparisons for a two-parameter grid using subfigures."""
# Normalize inputs
if which_params is None:
which_params = []
if which_params_values is None:
which_params_values = []
# determine grid shape
if len(which_params) >= 2:
param_row_name = which_params[0]
param_col_name = which_params[1]
row_vals = list(which_params_values[0])
col_vals = list(which_params_values[1])
rows = len(row_vals)
cols = len(col_vals)
elif len(which_params) == 1:
param_row_name = None
param_col_name = which_params[0]
row_vals = [None]
col_vals = list(which_params_values[0])
rows = 1
cols = len(col_vals)
else:
param_row_name = None
param_col_name = None
row_vals = [None]
cols = len(datasets)
col_vals = [None] * cols
rows = 1
total_cells = rows * cols
datasets_list = list(datasets)
if len(datasets_list) < total_cells:
datasets_list = datasets_list + [None] * (total_cells - len(datasets_list))
else:
datasets_list = datasets_list[:total_cells]
# figure size heuristic
if figsize is None:
fig_w = int(max(12, cols * 5.5))
fig_h = int(max(4, rows * 3.5))
else:
fig_w, fig_h = figsize
# create a gridspec with a top row and left column reserved for labels
# layout: (rows+1) x (cols+1) grid; [0,0] unused, [0,1:] column labels, [1:,0] row labels, [1:,1:] plots
# reduce the size reserved for labels (top/left) and tighten spacing
fig = plt.figure(figsize=(fig_w, fig_h))
outer_gs = fig.add_gridspec(rows + 1, cols + 1,
width_ratios=[0.08] + [1.0]*cols,
height_ratios=[0.02] + [1.0]*rows,
hspace=0.08, wspace=0.10)
upright_indices = congr_upright_indices + incongr_upright_indices
updown_indices = congr_updown_indices + incongr_updown_indices
colmap = {1: 'tab:blue', 2: 'tab:orange', 3: 'tab:green', 4: 'tab:red', 0: 'lightblue'}
legend_drawn = False
# Top: parameter name (center) and per-column values
if param_col_name is not None:
ax_colname = fig.add_subplot(outer_gs[0, 1:])
ax_colname.axis('off')
# place the parameter name a bit lower so it's closer to the column values and plots
ax_colname.text(0.5, 0.95, str(param_col_name), ha='center', va='bottom', fontsize=12, weight='bold')
for c, col_val in enumerate(col_vals):
# Make a small axis for each column value for reliable placement
ax_c = fig.add_subplot(outer_gs[0, c + 1])
ax_c.axis('off')
# raise the value text so it sits closer to the plots
ax_c.text(0.5, 0.5, str(col_val), ha='center', va='center', fontsize=10)
else:
# consume top row but leave it empty
for c in range(cols):
ax_c = fig.add_subplot(outer_gs[0, c + 1])
ax_c.axis('off')
# Left: parameter name (vertical) and per-row values
if param_row_name is not None:
ax_rowname = fig.add_subplot(outer_gs[1:, 0])
ax_rowname.axis('off')
# place the row parameter name slightly to the right so it visually aligns with row values