-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsu_core.py
More file actions
2150 lines (1854 loc) · 75.3 KB
/
Copy pathcsu_core.py
File metadata and controls
2150 lines (1854 loc) · 75.3 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
"""Core utilities for the shuffled-vs-unshuffled comparison pipeline.
This file is auto-refactored out of the original `compare_shuffled_unshuffled.py` to improve readability.
It contains:
- Robust statistical helpers
- CSV probing helpers
- Plot saving utilities (Plotly HTML/PNG/EPS + an index page)
- Generic helpers used by feature extraction, pipeline, and mixed-model modules
Public API:
- compare_shuffled_unshuffled
- compare_participant_metrics
"""
from __future__ import annotations
import os
import re
import warnings
import math
from fnmatch import fnmatch
from typing import Optional, List, Tuple, Any, Dict
import numpy as np
from numpy.typing import NDArray
import pandas as pd
from scipy.stats import ttest_ind, linregress, pearsonr, mannwhitneyu
import plotly.graph_objects as go # noqa:F401
import statsmodels.formula.api as smf # noqa:F401
import statsmodels.api as sm # noqa:F401
# Project helpers (used for plot output directories).
from helper import HMD_helper, apply_global_plotly_style
import common # project module used by HMD_helper.save_plotly
from custom_logger import CustomLogger
# Shared yaw/quaternion column heuristics.
# These are used by file-selection helpers (e.g., `_score_trial_file`) and yaw feature extraction.
# Kept in a standalone module to avoid circular imports between `csu_core` and `csu_features`.
from csu_yaw_constants import _YAW_CANDIDATES, _QUAT_REGEX, _QUAT_LIST_COL_PAT # noqa:F401
HAVE_SM = True
logger = CustomLogger(__name__) # use custom logger
# ---------------------------------------------------------------------------
# Output precision helpers
# ---------------------------------------------------------------------------
# Keep raw numeric values in DataFrames/CSVs, but format console/report tables
# with at most three decimal places. Small non-zero values are shown in
# scientific notation so p values do not appear as exact zero.
DISPLAY_DECIMALS = 3
font_size = common.get_configs("font_size")
def _format_float_for_display(value: float, decimals: int = DISPLAY_DECIMALS) -> str:
try:
x = float(value)
except Exception:
return str(value)
if np.isnan(x):
return "nan"
if np.isposinf(x):
return "inf"
if np.isneginf(x):
return "-inf"
if x != 0 and abs(x) < 10 ** (-decimals):
return f"{x:.{decimals}e}"
text = f"{x:.{decimals}f}".rstrip("0").rstrip(".")
return "0" if text in {"-0", ""} else text
def _to_string_3dp(df: pd.DataFrame, *args, **kwargs) -> str:
"""Return a DataFrame string with floats shown to at most 3 decimals."""
return df.to_string(*args, float_format=_format_float_for_display, **kwargs)
def _round_numeric_for_output(df: pd.DataFrame, decimals: int = DISPLAY_DECIMALS) -> pd.DataFrame:
"""Return a copy with numeric columns rounded for optional paper outputs."""
out = df.copy()
numeric_cols = out.select_dtypes(include=[np.number]).columns
if len(numeric_cols):
out.loc[:, numeric_cols] = out.loc[:, numeric_cols].round(decimals)
return out
# Consistent dataset labels and colours used across all exported figures.
DATASET_LABEL_MAP = {
"shuffled": "Randomised",
"unshuffled": "Fixed order",
"fixed-order": "Fixed order",
"fixed order": "Fixed order",
"randomized": "Randomised",
"randomised": "Randomised",
}
DATASET_COLOUR_MAP = {
"shuffled": "#1f77b4",
"unshuffled": "#ff7f0e",
"Randomised": "#1f77b4",
"Fixed order": "#ff7f0e",
}
# Compatibility alias for earlier patches that used American spelling.
DATASET_COLOR_MAP = DATASET_COLOUR_MAP
# ---------------------------------------------------------------------------
# Per-figure text size controls for exported Plotly figures
# ---------------------------------------------------------------------------
# Edit these dictionaries when a specific figure needs larger or smaller text.
# The keys are the file names passed to _save_plot(..., name="...") without
# extension. Wildcards are supported through PLOT_TEXT_SIZE_BY_PATTERN.
#
# Available keys in a style dictionary:
# x_label_size, y_label_size, x_tick_size, y_tick_size,
# legend_size, legend_title_size, legend_title_text, legend_x, legend_y,
# legend_xanchor, legend_yanchor, legend_orientation,
# line_width, violin_line_width, marker_line_width, marker_size,
# title_size, annotation_size, font_size, width, height
#
# Legend placement uses Plotly paper coordinates. For example,
# legend_x=0.98 and legend_y=0.98 places the legend near the top right,
# while legend_x=0.02 and legend_y=0.98 places it near the top left.
#
# These settings are applied centrally before HTML/PNG/EPS export, so all bar,
# line, scatter and violin plots can be controlled from one place.
PLOT_TEXT_SIZE_DEFAULT: Dict[str, Any] = {
"font_size": font_size - 4,
"x_label_size": font_size,
"y_label_size": font_size,
"x_tick_size": font_size - 4,
"y_tick_size": font_size - 4,
"legend_size": font_size - 4,
"legend_title_size": font_size - 4,
"title_size": font_size,
"annotation_size": font_size - 4,
"width": 1320,
"height": 680,
}
PLOT_TEXT_SIZE_BY_KIND: Dict[str, Dict[str, Any]] = {
"bar": {
"x_label_size": 22,
"y_label_size": 22,
"x_tick_size": 18,
"y_tick_size": 18,
"legend_size": 18,
"marker_line_width": 1,
"height": 760,
},
"line": {
"x_label_size": 24,
"y_label_size": 24,
"x_tick_size": 20,
"y_tick_size": 20,
"legend_size": 18,
"line_width": 3,
"height": 760,
},
"violin": {
"x_label_size": 24,
"y_label_size": 24,
"x_tick_size": 20,
"y_tick_size": 20,
"legend_size": 18,
"violin_line_width": 2,
"height": 760,
},
"scatter": {
"x_label_size": 22,
"y_label_size": 22,
"x_tick_size": 18,
"y_tick_size": 18,
"legend_size": 17,
"height": 740,
},
}
# Exact figure-specific overrides. Add any generated figure name here when you
# want that one plot to have different sizes from the default for its kind.
PLOT_TEXT_SIZE_BY_NAME: Dict[str, Dict[str, Any]] = {
# Main manuscript line plots
"curve_time_on_task_trigger_mean": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 34,
"y_tick_size": 34,
"legend_size": 34,
"legend_x": 0.25,
"legend_y": 0.98,
"legend_orientation": "v",
"line_width": 4,
"height": 820,
},
"curve_time_on_task_Q3": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 34,
"y_tick_size": 34,
"legend_size": 34,
"legend_x": 0.25,
"legend_y": 0.98,
"legend_orientation": "v",
"line_width": 4,
"height": 820,
},
"curve_time_on_task_dtrigger_sd": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 34,
"y_tick_size": 34,
"legend_size": 34,
"legend_x": 0.25,
"legend_y": 0.98,
"legend_orientation": "v",
"line_width": 4,
"height": 820,
},
# Appendix latency event absence line plots
"missingness_press_over_trial": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"legend_size": 36,
"legend_title_text": "",
"legend_x": 0.98,
"legend_y": 0.98,
"legend_orientation": "v",
"line_width": 4,
"height": 780,
},
"missingness_release_over_trial": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"legend_size": 36,
"legend_title_text": "",
"legend_x": 0.98,
"legend_y": 0.98,
"legend_orientation": "v",
"line_width": 4,
"height": 780,
},
# AUC bar plot
"F2_bar_auc_by_signal": {
"x_label_size": 24,
"y_label_size": 24,
"x_tick_size": 18,
"y_tick_size": 20,
"legend_size": 18,
"height": 820,
},
# Exposure based figure panels
"MM5_curve_Q3_exposure_yielding": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"legend_size": 36,
"legend_title_text": "",
"legend_x": 0.25,
"legend_y": 0.98,
"legend_orientation": "v",
"line_width": 4,
"height": 780,
},
"MM5_curve_Q3_exposure_eHMI": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"legend_size": 36,
"legend_title_text": "",
"legend_x": 0.85,
"legend_y": 0.18,
"legend_orientation": "v",
"line_width": 4,
"height": 780,
},
"MM5_forest_exposure_interactions": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"marker_size": 11,
"width": 1500,
"height": 720,
},
# Trial-position factor drift plots
"factor_drift_yielding_over_trial_index": {
"x_label_size": 28,
"y_label_size": 28,
"x_tick_size": 23,
"y_tick_size": 23,
"legend_size": 22,
"legend_x": 0.85,
"legend_y": 0.98,
"legend_orientation": "v",
"line_width": 4,
"marker_size": 8,
"height": 820,
"width": 1320,
},
"factor_drift_eHMIOn_over_trial_index": {
"x_label_size": 28,
"y_label_size": 28,
"x_tick_size": 23,
"y_tick_size": 23,
"legend_size": 22,
"legend_x": 0.8,
"legend_y": 0.98,
"legend_orientation": "v",
"line_width": 4,
"marker_size": 8,
"height": 820,
"width": 1320,
},
# Main manuscript participant-level learning and carryover violin plots
"compare_participant_violin_E_carryover_Q3": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"violin_line_width": 2.5,
"marker_size": 8,
"showlegend": False,
"height": 820,
"width": 1320,
},
"compare_participant_violin_E_drift_Q3": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"violin_line_width": 2.5,
"marker_size": 8,
"showlegend": False,
"height": 820,
"width": 1320,
},
"compare_participant_violin_E_slope_Q3": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"violin_line_width": 2.5,
"marker_size": 8,
"showlegend": False,
"height": 820,
"width": 1320,
},
"compare_participant_violin_E_carryover_dtrigger_sd": {
"x_label_size": 28,
"y_label_size": 28,
"x_tick_size": 24,
"y_tick_size": 24,
"violin_line_width": 2.5,
"marker_size": 8,
"showlegend": False,
"height": 820,
"width": 1320,
},
"compare_participant_violin_E_carryover_trigger_mean": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"violin_line_width": 2.5,
"marker_size": 8,
"showlegend": False,
"height": 820,
"width": 1320,
},
# Additional carryover factor violin plots
"compare_participant_violin_E_carryover_prev_eHMIOn_Q3": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"violin_line_width": 2.5,
"marker_size": 8,
"showlegend": False,
"height": 820,
"width": 1320,
},
"compare_participant_violin_E_carryover_prev_camera_Q3": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"violin_line_width": 2.5,
"marker_size": 8,
"showlegend": False,
"height": 820,
"width": 1320,
},
"compare_participant_violin_E_carryover_prev_distPed_Q3": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"violin_line_width": 2.5,
"marker_size": 8,
"showlegend": False,
"height": 820,
"width": 1320,
},
# Reliability figures
"reliability_trigger_mean_odd_even": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"legend_size": 30,
"legend_title_text": "",
"legend_x": 0.05,
"legend_y": 0.95,
"legend_xanchor": "left",
"legend_yanchor": "top",
"legend_orientation": "v",
"marker_size": 12,
"height": 760,
},
"reliability_trigger_mean_early_late": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"legend_size": 30,
"legend_title_text": "",
"legend_x": 0.05,
"legend_y": 0.95,
"legend_xanchor": "left",
"legend_yanchor": "top",
"legend_orientation": "v",
"marker_size": 12,
"height": 760,
},
"reliability_Q3_odd_even": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"legend_size": 30,
"legend_title_text": "",
"legend_x": 0.05,
"legend_y": 0.95,
"legend_xanchor": "left",
"legend_yanchor": "top",
"legend_orientation": "v",
"marker_size": 12,
"height": 760,
},
"reliability_Q3_early_late": {
"x_label_size": 40,
"y_label_size": 40,
"x_tick_size": 36,
"y_tick_size": 36,
"legend_size": 30,
"legend_title_text": "",
"legend_x": 0.05,
"legend_y": 0.95,
"legend_xanchor": "left",
"legend_yanchor": "top",
"legend_orientation": "v",
"marker_size": 12,
"height": 760,
},
}
# Wildcard overrides for groups of figures. Exact entries above still win.
PLOT_TEXT_SIZE_BY_PATTERN: List[Tuple[str, Dict[str, Any]]] = [
("compare_participant_violin_E_*", {"x_label_size": 26,
"y_label_size": 26,
"x_tick_size": 22,
"y_tick_size": 22,
"legend_size": 20,
"legend_x": 0.98,
"legend_y": 0.98,
"violin_line_width": 2,
"showlegend": False,
"height": 800}),
("compare_participant_violin_breakmatched_*", {"x_label_size": 24,
"y_label_size": 24,
"x_tick_size": 20,
"y_tick_size": 20,
"showlegend": False,
"height": 760}),
("compare_participant_violin_*", {"x_label_size": 24,
"y_label_size": 24,
"x_tick_size": 20,
"y_tick_size": 20,
"showlegend": False,
"height": 760}),
("compare_violin_*", {"x_label_size": 24,
"y_label_size": 24,
"x_tick_size": 20,
"y_tick_size": 20,
"showlegend": False,
"height": 760}),
("curve_time_on_task_*", {"x_label_size": 26,
"y_label_size": 26,
"x_tick_size": 22,
"y_tick_size": 22,
"legend_size": 20,
"legend_x": 0.98,
"legend_y": 0.98,
"line_width": 4,
"height": 800}),
("missingness_*_over_trial", {"x_label_size": 26,
"y_label_size": 26,
"x_tick_size": 22,
"y_tick_size": 22,
"legend_size": 20,
"legend_x": 0.98,
"legend_y": 0.98,
"line_width": 4,
"height": 780}),
("yaw_forward_fraction_by_context*", {"x_label_size": 22,
"y_label_size": 22,
"x_tick_size": 18,
"y_tick_size": 18,
"legend_size": 18,
"height": 760}),
("F2_bar_*", {"x_label_size": 24,
"y_label_size": 24,
"x_tick_size": 18,
"y_tick_size": 20,
"height": 820}),
("F2_roc_*", {"x_label_size": 24,
"y_label_size": 24,
"x_tick_size": 20,
"y_tick_size": 20,
"legend_size": 18,
"height": 760}),
("F1_violin_*", {"x_label_size": 24,
"y_label_size": 24,
"x_tick_size": 20,
"y_tick_size": 20,
"showlegend": False,
"height": 760}),
("F1_scatter_*", {"x_label_size": 22,
"y_label_size": 22,
"x_tick_size": 18,
"y_tick_size": 18,
"height": 740}),
]
def _infer_plot_kind(fig: Any) -> str:
"""Infer a broad plot kind from Plotly traces."""
try:
trace_types = {str(getattr(tr, "type", "")).lower() for tr in fig.data}
except Exception:
return "default"
if "violin" in trace_types or "box" in trace_types:
return "violin"
if "bar" in trace_types:
return "bar"
if "scatter" in trace_types:
try:
modes = [str(getattr(tr, "mode", "")) for tr in fig.data if str(getattr(tr,
"type", "")).lower() == "scatter"]
if any("lines" in m for m in modes):
return "line"
except Exception:
return "line"
return "scatter"
return "default"
def _plot_text_style_for_name(fig: Any, name: str) -> Dict[str, Any]:
"""Return the merged text/export-size style for one figure name."""
style: Dict[str, Any] = dict(PLOT_TEXT_SIZE_DEFAULT)
kind = _infer_plot_kind(fig)
style.update(PLOT_TEXT_SIZE_BY_KIND.get(kind, {}))
for pattern, overrides in PLOT_TEXT_SIZE_BY_PATTERN:
if fnmatch(str(name), pattern):
style.update(overrides)
style.update(PLOT_TEXT_SIZE_BY_NAME.get(str(name), {}))
return style
def _apply_plot_text_style(fig: Any, name: str) -> Any:
"""Apply figure-specific axis label and tick sizes before export."""
if fig is None:
return fig
style = _plot_text_style_for_name(fig, name)
try:
fig.update_layout(
font=dict(size=style.get("font_size", PLOT_TEXT_SIZE_DEFAULT["font_size"])),
title_font=dict(size=style.get("title_size", PLOT_TEXT_SIZE_DEFAULT["title_size"])),
)
if not style.get("show_title", False):
fig.update_layout(title_text=None)
except Exception:
pass
try:
fig.update_xaxes(
title_font_size=style.get("x_label_size", PLOT_TEXT_SIZE_DEFAULT["x_label_size"]),
tickfont_size=style.get("x_tick_size", PLOT_TEXT_SIZE_DEFAULT["x_tick_size"]),
automargin=True,
)
except Exception:
pass
try:
fig.update_yaxes(
title_font_size=style.get("y_label_size", PLOT_TEXT_SIZE_DEFAULT["y_label_size"]),
tickfont_size=style.get("y_tick_size", PLOT_TEXT_SIZE_DEFAULT["y_tick_size"]),
automargin=True,
)
except Exception:
pass
try:
legend_update = {
"font": dict(size=style.get("legend_size", PLOT_TEXT_SIZE_DEFAULT["legend_size"])),
"title": dict(
text=style.get("legend_title_text", None),
font=dict(size=style.get("legend_title_size", PLOT_TEXT_SIZE_DEFAULT["legend_title_size"])),
),
}
for style_key, legend_key in (
("legend_x", "x"),
("legend_y", "y"),
("legend_xanchor", "xanchor"),
("legend_yanchor", "yanchor"),
("legend_orientation", "orientation"),
("legend_traceorder", "traceorder"),
("legend_bgcolor", "bgcolor"),
("legend_bordercolor", "bordercolor"),
("legend_borderwidth", "borderwidth"),
):
if style_key in style:
legend_update[legend_key] = style[style_key]
fig.update_layout(legend=legend_update)
except Exception:
pass
try:
if "showlegend" in style:
showlegend = bool(style["showlegend"])
fig.update_layout(showlegend=showlegend)
for tr in fig.data:
try:
tr.showlegend = showlegend
except Exception:
pass
except Exception:
pass
try:
if style.get("line_width") is not None:
lw = float(style["line_width"])
for tr in fig.data:
try:
if str(getattr(tr, "type", "")).lower() != "scatter":
continue
mode = str(getattr(tr, "mode", ""))
if "lines" not in mode:
continue
line = getattr(tr, "line", None)
current_width = getattr(line, "width", None) if line is not None else None
hoverinfo = str(getattr(tr, "hoverinfo", "") or "").lower()
fill = str(getattr(tr, "fill", "") or "").lower()
# Do not turn hidden confidence-band boundary traces into visible lines.
if current_width == 0 or hoverinfo == "skip" or fill not in {"", "none"}:
continue
tr.line.width = lw
except Exception:
pass
except Exception:
pass
try:
if style.get("violin_line_width") is not None:
fig.update_traces(line=dict(width=float(style["violin_line_width"])), selector=dict(type="violin"))
fig.update_traces(line=dict(width=float(style["violin_line_width"])), selector=dict(type="box"))
except Exception:
pass
try:
if style.get("marker_line_width") is not None:
fig.update_traces(marker_line_width=float(style["marker_line_width"]), selector=dict(type="bar"))
except Exception:
pass
try:
if style.get("marker_size") is not None:
fig.update_traces(marker=dict(size=float(style["marker_size"])), selector=dict(type="scatter"))
except Exception:
pass
try:
fig.update_annotations(font_size=style.get("annotation_size", PLOT_TEXT_SIZE_DEFAULT["annotation_size"]))
except Exception:
pass
# Mark figures styled by csu_core so helper.save_plotly does not reapply
# its own per-name defaults and override values edited here.
try:
existing_meta = getattr(fig.layout, "meta", None)
meta = dict(existing_meta) if isinstance(existing_meta, dict) else {}
meta["csu_core_style_applied"] = True
meta["csu_plot_name"] = str(name)
fig.update_layout(meta=meta)
except Exception:
pass
return fig
def _plot_export_size(name: str, fig: Any) -> Tuple[int, int]:
"""Return width and height for static exports of a named figure."""
style = _plot_text_style_for_name(fig, name)
return int(style.get("width", 1320)), int(style.get("height", 680))
def _normalise_dataset_token(value: Any) -> Any:
if value is None:
return value
s = str(value)
key = s.strip().lower().replace("_", " ")
if key in DATASET_LABEL_MAP:
return DATASET_LABEL_MAP[key]
return value
def _rgba_from_hex(hex_colour: str, alpha: float) -> str:
c = str(hex_colour).lstrip("#")
if len(c) != 6:
return f"rgba(0,0,0,{alpha})"
r = int(c[0:2], 16)
g = int(c[2:4], 16)
b = int(c[4:6], 16)
return f"rgba({r},{g},{b},{alpha})"
def _humanise_label(value: Any) -> Any:
"""Convert raw column names into publication-ready British English labels."""
if value is None:
return value
if not isinstance(value, str):
return value
s = value.strip()
if not s:
return s
# dataset names first
norm = _normalise_dataset_token(s)
if isinstance(norm, str) and norm != s:
return norm
direct = {
'dataset': 'Dataset',
'participant_id': 'Participant ID',
'video_id': 'Video ID',
'condition_name': 'Condition',
'trial_index': 'Trial number',
'trial_pos_norm': 'Normalised trial position',
'bin_center': 'Normalised trial position',
'y_mean': 'Mean value',
'sem': 'Standard error',
'q1': 'Q1 rating',
'q2': 'Q2 rating',
'q3': 'Q3 rating',
'Q1': 'Q1 rating',
'Q2': 'Q2 rating',
'Q3': 'Q3 rating',
'trigger_mean': 'Mean unsafety',
'avg_trigger': 'Mean unsafety',
'mean_trigger': 'Mean unsafety',
'frac_time_unsafe': 'Fraction of trial time in unsafe zone',
'unsafe_time_frac': 'Fraction of trial time in unsafe zone',
'frac_unsafe': 'Fraction of trial time in unsafe zone',
'dtrigger_sd': 'Unsafety volatility',
'trigger_sd': 'Unsafety volatility',
'volatility': 'Unsafety volatility',
'n_transitions': 'Number of unsafety transitions',
'transitions': 'Number of unsafety transitions',
'num_transitions': 'Number of unsafety transitions',
'latency_first_press_s': 'Latency to first button press (s)',
'latency_first_release_s': 'Latency to first button release (s)',
'press_release_hysteresis_s': 'Interval from first press to first release (s)',
'yielding': 'Yielding',
'eHMIOn': 'eHMI on',
'prev_yielding': 'Previous trial yielding',
'prev_eHMIOn': 'Previous trial eHMI on',
'prev_camera': 'Previous trial camera condition',
'prev_distPed': 'Previous trial pedestrian distance',
'distPed': 'Pedestrian distance',
'camera': 'Camera condition',
'yaw_abs_mean': 'Mean absolute head yaw (deg)',
'yaw_forward_frac_15': 'Fraction of time looking forwards',
'yaw_sd': 'Standard deviation of head yaw (deg)',
'yaw_entropy': 'Head yaw entropy',
'yaw_speed_mean': 'Mean head yaw speed (deg/s)',
'head_turn_count_15': 'Number of head turns',
'head_turn_dwell_mean_s_15': 'Mean head turn dwell time (s)',
'yaw_speed_pre_press_mean_1s': 'Mean head yaw speed before button press (deg/s)',
'lag_turn_to_press_s_15': 'Lag from head turn to button press (s)',
'n_trials_main': 'Number of main trials',
'completion_frac': 'Completion fraction',
}
if s in direct:
return direct[s]
# compound metric names
prefixes = [
('carryover_prev_yielding_', 'Carryover effect of previous yielding on {}'),
('carryover_prev_eHMIOn_', 'Carryover effect of previous eHMI on on {}'),
('carryover_prev_camera_', 'Carryover effect of previous camera condition on {}'),
('carryover_prev_distPed_', 'Carryover effect of previous pedestrian distance on {}'),
('drift_late_minus_early_', 'Late minus early change in {}'),
('slope_', 'Linear slope of {} over trial position'),
('post_break_reset_', 'Post break reset in {}'),
('break_reset_matched_', 'Break matched change in {}'),
('switch_cost_', 'Switch cost in {}'),
('missing_frac_', 'Missing fraction for {}'),
('baseline_mean_', 'Baseline mean of {}'),
('curve_time_on_task_', '{} over trial position'),
]
for prefix, template in prefixes:
if s.startswith(prefix):
rest = s[len(prefix):]
return template.format(_humanise_label(rest).lower())
# general clean-up
pretty = s.replace('_', ' ')
pretty = re.sub(r'\bnormalized\b', 'normalised', pretty, flags=re.IGNORECASE)
pretty = re.sub(r'\bunshuffled\b', 'Fixed order', pretty, flags=re.IGNORECASE)
pretty = re.sub(r'\bshuffled\b', 'Randomised', pretty, flags=re.IGNORECASE)
pretty = re.sub(r'\s+', ' ', pretty).strip()
if pretty.islower():
pretty = pretty.capitalize()
return pretty
def _sanitise_axis_like(obj: Any) -> None:
try:
title = getattr(obj, 'title', None)
if title is not None:
text = getattr(title, 'text', None)
if isinstance(text, str) and text:
title.text = _humanise_label(text)
except Exception:
pass
try:
ticktext = getattr(obj, 'ticktext', None)
if ticktext:
obj.ticktext = tuple(_humanise_label(x) for x in ticktext)
except Exception:
pass
def _dataset_colour_from_any_label(label: Any) -> Optional[str]:
if label is None:
return None
s = str(label).strip()
if s in DATASET_COLOUR_MAP:
return DATASET_COLOUR_MAP[s]
key = s.lower().replace("_", " ")
if key in {"shuffled", "randomised", "randomized"}:
return DATASET_COLOUR_MAP["shuffled"]
if key in {"unshuffled", "fixed order", "fixed-order"}:
return DATASET_COLOUR_MAP["unshuffled"]
return None
def _split_single_dataset_violin(fig: Any) -> None:
"""Turn a single dataset violin/box trace into one trace per dataset so colours can differ."""
try:
if len(fig.data) != 1:
return
tr = fig.data[0]
if getattr(tr, "type", None) not in {"violin", "box"}:
return
x = list(getattr(tr, "x", []) or [])
y = list(getattr(tr, "y", []) or [])
if not x or len(x) != len(y):
return
x_norm = [_normalise_dataset_token(v) for v in x]
wanted = ["Randomised", "Fixed order"]
if not any(v in wanted for v in x_norm):
return
new_traces = []
for ds in wanted:
idx = [i for i, v in enumerate(x_norm) if v == ds]
if not idx:
continue
xs = [ds] * len(idx)
ys = [y[i] for i in idx]
colour = DATASET_COLOUR_MAP.get(ds)
common = dict(
x=xs,
y=ys,
name=ds,
legendgroup=ds,
box_visible=bool(getattr(tr, "box", None) and getattr(tr.box, "visible", False)) or True,
meanline_visible=bool(getattr(tr, "meanline", None) and getattr(tr.meanline, "visible", False)),
points=getattr(tr, "points", "outliers"),
jitter=getattr(tr, "jitter", None),
pointpos=getattr(tr, "pointpos", None),
opacity=getattr(tr, "opacity", None) or 0.75,
showlegend=True,
)
if getattr(tr, "type", None) == "violin":
nt = go.Violin(**common)
nt.fillcolor = _rgba_from_hex(colour, 0.35) # type: ignore[arg-type]
else:
nt = go.Box(**common)
nt.line = dict(color=colour)
nt.marker = dict(color=colour)
new_traces.append(nt)
if new_traces:
fig.data = tuple(new_traces)
except Exception:
return
def _sanitise_figure_for_export(fig: Any) -> Any:
if fig is None:
return fig
try:
_split_single_dataset_violin(fig)
except Exception:
pass
try:
for tr in fig.data:
try:
if hasattr(tr, "name") and isinstance(tr.name, str):
tr.name = _humanise_label(tr.name)
if hasattr(tr, "legendgroup") and isinstance(tr.legendgroup, str):
tr.legendgroup = _humanise_label(tr.legendgroup)
ds_colour = None
for cand in [getattr(tr, "name", None), getattr(tr, "legendgroup", None)]:
ds_colour = _dataset_colour_from_any_label(cand)
if ds_colour is not None:
break
if ds_colour is not None:
if hasattr(tr, "line") and tr.line is not None:
tr.line.color = ds_colour
if hasattr(tr, "marker") and tr.marker is not None:
tr.marker.color = ds_colour
try:
if getattr(tr.marker, "line", None) is not None and getattr(tr.marker.line, "color", None) is None: # noqa:E501
tr.marker.line.color = ds_colour
except Exception:
pass
if hasattr(tr, "fillcolor"):
# Lighter fill for violins and filled areas