-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAllFigScript.m
More file actions
3258 lines (2719 loc) · 178 KB
/
AllFigScript.m
File metadata and controls
3258 lines (2719 loc) · 178 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
% UNIFIED MATLAB SCRIPT FOR MANUSCRIPT FIGURES 3, 4, & 5
%
% Date: Dec 9, 2025
% Author: Noah Muscat
%
% Description:
% This master script combines the logic from three separate scripts to
% generate all components for Figures 3, 4, and 5. It centralizes the
% configuration, loads and processes the data only once, and then
% generates each figure in a clearly defined section. All figures are
% saved as PNG files.
%
% Script Sections:
% 1. Configuration & Setup
% 2. Load and Preprocess Data
% 3. Generate Figure 3 Components
% 4. Generate Figure 4 Components
% 5. Generate Figure 5 Components
% 6. Helper Functions
%
% ASSUMPTIONS: violinplot.m is on the MATLAB path.
% ---------------------------------------------------------------------
%% --- 1. Configuration & Setup ---
clear; clc; close all; % Start fresh
% --- File and Path Parameters ---
filename = '/Users/noahmuscat/University of Michigan Dropbox/Noah Muscat/ActivityAnalysis/ActigraphyOnly/Unified_AO1to12_Combined_Data.csv';
savePath_Fig3 = '/Users/noahmuscat/Desktop/WatsonLab/AOPaper/Figure3Plots';
savePath_Fig4 = '/Users/noahmuscat/Desktop/WatsonLab/AOPaper/Figure4Plots';
savePath_Fig5 = '/Users/noahmuscat/Desktop/WatsonLab/AOPaper/Figure5Plots';
% --- Master list of Activity Metrics to Plot ---
activity_metrics_to_plot = {'SelectedPixelDifference', 'NormalizedActivity'};
metric_suffixes = {'PixelDiff', 'Normalized'};
metric_ylabels = {'Activity (Pixel Difference)', 'Normalized Activity'};
pixelDiffVar = 'SelectedPixelDifference';
normalizedActivityVar = 'NormalizedActivity';
% --- Key Data Column Names ---
animalVar = 'Animal';
conditionVar = 'Condition';
relativeDayVar = 'RelativeDay';
timeVarZT = 'DateZT';
ztHourVar = 'ZT_Time';
% --- Analysis Parameters ---
samplingIntervalMinutes = 5;
hoursPerDay = 24;
daysForPoolingFig3AB = 14;
targetConditionFig3AB = '300Lux';
ztLightsOnStart = 0; ztLightsOnEnd = 11;
ztLightsOffStart = 12; ztLightsOffEnd = 23;
% --- Condition Ordering ---
allConditions = {'300Lux', '1000Lux', 'FullDark', '300LuxEnd'};
% --- Animal Grouping ---
allAnimals = string({'AO1', 'AO2', 'AO3', 'AO4', 'AO5', 'AO6', 'AO7', 'AO8', 'AO9', 'AO10', 'AO11', 'AO12'});
maleAnimals = string({'AO1', 'AO2', 'AO3', 'AO7', 'AO9', 'AO12'});
femaleAnimals = string({'AO4', 'AO5', 'AO6', 'AO8', 'AO10', 'AO11'});
fourCondAnimals = string({'AO5', 'AO6', 'AO7', 'AO8', 'AO9','AO10','AO11','AO12'});
% --- Color Definitions ---
maleColor = [0.2 0.5470 0.8410];
femaleColor = [0.9500 0.4250 0.1980];
grayColor = [0.6 0.6 0.6];
% --- Setup Save Directories ---
all_paths = {savePath_Fig3, savePath_Fig4, savePath_Fig5};
for p_idx = 1:length(all_paths)
current_path = all_paths{p_idx};
disp(['Checking save directory: ', current_path]);
if ~isfolder(current_path)
try mkdir(current_path); disp('Save directory created.');
catch ME, error('SaveDirErr:CouldNotCreate', 'Could not create save directory "%s". Err: %s', current_path, ME.message); end
end
end
%% --- 2. Load and Preprocess Data ---
disp(['Loading data from: ', filename]);
try
opts = detectImportOptions(filename);
opts.VariableNamingRule = 'preserve';
expectedVars = {pixelDiffVar, normalizedActivityVar, animalVar, conditionVar, relativeDayVar, timeVarZT, ztHourVar};
if ~all(ismember(expectedVars, opts.VariableNames)), error('LoadErr:MissingColumn', 'One or more expected columns not found in %s.', filename); end
opts = setvartype(opts, {pixelDiffVar, normalizedActivityVar, relativeDayVar, ztHourVar}, 'double');
opts = setvartype(opts, {animalVar, conditionVar}, 'string');
opts = setvartype(opts, timeVarZT, 'datetime');
opts = setvaropts(opts, timeVarZT, 'InputFormat', 'dd-MMM-yyyy HH:mm:ss');
dataTable = readtable(filename, opts);
disp('Data loaded successfully.');
catch ME_load, error('LoadErr:FileProcessing', 'Failed to load/parse CSV "%s". Err: %s', filename, ME_load.message); end
disp('Starting data preprocessing...');
dataTable = sortrows(dataTable, timeVarZT);
dataTable.DayOfCondition = floor(dataTable.(relativeDayVar));
colsToClean = {pixelDiffVar, normalizedActivityVar, timeVarZT, relativeDayVar, ztHourVar, animalVar, conditionVar, 'DayOfCondition'};
nanRowsFilter = false(height(dataTable), 1);
for c_idx = 1:length(colsToClean)
colData = dataTable.(colsToClean{c_idx});
if isdatetime(colData), nanRowsFilter = nanRowsFilter | isnat(colData);
elseif isnumeric(colData), nanRowsFilter = nanRowsFilter | isnan(colData);
elseif isstring(colData), nanRowsFilter = nanRowsFilter | ismissing(colData);
end
end
if any(nanRowsFilter), fprintf('%d rows removed due to missing values.\n', sum(nanRowsFilter)); dataTable(nanRowsFilter, :) = []; end
if isempty(dataTable), error('PreprocErr:NoData', 'No valid data after NaN removal.'); end
dataTable = dataTable(ismember(dataTable.(animalVar), allAnimals), :);
if isempty(dataTable), error('PreprocErr:NoAnimalData', 'No data found for the animals specified in `allAnimals`.'); end
dataTable.Condition = categorical(dataTable.Condition, allConditions, 'Ordinal', true);
dataTable.Sex = categorical(ismember(dataTable.(animalVar), maleAnimals), [0, 1], {'Female', 'Male'});
dataTable.LightPeriod = categorical((dataTable.(ztHourVar) >= ztLightsOnStart & dataTable.(ztHourVar) <= ztLightsOnEnd), [0, 1], {'Off', 'On'});
disp('Data preprocessing complete.');
%% --- 3. GENERATE FIGURE 3 COMPONENTS ---
disp('=====================================================');
disp('--- Starting Generation of Figure 3 Components ---');
disp('=====================================================');
initialBaselineData = [];
for i_an = 1:length(allAnimals)
currentAnimalID = allAnimals(i_an);
animalData = dataTable(dataTable.(animalVar) == currentAnimalID, :);
animalConds = unique(animalData.Condition, 'stable');
if ~isempty(animalConds) && animalConds(1) == string(targetConditionFig3AB)
animalTargetCondData = animalData(animalData.Condition == string(targetConditionFig3AB), :);
if ~isempty(animalTargetCondData)
uniqueDays = unique(animalTargetCondData.DayOfCondition);
if isempty(uniqueDays), continue; end
daysToKeep = uniqueDays(max(1, end-daysForPoolingFig3AB+1):end);
finalDataForPooling = animalTargetCondData(ismember(animalTargetCondData.DayOfCondition, daysToKeep), :);
initialBaselineData = [initialBaselineData; finalDataForPooling];
end
end
end
if isempty(initialBaselineData), error('DataErr:Fig3_NoBaseline', 'No baseline data found for Figure 3.'); end
for met_idx = 1:length(activity_metrics_to_plot)
current_metric_var = activity_metrics_to_plot{met_idx};
current_metric_suffix = metric_suffixes{met_idx};
current_metric_ylabel = metric_ylabels{met_idx};
fprintf('\n--- Generating Figure 3 components for metric: %s ---\n', current_metric_var);
%% FIG 3A: Averaged Actogram
disp('--- Starting Figure 3A: Averaged Actogram ---');
try
alignedAnimalData = NaN(daysForPoolingFig3AB, hoursPerDay, length(allAnimals));
for i_an = 1:length(allAnimals)
currentAnimalID = allAnimals(i_an);
animalData = dataTable(dataTable.(animalVar) == currentAnimalID & dataTable.Condition == string(targetConditionFig3AB), :);
if isempty(animalData), continue; end
uniqueDays = unique(animalData.DayOfCondition);
daysToKeep = uniqueDays(max(1, end-daysForPoolingFig3AB+1):end);
for i_day_idx = 1:min(length(daysToKeep), daysForPoolingFig3AB)
dayData = animalData(animalData.DayOfCondition == daysToKeep(i_day_idx), :);
if ~isempty(dayData)
hourlyMeans = groupsummary(dayData, ztHourVar, 'mean', current_metric_var);
[lia, locb] = ismember(hourlyMeans.(ztHourVar), (0:23)');
alignedAnimalData(i_day_idx, locb(lia), i_an) = hourlyMeans.(['mean_', current_metric_var])(lia);
end
end
end
actogramMatrix = mean(alignedAnimalData, 3, 'omitnan');
hFig3A_current = figure('Name', sprintf('Fig 3A: Averaged Actogram (%s)', current_metric_suffix), 'Visible', 'off', 'Color', 'w');
ax3A = axes('Parent', hFig3A_current);
imagesc(ax3A, (0:23), (1:daysForPoolingFig3AB), actogramMatrix); colormap(ax3A, 'parula'); ax3A.YDir = 'reverse';
xlabel(ax3A, 'ZT Hour'); ylabel(ax3A, sprintf('Day of %s (Aligned)', targetConditionFig3AB));
ylim(ax3A,[0.5, daysForPoolingFig3AB + 0.5]); xticks(ax3A, [0,6,12,18,23]); yticks(ax3A, 2:2:daysForPoolingFig3AB);
title(ax3A,sprintf('Averaged Actogram (%s)\nLast %d days of %s',strrep(current_metric_suffix,'_',' '),daysForPoolingFig3AB,targetConditionFig3AB));
cb3A = colorbar(ax3A); ylabel(cb3A, current_metric_ylabel);
hold(ax3A,'on'); patch(ax3A,[ztLightsOffStart-0.5, ztLightsOffEnd+0.5, ztLightsOffEnd+0.5, ztLightsOffStart-0.5],[0.5,0.5,daysForPoolingFig3AB+0.5,daysForPoolingFig3AB+0.5],[0.85 0.85 0.85],'FaceAlpha',0.25,'EdgeColor','none','HandleVisibility','off'); hold(ax3A,'off');
set(ax3A,'Layer','top', 'Position', [0.13 0.11 0.7 0.815]); % Add margins for whitespace
fig_filename = fullfile(savePath_Fig3, sprintf('Figure3A_Actogram_Averaged_%s.png', current_metric_suffix));
exportgraphics(hFig3A_current, fig_filename); disp(['Saved: ', fig_filename]); close(hFig3A_current);
catch ME_3A, warning('ErrGen:Fig3A','Error Fig 3A (%s): %s', current_metric_suffix, ME_3A.message); end
%% FIG 3B: Pooled Periodogram
disp('--- Starting Figure 3B: Pooled Periodogram ---');
try
hFig3B_current = figure('Name', sprintf('Fig 3B: Periodogram (%s)', current_metric_suffix), 'Visible', 'off', 'Color', 'w');
ax3B = axes('Parent', hFig3B_current);
tempDataForPerio = initialBaselineData;
tempDataForPerio.RoundedTime5Min = dateshift(tempDataForPerio.(timeVarZT),'start','minute',samplingIntervalMinutes);
pooled5MinStats = groupsummary(tempDataForPerio,'RoundedTime5Min','mean',current_metric_var);
activitySignal = pooled5MinStats.(['mean_',current_metric_var]);
timeSignalHours = hours(pooled5MinStats.RoundedTime5Min - pooled5MinStats.RoundedTime5Min(1));
validIdx = ~isnan(activitySignal); activitySignal = activitySignal(validIdx); timeSignalHours = timeSignalHours(validIdx);
periodogramRangeHours = [0.5, 48];
[pxx, f_hz] = plomb(activitySignal, timeSignalHours, 1/periodogramRangeHours(1), 4);
periodHours = 1 ./ f_hz;
validDataIdx = isfinite(periodHours) & isfinite(pxx);
periodHours = periodHours(validDataIdx); pxx = pxx(validDataIdx);
displayRangeIdx = periodHours >= periodogramRangeHours(1) & periodHours <= periodogramRangeHours(2);
[periodHours, sortIdx] = sort(periodHours(displayRangeIdx)); pxx = pxx(displayRangeIdx); pxx = pxx(sortIdx);
plot(ax3B,periodHours,pxx,'LineWidth',1.5,'Color','k');
xlabel(ax3B,'Period (hours)'); ylabel(ax3B,'Power');
title(ax3B,sprintf('Periodogram (%s)\nLast %dd %s',current_metric_suffix,daysForPoolingFig3AB,targetConditionFig3AB));
grid(ax3B,'on'); xlim(ax3B,periodogramRangeHours);
set(ax3B, 'Position', [0.13 0.11 0.775 0.75]); % Add margins for whitespace
fig_filename = fullfile(savePath_Fig3, sprintf('Figure3B_Periodogram_Last14d_%s.png', current_metric_suffix));
exportgraphics(hFig3B_current, fig_filename); disp(['Saved: ', fig_filename]); close(hFig3B_current);
catch ME_3B, warning('ErrGen:Fig3B','Error Fig 3B (%s): %s',current_metric_suffix, ME_3B.message); end
%% FIG 3C: Pooled 24-Hour Activity Profile (WITH HOURLY STATS)
disp('--- Starting Figure 3C: Pooled 24-Hour Profile ---');
try
hFig3C_current = figure('Name', sprintf('Fig 3C: 24h Profile (%s)', current_metric_suffix), 'Visible', 'off', 'Color', 'w');
ax3C = axes('Parent', hFig3C_current);
% Calculate Plotting Data (Mean +/- SEM)
hourlyStats_3C = groupsummary(initialBaselineData, ztHourVar, {'mean','std','nnz'}, current_metric_var);
hourlyStats_3C = sortrows(hourlyStats_3C, ztHourVar);
meanAct_3C = hourlyStats_3C.(['mean_',current_metric_var]);
semAct_3C = hourlyStats_3C.(['std_',current_metric_var]) ./ sqrt(hourlyStats_3C.(['nnz_',current_metric_var]));
% Plot the Profile
errorbar(ax3C, hourlyStats_3C.(ztHourVar), meanAct_3C, semAct_3C, 'o-', 'LineWidth', 1.5, 'MarkerSize', 4, 'CapSize', 3, 'Color', [0.2 0.2 0.2]);
hold(ax3C,'on');
% Stats: Hour X vs. Average of Other 23 Hours
disp('--- STATS: Fig 3C (Hour vs Daily Average) ---');
unique_animals = unique(initialBaselineData.Animal);
p_values_3C = ones(24, 1);
% Calculate animal-level means for the t-test to avoid pseudoreplication
% Create a matrix: Rows = Animals, Cols = Hours (0-23)
animal_hourly_matrix = NaN(length(unique_animals), 24);
for i = 1:length(unique_animals)
an_data = initialBaselineData(initialBaselineData.Animal == unique_animals(i), :);
an_hourly = groupsummary(an_data, ztHourVar, 'mean', current_metric_var);
% Map to 0-23 index
[found, idx] = ismember((0:23)', an_hourly.(ztHourVar));
animal_hourly_matrix(i, found) = an_hourly.(['mean_', current_metric_var])(idx(found));
end
% No bonferroni
alpha_3C = 0.05;
for h = 1:24 % Loop 1 to 24 (corresponding to ZT 0 to 23)
col_target = animal_hourly_matrix(:, h);
col_others = animal_hourly_matrix;
col_others(:, h) = []; % Remove target column
mean_others = mean(col_others, 2, 'omitnan'); % Average of the other 23 hours per animal
% Paired t-test: Is this hour significantly different from the animal's background average?
if all(~isnan(col_target) & ~isnan(mean_others))
[~, p] = ttest(col_target, mean_others);
p_values_3C(h) = p;
end
end
% 4. Plot Asterisks
% Find significant indices
sig_idx = find(p_values_3C < alpha_3C);
if ~isempty(sig_idx)
% Determine Y-position for asterisks (slightly above the error bar)
y_points = meanAct_3C(sig_idx) + semAct_3C(sig_idx);
% Add a buffer so it doesn't touch the bar (5% of range)
y_range = max(meanAct_3C) - min(meanAct_3C);
y_asterisks = y_points + (y_range * 0.05);
plot(ax3C, sig_idx-1, y_asterisks, '*', 'Color', 'k', 'MarkerSize', 6);
fprintf('Significant Hours (p < %.4f): ZT %s\n', alpha_3C, num2str(sig_idx' - 1));
end
% 5. Standard Formatting
yl3C=ylim(ax3C);
% Adjust Y-lim if asterisks are cut off
if ~isempty(sig_idx)
ylim(ax3C, [yl3C(1), max(yl3C(2), max(y_asterisks) + y_range*0.05)]);
yl3C=ylim(ax3C);
end
patch(ax3C,[ztLightsOffStart, ztLightsOffEnd+1, ztLightsOffEnd+1, ztLightsOffStart], [yl3C(1) yl3C(1) yl3C(2) yl3C(2)], [0.85 0.85 0.85],'FaceAlpha',0.25,'EdgeColor','none');
if strcmp(current_metric_var, normalizedActivityVar), plot(ax3C,xlim(ax3C),[0 0],'k--'); end
hold(ax3C,'off');
xlabel(ax3C,'ZT Hour'); ylabel(ax3C,['Mean ',current_metric_ylabel]);
title(ax3C,sprintf('Pooled 24h Activity Profile (%s - Baseline)',current_metric_suffix));
xticks(ax3C,0:3:23); xlim(ax3C,[-0.5,23.5]); grid(ax3C,'on');
set(ax3C, 'Position', [0.13 0.11 0.775 0.815]);
fig_filename = fullfile(savePath_Fig3, sprintf('Figure3C_Profile_Baseline_%s.png', current_metric_suffix));
exportgraphics(hFig3C_current, fig_filename); disp(['Saved: ', fig_filename]); close(hFig3C_current);
catch ME_3C, warning('ErrGen:Fig3C','Error Fig 3C (%s): %s',current_metric_suffix, ME_3C.message); end
%% FIG 3D: Diurnality Quantification (Violin Plots) (WITH STATS)
disp('--- Starting Figure 3D: Diurnality Violins ---');
fprintf('\n--- STATS: Figure 3D (Last 14 days) for %s ---\n', current_metric_suffix);
try
if ~exist('violinplot.m','file'),error('ViolinPlotNotFound:Fig3D','violinplot.m not found.');end
hFig3D_current = figure('Name', sprintf('Fig 3D: Diurnality Violins (%s)', current_metric_suffix), 'Visible', 'off', 'Color', 'w');
ax3D = axes('Parent', hFig3D_current); hold(ax3D, 'on');
time_windows = {[0 23], [0 11], [3 9], [12 23], [15 21], [10 14], [22 2]};
window_labels = {'Full Day', 'Bright (0-11)', 'Mid-Bright (3-9)', 'Dark (12-23)', 'Mid-Dark (15-21)', 'Bright-Dark (10-14)', 'Dark-Bright (22-2)'};
animal_window_means_list = [];
baselineAnimals = unique(initialBaselineData.Animal);
for i_an = 1:length(baselineAnimals)
T_animal = initialBaselineData(initialBaselineData.Animal == baselineAnimals(i_an), :);
if isempty(T_animal), continue; end
for i_win = 1:length(time_windows)
window = time_windows{i_win};
if window(1) <= window(2), idx_time = T_animal.(ztHourVar) >= window(1) & T_animal.(ztHourVar) <= window(2);
else, idx_time = T_animal.(ztHourVar) >= window(1) | T_animal.(ztHourVar) <= window(2); end
mean_act_this_win = mean(T_animal.(current_metric_var)(idx_time), 'omitnan');
animal_window_means_list = [animal_window_means_list; {baselineAnimals(i_an), window_labels{i_win}, T_animal.Sex(1), mean_act_this_win}];
end
end
plotTable_3D = cell2table(animal_window_means_list, 'VariableNames', {'Animal', 'Window', 'Sex', 'MeanActivity'});
plotTable_3D.Window = categorical(plotTable_3D.Window, window_labels);
violinplot(plotTable_3D.MeanActivity, plotTable_3D.Window, 'Parent', ax3D, 'GroupOrder', window_labels, 'ShowData', false, 'ViolinColor', grayColor);
jitterAmount = 0.15;
for i_win = 1:length(window_labels)
window_data = plotTable_3D(plotTable_3D.Window == window_labels{i_win}, :);
x_scatter = i_win + (rand(height(window_data), 1) - 0.5) * jitterAmount;
male_idx = window_data.Sex == 'Male';
scatter(ax3D, x_scatter(male_idx), window_data.MeanActivity(male_idx), 40, maleColor, 'filled', 'MarkerFaceAlpha', 0.9);
scatter(ax3D, x_scatter(~male_idx), window_data.MeanActivity(~male_idx), 40, femaleColor, 'filled', 'MarkerFaceAlpha', 0.9);
end
num_tests = 3;
corrected_alpha = 0.05; % not using Bonferroni
fprintf('Using standard alpha (0.05)');
y_max = max(plotTable_3D.MeanActivity, [], 'omitnan'); if isempty(y_max) || isnan(y_max), y_max=1; end
current_ylim = ylim(ax3D);
y_range = diff(current_ylim); if y_range==0 || isnan(y_range), y_range=y_max; end
bright_data = plotTable_3D(plotTable_3D.Window == 'Bright (0-11)', :);
dark_data = plotTable_3D(plotTable_3D.Window == 'Dark (12-23)', :);
stats_table = outerjoin(bright_data(:,{'Animal', 'MeanActivity'}), dark_data(:,{'Animal', 'MeanActivity'}), 'Keys','Animal', 'MergeKeys', true);
stats_table.Properties.VariableNames(2:3) = {'Bright', 'Dark'};
[~, p_bvd] = ttest(stats_table.Bright, stats_table.Dark);
fprintf('Paired T-Test (Bright vs Dark): p = %.4f\n', p_bvd);
y_pos1 = current_ylim(2) + 0.05*y_range;
plot_sig_bar(ax3D, [2, 4], p_bvd, y_pos1, corrected_alpha);
midbright_data = plotTable_3D(plotTable_3D.Window == 'Mid-Bright (3-9)', :);
middark_data = plotTable_3D(plotTable_3D.Window == 'Mid-Dark (15-21)', :);
stats_table_mid = outerjoin(midbright_data(:,{'Animal', 'MeanActivity'}), middark_data(:,{'Animal', 'MeanActivity'}), 'Keys','Animal', 'MergeKeys', true);
stats_table_mid.Properties.VariableNames(2:3) = {'MidBright', 'MidDark'};
[~, p_mbvmd] = ttest(stats_table_mid.MidBright, stats_table_mid.MidDark);
fprintf('Paired T-Test (Mid-Bright vs Mid-Dark): p = %.4f\n', p_mbvmd);
y_pos2 = y_pos1 + 0.15*y_range;
plot_sig_bar(ax3D, [3, 5], p_mbvmd, y_pos2, corrected_alpha);
transition_data = plotTable_3D(plotTable_3D.Window == 'Bright-Dark (10-14)', :);
fullday_data = plotTable_3D(plotTable_3D.Window == 'Full Day', :);
stats_table_trans = outerjoin(transition_data(:,{'Animal', 'MeanActivity'}), fullday_data(:,{'Animal', 'MeanActivity'}), 'Keys','Animal', 'MergeKeys', true);
stats_table_trans.Properties.VariableNames(2:3) = {'Transition', 'FullDay'};
[~, p_tvfd] = ttest(stats_table_trans.Transition, stats_table_trans.FullDay);
fprintf('Paired T-Test (Transition vs Full Day): p = %.4f\n', p_tvfd);
y_pos3 = y_pos2 + 0.15*y_range;
plot_sig_bar(ax3D, [1, 6], p_tvfd, y_pos3, corrected_alpha);
ylim(ax3D, [current_ylim(1), y_pos3 + 0.1*y_range]);
xticklabels(ax3D, window_labels); xtickangle(ax3D, 45);
ylabel(ax3D,['Mean ',current_metric_ylabel]);
title(ax3D,sprintf('Diurnality (Last 14d Baseline - 300Lux)\n%s', strrep(current_metric_suffix,'_',' ')));
if strcmp(current_metric_var, normalizedActivityVar), line(ax3D, xlim(ax3D), [0 0], 'Color', 'k', 'LineStyle', ':'); end
set(ax3D, 'Position', [0.13 0.2 0.775 0.7]);
drawnow;
fig_filename = fullfile(savePath_Fig3, sprintf('Figure3D_Violins_PooledSex_CorrectedStats_%s.png', current_metric_suffix));
exportgraphics(hFig3D_current, fig_filename); disp(['Saved: ', fig_filename]); close(hFig3D_current);
catch ME_3D, warning('ErrGen:Fig3D','Error Fig 3D (%s): %s', current_metric_suffix, ME_3D.message); end
%% FIG 3D (Extended): Weekly Breakdown
disp('--- Starting Figure 3D Weekly Breakdown ---');
baselineDataOnly = dataTable(dataTable.Condition == targetConditionFig3AB, :);
max_day = max(baselineDataOnly.DayOfCondition);
num_weeks = floor((max_day+1)/7);
for i_week = 1:num_weeks
start_day = (i_week-1) * 7;
end_day = i_week * 7 - 1;
weekly_data = baselineDataOnly(baselineDataOnly.DayOfCondition >= start_day & baselineDataOnly.DayOfCondition <= end_day, :);
if isempty(weekly_data)
fprintf('Skipping Week %d: No data available.\n', i_week);
continue;
end
fprintf('\n--- Generating Weekly Figure 3D for Week %d (Days %d-%d) ---\n', i_week, start_day, end_day);
try
if ~exist('violinplot.m','file'),error('ViolinPlotNotFound:Fig3D_Weekly','violinplot.m not found.');end
hFig3D_weekly = figure('Name', sprintf('Fig 3D Weekly W%d (%s)', i_week, current_metric_suffix), 'Visible', 'off', 'Color', 'w');
ax3D_w = axes('Parent', hFig3D_weekly); hold(ax3D_w, 'on');
time_windows = {[0 23], [0 11], [3 9], [12 23], [15 21], [10 14], [22 2]};
window_labels = {'Full Day', 'Bright (0-11)', 'Mid-Bright (3-9)', 'Dark (12-23)', 'Mid-Dark (15-21)', 'Bright-Dark (10-14)', 'Dark-Bright (22-2)'};
animal_window_means_list_w = [];
weekAnimals = unique(weekly_data.Animal);
for i_an = 1:length(weekAnimals)
T_animal_w = weekly_data(weekly_data.Animal == weekAnimals(i_an), :);
if isempty(T_animal_w), continue; end
for i_win = 1:length(time_windows)
window = time_windows{i_win};
if window(1) <= window(2), idx_time = T_animal_w.(ztHourVar) >= window(1) & T_animal_w.(ztHourVar) <= window(2);
else, idx_time = T_animal_w.(ztHourVar) >= window(1) | T_animal_w.(ztHourVar) <= window(2); end
mean_act_this_win = mean(T_animal_w.(current_metric_var)(idx_time), 'omitnan');
animal_window_means_list_w = [animal_window_means_list_w; {weekAnimals(i_an), window_labels{i_win}, T_animal_w.Sex(1), mean_act_this_win}];
end
end
if isempty(animal_window_means_list_w), close(hFig3D_weekly); continue; end
plotTable_3D_w = cell2table(animal_window_means_list_w, 'VariableNames', {'Animal', 'Window', 'Sex', 'MeanActivity'});
plotTable_3D_w.Window = categorical(plotTable_3D_w.Window, window_labels);
violinplot(plotTable_3D_w.MeanActivity, plotTable_3D_w.Window, 'Parent', ax3D_w, 'GroupOrder', window_labels, 'ShowData', false, 'ViolinColor', grayColor);
jitterAmount = 0.15;
for i_win = 1:length(window_labels)
window_data = plotTable_3D_w(plotTable_3D_w.Window == window_labels{i_win}, :);
x_scatter = i_win + (rand(height(window_data), 1) - 0.5) * jitterAmount;
male_idx = window_data.Sex == 'Male';
scatter(ax3D_w, x_scatter(male_idx), window_data.MeanActivity(male_idx), 40, maleColor, 'filled', 'MarkerFaceAlpha', 0.9);
scatter(ax3D_w, x_scatter(~male_idx), window_data.MeanActivity(~male_idx), 40, femaleColor, 'filled', 'MarkerFaceAlpha', 0.9);
end
num_tests_weekly = 2;
corrected_alpha_weekly = 0.05; % no bonferroni
fprintf('--- STATS: Figure 3D WEEK %d for %s ---\n', i_week, current_metric_suffix);
y_max_w = max(plotTable_3D_w.MeanActivity, [], 'omitnan'); if isempty(y_max_w) || isnan(y_max_w), y_max_w=1; end
current_ylim_w = ylim(ax3D_w);
y_range_w = diff(current_ylim_w); if y_range_w==0 || isnan(y_range_w), y_range_w=y_max_w; end
bright_data_w = plotTable_3D_w(plotTable_3D_w.Window == 'Bright (0-11)', :);
dark_data_w = plotTable_3D_w(plotTable_3D_w.Window == 'Dark (12-23)', :);
stats_table_w1 = outerjoin(bright_data_w(:,{'Animal', 'MeanActivity'}), dark_data_w(:,{'Animal', 'MeanActivity'}), 'Keys','Animal', 'MergeKeys', true);
stats_table_w1.Properties.VariableNames(2:3) = {'Bright', 'Dark'};
[~, p_bvd_w] = ttest(stats_table_w1.Bright, stats_table_w1.Dark);
fprintf('Paired T-Test (Bright vs Dark): p = %.4f\n', p_bvd_w);
y_pos1_w = current_ylim_w(2) + 0.05 * y_range_w;
plot_sig_bar(ax3D_w, [2, 4], p_bvd_w, y_pos1_w, corrected_alpha_weekly);
midbright_data_w = plotTable_3D_w(plotTable_3D_w.Window == 'Mid-Bright (3-9)', :);
middark_data_w = plotTable_3D_w(plotTable_3D_w.Window == 'Mid-Dark (15-21)', :);
stats_table_w2 = outerjoin(midbright_data_w(:,{'Animal', 'MeanActivity'}), middark_data_w(:,{'Animal', 'MeanActivity'}), 'Keys','Animal', 'MergeKeys', true);
stats_table_w2.Properties.VariableNames(2:3) = {'MidBright', 'MidDark'};
[~, p_mbvmd_w] = ttest(stats_table_w2.MidBright, stats_table_w2.MidDark);
fprintf('Paired T-Test (Mid-Bright vs Mid-Dark): p = %.4f\n', p_mbvmd_w);
y_pos2_w = y_pos1_w + 0.15 * y_range_w;
plot_sig_bar(ax3D_w, [3, 5], p_mbvmd_w, y_pos2_w, corrected_alpha_weekly);
ylim(ax3D_w, [current_ylim_w(1), y_pos2_w + 0.1*y_range_w]);
xticklabels(ax3D_w, window_labels); xtickangle(ax3D_w, 45);
ylabel(ax3D_w,['Mean ',current_metric_ylabel]);
title(ax3D_w,sprintf('Baseline Diurnality (300Lux) - Week %d (Days %d-%d)\n%s',i_week, start_day, end_day, strrep(current_metric_suffix,'_',' ')));
if strcmp(current_metric_var, normalizedActivityVar), line(ax3D_w, xlim(ax3D_w), [0 0], 'Color', 'k', 'LineStyle', ':'); end
set(ax3D_w, 'Position', [0.13 0.2 0.775 0.7]);
drawnow;
fig_filename = fullfile(savePath_Fig3, sprintf('Figure3D_WeeklyBaseline_W%d_CorrectedStats_%s.png', i_week, current_metric_suffix));
exportgraphics(hFig3D_weekly, fig_filename); disp(['Saved: ', fig_filename]); close(hFig3D_weekly);
catch ME_3D_weekly, warning('ErrGen:Fig3D_Weekly','Error Fig 3D Weekly (W%d, %s): %s', i_week, current_metric_suffix, ME_3D_weekly.message); end
end
end
%% --- 4. GENERATE FIGURE 4 COMPONENTS ---
disp('=====================================================');
disp('--- Starting Generation of Figure 4 Components ---');
disp('=====================================================');
for met_idx = 1:length(activity_metrics_to_plot)
current_metric_var = activity_metrics_to_plot{met_idx};
current_metric_suffix = metric_suffixes{met_idx};
current_metric_ylabel = metric_ylabels{met_idx};
fprintf('\n--- Generating Figure 4 components for metric: %s ---\n', current_metric_var);
%% FIG 4A: 48h Diurnality Line Plots by Condition (with Day/Night avg lines)
disp('--- Starting Figure 4A: 48h Profiles ---');
try
lightingConditions_Fig4A = {'300Lux', '1000Lux', 'FullDark', '300LuxEnd'};
hFig4A_Subplots = figure('Name', sprintf('Fig 4A: 48h Profiles by Condition (%s)', current_metric_suffix), 'Visible', 'off', 'Color', 'w', 'Units', 'inches', 'Position', [1 1 7 9]);
% Create a tiled layout
t = tiledlayout(4, 1, 'TileSpacing', 'compact', 'Padding', 'compact');
global_min_y = Inf; global_max_y = -Inf;
all_profiles_4A = cell(length(lightingConditions_Fig4A), 1);
% New storage for day/night averages per condition
mean_levels_day = cell(length(lightingConditions_Fig4A), 1);
mean_levels_night = cell(length(lightingConditions_Fig4A), 1);
% --- Pre-computation Loop ---
for i_cond = 1:length(lightingConditions_Fig4A)
data_this_cond = dataTable(ismember(dataTable.Animal, fourCondAnimals) & dataTable.Condition == lightingConditions_Fig4A{i_cond}, :);
if isempty(data_this_cond), continue; end
% 1. Calculate Hourly Profile
hourly_mean = groupsummary(data_this_cond, ztHourVar, 'mean', current_metric_var);
mean_profile_24h = NaN(hoursPerDay, 1);
[lia, locb] = ismember((0:23)', hourly_mean.(ztHourVar));
mean_profile_24h(lia) = hourly_mean.(['mean_', current_metric_var])(locb(lia));
all_profiles_4A{i_cond} = mean_profile_24h;
% 2. Calculate Day (ZT 0-11) and Night (ZT 12-23) Grand Averages for this condition
day_idx = data_this_cond.(ztHourVar) >= 0 & data_this_cond.(ztHourVar) <= 11;
night_idx = data_this_cond.(ztHourVar) >= 12 & data_this_cond.(ztHourVar) <= 23;
mean_levels_day{i_cond} = mean(data_this_cond.(current_metric_var)(day_idx), 'omitnan');
mean_levels_night{i_cond} = mean(data_this_cond.(current_metric_var)(night_idx), 'omitnan');
% 3. Update global limits for common Y-axis
global_min_y = min(global_min_y, min(mean_profile_24h,[],'omitnan'));
global_max_y = max(global_max_y, max(mean_profile_24h,[],'omitnan'));
end
% --- Plotting Loop ---
for i_cond_4A = 1:length(lightingConditions_Fig4A)
ax4A = nexttile;
hold(ax4A, 'on');
% Plot the 48h Profile
mean_profile_48h = [all_profiles_4A{i_cond_4A}; all_profiles_4A{i_cond_4A}];
plot(ax4A, (0:47)', mean_profile_48h, 'k-', 'LineWidth', 1.5);
% Plot the Day/Night Average horizontal dashed lines
if isfinite(mean_levels_day{i_cond_4A})
yline(ax4A, mean_levels_day{i_cond_4A}, 'r--', 'LineWidth', 1, 'HandleVisibility', 'off');
end
if isfinite(mean_levels_night{i_cond_4A})
yline(ax4A, mean_levels_night{i_cond_4A}, 'r--', 'LineWidth', 1, 'HandleVisibility', 'off');
end
% Set a globally consistent Y-limit
if isfinite(global_min_y) && isfinite(global_max_y)
ylim(ax4A, [global_min_y - 0.1*abs(global_min_y), global_max_y + 0.1*abs(global_max_y)]);
end
% Add Shading and formatting
current_ylim = ylim(ax4A);
patch(ax4A, [ztLightsOffStart, ztLightsOffEnd+1, ztLightsOffEnd+1, ztLightsOffStart], [current_ylim(1) current_ylim(1) current_ylim(2) current_ylim(2)], [0.9 0.9 0.9], 'FaceAlpha', 0.3, 'EdgeColor', 'none');
patch(ax4A, [ztLightsOffStart+24, ztLightsOffEnd+1+24, ztLightsOffEnd+1+24, ztLightsOffStart+24], [current_ylim(1) current_ylim(1) current_ylim(2) current_ylim(2)], [0.9 0.9 0.9], 'FaceAlpha', 0.3, 'EdgeColor', 'none');
title(ax4A, lightingConditions_Fig4A{i_cond_4A});
xticks(ax4A, 0:6:47); xlim(ax4A, [-0.5 47.5]); grid(ax4A, 'on');
end
% Add shared labels and a main title using the tiled layout handle
xlabel(t, 'ZT Hour (Double Plotted)');
ylabel(t, current_metric_ylabel);
title(t, sprintf('48h Activity Profiles by Condition (%s)', current_metric_suffix));
fig_filename = fullfile(savePath_Fig4, sprintf('Figure4A_SubplotProfiles_SameY_%s.png', current_metric_suffix));
exportgraphics(hFig4A_Subplots, fig_filename); disp(['Saved: ', fig_filename]); close(hFig4A_Subplots);
catch ME_4A, warning('ErrGen:Fig4A','Error Fig 4A (%s): %s', current_metric_suffix, ME_4A.message); end
%% FIG 4B: Overlay Activity Profiles with Difference Line (N=12, SEM Shading)
disp('--- Starting Figure 4B: Overlay Profiles (SEM) ---');
try
hFig4B_OverlayDiff = figure('Name', sprintf('Fig 4B: Overlay Profiles & Difference (%s)', current_metric_suffix), 'Visible', 'off', 'Color', 'w');
ax4B = axes('Parent', hFig4B_OverlayDiff); hold(ax4B, 'on');
conditions_Fig4B = {'300Lux', '1000Lux', 'FullDark'};
lineColors = {[0 0.4470 0.7410], [0.8500 0.3250 0.0980], [0.4660 0.6740 0.1880]};
mean_profiles = table();
% 1. Calculate and Plot Lines
for i_cond = 1:length(conditions_Fig4B)
animals_for_cond = allAnimals;
if strcmp(conditions_Fig4B{i_cond},'FullDark'), animals_for_cond=fourCondAnimals; end
data_this_cond = dataTable(ismember(dataTable.Animal, animals_for_cond) & dataTable.Condition == conditions_Fig4B{i_cond}, :);
hourly_stats = groupsummary(data_this_cond, ztHourVar, {'mean','std','nnz'}, current_metric_var);
mean_prof = NaN(hoursPerDay,1); sem_prof = NaN(hoursPerDay,1);
[lia,locb] = ismember((0:23)', hourly_stats.(ztHourVar));
mean_prof(lia) = hourly_stats.(['mean_',current_metric_var])(locb(lia));
% SEM Calculation
sd_val = hourly_stats.(['std_',current_metric_var])(locb(lia));
n_val = hourly_stats.(['nnz_',current_metric_var])(locb(lia));
sem_val = sd_val ./ sqrt(n_val); sem_val(n_val <= 1) = NaN;
sem_prof(lia) = sem_val;
mean_profiles.(conditions_Fig4B{i_cond}) = mean_prof;
plot(ax4B, (0:23)', mean_prof, 'Color', lineColors{i_cond}, 'LineWidth', 2, 'DisplayName', conditions_Fig4B{i_cond});
fill(ax4B, [(0:23)'; flipud((0:23)')], [mean_prof-sem_prof; flipud(mean_prof+sem_prof)], ...
lineColors{i_cond}, 'FaceAlpha', 0.2, 'EdgeColor', 'none', 'HandleVisibility', 'off');
end
% 2. Plot Difference Line
diff_profile = mean_profiles.('1000Lux') - mean_profiles.('300Lux');
plot(ax4B, (0:23)', diff_profile, 'k:', 'LineWidth', 1.5, 'DisplayName', 'Diff (1000L-300L)');
% 3. STATS: Hourly T-Test (300 vs 1000) using ANIMAL MEANS (N=12)
p_values = ones(24, 1);
stats_animals = allAnimals;
fprintf('\n--- STATS: Figure 4B (300Lux vs 1000Lux) ---\n');
fprintf(' Calculating statistics on N=%d animals (Paired T-Test)...\n', length(stats_animals));
prof_300_N12 = NaN(length(stats_animals), 24);
prof_1000_N12 = NaN(length(stats_animals), 24);
for i = 1:length(stats_animals)
d3 = dataTable(dataTable.Animal == stats_animals(i) & dataTable.Condition == '300Lux', :);
if ~isempty(d3), h=groupsummary(d3,ztHourVar,'mean',current_metric_var); [~,l]=ismember(0:23,h.(ztHourVar)); prof_300_N12(i,l>0)=h.(['mean_',current_metric_var])(l(l>0)); end
d1 = dataTable(dataTable.Animal == stats_animals(i) & dataTable.Condition == '1000Lux', :);
if ~isempty(d1), h=groupsummary(d1,ztHourVar,'mean',current_metric_var); [~,l]=ismember(0:23,h.(ztHourVar)); prof_1000_N12(i,l>0)=h.(['mean_',current_metric_var])(l(l>0)); end
end
for zt = 1:24
v3=prof_300_N12(:,zt); v1=prof_1000_N12(:,zt); idx=~isnan(v3)&~isnan(v1);
if sum(idx)>=3, [~,p]=ttest(v3(idx),v1(idx)); p_values(zt)=p; end
end
% 4. PLOT ASTERISKS
alpha_4B = 0.05; sig_indices = find(p_values < alpha_4B);
current_ylim = ylim(ax4B);
if ~isempty(sig_indices)
sig_zt = sig_indices - 1;
fprintf(' Significant Differences (p<0.05) found at ZT: %s\n', num2str(sig_zt'));
y_asterisks = NaN(size(sig_zt));
for k = 1:length(sig_zt)
idx = sig_indices(k);
y_asterisks(k) = max(mean_profiles.('300Lux')(idx), mean_profiles.('1000Lux')(idx)) + (current_ylim(2)-current_ylim(1))*0.05;
end
plot(ax4B, sig_zt, y_asterisks, '*', 'Color', 'k', 'MarkerSize', 6, 'HandleVisibility', 'off');
if max(y_asterisks) > current_ylim(2), ylim(ax4B, [current_ylim(1), max(y_asterisks)*1.05]); end
else
fprintf(' No significant hourly differences found.\n');
end
% 5. SHADING (Last)
final_ylim = ylim(ax4B);
patch(ax4B, [ztLightsOffStart, ztLightsOffEnd+1, ztLightsOffEnd+1, ztLightsOffStart], ...
[final_ylim(1) final_ylim(1) final_ylim(2) final_ylim(2)], ...
[0.9 0.9 0.9],'FaceAlpha',0.2,'EdgeColor','none', 'HandleVisibility', 'off');
title(ax4B, sprintf('Fig 4B: Activity Profiles & Difference (%s)', current_metric_suffix));
xlabel(ax4B, 'ZT Hour'); ylabel(ax4B, current_metric_ylabel);
xticks(ax4B, 0:6:23); xlim(ax4B, [-0.5 23.5]); grid(ax4B, 'on'); legend(ax4B, 'Location', 'northeast');
set(ax4B, 'Position', [0.13 0.11 0.775 0.815]);
exportgraphics(hFig4B_OverlayDiff, fullfile(savePath_Fig4, sprintf('Figure4B_OverlayAndDiff_%s.png', current_metric_suffix))); close(hFig4B_OverlayDiff);
catch ME_4B, warning('ErrGen:Fig4B','Error Fig 4B (%s): %s', current_metric_suffix, ME_4B.message); end
%% FIG 4C: Quantification of Diurnality (Violins)
disp('--- Starting Figure 4C: Diurnality Violins ---');
try
if ~exist('violinplot.m','file'),error('ViolinPlotNotFound:Fig4C','violinplot.m not found.');end
hFig4C_violins = figure('Name', sprintf('Fig 4C: Diurnality Violins by Cond (%s)', current_metric_suffix), 'Visible', 'off', 'Color', 'w');
ax4C = axes('Parent', hFig4C_violins); hold(ax4C, 'on');
conditions_Fig4C = {'300Lux', '1000Lux', 'FullDark', '300LuxEnd'};
plotData = []; groupData = []; groupOrder = {};
% Data Containers for Cross-Condition Stats
data_300_ON = []; data_1000_ON = [];
data_300_OFF = []; data_1000_OFF = [];
for i_cond = 1:length(conditions_Fig4C)
for lp = ["On", "Off"]
groupName = [conditions_Fig4C{i_cond}, '-', char(lp)];
animals_for_cond = allAnimals; if ismember(conditions_Fig4C{i_cond},["FullDark","300LuxEnd"]), animals_for_cond=fourCondAnimals; end
data_segment = dataTable(ismember(dataTable.Animal, animals_for_cond) & dataTable.Condition == conditions_Fig4C{i_cond} & dataTable.LightPeriod == lp, :);
if isempty(data_segment), continue; end
animal_means = groupsummary(data_segment, animalVar, 'mean', current_metric_var);
% Store data for plotting
plotData = [plotData; animal_means.(['mean_',current_metric_var])];
groupData = [groupData; repmat(categorical({groupName}), height(animal_means),1)];
groupOrder{end+1} = groupName;
% Store data for Stats (Specific Comparisons)
if strcmp(conditions_Fig4C{i_cond}, '300Lux') && lp == "On", data_300_ON = animal_means; end
if strcmp(conditions_Fig4C{i_cond}, '1000Lux') && lp == "On", data_1000_ON = animal_means; end
if strcmp(conditions_Fig4C{i_cond}, '300Lux') && lp == "Off", data_300_OFF = animal_means; end
if strcmp(conditions_Fig4C{i_cond}, '1000Lux') && lp == "Off", data_1000_OFF = animal_means; end
end
end
violinplot(plotData, groupData, 'Parent', ax4C, 'GroupOrder', groupOrder, 'ViolinColor', grayColor, 'ShowData', false);
% Scatter overlay loop (Standard)
jitterAmount = 0.15;
for i_group = 1:length(groupOrder)
group_label = groupOrder{i_group};
parts = split(group_label, '-'); cond_str = string(parts{1}); lp_str = string(parts{2});
animals_for_cond = allAnimals; if ismember(cond_str, ["FullDark","300LuxEnd"]), animals_for_cond=fourCondAnimals; end
group_data = dataTable(ismember(dataTable.Animal, animals_for_cond) & dataTable.Condition == cond_str & dataTable.LightPeriod == lp_str, :);
animal_means_this_group = groupsummary(group_data, {'Animal', 'Sex'}, 'mean', current_metric_var);
if ~isempty(animal_means_this_group)
x_scatter = i_group + (rand(height(animal_means_this_group), 1) - 0.5) * jitterAmount;
male_idx = animal_means_this_group.Sex == 'Male';
scatter(ax4C, x_scatter(male_idx), animal_means_this_group.(['mean_',current_metric_var])(male_idx), 40, maleColor, 'filled', 'MarkerFaceAlpha', 0.8, 'HandleVisibility', 'off');
scatter(ax4C, x_scatter(~male_idx), animal_means_this_group.(['mean_',current_metric_var])(~male_idx), 40, femaleColor, 'filled', 'MarkerFaceAlpha', 0.8, 'HandleVisibility', 'off');
end
end
% --- Cross-Condition (300 vs 1000) ---
fprintf('\n--- STATS: Fig 4C Cross-Condition (Effect of Light Intensity) ---\n');
% Align 300 and 1000 data (N=12)
% Assuming animals are in same order or using join (safer)
t_300_ON = data_300_ON(:, {animalVar, ['mean_', current_metric_var]}); t_300_ON.Properties.VariableNames{2} = 'Val_300';
t_1000_ON = data_1000_ON(:, {animalVar, ['mean_', current_metric_var]}); t_1000_ON.Properties.VariableNames{2} = 'Val_1000';
joined_ON = innerjoin(t_300_ON, t_1000_ON);
[~, p_ON_cross] = ttest(joined_ON.Val_300, joined_ON.Val_1000);
fprintf('Paired T-Test | 300Lux ON vs 1000Lux ON: p = %.4f (N=%d)\n', p_ON_cross, height(joined_ON));
t_300_OFF = data_300_OFF(:, {animalVar, ['mean_', current_metric_var]}); t_300_OFF.Properties.VariableNames{2} = 'Val_300';
t_1000_OFF = data_1000_OFF(:, {animalVar, ['mean_', current_metric_var]}); t_1000_OFF.Properties.VariableNames{2} = 'Val_1000';
joined_OFF = innerjoin(t_300_OFF, t_1000_OFF);
[~, p_OFF_cross] = ttest(joined_OFF.Val_300, joined_OFF.Val_1000);
fprintf('Paired T-Test | 300Lux OFF vs 1000Lux OFF: p = %.4f (N=%d)\n', p_OFF_cross, height(joined_OFF));
% --- Original Stats (On vs Off) ---
disp('--- STATS: Fig 4C Diurnality (On vs Off) ---');
% --- Plotting Significance Bars ---
y_lims = get(ax4C, 'YLim'); y_range = diff(y_lims);
y_top = y_lims(2);
% 1. Cross-Condition ON (300 vs 1000)
if p_ON_cross < 0.05
x1 = find(strcmp(groupOrder, '300Lux-On'));
x2 = find(strcmp(groupOrder, '1000Lux-On'));
y_line = y_top + y_range * 0.15; % High arch
plot(ax4C, [x1, x1, x2, x2], [y_top+y_range*0.02, y_line, y_line, y_top+y_range*0.02], 'k-', 'LineWidth', 1.2);
if p_ON_cross < 0.001, str='***'; elseif p_ON_cross<0.01, str='**'; else, str='*'; end
text(ax4C, mean([x1, x2]), y_line + y_range*0.02, str, 'HorizontalAlignment', 'center', 'FontSize', 10);
y_top = y_line; % Bump up for next bars
end
xtickangle(ax4C, 45);
ylabel(ax4C, ['Mean ', current_metric_ylabel]);
title(ax4C, sprintf('Fig 4C: Diurnality Violins (%s)', current_metric_suffix));
set(ax4C, 'Position', [0.13 0.2 0.775 0.7]);
fig_filename = fullfile(savePath_Fig4, sprintf('Figure4C_Violins_GrayPooled_%s.png', current_metric_suffix));
exportgraphics(hFig4C_violins, fig_filename); disp(['Saved: ', fig_filename]); close(hFig4C_violins);
catch ME_4C, warning('ErrGen:Fig4C','Error Fig 4C (%s): %s', current_metric_suffix, ME_4C.message); end
%% FIG 4D: Shift in Activity Peaks During FullDark (CIRCULAR STATS + CoG PEAK)
disp('--- Starting Figure 4D: Peak Shift (Center of Gravity) ---');
if strcmp(current_metric_var, normalizedActivityVar)
disp('Skipping Figure 4D for NormalizedActivity (Percentage change invalid for Z-scores).');
else
try
hFig4D_peak = figure('Name', sprintf('Fig 4D: Peak Shift in FullDark (%s)', current_metric_suffix), 'Visible', 'off', 'Color', 'w');
ax4D = axes('Parent', hFig4D_peak);
data_FD = dataTable(ismember(dataTable.Animal, fourCondAnimals) & dataTable.Condition == 'FullDark', :);
animals_to_test = fourCondAnimals;
unique_days_FD = unique(data_FD.DayOfCondition);
% 1. Calculate Daily Peaks using Center of Gravity (CoG)
animal_daily_peaks = NaN(length(unique_days_FD), length(animals_to_test));
for i_animal = 1:length(animals_to_test)
animal_id = animals_to_test(i_animal);
data_this_animal = data_FD(data_FD.Animal == animal_id, :);
for i_day = 1:length(unique_days_FD)
day_val = unique_days_FD(i_day);
data_this_day_animal = data_this_animal(data_this_animal.DayOfCondition == day_val, :);
if isempty(data_this_day_animal), continue; end
hourly_mean = groupsummary(data_this_day_animal, ztHourVar, 'mean', current_metric_var);
% --- CENTER OF GRAVITY CALCULATION ---
if ~isempty(hourly_mean)
hours = hourly_mean.(ztHourVar);
activity = hourly_mean.(['mean_', current_metric_var]);
% Zero out negative values if using normalized data (cannot have negative mass)
activity(activity < 0) = 0;
if sum(activity) > 0
% Convert Time to Angles (0-24h -> 0-2pi)
angles = hours * (2*pi / 24);
% Calculate Vector Components weighted by Activity
X = sum(activity .* cos(angles));
Y = sum(activity .* sin(angles));
% Calculate Mean Phase (angle)
mean_angle = atan2(Y, X);
% Convert back to Hours (0-24)
cog_zt = mod(mean_angle * (24 / (2*pi)), 24);
animal_daily_peaks(i_day, i_animal) = cog_zt;
end
end
end
end
disp('--- STATS: Figure 4D (Circular Mean & Shift) ---');
min_day_idx = 1; max_day_idx = length(unique_days_FD);
if max_day_idx >= 7
% Define Week Ranges
first_week_indices = 1:7;
last_week_indices = (max_day_idx-6):max_day_idx;
% Get Data (Rows=Days, Cols=Animals)
first_week_data = animal_daily_peaks(first_week_indices, :);
last_week_data = animal_daily_peaks(last_week_indices, :);
% --- CIRCULAR MEAN FUNCTION ---
% Converts ZT (0-24) to Radians, averages vectors, converts back
calc_circ_mean = @(x) mod(atan2(mean(sin(x*2*pi/24),1,'omitnan'), mean(cos(x*2*pi/24),1,'omitnan')) * 24/(2*pi), 24);
% Calculate Circular Mean for each ANIMAL (Columns)
first_week_means = calc_circ_mean(first_week_data);
last_week_means = calc_circ_mean(last_week_data);
% --- CALCULATE SHIFT (Shortest Distance on Circle) ---
raw_diff = last_week_means - first_week_means;
circular_diff = mod(raw_diff + 12, 24) - 12; % Wraps result to [-12, +12] range
% Calculate Grand Means for Display
grand_mean_first = calc_circ_mean(first_week_means'); % Transpose to treat as column
grand_mean_last = calc_circ_mean(last_week_means');
fprintf('Comparing Mean Peak ZT (CoG) per animal in FullDark:\n');
fprintf(' - First Week Circular Mean: %.2f\n', grand_mean_first);
fprintf(' - Last Week Circular Mean: %.2f\n', grand_mean_last);
fprintf(' - Mean Shift: %.2f hours\n', mean(circular_diff));
% Test if the SHIFT is significantly different from 0
[h, p_peak, ci, stats_peak] = ttest(circular_diff, 0);
fprintf('One-Sample T-Test on Phase Shift (diff vs 0): t=%.3f, p=%.4f\n', stats_peak.tstat, p_peak);
end
daily_peak_ZT_pooled = NaN(length(unique_days_FD),1);
for i_day = 1:length(unique_days_FD)
day_val = unique_days_FD(i_day);
data_this_day_pooled = data_FD(data_FD.DayOfCondition == day_val, :);
if ~isempty(data_this_day_pooled)
hourly_mean = groupsummary(data_this_day_pooled, ztHourVar, 'mean', current_metric_var);
if ~isempty(hourly_mean)
% --- POOLED CENTER OF GRAVITY ---
hours = hourly_mean.(ztHourVar);
activity = hourly_mean.(['mean_', current_metric_var]);
activity(activity < 0) = 0; % Remove negative weights
if sum(activity) > 0
angles = hours * (2*pi / 24);
X = sum(activity .* cos(angles));
Y = sum(activity .* sin(angles));
mean_angle = atan2(Y, X);
daily_peak_ZT_pooled(i_day) = mod(mean_angle * (24 / (2*pi)), 24);
end
end
end
end
plot(ax4D, unique_days_FD(~isnan(daily_peak_ZT_pooled)), daily_peak_ZT_pooled(~isnan(daily_peak_ZT_pooled)), 'o-k', 'LineWidth', 1.5);
title(ax4D, sprintf('Fig 4D: Peak Activity ZT (CoG) (%s)', current_metric_suffix));
xlabel(ax4D, 'Day'); ylabel(ax4D, 'Peak ZT'); ylim(ax4D, [-1 24]);
fig_filename = fullfile(savePath_Fig4, sprintf('Figure4D_PeakShift_CoG_%s.png', current_metric_suffix));
exportgraphics(hFig4D_peak, fig_filename); disp(['Saved: ', fig_filename]); close(hFig4D_peak);
catch ME_4D, warning('ErrGen:Fig4D','Error Fig 4D (%s): %s', current_metric_suffix, ME_4D.message); end
end
%% FIG 4E: Percentage Change (ON vs OFF) Violin Plot
disp('--- Starting Figure 4E: ON/OFF Pct Change Violins ---');
if strcmp(current_metric_var, normalizedActivityVar)
disp('Skipping Figure 4E for NormalizedActivity (Percentage change invalid for Z-scores).');
else
try
% 1. Setup Figure
if ~exist('violinplot.m','file'),error('ViolinPlotNotFound:Fig4E','violinplot.m not found.');end
hFig4E_violins = figure('Name', sprintf('Fig 4E: ON/OFF Pct Change Violins (%s)', current_metric_suffix), 'Visible', 'off', 'Color', 'w');
ax4E = axes('Parent', hFig4E_violins); hold(ax4E, 'on');
% 2. Define Conditions and Data Containers
conditions_Fig4E = {'300Lux', '1000Lux', 'FullDark', '300LuxEnd'};
plotData_4E = []; groupData_4E = []; groupOrder_4E = {};
% Temporary storage to avoid re-calculating for the scatter loop
grouped_pct_data = containers.Map;
% 3. Main Data Processing Loop
for i_cond = 1:length(conditions_Fig4E)
cond_name = conditions_Fig4E{i_cond};
% Apply specific animal selection logic
animals_for_cond = allAnimals;
if ismember(cond_name, ["FullDark","300LuxEnd"]), animals_for_cond=fourCondAnimals; end
% Get raw data for this condition
data_segment = dataTable(ismember(dataTable.Animal, animals_for_cond) & dataTable.Condition == cond_name, :);
if isempty(data_segment), continue; end
% Aggregate mean by Animal, Sex, and LightPeriod
animal_means = groupsummary(data_segment, {'Animal', 'Sex', 'LightPeriod'}, 'mean', current_metric_var);
% Pivot data so 'On' and 'Off' are columns for each animal
try
pivoted_data = unstack(animal_means, ['mean_' current_metric_var], 'LightPeriod', 'GroupingVariables', {'Animal', 'Sex'});
% Check if both On and Off exist after unstacking
if all(ismember({'On', 'Off'}, pivoted_data.Properties.VariableNames))
% Calculate INDIVIDUAL Percentage Change: ((ON - OFF) / OFF) * 100
% Add epsilon to denominator to prevent division by zero
epsilon = 1e-9;
pivoted_data.PctChange = ((pivoted_data.On - pivoted_data.Off) ./ (pivoted_data.Off + epsilon)) * 100;
% Remove NaNs or Infs if OFF was 0
valid_rows = isfinite(pivoted_data.PctChange);
pivoted_data = pivoted_data(valid_rows, :);
% Append to main plotting data
plotData_4E = [plotData_4E; pivoted_data.PctChange];
groupData_4E = [groupData_4E; repmat(categorical({cond_name}), height(pivoted_data), 1)];
groupOrder_4E{end+1} = cond_name;
% Store for the scatter overlay loop
grouped_pct_data(cond_name) = pivoted_data;
else
warning('Fig4E:IncompleteData', 'Missing ON or OFF data for condition: %s', cond_name);
end
catch ME_Pivot
warning('Fig4E:PivotError', 'Could not pivot data for %s: %s', cond_name, ME_Pivot.message);
end
end
% 4. Create Base Gray Violin Plot
violinplot(plotData_4E, groupData_4E, 'Parent', ax4E, 'GroupOrder', groupOrder_4E, 'ViolinColor', grayColor, 'ShowData', false);
% 5. Reference line at 0%
yline(ax4E, 0, 'k--', 'LineWidth', 1.2, 'HandleVisibility', 'off');
% 6. Overlay Individual Data Points (Males vs Females)
jitterAmount = 0.15;
for i_group = 1:length(groupOrder_4E)
group_label = groupOrder_4E{i_group};
if isKey(grouped_pct_data, group_label)
group_data = grouped_pct_data(group_label);
% Jitter x-positions
x_scatter = i_group + (rand(height(group_data), 1) - 0.5) * jitterAmount;
% Split by Sex and Plot
male_idx = group_data.Sex == 'Male';
scatter(ax4E, x_scatter(male_idx), group_data.PctChange(male_idx), 40, maleColor, 'filled', 'MarkerFaceAlpha', 0.8, 'HandleVisibility', 'off');
scatter(ax4E, x_scatter(~male_idx), group_data.PctChange(~male_idx), 40, femaleColor, 'filled', 'MarkerFaceAlpha', 0.8, 'HandleVisibility', 'off');
end
end
try
disp('--- STATS: Figure 4E (Corrected: Paired t-tests) ---');
hold(ax4E, 'on');
% --- 1. Create a single wide table to align all animals ---
% Get data + Animal IDs from the map.
temp_table_300 = grouped_pct_data('300Lux');
table_300 = temp_table_300(:, {'Animal', 'PctChange'});
table_300.Properties.VariableNames{'PctChange'} = 'Pct_300';
temp_table_1000 = grouped_pct_data('1000Lux');
table_1000 = temp_table_1000(:, {'Animal', 'PctChange'});
table_1000.Properties.VariableNames{'PctChange'} = 'Pct_1000';
temp_table_dark = grouped_pct_data('FullDark');
table_dark = temp_table_dark(:, {'Animal', 'PctChange'});
table_dark.Properties.VariableNames{'PctChange'} = 'Pct_Dark';
temp_table_end = grouped_pct_data('300LuxEnd');
table_end = temp_table_end(:, {'Animal', 'PctChange'});
table_end.Properties.VariableNames{'PctChange'} = 'Pct_End';
% Join them all.
paired_table = outerjoin(table_300, table_1000, 'Keys', 'Animal', 'MergeKeys', true);
paired_table = outerjoin(paired_table, table_dark, 'Keys', 'Animal', 'MergeKeys', true);
paired_table = outerjoin(paired_table, table_end, 'Keys', 'Animal', 'MergeKeys', true);
p_values = containers.Map('KeyType', 'char', 'ValueType', 'double');
% --- 2. Run PAIRED t-tests (ttest) ---
[~, p] = ttest(paired_table.Pct_300, paired_table.Pct_1000);
p_values('1000Lux_vs_300Lux') = p;
fprintf('Paired T-Test (300Lux vs 1000Lux) [N=%d]: p = %.4f\n', sum(~isnan(paired_table.Pct_300) & ~isnan(paired_table.Pct_1000)), p);
[~, p] = ttest(paired_table.Pct_300, paired_table.Pct_Dark);
p_values('FullDark_vs_300Lux') = p;
fprintf('Paired T-Test (300Lux vs FullDark) [N=%d]: p = %.4f\n', sum(~isnan(paired_table.Pct_300) & ~isnan(paired_table.Pct_Dark)), p);
[~, p] = ttest(paired_table.Pct_300, paired_table.Pct_End);
p_values('300LuxEnd_vs_300Lux') = p;
fprintf('Paired T-Test (300Lux vs 300LuxEnd) [N=%d]: p = %.4f\n', sum(~isnan(paired_table.Pct_300) & ~isnan(paired_table.Pct_End)), p);
[~, p] = ttest(paired_table.Pct_Dark, paired_table.Pct_1000);
p_values('FullDark_vs_1000Lux') = p;
fprintf('Paired T-Test (FullDark vs 1000Lux) [N=%d]: p = %.4f\n', sum(~isnan(paired_table.Pct_Dark) & ~isnan(paired_table.Pct_1000)), p);
[~, p] = ttest(paired_table.Pct_End, paired_table.Pct_1000);
p_values('300LuxEnd_vs_1000Lux') = p;
fprintf('Paired T-Test (300LuxEnd vs 1000Lux) [N=%d]: p = %.4f\n', sum(~isnan(paired_table.Pct_End) & ~isnan(paired_table.Pct_1000)), p);
[~, p] = ttest(paired_table.Pct_Dark, paired_table.Pct_End);
p_values('FullDark_vs_300LuxEnd') = p;
fprintf('Paired T-Test (FullDark vs 300LuxEnd) [N=%d]: p = %.4f\n', sum(~isnan(paired_table.Pct_Dark) & ~isnan(paired_table.Pct_End)), p);
% --- 3. Plot Significance Bars (4C Style) ---
x_control = find(strcmp(groupOrder_4E, '300Lux'));
x_1000 = find(strcmp(groupOrder_4E, '1000Lux'));
x_dark = find(strcmp(groupOrder_4E, 'FullDark'));
x_end = find(strcmp(groupOrder_4E, '300LuxEnd'));
y_lims_4E = get(ax4E, 'YLim');
y_range_4E = diff(y_lims_4E);
% Define 6 Y-levels
y_level_1 = y_lims_4E(2) + y_range_4E * 0.05; y_text_1 = y_level_1 + y_range_4E * 0.01;
y_level_2 = y_text_1 + y_range_4E * 0.05; y_text_2 = y_level_2 + y_range_4E * 0.01;
y_level_3 = y_text_2 + y_range_4E * 0.05; y_text_3 = y_level_3 + y_range_4E * 0.01;
y_level_4 = y_text_3 + y_range_4E * 0.05; y_text_4 = y_level_4 + y_range_4E * 0.01;
y_level_5 = y_text_4 + y_range_4E * 0.05; y_text_5 = y_level_5 + y_range_4E * 0.01;
y_level_6 = y_text_5 + y_range_4E * 0.05; y_text_6 = y_level_6 + y_range_4E * 0.01;
new_y_max_4E = y_text_6 + y_range_4E * 0.03;
set(ax4E, 'YLim', [y_lims_4E(1), new_y_max_4E]);