-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDGTtool.m
1668 lines (1442 loc) · 61.8 KB
/
DGTtool.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 DGTtool < handle
%DGTtool: A simple and user-friendly tool for computing STFT/DGT.
% (MATLAB 2020b or later and Signal Processing Toolbox are required.)
%
%
% --- Quick start ---
%
% DGTtool provides an easy way to compute STFT/DGT.
% - 1st step: Construct a DGTtool object.
% F = DGTtool
% - 2nd step: Compute spectrogram X from a time-domain signal x.
% X = F(x);
% That's all for computing STFT/DGT.
%
% The following command reconstructs the time-domain signal.
% x = F.pinv(X);
% Note: The reconstructed signal may be longer than the original one.
%
%
% --- Parameter settings ---
%
% Parameters of STFT/DGT can be set as follows:
% F = DGTtool('windowShift',100,'windowLength',1000,'FFTnum',500)
%
% The acceptable parameters are
% 'windowShift' (positive integer)
% 'windowLength' (positive integer)
% 'FFTnum' (positive integer)
% 'windowName' (char or string)
% 'windowVector' (column vector)
%
% List of window names is given by typing DGTtool.windowList at the command line.
% Partial matching of leading characters is supported (case-insensitive).
%
% The order of parameters can be altered as follows:
% F = DGTtool('windowName','b','windowLength',1000,'windowShift',100)
%
% Note: MATLAB 2021a or later allows the Name=Value syntax:
% F = DGTtool(windowName='b', windowLength=1000, windowShift=100)
%
%
% --- Methods ---
%
% The following methods can be called as F.methodName(inputVars).
%
% DGTtool Methods:
% Forward Transforms
% subsref - Implemented for shortcut notation of DGT (F(x))
% DGT - Compute STFT/DGT (F(x) is shortcut of F.DGT(x))
% reassign - Compute sparse (reassigned) spectrogram
%
% Inverse transforms
% H - Inverse STFT/DGT (complex conjugate transpose of F)
% pinv - Inverse STFT/DGT with perfect reconstruction (pseudo-inverse of F)
%
% Plot functions
% plot - Draw spectrogram
% plotPhase - Visualize phase spectrogram
% plotReassign - Draw sparse (reassigned) spectrogram
%
% Window utilities
% setWindow - Change window
% makeWindowTight - Compute canonical tight window
% plotWin - Draw windows
%
% Phase manipulation
% makeZeroPhase - Remove linear phase component of window
% undoMakeZeroPhase - Cancel the effect of makeZeroPhase
% changeDGTdef - Convert DGT definition
% undoChangeDGTdef - Cancel the effect of changeDGTdef
%
%
% --- Static methods ---
%
% Static methods can be used without constructing a DGTtool object.
% To use them, type DGTtool.methodName with input/output arguments.
%
% DGTtool Methods:
% Window utilities
% windowList - Returns acceptable window names
% getWindow - Compute window
% computeCanonicalDual - Compute canonical dual window
% computeCanonicalTight - Compute canonical tight window
% computeNumericalDiffWin - Compute numerical differential
% isdual - Check whether a pair of windows is dual
%
% Zero-padding
% zeroPad - Add zero at the end of signals
% extendSignalByZeroPad - Add zero at the end of signals
% zeroPadForFactorDGT - Add zero at the end of signals
% sigLenForFactorDGT - Compute required signal length
%
%
% See the associated demo file (demo.m) for explanation and usage.
% See also DGTtool, DGT, pinv, plot
% Author: Kohei Yatabe (2021)
% [Memo]
% 2020b is required because of pagemtimes.
% 2019b might be enough for performing STFT/DGT (depending on settings).
% 2019b is required because of arguments.
% Signal Processing Toolbox is required because of buffer.
% Signal Processing Toolbox is required for Slepian and Chebyshev windows.
properties (Dependent)
redundancy % Ratio of number of time-frequency bins to signal length.
end
properties
shift % Amount of shift of window
FFTnum % Number of frequency bins in time-frequency domain
win % Column vector of window
dualWin % Column vector of dual window of win
end
properties (SetAccess = private)
diffWin % Differential of win
sigLen % Length of signal that is inputted last time
isDual = false % True when dualWin is dual of win
isCanonical = false % True when dualWin is canonical dual of win
end
properties (Hidden = true)
OLAindex
factorIdx
defConverter
zeroPhaseConverter
isNotCompDual = true
isNotWinCalcInDGT = true
end
methods % main
function obj = DGTtool(options)
%Constructor: Create a DGTtool object with given parameters.
% Parameters of STFT/DGT can be set through Name-Value pairs.
%
% Usage:
% F = DGTtool
% F = DGTtool(Name,Value)
% F = DGTtool(Name1,Value1,Name2,Value2,...)
%
% Name of options:
% 'windowShift' (positive integer, default = 256)
% 'windowLength' (positive integer, default = 2048)
% 'FFTnum' (positive integer, default = length(win))
% 'windowName' (char or string, default = '4termC5Nuttall')
% 'windowVector' (column vector)
%
% Acceptable window name:
% 'Hann'
% 'Blackman'
% '3termC1Nuttall'
% '3termC3Nuttall'
% '4termC1Nuttall'
% '4termC3Nuttall'
% '4termC5Nuttall'
% 'Gauss'
% 'Slepian'
% 'Chebyshev'
%
% Note: If windowVector is given, windowLength and windowName are ignored.
%
% See also windowList, setWindow, plotWin
arguments
options.windowShift (1,1) {mustBePositive,mustBeInteger} = 256
options.windowLength (1,1) {mustBePositive,mustBeInteger} = 2048
options.FFTnum (1,1) {mustBePositive,mustBeInteger}
options.windowVector (:,1) double
options.windowName char
end
if isfield(options,'windowVector')
obj.win = options.windowVector;
elseif isfield(options,'windowName')
[obj.win,obj.diffWin] = DGTtool.getWindow(options.windowLength,options.windowName);
else
[obj.win,obj.diffWin] = DGTtool.getWindow(options.windowLength,'4termC5Nuttall');
end
if isfield(options,'FFTnum')
obj.FFTnum = options.FFTnum;
else
obj.FFTnum = length(obj.win);
end
obj.shift = options.windowShift;
obj.factorIdx = struct('c',[],'d',[],'p',[],'q',[],'wIdx',[],'xIdx',[],'cIdx',[]);
end
function varargout = subsref(obj,data)
%SUBSREF: Shortcut for DGT.
% Parenthesis notation (operator form) calls DGT.
%
% Usage:
% X = F(x)
%
% See also DGT
% Note: F(x) is shortcut of subsref(F,struct('type','()','subs',{{x}}))
switch data(1).type
case '()' % Call DGT
% Many of validations are skipped for speed.
if length(data) ~= 1
error 'DGT must be performed as F(x)'
end
if numel(data.subs) ~= 1
warning 'Only one input is allowed. Others will be ignored.'
end
x = data.subs{1};
[varargout{1:nargout}] = DGT(obj,x);
case '.' % implemented for access to properties and methods
switch length(data)
case 1
[varargout{1:nargout}] = obj.(data.subs);
case 2
[varargout{1:nargout}] = obj.(data(1).subs)(data(2).subs{:});
otherwise % not implemented for now
error 'Unexpected usage!'
end
otherwise % not implemented for now
error 'Unexpected usage!'
end
end
function [X,f,t] = DGT(obj,x)
%DGT: Compute spectrogram by DGT.
% Parenthesis notation can be used for shortcut.
% Normalized frequency f and sample index t can be returned.
%
% Usage:
% X = F(x)
% [X,f,t] = F(x)
%
% Note: The following notation gives the same result.
% X = F.DGT(x)
% X = DGT(F,x)
%
% See also DGTtool, DGTtool/DGTtool, reassign
if obj.FFTnum < length(obj.win)
x = zeroPadForFactorAlg(obj,x,length(x));
end
if size(x,1) < length(obj.win)
setFlag_winCalcInDGT(obj)
obj.win = zeroPadForFactorAlg(obj,obj.win,length(obj.win));
x = zeroPadForFactorAlg(obj,x,length(obj.win));
end
useFactorizationAlgorithm = size(x,1) == length(obj.win);
if ~isequal(obj.sigLen,size(x,1))
if useFactorizationAlgorithm
c = lcm(obj.shift,obj.FFTnum);
else
c = obj.shift;
end
obj.sigLen = ceil(size(x,1)/c)*c;
end
if useFactorizationAlgorithm
if ~isequal(obj.sigLen,size(x,1))
x = zeroPadForFactorAlg(obj,x,obj.sigLen);
end
if ~isequal(obj.sigLen,length(obj.win))
obj.win = zeroPadForFactorAlg(obj,obj.win,obj.sigLen);
end
if factorIdxMismatch(obj.shift,obj.FFTnum,size(x,1)/obj.shift,obj.factorIdx)
computeIndexForFactorAlg(obj,size(x,1)/obj.shift,length(x),size(x,2));
end
if nargout > 1
[X,f,t] = DGT_factorAlg(x,obj.win,obj.shift,obj.FFTnum,obj.factorIdx);
else
X = DGT_factorAlg(x,obj.win,obj.shift,obj.FFTnum,obj.factorIdx);
end
else
if nargout > 1
[X,f,t] = DGT_usualAlg(x,obj.win,obj.shift,obj.FFTnum,obj.sigLen);
else
X = DGT_usualAlg(x,obj.win,obj.shift,obj.FFTnum,obj.sigLen);
end
end
end
function x = H(obj,X,sWin)
%H: Inverse DGT.
% Synthesis window can be specified. This function is complex
% conjugate transpose of DGT if a window is not specified.
%
% Usage:
% x = F.H(X)
% x = F.H(X,synthesisWindow)
%
% See also pinv, makeWindowTight
% Validation of input arguments is skipped for speed.
% By default, this function uses analysis window.
if ~exist('sWin','var')
sWin = obj.win;
end
signalLength = size(X,2)*obj.shift;
useFactorizationAlgorithm = signalLength <= length(sWin);
if useFactorizationAlgorithm
if length(sWin) ~= length(obj.win)
X = changeDGTdef(obj,X);
end
if length(sWin) ~= signalLength
sWin = zeroPadForFactorAlg(obj,sWin,length(sWin));
X = [X, X(:,1:(length(sWin)/obj.shift)-size(X,2),:)];
end
if isempty(obj.factorIdx) || sizeMismatch(obj.factorIdx,X) || factorIdxMismatch(obj.shift,obj.FFTnum,size(X,2),obj.factorIdx)
computeIndexForFactorAlg(obj,size(X,2),length(sWin),size(X,3));
end
x = invDGT_factorAlg(X,sWin,obj.shift,obj.FFTnum,obj.factorIdx);
else
if ~isequal(size(obj.OLAindex,1:3),[length(sWin) size(X,[2 3])])
computeIndexForOLA(obj,X,sWin);
end
x = invDGT_usualAlg(X,sWin,obj.FFTnum,obj.OLAindex);
end
obj.sigLen = size(x,1);
end
function x = pinv(obj,X)
%PINV: Inverse DGT with perfect reconstruction.
% Signal is reconstructed using canonical dual window.
%
% Usage:
% x = F.pinv(X)
%
% See also DGTtool, DGT, H, computeCanonicalDual
signalLength = size(X,2)*obj.shift;
if isempty(obj.dualWin) || ~obj.isDual || signalLength < length(obj.dualWin)
newLen = max(signalLength,length(obj.dualWin));
newLen = DGTtool.sigLenForFactorDGT(newLen,obj.shift,obj.FFTnum);
obj.dualWin = getCanonicalDualWin(obj,newLen);
end
if ~obj.isCanonical
warning 'This is not pseudoinverse because the given dual window is not canonical. Consider using F.H(x,F.dualWin) for non-canonical dual.'
end
useFactorizationAlgorithm = signalLength <= length(obj.dualWin);
x = H(obj,X,obj.dualWin);
if useFactorizationAlgorithm && length(obj.win) ~= length(obj.dualWin)
x = circshift(x,-length(obj.win)+obj.shift);
end
end
function [reassignedS,f,t,X,IF,GD,dXdt,dXdf] = reassign(obj,x,epsilon)
%REASSIGN: Compute reassigned spectrogram.
% Reassigned spectrogram is a sparse time-frequency representation.
%
% Usage:
% rS = F.reassign(x)
% rS = F.reassign(x,epsilon)
% [rS,f,t,X,IF,GD,dXdt,dXdf] = F.reassign(x)
%
% Input:
% x - Time-domain signal (column vectors)
% epsilon - Small number used for avoiding zero-division
%
% Output:
% rS - Reassigned spectrogram (non-negative valued)
% f - Normalized frequency (column vector)
% t - Time indices (row vector)
% X - Spectrogram (complex-valued)
% IF - Instantaneous frequency (time-derivative of phase)
% GD - Group delay (frequency-derivative of phase)
% dXdt - Time-derivative of spectrogram
% dXdf - Frequency-derivative of spectrogram
%
% See also plotReassign
arguments
obj
x (:,:) double
epsilon (1,1) double {mustBePositive} = 1e-12;
end
[~,maxIdx] = max(obj.win);
if (maxIdx - length(obj.win)/2) > 1
warning 'Window seems improper. Consider using F.setWindow.'
end
nWin = obj.win / sum(obj.win);
cg = centerOfGravity(nWin);
tRamp = (-length(nWin)/2:length(nWin)/2-1)' + mod(length(nWin),2)/2; % mod for odd/even cases
tRamp = circshift(tRamp,floor(cg)-floor(length(nWin)/2)-1);
tWin = tRamp .* nWin;
if isempty(obj.diffWin)
obj.sigLen = DGTtool.sigLenForFactorDGT(size(x,1),obj.shift,obj.FFTnum);
dWin = DGTtool.computeNumericalDiffWin(nWin,obj.sigLen) * obj.FFTnum / length(obj.win);
x = DGTtool.extendSignalByZeroPad(x,obj.sigLen);
tWin = DGTtool.extendSignalByZeroPad(tWin,obj.sigLen);
nWin = DGTtool.extendSignalByZeroPad(nWin,obj.sigLen);
else
obj.sigLen = ceil(size(x,1)/obj.shift) * obj.shift;
dWin = obj.diffWin * obj.FFTnum / length(obj.win) / sum(obj.win);
end
if size(x,1) < length(nWin) || size(x,1) < length(dWin)
error 'Signal is shorter than window.'
end
useFactorizationAlgorithm = obj.sigLen == length(dWin);
if useFactorizationAlgorithm
if factorIdxMismatch(obj.shift,obj.FFTnum,size(x,1)/obj.shift,obj.factorIdx)
computeIndexForFactorAlg(obj,size(x,1)/obj.shift,length(x),size(x,2));
end
[X,f,t] = DGT_factorAlg(x,nWin,obj.shift,obj.FFTnum,obj.factorIdx);
dXdt = DGT_factorAlg(x,dWin,obj.shift,obj.FFTnum,obj.factorIdx);
dXdf = DGT_factorAlg(x,tWin,obj.shift,obj.FFTnum,obj.factorIdx);
else
[X,f,t] = DGT_usualAlg(x,nWin,obj.shift,obj.FFTnum,obj.sigLen);
dXdt = DGT_usualAlg(x,dWin,obj.shift,obj.FFTnum,obj.sigLen);
dXdf = DGT_usualAlg(x,tWin,obj.shift,obj.FFTnum,obj.sigLen);
end
S = abs(X).^2;
Splus = S + epsilon;
IF = -imag(dXdt.*conj(X)./Splus);
GD = real(dXdf.*conj(X)./Splus);
fNew = f*obj.FFTnum + IF;
tNew = t + GD;
fNewIdx = round(fNew(:)) + 1;
tNewIdx = round(tNew(:)/obj.shift);
tNewIdx = mod(tNewIdx,size(X,2)) + 1;
idx = (fNewIdx >= 1) & (fNewIdx <= size(X,1));
chIdx = ones(size(X)) .* reshape(1:size(X,3),1,1,[]);
reassignedS = accumarray([fNewIdx(idx) tNewIdx(idx) chIdx(idx)], S(idx), size(X,1:3));
if nargin > 1
t = mod(t,size(X,2)*obj.shift);
[~,tRot] = min(t);
X = circshift(X,-tRot+1,2);
IF = circshift(IF,-tRot+1,2);
GD = circshift(GD,-tRot+1,2);
dXdt = circshift(dXdt,-tRot+1,2);
dXdf = circshift(dXdf,-tRot+1,2);
t = circshift(t,-tRot+1);
end
end
function setWindow(obj,windowLength,windowName,varargin)
%setWindow: Set a new window (current window is deleted).
% All input variables are directly passed to DGTtool.getWindow.
%
% Usage:
% F.setWindow(windowLength,windowName)
% F.setWindow(___,Name,Value)
%
% See also getWindow, plotWin
[obj.win,obj.diffWin] = DGTtool.getWindow(windowLength,windowName,varargin{:});
end
function makeWindowTight(obj,signalLength)
%makeWindowTight: Replace window by its canonical tight window.
% Canonical tight window makes F.H(X) and F.pinv(X) equal.
% Signal length must be specified whenever FFTnum < winLen.
%
% Usage:
% F.makeWindowTight
% F.makeWindowTight(signalLength)
%
% See also computeCanonicalTight, plotWin
if ~exist('signalLength','var')
signalLength = max(obj.sigLen,length(obj.win));
else
signalLength = max(signalLength,length(obj.win));
obj.sigLen = ceil(signalLength/obj.shift)*obj.shift;
end
if isempty(signalLength)
if obj.FFTnum < length(obj.win)
error 'Must specify signal length, e.g., F.makeWindowTight(length(x)).'
else
signalLength = length(obj.win);
end
end
obj.win = DGTtool.computeCanonicalTight(obj.win,obj.shift,obj.FFTnum,signalLength);
obj.dualWin = obj.win;
end
function X = changeDGTdef(obj,X)
%changeDGTdef: Phase is modified to change definition of DGT.
%
% Usage:
% X = F.changeDGTdef(X)
%
% See also undoChangeDGTdef
if ~isequal(size(obj.defConverter),size(X,1:2))
obj.defConverter = calculateDefConverter(X,obj.shift,obj.FFTnum);
end
X = X .* obj.defConverter;
end
function X = undoChangeDGTdef(obj,X)
%undoChangeDGTdef: Reset phase modified by changeDGTdef.
%
% Usage:
% X = F.undoChangeDGTdef(X)
%
% See also changeDGTdef
if ~isequal(size(obj.defConverter),size(X,1:2))
error 'Parameters seem different.'
end
X = X .* conj(obj.defConverter);
end
function X = makeZeroPhase(obj,X)
%makeZeroPhase: Phase is modified to remove linear phase component of window.
%
% Usage:
% X = F.makeZeroPhase(X)
%
% See also undoMakeZeroPhase
if ~isequal(size(obj.zeroPhaseConverter,1),size(X,1))
obj.zeroPhaseConverter = calculateZeroPhaseConverter(X,obj.FFTnum,obj.win);
end
X = X .* obj.zeroPhaseConverter;
end
function X = undoMakeZeroPhase(obj,X)
%undoMakeZeroPhase: Reset phase modified by makeZeroPhase.
%
% Usage:
% X = F.undoMakeZeroPhase(X)
%
% See also makeZeroPhase
if ~isequal(size(obj.zeroPhaseConverter,1),size(X,1))
error 'Parameters seem different.'
end
X = X .* conj(obj.zeroPhaseConverter);
end
end
methods % plot
function plot(obj,x,fs,options)
%PLOT: Compute spectrogram and display it.
% Signal and spectrum are also displayed.
%
% Usage:
% F.plot(x)
% F.plot(x,fs)
% F.plot(___,Name,Value)
%
% Options:
% 'range' (number, default = 80 [dB])
% 'trunc' (number, default = 0 [dB])
% 'normalize' (true/false, default = true)
%
% See also plotPhase, plotReassign, DGT
arguments
obj
x (:,:) {mustBeNumeric,mustBeSkinny}
fs (1,1) {mustBePositive} = 1
options.range = 80
options.trunc = 0
options.normalize = true
end
if options.normalize
normConst = sum(obj.win) / 2;
else
normConst = 1;
end
[X,f,t] = DGT(obj,x);
X = X / normConst;
t = mod(t,size(X,2)*obj.shift);
[~,tRot] = min(t);
X = circshift(X,-tRot+1,2);
t = circshift(t,-tRot+1);
if fs == 1
fsPlot = fs;
fUnit = '[periods/sample]';
tUnit = '[samples]';
else
fsPlot = fs/1000;
f = f*fsPlot;
t = t/fs;
fUnit = '[kHz]';
tUnit = '[s]';
end
for n = 1:size(X,3)
s = 20*log10(abs(fft(x(:,n)/normConst)));
xLonger = buffer(x(:,n),size(X,2)*obj.shift);
figure
tiledlayout(10,14,'TileSpacing','none','Padding','compact')
ax_s = nexttile(1,[8 2]);
plot(s(1:floor(length(s)/2)+1),(0:floor(length(s)/2))/length(s)*fsPlot)
xlim(max(s)-[options.range 0]-options.trunc)
ylim([0 floor(length(s)/2)/length(s)*fsPlot])
set(gca,'FontSize',10,'xDir','reverse')
ylabel(['Frequency ' fUnit],'FontSize',12)
ax_X = nexttile(3,[8 12]);
imagesc(t,f,20*log10(abs(X(:,:,n))))
axis xy off
caxis(max(caxis)-[options.range 0]-options.trunc)
xlim([0 size(x,1)-1]/fs)
ylim([0 floor(length(s)/2)/length(s)*fsPlot])
ax_x = nexttile(115,[2 12]);
plot((0:length(xLonger)-1)/fs,xLonger)
axis tight
xlim([0 size(x,1)-1]/fs)
set(gca,'FontSize',10)
yticks(0)
yline(0)
xlabel(['Time ' tUnit],'FontSize',12)
nexttile(127,[1 1])
image([-1 1],ax_X.CLim,reshape(colormap,[],1,3))
axis xy
set(gca,'FontSize',10)
xticks([])
ylabel('Power [dB]','FontSize',11)
linkaxes([ax_X ax_x],'x')
linkaxes([ax_X ax_s],'y')
end
end
function plotPhase(obj,x,fs,options)
%plotPhase: Visualize phase.
% Color and brightness represent phase and magnitude, respectively.
% F.makeZeroPhase is applied for better visibility.
%
% Usage:
% F.plotPhase(x)
% F.plotPhase(x,fs)
% F.plotPhase(___,Name,Value)
%
% Options:
% 'range' (number, default = 40 [dB])
% 'trunc' (number, default = 15 [dB])
% 'normalize' (true/false, default = true)
%
% See also plot, plotReassign, makeZeroPhase
arguments
obj
x (:,:) {mustBeNumeric,mustBeSkinny}
fs (1,1) {mustBePositive} = 1
options.range = 40
options.trunc = 15
options.normalize = true
end
if options.normalize
normConst = sum(obj.win) / 2;
else
normConst = 1;
end
[X,f,t] = DGT(obj,x);
X = X / normConst;
X = makeZeroPhase(obj,X);
t = mod(t,size(X,2)*obj.shift);
[~,tRot] = min(t);
X = circshift(X,-tRot+1,2);
t = circshift(t,-tRot+1);
if fs == 1
fsPlot = fs;
fUnit = '[periods/sample]';
tUnit = '[samples]';
else
fsPlot = fs/1000;
f = f*fsPlot;
t = t/fs;
fUnit = '[kHz]';
tUnit = '[s]';
end
for n = 1:size(X,3)
A = 20*log10(abs(X(:,:,n)));
maxC = max(A(:)) - options.trunc;
minC = maxC - options.range;
A = rescale(A,'InputMin',minC,'InputMax',maxC);
P = rescale(angle(X(:,:,n)),'InputMin',-pi,'InputMax',pi);
C = hsv2rgb(cat(3,P,ones(size(X(:,:,n))),A));
s = 20*log10(abs(fft(x(:,n)/normConst)));
xLonger = buffer(x(:,n),size(X,2)*obj.shift);
figure
tiledlayout(10,14,'TileSpacing','none','Padding','compact')
ax_s = nexttile(1,[8 2]);
plot(s(1:floor(length(s)/2)+1),(0:floor(length(s)/2))/length(s)*fsPlot)
xlim(max(s)-[options.range 0]-options.trunc)
ylim([0 floor(length(s)/2)/length(s)*fsPlot])
set(gca,'FontSize',10,'xDir','reverse')
ylabel(['Frequency ' fUnit],'FontSize',12)
ax_X = nexttile(3,[8 12]);
image(t,f,C)
axis xy off
xlim([0 size(x,1)-1]/fs)
ylim([0 floor(length(s)/2)/length(s)*fsPlot])
ax_x = nexttile(115,[2 12]);
plot((0:length(xLonger)-1)/fs,xLonger)
axis tight
xlim([0 size(x,1)-1]/fs)
set(gca,'FontSize',10)
yticks(0)
yline(0)
xlabel(['Time ' tUnit],'FontSize',12)
nexttile(127,[1 1])
image([-1 1],[minC maxC],hsv2rgb(cat(3,repmat(linspace(0,1,64),128,1),ones(128,64),repmat(linspace(0,1,128)',1,64))))
axis xy
set(gca,'FontSize',10)
xticks(-1:1)
xticklabels({'-\pi',0,'\pi'})
xtickangle(0)
xlabel('Phase [rad]','FontSize',11)
ylabel('Power [dB]','FontSize',11)
linkaxes([ax_X ax_x],'x')
linkaxes([ax_X ax_s],'y')
end
end
function plotReassign(obj,x,fs,options)
%plotReassign: Compute reassigned spectrogram and display it.
% Resolution of reassigned spectrogram depends on shift and FFTnum.
%
% Usage:
% F.plotReassign(x)
% F.plotReassign(x,fs)
% F.plotReassign(___,Name,Value)
%
% Options:
% 'range' (number, default = 100 [dB])
% 'trunc' (number, default = 0 [dB])
% 'normalize' (true/false, default = true)
%
% See also plot, plotPhase, reassign
arguments
obj
x (:,:) {mustBeNumeric,mustBeSkinny}
fs (1,1) {mustBePositive} = 1
options.range = 100
options.trunc = 0
options.normalize = true
end
[X,f,t] = reassign(obj,x);
if options.normalize
normConst = sum(obj.win);
else
normConst = 1;
X = X * sum(obj.win);
end
t = mod(t,size(X,2)*obj.shift);
[~,tRot] = min(t);
X = circshift(X,-tRot+1,2);
t = circshift(t,-tRot+1);
if fs == 1
fsPlot = fs;
fUnit = '[periods/sample]';
tUnit = '[samples]';
else
fsPlot = fs/1000;
f = f*fsPlot;
t = t/fs;
fUnit = '[kHz]';
tUnit = '[s]';
end
for n = 1:size(X,3)
s = 20*log10(abs(fft(x(:,n)/normConst)));
xLonger = buffer(x(:,n),size(X,2)*obj.shift);
figure
tiledlayout(10,14,'TileSpacing','none','Padding','compact')
ax_s = nexttile(1,[8 2]);
plot(s(1:floor(length(s)/2)+1),(0:floor(length(s)/2))/length(s)*fsPlot)
xlim(max(s)-[options.range 0]-options.trunc)
ylim([0 floor(length(s)/2)/length(s)*fsPlot])
set(gca,'FontSize',10,'xDir','reverse')
ylabel(['Frequency ' fUnit],'FontSize',12)
ax_X = nexttile(3,[8 12]);
imagesc(t,f,20*log10(abs(X(:,:,n))))
axis xy off
caxis(max(caxis)-[options.range 0]-options.trunc)
xlim([0 size(x,1)-1]/fs)
ylim([0 floor(length(s)/2)/length(s)*fsPlot])
ax_x = nexttile(115,[2 12]);
plot((0:length(xLonger)-1)/fs,xLonger)
axis tight
xlim([0 size(x,1)-1]/fs)
set(gca,'FontSize',10)
yticks(0)
yline(0)
xlabel(['Time ' tUnit],'FontSize',12)
nexttile(127,[1 1])
image([-1 1],ax_X.CLim,reshape(colormap,[],1,3))
axis xy
set(gca,'FontSize',10)
xticks([])
ylabel('Power [dB]','FontSize',11)
linkaxes([ax_X ax_x],'x')
linkaxes([ax_X ax_s],'y')
end
end
function plotWin(obj)
%plotWin: Display currently available windows.
% Some windows may not appear if they are not calculated yet.
%
% Usage:
% F.plotWin
%
% See also setWindow, getWindow
h = figure;
h.Position(4) = h.Position(4)/2;
tiledlayout(1,3,'TileSpacing','compact','Padding','compact')
nexttile
windowStylePlot(obj.win)
title('window','FontSize',12)
nexttile
windowStylePlot(obj.dualWin)
title('dual window','FontSize',12)
nexttile
windowStylePlot(obj.diffWin)
title('differential window','FontSize',12)
end
end
methods (Static)
function winList = windowList
%winList: List of window names acceptable in DGTtool.
%
% Usage:
% c = DGTtool.windowList
%
% See also getWindow, DGTtool, DGTtool/DGTtool
winList = {
'Hann'
'Blackman'
'3termC1Nuttall'
'3termC3Nuttall'
'4termC1Nuttall'
'4termC3Nuttall'
'4termC5Nuttall'
'Gauss'
'Slepian'
'Chebyshev'
};
end
function [win,diffWin] = getWindow(windowLength,windowName,options)
%getWindow: Compute specified window.
% Windows are returned as column vectors.
%
% Usage:
% win = DGTtool.getWindow(windowLength,windowName)
% [win,diffWin] = DGTtool.getWindow(___)
%
% Acceptable window name (shortcut):
% 'Hann' ('h')
% 'Blackman' ('b')
% '3termC1Nuttall' ('3termC1')
% '3termC3Nuttall' ('3termC3')
% '4termC1Nuttall' ('4termC1')
% '4termC3Nuttall' ('4termC3')
% '4termC5Nuttall' ('4termC5')
% 'Gauss' ('g')
% 'Slepian' ('s')
% 'Chebyshev' ('c')
%
% For 'Gauss', 'Slepian' and 'Chebyshev', options can be set.
% win = DGTtool.getWindow(___,Name,Value)
%
% Options (width parameters):
% 'Gauss' (number, default = 0.02)
% 'Slepian' (number, default = 12)
% 'Chebyshev' (number, default = 340 [dB])
%
% see also DGTtool, DGTtool/DGTtool, setWindow
arguments
windowLength (1,1) {mustBePositive,mustBeInteger}
windowName char
options.Gauss (1,1) {mustBePositive} = 0.02
options.Slepian (1,1) {mustBePositive} = 12
options.Chebyshev (1,1) {mustBePositive} = 340
end
winList = DGTtool.windowList;
winName = validatestring(windowName,winList);
isodd = mod(windowLength,2); % 1 (if odd) or 0 (if even)
K = windowLength + isodd; % always even
if ismember(winName,winList(1:7)) % cosine window case
switch winName
case 'Hann'
c = [0.5; 0.5];
case 'Blackman'
c = [0.42; 0.5; 0.08];
case '3termC1Nuttall'
c = [0.40897; 0.5; 0.09103];
case '3termC3Nuttall'
c = [3; 4; 1]/8;
case '4termC1Nuttall'
c = [0.355768; 0.487396; 0.144232; 0.012604];
case '4termC3Nuttall'
c = [0.338946; 0.481973; 0.161054; 0.018027];
case '4termC5Nuttall'
c = [10; 15; 6; 1]/32;
end
t = (-(K/2-1):(K/2-1))' / K; % always odd (-0.5 < t < 0.5)
win = cos(2*pi*t.*(0:length(c)-1)) * c;
if nargout == 2
diffC = (0:length(c)-1)' .* c;
diffWin = -sin(2*pi*t.*(0:length(c)-1)) * diffC;
end
else % other case
switch winName
case 'Gauss'
t = (-(K/2-1):(K/2-1))' / K;
win = exp(-pi*t.^2/options.Gauss);
case 'Slepian'
win = dpss(K-1,options.Slepian,1); % Signal Processing Toolbox
win = win / max(win);
case 'Chebyshev'
win = chebwin(K-1,options.Chebyshev); % Signal Processing Toolbox
end
if nargout == 2
if isequal(winName,'Gauss')
diffWin = -exp(-pi*t.^2/options.Gauss).*t/options.Gauss;
elseif win(1) < eps * length(win)
diffWin = DGTtool.computeNumericalDiffWin(win,2^nextpow2(2*length(win)));
diffWin = diffWin(1:length(win));
else
diffWin = [];
end
end