-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudioClip.m
2643 lines (2196 loc) · 101 KB
/
audioClip.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
classdef audioClip < handle
%AUDIOCLIP represent a segment of audiodata
% Detailed explanation goes here
properties
% + info - a struct containig info on the source with fields:
% * ratNum - rat serial number/id
% * paradigm - experimental paradigm
% * dayNum - day number of experiment
info = struct('fileName','',...
'filePath','',...
'ratNum',0,...
'paradigm','',...
'dayNum',0,...
'recordingMode','main',...
'subjectSex','male',...
'stimulusSex','',...
'stimulusAge','',...
'nameOfAnalyst','');
object_save_path = '' % hold the save place of the file
vec = []; % the audio vector, if this is empty, no plot is made
times_ = [];
fs = 2.5e5; % sampling rate of the audio vector
window = 512; % fft window length in bins
overlap = 128; % fft overlap length in bins
fft = 512; % number of DFT point also bins
threshold = -inf; % threshold - minimal value for spectrogram
clim = []; % color map limits, auto if empty
climMode = 'auto' % if clim is on auto, clim will be disregarded
stft = []; % short-time Fourier transform of the input signal
cyclicalF = []; % cyclicalF - cyclical frequencies
timeVec = []; % vector of time instants
psd = []; % psd vector
spectrogram_sample_rate = [];
max_bins_to_plot = 2.5e7; %Maximum number of bins to plot
emptyFlag = true; % empty flag, true if the object is empty
roiTable
triggerTime = 0;
sourceType = 'wav' %type of souce vector - wav or mat
vecSource = ''; %source of the vector, file of workspace
ylims;
absTime = 0; %If the clip was spliced from a bigger clip, this property saves the time
linkRoiTimesToFs = true %If true, changing sampling rate will also change time stamps.
detectionParameters = struct();
cleanSyllables = [];
probability_vector = array2timetable(nan,'RowTimes',duration(seconds(0))',"VariableNames",{'Probability'});
load_audio_vector_flag = false; %Determine if the audio vector will be loaded automatically when loading the file
audioLen = nan;
obj_snr =struct('mean_snr',nan,'local_snr',nan,'filtered_psd',nan)
end
properties (GetAccess = 'public', SetAccess = 'public')
addedTypeList = table('Size',[0,3],'VariableNames',{'Name','Color','Comments'},'VariableTypes',{'string','double','string'});
end
properties (Constant)
defaultDetectionParameters = struct('th',0.2,'smoothingK',4,'label',"USV-Auto",'fs',2.5e5,'y_lim',[80,118])
roiTypeList = cell2table(...
{"USV",[1,0,1],"";...
'Low',[1,1,0],"";...
"AC",[0,1,1],"";...
"22_khz_calls",[0.92941, 0.69412, 0.12549],"";...
"USV-Auto",[0,1,0],"AutoDetected USV";...
"Noise",[1,0,0],"Noise segments identified as USV";...
"FN",[0,0,0],"Missed syllables";...
"stimulusUSV",[0,0,1],"Syllables emitted by the stimulus rat";...
"subjectUSV",[0.5,0,1],"Syllables emitted by the subject rat";...
"possibly subjectUSV",[1,1,1],"AutoDetected USV by DeepSqueak";...
"Low_new",[1,0.5,0.5],"New found low vocalization"},...
'VariableNames',{'Name','Color','Comments'})
% roiTableTemplate = table('Size',[0,8],'VariableNames',{'Label','TimeStart','TimeEnd','FrLow','FrHigh','Duration',...
% 'SourcePath','Comments'},'VariableTypes',{'string','double','double','double','double','double','string','string'});
roiTableTemplate = table('Size',[0,9],'VariableNames',{'Label','TimeStart','TimeEnd','FrLow','FrHigh','Duration','Score'...
'SourcePath','Comments'},...
'VariableTypes',{'string','double','double','double','double','double','double','string','string'});
end
properties(Dependent)
summaryTable
audioLen_
allROIs
path
times
name
recordingMode %This can be either main or mini or sniffing, derived from the file info
timeVecAll % vector of time
number_of_detected
extended_roi_table
end
properties(SetAccess = 'private')
lastDetectionParameters = struct('th',0.4,'smoothingK',4,'label',"USV-Auto","fs",2.5e5,'y_lim',[80,118])
end
methods
function this = audioClip(S,dataIn)
this.roiTable = audioClip.roiTableTemplate;
if nargin==0
%AUDIOCLIP Construct an instance of this class
% Detailed explanation goes here
return
else
if isstruct(S)
this.fs = S.fs ;
this.roiTable = S.roiTable ;
this.times_ = S.times_ ;
this.triggerTime = S.triggerTime ;
this.ylims = S.ylims ;
this.absTime = S.absTime ;
this.sourceType = S.sourceType ;
this.clim = S.clim ;
this.climMode = S.climMode ;
this.window = S.window ;
this.fft = S.fft ;
this.overlap = S.overlap ;
this.addedTypeList = S.addedTypeList;
this.vec = S.vec ;
this.info = S.info ;
this.audioLen = S.audioLen;
this.obj_snr = S.obj_snr;
if isfield(S,'load_audio_vector_flag')
this.load_audio_vector_flag = S.load_audio_vector_flag;
end
if isfield(S,'probability_vector')
this.probability_vector = S.probability_vector;
end
else
if isvector(S)
this.vec = S;
this.audioLen = this.audioLen_;
end
if exist('dataIn','var')&&~isempty(dataIn)
this.info = dataIn;
end
end
this.emptyFlag = false;
end
end
function obj_copy = copyobj(obj,p, objtype)
if ~exist('objtype','var')
obj_copy = audioClip;
else
obj_copy = objtype;
end
if ~exist('p','var')||isempty(p)
p = properties(obj);
end
if ~iscell(p)
p = {p};
end
num_att = length(p);
for ip = 1:num_att
this_att = p{ip};
mp = findprop(obj_copy,this_att);
% Dont copy constants and dependant properties
if isempty(mp) || mp.Dependent || mp.Constant
continue
end
obj_copy.(this_att) = obj.(this_att);
end
end
function change_setting_to_low(obj,config)
if ~exist('config','var') || isempty(config)
config = struct;
config.ylims = [500, 25000];
config.window = 5000;
config.fft = 5000;
config.overlap = 4750;
end
if isfield(config,'ylims')
obj.ylims = config.ylims;
end
if isfield(config,'obj.window')
obj.obj.window = config.obj.window;
end
if isfield(config,'fft')
obj.fft = config.fft;
end
if isfield(config,'overlap')
obj.overlap = config.overlap;
end
if isfield(config,'clim')
obj.clim = config.clim;
end
end
function newObj = split_obj_by_time(obj,labels,times_range)
if isempty(obj)
newObj = audioClip;
return
end
if ~exist('labels','var')||isempty(labels)
labels = [];
end
if ~exist('times_range','var')||isempty(times_range)
times_range = [0, obj.audioLen_];
end
newObj = copyobj(obj);
newObj.vec = obj.getCurrentVec(times_range);
tab = obj.filtered_roi_table(labels,times_range);
tab.TimeStart = tab.TimeStart-times_range(1);
tab.TimeEnd = tab.TimeEnd-times_range(1);
newObj.refresh_audioLen;
newObj.times_ = [0,1];
newObj.roiTable = tab;
end
function labels_vector = get_labels_vector(obj,labels,output_length, output_fs)
if ~exist('labels','var')||isempty(labels)
labels = {};
end
if ~exist('output_length','var')||isempty(output_length)
output_length = numel(obj.vec);
end
if ~exist('output_fs','var')||isempty(output_fs)
output_fs = obj.fs;
end
tab = obj.filtered_roi_table(labels);
tab = tab{:,["TimeStart","TimeEnd"]};
labels_vector = create_logical_vec_from_table_v2(tab,output_length, output_fs);
end
function newObj = downsample_obj(obj,newFs)
newObj = copyobj(obj);
downvec = downsample_audio(obj.vec,obj.fs, newFs);
newObj.fs = newFs;
newObj.vec = downvec;
newObj.refresh_audioLen;
newObj.roiTable = obj.roiTable;
newObj.window = 1000;
newObj.overlap = 950;
newObj.fft = 1000;
newObj.ylims = [5 50];
end
function set.climMode(this,val)
%Set mode of clim
%Clim must be a char or string array with two possible values:
%'auto' or 'manual'
if ischar(val)||isstring(val)
switch val
case {'auto','manual'}
this.climMode = val;
otherwise
error('clim mode must be auto or manual')
end
else
error('invalid clim mode')
end
end
function set.audioLen(this,val)
if isempty(val)||val==0
val = this.audioLen_;
end
this.audioLen = val;
end
function len = get.audioLen_(this)
if isempty(this.vec)
len = nan;
else
len = numel(this.vec)/this.fs;
end
end
function [obj,sh,psd] = drawSpectrogram(obj,axSpect, axP)
%Draw a spectrogram and a normlized pds
% Draw plots and update plots accordingly
%{
Inputs:
axSpect - handel for axis on which to plot the spectrogram
axP - handel for axis on which to plot the power spectral density
dataIn - an instanse of audioClip class
Outputs:
sh - handel for surf plot of spectrogram
psd - handel for the line plot psd
dataOut - an instanse of audioClip class, updated
%}
if nargin==1
% Create figure
figure1 = figure;
% Create axes
axSpect = axes('Parent',figure1,...
'Position',[0.13 0.3 0.775 0.7]);
% Set the remaining axes properties
set(axSpect,'XTick',zeros(1,0));
% Create axes
axP = axes('Parent',figure1,...
'Position',[0.13 0.07 0.775 0.23]);
end
if isempty(obj.vec)
error ('Empty audio vector')
end
if obj.times(1)<0||obj.times(2)>obj.audioLen
error('Time range must be between %f and %f',0,obj.audioLen)
end
vectorInds = (1+obj.fs*obj.times(1)):(obj.fs*obj.times(2));
%Perform fft on audio vector
if ~isempty(obj.vec)
[s,f,t,ps] = spectrogram(obj.vec(vectorInds),obj.window,obj.overlap,obj.fft,obj.fs,'yaxis','MinThreshold',obj.threshold);
else
sh = [];
psd = [];
return
end
%Create plot with set threshold and clim
sh = surf(axSpect,log10(abs(s)),'EdgeColor','none');
view(axSpect,2);
if ~isempty(obj.clim)
axSpect.CLim = obj.clim;
end
%Create psd plot
psSum = smooth(sum(ps),0.01);
psSum = psSum./max(psSum);
psd = plot(axP,t,psSum);
%Make axes tight
axis(axSpect,'tight')
axis(axP,'tight')
%Update output values
obj.stft = s;
obj.cyclicalF = f;
obj.timeVec = t;
obj.psd = ps;
obj.spectrogram_sample_rate = numel(t)/(t(end)-t(1));
end
function tab = get.allROIs(obj)
added = obj.addedTypeList;
basicTypes = obj.roiTypeList;
if ~isempty(added)
tab = [basicTypes;added];
else
tab = basicTypes;
end
end
function tvec = get.timeVecAll(obj)
len = obj.audioLen;
fs_ = obj.fs;
n_bins = floor(len*fs_);
tvec = (0:(n_bins-1))./fs_;
end
function set.fs(obj,newFs)
%When changing the sampling rate, the time stamps should also be updated to match the new fs
oldFs = obj.fs;
obj.fs = newFs;
%If the roi table is empty, no need to update anything
%If there are any syllables in the roi table, all the time
%stamps should be updated accordingly to the new sampling rate
roiTab = obj.roiTable;
if isempty(roiTab)||~obj.linkRoiTimesToFs
return
end
roiTab.TimeStart = roiTab.TimeStart.*oldFs/newFs;
roiTab.TimeEnd = roiTab.TimeEnd.*oldFs/newFs;
obj.roiTable = roiTab;
obj.refresh_audioLen()
end
function set.linkRoiTimesToFs(obj,flag)
if islogical(flag)&&isscalar(flag)
obj.linkRoiTimesToFs = flag;
else
warning('input to obj.linkRoiTimesToFs must be logical scalar')
end
end
function ret = get.times(obj)
maxLen = inf;
if isempty(obj.times_)
ret(1,1) = 0;
ret(1,2) = min(obj.audioLen,1);
else
tempRet = obj.times_;
ret(1) = max(0,tempRet(1));
ret(2) = min(tempRet(2),obj.audioLen);
%Make sure the length doen't go over maxLen seconds
ret(2) = min(ret(2),ret(1)+maxLen);
end
end
function set.times_(obj,t)
% maxDisp = 20;
if isempty(t)
return
end
if isnumeric(t)&&(all(size(t) == [1,2]))
% if t(end)<=obj.audioLen&&t(1)>=0&&diff(t)<=maxDisp %#ok
% obj.times_ = t;
% end
% else
% error('Invalid time range')
obj.times_ = t;
end
end
function refresh_audioLen(self)
self.audioLen = self.audioLen_;
end
function switch_to_sniffing(self)
self.fs = 5000;
self.window = 10;
self.overlap = 8;
self.refresh_audioLen()
end
function set.roiTable(obj,input)
%I have added score variable to the table late, so make sure
%that older versions get nan values
if istable(input)
if ~contains('Score',input.Properties.VariableNames)
input.Score = nan(size(input,1),1);
end
elseif iscell(input)
if size(input,2) == 8
input = [input,num2cell(nan(size(input,1),2))] ;
end
end
try
[obj.roiTableTemplate;input]; %#ok
catch ME
error('Invalid roi table input')
end
obj.roiTable = input;
end
function ret = isempty(obj)
try
ret = obj.emptyFlag ;
catch
ret = true;
end
end
function set.ylims(obj,vals)
if all(size(vals)~=[1,2])||~isnumeric(vals)
% warning('ylims must be a 1x2 vector')
obj.ylims = [0,obj.fs/2]; %#ok
else
obj.ylims = vals;
end
end
function pram_current = get.lastDetectionParameters(this)
pram_default = this.detectionParameters;
pram_current = this.lastDetectionParameters;
default_filednames = fieldnames(pram_default);
for p =default_filednames'
p = p{:};
if ~isfield(pram_current,p)
prop = extractfield(pram_default,p);
pram_current.(p)= prop;
end
end
end
function pram_current = get.detectionParameters(this)
pram_default = this.defaultDetectionParameters;
pram_current = this.detectionParameters;
default_filednames = fieldnames(pram_default);
for p =default_filednames'
p = p{:};
if ~isfield(pram_current,p)
prop = extractfield(pram_default,p);
pram_current.(p) = prop;
end
end
end
function ret = get.path(obj)
ret = fullfile(obj.info.filePath,obj.info.fileName);
end
function change_folder(obj,new_folder,verbose)
if ~exist('verbose','var')
verbose = false;
end
obj.info.filePath = new_folder;
if verbose
disp('The path was changed to:')
disp(obj.path)
end
end
function set.addedTypeList(obj,input)
if isempty(input)
if ~isempty(obj)
%warning('Added roi list was deleted')
end
obj.addedTypeList(:,:) = [];
elseif istable(input)||iscell(input)
%If there is an attempt to add a label in the constant
%label list, dont add it and do not modify
constT = obj.roiTypeList;
newNames = input{:,1};
constNames = constT{:,1};
[~,TF] = setdiff(newNames,constNames);
input = input(TF,:);
if isempty(input)
return
end
newNames = reshape([input{:,1}],1,[]);
%If the new ori types allready exist in the variable,
%replace them with new comment and new color
t = obj.addedTypeList;
oldNames = [t{:,1}]';
[~,ia,ib] = union(newNames,oldNames);
t = [t(ib,:);input(ia,:)];
obj.addedTypeList = t;
else
error('Invalid input')
end
end
function ret = get.number_of_detected(obj)
roitab = obj.roiTable;
ret = size(roitab,1);
end
function set.probability_vector(obj,ret)
if isempty(ret)
return
end
if isa(ret,'timetable')
obj.probability_vector = ret;
return
end
try
prob_vec = ret.Probability;
catch
prob_vec = ret.prob_vec;
end
if isfield(ret,'detection_times')
detection_times = ret.detection_times;
else
detection_times = [];
end
if isempty(detection_times)
obj.probability_vector = [];
else
k = linspace(detection_times(1),detection_times(2),(numel(prob_vec)));
obj.probability_vector = array2timetable(prob_vec','RowTimes',duration(seconds(k))',"VariableNames",{'Probability'});
end
end
function recMode = get.recordingMode(obj)
recMode = obj.info.recordingMode;
end
function objName = get.name(obj)
thisName = obj.info.fileName;
if isempty(thisName)
objName = '';
return
end
[~,objName,~] = fileparts(thisName);
end
function refresh_info(obj)
obj.info = getRecodringDetailsFemales(obj.name,obj.path);
end
function exlTable = saveExcle(...
obj,...
namestring,...
folderName,...
subtractTriggerTime,...
saveFlag,...
refreshInfoFlag,...
tableType,...
fileType,...
fileName)
%{
inputs:
namestring - a string to add to the saved file, start the name with +
or - to add in front or name or before respectivly
folderName - save folder name, if empty, save at the pwd
subtractTriggerTime - if true, subtract the trigger time from all
timestamps
saveFlag - if true or empty, save the table to disk
refreshInfoFlag - if true, reload details from name, not relevant
tableType - chooce which table to save, roi for the regular
table, extended for extended table and
onlyTimeStamps to save only the time stamps
fileType - file type to save table, default : .exls
fileName - file name, if empty, same as the audio file
%}
if ~exist('saveFlag','var')||isempty(saveFlag)
saveFlag = true;
end
if ~exist('refreshInfoFlag','var')||isempty(refreshInfoFlag)
refreshInfoFlag = true;
end
if ~exist('subtractTriggerTime','var')||isempty(subtractTriggerTime)
subtractTriggerTime = true;
end
if ~exist('tableType','var')||isempty(tableType)
tableType = 'roi';
end
if ~exist('fileType','var')||isempty(fileType)
fileType = '.xlsx';
end
if ~exist('fileName','var')||isempty(fileName)
fileName = obj.name;
end
if nargin>1
if ~isempty(namestring)
if namestring(1)=='+'
fileName = [fileName,namestring(2:end)];
elseif namestring(1)=='-'
fileName = namestring(2:end);
else
fileName = [fileName,namestring];
end
end
end
%Add folder name, if empty, will be saved in present folder
if exist('folderName','var')&&~isempty(folderName)
if ~isfolder(folderName)
warning('folder %s doesnt exist',folderName)
else
fileName = fullfile(folderName,fileName);
end
end
%Prevent overwriting
fileNameCounter = 2;
fullfilename = [char(fileName),fileType];
while isfile(fullfilename)
fullfilename = sprintf('%s_%03d%s',fileName,fileNameCounter,fileType);
fileNameCounter = fileNameCounter+1;
end
%In some cases, the delais are missing, regather info to
%prevent errors
if refreshInfoFlag
obj.refresh_info;
end
%Add recording data
tab = obj.roiTable;
%Subtract trigger time
if subtractTriggerTime
tab.TimeStart = tab.TimeStart-obj.triggerTime;
tab.TimeEnd = tab.TimeEnd-obj.triggerTime;
end
switch tableType
case 'onlyTimeStamps'
temp_tab = table(tab.TimeStart,tab.TimeEnd,'VariableNames',{'time_start','time_end'});
tab = temp_tab;
case 'roi'
tab.ratNum = repmat({obj.info.ratNum},[size(tab,1),1]);
tab.recordingDay = repmat({obj.info.dayNum},[size(tab,1),1]);
tab.paradigme = repmat({obj.info.paradigm},[size(tab,1),1]);
tab.subjectSex = repmat({obj.info.subjectSex},[size(tab,1),1]);
tab.stimulusSex = repmat({obj.info.stimulusSex},[size(tab,1),1]);
tab.stimulusAge = repmat({obj.info.stimulusAge},[size(tab,1),1]);
tab.recordingMode = repmat({obj.recordingMode},[size(tab,1),1]);
tab.nameOfAnalyst = repmat({obj.info.nameOfAnalyst},[size(tab,1),1]);
%Move file info to front
vars = [9:16];
tab = movevars(tab,vars,'Before',1);
case 'extended'
tab = obj.extended_roi_table;
otherwise
error('The tableType parameter must be either onlyTimeStamps,roi or extended, but it was %s instead',tableType)
end
if saveFlag
writetable(tab,fullfilename)
end
if nargout>0
exlTable = tab;
end
end
function tabout = filtered_roi_table(obj,labels, times)
tabout = obj.roiTable;
if exist('labels', 'var')&&~isempty(labels)
inds_to_filter = any(tabout.Label== labels,2);
tabout = tabout(inds_to_filter,:);
end
if exist('times', 'var')&&~isempty(times)
inds_to_filter = all([tabout.TimeStart>= times(1),tabout.TimeEnd<= times(2)],2);
tabout = tabout(inds_to_filter,:);
end
end
function tabout = get.extended_roi_table(obj)
%Reconstcut table to match other programms
%{
Variables in table:
*. File_Name - this is important when combining several exl
files
*. File_Path
*.Id - serial number of specific usv
*. Label - the label given to a specific usv
*. Score - how sure the model is about this usv
*. Trigger_Time
*. Begin_Time - start of this usv
*. End_Time - end of this usv
*. USV_Length - duration of usv in sec
*. Mean_Freq
*. Low_Freq
*. High_Freq
*. Range_Freq
*. Local_SNR
*. Signal_amp
*. Signal_PSD
%}
tabout = cell2table({'','',zeros(0,1),'',zeros(0,1),zeros(0,1),zeros(0,1),zeros(0,1),zeros(0,125),zeros(0,125),zeros(0,1),zeros(0,1),zeros(0,1),zeros(0,1),...
zeros(0,1),zeros(0,1),zeros(0,1)},...
'VariableNames',{'File_Name','File_Path','Id','Label','Score','Local_SNR','Signal_amp','Signal_PSD','Filtered_PSD','Trigger_Time','Begin_Time','End_Time','USV_Length',...
'Mean_Freq','Low_Freq','High_Freq','Range_Freq'});
tabout(1,:) = [];
tabin = obj.roiTable;
sz = size(tabin,1);
if sz==0
return
end
File_Name = string(repmat(obj.info.fileName,[sz,1]));
File_Path = string(repmat(obj.info.filePath,[sz,1]));
Id = num2cell((1:sz)');
Label = tabin.Label;
Score = num2cell(tabin.Score);
Trigger_Time = num2cell(repmat(obj.triggerTime,[sz,1]));
Begin_Time = num2cell(tabin.TimeStart);
End_Time = num2cell(tabin.TimeEnd);
USV_Length = num2cell(tabin.Duration);
Mean_Freq = num2cell(mean([tabin.FrHigh,tabin.FrLow],2));
Low_Freq = num2cell(tabin.FrLow);
High_Freq = num2cell(tabin.FrHigh);
Range_Freq = num2cell(abs(tabin.FrHigh-tabin.FrLow));
Local_SNR = (obj.obj_snr.local_snr);
Sig_AMP = (obj.obj_snr.sig_amp);
Sig_psd = (obj.obj_snr.sig_psd);
Filtered_psd = obj.obj_snr.filtered_psd;
if size(Local_SNR,1)<sz
Local_SNR = nan(sz,1);
Sig_AMP = nan(sz,1);
Sig_psd = nan(sz,125);
Filtered_psd = nan(sz,125);
end
if isscalar(Filtered_psd)
Filtered_psd = nan(sz,125);
end
Local_SNR = num2cell(Local_SNR);
Sig_AMP = num2cell(Sig_AMP);
Sig_psd = num2cell(Sig_psd);
tabout = table(File_Name,File_Path,Id,Label,Score,Local_SNR,Sig_AMP,Sig_psd,Filtered_psd,Trigger_Time,Begin_Time,End_Time,USV_Length,Mean_Freq,Low_Freq,High_Freq,Range_Freq);
end
function tab = short_table_to_roiTable(obj,tab,x_offset, y_offset)
% y_offset - lift the box so it will not overlap
if ~exist('y_offset','var')
y_offset = 0;
end
% x_offset - compensate for the shift in time
if ~exist('x_offset','var')
x_offset = 0;
end
sz = size(tab,1);
isTableCol = @(t, thisCol) ismember(thisCol, t.Properties.VariableNames);
if isTableCol(tab,'FrLow')
FrLow = tab.FrLow;
FrHigh = tab.FrHigh;
else
FrLow = zeros(sz,1) + y_offset;
FrHigh = ones(sz,1)*20000 + y_offset;
end
if isTableCol(tab,'Label')
Label = tab.Label;
else
Label = repmat("undefined",[sz,1]);
end
TimeStart = tab.Onsets + x_offset;
TimeEnd = tab.Offsets + x_offset;
Duration = TimeEnd - TimeStart;
SourcePath = repmat({obj.path},size(TimeStart));
Comments = repmat("",size(TimeStart));
Score = nan(sz,1);
% tab = table(Label,TimeStart,TimeEnd,FrLow,FrHigh,Duration,AudioVector,SourcePath,Comments);
tab = table(Label,TimeStart,TimeEnd,FrLow,FrHigh,Duration,Score,SourcePath,Comments);
tab = sortrows(tab,{'TimeStart','Label'});
end
function [tab] = roi2table(obj,roilist)
if ~exist('roilist','var')||isempty(roilist)
tab = obj.roiTableTemplate;
return
end
if isa(roilist,'images.roi.Rectangle')
% if isvalid(roilist)
%
% end
Label = string(get(roilist,'Label'));
Score = nan(size(roilist));
%Clear numbers and spaces
LabelsNoNum = [];
for ilabel = 1:size(Label)
tempLabels = split(Label(ilabel),' ');
LabelsNoNum = [LabelsNoNum;tempLabels(1)]; %#ok
end
Label = LabelsNoNum;
positions = get(roilist,'Position');
if iscell(positions)
positions = cell2mat(positions);
end
elseif isstruct(roilist)&&isfield(roilist,'Positions')
Label = roilist.Label;
positions = roilist.Positions;
if contains('Score',roilist.tab.Properties.VariableNames)
Score = roilist.tab.Score;
else
Score = nan(size(roilist.tab,1),1);
end
else
tab = obj.roiTableTemplate;
return
end
TimeStart = positions(:,1);
TimeEnd = TimeStart + positions(:,3);
FrLow = positions(:,2);
FrHigh = FrLow + positions(:,4);
Duration = TimeEnd - TimeStart;
SourcePath = repmat({obj.path},size(TimeStart));
Comments = repmat("",size(TimeStart));
% tab = table(Label,TimeStart,TimeEnd,FrLow,FrHigh,Duration,AudioVector,SourcePath,Comments);
tab = table(Label,TimeStart,TimeEnd,FrLow,FrHigh,Duration,Score,SourcePath,Comments);
tab = sortrows(tab,{'TimeStart','Label'});
end
function obj = replaceRowsInTable(obj,tabIn,deleteAllFlag)
if ~isa(tabIn,'table')
tabIn = obj.roi2table(tabIn);
end
if ~exist('deleteAllFlag','var')
deleteAllFlag = false;
end
if deleteAllFlag
lables = unique(obj.roiTable.Label);
else
lables = unique(tabIn.Label);
end
%If there are number, remove them!
obj = obj.deleteRowsFromTableByRange(obj.times,lables);
obj = obj.addRowsToTable(tabIn);
% end
end
function obj = removeRowsFromTable(obj,lablesToRemove,rangesToRemove)
%Inputs : lables - labels of rows to remove
% ranges - time ranges of rows to remove
szLabels = size(lablesToRemove,1);
szRanges = size(rangesToRemove,1);
if szLabels~=szRanges
error('Sizes of lables and ranges must be equel')
end
if isempty(obj.roiTable)
return
end
lablesInObj = obj.roiTable.Label;
rangesInObj = obj.roiTable{:,{'TimeStart','TimeEnd'}};
indLabels = ismember(lablesInObj, lablesToRemove); %Find inds of tags
indStarts = ismember(rangesInObj(:,1), rangesToRemove(:,1));
indEndingss = ismember(rangesInObj(:,2), rangesToRemove(:,2));
%Remove rows where all identifiers are the same
indToRemove = all([indLabels,indStarts,indEndingss]);
obj.roiTable(indToRemove,:) = [];
end
function obj = addRowsToTable(obj,tabIn)
%Inputs : tabIn - table with data or roi object
if isempty(tabIn)
return
end
if isa(tabIn,'images.roi.Rectangle')||isa(tabIn,'matlab.graphics.GraphicsPlaceholder')
tabIn = obj.roi2table(tabIn);
end
if istable(tabIn)
if ~contains('Score',tabIn.Properties.VariableNames)
tabIn.Score = nan(size(tabIn,1),1);
end
elseif iscell(tabIn)
if size(tabIn,2) == 8
tabIn = [tabIn,num2cell(nan(size(tabIn,1),2))] ;
end
end
if isempty(obj.roiTable)
obj.roiTable = tabIn;
else
obj.roiTable = [obj.roiTable;tabIn];
obj.roiTable = sortrows(obj.roiTable,{'TimeStart','Label'});
end
end
function obj = clearRoiTable(obj,label)