-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetEdit.m
1300 lines (1205 loc) · 48.3 KB
/
detEdit.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
% detEdit.m
% 2/21/2016 modified for version 1.1
% For Kogia JAH 5/22/15
% Estimate the number of False Detections
% JAH 10-19-2014
% spec2 uses the LTSA for the click spectra
% spec3 uses the TPWS file for the click spectra JAH 9-26-14
% spcc4 used the TPWS2 file JAH 10-12-14
% 7-7-14 use Simone bouts and Sean Detector JAH
% includes brushing FD, MD in and out of files
% Brushing only works in MATLAB ver 2013b, not 2013a or 2012b
% modified for BW 140308 jah 140320 jah for small ici
% 140311 smw detection editor based on evalSessions.m
clearvars
% utSetDesktopTitle('detEdit');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load user input. Has to happen first so you know species.
detEdit_settings_kelby
% define subfolder that fit specified iteration
% if itnum > 1
% for id = 2: str2num(itnum); % iternate id times according to itnum
% subfolder = ['TPWS',num2str(id)];
% sdir = (fullfile(sdir,subfolder));
% end
% end
%% Load Settings preferences
% Get parameter settings worked out between user preferences, defaults, and
% species-specific settings:
p = sp_setting_defaults('sp',sp,'srate',srate,'analysis','detEdit','spParamsUser',spParamsUser);
%% Check if TPWS file exists
% Concatenate parts of file name
if isempty(p.speName)
detfn = [filePrefix,'.*','TPWS',itnum,'.mat'];
else
detfn = [filePrefix,'.*',p.speName,'.*TPWS',itnum,'.mat'];
end
% Get a list of all the files in the start directory
fileList = cellstr(ls(sdir));
% Find the file name that matches the filePrefix
fileMatchIdx = find(~cellfun(@isempty,regexp(fileList,detfn))>0);
if isempty(fileMatchIdx)
% if no matches, throw error
error('No files matching filePrefix found!')
elseif length(fileMatchIdx)>1
% if more than one match, throw error
error('Multiple TPWS files match the filePrefix. Make the prefix more specific.')
end
matchingFile = fileList{fileMatchIdx};
fnTPWS = fullfile(sdir,matchingFile);
%% Handle Transfer Function
% add in transfer function if desired
if p.tfSelect > 0
if ~exist('tfName','var')% user interface to get TF file
disp('Load Transfer Function File');
[fname,pname] = uigetfile('I:\Harp_TF\*.tf','Load TF File');
tffn = fullfile(pname,fname);
else % or get it automatically from tf directory provided in settings
stndeploy = strsplit(filePrefix,'_'); % get only station and deployment
tffn = findTfFile(tfName,stndeploy); % get corresponding tf file
end
if strcmp(num2str(fname),'0')
disp('Cancelled TF File');
return
else %give feedback
disp(['TF File: ',tffn]);
end
fid = fopen(tffn);
[A,count] = fscanf(fid,'%f %f',[2,inf]);
tffreq = A(1,:);
tfuppc = A(2,:);
fclose(fid);
tf = interp1(tffreq,tfuppc,p.tfSelect,'linear','extrap');
disp(['TF @',num2str(p.tfSelect),' Hz =',num2str(tf)]);
else
tf = 0;
disp('No TF Applied');
end
%% Generate FD, TD, and ID files if needed
% Name and build false detection file
ffn = strrep(matchingFile,'TPWS','FD');
fnameFD = fullfile(sdir,ffn);
AFD = exist(fnameFD,'file');
if (AFD ~= 2) % if it doesn't exist, make it
zFD(1,1) = 1;
save(fnameFD,'zFD');
disp('Make new FD file');
end
% Name true detection file
tfn = strrep(matchingFile,'TPWS','TD');
fnameTD = fullfile(sdir,tfn);
% NOTE: TD file is made below because it depends on a later variable
% Name and build ID file
idfn = strrep(matchingFile,'TPWS','ID');
fnameID = fullfile(sdir,idfn);
AID = exist(fnameID,'file');
if (AID ~= 2)% if it doesn't exist, make it
zID = [];
save(fnameID,'zID');
disp('Make new ID file');
end
% Name and build ID file
mdfn = strrep(matchingFile,'TPWS','MD');
fnameMD = fullfile(sdir,mdfn);
AMD = exist(fnameMD,'file');
if (AMD ~= 2)% if it doesn't exist, make it
zMD = [];
save(fnameMD,'zMD');
disp('Make new MD file');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Load detections and false detections
% MTT = time MPP = peak-peak % MSN = waveform %MSP = spectra
load(fnTPWS,'MTT','MPP')
% if you have more than "maxDetLoad" detections, don't load all spectra and
% time series into memory. You can access them from the disk instead.
% Note: Can't remove duplicates in that case, because matlab won't let you
% select non-contiguous sets from files stored on disk.
nDets = length(MTT);
if ~exist('maxDetLoad')
loadMSP = true;
elseif isempty(maxDetLoad)
loadMSP = true;
else
loadMSP = nDets <= maxDetLoad; % true/false, if you have more detections than
end
% the maximum load this becomes false.
ic1 = [];
if loadMSP
% remove duplicates from MTT (can't do this if too many detections to load into memory).
[uMTT,ia1,ic1] = unique(MTT);
if (length(uMTT) ~= length(MTT))
disp([' TimeLevel Data NOT UNIQUE - removed: ', ...
num2str(length(ic1) - length(ia1))]);
end
load(fnTPWS,'MSP','MSN')
else
ia1 = [1:length(MTT)]';
end
[r,c] = size(MTT); %get shape of array
if (r > c)
clickTimes = MTT(ia1);
clickLevels = MPP(ia1);
else
clickTimes = MTT(ia1)';
clickLevels = MPP(ia1)';
end
if specploton && loadMSP
% if specploton and there aren't too many detections, load spectra
csn = MSN(ia1,:);
csp = MSP(ia1,:);
else
disp('No Waveform or Spectra');
end
%% apply tf and remove low amplitude detections
clickLevels = clickLevels + tf;
ib1 = find(clickLevels >= p.threshRL);
if (size(ib1,1) ~= size(clickLevels,1)) && ~loadMSP % catch for case where enforcing
% min RL threshold on large dataset creates non-continuous indices.
error('detEdit:RL',['Error: Re-run makeTPWS to enforce your minimum peak to peak RL threshold.\n',...
'You cannot do it here because you have too many detections to load into memory.\n',...
sprintf('TPWS minimum RL = %d \ndetEdit minimum RL = %d',min(clickLevels),p.threshRL)])
end
if (size(ib1,1) == 0)
% min RL threshold excludes all detections
error('detEdit:RL',['Error: No detections meet the minimum peak to peak RL threshold.\n',...
sprintf('TPWS maximum RL = %d \ndetEdit minimum RL = %d',max(clickLevels),p.threshRL)])
end
% prune by RL only if spectra & waveforms have been loaded
if specploton && loadMSP
disp([' Removed too low:',num2str(length(ia1)-length(ib1))]);
clickTimes = clickTimes(ib1);
clickLevels = clickLevels(ib1);
keepers = ia1(ib1);
csn = csn(ib1,:);
csp = csp(ib1,:);
else
keepers = ia1;
end
%% Make FD file intersect with MTT
load(fnameFD) % false detection times zFD
jFD = []; ia = []; ic = [];
if (~isempty(zFD))
[jFD,ia,ic] = intersect(MTT,zFD);
rFD = length(zFD) - length(jFD);
disp([' Removed ',num2str(rFD),...
' FD detections that do not match detection times']);
if size(jFD,1)<size(jFD,2)
jFD = jFD';
end
zFD = jFD;
save(fnameFD,'zFD');
end
%% Make ID file intersect with MTT
load(fnameID) % identified detection times zID
if (~isempty(zID))
[jID,ia,ic] = intersect(MTT,zID(:,1));
rID = length(zID) - length(jID);
disp([' Removed ',num2str(rID),...
' ID detections that do not match detection times']);
if size(jID,1)<size(jID,2)
jID = jID';
end
zID = zID(ic,:);
save(fnameID,'zID');
end
%% Make MD file intersect with MTT
load(fnameMD) % identified detection times zMD
if (~isempty(zMD))
[jMD,ia,ic] = intersect(MTT,zMD(:,1));
rMD = length(zMD) - length(jMD);
disp([' Removed ',num2str(rMD),...
' MD detections that do not match detection times']);
if size(jMD,1)<size(jMD,2)
jMD = jMD';
end
zMD = zMD(ic,:);
save(fnameMD,'zMD');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Calculate bout starts and ends
% TODO: this is calculated in mkLTSA, we should save it there instead of
% recalculating here but would create backward compatibility issues
% TODO: Should be a function
bFlag = 0;
% find edges (start and end times) of bouts or sessions
dt = diff(clickTimes)*24*60*60; % calculate time between detections in seconds
gt = gth*60*60; % gap time in sec
I = find(dt>gt); % find start of gaps
sb = [clickTimes(1);clickTimes(I+1)]; % start time of bout
eb = [clickTimes(I);clickTimes(end)]; % end time of bout
dd = clickTimes(end)-clickTimes(1); % deployment duration [d]
nb = length(sb); % number of bouts
bd = (eb - sb); % duration of bout in days
% find bouts longer than the minimum
if ~isempty(p.minBout)
bdI = find(bd > (p.minBout / (60*60*24)));
bd = bd(bdI);
sb = sb(bdI);
eb = eb(bdI);
nb = length(sb); % number of bouts
end
% limit the length of a bout
blim = p.ltsaMax/24; % 6 hr bout length limit in days
ib = 1;
while ib <= nb
bd = (eb - sb); %duration bout in days
if (bd(ib) > blim) % find long bouts
nadd = ceil(bd(ib)/blim) - 1; % number of bouts to add
for imove = nb : -1: (ib +1)
sb(imove+nadd)= sb(imove);
end
for iadd = 1 : 1: nadd
sb(ib+iadd) = sb(ib) + blim*iadd;
end
for imove = nb : -1 : ib
eb(imove+nadd) = eb(imove);
end
for iadd = 0 : 1 : (nadd - 1)
eb(ib+iadd) = sb(ib) + blim*(iadd+1);
end
nb = nb + nadd;
ib = ib + nadd;
end
ib = ib + 1;
end
disp(['Number Bouts : ',num2str(nb)])
%% Make LTSA session file
lsfn = strrep(matchingFile,'TPWS','LTSA');
fnameLTSA = fullfile(sdir,lsfn);
Altsa = exist(fnameLTSA,'file');
if Altsa ~= 2
disp(['Error: LTSA Sessions File Does Not Exist: ',fnameLTSA])
return
else
disp('Loading LTSA Sessions, please wait ...')
load(fnameLTSA) % LTSA sessions: pwr and pt structures
disp('Done Loading LTSA Sessions')
sltsa = size(pt);
if (sltsa(2) ~= nb)
disp(['Error: Number of LTSA sessions calculated here doesn''t match ',...
'input LTSA file. Check ltsaMax parameter.'])
return
end
end
%% Set up Tests for False Detections
% The false positive estimate tool picks every Nth click to test. If you
% have false positives in zFD, you can pick out only the true ones to
% determine which click indices to look at (that happens just below),
% but if the user then adds or removes anything from zFD, the indices won't
% adjust. Provide a warning to tell the user there might be an issue.
if ~isempty(zFD)
disp(strcat('WARNING: This dataset contains false-flagged detections. ', ...
' It is recommended that you remove them using modDet prior to ',...
'estimating false positive rate.'))
end
[~,trueClickIDx] = setdiff(clickTimes, zFD);
ixfd = (1: c4fd : length(trueClickIDx)); % selected to test for False Det
testClickIdx = trueClickIDx(ixfd);
A6 = exist(fnameTD,'file');
if (A6 ~= 2)
zTD = -1.*ones(nb,4);
save(fnameTD,'zTD'); % create new TD
disp(' Make new TD file');
else
load(fnameTD)
if (length(zTD(:,1)) ~= nb)
disp([' Problem with TD file:',fnameTD]);
return
end
end
%% Compute Spectra Plot Parameters
% max and min for LTSA frequency
fiminLTSA = 0;% TODO: make this configurable
fimaxLTSA = srate/2 ; % in kHz 100 or 160 kHz
% set ltsa step size
iPwr = 1;
while isempty(pwr{1,iPwr}) && iPwr<length(pwr)
iPwr = iPwr+1;
end
% ToDo: Seems like LTSA parameters (step size and frequency bins) could
% be calculated from LTSA directly, especially because there are
% inconsistent step sizes in some LTSAs.
if any(strcmp('dfManual',fieldnames(p)))&& ~isempty(p.dfManual)
% allow non-standard ltsa step sizes
df = p.dfManual;
else
df = 1000*fimaxLTSA/(size(pwr{1,iPwr},1)-1);
end
% for LTSA PLOT
f = 1000*fiminLTSA:df:1000*fimaxLTSA;
if p.tfSelect > 0 % tfParams isn't being used...
tfLTSA = interp1(tffreq,tfuppc,f,'linear','extrap')'; % add to LTSA vector
else
tfLTSA = zeros(size(f))';
end
if specploton
% check length of MSP
inFileMat = matfile(fnTPWS);
if ~loadMSP
MSP = inFileMat.MSP(1,:);
end
smsp2 = size(MSP,2);% 2nd element is num fft points
ift = 1:smsp2;
% make frequency vector that matches spectral bins
if any(strcmp('f',fieldnames(inFileMat)))
fmsp = inFileMat.f;
else
fmsp = [];
end
if isempty(fmsp)
fmsp = ((srate/2)/(smsp2-1))*ift - (srate/2)/(smsp2-1);
fprintf('No freq vector in TPWS file. Using approximation based on sample rate.\n')
end
% find the indices that are in the range of interest
fi = find(fmsp > p.fLow &...
fmsp <= p.fHi);
fimint = fi(1); fimaxt = fi(end);
ft = fmsp(fi);
% for the PP vs RMS plot
if (p.tfSelect > 0)
Ptfpp = interp1(tffreq,tfuppc,fmsp*1000,'linear','extrap');
else
Ptfpp = zeros(1,smsp2);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
kstart = input('Starting Session: ');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
pause on
disp('Press ''b'' key to go backward ')
disp('Press any other key to go forward')
cc = ' '; % avoids crash when first bout too short
k = kstart;
yell = [];
blag = 0;
if (size(zTD,2) == 2) % this seems to patch on extra columns
% to old zTD matrices that maybe only had the first two. Probably
% only needed for backward compatibility
zTD = [zTD,-1.*ones(length(zTD),2)];
save(fnameTD,'zTD');
end
%% Main Loop
% loop over the number of bouts (sessions)
%onerun = 1; % What does this do?
while (k <= nb)
disp([' BEGIN SESSION: ',num2str(k)]);
% load in FD, MD and TD each session in case these have been modified
load(fnameFD); % brings in zFD
load(fnameID); % brings in zID
load(fnameMD); % brings in zMD
load(fnameTD); % brings in zTD
% If all time series are loaded:
% Make PP versus RMS plot for all clicks, if all time series are loaded
figure(51); clf; set(51,'name',sprintf('RL pp vs. RL rms (left shift by %d)',p.threshRL))
h51 = gca;
% Make RMS versus frequency plot for all clicks
figure(53); clf; set(53,'name',sprintf('RL rms vs. Peak freq. (left shift by %d)',p.threshRL))
h53 = gca;
if p.threshHiFreq ~=0 %any(strcmp('threshHiFreq',fieldnames(p)))
ymax = p.threshHiFreq + 1;
else
ymax = fmsp(end); % yaxis max of plot 53 (Default)
end
if specploton && loadMSP
xmsp0All = csp + repmat(Ptfpp,size(csp,1),1);
[xmspAll,im] = max(xmsp0All(:,fimint:fimaxt),[],2); % maximum between flow-100kHz
% calculate peak-to-peak amplitude including transfer function
if isrow(clickLevels)
xmppAll = clickLevels-tf+ Ptfpp(im + fimint-1); % vectorized version
else
xmppAll = clickLevels'-tf+ Ptfpp(im + fimint-1); % vectorized version
end
% turn diagonal to vertical (easier way to find thresholds)
if isrow(xmspAll)
pxmspAll = xmspAll' - p.slope*(xmppAll - p.threshRL); %use slope of 1 to mod xmsp for plot
elseif isrow(xmppAll)
pxmspAll = xmspAll - p.slope*(xmppAll' - p.threshRL); %use slope of 1 to mod xmsp for plot
else
pxmspAll = xmspAll - p.slope*(xmppAll - p.threshRL); %use slope of 1 to mod xmsp for plot
end
plot(h51,pxmspAll,xmppAll,'o','MarkerEdgeColor',[.7,.7,.7],'UserData',clickTimes)
title(h51,['Based on ',num2str(length(xmppAll)),' clicks']);
% apply RMS threshold to figure (51)
% if (p.threshRMS > 0)
% if onerun == 1
% if p.threshPP > 0
% badClickTime = clickTimes(pxmspAll < p.threshRMS &...
% xmppAll' < p.threshPP); % for all false if below RMS threshold
% else
% badClickTime = clickTimes(pxmspAll < p.threshRMS);
% end
% disp(['Number of Detections Below RMS threshold = ',num2str(length(badClickTime))])
% zFD = [zFD; badClickTime]; % cummulative False Detection matrix
% save(fnameFD,'zFD')
% end
% if p.threshPP > 0
% xtline = [p.threshRMS,p.threshRMS]; ytline = [ min(xmppAll),p.threshPP];
% else
% xtline = [p.threshRMS,p.threshRMS]; ytline = [ min(xmppAll),max(xmppAll)];
% end
% hold(h51,'on');
% plot(h51,xtline,ytline,'r')
% hold(h51,'off');
% %p.threshRMS = 0;
% end
% plot RMS vs frequency plot, keeping RMS vertical like in fig(51)
freqAll = fmsp(im + fimint-1);
plot(h53,pxmspAll,freqAll,'o','MarkerEdgeColor',[.7,.7,.7],'UserData',clickTimes)
title(h53,['Based on total of ',num2str(length(freqAll)),' clicks']);
% apply High Frequency threshold to figure (53)
% if onerun == 1
% if (p.threshHiFreq > 0)
% badClickTime = clickTimes(freqAll > p.threshHiFreq); % for all false if below RMS threshold
% disp(['Number of Detections Below Freq threshold = ',num2str(length(badClickTime))])
% zFD = [zFD; badClickTime]; % cummulative False Detection matrix
% save(fnameFD,'zFD')
% %p.threshHiFreq = 0;
% end
% end
% if (p.threshHiFreq > 0)
% xtline = [min(pxmspAll),max(pxmspAll)]; ytline = [p.threshHiFreq ,p.threshHiFreq];
% hold(h53,'on');
% plot(h53,xtline,ytline,'r')
% hold(h53,'off');
% end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% find detections and false detections within this bout (session)
J = []; JFD =[]; Jtrue = []; XFD = []; JID = [];
J = find(clickTimes >= sb(k) & clickTimes <= eb(k));
if specploton && loadMSP
% have to load consecutive detections if reading from disk
J = J(1):J(end);
csnJ = csn(J,:);
cspJ = csp(J,:);
elseif specploton % only load the ones you need for this session
csnJ = inFileMat.MSN(keepers(J),:);
cspJ = inFileMat.MSP(keepers(J),:);
end
% get indices of test clicks in this session
XFD = [];
% XFD = find(clickTimes(testClickIdx) >= sb(k) &...
% clickTimes(testClickIdx) <= eb(k));
% zTD(k,1) = length(XFD);
%
% Test for XFD and strcmp('x or z or w') - if no test points skip
% x = true, z = false, w = window
% if (isempty(XFD) && (strcmp(cc,'x') || ...
% strcmp(cc,'z') || strcmp(cc,'w')));
% disp(' NO Test Detections, so skip')
% k = k + 1;
% continue
% end
if ~isempty(J) % if there are detection in this session
t = clickTimes(J); % detection times in this session
disp([' Detection times:',num2str(length(t))]);
if (~isempty(XFD))
xt = clickTimes(testClickIdx(XFD)); %times to test for False Detection
xPP = clickLevels(testClickIdx(XFD)); %amplitude for test False Detection
disp([' Test False Detection times:',num2str(zTD(k,1))]),
else
xt = [];
end
RL = clickLevels(J); % received levels in this session
nd = length(J); % number of detections in this session
% get false detection times that intersect with detection times
K2 = []; % holds false indices
ff2 = 0;
tfd = [];
if (~isempty(zFD)) % get times and indices of false detections
[tfd,K2,~] = intersect(t,zFD(:,1));
rlFD = RL(K2);
end
if ~isempty(K2) % if this session contains false detections
ff2 = 1; % set false flag to true
if specploton
wavFD = norm_wav(mean(csnJ(K2,:),1)); % calculate mean false time series
specFD = cspJ(K2,:); % get set of false spectra
end
disp([' False detections:',num2str(length(K2))])
else
ff2 = 0;
disp(' No False Detections')
end
% get ID'd detection times that intersect with detection times
K3 = []; % holds Id'd indices
ff3 = 0; % becomes positive if you have ID's detections in this session
tID = []; % times of ID'd detections
IDidx = [];
if ~isempty(zID)
[tID,K3,IDidx] = intersect(t,zID(:,1));
rlID = RL(K3);
end
if ~isempty(K3)
ff3 = 1;
spCodeSet = zID(IDidx,2); % get ID codes for everything in this session
specIDs = unique(spCodeSet); % get unique ID codes
if specploton % get mean spectra for each ID'd type
wavID = [];
specID = [];
for iSpID = 1:length(specIDs)
thisSet = spCodeSet == specIDs(iSpID);
wavID(iSpID,:) = norm_wav(mean(csnJ(K3(thisSet,:),:),1));
specID(iSpID,:) = mean(cspJ(K3(thisSet,:),:),1);
end
end
disp([' ID detections:',num2str(length(K3))])
else
ff3 = 0;
disp(' No identified detections (ID)')
end
% get MisID detection times that intersect with detection times
K4 = []; % holds MD'd indices
ff4 = 0; % becomes positive if you have MD's detections in this session
tMD = []; % times of MD'd detections
MDidx = [];
if ~isempty(zMD)
[tMD,K4,MDidx] = intersect(t,zMD(:,1));
rlMD = RL(K4);
end
if ~isempty(K4) % if this session contains mis-ID detections
ff4 = 1; % set false flag to true
if specploton
wavMD = norm_wav(mean(csnJ(K4,:),1)); % calculate mean MD series
specMD = cspJ(K4,:); % get set of MD spectra
end
disp([' MD detections:',num2str(length(K4))])
else
ff4 = 0;
disp(' No misidentified Detections (MD)')
end
% Calculate indices of detections which are neither false, ID'd,
% or MD
JFD = J(K2);
JID = J(K3);
JMD = J(K4);
JFIM = union(union(JFD,JID),JMD);
JFM = union(JFD,JMD);
[Jtrue,iJ,~]= setxor(J,JFIM); % find all true detections
%[JtrueWithID,~,~]= setxor(J,JFM); % find all true detections no ID
trueTimes = clickTimes(Jtrue);% vector of true times in this session
if specploton
cspJtrue = cspJ(iJ,:); % true spectra in this session
csnJtrue = csnJ(iJ,:); % true time series in this session
wtrue = norm_wav(nanmean(csnJtrue,1)); % mean of true spectra in this session
strue = nanmean(cspJtrue,1); % mean of true time series in this session
end
disp([' True Detections: ',num2str(length(trueTimes))])
else
disp('Error: no detections between bout start and end')
return
end
dt = diff(t)*24*60*60; % inter-detection interval (IDI) and convert from days to seconds
if ff2 % calculate IDI for false and id'd detections
dtFD = dt(K2(1:end-1));
end
if ff3
dtID = dt(K3(1:end-1));
end
if ff4
dtMD = dt(K4(1:end-1));
end
disp(['END SESSION: ',num2str(k),' Start: ',datestr(sb(k)),...
' End:',datestr(eb(k))])
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% calculate number of detections per bin
[KB,binCX,binT,binC] = ndets_per_bin(t,xt,RL,dt,minNdet,nd);
% filter empty and low number bins
if isempty(KB) % not sure what this case does?
disp(['No bins with at least ',num2str(minNdet),' detections'])
binT = 0;
binRL = 0;
binC = 0;
k = k + 1; % go to next
continue
end
if (strcmp(cc,'w') && (zTD(k,2) == 0))
disp(['Session: ',num2str(k),' # Test Detect Bins: ',...
num2str(length(binCX)),' but NO False']);
zTD(k,3) = length(binCX);
zTD(k,4) = 0;
save(fnameTD,'zTD');
k = k + 1;
continue
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Number detection per spectral bin in LTSA
% make a spectra in figure 50
PT = pt{1,k}; % LTSA session time vector
pwr1 = pwr{1,k}; % LTSA power vector
nbinS = length(PT);
if (nbinS == 0)
disp('No LTSA for this Session');
PT(1) = sb(k) ; PT(2) = eb(k); % start end times for plots
pwr1(1:length(f)) = ones; % make uniform LTSA
else
pwr1 = pwr1((1000*fiminLTSA/df)+1:round(1000*fimaxLTSA/df)+1,:);
end
durS = PT(end) - PT(1);
if specploton
% allSPEC = norm_spec(cspJ,fimint,fimint,fimaxt);
figure(50);clf;set(50,'name','Frequency Spectra')
h50 = gca;
figure(52);clf;set(52,'name','Waveform')
h52 = gca;
trueSpec = [];
if ~isempty(trueTimes)
% plot average true click spectrum
trueSpec = norm_spec_simple(cspJtrue,fimint,fimaxt);
plot(h50,ft,trueSpec,'Linewidth',4)
% average true click waveform
plot(h52, wtrue);
else
disp(['No true with at least ',num2str(minNdet),' detections'])
end
if ff2 % average false click spec
SPEC2 = norm_spec_simple(specFD,fimint,fimaxt);
% plot average false click spectrum
hold(h50, 'on')
plot(h50,ft,SPEC2,'r','Linewidth',4)
hold(h50, 'off')
% plot average false click waveform
hold(h52, 'on')
plot(h52,wavFD + 0.5 ,'r');
hold(h52, 'off')
end
if ff3 % average id click spec
specID_norm = [];
for iSpec = 1:size(specID,1)
specID_norm(iSpec,:) = norm_spec_simple(specID(iSpec,:),fimint,fimaxt);
end
% plot average ID'd click spectra
hold(h50, 'on')
hID = plot(h50,ft,specID_norm,'Linewidth',4);
hold(h50, 'off')
% plot average ID'd click waveform(s)
hold(h52, 'on')
hID2 = plot(h52,(wavID + repmat(-1*rand(size(hID)),1,length(wavID)))');
for iC = 1:length(hID) % set colors
set(hID(iC),'Color',colorTab(specIDs(iC),:))
set(hID2(iC),'Color',colorTab(specIDs(iC),:))
end
hold(h52, 'off')
end
if ff4 % average false click spec
SPEC4 = norm_spec_simple(specMD,fimint,fimaxt);
% plot average false click spectrum
hold(h50, 'on')
plot(h50,ft,SPEC4,'g','Linewidth',4)
hold(h50, 'off')
% plot average false click waveform
hold(h52, 'on')
plot(h52,wavMD + 1,'g');
hold(h52, 'off')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add detections of this session in figure 51 and 53
% for all detections in this session, calculate xmpp and xmsp
xmsp0 = cspJ + repmat(Ptfpp,size(cspJ,1),1); % add transfer fun to session's spectra
[xmsp,im] = max(xmsp0(:,fimint:fimaxt),[],2);
if isrow(RL)
xmpp = RL - tf + Ptfpp([im + fimint - 1]);
else
xmpp = RL' - tf + Ptfpp([im + fimint - 1]);
end
% turn diagonal to vertical
if ~isempty(xmsp) && ~isempty(xmpp)
if isrow(xmsp)
pxmsp = xmsp' - p.slope*(xmpp - p.threshRL); %use slope of 1 to mod xmsp for plot
elseif isrow(xmpp)
pxmsp = xmsp - p.slope*(xmpp' - p.threshRL);
else
pxmsp = xmsp - p.slope*(xmpp - p.threshRL);
end
end
% Plot PP versus RMS Plot for this session
hold(h51, 'on')
plot(h51,pxmsp,xmpp,'.','UserData',t)% true ones in blue
if ~loadMSP % plot threshold line now because no background data
% if (p.threshRMS > 0)
% if onerun == 1
% if p.threshPP > 0
% badClickTime = t(pxmsp < p.threshRMS &...
% xmpp' < p.threshPP); % for all false if below RMS threshold
% else
% badClickTime = t(pxmsp < p.threshRMS);
% end
% disp(['Number of Detections Below RMS threshold = ',num2str(length(badClickTime))])
% zFD = [zFD; badClickTime]; % cummulative False Detection matrix
% save(fnameFD,'zFD')
if ~isempty(zFD) % get times and indices of false detections
[tfd,K2,~] = intersect(t,zFD(:,1));
rlFD = RL(K2);
end
if ~isempty(K2) % if this session contains false detections
ff2 = 1; % set false flag to true
if specploton
wavFD = norm_wav(mean(csnJ(K2,:),1)); % calculate mean false time series
specFD = cspJ(K2,:); % get set of false spectra
end
dtFD = dt(K2(1:end-1));
disp([' False detections:',num2str(length(K2))])
else
ff2 = 0;
disp(' No False Detections')
end
% end
% end
% if p.threshPP > 0 && exist('plotaxes','var')
% xtline = [p.threshRMS,p.threshRMS]; ytline = [ plotaxes.minPP,p.threshPP];
% elseif p.threshPP > 0
% xtline = [p.threshRMS,p.threshRMS]; ytline = [ min(xmpp),p.threshPP];
% else
% xtline = [p.threshRMS,p.threshRMS]; ytline = [ min(xmpp),max(xmpp)];
% end
% plot(h51,xtline,ytline,'r')
end
if ff2 % false in red
plot(h51,pxmsp(K2),xmpp(K2),'r.','UserData',t(K2))
end
if ff3 % ID'd in associated color
for iC2 = 1:length(specIDs) % set colors
thisIDset = spCodeSet ==specIDs(iC2);
hPP = plot(h51,pxmsp(K3(thisIDset)),xmpp(K3(thisIDset)),'.','UserData',t(K3(thisIDset)));
set(hPP,'Color',colorTab(specIDs(iC2),:))
end
end
if ff4 % MD in green
plot(h51,pxmsp(K4),xmpp(K4),'g.','UserData',t(K4))
end
hold(h51, 'off')
% Plot RMS vs frequency plot for this session
hold(h53, 'on')
freq = fmsp(im + fimint -1);
plot(h53,pxmsp,freq,'.','UserData',t) % true ones in blue
if ~loadMSP
% if onerun == 1
% if (p.threshHiFreq > 0)
% badClickTime = t(freq > p.threshHiFreq); % for all false if below RMS threshold
% disp(['Number of Detections Below Freq threshold = ',num2str(length(badClickTime))])
% zFD = [zFD; badClickTime]; % cummulative False Detection matrix
% save(fnameFD,'zFD')
if ~isempty(zFD) % get times and indices of false detections
[tfd,K2,~] = intersect(t,zFD(:,1));
rlFD = RL(K2);
end
if ~isempty(K2) % if this session contains false detections
ff2 = 1; % set false flag to true
if specploton
wavFD = norm_wav(mean(csnJ(K2,:),1)); % calculate mean false time series
specFD = cspJ(K2,:); % get set of false spectra
end
disp([' False detections:',num2str(length(K2))])
dtFD = dt(K2(1:end-1));
else
ff2 = 0;
disp(' No False Detections')
end
% end
% end
% if p.threshHiFreq > 0 && exist('plotaxes','var')
% xtline = [plotaxes.minRMS,plotaxes.maxRMS]; ytline = [p.threshHiFreq ,p.threshHiFreq];
% elseif p.threshHiFreq > 0
% xtline = [min(pxmsp),max(pxmsp)]; ytline = [p.threshHiFreq ,p.threshHiFreq];
% end
% plot(h53,xtline,ytline,'r')
end
if ff2 % false in red
plot(h53,pxmsp(K2),freq(K2),'r.','UserData',t(K2))
end
if ff3 % ID'd in associated color
for iC2 = 1:length(specIDs) % set colors
thisIDset = spCodeSet ==specIDs(iC2);
hPP = plot(h53,pxmsp(K3(thisIDset)),freq(K3(thisIDset)),'.','UserData',t(K3(thisIDset)));
set(hPP,'Color',colorTab(specIDs(iC2),:))
end
end
if ff4 % MD in green
plot(h53,pxmsp(K4),freq(K4),'g.','UserData',t(K4))
end
hold(h53, 'off')
if p.threshHiFreq > 0
ylim(h53,[p.fLow ymax+10])
else
ylim(h53,[p.fLow ymax])
end
end
% add figure labels
xlabel(h50,'Frequency (kHz)');
grid(h50,'on')
xlim(h50, 'manual');
ylim(h50,[0 1]);
xlim(h50,[p.fLow,p.fHi])
xlabel(h51,'dB RMS')
ylabel(h51,'dB Peak-to-peak')
if exist('plotaxes','var')
xlim(h51,[plotaxes.minRMS,plotaxes.maxRMS])
ylim(h51,[plotaxes.minPP,plotaxes.maxPP])
end
xlabel(h52,'Time (1ms @ 200kHz)');
ylabel(h52,' Normalized Amplitude');
xlabel(h53,'dB RMS')
ylabel(h53,'Peak Frequency (kHz)')
if exist('plotaxes','var')
xlim(h53,[plotaxes.minRMS,plotaxes.maxRMS])
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% plots stuff now in figure(201)
warning('off')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure(201);clf
set(201,'name','LTSA and time series')
hA201 = subplot_layout; % Top panel, Figure 201: Received Level
plot(hA201(1),t,RL,'b.','UserData',t)
hold(hA201(1),'on')
if ff2 % plot False detections in red
plot(hA201(1),tfd,rlFD,'r.','UserData',tfd)
% disp([' false det plotted:',num2str(length(tfd))])
end
if ff3 % plot ID'd detections in associated color
spCodeSet = zID(IDidx,2); % get species codes for everything in this session
specIDs = unique(spCodeSet); % get unigue species codes
for iC2 = 1:length(specIDs) % set colors
thisIDset = spCodeSet ==specIDs(iC2);
hRLID = plot(hA201(1),tID(thisIDset),rlID(thisIDset),'.','UserData',tID(thisIDset));
set(hRLID,'Color',colorTab(specIDs(iC2),:))
end
end
if ff4 % plot MD detections in green
plot(hA201(1),tMD,rlMD,'g.','UserData',tfd)
end
hold(hA201(1),'off')
axis(hA201(1),[PT(1) PT(end) p.rlLow p.rlHi])
datetick(hA201(1),'x',15,'keeplimits')
grid(hA201(1),'on')
tstr(1) = {fnTPWS};
tstr(2) = {['Session: ',num2str(k),'/',num2str(nb),' Start Time ',...
datestr(sb(k)),' Detect = ',num2str(nd)]};
title(hA201(1),tstr);
ylabel(hA201(1),'RL [dB re 1\muPa]')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% middle panel LTSA
c = (p.ltsaContrast/100) .* pwr1 + p.ltsaBright;
image(PT,f/1000,c,'parent',hA201(2))
set(hA201(2),'yDir','normal')
axis(hA201(2),[PT(1) PT(end) p.ltsaLims])%v2(4)
ylabel(hA201(2),'Frequency (kHz)')
datetick(hA201(2),'keeplimits')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Bottom panel, Figure 201: Inter-Detection Interval
% make two copies of dt points for brush
tdt2 = [];
dt2 = [];
ldt = length(dt);
if ldt > 0
tdt2 = reshape([t(1:ldt),t((1:ldt)+1)]',2*ldt,1);
dt2 = reshape([dt,dt]',2*ldt,1);
[AX,H1,H2] = plotyy(hA201(3),tdt2,dt2,binT,binC,'plot','semilogy');
set(H1,'Marker','.','MarkerFaceColor','b','LineStyle','none','UserData',tdt2)
set(H2,'Marker','o','MarkerFaceColor','c','LineStyle','none',...
'Markersize',4.5,'UserData',dt2)
% Note: plotyy is buggy in 2012b, axis handles work only if called
% using "axes" and avoid calls to "subplot"
% Do setup for 1st axes
axis(AX(1),[PT(1) PT(end) 0 p.dtHi])
datetick(AX(1),'x',15,'keeplimits')
Ytick = 0:p.dtHi/10:p.dtHi; % make 0.05 Kogia, 0.2 BW
set(AX(1),'YTick',Ytick)
datetick(AX(1),'x',15,'keeplimits')
grid(AX(1),'on')
ylabel(AX(1),'Time between detections [s]')
% Do setup for 2nd axes
axis(AX(2),[PT(1), PT(end), 1, 100])
datetick(AX(2),'x',15,'keeplimits')
Ytick2 = [.1 1 10 100 1000 10000];
set(AX(2),'YTick',Ytick2)
ylabel(AX(2),'Det/bin')
xlabel(AX(2),'Time [GMT]')
title(AX(2),'Inter-Detection Interval (IDI)')
%grid(AX(2),'on')
%%% plot FD, ID, MD
hold(AX(1),'on')
if ff2
plot(AX(1),tfd(2:end),dtFD,'.r','UserData',tfd(2:end))