-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathspiky.m
8321 lines (7400 loc) · 295 KB
/
spiky.m
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
function varargout = spiky(varargin)
% SPIKY Analysis software for physiological and behavioral
%
% Usage:
% < spiky >
% Runs the Spiky GUI
%
% < spiky(FUN) >
% Runs the internal function FUN in Spiky. Ex:m
% spiky, e.g. spiky('LoadTrial(''A1807004.daq'')')
%
% Alternative syntax for running subroutines:
% global Spiky
% Spiky.SUB(arg1, ..., argn)
% where SUB is the subroutine to run.
%
% Notes:
% When adding help entries to local functions, last comment line should
% end with a single percentage and then newline.
%
% Spiky - Spike sorting GUI for Matlab
% Copyright (C) 2005-2016 Per M Knutsen <p.m.knutsen@medisin.uio.no>
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
%
% Abort if Spiky is already running
hPlot = findobj('Tag', 'Spiky');
if ~isempty(hPlot)
disp('Spiky is already running')
return
end
clc
disp('Spiky - Spike-sorting and analysis in Matlab')
disp('Copyright (C) 2005-2016 Per M Knutsen <p.m.knutsen@medisin.uio.no>')
disp('This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are')
fprintf('are welcome to redistribute it under certain conditions; see LICENSE for details.\n\n')
% Set path to spike-sorting software
disp('Initializing paths...')
sPath = which('spiky');
sPath = sPath(1:end-7);
addpath(genpath(sPath), '-end');
% Get list of all internal sub-routines
disp('Initializing function handles...')
csStr = mlintmex('-calls', which(mfilename));
[~,~,~,~,subs] = regexp(csStr, '[S]\d* \d+ \d+ (\w+)\n');
cSubs = [subs{:}]';
% Generate function handles for all sub-routines
global Spiky;
Spiky = struct([]);
Spiky(1).main = struct([]);
Spiky(1).import = struct([]);
Spiky(1).export = struct([]);
Spiky(1).help = eval('@GetHelp');
Spiky.analysis = struct('discrete', struct([]), 'continuous', struct([]));
for i = 1:length(cSubs)
Spiky.main(1).(cSubs{i}) = eval(['@' cSubs{i}]);
end
% Create handles to all /analysis/discrete functions
sThisPath = [sPath filesep 'analysis' filesep 'discrete' filesep];
tFiles = dir(sThisPath);
for f = 1:length(tFiles)
if ~isempty(strfind(tFiles(f).name, '.m')) && isempty(strfind(tFiles(f).name, '.m~'))
sName = tFiles(f).name(1:end-2);
Spiky.analysis.discrete(1).(sName) = eval(['@' sName]);
end
end
% Create handles to all /analysis/discrete functions
sThisPath = [sPath filesep 'analysis' filesep 'continuous' filesep];
tFiles = dir(sThisPath);
for f = 1:length(tFiles)
if ~isempty(strfind(tFiles(f).name, '.m')) && isempty(strfind(tFiles(f).name, '.m~'))
sName = tFiles(f).name(1:end-2);
Spiky.analysis.continuous(1).(sName) = eval(['@' sName]);
end
end
% Create handles to all import and export filters and data filters
csSetHandles = {'import' 'export' 'filters'};
for sHandle = csSetHandles
sThisPath = [sPath filesep sHandle{1} filesep];
tFiles = dir(sThisPath);
for f = 1:length(tFiles)
if ~isempty(strfind(tFiles(f).name, '.m')) && isempty(strfind(tFiles(f).name, '.m~'))
sName = tFiles(f).name(1:end-2);
Spiky.(sHandle{1})(1).(sName) = eval(['@' sName]);
end
end
end
% Make Spiky available immediately in base workspace
evalin('base', 'global Spiky')
fprintf('\nSpiky API:\nTo interface with Spiky from your own code, load the global variable Spiky.\n')
fprintf('Functions are called with the syntax Spiky.[function](). Example:\n\n')
fprintf('\tglobal Spiky;Spiky.help(''ZoomReset'')\n\tSpiky.main.ZoomReset().\n\n')
fprintf('To access the documentation of API calls use Spiky.help([function]).\n\n')
global g_hSpike_Viewer
g_hSpike_Viewer = figure;
hGUI = g_hSpike_Viewer;
% Set FV default settings
FV = SetFVDefaults();
SetStruct(FV);
ThemeObject([]); % set default line colors
% Set GUI window properties
ThemeObject(hGUI, 'Name', 'Spiky', 'MenuBar', 'none', 'UserData', FV, ...
'Tag', 'Spiky', 'PaperOrientation', 'landscape', 'PaperUnits', 'normalized', ...
'PaperPosition', [.05 .05 .9 .9], 'InvertHardcopy', 'off', ...
'closeRequestFcn', @ExitSpiky, 'visible', 'off', ...
'WindowButtonMotionFcn', @GUIMouseMotion );
MinimizeGUI();
if isfield(get(hGUI),'SizeChangedFcn')
set(hGUI, 'SizeChangedFcn', @GUIResize )
end
movegui(hGUI, 'center')
set(hGUI, 'visible', 'on')
% Create GUI toolbar and menu
GUIRefreshToolbar();
GUIRefreshMenu();
% Set Spiky to by default NOT be in MERGE MODE
global g_bMergeMode g_bBatchMode
g_bMergeMode = 0;
g_bBatchMode = false;
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MinimizeGUI()
% Set the height of the GUI window to the minimum
%
hGUI = GetGUIHandle();
vPos = get(hGUI, 'position');
if datenum(version('-date')) < 736000
nHeight = 20;
else
nHeight = 0;
end
set(hGUI, 'position', [vPos(1)-200 vPos(2)-50 500 nHeight], 'name', 'Spiky')
% Delete axes and context menus
delete(findobj(hGUI, 'type', 'axes'))
delete(findobj(hGUI, 'type', 'uicontextmenu'))
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function GUIResize(varargin)
% Execute code when GUI is resized
%
% Refresh GUI when it is resized
% Resizing the GUI in Linux has the effect of shuffling menu items around
%GUIRefresh()
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function GUIMouseMotion(varargin)
% Execute code when mouse cursor moves over GUI, such as updating status
% text in bottom left corner of UI.
%
[FV, ~] = GetStruct();
% Create tooltip if it does not exist
hFig = GetGUIHandle();
hTxt = findobj(hFig, 'Tag', 'AxesCursorLocationTip');
if isempty(hTxt)
hTxt = uicontrol(hFig, 'Style', 'text', 'Position', [0 0 400 15], ...
'HorizontalAlignment', 'left', 'Tag', 'AxesCursorLocationTip', ...
'fontsize', 8, 'backgroundcolor', get(hFig, 'color'));
end
ThemeObject(hTxt)
% Get handle of axes cursor is above
% Note that overobj() is an undocumented function and may changed in the
% future
hAx = overobj('axes');
if isempty(hAx)
set(hTxt(1), 'string', '')
else
% Update tooltip
mPnt = get(hAx, 'CurrentPoint');
hAxLab = findobj(hAx, 'type', 'text');
sChDescr = '';
if ~isempty(hAxLab)
sChDescr = get(hAxLab(1), 'string');
end
% Get channel real name
sCh = sChDescr;
if ~isempty(sChDescr)
sChB = GetChannelRealName(sChDescr);
if ~isempty(sChB)
sCh = sChB;
end
end
% Get voltage scaling
sUnit = get(get(hAx, 'ylabel'), 'userdata');
if isempty(sUnit)
sUnit = FV.tAmplitudeUnit.sUnit;
end
% Check if channel is filtered or not
sFilters = '';
if isfield(FV, 'tFilteredChannels')
if isfield(FV.tFilteredChannels, sCh)
sFilters = ', FILTERED';
end
end
set(hTxt(1), 'string', sprintf(' %s (%s): %.1f sec , %.1f %s %s ', ...
sChDescr, sCh, mPnt(1, 1), mPnt(1, 2), sUnit, sFilters), ...
'backgroundcolor', get(hFig, 'color'))
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function GUIRefresh(varargin)
% Refresh Spiky GUI
%
global g_bBatchMode
hGUI = GetGUIHandle();
ViewTrialData();
GUIRefreshToolbar();
GUIRefreshMenu();
g_bBatchMode = 0;
ThemeObject(GetGUIHandle());
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function GUIRefreshToolbar()
% Refresh toolbar in Spiky GUI
%
% This is an alias function for sp_refreshtoolbar(). Usage is identical,
% ie simply: GUIRefreshToolbar()
%
sp_refreshtoolbar();
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function GUIRefreshMenu()
% Refresh menu in Spiky GUI
%
% This is an alias function for sp_refreshmenu(). Usage is identical,
% ie simply: GUIRefreshMenu()
%
sp_refreshmenu();
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function GetScriptHelp(varargin)
% Get help entry of a script file
%
% Usage:
% GetScriptHelp() to select script manually
% GetScriptHelp('script.m')
%
sScriptPath = which('spiky');
sScriptPath = [sScriptPath(1:end-7) 'scripts' filesep];
if nargin == 1
sScript = varargin{1};
else
% Select script file manually
[sScript, sScriptPath] = uigetfile(sprintf('%s*.m', sScriptPath), 'Select script file');
end
% Strip .m from filename
[~, sScript, ~] = fileparts(sScript);
% Get full path to script file
sScriptPath = [sScriptPath sScript '.m'];
if exist(sScriptPath, 'file')
disp(sprintf('Script:\t%s', sScript))
disp(help(sScriptPath))
else
sp_disp(sprintf('No help entry for script %s', sScript));
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function GetHelp(varargin)
% Get help entry of local function inside spiky.m
%
if nargin < 1
sp_disp('Which help entry do you want?');
return;
else
sFunction = varargin{1};
% Remove @ sign in case a function handle was passed, eg:
% Spiky.help(Spiky.main.MergeChannels)
if isa(sFunction, 'function_handle')
sFunction = func2str(sFunction);
end
end
% Read spiky.m
sPath = which('spiky');
sSpiky = fileread(sPath);
% Find the string 'function FUNCTIONNAME'
sExpr = ['[^\n]*function ' sFunction '([^\n]*'];
[~, nStart, nEnd] = regexp(sSpiky, sExpr, 'match');
if isempty(nStart)
sp_disp(sprintf('No help entry for %s()', sFunction));
return
end
disp(sprintf('Function call:\t%s', sSpiky(nStart+9:nEnd)))
% Find comments that follow
sExpr = '%[\r\n|\n|\r]';
[~, nStartC, nEndC] = regexp(sSpiky(nEnd+2:nEnd+5000), sExpr, 'match');
disp(sSpiky(nEnd:(nEnd+nStartC(1))))
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function CreateAnalysisMenu(hParent, sType, varargin)
% Create and return a uimenu with callbacks to continuous analysis
% functions. Use this function to create uimenus for GUIs and figures.
%
% Usage:
% CreateAnalysisMenu(H, TYPE)
%
% where H is the parent of the uimenu and TYPE is the type of analysis
% functions included in the menu. Valid values of TYPE are 'continuous' or
% 'discrete'.
%
% Load list of continuous analysis functions
sSpikyPath = which('spiky');
sContPath = [sSpikyPath(1:end-7) filesep 'analysis' filesep sType filesep ];
tFiles = dir(sContPath);
% Create menu with label
if nargin > 2
sLabel = varargin{1};
else
sLabel = ['&' regexprep(sType, '(\<[a-z])','${upper($1)}')];
end
hMenu = uimenu('Parent', hParent, 'Label', sLabel);
for f = 1:length(tFiles)
if ~isempty(strfind(tFiles(f).name, '.m')) && isempty(strfind(tFiles(f).name, '.m~'));
sName = strrep(tFiles(f).name(1:end-2), '_', ' ');
vIndx = strfind(sName, ' ');
sName([1 vIndx+1]) = upper(sName([1 vIndx+1]));
uimenu('Label', sName, 'Parent', hMenu, ...
'Callback', {@RunAnalysis, tFiles(f).name(1:end-2), sType});
end
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function CheckUpdate(varargin)
% Compare commit SHA hash on disk with latest version online
%
hWin = msgbox('Checking for a newer version of Spiky...', 'Spiky Update');
try
sResp = urlread('https://api.github.com/repos/pmknutsen/spiky/commits');
catch
close(hWin)
warndlg(lasterr, 'Spiky')
return
end
[~,~,~,~,cSHA] = regexp(sResp, '[{"sha":"(\w+)"');
sSHA = cell2mat(cSHA{1});
close(hWin)
if strcmp(GetGitHash(), sSHA(1:10))
msgbox('You have the latest version of Spiky.', 'Spiky Update')
else
msgbox(sprintf('A new version of Spiky is available at:\nhttps://github.com/pmknutsen/spiky'), 'Spiky Update')
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function SetAmplitudeUnit(varargin)
% Set the voltage amplitude unit on a per-channel basis.
%
% Usage:
% SetAmplitudeUnit(S)
% sets a common unit S for all channels with an undefined unit
% (i.e. channels where the unit is assumed to be volts)
%
% SetAmplitudeUnit(S, C)
% sets the voltage unit S for channel C
%
% where S can be:
% 'V' (volts)
% 'mV' (millivolts)
% 'uV' (microvolts)
%
if isobject(varargin{1})
sUnit = varargin{3};
else
sUnit = varargin{1};
end
switch sUnit
case 'V', nFactor = 1;
case 'mV', nFactor = 10^3;
case 'uV', nFactor = 10^6;
otherwise
sp_disp(sprintf('%s is an invalid unit', sUnit))
return
end
tAmplitudeUnit = struct('sUnit', sUnit, 'nFactor', nFactor);
[FV, ~] = GetStruct();
bReplot = 1;
if strcmp(FV.tAmplitudeUnit.sUnit, tAmplitudeUnit.sUnit)
bReplot = 0;
end
FV.tAmplitudeUnit = tAmplitudeUnit;
SetStruct(FV);
if bReplot
ViewTrialData();
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function PanRight(varargin)
% Pan the displayed data range towards right
%
if ~IsDataLoaded, return, end
[FV, ~] = GetStruct();
vChild = findobj(get(findobj('Tag', 'Spiky'), 'children'), 'Type', 'axes'); % axes handles
vX = get(vChild(end), 'xlim');
FV.vXlim = vX+(diff(vX)/4); % pan right by 25%
SetStruct(FV); ViewTrialData
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function PanLeft(varargin)
% Pan the displayed data range towards left
%
if ~IsDataLoaded, return, end
[FV, ~] = GetStruct();
vChild = findobj(get(findobj('Tag', 'Spiky') ,'children'), 'Type', 'axes'); % axes handles
vX = get(vChild(end), 'xlim');
FV.vXlim = vX-(diff(vX)/4); % pan left by 25%
SetStruct(FV); ViewTrialData();
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ZoomReset(varargin)
% Reset all zoom levels so the entire data range is shown
%
[FV, ~] = GetStruct();
if ~isfield(FV, 'tData') return, end
FV.vXlim = [];
cFieldnames = fieldnames(FV.tYlim);
for f = 1:length(cFieldnames)
FV.tYlim.(cFieldnames{f}) = [];
end
SetStruct(FV);
ViewTrialData();
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ZoomIn(varargin)
% Increase horizontal zoom by 25%
%
if ~IsDataLoaded, return, end
[FV, ~] = GetStruct();
vX = GetXLim();
FV.vXlim = [mean(vX)-(diff(vX)/4) mean(vX)+(diff(vX)/4)];
SetStruct(FV); ViewTrialData
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function vXLim = GetXLim(varargin)
% Get current x-axis limits
%
% Usage:
% vXLim = GetXLim()
%
vChild = findobj(get(findobj('Tag', 'Spiky'), 'children'), 'Type', 'axes'); % axes handles
vXLim = get(vChild(end), 'xlim');
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ZoomOut(varargin)
% Decrease horizontal zoom by 25%
%
if ~IsDataLoaded, return, end
[FV, ~] = GetStruct();
vChild = findobj(get(findobj('Tag', 'Spiky') ,'children'), 'Type', 'axes'); % axes handles
vX = get(vChild(end), 'xlim');
FV.vXlim = [mean(vX)-(diff(vX)*2) mean(vX)+(diff(vX)*2)];
SetStruct(FV); ViewTrialData
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ZoomRange(varargin)
% Select a horizontal zoom range manually
%
if ~IsDataLoaded, return, end
[FV, ~] = GetStruct();
if FV.bPanOn, pan off, end
hold on;
hLin = plot(NaN,NaN);
% If panning is currently enabled we need to turn that off in order
% to detect mouse presses in window
set(findobj(get(GetGUIHandle(), 'children'), 'type', 'axes'), 'ButtonDownFcn', '')
% Point 1
waitforbuttonpress
global pnt1
pnt1 = get(gca,'CurrentPoint'); % button down detected
% Callback that draws the line between points
set(GetGUIHandle(), 'WindowButtonMotionFcn', @ZoomRangeUpdateLine)
try
waitforbuttonpress;
catch
return;
end
pnt2 = get(gca,'CurrentPoint'); % button down detected
set(GetGUIHandle(), 'windowButtonMotionFcn', ''); % reset motion callback
hLine = findobj('Tag', 'SpikyXZoomIndicator');
if isempty(hLine), return, end
FV.vXlim = sort(get(hLine(3), 'xdata'));
delete(hLine)
SetStruct(FV);
ViewTrialData()
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ZoomRangeUpdateLine(varargin)
% Callback to update display of zoom indicator during horizontal zoom
%
global pnt1
pnt2 = get(gca, 'CurrentPoint'); % button down detected
hLine = findobj('Tag', 'SpikyXZoomIndicator');
hLine = flipud(hLine);
if isempty(hLine)
for i = 1:6
hLine(i) = line(0,0);
end
vYPos = get(gca, 'ylim');
vXPos = get(gca, 'xlim');
nYPos = mean(vYPos);
nH = diff(vYPos) * .2;
% 'Shadow' line
set(hLine(1), 'Tag', 'SpikyXZoomIndicator', 'ydata', [nYPos nYPos])
set(hLine(2), 'Tag', 'SpikyXZoomIndicator', 'ydata', [nYPos-nH nYPos+nH], 'xdata', [pnt1(1,1) pnt1(1,1)])
set(hLine(3), 'Tag', 'SpikyXZoomIndicator', 'ydata', [nYPos-nH nYPos+nH], 'xdata', [pnt1(1,1) pnt1(1,1)])
% 'Highlight' line
set(hLine(4), 'Tag', 'SpikyXZoomIndicator', 'ydata', [nYPos nYPos])
set(hLine(5), 'Tag', 'SpikyXZoomIndicator', 'ydata', [nYPos-nH nYPos+nH], 'xdata', [pnt1(1,1) pnt1(1,1)])
set(hLine(6), 'Tag', 'SpikyXZoomIndicator', 'ydata', [nYPos-nH nYPos+nH], 'xdata', [pnt1(1,1) pnt1(1,1)])
set(hLine([1:3]), 'linewidth', 3, 'color', 'k')
set(hLine([4:6]), 'linewidth', 1, 'color', 'w')
end
set(hLine([1 4]), 'xdata', [pnt1(1,1) pnt2(1,1)])
set(hLine([3 6]), 'xdata', [pnt2(1,1) pnt2(1,1)])
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function PCACleaning(varargin)
%
%
if ~IsDataLoaded, return, end
[FV, hWin] = GetStruct();
global g_bBatchMode
% Build a matrix containing the continuous data vectors of selected
% electrode. Note that the selected electrode must contain at least 3
% channels (i.e. be a tri-trode, tetrode or more. Stereotrodes and
% individual electrodes cannot be cleaned!)
%
if ~g_bBatchMode
if isfield(FV, 'tExperimentVariables')
if isfield(FV, 'sVariable')
nIndx = find(strcmp({FV.tExperimentVariables.sVariable}, 'bPCACleanedChannels'));
if ~isempty(nIndx)
if FV.tExperimentVariables(nIndx).sValue
switch questdlg('This file has already been PCA cleaned. If it is necessary to redo the cleaning it is recommended you first re-load the original files from disk.', ...
'Spiky', 'Continue', 'Abort', 'Abort')
case 'Abort', return
end
end
end
end
end
end
csChannels = FV.csDisplayChannels;
if length(csChannels) < 3
waitfor(warndlg('A minimum of 3 channels must be selected for PCA cleaning.'))
return
end
% Initialize matrix to be cleaned
mRaw = []; % create matrix that should be filtered
for i = 1:length(csChannels)
vRaw = FV.tData.(csChannels{i})';
% Check that vector is same length as the others
if ~isempty(mRaw)
if length(vRaw) ~= size(mRaw, 1)
waitfor(warndlg(['All channels must have the same vector length. Try de-selecting channels that should not be included for PCA cleaning.']))
return
end
end
mRaw = [mRaw vRaw];
end
% Initialize global variables used in pca_cleaning()
global ptspercut;
ptspercut = FV.tData.([csChannels{1} '_KHz']) * 1000; % equal to sampling frequency
% Clean
vIndx = [strfind(FV.sLoadedTrial, '/') strfind(FV.sLoadedTrial, '\')];
if isempty(vIndx)
sp_disp(sprintf('Start PCA cleaning of %s ...', FV.sLoadedTrial))
else
sp_disp(sprintf('Start PCA cleaning of %s ...', FV.sLoadedTrial(vIndx(end)+1:end)))
end
mClean = pca_cleaning(mRaw, 0); % run PCA cleaning
sp_disp('Done PCA cleaning!')
% Plot cleaned on top of raw data
persistent p_bNeverPlotPCA
if isempty(p_bNeverPlotPCA), p_bNeverPlotPCA = 0; end
if ~p_bNeverPlotPCA && ~g_bBatchMode
sAns = questdlg('Do you want to plot and compare PCA cleaned traces?', 'Spiky', 'No', 'Yes', 'Never plot', 'Yes');
else
sAns = 'No';
end
if strcmpi(sAns, 'Never plot'), p_bNeverPlotPCA = 1; end
if strcmpi(sAns, 'Yes') && ~p_bNeverPlotPCA && ~g_bBatchMode
hFig = figure;
ThemeObject(hFig)
set(hFig, 'name', 'Spiky PCA Cleaning')
for c = 1:size(mRaw,2)
hAx = axes('position', [.05 (1/size(mRaw,2))*(c-1) .95 1/size(mRaw,2)]);
ThemeObject(hAx)
set(hAx, 'xtick', [])
hold
plot(mRaw(:,c), 'g')
plot(mClean(:,c), 'r')
ylabel(csChannels{c})
end
linkaxes(get(gcf,'children'), 'xy')
uiwait(hFig)
end
if g_bBatchMode
sAns = 'Yes';
else
sAns = questdlg('Keep cleaned data? Keeping will overwrite the data vectors in this .spb file. Original, raw data is not over-written.', 'Spiky', 'Yes', 'No', 'Cancel', 'Yes');
end
switch sAns
case 'Yes'
% Replace raw data with cleaned data in FV
for i = 1:length(csChannels)
FV.tData.(csChannels{i}) = mClean(:,i)';
end
% Log this change in FV.tExperimentVariables
if isfield(FV, 'tExperimentVariables')
if isfield(FV, 'sVariable')
nIndx = find(strcmp({FV.tExperimentVariables.sVariable}, 'bPCACleanedChannels'));
if isempty(nIndx)
FV.tExperimentVariables(end+1).sVariable = 'bPCACleanedChannels';
FV.tExperimentVariables(end).sValue = '1';
% Save names of channels used for PCA cleaning
FV.tExperimentVariables(end+1).sVariable = 'sPCACleanedChannels';
FV.tExperimentVariables(end).sValue = mat2str(cell2mat(csChannels'));
else
FV.tExperimentVariables(nIndx).sValue = '1';
nIndx = strcmp({FV.tExperimentVariables.sVariable}, 'sPCACleanedChannels');
FV.tExperimentVariables(nIndx).sValue = mat2str(cell2mat(csChannels'));
end
end
else
% TODO
end
SetStruct(FV)
ViewTrialData
% Remember task for batching
if ~g_bBatchMode BatchRedo([], 'PCACleaning'); end
case 'No', return
case 'Cancel', return
end
figure(hWin)
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function NewExperimentVariable(sVarName, sVarValue)
% Create a new experiment variable.
%
% Values of existing variables are replaced.
%
% Usage: NewExperimentVariable(VARNAME, VARVALUE)
%
[FV, ~] = GetStruct();
if ~isfield(FV, 'tExperimentVariables')
FV(1).tExperimentVariables = struct();
end
if ~isfield(FV.tExperimentVariables, 'sVariable')
nIndx = 1;
else
nIndx = find(strcmp({FV.tExperimentVariables.sVariable}, sVarName));
if isempty(nIndx)
nIndx = length(FV.tExperimentVariables) + 1;
end
end
FV.tExperimentVariables(nIndx).sVariable = sVarName;
FV.tExperimentVariables(nIndx).sValue = sVarValue;
SetStruct(FV);
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function SaveResults(varargin)
% Save data to an SPB file in default path
%
% Usage: SaveResults()
%
global g_hSpike_Viewer
if ~IsDataLoaded, return, end
sPointer = get(g_hSpike_Viewer,'Pointer');
set(g_hSpike_Viewer,'Pointer','watch')
[FV, ~] = GetStruct();
sPath = [FV.sLoadedTrial(1:end-4) '.spb'];
save(sPath, 'FV', '-v7.3')
% Update the title of the Spiky window to reflect that settings were saved
set(GetGUIHandle(), 'Name', sprintf('%s - Spiky', GetCurrentFile()))
set(GetGUIHandle(),'Pointer', sPointer)
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function OpenSettings(varargin)
% OpenSettings loads data and settings from an SPB file
%
persistent p_bAlwaysUseDuplicate
if isempty(p_bAlwaysUseDuplicate)
p_bAlwaysUseDuplicate = 0;
end
%if ~IsDataLoaded, return, end % returns true when loading SPB files
[FV, ~] = GetStruct();
tData = FV.tData; % original raw data and paths
sDirectory = FV.sDirectory;
sLoadedTrial = FV.sLoadedTrial;
bSelect = 0;
if ~isempty(varargin)
if ~isstr(varargin{1})
bSelect = 1;
bRefresh = 1;
else
sPath = varargin{1};
bRefresh = 0;
end
end
if bSelect
sPath = [FV.sLoadedTrial(1:end-4) '.spb'];
[sFile, sPath] = uigetfile(sPath, 'Select data file');
sPath = [sPath sFile];
end
try
load(sPath, 'FV', '-MAT')
catch
[sLastMsg, ~] = lasterr();
% Check for 'corrupt' string in error message
if ~isempty(strfind(sLastMsg, 'corrupt'))
warndlg('Failed reading file. The file may be corrupt. Deleting it will remove this error.', 'Spiky')
end
end
% If data already exists in tData, possibilities are;
% 1) Fields are duplicates of those on disk (filtered, inverted, PCA cleaned etc)
% 2) Additional fields to those on disk have previously been imported
% TODO:
% If fields are real duplicates, ask what to do (keep/replace)
% If fields have been imported, keep
% FV.tData -> saved/processed data from .spb file
% tData -> raw data from .daq file only (all kept by default)
% tDataTemp -> Temporary structure we will store data to keep in
% Keep all saved data by default
tDataTemp = FV.tData;
% Find duplicate or additional fields in DAQ file
% - Additional (imported) fields are kept by default
% - User is asked whether to keep duplicate fields or revert to original (raw)
if isfield(FV, 'tData') % is there saved data?
if ~isempty(FV.tData)
sAns = '';
cFieldnamesDAQ = fieldnames(tData);
cFieldnamesSPB = fieldnames(FV.tData);
for f = 1:length(cFieldnamesDAQ)
if any(strcmp(cFieldnamesDAQ{f}, cFieldnamesSPB)) % duplicate field (ask)
if p_bAlwaysUseDuplicate, sAns = 'Always use duplicate';
else
if isempty(sAns) % ask whether to keep or replace
% Ask only once
sAns = questdlg('A duplicate of the raw data exists in an existing Spiky generated file. Do you wish to use this data, or reload all raw data from the .daq file? Note that reloading raw data will erase imported fields.', ...
'Duplicate data warning', 'Use duplicate', 'Always use duplicate', 'Reload data', 'Use duplicate');
end
end
switch sAns
case 'Use duplicate'
% No need to do anything if saved fields are to be
% kept since these are included by default above
case 'Always use duplicate'
p_bAlwaysUseDuplicate = 1;
case 'Reload data' % retrieve and keep original field
%cFieldnamesDAQ{f}
tDataTemp.(cFieldnamesDAQ{f}) = tData.(cFieldnamesDAQ{f});
end
else % Keep by default new/imported fields that do not exist in .daq file
if isfield(FV.tData, cFieldnamesDAQ{f})
tDataTemp.(cFieldnamesDAQ{f}) = FV.tData.(cFieldnamesDAQ{f});
end
end
end
end
end
FV.tData = tDataTemp;
FV.sDirectory = sDirectory;
FV.sLoadedTrial = sLoadedTrial;
if bRefresh, ViewTrialData(); end
SetStruct(FV)
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function AutoloadNewFiles(varargin)
% ** NOT IMPLEMENTED IN THIS VERSION **
%
[FV, ~] = GetStruct();
if ~isfield(FV, 'sDirectory')
warndlg('You must first select the directory that should be monitored in File->Open Directory', 'Spiky')
else
map_autoload([FV.sDirectory filesep])
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function SetFilterOptions(varargin)
% Set filtering options per channel in a UI.
%
% Usage: SetFilterOptions()
%
[FV, ~] = GetStruct();
csFilters = GetFilters();
csFilters = {' ' csFilters{:}};
% Initialize figure
hFig = figure('closeRequestFcn', 'set(gcbf,''userdata'',1)', ...
'Name', 'Spiky Filtering Options', 'ToolBar', 'none', ...
'menuBar','none');
vPos = get(hFig, 'position');
vPos = [vPos(1:2) 730 500];
ThemeObject(hFig, 'position', vPos)
centerfig(hFig, GetGUIHandle());
cColumnNames = {'Channel', 'Filter 1', 'Filter 2', 'Highpass (Hz)', 'Lowpass (Hz)', 'Filter 3', 'Filter 4'};
cColumnFormat = {[], csFilters, csFilters, 'numeric', 'numeric', csFilters, csFilters};
cColumnEditable = [false true true true true true true];
if ~isfield(FV, 'tFilteredChannels')
FV.tFilteredChannels = struct();
end
% Create data cell for table
cData = {};
for i = 1:length(FV.csChannels)
cData{i, 1} = GetChannelDescription(FV.csChannels{i});
if isempty(cData{i, 1})
cData{i, 1} = FV.csChannels{i};
end
if isfield(FV.tFilteredChannels, FV.csChannels{i})
% Pre-bandpass filters
if isfield(FV.tFilteredChannels.(FV.csChannels{i}), 'csFiltersPre')
cData{i, 2} = FV.tFilteredChannels.(FV.csChannels{i}).csFiltersPre{1};
if length(FV.tFilteredChannels.(FV.csChannels{i}).csFiltersPre) > 1
cData{i, 3} = FV.tFilteredChannels.(FV.csChannels{i}).csFiltersPre{2};
else cData{i, 3} = []; end
else
cData{i, 3} = [];
end
% Bandpass
if isfield(FV.tFilteredChannels.(FV.csChannels{i}), 'nHighPass')
cData{i, 4} = FV.tFilteredChannels.(FV.csChannels{i}).nHighPass;
else cData{i, 4} = []; end
if isfield(FV.tFilteredChannels.(FV.csChannels{i}), 'nLowPass')
cData{i, 5} = FV.tFilteredChannels.(FV.csChannels{i}).nLowPass;
else cData{i, 5} = []; end
% Post-bandpass filters
if isfield(FV.tFilteredChannels.(FV.csChannels{i}), 'csFiltersPost')
cData{i, 6} = FV.tFilteredChannels.(FV.csChannels{i}).csFiltersPost{1};
if length(FV.tFilteredChannels.(FV.csChannels{i}).csFiltersPost) > 1
cData{i, 7} = FV.tFilteredChannels.(FV.csChannels{i}).csFiltersPost{2};
else cData{i, 7} = []; end
else
cData{i, 7} = [];
end
else
cData{i, 2} = [];
cData{i, 3} = [];
cData{i, 4} = [];
cData{i, 5} = [];
cData{i, 6} = [];
cData{i, 7} = [];
end
end
%% Create table
hTable = uitable('Units', 'normalized','Position', [0 0 1 1], 'Data', cData, ...
'ColumnName', cColumnNames, 'ColumnEditable', cColumnEditable, ...
'ColumnFormat', cColumnFormat, 'ColumnWidth', {150 80 80 100 100 100});
% Wait for figure to be closed
waitfor(hFig, 'userdata')
cData = get(hTable, 'data');
delete(hFig)
%% Replace NaNs with nothing
for i = 1:numel(cData)
if isnan((cData{i}))
cData{i} = [];
end
end
%% Get new filter parameters
FV.tFilteredChannels = struct([]);
for i = 1:length(FV.csChannels)
if ~isempty(cData{i, 2}) && ~strcmp(cData{i, 2}, ' ')
FV.tFilteredChannels(1).(FV.csChannels{i}).csFiltersPre{1} = cData{i, 2};
end
if ~isempty(cData{i, 3}) && ~strcmp(cData{i, 3}, ' ')
FV.tFilteredChannels(1).(FV.csChannels{i}).csFiltersPre{2} = cData{i, 3};
end
if ~isempty(cData{i, 4})
if ~isnumeric(cData{i, 4}), cData{i, 4} = str2num(cData{i, 4}); end
FV.tFilteredChannels(1).(FV.csChannels{i}).nHighPass = cData{i, 4};
end
if ~isempty(cData{i, 5})