-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathepicTreeGUI.m
More file actions
957 lines (804 loc) · 36.1 KB
/
epicTreeGUI.m
File metadata and controls
957 lines (804 loc) · 36.1 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
classdef epicTreeGUI < handle
% EPICTREEGUI Interactive GUI for visualizing and analyzing epoch data
%
% Main GUI controller that integrates:
% - epicTreeTools (data organization)
% - epicGraphicalTree (tree visualization)
% - singleEpoch (epoch viewer)
%
% Usage:
% % Load data and build tree
% [data, ~] = loadEpicTreeData('data.mat');
% tree = epicTreeTools(data);
% tree.buildTreeWithSplitters({
% @epicTreeTools.splitOnCellType,
% @epicTreeTools.splitOnExperimentDate,
% 'cellInfo.id'
% });
%
% % Launch GUI with pre-built tree
% gui = epicTreeGUI(tree);
% gui = epicTreeGUI(tree, 'noEpochs'); % Hide individual epochs
%
% Layout:
% [40% Tree Browser] | [60% Viewer/Plotting]
%
% See also: epicTreeTools, epicGraphicalTree, getSelectedData, loadEpicTreeData
properties
% Data
tree % epicTreeTools root node
allEpochs % Flat epoch list (cell array)
h5File % H5 file path for lazy loading
matFilePath = '' % Path to source .mat file (for .ugm file discovery)
loadedMask = [] % Selection mask loaded at startup (for close comparison)
% UI Components
figure % Main figure handle
treeBrowser % struct: panel, graphTree
plottingCanvas % struct: panel, axes, infoTable
% State
showEpochs = true % Show individual epochs in tree
isBusy = false % Busy flag
end
properties (Hidden = true)
title = 'Epic Tree GUI'
fontSize = 12
xDivLeft = 0.4 % Tree panel width (40%)
end
methods
function self = epicTreeGUI(treeObj, varargin)
% Constructor - Accepts pre-built epicTreeTools object only
%
% Usage:
% % Build tree first
% [data, ~] = loadEpicTreeData('data.mat');
% tree = epicTreeTools(data);
% tree.buildTreeWithSplitters({@epicTreeTools.splitOnCellType, ...});
%
% % Launch GUI
% gui = epicTreeGUI(tree);
% gui = epicTreeGUI(tree, 'noEpochs'); % Hide individual epochs
%
% This matches the legacy epochTreeGUI pattern.
% Parse options
if any(strcmpi(varargin, 'noEpochs'))
self.showEpochs = false;
end
% Create figure
self.figure = figure(...
'Name', self.title, ...
'NumberTitle', 'off', ...
'MenuBar', 'none', ...
'ToolBar', 'none', ...
'Position', [100 100 1200 700], ...
'CloseRequestFcn', @(src,evt) self.onClose(), ...
'Visible', 'off');
% Build UI components
self.buildUIComponents();
% Validate and set tree
if nargin >= 1 && ~isempty(treeObj)
if isa(treeObj, 'epicTreeTools')
% Pre-built tree passed in
self.tree = treeObj;
self.allEpochs = self.tree.allEpochs;
% Store .mat file path for .ugm file persistence
if ~isempty(self.tree.sourceFile)
self.matFilePath = self.tree.sourceFile;
end
% Store loaded mask for close comparison (build from current isSelected state)
self.loadedMask = self.buildCurrentMask();
% Get H5 file from config
try
config = epicTreeConfig();
if isfield(config, 'h5_dir') && ~isempty(config.h5_dir)
% Get experiment name from first epoch
if ~isempty(self.allEpochs)
ep = self.allEpochs{1};
if isfield(ep, 'expInfo') && isfield(ep.expInfo, 'exp_name')
expName = ep.expInfo.exp_name;
self.h5File = fullfile(config.h5_dir, [expName '.h5']);
% Verify H5 file exists
if ~exist(self.h5File, 'file')
warning('epicTreeGUI:H5NotFound', ...
'H5 file not found: %s\nData will not load!', self.h5File);
self.h5File = '';
else
fprintf('✓ H5 file found: %s\n', self.h5File);
end
end
end
else
warning('epicTreeGUI:NoH5Config', ...
'H5 directory not configured! Run: epicTreeConfig(''h5_dir'', ''/path/to/h5'')');
end
catch ME
warning('epicTreeGUI:ConfigError', ...
'Error getting H5 config: %s', ME.message);
end
% Update tree browser
self.initTreeBrowser();
% Update title
nEpochs = length(self.allEpochs);
set(self.figure, 'Name', sprintf('%s - %d epochs', self.title, nEpochs));
else
error('Input must be an epicTreeTools object. Use loadEpicTreeData() then build tree with buildTreeWithSplitters().');
end
end
% Show figure
set(self.figure, 'Visible', 'on');
end
function delete(self)
% Destructor
if ~isempty(self.figure) && ishandle(self.figure)
delete(self.figure);
end
end
function nodes = getSelectedEpochTreeNodes(self)
% GETSELECTEDEPOCHTREENODES Get selected tree nodes
%
% Returns cell array of epicTreeTools nodes
if isempty(self.treeBrowser) || isempty(self.treeBrowser.graphTree)
nodes = {};
return;
end
% Get selected epicGraphicalTreeNodes
[graphNodes, ~] = self.treeBrowser.graphTree.getSelectedNodes();
% Extract epicTreeTools nodes from userData
nodes = cell(size(graphNodes));
for ii = 1:length(graphNodes)
if ~isempty(graphNodes{ii}) && ~isempty(graphNodes{ii}.userData)
nodes{ii} = graphNodes{ii}.userData;
end
end
end
function epochs = getSelectedEpochs(self)
% GETSELECTEDEPOCHS Get epochs from selected tree nodes
%
% Returns cell array of epoch structs
nodes = self.getSelectedEpochTreeNodes();
epochs = {};
for ii = 1:length(nodes)
if ~isempty(nodes{ii})
nodeEpochs = nodes{ii}.getAllEpochs(true); % Only selected
epochs = [epochs; nodeEpochs(:)];
end
end
end
end
%% Private Methods - UI Building
methods (Access = private)
function buildUIComponents(self)
% Build all UI components
% Initialize structs
self.treeBrowser = struct();
self.plottingCanvas = struct();
% Create tree browser panel (left)
self.buildTreeBrowserPanel();
% Create plotting canvas (right)
self.buildPlottingCanvas();
% Create menu bar
self.buildMenuBar();
end
function buildTreeBrowserPanel(self)
% Build the tree browser panel (left side)
% Main panel
self.treeBrowser.panel = uipanel(self.figure, ...
'Title', 'Epoch Tree', ...
'FontSize', self.fontSize, ...
'Units', 'normalized', ...
'Position', [0 0 self.xDivLeft 1]);
% Tree axes (takes up most of the panel)
self.treeBrowser.treeAxes = axes('Parent', self.treeBrowser.panel, ...
'Units', 'normalized', ...
'Position', [0.02 0.12 0.96 0.87]);
% Initialize epicGraphicalTree
self.treeBrowser.graphTree = epicGraphicalTree(self.treeBrowser.treeAxes, 'Epochs');
self.treeBrowser.graphTree.nodesSelectedFcn = @(tree) self.onTreeSelectionChanged(tree);
self.treeBrowser.graphTree.nodesCheckedFcn = @(tree) self.onTreeCheckChanged(tree);
% Button panel (bottom)
self.treeBrowser.buttonPanel = uipanel(self.treeBrowser.panel, ...
'Title', '', ...
'BorderType', 'none', ...
'Units', 'normalized', ...
'Position', [0.02 0.01 0.96 0.10]);
% Set Example button
self.treeBrowser.setExampleBtn = uicontrol(self.treeBrowser.buttonPanel, ...
'Style', 'pushbutton', ...
'String', 'Set Example', ...
'Units', 'normalized', ...
'Position', [0.02 0.3 0.3 0.6], ...
'Callback', @(src,evt) self.onSetExample());
% Select All button
self.treeBrowser.selectAllBtn = uicontrol(self.treeBrowser.buttonPanel, ...
'Style', 'pushbutton', ...
'String', 'Select All', ...
'Units', 'normalized', ...
'Position', [0.35 0.3 0.3 0.6], ...
'Callback', @(src,evt) self.onSelectAll());
% Clear Selection button
self.treeBrowser.clearSelBtn = uicontrol(self.treeBrowser.buttonPanel, ...
'Style', 'pushbutton', ...
'String', 'Clear Sel', ...
'Units', 'normalized', ...
'Position', [0.68 0.3 0.3 0.6], ...
'Callback', @(src,evt) self.onClearSelection());
end
function buildPlottingCanvas(self)
% Build the plotting canvas (right side)
% Main panel
self.plottingCanvas.panel = uipanel(self.figure, ...
'Title', 'Data Viewer', ...
'FontSize', self.fontSize, ...
'Units', 'normalized', ...
'Position', [self.xDivLeft 0 (1 - self.xDivLeft) 1]);
% Info table (top)
self.plottingCanvas.infoTable = uitable(self.plottingCanvas.panel, ...
'Units', 'normalized', ...
'Position', [0.02 0.85 0.96 0.13], ...
'ColumnName', {'Property', 'Value'}, ...
'ColumnWidth', {120, 200}, ...
'Data', {'Node', ''; 'Epochs', ''; 'Selected', ''});
% Plot axes (bottom)
self.plottingCanvas.axes = axes('Parent', self.plottingCanvas.panel, ...
'Units', 'normalized', ...
'Position', [0.1 0.1 0.85 0.70]);
xlabel(self.plottingCanvas.axes, 'Time (ms)');
ylabel(self.plottingCanvas.axes, 'Response');
end
function buildMenuBar(self)
% Build menu bar
% File menu
fileMenu = uimenu(self.figure, 'Label', 'File');
uimenu(fileMenu, 'Label', 'Export Selection...', 'Callback', @(src,evt) self.onExportSelection());
uimenu(fileMenu, 'Label', 'Save Epoch Mask...', 'Callback', @(src,evt) self.onSaveEpochMask());
uimenu(fileMenu, 'Label', 'Close', 'Callback', @(src,evt) self.onClose(), 'Separator', 'on');
% Analysis menu
analysisMenu = uimenu(self.figure, 'Label', 'Analysis');
uimenu(analysisMenu, 'Label', 'Mean Response Trace', 'Callback', @(src,evt) self.onAnalysisMeanTrace());
uimenu(analysisMenu, 'Label', 'Response Amplitude', 'Callback', @(src,evt) self.onAnalysisAmplitude());
% Help menu
helpMenu = uimenu(self.figure, 'Label', 'Help');
uimenu(helpMenu, 'Label', 'Keyboard Shortcuts', 'Callback', @(src,evt) self.showKeyboardHelp());
uimenu(helpMenu, 'Label', 'About', 'Callback', @(src,evt) self.showAbout());
end
function initTreeBrowser(self)
% Initialize tree browser from epicTreeTools
if isempty(self.tree)
return;
end
% Delete existing epicGraphicalTree (cleans up all widgets)
if ~isempty(self.treeBrowser.graphTree)
delete(self.treeBrowser.graphTree);
end
% Recreate epicGraphicalTree
self.treeBrowser.graphTree = epicGraphicalTree(self.treeBrowser.treeAxes, 'Epochs');
gTree = self.treeBrowser.graphTree;
gTree.nodesSelectedFcn = @(tree) self.onTreeSelectionChanged(tree);
gTree.nodesCheckedFcn = @(tree) self.onTreeCheckChanged(tree);
% Build graphical tree from epicTreeTools
self.marryEpochNodesToWidgets(self.tree, gTree.trunk);
% Draw
gTree.trunk.isExpanded = true;
gTree.draw();
end
function marryEpochNodesToWidgets(self, epochNode, browserNode)
% Recursively create epicGraphicalTreeNodes for epicTreeTools nodes
gTree = self.treeBrowser.graphTree;
% Set browser node properties
browserNode.userData = epochNode;
% Get display name
if ~isempty(epochNode.splitValue)
if isnumeric(epochNode.splitValue)
browserNode.name = sprintf('%s = %g', epochNode.splitKey, epochNode.splitValue);
elseif ischar(epochNode.splitValue)
displayValue = self.abbreviateProtocolName(epochNode.splitValue);
browserNode.name = sprintf('%s', displayValue);
else
displayValue = self.abbreviateProtocolName(char(string(epochNode.splitValue)));
browserNode.name = displayValue;
end
else
browserNode.name = 'Root';
end
% Add epoch count
nEpochs = epochNode.epochCount();
browserNode.name = sprintf('%s (%d)', browserNode.name, nEpochs);
% Set check state from custom property
browserNode.isChecked = epochNode.custom.isSelected;
% Handle example nodes (red background)
if epochNode.custom.isExample
browserNode.textBackgroundColor = [1 0.8 0.8];
end
% Recurse on children OR create individual epoch nodes
if ~epochNode.isLeaf
% Internal node - recurse on children
for ii = 1:length(epochNode.children)
childEpoch = epochNode.children{ii};
childBrowser = gTree.newNode(browserNode, '');
self.marryEpochNodesToWidgets(childEpoch, childBrowser);
end
elseif self.showEpochs && ~isempty(epochNode.epochList)
% Leaf node - create individual epoch widgets (legacy behavior)
epochs = epochNode.epochList;
for ii = 1:length(epochs)
ep = epochs{ii};
% Create epoch widget
epochWidget = gTree.newNode(browserNode, '');
epochWidget.userData = ep; % Store epoch struct directly, not tree node
% Set selection state
if isfield(ep, 'isSelected') && ~isempty(ep.isSelected)
epochWidget.isChecked = ep.isSelected;
else
epochWidget.isChecked = true;
end
% Format name: "#N: date/time"
epochWidget.name = self.formatEpochName(ii, ep);
% Pink background for individual epochs
epochWidget.textColor = [0 0 0];
epochWidget.textBackgroundColor = [1 .85 .85];
end
end
end
end
%% Private Methods - Callbacks
methods (Access = private)
function onClose(self)
% Close handler: compare current selection to loaded mask, prompt to save changes
try
% Build current mask from isSelected flags (one-time)
currentMask = self.buildCurrentMask();
% Compare to loaded mask
if ~isempty(self.loadedMask) && ~isempty(currentMask)
% Check if masks differ
if length(currentMask) == length(self.loadedMask)
if ~isequal(currentMask, self.loadedMask)
% Selection changed - prompt user
choice = questdlg(...
'Selection state has changed since loading. Update mask with session changes?', ...
'Save Changes?', ...
'Update Mask', 'Discard Changes', 'Cancel', ...
'Update Mask');
switch choice
case 'Update Mask'
% Save to latest .ugm or create new if none exists
if ~isempty(self.matFilePath)
latestUGM = epicTreeTools.findLatestUGM(self.matFilePath);
if isempty(latestUGM)
% Create new
filepath = epicTreeTools.generateUGMFilename(self.matFilePath);
self.tree.saveUserMetadata(filepath);
else
% Update latest
self.tree.saveUserMetadata(latestUGM);
end
end
% Continue closing
case 'Discard Changes'
% Continue closing without saving
case 'Cancel'
% Don't close
return;
end
end
end
end
catch ME
warning('epicTreeGUI:onClose', ...
'Error during close handler: %s. Closing without saving.', ME.message);
end
% Always close figure, even if save logic failed
delete(self.figure);
end
function onTreeSelectionChanged(self, ~)
% Handle tree node selection change
% Get selected graphical nodes
if isempty(self.treeBrowser) || isempty(self.treeBrowser.graphTree)
return;
end
[graphNodes, ~] = self.treeBrowser.graphTree.getSelectedNodes();
if isempty(graphNodes) || isempty(graphNodes{1})
return;
end
% Check userData type
userData = graphNodes{1}.userData;
if isa(userData, 'epicTreeTools')
% Tree node clicked
% Performance optimization: Navigate to first single epoch
% Find first leaf node
leaves = userData.leafNodes();
if ~isempty(leaves)
firstLeaf = leaves{1};
% Get first epoch from that leaf
if ~isempty(firstLeaf.epochList)
firstEpoch = firstLeaf.epochList{1};
fprintf('Note: Showing first epoch from node "%s"\n', ...
string(userData.splitValue));
% Plot single epoch
self.updateInfoTableForEpoch(firstEpoch);
self.plotSingleEpoch(firstEpoch);
return;
end
end
% Fallback: if no epochs found, show node info
self.updateInfoTable(userData);
self.plotNodeData(userData);
elseif isstruct(userData)
% Individual epoch - display single epoch
self.updateInfoTableForEpoch(userData);
self.plotSingleEpoch(userData);
end
end
function onTreeCheckChanged(self, ~)
% Handle check/selection change
% Sync check state to epicTreeTools nodes or individual epochs
gTree = self.treeBrowser.graphTree;
for ii = 1:length(gTree.nodeList)
gNode = gTree.nodeList{ii};
if ~isempty(gNode.userData)
if isa(gNode.userData, 'epicTreeTools')
% Tree node - update custom flag
gNode.userData.custom.isSelected = gNode.isChecked;
% Also update epochs if leaf
if gNode.userData.isLeaf
gNode.userData.setSelected(gNode.isChecked, false);
end
elseif isstruct(gNode.userData)
% Individual epoch - update isSelected field
gNode.userData.isSelected = gNode.isChecked;
end
end
end
end
function onSetExample(self)
% Toggle example flag on selected nodes
nodes = self.getSelectedEpochTreeNodes();
for ii = 1:length(nodes)
if ~isempty(nodes{ii})
nodes{ii}.custom.isExample = ~nodes{ii}.custom.isExample;
end
end
self.initTreeBrowser();
end
function onSelectAll(self)
% Select all epochs
if ~isempty(self.tree)
self.tree.setSelected(true, true);
self.initTreeBrowser();
end
end
function onClearSelection(self)
% Clear all selections
if ~isempty(self.tree)
self.tree.setSelected(false, true);
self.initTreeBrowser();
end
end
function onExportSelection(self)
% Export selected epochs
epochs = self.getSelectedEpochs();
if isempty(epochs)
msgbox('No epochs selected', 'Export');
return;
end
[file, path] = uiputfile('*.mat', 'Export Selected Epochs');
if file ~= 0
selectedEpochs = epochs;
save(fullfile(path, file), 'selectedEpochs');
msgbox(sprintf('Exported %d epochs', length(epochs)), 'Export');
end
end
function onSaveEpochMask(self)
% Save current selection state to .ugm file
% Validate we have data and path
if isempty(self.tree) || isempty(self.tree.allEpochs)
errordlg('No data loaded.', 'Save Epoch Mask');
return;
end
if isempty(self.matFilePath)
% Ask user to specify the .mat file path
[file, path] = uigetfile('*.mat', 'Select the source .mat file for this dataset');
if file == 0
return; % User cancelled
end
self.matFilePath = fullfile(path, file);
self.tree.sourceFile = self.matFilePath;
end
% Find existing .ugm files
latestUGM = epicTreeTools.findLatestUGM(self.matFilePath);
if isempty(latestUGM)
% No existing files - create new
filepath = epicTreeTools.generateUGMFilename(self.matFilePath);
self.tree.saveUserMetadata(filepath);
% Update loadedMask to current state (for close comparison)
self.loadedMask = self.buildCurrentMask();
msgbox(sprintf('Selection mask saved to:\n%s', filepath), 'Epoch Mask Saved');
else
% Existing files found - ask user
% Use questdlg for broader MATLAB compatibility (works pre-R2020a too)
choice = questdlg(...
sprintf('Found existing selection file:\n%s\n\nReplace it or create a new one?', latestUGM), ...
'Save Epoch Mask', ...
'Replace Latest', 'Create New', 'Cancel', ...
'Create New');
switch choice
case 'Replace Latest'
self.tree.saveUserMetadata(latestUGM);
% Update loadedMask to current state
self.loadedMask = self.buildCurrentMask();
msgbox(sprintf('Selection mask updated:\n%s', latestUGM), 'Epoch Mask Saved');
case 'Create New'
filepath = epicTreeTools.generateUGMFilename(self.matFilePath);
self.tree.saveUserMetadata(filepath);
% Update loadedMask to current state
self.loadedMask = self.buildCurrentMask();
msgbox(sprintf('Selection mask saved to:\n%s', filepath), 'Epoch Mask Saved');
case 'Cancel'
% Do nothing
end
end
end
function onAnalysisMeanTrace(self)
% Compute and plot mean response trace
nodes = self.getSelectedEpochTreeNodes();
if isempty(nodes) || isempty(nodes{1})
msgbox('Select a tree node first', 'Analysis');
return;
end
node = nodes{1};
[data, ~, fs] = epicTreeTools.getSelectedData(node, 'Amp1', self.h5File);
if isempty(data)
msgbox('No response data available', 'Analysis');
return;
end
% Convert to double and ensure fs is valid
data = double(data);
fs = double(fs);
if isempty(fs) || fs == 0
fs = 10000; % Default sample rate
end
% Compute mean and SEM
meanTrace = mean(data, 1);
semTrace = std(data, [], 1) / sqrt(size(data, 1));
t = (0:length(meanTrace)-1) / fs * 1000;
% Plot
ax = self.plottingCanvas.axes;
cla(ax);
hold(ax, 'on');
fill(ax, [t fliplr(t)], [meanTrace-semTrace fliplr(meanTrace+semTrace)], ...
[0.8 0.8 1], 'EdgeColor', 'none', 'FaceAlpha', 0.5);
plot(ax, t, meanTrace, 'b', 'LineWidth', 2);
hold(ax, 'off');
xlabel(ax, 'Time (ms)');
ylabel(ax, 'Response');
title(ax, sprintf('Mean Response (n=%d)', size(data,1)));
end
function onAnalysisAmplitude(self)
msgbox('Amplitude analysis not yet implemented', 'Analysis');
end
function updateInfoTable(self, node)
% Update info table for selected tree node
nEpochs = node.epochCount();
nSelected = node.selectedCount();
% Convert splitValue to char (table requires char, not string objects)
if isempty(node.splitValue)
valueStr = '';
elseif isnumeric(node.splitValue)
valueStr = sprintf('%g', node.splitValue);
elseif ischar(node.splitValue)
valueStr = node.splitValue;
else
valueStr = char(string(node.splitValue));
end
data = {
'Node', node.splitKey;
'Value', valueStr;
'Epochs', sprintf('%d', nEpochs);
'Selected', sprintf('%d', nSelected)
};
set(self.plottingCanvas.infoTable, 'Data', data);
end
function updateInfoTableForEpoch(self, epoch)
% Update info table for selected individual epoch
% Extract epoch metadata
if isfield(epoch, 'expInfo') && isfield(epoch.expInfo, 'date')
dateStr = epoch.expInfo.date;
else
dateStr = 'Unknown';
end
if isfield(epoch, 'isSelected')
isSelected = logical(epoch.isSelected);
else
isSelected = true;
end
% Get protocol name
if isfield(epoch, 'protocolSettings') && isfield(epoch.protocolSettings, 'protocolID')
protocol = epoch.protocolSettings.protocolID;
elseif isfield(epoch, 'parameters') && isfield(epoch.parameters, 'protocol')
protocol = epoch.parameters.protocol;
else
protocol = 'Unknown';
end
data = {
'Type', 'Single Epoch';
'Date', dateStr;
'Protocol', char(protocol);
'Selected', char(string(isSelected))
};
set(self.plottingCanvas.infoTable, 'Data', data);
end
function plotNodeData(self, node)
% Plot data for selected tree node (aggregated epochs)
ax = self.plottingCanvas.axes;
% Get selected data (pass H5 file for lazy loading)
[data, ~, fs] = epicTreeTools.getSelectedData(node, 'Amp1', self.h5File);
if isempty(data)
cla(ax);
text(ax, 0.5, 0.5, 'No response data', ...
'HorizontalAlignment', 'center', 'Units', 'normalized');
return;
end
% Convert to double and ensure fs is valid
data = double(data);
fs = double(fs);
if isempty(fs) || fs == 0
fs = 10000; % Default sample rate
end
% Plot all traces
cla(ax);
hold(ax, 'on');
t = (0:size(data,2)-1) / fs * 1000;
for ii = 1:min(size(data,1), 20) % Limit to 20 traces
plot(ax, t, data(ii,:), 'Color', [0.7 0.7 0.7]);
end
plot(ax, t, mean(data,1), 'k', 'LineWidth', 2);
hold(ax, 'off');
xlabel(ax, 'Time (ms)');
ylabel(ax, 'Response');
title(ax, sprintf('%d epochs', size(data,1)));
end
function plotSingleEpoch(self, epoch)
% Plot data for a single epoch (lazy loaded from H5)
ax = self.plottingCanvas.axes;
cla(ax);
try
% Use getSelectedData for single epoch (lazy loads from H5)
epochList = {epoch};
[data, ~, fs] = epicTreeTools.getSelectedData(epochList, 'Amp1', self.h5File);
if isempty(data)
text(ax, 0.5, 0.5, 'No response data', ...
'HorizontalAlignment', 'center', 'Units', 'normalized');
return;
end
% Convert to double and ensure fs is valid
data = double(data(:)'); % Ensure row vector of doubles
fs = double(fs);
if isempty(fs) || fs == 0
fs = 10000; % Default sample rate
end
% Plot single trace
t = (0:length(data)-1) / fs * 1000; % Convert to ms
plot(ax, t, data, 'b', 'LineWidth', 1.5);
xlabel(ax, 'Time (ms)');
ylabel(ax, 'Amp1');
title(ax, 'Single Epoch');
catch ME
text(ax, 0.5, 0.5, sprintf('Error loading data:\n%s', ME.message), ...
'HorizontalAlignment', 'center', 'Units', 'normalized');
end
end
function showKeyboardHelp(self)
msg = sprintf([...
'Keyboard Shortcuts:\n\n' ...
'Up/Down Arrow - Navigate tree\n' ...
'Left Arrow - Collapse node\n' ...
'Right Arrow - Expand node\n' ...
'F or Space - Toggle selection\n']);
msgbox(msg, 'Keyboard Shortcuts');
end
function showAbout(self)
msg = sprintf([...
'Epic Tree GUI v2.0\n\n' ...
'Pure MATLAB epoch tree browser.\n\n' ...
'Based on legacy Rieke Lab tools.']);
msgbox(msg, 'About');
end
function shortName = abbreviateProtocolName(~, fullName)
% ABBREVIATEPROTOCOLNAME Shorten long protocol names for display
%
% Converts:
% 'edu.washington.riekelab.protocols.SingleSpot' -> 'SingleSpot'
% 'edu.washington.riekelab.turner.protocols.Foo' -> 'Foo'
%
% Max length: 40 characters (truncate with '...')
if ~ischar(fullName) && ~isstring(fullName)
shortName = char(fullName);
return;
end
fullName = char(fullName);
% Extract last component after final '.' (protocol name only)
parts = strsplit(fullName, '.');
if length(parts) > 1
shortName = parts{end};
else
shortName = fullName;
end
% Truncate if still too long
maxLen = 40;
if length(shortName) > maxLen
shortName = [shortName(1:maxLen-3) '...'];
end
end
function name = formatEpochName(~, index, epoch)
% FORMATEPOCHNAME Format epoch display name
%
% Legacy format: "#N: YYYY-MM-DD HH:MM:SS"
% Example: " 1: 2025-12-02 10:15:30"
% Try to extract date/time from epoch
if isfield(epoch, 'expInfo') && isfield(epoch.expInfo, 'date')
dateStr = epoch.expInfo.date;
elseif isfield(epoch, 'startTime')
dateStr = epoch.startTime;
else
dateStr = '';
end
% Format name
if ~isempty(dateStr)
name = sprintf('%3d: %s', index, dateStr);
else
name = sprintf('%3d', index);
end
end
function h5Path = getH5FilePath(~, metadata, matPath)
% GETH5FILEPATH Get H5 file path for lazy loading
%
% Tries multiple strategies to find the H5 file
% Strategy 1: Check epicTreeConfig
try
config = epicTreeConfig();
if isfield(config, 'h5_dir') && ~isempty(config.h5_dir)
h5Dir = config.h5_dir;
% Look for H5 file in this directory
if isfield(metadata, 'exp_name')
h5Path = fullfile(h5Dir, [metadata.exp_name '.h5']);
if exist(h5Path, 'file')
return;
end
end
end
catch
% Config not available
end
% Strategy 2: Look for h5 directory next to .mat file
[matDir, matName, ~] = fileparts(matPath);
h5Dir = fullfile(fileparts(matDir), 'h5');
if exist(h5Dir, 'dir')
% Extract experiment name from mat file
if isfield(metadata, 'exp_name')
expName = metadata.exp_name;
else
% Use mat filename as experiment name
expName = matName;
end
h5Path = fullfile(h5Dir, [expName '.h5']);
if exist(h5Path, 'file')
return;
end
end
% Strategy 3: Return empty (will use in-memory data if available)
h5Path = '';
end
function mask = buildCurrentMask(self)
% Build selection mask from current isSelected flags (one-time)
if isempty(self.tree) || isempty(self.tree.allEpochs)
mask = [];
return;
end
allEps = self.tree.allEpochs;
mask = false(length(allEps), 1);
for i = 1:length(allEps)
if isfield(allEps{i}, 'isSelected') && allEps{i}.isSelected
mask(i) = true;
end
end
end
end
end