├── Fig13_Fig15 ├── Copy_of_doa_cvnn_module_CP10.m ├── Copy_of_doa_cvnn_module_test_CP10.m ├── EchoSignalGen.m ├── OMP.m ├── __pycache__ │ ├── complexFunctions.cpython-36.pyc │ ├── complexLayers.cpython-36.pyc │ ├── complexModules.cpython-36.pyc │ ├── fr.cpython-36.pyc │ └── util.cpython-36.pyc ├── bz.h5 ├── cResFreq_epoch_60.pth ├── complexFunctions.py ├── complexLayers.py ├── complexModules.py ├── data1_resfreq.mat ├── deepfreq_epoch_120.pth ├── deepfreq_model.py ├── fr.py ├── main.asv ├── main.m ├── main2_bak.m ├── main_old.m ├── matlab_imag2.h5 ├── matlab_real2.h5 ├── modules.py ├── readme ├── real_data.asv ├── real_data.m ├── resfreq_model.py ├── tight_subplot.m └── util.py ├── Fig1_Fig4 ├── Copy_of_doa_cvnn_module_CP10.m ├── Copy_of_doa_cvnn_module_test_CP10.m ├── OMP.m ├── __pycache__ │ ├── complexFunctions.cpython-36.pyc │ ├── complexLayers.cpython-36.pyc │ ├── complexModules.cpython-36.pyc │ ├── fr.cpython-36.pyc │ ├── modules.cpython-36.pyc │ └── util.cpython-36.pyc ├── cResFreq.m ├── cResFreq_epoch_60.pth ├── complexFunctions.py ├── complexLayers.py ├── complexModules.py ├── cvnn.m ├── data1_deepfreq.mat ├── data1_resfreq.mat ├── deepfreq.m ├── deepfreq_390.pth ├── deepfreq_epoch_120.pth ├── deepfreq_model.py ├── epoch_390.pth ├── epoch_50.pth ├── fr.py ├── matlab_imag1.h5 ├── matlab_imag2.h5 ├── matlab_real1.h5 ├── matlab_real2.h5 ├── modules.py ├── music.fig ├── music.m ├── noisedSig_0dB.mat ├── noisedSig_20dB.mat ├── omp_main.m ├── plot_figure.m ├── prdgrm.m ├── readme ├── resfreq_390.pth ├── resfreq_model.py ├── tight_subplot.m └── util.py ├── Fig9 ├── Copy_of_doa_cvnn_module_CP10.m ├── Copy_of_doa_cvnn_module_test_CP10.m ├── Fig9_main_sidelobe_main.m ├── OMP.m ├── cResFreq_epoch_60.pth ├── complexFunctions.py ├── complexLayers.py ├── complexModules.py ├── deepfreq_epoch_120.pth ├── deepfreq_model.py ├── fr.py ├── modules.py ├── readme ├── resfreq_model.py ├── tight_subplot.m └── util.py ├── Python codes └── RDN-1D │ ├── ACCURACY.py │ ├── Copy_of_doa_cvnn_module_CP10.m │ ├── Copy_of_doa_cvnn_module_test_CP10.m │ ├── checkpoint │ ├── deepfreq_norm_snr40_big8 │ │ ├── fr │ │ │ └── deepfreq_epoch_120.pth │ │ ├── run.args │ │ └── run.log │ ├── freq_train_big8 │ │ ├── events.out.tfevents.1615898021.DESKTOP-C7QQ9IB.31392.0 │ │ ├── fr │ │ │ └── epoch_140.pth │ │ ├── run.args │ │ └── run.log │ └── skipfreq_snr_big8 │ │ ├── fr │ │ └── epoch_60.pth │ │ ├── run.args │ │ └── run.log │ ├── complexFunctions.py │ ├── complexLayer1Train.py │ ├── complexLayers.py │ ├── complexModules.py │ ├── complexTrain.py │ ├── cvnn_func.m │ ├── data │ ├── data.py │ ├── dataset.py │ ├── fr.py │ ├── loss.py │ ├── noise.py │ └── source_number.py │ ├── modules.py │ └── util.py └── README.md /Fig13_Fig15/Copy_of_doa_cvnn_module_CP10.m: -------------------------------------------------------------------------------- 1 | 2 | function [wHI, wOH, zO_set] = Copy_of_doa_cvnn_module_CP10 (zI_set, zO_teach_set) 3 | len=size(zI_set,3); 4 | bsz=size(zI_set,1); 5 | sizeI=size(zI_set,2); 6 | sizeH=12; 7 | sizeO=1; 8 | TDL_n=29; 9 | fc=500e3; 10 | k1= 0.1; % learning constant 11 | k2= 0.1; 12 | Ts=1e-7; 13 | rng('default') 14 | 15 | wHI = rand(sizeH, sizeI); 16 | wOH = rand(sizeO, sizeH); 17 | wHI(:,1)=1; 18 | wOH(:,1)=1; 19 | 20 | % Power inversion initiation 21 | % zI=zI_set; 22 | % Rxx=squeeze(zI(1,:,:))*squeeze(zI(1,:,:))'/8; 23 | % S=[1,0,0,0,0,0,0,0]'; 24 | % Wopt=Rxx\S; 25 | % Wopt=Wopt/abs(Wopt(1)); 26 | % for j=1:sizeH 27 | % for nn=1:TDL_n 28 | % wHI(j,:,nn)=Wopt; 29 | % end 30 | % end 31 | % wOH_amp=randn(sizeO, sizeH, TDL_n); 32 | % wOH_phase=randn(sizeO, sizeH, TDL_n); 33 | % wOH =wOH_amp.*exp(1i*wOH_phase); 34 | % wHI(:,:,1)=1; 35 | % wOH(:,:,1)=1; 36 | 37 | % wHI_amp=randn(sizeH, sizeI, TDL_n); 38 | % wHI_phase=randn(sizeH, sizeI, TDL_n); 39 | % wHI =wHI_amp.*exp(1i*wHI_phase); 40 | % wOH_amp=randn(sizeO, sizeH, TDL_n); 41 | % wOH_phase=randn(sizeO, sizeH, TDL_n); 42 | % wOH =wOH_amp.*exp(1i*wOH_phase); 43 | % wHI(:,:,1)=1; 44 | % wOH(:,:,1)=1; 45 | 46 | 47 | iteration =301; 48 | counter = 1; 49 | er_matrix = zeros(); 50 | %% input normalization 51 | % for row=1:s 52 | % zI_set(row, 1:end-1) = zI_set(row, 1:end-1)/ max(abs(zI_set(row, 1:end-1))); 53 | % zO_teach_set(row, :) = zO_teach_set(row, :) / max(abs(zO_teach_set(row, :))); 54 | % end 55 | %% 56 | min_er=10000; 57 | while counter < iteration 58 | er = 0; 59 | for iter=1:bsz 60 | for ti=1:len 61 | uHI=zeros(sizeH,len); 62 | yHI=zeros(sizeH,len); 63 | xin=zeros(sizeI,len); 64 | for j=1:sizeH 65 | uj=zeros(1,len); 66 | for i=1:sizeI 67 | uji=zeros(1,len); 68 | if ~(i==1) 69 | ss=squeeze(zI_set(iter,i,:)).'; 70 | xin(i,:)=ss; 71 | wgt_xin=wHI(j,i)*ss; 72 | uji=uji+wgt_xin; 73 | else 74 | uji=squeeze(zI_set(iter,i,:)).'; 75 | end 76 | uj=uj+uji; 77 | end 78 | uHI(j,:)=uj; 79 | yHI(j,:)=tanh(abs(uHI(j,:))).*exp(1i*angle(uHI(j,:))); 80 | end 81 | 82 | % output zO 83 | uOH=zeros(sizeO,len); 84 | yOH=zeros(sizeO,len); 85 | xin2=zeros(sizeH,len); 86 | for j=1:sizeO 87 | uj=zeros(1,len); 88 | for i=1:sizeH 89 | uji=zeros(1,len); 90 | if ~(i==1) 91 | ss=yHI(i,:); 92 | xin2(i,:)=ss; 93 | wgt_xin2=wOH(j,i)*ss; 94 | uji=uji+wgt_xin2; 95 | 96 | else 97 | uji=yHI(i,:); 98 | end 99 | uj=uj+uji; 100 | end 101 | uOH(j,:)=uj; 102 | yOH(j,:)=tanh(abs(uOH(j,:))).*exp(1i*angle(uOH(j,:))); 103 | end 104 | 105 | %loss 106 | temp = yOH(ti)*yOH(ti)'; 107 | er = (1/2) .* sum( temp )+er ; 108 | 109 | zOt = zO_teach_set(iter, :); 110 | zO=yOH; 111 | for jj = 1:sizeO 112 | for ii = 1:sizeH 113 | 114 | if ii==1 115 | deltaEwOH1(jj,ii)=0; 116 | else 117 | deltaEwOH1(jj,ii) = (1- abs(zO(jj,ti)).^2) .* (abs(zO(jj,ti)) - abs(zOt(jj,ti)) .* ... 118 | cos(angle(zO(jj,ti)) - angle(zOt(jj,ti)))) .* abs((xin2(ii,ti))) .* ... 119 | cos(angle(zO(jj,ti)) - angle((xin2(ii,ti))) - angle(wOH(jj,ii))) - ... 120 | abs(zO(jj,ti)) .* abs(zOt(jj,ti)) .* sin(angle(zO(jj,ti)) - angle(zOt(jj,ti))) .* ... 121 | (abs((xin2(ii,ti))) ./ (abs(uOH(jj,ti)))).* ... 122 | sin(angle(zO(jj,ti)) - angle((xin2(ii,ti))) - angle(wOH(jj,ii))); 123 | end 124 | 125 | end 126 | end 127 | 128 | for jj = 1:sizeO 129 | for ii = 1:sizeH 130 | if ii==1 131 | deltaEwOH2(jj,ii)=0; 132 | else 133 | deltaEwOH2(jj,ii) = (1- abs(zO(jj,ti)).^2) .* (abs(zO(jj,ti)) - abs(zOt(jj,ti)) .* ... 134 | cos(angle(zO(jj,ti)) - angle(zOt(jj,ti))) ) .* abs((xin2(ii,ti))) .* ... 135 | sin(angle(zO(jj,ti)) - angle((xin2(ii,ti))) - angle(wOH(jj,ii))) + ... 136 | abs(zO(jj,ti)) .* abs(zOt(jj,ti)) .* sin(angle(zO(jj,ti)) - angle(zOt(jj,ti))) .* ... 137 | (abs((xin2(ii,ti))) ./ (abs(uOH(jj,ti)))).* ... 138 | cos(angle(zO(jj,ti)) - angle((xin2(ii,ti))) - angle(wOH(jj,ii))); 139 | end 140 | end 141 | end 142 | 143 | 144 | % Hermite conjugate 145 | for h = 1:sizeH 146 | zHt(h,:) = zeros(1,len); 147 | end 148 | 149 | zH=yHI; 150 | for jj = 1:sizeH 151 | for ii = 1:sizeI 152 | 153 | if ii==1 154 | deltaEwHI1(jj,ii)=0; 155 | else 156 | deltaEwHI1(jj,ii) = (1- abs(zH(jj,ti)).^2) .* (abs(zH(jj,ti)) - abs(zHt(jj,ti)).* ... 157 | cos(angle(zH(jj,ti)) - angle(zHt(jj,ti)))) .* abs((xin(ii,ti))) .* ... 158 | cos(angle(zH(jj,ti)) - angle((xin(ii,ti))) - angle(wHI(jj,ii))) - ... 159 | abs(zH(jj,ti)) .* abs(zHt(jj,ti)) .* sin(angle(zH(jj,ti)) - angle(zHt(jj,ti))) .* ... 160 | (abs((xin(ii,ti))) ./ (abs(uHI(jj,ti)))).* ... 161 | sin(angle(zH(jj,ti)) - angle((xin(ii,ti))) - angle(wHI(jj,ii))); 162 | end 163 | 164 | end 165 | end 166 | 167 | 168 | 169 | for jj = 1:sizeH 170 | for ii=1:sizeI 171 | 172 | if ii==1 173 | deltaEwHI2(jj,ii)=0; 174 | else 175 | deltaEwHI2(jj,ii) = (1- abs(zH(jj,ti)).^2) .* (abs(zH(jj,ti)) - abs(zHt(jj,ti)) .* ... 176 | cos(angle(zH(jj,ti)) - angle(zHt(jj,ti)))) .* abs((xin(ii,ti))) .* ... 177 | sin(angle(zH(jj,ti)) - angle((xin(ii,ti))) - angle(wHI(jj,ii))) + ... 178 | abs(zH(jj,ti)) .* abs(zHt(jj,ti)) .* sin(angle(zH(jj,ti)) - angle(zHt(jj,ti))) .* ... 179 | (abs((xin(ii,ti))) ./ (abs(uHI(jj,ti)))).* ... 180 | cos(angle(zH(jj,ti)) - angle((xin(ii,ti))) - angle(wHI(jj,ii))); 181 | end 182 | 183 | end 184 | end 185 | 186 | 187 | wHI1 = abs(wHI) - k1 * deltaEwHI1; 188 | wOH1 = abs(wOH) - k2 * deltaEwOH1; 189 | 190 | wHI2 = angle(wHI) - k1 * deltaEwHI2; 191 | wOH2 = angle(wOH) - k2 * deltaEwOH2; 192 | 193 | wHI = wHI1 .* exp(1i* wHI2); 194 | wOH = wOH1 .* exp(1i* wOH2); 195 | zO_set(iter, :) = zO; 196 | end 197 | end 198 | if counter==4000 199 | x=1; 200 | end 201 | er_matrix(counter) = er; 202 | counter = counter +1; 203 | 204 | if er<=min_er 205 | min_er=er; 206 | flag_count=1; 207 | else 208 | flag_count=flag_count+1; 209 | if flag_count>=16 210 | k2=k2/1.2; 211 | k1=k1/1.2; 212 | flag_count=0; 213 | min_er=er; 214 | end 215 | end 216 | hint=[counter,er,k1,k2] 217 | if rem(counter,100)==0 218 | save wgt_freq22.mat wHI wOH 219 | end 220 | end 221 | 222 | end -------------------------------------------------------------------------------- /Fig13_Fig15/Copy_of_doa_cvnn_module_test_CP10.m: -------------------------------------------------------------------------------- 1 | 2 | function [zO_set,signal] = Copy_of_doa_cvnn_module_test_CP10 (zI_set, wHI,wOH) 3 | len=size(zI_set,3); 4 | N_ang=size(zI_set,1); 5 | sizeI=size(zI_set,2); 6 | sizeH=12; 7 | sizeO=1; 8 | TDL_n=29; 9 | fc=500e3; 10 | Ts=1e-7; 11 | fs=1/Ts; 12 | df=fs/len; 13 | factor=exp(-1i*2*pi*(0:len-1)*df*Ts); 14 | 15 | %% 16 | 17 | for iter=1:N_ang 18 | %TDL output/hidden layer output 19 | uHI=zeros(sizeH,len); 20 | yHI=zeros(sizeH,len); 21 | xin=zeros(sizeI,len); 22 | for j=1:sizeH 23 | uj=zeros(1,len); 24 | for i=1:sizeI 25 | uji=zeros(1,len); 26 | if ~(i==1) 27 | ss=squeeze(zI_set(iter,i,:)).'; 28 | xin(i,:)=ss; 29 | wgt_xin=wHI(j,i)*ss; 30 | uji=uji+wgt_xin; 31 | else 32 | uji=squeeze(zI_set(iter,i,:)).'; 33 | end 34 | uj=uj+uji; 35 | end 36 | uHI(j,:)=uj; 37 | 38 | yHI(j,:)=tanh(abs(uHI(j,:))).*exp(1i*angle(uHI(j,:))); 39 | end 40 | 41 | % output zO 42 | uOH=zeros(sizeO,len); 43 | yOH=zeros(sizeO,len); 44 | xin2=zeros(sizeH,len); 45 | for j=1:sizeO 46 | uj=zeros(1,len); 47 | for i=1:sizeH 48 | uji=zeros(1,len); 49 | if ~(i==1) 50 | ss=yHI(i,:); 51 | xin2(i,:)=ss; 52 | wgt_xin2=wOH(j,i)*ss; 53 | uji=uji+wgt_xin2; 54 | else 55 | uji=yHI(i,:); 56 | end 57 | uj=uj+uji; 58 | end 59 | uOH(j,:)=uj; 60 | % yOH(j,:)=tanh(abs(uOH(j,:))).*exp(1i*angle(uOH(j,:))); 61 | yOH(j,:)=uj; 62 | end 63 | 64 | 65 | temp = yOH*yOH'; 66 | zO_set(iter) = temp; 67 | signal(iter,:)=yOH; 68 | end 69 | 70 | 71 | 72 | end 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /Fig13_Fig15/EchoSignalGen.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig13_Fig15/EchoSignalGen.m -------------------------------------------------------------------------------- /Fig13_Fig15/OMP.m: -------------------------------------------------------------------------------- 1 | function [A]=OMP(D,X,L) 2 | %============================================= 3 | % Sparse coding of a group of signals based on a given 4 | % dictionary and specified number of atoms to use. 5 | % ||X-DA|| 6 | % input arguments: 7 | % D - the dictionary (its columns MUST be normalized). 8 | % X - the signals to represent 9 | % L - the max. number of coefficients for each signal. 10 | % output arguments: 11 | % A - sparse coefficient matrix. 12 | %============================================= 13 | [n,P]=size(X); 14 | [n,K]=size(D); 15 | for k=1:1:P, 16 | a=[]; 17 | x=X(:,k); %the kth signal sample 18 | residual=x; %initial the residual vector 19 | indx=zeros(L,1); %initial the index vector 20 | 21 | %the jth iter 22 | for j=1:1:L, 23 | 24 | %compute the inner product 25 | proj=D'*residual; 26 | 27 | %find the max value and its index 28 | [maxVal,pos]=max(abs(proj)); 29 | 30 | %store the index 31 | pos=pos(1); 32 | indx(j)=pos; 33 | 34 | %solve the Least squares problem. 35 | a=pinv(D(:,indx(1:j)))*x; 36 | 37 | %compute the residual in the new dictionary 38 | residual=x-D(:,indx(1:j))*a; 39 | 40 | 41 | %the precision is fill our demand. 42 | % if sum(residual.^2) < 1e-6 43 | % break; 44 | % end 45 | end; 46 | temp=zeros(K,1); 47 | temp(indx(1:j))=a; 48 | A(:,k)=sparse(temp); 49 | end; 50 | return; -------------------------------------------------------------------------------- /Fig13_Fig15/__pycache__/complexFunctions.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig13_Fig15/__pycache__/complexFunctions.cpython-36.pyc -------------------------------------------------------------------------------- /Fig13_Fig15/__pycache__/complexLayers.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig13_Fig15/__pycache__/complexLayers.cpython-36.pyc -------------------------------------------------------------------------------- /Fig13_Fig15/__pycache__/complexModules.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig13_Fig15/__pycache__/complexModules.cpython-36.pyc -------------------------------------------------------------------------------- /Fig13_Fig15/__pycache__/fr.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig13_Fig15/__pycache__/fr.cpython-36.pyc -------------------------------------------------------------------------------- /Fig13_Fig15/__pycache__/util.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig13_Fig15/__pycache__/util.cpython-36.pyc -------------------------------------------------------------------------------- /Fig13_Fig15/bz.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig13_Fig15/bz.h5 -------------------------------------------------------------------------------- /Fig13_Fig15/cResFreq_epoch_60.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig13_Fig15/cResFreq_epoch_60.pth -------------------------------------------------------------------------------- /Fig13_Fig15/complexFunctions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | @author: spopoff 6 | """ 7 | 8 | from torch.nn.functional import relu, max_pool2d, avg_pool2d, dropout, dropout2d 9 | import torch 10 | 11 | 12 | def complex_matmul(A, B): 13 | ''' 14 | Performs the matrix product between two complex matrices 15 | ''' 16 | 17 | outp_real = torch.matmul(A.real, B.real) - torch.matmul(A.imag, B.imag) 18 | outp_imag = torch.matmul(A.real, B.imag) + torch.matmul(A.imag, B.real) 19 | 20 | return outp_real.type(torch.complex64) + 1j * outp_imag.type(torch.complex64) 21 | 22 | 23 | def complex_avg_pool2d(input, *args, **kwargs): 24 | ''' 25 | Perform complex average pooling. 26 | ''' 27 | absolute_value_real = avg_pool2d(input.real, *args, **kwargs) 28 | absolute_value_imag = avg_pool2d(input.imag, *args, **kwargs) 29 | 30 | return absolute_value_real.type(torch.complex64) + 1j * absolute_value_imag.type(torch.complex64) 31 | 32 | 33 | def complex_relu(input): 34 | return relu(input.real).type(torch.complex64) + 1j * relu(input.imag).type(torch.complex64) 35 | 36 | 37 | def _retrieve_elements_from_indices(tensor, indices): 38 | flattened_tensor = tensor.flatten(start_dim=-2) 39 | output = flattened_tensor.gather(dim=-1, index=indices.flatten(start_dim=-2)).view_as(indices) 40 | return output 41 | 42 | 43 | def complex_max_pool2d(input, kernel_size, stride=None, padding=0, 44 | dilation=1, ceil_mode=False, return_indices=False): 45 | ''' 46 | Perform complex max pooling by selecting on the absolute value on the complex values. 47 | ''' 48 | absolute_value, indices = max_pool2d( 49 | input.abs(), 50 | kernel_size=kernel_size, 51 | stride=stride, 52 | padding=padding, 53 | dilation=dilation, 54 | ceil_mode=ceil_mode, 55 | return_indices=True 56 | ) 57 | # performs the selection on the absolute values 58 | absolute_value = absolute_value.type(torch.complex64) 59 | # retrieve the corresonding phase value using the indices 60 | # unfortunately, the derivative for 'angle' is not implemented 61 | angle = torch.atan2(input.imag, input.real) 62 | # get only the phase values selected by max pool 63 | angle = _retrieve_elements_from_indices(angle, indices) 64 | return absolute_value \ 65 | * (torch.cos(angle).type(torch.complex64) + 1j * torch.sin(angle).type(torch.complex64)) 66 | 67 | 68 | def complex_dropout(input, p=0.5, training=True): 69 | # need to have the same dropout mask for real and imaginary part, 70 | # this not a clean solution! 71 | mask = torch.ones_like(input).type(torch.float32) 72 | mask = dropout(mask, p, training) * 1 / (1 - p) 73 | return mask * input 74 | 75 | 76 | def complex_dropout2d(input, p=0.5, training=True): 77 | # need to have the same dropout mask for real and imaginary part, 78 | # this not a clean solution! 79 | mask = torch.ones_like(input).type(torch.float32) 80 | mask = dropout2d(mask, p, training) * 1 / (1 - p) 81 | return mask * input -------------------------------------------------------------------------------- /Fig13_Fig15/data1_resfreq.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig13_Fig15/data1_resfreq.mat -------------------------------------------------------------------------------- /Fig13_Fig15/deepfreq_epoch_120.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig13_Fig15/deepfreq_epoch_120.pth -------------------------------------------------------------------------------- /Fig13_Fig15/deepfreq_model.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | import torch 4 | import util 5 | import matplotlib.pyplot as plt 6 | import h5py 7 | import scipy.io as sio 8 | 9 | # In[2]: 10 | def myModel(): 11 | fr_path = 'deepfreq_epoch_120.pth' 12 | xgrid = np.linspace(-0.5, 0.5, 4096, endpoint=False) 13 | # load models 14 | fr_module, _, _, _, _ = util.load(fr_path, 'fr') 15 | fr_module.cpu() 16 | fr_module.eval() 17 | 18 | f = h5py.File('matlab_real1.h5', 'r') 19 | real_data = f['matlab_real1'][:] 20 | f.close() 21 | f = h5py.File('matlab_imag1.h5', 'r') 22 | imag_data = f['matlab_imag1'][:] 23 | f.close() 24 | f = h5py.File('bz.h5', 'r') 25 | bz = f['bz'][:] 26 | f.close() 27 | N = 64 28 | 29 | signal_50dB = np.zeros([int(bz), 2, N]).astype(np.float32) 30 | signal_50dB[:, 0,:] = (real_data.astype(np.float32)).T 31 | signal_50dB[:, 1,:] = (imag_data.astype(np.float32)).T 32 | signal_50dB_c = signal_50dB[:, 0] + 1j * signal_50dB[:, 1] 33 | 34 | with torch.no_grad(): 35 | fr_50dB = fr_module(torch.tensor(signal_50dB)) 36 | fr_50dB = fr_50dB.cpu().data.numpy() 37 | 38 | dataNew = 'data1_deepfreq.mat' 39 | sio.savemat(dataNew, {'data1_deepfreq':fr_50dB}) 40 | 41 | myModel() -------------------------------------------------------------------------------- /Fig13_Fig15/fr.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import scipy.signal 3 | import matplotlib.pyplot as plt 4 | 5 | 6 | def freq2fr(f, xgrid, kernel_type='gaussian', param=None, r=None,nfreq=None): 7 | """ 8 | Convert an array of frequencies to a frequency representation discretized on xgrid. 9 | """ 10 | if kernel_type == 'gaussian': 11 | return gaussian_kernel(f, xgrid, param, r,nfreq) 12 | elif kernel_type == 'triangle': 13 | return triangle(f, xgrid, param) 14 | 15 | # def gaussian_kernel(f, xgrid, sigma, r,nfreq): 16 | # """ 17 | # Create a frequency representation with a Gaussian kernel. 18 | # """ 19 | # for i in range(f.shape[0]): 20 | # r[i,nfreq[i]:]=np.min(r[i,0:nfreq[i]]) 21 | # 22 | # fr = np.zeros((f.shape[0], xgrid.shape[0])) 23 | # # for i in range(f.shape[1]): 24 | # # dist = np.abs(xgrid[None, :] - f[:, i][:, None]) 25 | # # rdist = np.abs(xgrid[None, :] - (f[:, i][:, None] + 1)) 26 | # # ldist = np.abs(xgrid[None, :] - (f[:, i][:, None] - 1)) 27 | # # dist = np.minimum(dist, rdist, ldist) 28 | # # # fr += np.exp(- dist ** 2 / sigma ** 2) 29 | # # fr += np.exp(- dist ** 2 / sigma ** 2) 30 | # # fr=20*np.log10(fr+1e-2)+40*(r[:,i][:,None]) 31 | # # m1 = np.zeros((f.shape[0], xgrid.shape[0]), dtype='float32') 32 | # 33 | # fr_ground = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 34 | # for ii in range(fr.shape[0]): 35 | # 36 | # for i in range(f.shape[1]): 37 | # if f[ii, i] == -10: 38 | # continue 39 | # idx0 = (f[ii, i] + 0.5) / (1 / (np.shape(xgrid)[0])) 40 | # 41 | # ctr0 = int(np.round(idx0)) 42 | # if ctr0 == (np.shape(xgrid)[0]): 43 | # ctr0 = (np.shape(xgrid)[0]) - 1 44 | # 45 | # # if ctr0 == 0: 46 | # # ctr0_up = 1 47 | # # else: 48 | # # ctr0_up = ctr0 - 1 49 | # # if ctr0 == np.shape(xgrid)[0] - 1: 50 | # # ctr0_down = np.shape(xgrid)[0] - 2 51 | # # else: 52 | # # ctr0_down = ctr0 + 1 53 | # 54 | # FX=xgrid[ctr0] 55 | # dist = np.abs(xgrid - FX) 56 | # rdist = np.abs(xgrid - (FX + 1)) 57 | # ldist = np.abs(xgrid - (FX - 1)) 58 | # dist = np.minimum(dist, rdist, ldist) 59 | # fr[ii,:] += np.exp(- dist ** 2 / sigma ** 2)*20*np.log10(10*r[ii,i]+1) 60 | # cost = (np.power(20*np.log10(10*np.max(r[ii,:])+1),2)/ np.power(fr[ii,ctr0],2)) 61 | # fr_ground[ii, ctr0] = cost 62 | # 63 | # 64 | # 65 | # m2 = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 66 | # m1=m2 67 | # return fr, fr_ground.astype('float32'), m1, m2 68 | 69 | def gaussian_kernel(f, xgrid, sigma, r,nfreq): 70 | """ 71 | Create a frequency representation with a Gaussian kernel. 72 | """ 73 | for i in range(f.shape[0]): 74 | r[i,nfreq[i]:]=np.min(r[i,0:nfreq[i]]) 75 | 76 | fr = np.zeros((f.shape[0], xgrid.shape[0])) 77 | for i in range(f.shape[1]): 78 | dist = np.abs(xgrid[None, :] - f[:, i][:, None]) 79 | rdist = np.abs(xgrid[None, :] - (f[:, i][:, None] + 1)) 80 | ldist = np.abs(xgrid[None, :] - (f[:, i][:, None] - 1)) 81 | dist = np.minimum(dist, rdist, ldist) 82 | # fr += np.exp(- dist ** 2 / sigma ** 2) 83 | fr += np.exp(- dist ** 2 / sigma ** 2) 84 | # fr=20*np.log10(fr+1e-2)+40*(r[:,i][:,None]) 85 | m1 = np.zeros((f.shape[0], xgrid.shape[0]), dtype='float32') 86 | 87 | fr_ground = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 88 | fr_ground2 = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 89 | for ii in range(fr.shape[0]): 90 | # mv = -1 91 | # tol = 0 92 | # for k in range(f.shape[1]): 93 | # if f[ii, k] == -10: 94 | # break 95 | # tol += r[ii, k]/np.min(r[ii,:]) 96 | # if r[ii, k]/np.min(r[ii,:]) > mv: 97 | # mv = r[ii, k]/np.min(r[ii,:]) 98 | # mean_v = tol / k 99 | mv=np.max(fr[ii]) 100 | 101 | for i in range(f.shape[1]): 102 | # cost = (np.power(mv, 2) / np.abs(20 * np.log10(r[ii, i]) + 80)).astype('float32') 103 | # cost=1 104 | if f[ii, i] == -10: 105 | continue 106 | idx0 = (f[ii, i] + 0.5) / (1 / (np.shape(xgrid)[0])) 107 | 108 | ctr0 = int(np.round(idx0)) 109 | if ctr0 == (np.shape(xgrid)[0]): 110 | ctr0 = (np.shape(xgrid)[0]) - 1 111 | # if np.power(fr[ii,ctr0],2)==0: 112 | # xx=1 113 | cost = (np.power(mv, 2) / np.power(fr[ii,ctr0],2)).astype('float32') 114 | fr_ground[ii, ctr0] = cost 115 | # if r[ii, i]/np.min(r[ii,:])< mean_v:8 116 | # fr_ground2[ii, ctr0] = mean_v / (fr[ii,ctr0]) 117 | 118 | m1[ii,ctr0]=1 119 | if ctr0 == 0: 120 | ctr0_up = 1 121 | fr_ground[ii, ctr0_up] = cost 122 | m1[ii, ctr0_up] = 1 123 | else: 124 | ctr0_up = ctr0 - 1 125 | fr_ground[ii, ctr0_up] = cost 126 | m1[ii, ctr0_up] = 1 127 | if ctr0 == np.shape(xgrid)[0] - 1: 128 | ctr0_down = np.shape(xgrid)[0] - 2 129 | fr_ground[ii, ctr0_down] = cost 130 | m1[ii, ctr0_down] = 1 131 | else: 132 | ctr0_down = ctr0 + 1 133 | fr_ground[ii, ctr0_down] = cost 134 | m1[ii, ctr0_down] = 1 135 | 136 | m2 = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') - m1 137 | return fr, fr_ground, m1, m2 138 | 139 | 140 | def triangle(f, xgrid, slope): 141 | """ 142 | Create a frequency representation with a triangle kernel. 143 | """ 144 | fr = np.zeros((f.shape[0], xgrid.shape[0])) 145 | for i in range(f.shape[1]): 146 | dist = np.abs(xgrid[None, :] - f[:, i][:, None]) 147 | rdist = np.abs(xgrid[None, :] - (f[:, i][:, None] + 1)) 148 | ldist = np.abs(xgrid[None, :] - (f[:, i][:, None] - 1)) 149 | dist = np.minimum(dist, rdist, ldist) 150 | fr += np.clip(1 - slope * dist, 0, 1) 151 | return fr 152 | 153 | 154 | def find_freq_m(fr, nfreq, xgrid, max_freq=10): 155 | """ 156 | Extract frequencies from a frequency representation by locating the highest peaks. 157 | """ 158 | ff = -np.ones((1, max_freq)) 159 | for n in range(1): 160 | find_peaks_out = scipy.signal.find_peaks(fr, height=(None, None)) 161 | num_spikes = min(len(find_peaks_out[0]), nfreq) 162 | idx = np.argpartition(find_peaks_out[1]['peak_heights'], -num_spikes)[-num_spikes:] 163 | ff[n, :num_spikes] = np.sort(xgrid[find_peaks_out[0][idx]]) 164 | return ff 165 | 166 | 167 | def find_freq(fr, nfreq, xgrid, max_freq=10): 168 | """ 169 | Extract frequencies from a frequency representation by locating the highest peaks. 170 | """ 171 | ff = -np.ones((nfreq.shape[0], max_freq)) 172 | for n in range(len(nfreq)): 173 | 174 | if nfreq[n] < 1: # at least one frequency 175 | nf = 1 176 | else: 177 | nf = nfreq[n] 178 | 179 | find_peaks_out = scipy.signal.find_peaks(fr[n], height=(None, None)) 180 | num_spikes = min(len(find_peaks_out[0]), int(nf)) 181 | idx = np.argpartition(find_peaks_out[1]['peak_heights'], -num_spikes)[-num_spikes:] 182 | ff[n, :num_spikes] = np.sort(xgrid[find_peaks_out[0][idx]]) 183 | return ff 184 | 185 | 186 | def periodogram(signal, xgrid): 187 | """ 188 | Compute periodogram. 189 | """ 190 | js = np.arange(signal.shape[1]) 191 | return (np.abs(np.exp(-2.j * np.pi * xgrid[:, None] * js).dot(signal.T) / signal.shape[1]) ** 2).T 192 | 193 | 194 | def make_hankel(signal, m): 195 | """ 196 | Auxiliary function used in MUSIC. 197 | """ 198 | n = len(signal) 199 | h = np.zeros((m, n - m + 1), dtype='complex128') 200 | for r in range(m): 201 | for c in range(n - m + 1): 202 | h[r, c] = signal[r + c] 203 | return h 204 | 205 | 206 | def music(signal, xgrid, nfreq, m=20): 207 | """ 208 | Compute frequency representation obtained with MUSIC. 209 | """ 210 | music_fr = np.zeros((signal.shape[0], len(xgrid))) 211 | for n in range(signal.shape[0]): 212 | hankel = make_hankel(signal[n], m) 213 | _, _, V = np.linalg.svd(hankel) 214 | v = np.exp(-2.0j * np.pi * np.outer(xgrid[:, None], np.arange(0, signal.shape[1] - m + 1))) 215 | u = V[nfreq[n]:] 216 | fr = -np.log(np.linalg.norm(np.tensordot(u, v, axes=(1, 1)), axis=0) ** 2) 217 | music_fr[n] = fr 218 | return music_fr 219 | -------------------------------------------------------------------------------- /Fig13_Fig15/main.asv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig13_Fig15/main.asv -------------------------------------------------------------------------------- /Fig13_Fig15/main.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig13_Fig15/main.m -------------------------------------------------------------------------------- /Fig13_Fig15/main2_bak.m: -------------------------------------------------------------------------------- 1 | %% 2 | clear all 3 | close all 4 | Rmin=20000; 5 | Rmax=35150; 6 | Fc=8.5e9; 7 | T=100e-6; %脉冲宽度 8 | B=0.3e9; 9 | k=B/T; 10 | K=k; 11 | Fs=1e9; 12 | dt=1/Fs; 13 | Ts=dt; 14 | c=3e8; 15 | Rwid=Rmax-Rmin; 16 | Twid=2*Rwid/c; 17 | Nwid=ceil(Twid/Ts); 18 | Nchirp=ceil(T/Ts); 19 | t=linspace(2*Rmin/c,2*Rmax/c,Nwid); 20 | nb=T*B; 21 | df=1/T; 22 | f=(-(nb-1)/2:(nb-1)/2)*df; 23 | %% 24 | center=[Rmin+T*c/4+50,0,0]; 25 | x=1*[0,-1,-1, -1,-3.5,-6.5,-6.5,-3.5,-1, -1, -2.5,-2.5,2.5, 2.5, 1, 1, 3.5,6.5,6.5,3.5,1,1,1,0]+center(1); 26 | y=1*[9, 7,5.5, 4, 2.5, 0.5,-1, -0.5, 0, -2.5, -3.5, -4, -4, -3.5,-2.5,0,-0.5,-1, 0.5,2.5,4,5.5,7,9]; 27 | % x=1*[0,-1,-1]+center(1); 28 | % y=1*[9, 7,5.5]; 29 | 30 | tgt_num=length(x); 31 | theta=1/2*pi; 32 | for i=1:length(x) 33 | huai=atan2(y(i)-center(2),x(i)-center(1)); 34 | xx(i)=sqrt((x(i)-center(1))^2+(y(i)-center(2))^2)*cos(huai+theta)+center(1); 35 | yy(i)=sqrt((x(i)-center(1))^2+(y(i)-center(2))^2)*sin(huai+theta); 36 | end 37 | 38 | %% 39 | x=xx; 40 | y=yy; 41 | w=1.5; 42 | for i=1:128 43 | for ii=1:length(x) 44 | theta=atan2(y(ii)-center(2),x(ii)-center(1)); 45 | RR(i,ii)=sqrt((x(ii)-center(1))^2+(y(ii)-center(2))^2)*cos(theta+w*(i)/180*pi)+center(1); 46 | end 47 | end 48 | 49 | len=fix(T/dt); 50 | lin=-len/2:len/2-1; 51 | S_Ref=exp(j*pi*k*(lin*dt).^2); 52 | amp=abs(randn(1,tgt_num)); 53 | SNR=20; 54 | bz=120; 55 | sig=zeros(bz,size(f,2)); 56 | for i1=1:bz 57 | i1 58 | for tgt=1:length(x) 59 | tau(tgt)=2*RR(i1,tgt)/c; 60 | sig(i1,:)=sig(i1,:)+amp(tgt)*exp(-1i*2*pi*(f+Fc)*tau(tgt)); 61 | end 62 | sig(i1,:)=sig(i1,:)/sqrt(mean(abs(sig(i1,:).^2))); 63 | sig(i1,:)=sig(i1,:)*10^(SNR/20)+wgn(size(sig(i1,:),1),size(sig(i1,:),2),0,'complex'); 64 | ys1=sig(i1,:).*exp(-1i*2*pi*4700*(1:length(sig(1,:)))/length(sig(1,:))); 65 | ys2=fft(resample(ys1,1,60)); 66 | tmp=ys2(172:235); 67 | 68 | sig2(i1,:)=ifft(fftshift(tmp)); 69 | RPP(i1,:)=sig2(i1,:)/max(max(abs(sig2(i1,:)))); 70 | end 71 | if ~exist('matlab_real2.h5','file')==0 72 | delete('matlab_real2.h5') 73 | end 74 | 75 | if ~exist('matlab_imag2.h5','file')==0 76 | delete('matlab_imag2.h5') 77 | end 78 | 79 | 80 | if ~exist('bz.h5','file')==0 81 | delete('bz.h5') 82 | end 83 | 84 | h5create('matlab_real2.h5','/matlab_real2',size(RPP)); 85 | h5write('matlab_real2.h5','/matlab_real2',real(RPP)); 86 | h5create('matlab_imag2.h5','/matlab_imag2',size(RPP)); 87 | h5write('matlab_imag2.h5','/matlab_imag2',imag(RPP)); 88 | h5create('bz.h5','/bz',size(bz)); 89 | h5write('bz.h5','/bz',bz) 90 | 91 | system('D:\ProgramData\Anaconda3\envs\complexPytorch-gpu\python.exe resfreq_model.py') 92 | load data1_resfreq.mat 93 | figure;imagesc(abs(data1_resfreq)) 94 | win=ones(size(sig2,1),1)*hamming(64).'; 95 | 96 | spc=fftshift(abs(fft(sig2.*win,4096,2)),2); 97 | figure;imagesc(spc); 98 | % SNR=20; 99 | % for ll=1:64 100 | % ll 101 | % R=RR(ll,:); 102 | % RCS=ones(1,length(R))*1; 103 | % xs=zeros(1,len); 104 | % %================================================================== 105 | % %%Gnerate the echo 106 | % t=linspace(2*Rmin/c,2*Rmax/c,Nwid); %receive wind 107 | % M=length(R); 108 | % td=ones(M,1)*t-2*R'/c*ones(1,Nwid); 109 | % xs=RCS*((ones(Nwid,1)*exp(-1i*2*pi*Fc*2*R/c)).'.*exp(1i*pi*K*td.^2).*(abs(td)=16 210 | k2=k2/1.2; 211 | k1=k1/1.2; 212 | flag_count=0; 213 | min_er=er; 214 | end 215 | end 216 | hint=[counter,er,k1,k2] 217 | if rem(counter,100)==0 218 | save wgt_freq22.mat wHI wOH 219 | end 220 | end 221 | 222 | end -------------------------------------------------------------------------------- /Fig1_Fig4/Copy_of_doa_cvnn_module_test_CP10.m: -------------------------------------------------------------------------------- 1 | 2 | function [zO_set,signal] = Copy_of_doa_cvnn_module_test_CP10 (zI_set, wHI,wOH) 3 | len=size(zI_set,3); 4 | N_ang=size(zI_set,1); 5 | sizeI=size(zI_set,2); 6 | sizeH=12; 7 | sizeO=1; 8 | TDL_n=29; 9 | fc=500e3; 10 | Ts=1e-7; 11 | fs=1/Ts; 12 | df=fs/len; 13 | factor=exp(-1i*2*pi*(0:len-1)*df*Ts); 14 | 15 | %% 16 | 17 | for iter=1:N_ang 18 | %TDL output/hidden layer output 19 | uHI=zeros(sizeH,len); 20 | yHI=zeros(sizeH,len); 21 | xin=zeros(sizeI,len); 22 | for j=1:sizeH 23 | uj=zeros(1,len); 24 | for i=1:sizeI 25 | uji=zeros(1,len); 26 | if ~(i==1) 27 | ss=squeeze(zI_set(iter,i,:)).'; 28 | xin(i,:)=ss; 29 | wgt_xin=wHI(j,i)*ss; 30 | uji=uji+wgt_xin; 31 | else 32 | uji=squeeze(zI_set(iter,i,:)).'; 33 | end 34 | uj=uj+uji; 35 | end 36 | uHI(j,:)=uj; 37 | 38 | yHI(j,:)=tanh(abs(uHI(j,:))).*exp(1i*angle(uHI(j,:))); 39 | end 40 | 41 | % output zO 42 | uOH=zeros(sizeO,len); 43 | yOH=zeros(sizeO,len); 44 | xin2=zeros(sizeH,len); 45 | for j=1:sizeO 46 | uj=zeros(1,len); 47 | for i=1:sizeH 48 | uji=zeros(1,len); 49 | if ~(i==1) 50 | ss=yHI(i,:); 51 | xin2(i,:)=ss; 52 | wgt_xin2=wOH(j,i)*ss; 53 | uji=uji+wgt_xin2; 54 | else 55 | uji=yHI(i,:); 56 | end 57 | uj=uj+uji; 58 | end 59 | uOH(j,:)=uj; 60 | % yOH(j,:)=tanh(abs(uOH(j,:))).*exp(1i*angle(uOH(j,:))); 61 | yOH(j,:)=uj; 62 | end 63 | 64 | 65 | temp = yOH*yOH'; 66 | zO_set(iter) = temp; 67 | signal(iter,:)=yOH; 68 | end 69 | 70 | 71 | 72 | end 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /Fig1_Fig4/OMP.m: -------------------------------------------------------------------------------- 1 | function [A]=OMP(D,X,L) 2 | %============================================= 3 | % Sparse coding of a group of signals based on a given 4 | % dictionary and specified number of atoms to use. 5 | % ||X-DA|| 6 | % input arguments: 7 | % D - the dictionary (its columns MUST be normalized). 8 | % X - the signals to represent 9 | % L - the max. number of coefficients for each signal. 10 | % output arguments: 11 | % A - sparse coefficient matrix. 12 | %============================================= 13 | [n,P]=size(X); 14 | [n,K]=size(D); 15 | for k=1:1:P, 16 | a=[]; 17 | x=X(:,k); %the kth signal sample 18 | residual=x; %initial the residual vector 19 | indx=zeros(L,1); %initial the index vector 20 | 21 | %the jth iter 22 | for j=1:1:L, 23 | 24 | %compute the inner product 25 | proj=D'*residual; 26 | 27 | %find the max value and its index 28 | [maxVal,pos]=max(abs(proj)); 29 | 30 | %store the index 31 | pos=pos(1); 32 | indx(j)=pos; 33 | 34 | %solve the Least squares problem. 35 | a=pinv(D(:,indx(1:j)))*x; 36 | 37 | %compute the residual in the new dictionary 38 | residual=x-D(:,indx(1:j))*a; 39 | 40 | 41 | %the precision is fill our demand. 42 | % if sum(residual.^2) < 1e-6 43 | % break; 44 | % end 45 | end; 46 | temp=zeros(K,1); 47 | temp(indx(1:j))=a; 48 | A(:,k)=sparse(temp); 49 | end; 50 | return; -------------------------------------------------------------------------------- /Fig1_Fig4/__pycache__/complexFunctions.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/__pycache__/complexFunctions.cpython-36.pyc -------------------------------------------------------------------------------- /Fig1_Fig4/__pycache__/complexLayers.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/__pycache__/complexLayers.cpython-36.pyc -------------------------------------------------------------------------------- /Fig1_Fig4/__pycache__/complexModules.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/__pycache__/complexModules.cpython-36.pyc -------------------------------------------------------------------------------- /Fig1_Fig4/__pycache__/fr.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/__pycache__/fr.cpython-36.pyc -------------------------------------------------------------------------------- /Fig1_Fig4/__pycache__/modules.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/__pycache__/modules.cpython-36.pyc -------------------------------------------------------------------------------- /Fig1_Fig4/__pycache__/util.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/__pycache__/util.cpython-36.pyc -------------------------------------------------------------------------------- /Fig1_Fig4/cResFreq.m: -------------------------------------------------------------------------------- 1 | clc 2 | clear all 3 | close all 4 | format long 5 | rng('default'); 6 | 7 | L=64; 8 | nfft=L*64; 9 | x_label=-0.5:1/nfft:0.5-1/nfft; 10 | w=2*pi*[-5/L,0/L,5/L,5.7/L,8/L,13/L]; 11 | y=w/2/pi; 12 | tgt_num=length(w); 13 | amp=ones(1,tgt_num); 14 | amp(tgt_num-2)=10^(-10/20); 15 | amp(tgt_num)=10^(-20/20); 16 | sig=zeros(1,L); 17 | nfft=4096; 18 | search_f=-0.5:1/nfft:0.5-1/nfft; 19 | for i=1:tgt_num 20 | theta=2*pi*rand(); 21 | sig=sig+amp(i)*exp(1i*theta)*exp(1i*w(i)*(0:(L-1))); 22 | end 23 | sig=sig/sqrt(mean(abs(sig.^2))); 24 | %% 25 | SNR=20; 26 | noise=wgn(size(sig,1),size(sig,2),0,'complex'); 27 | noisedSig_20dB=sig*10^(SNR/20)+noise; 28 | SNR=0; 29 | noise=wgn(size(sig,1),size(sig,2),0,'complex'); 30 | noisedSig_0dB=sig*10^(SNR/20)+noise; 31 | 32 | % load noisedSig_20dB 33 | % load noisedSig_0dB 34 | %% cResFreq 35 | delete('data1_resfreq.mat') 36 | if ~exist('matlab_real2.h5','file')==0 37 | delete('matlab_real2.h5') 38 | end 39 | if ~exist('matlab_imag2.h5','file')==0 40 | delete('matlab_imag2.h5') 41 | end 42 | mv=max(abs(noisedSig_20dB)); 43 | noisedSig=noisedSig_20dB/mv; 44 | h5create('matlab_real2.h5','/matlab_real2',size(noisedSig)); 45 | h5write('matlab_real2.h5','/matlab_real2',real(noisedSig)); 46 | h5create('matlab_imag2.h5','/matlab_imag2',size(noisedSig)); 47 | h5write('matlab_imag2.h5','/matlab_imag2',imag(noisedSig)); 48 | flag=system('D:\ProgramData\Anaconda3\envs\complexPytorch-gpu\python.exe resfreq_model.py'); 49 | h=figure(4) 50 | set(h,'position',[100 100 1000 600]); 51 | 52 | for i=1:tgt_num 53 | h1=stem(y(i),-80,'r-','Marker','none','linewidth',2); 54 | hold on; 55 | h2=stem(y(i),3,'r-','Marker','none','linewidth',2); 56 | hold on; 57 | set(get(get(h1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 58 | set(get(get(h2,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 59 | end 60 | 61 | set(gca,'FontSize',20); 62 | set(get(gca,'XLabel'),'FontSize',20); 63 | set(get(gca,'YLabel'),'FontSize',20); 64 | if flag==0 65 | load data1_resfreq.mat 66 | 67 | normDeepFreq=10*log10(data1_resfreq.^2/max(data1_resfreq.^2)+1e-13); 68 | plot(x_label,real(normDeepFreq),'b:.','linewidth',3); 69 | axis([-0.1 0.25 -60 3]) 70 | ylabel('Normalized PSD / dB'); 71 | xlabel('Normalized freq. / Hz'); 72 | 73 | hold on 74 | end 75 | 76 | %% 77 | delete('data1_resfreq.mat') 78 | if ~exist('matlab_real2.h5','file')==0 79 | delete('matlab_real2.h5') 80 | end 81 | if ~exist('matlab_imag2.h5','file')==0 82 | delete('matlab_imag2.h5') 83 | end 84 | mv=max(abs(noisedSig_0dB)); 85 | noisedSig0=noisedSig_0dB/mv; 86 | h5create('matlab_real2.h5','/matlab_real2',size(noisedSig0)); 87 | h5write('matlab_real2.h5','/matlab_real2',real(noisedSig0)); 88 | h5create('matlab_imag2.h5','/matlab_imag2',size(noisedSig0)); 89 | h5write('matlab_imag2.h5','/matlab_imag2',imag(noisedSig0)); 90 | flag=system('D:\ProgramData\Anaconda3\envs\complexPytorch-gpu\python.exe resfreq_model.py'); 91 | if flag==0 92 | 93 | load data1_resfreq.mat 94 | 95 | normDeepFreq0=10*log10(data1_resfreq.^2/max(data1_resfreq.^2)+1e-13); 96 | plot(x_label,real(normDeepFreq0),'k:.','linewidth',3); 97 | 98 | legend('SNR = 20dB','SNR = 0dB'); 99 | ylabel('Normalized Power / dB'); 100 | xlabel('Normalized freq. / Hz'); 101 | grid on; 102 | end -------------------------------------------------------------------------------- /Fig1_Fig4/cResFreq_epoch_60.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/cResFreq_epoch_60.pth -------------------------------------------------------------------------------- /Fig1_Fig4/complexFunctions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | @author: spopoff 6 | """ 7 | 8 | from torch.nn.functional import relu, max_pool2d, avg_pool2d, dropout, dropout2d 9 | import torch 10 | 11 | 12 | def complex_matmul(A, B): 13 | ''' 14 | Performs the matrix product between two complex matrices 15 | ''' 16 | 17 | outp_real = torch.matmul(A.real, B.real) - torch.matmul(A.imag, B.imag) 18 | outp_imag = torch.matmul(A.real, B.imag) + torch.matmul(A.imag, B.real) 19 | 20 | return outp_real.type(torch.complex64) + 1j * outp_imag.type(torch.complex64) 21 | 22 | 23 | def complex_avg_pool2d(input, *args, **kwargs): 24 | ''' 25 | Perform complex average pooling. 26 | ''' 27 | absolute_value_real = avg_pool2d(input.real, *args, **kwargs) 28 | absolute_value_imag = avg_pool2d(input.imag, *args, **kwargs) 29 | 30 | return absolute_value_real.type(torch.complex64) + 1j * absolute_value_imag.type(torch.complex64) 31 | 32 | 33 | def complex_relu(input): 34 | return relu(input.real).type(torch.complex64) + 1j * relu(input.imag).type(torch.complex64) 35 | 36 | 37 | def _retrieve_elements_from_indices(tensor, indices): 38 | flattened_tensor = tensor.flatten(start_dim=-2) 39 | output = flattened_tensor.gather(dim=-1, index=indices.flatten(start_dim=-2)).view_as(indices) 40 | return output 41 | 42 | 43 | def complex_max_pool2d(input, kernel_size, stride=None, padding=0, 44 | dilation=1, ceil_mode=False, return_indices=False): 45 | ''' 46 | Perform complex max pooling by selecting on the absolute value on the complex values. 47 | ''' 48 | absolute_value, indices = max_pool2d( 49 | input.abs(), 50 | kernel_size=kernel_size, 51 | stride=stride, 52 | padding=padding, 53 | dilation=dilation, 54 | ceil_mode=ceil_mode, 55 | return_indices=True 56 | ) 57 | # performs the selection on the absolute values 58 | absolute_value = absolute_value.type(torch.complex64) 59 | # retrieve the corresonding phase value using the indices 60 | # unfortunately, the derivative for 'angle' is not implemented 61 | angle = torch.atan2(input.imag, input.real) 62 | # get only the phase values selected by max pool 63 | angle = _retrieve_elements_from_indices(angle, indices) 64 | return absolute_value \ 65 | * (torch.cos(angle).type(torch.complex64) + 1j * torch.sin(angle).type(torch.complex64)) 66 | 67 | 68 | def complex_dropout(input, p=0.5, training=True): 69 | # need to have the same dropout mask for real and imaginary part, 70 | # this not a clean solution! 71 | mask = torch.ones_like(input).type(torch.float32) 72 | mask = dropout(mask, p, training) * 1 / (1 - p) 73 | return mask * input 74 | 75 | 76 | def complex_dropout2d(input, p=0.5, training=True): 77 | # need to have the same dropout mask for real and imaginary part, 78 | # this not a clean solution! 79 | mask = torch.ones_like(input).type(torch.float32) 80 | mask = dropout2d(mask, p, training) * 1 / (1 - p) 81 | return mask * input -------------------------------------------------------------------------------- /Fig1_Fig4/cvnn.m: -------------------------------------------------------------------------------- 1 | clc 2 | clear all 3 | close all 4 | format long 5 | rng('default'); 6 | 7 | L=64; 8 | nfft=L*64; 9 | x_label=-0.5:1/nfft:0.5-1/nfft; 10 | w=2*pi*[-5/L,0/L,5/L,5.7/L]; 11 | y=w/2/pi; 12 | tgt_num=length(w); 13 | amp=ones(1,tgt_num); 14 | amp(tgt_num)=10^(-10/20); 15 | sig=zeros(1,L); 16 | nfft=4096; 17 | search_f=-0.5:1/nfft:0.5-1/nfft; 18 | for i=1:tgt_num 19 | theta=2*pi*rand(); 20 | sig=sig+amp(i)*exp(1i*theta)*exp(1i*w(i)*(0:(L-1))); 21 | end 22 | sig=sig/sqrt(mean(abs(sig.^2))); 23 | 24 | SNR=20; 25 | noise=wgn(size(sig,1),size(sig,2),0,'complex'); 26 | noisedSig_20dB=sig*10^(SNR/20)+noise; 27 | SNR=0; 28 | noise=wgn(size(sig,1),size(sig,2),0,'complex'); 29 | noisedSig_0dB=sig*10^(SNR/20)+noise; 30 | 31 | %% 32 | Ns=1; 33 | Nsnap=8; 34 | mv=max(abs(noisedSig_20dB)); 35 | RPP=noisedSig_20dB/mv; 36 | t=0:63; 37 | nfft=4096; 38 | len=size(RPP,2); 39 | snapLen=len-Nsnap+1; 40 | freqs = -0.5:1/nfft:0.5-1/nfft; 41 | 42 | for indix=1:size(RPP,1) 43 | % for indix=1:1 44 | ss=RPP(indix,:); 45 | zI=zeros(Ns,Nsnap,snapLen); 46 | for si=1:Ns 47 | for i=1:Nsnap 48 | zI(si,i,:)=ss(si,i:i+snapLen-1); 49 | end 50 | end 51 | zO_teach_set=zeros(Ns,snapLen); 52 | zI_set=zI; 53 | [wHI, wOH, zO_set_train] = Copy_of_doa_cvnn_module_CP10(zI_set, zO_teach_set); 54 | 55 | 56 | zI=zeros(length(freqs),Nsnap,snapLen); 57 | for tgt=1:length(freqs) 58 | zIk=exp(1i*(2*pi*freqs(tgt)*t)); 59 | zIk=zIk/max(abs(zIk)); 60 | for i=1:Nsnap 61 | zI(tgt,i,:)=zIk(i:i+snapLen-1); 62 | end 63 | end 64 | 65 | load wgt_freq22.mat 66 | zI_set = zI; 67 | [zO_set_test,signal] = Copy_of_doa_cvnn_module_test_CP10(zI,wHI,wOH); 68 | final_ret(indix,:)=ones(1,nfft)./(zO_set_test+1e-10); 69 | P_ah20(indix,:)=final_ret(indix,:)/max(abs(final_ret(indix,:))); 70 | end 71 | 72 | Ns=1; 73 | Nsnap=8; 74 | mv=max(abs(noisedSig_0dB)); 75 | RPP=noisedSig_0dB/mv; 76 | t=0:63; 77 | nfft=4096; 78 | len=size(RPP,2); 79 | snapLen=len-Nsnap+1; 80 | freqs = -0.5:1/nfft:0.5-1/nfft; 81 | final_ret20=zeros(size(RPP,1),length(freqs)); 82 | for indix=1:size(RPP,1) 83 | % for indix=1:1 84 | ss=RPP(indix,:); 85 | zI=zeros(Ns,Nsnap,snapLen); 86 | for si=1:Ns 87 | for i=1:Nsnap 88 | zI(si,i,:)=ss(si,i:i+snapLen-1); 89 | end 90 | end 91 | zO_teach_set=zeros(Ns,snapLen); 92 | zI_set=zI; 93 | [wHI, wOH, zO_set_train] = Copy_of_doa_cvnn_module_CP10(zI_set, zO_teach_set); 94 | 95 | 96 | zI=zeros(length(freqs),Nsnap,snapLen); 97 | for tgt=1:length(freqs) 98 | zIk=exp(1i*(2*pi*freqs(tgt)*t)); 99 | zIk=zIk/max(abs(zIk)); 100 | for i=1:Nsnap 101 | zI(tgt,i,:)=zIk(i:i+snapLen-1); 102 | end 103 | end 104 | 105 | load wgt_freq22.mat 106 | zI_set = zI; 107 | [zO_set_test,signal] = Copy_of_doa_cvnn_module_test_CP10(zI,wHI,wOH); 108 | final_ret(indix,:)=ones(1,nfft)./(zO_set_test+1e-10); 109 | P_ah0(indix,:)=final_ret(indix,:)/max(abs(final_ret(indix,:))); 110 | end 111 | 112 | %% 113 | h=figure(1) 114 | set(h,'position',[100 100 1000 600]); 115 | 116 | for i=1:tgt_num 117 | h1=stem(y(i),-40,'r-','Marker','none','linewidth',2); 118 | hold on; 119 | h2=stem(y(i),3,'r-','Marker','none','linewidth',2); 120 | hold on; 121 | set(get(get(h1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 122 | set(get(get(h2,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 123 | end 124 | axis([-0.1 0.15 -40 3]) 125 | set(gca,'FontSize',20); 126 | set(get(gca,'XLabel'),'FontSize',20); 127 | set(get(gca,'YLabel'),'FontSize',20); 128 | normah=20*log10(P_ah20/max(P_ah20)+1e-13); 129 | plot(x_label,real(normah).','b:.','linewidth',3); 130 | hold on 131 | normah=20*log10(P_ah0/max(P_ah0)+1e-13); 132 | plot(x_label,real(normah).','k:.','linewidth',3); 133 | legend('SNR = 20dB','SNR = 0dB'); 134 | ylabel('Normalized Power / dB'); 135 | xlabel('Normalized freq. / Hz'); 136 | grid on; 137 | hold on; 138 | 139 | % save p_ah.mat P_ah20 P_ah0 -------------------------------------------------------------------------------- /Fig1_Fig4/data1_deepfreq.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/data1_deepfreq.mat -------------------------------------------------------------------------------- /Fig1_Fig4/data1_resfreq.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/data1_resfreq.mat -------------------------------------------------------------------------------- /Fig1_Fig4/deepfreq.m: -------------------------------------------------------------------------------- 1 | clc 2 | clear all 3 | close all 4 | format long 5 | rng('default'); 6 | 7 | L=64; 8 | nfft=L*64; 9 | x_label=-0.5:1/nfft:0.5-1/nfft; 10 | w=2*pi*[-5/L,0/L,5/L,5.7/L,8/L,13/L]; 11 | y=w/2/pi; 12 | tgt_num=length(w); 13 | amp=ones(1,tgt_num); 14 | amp(tgt_num-2)=10^(-10/20); 15 | amp(tgt_num)=10^(-20/20); 16 | sig=zeros(1,L); 17 | nfft=4096; 18 | search_f=-0.5:1/nfft:0.5-1/nfft; 19 | for i=1:tgt_num 20 | theta=2*pi*rand(); 21 | sig=sig+amp(i)*exp(1i*theta)*exp(1i*w(i)*(0:(L-1))); 22 | end 23 | sig=sig/sqrt(mean(abs(sig.^2))); 24 | %% 25 | SNR=20; 26 | noise=wgn(size(sig,1),size(sig,2),0,'complex'); 27 | noisedSig_20dB=sig*10^(SNR/20)+noise; 28 | SNR=0; 29 | noise=wgn(size(sig,1),size(sig,2),0,'complex'); 30 | noisedSig_0dB=sig*10^(SNR/20)+noise; 31 | 32 | % load noisedSig_20dB 33 | % load noisedSig_0dB 34 | %% DeepFreq 35 | if ~exist('matlab_real1.h5','file')==0 36 | delete('matlab_real1.h5') 37 | end 38 | if ~exist('matlab_imag1.h5','file')==0 39 | delete('matlab_imag1.h5') 40 | end 41 | mv=max(abs(noisedSig_20dB)); 42 | noisedSig=noisedSig_20dB/mv; 43 | h5create('matlab_real1.h5','/matlab_real1',size(noisedSig)); 44 | h5write('matlab_real1.h5','/matlab_real1',real(noisedSig)); 45 | h5create('matlab_imag1.h5','/matlab_imag1',size(noisedSig)); 46 | h5write('matlab_imag1.h5','/matlab_imag1',imag(noisedSig)); 47 | flag=system('D:\ProgramData\Anaconda3\envs\complexPytorch-gpu\python.exe deepfreq_model.py'); 48 | h=figure(3) 49 | set(h,'position',[100 100 1000 600]); 50 | 51 | for i=1:tgt_num 52 | h1=stem(y(i),-80,'r-','Marker','none','linewidth',2); 53 | hold on; 54 | h2=stem(y(i),3,'r-','Marker','none','linewidth',2); 55 | hold on; 56 | set(get(get(h1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 57 | set(get(get(h2,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 58 | end 59 | 60 | set(gca,'FontSize',20); 61 | set(get(gca,'XLabel'),'FontSize',20); 62 | set(get(gca,'YLabel'),'FontSize',20); 63 | if flag==0 64 | load data1_deepfreq.mat 65 | data1_deepfreq20=data1_deepfreq; 66 | normDeepFreq=10*log10(data1_deepfreq20.^2/max(data1_deepfreq20.^2)+1e-13); 67 | plot(x_label,real(normDeepFreq),'b:.','linewidth',3); 68 | 69 | ylabel('Normalized PSD / dB'); 70 | xlabel('Normalized freq. / Hz'); 71 | grid on; 72 | hold on 73 | end 74 | %% 75 | if ~exist('matlab_real1.h5','file')==0 76 | delete('matlab_real1.h5') 77 | end 78 | if ~exist('matlab_imag1.h5','file')==0 79 | delete('matlab_imag1.h5') 80 | end 81 | mv=max(abs(noisedSig_0dB)); 82 | noisedSig=noisedSig_0dB/mv; 83 | h5create('matlab_real1.h5','/matlab_real1',size(noisedSig)); 84 | h5write('matlab_real1.h5','/matlab_real1',real(noisedSig)); 85 | h5create('matlab_imag1.h5','/matlab_imag1',size(noisedSig)); 86 | h5write('matlab_imag1.h5','/matlab_imag1',imag(noisedSig)); 87 | flag=system('D:\ProgramData\Anaconda3\envs\complexPytorch-gpu\python.exe deepfreq_model.py'); 88 | if flag==0 89 | load data1_deepfreq.mat 90 | data1_deepfreq0=data1_deepfreq; 91 | normDeepFreq=10*log10(data1_deepfreq0.^2/max(data1_deepfreq0.^2)+1e-13); 92 | plot(x_label,real(normDeepFreq),'k:.','linewidth',3); 93 | legend('SNR = 20dB','SNR = 0dB'); 94 | ylabel('Normalized Power / dB'); 95 | xlabel('Normalized freq. / Hz'); 96 | grid on; 97 | end 98 | axis([-0.1 0.25 -40 3]) 99 | % save deepfreq.mat data1_deepfreq20 data1_deepfreq0 -------------------------------------------------------------------------------- /Fig1_Fig4/deepfreq_390.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/deepfreq_390.pth -------------------------------------------------------------------------------- /Fig1_Fig4/deepfreq_epoch_120.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/deepfreq_epoch_120.pth -------------------------------------------------------------------------------- /Fig1_Fig4/deepfreq_model.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | import torch 4 | import util 5 | import matplotlib.pyplot as plt 6 | import h5py 7 | import scipy.io as sio 8 | 9 | # In[2]: 10 | def myModel(): 11 | fr_path = 'deepfreq_epoch_120.pth' 12 | xgrid = np.linspace(-0.5, 0.5, 4096, endpoint=False) 13 | # load models 14 | fr_module, _, _, _, _ = util.load(fr_path, 'fr') 15 | fr_module.cpu() 16 | fr_module.eval() 17 | 18 | f = h5py.File('matlab_real1.h5', 'r') 19 | real_data = f['matlab_real1'][:] 20 | f.close() 21 | f = h5py.File('matlab_imag1.h5', 'r') 22 | imag_data = f['matlab_imag1'][:] 23 | f.close() 24 | bz=1; 25 | N = 64 26 | 27 | signal_50dB = np.zeros([int(bz), 2, N]).astype(np.float32) 28 | signal_50dB[:, 0,:] = (real_data.astype(np.float32)).T 29 | signal_50dB[:, 1,:] = (imag_data.astype(np.float32)).T 30 | signal_50dB_c = signal_50dB[:, 0] + 1j * signal_50dB[:, 1] 31 | 32 | with torch.no_grad(): 33 | fr_50dB = fr_module(torch.tensor(signal_50dB)) 34 | fr_50dB = fr_50dB.cpu().data.numpy() 35 | 36 | dataNew = 'data1_deepfreq.mat' 37 | sio.savemat(dataNew, {'data1_deepfreq':fr_50dB}) 38 | 39 | myModel() -------------------------------------------------------------------------------- /Fig1_Fig4/epoch_390.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/epoch_390.pth -------------------------------------------------------------------------------- /Fig1_Fig4/epoch_50.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/epoch_50.pth -------------------------------------------------------------------------------- /Fig1_Fig4/fr.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import scipy.signal 3 | import matplotlib.pyplot as plt 4 | 5 | 6 | def freq2fr(f, xgrid, kernel_type='gaussian', param=None, r=None,nfreq=None): 7 | """ 8 | Convert an array of frequencies to a frequency representation discretized on xgrid. 9 | """ 10 | if kernel_type == 'gaussian': 11 | return gaussian_kernel(f, xgrid, param, r,nfreq) 12 | elif kernel_type == 'triangle': 13 | return triangle(f, xgrid, param) 14 | 15 | # def gaussian_kernel(f, xgrid, sigma, r,nfreq): 16 | # """ 17 | # Create a frequency representation with a Gaussian kernel. 18 | # """ 19 | # for i in range(f.shape[0]): 20 | # r[i,nfreq[i]:]=np.min(r[i,0:nfreq[i]]) 21 | # 22 | # fr = np.zeros((f.shape[0], xgrid.shape[0])) 23 | # # for i in range(f.shape[1]): 24 | # # dist = np.abs(xgrid[None, :] - f[:, i][:, None]) 25 | # # rdist = np.abs(xgrid[None, :] - (f[:, i][:, None] + 1)) 26 | # # ldist = np.abs(xgrid[None, :] - (f[:, i][:, None] - 1)) 27 | # # dist = np.minimum(dist, rdist, ldist) 28 | # # # fr += np.exp(- dist ** 2 / sigma ** 2) 29 | # # fr += np.exp(- dist ** 2 / sigma ** 2) 30 | # # fr=20*np.log10(fr+1e-2)+40*(r[:,i][:,None]) 31 | # # m1 = np.zeros((f.shape[0], xgrid.shape[0]), dtype='float32') 32 | # 33 | # fr_ground = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 34 | # for ii in range(fr.shape[0]): 35 | # 36 | # for i in range(f.shape[1]): 37 | # if f[ii, i] == -10: 38 | # continue 39 | # idx0 = (f[ii, i] + 0.5) / (1 / (np.shape(xgrid)[0])) 40 | # 41 | # ctr0 = int(np.round(idx0)) 42 | # if ctr0 == (np.shape(xgrid)[0]): 43 | # ctr0 = (np.shape(xgrid)[0]) - 1 44 | # 45 | # # if ctr0 == 0: 46 | # # ctr0_up = 1 47 | # # else: 48 | # # ctr0_up = ctr0 - 1 49 | # # if ctr0 == np.shape(xgrid)[0] - 1: 50 | # # ctr0_down = np.shape(xgrid)[0] - 2 51 | # # else: 52 | # # ctr0_down = ctr0 + 1 53 | # 54 | # FX=xgrid[ctr0] 55 | # dist = np.abs(xgrid - FX) 56 | # rdist = np.abs(xgrid - (FX + 1)) 57 | # ldist = np.abs(xgrid - (FX - 1)) 58 | # dist = np.minimum(dist, rdist, ldist) 59 | # fr[ii,:] += np.exp(- dist ** 2 / sigma ** 2)*20*np.log10(10*r[ii,i]+1) 60 | # cost = (np.power(20*np.log10(10*np.max(r[ii,:])+1),2)/ np.power(fr[ii,ctr0],2)) 61 | # fr_ground[ii, ctr0] = cost 62 | # 63 | # 64 | # 65 | # m2 = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 66 | # m1=m2 67 | # return fr, fr_ground.astype('float32'), m1, m2 68 | 69 | def gaussian_kernel(f, xgrid, sigma, r,nfreq): 70 | """ 71 | Create a frequency representation with a Gaussian kernel. 72 | """ 73 | for i in range(f.shape[0]): 74 | r[i,nfreq[i]:]=np.min(r[i,0:nfreq[i]]) 75 | 76 | fr = np.zeros((f.shape[0], xgrid.shape[0])) 77 | for i in range(f.shape[1]): 78 | dist = np.abs(xgrid[None, :] - f[:, i][:, None]) 79 | rdist = np.abs(xgrid[None, :] - (f[:, i][:, None] + 1)) 80 | ldist = np.abs(xgrid[None, :] - (f[:, i][:, None] - 1)) 81 | dist = np.minimum(dist, rdist, ldist) 82 | # fr += np.exp(- dist ** 2 / sigma ** 2) 83 | fr += np.exp(- dist ** 2 / sigma ** 2) 84 | # fr=20*np.log10(fr+1e-2)+40*(r[:,i][:,None]) 85 | m1 = np.zeros((f.shape[0], xgrid.shape[0]), dtype='float32') 86 | 87 | fr_ground = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 88 | fr_ground2 = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 89 | for ii in range(fr.shape[0]): 90 | # mv = -1 91 | # tol = 0 92 | # for k in range(f.shape[1]): 93 | # if f[ii, k] == -10: 94 | # break 95 | # tol += r[ii, k]/np.min(r[ii,:]) 96 | # if r[ii, k]/np.min(r[ii,:]) > mv: 97 | # mv = r[ii, k]/np.min(r[ii,:]) 98 | # mean_v = tol / k 99 | mv=np.max(fr[ii]) 100 | 101 | for i in range(f.shape[1]): 102 | # cost = (np.power(mv, 2) / np.abs(20 * np.log10(r[ii, i]) + 80)).astype('float32') 103 | # cost=1 104 | if f[ii, i] == -10: 105 | continue 106 | idx0 = (f[ii, i] + 0.5) / (1 / (np.shape(xgrid)[0])) 107 | 108 | ctr0 = int(np.round(idx0)) 109 | if ctr0 == (np.shape(xgrid)[0]): 110 | ctr0 = (np.shape(xgrid)[0]) - 1 111 | # if np.power(fr[ii,ctr0],2)==0: 112 | # xx=1 113 | cost = (np.power(mv, 2) / np.power(fr[ii,ctr0],2)).astype('float32') 114 | fr_ground[ii, ctr0] = cost 115 | # if r[ii, i]/np.min(r[ii,:])< mean_v:8 116 | # fr_ground2[ii, ctr0] = mean_v / (fr[ii,ctr0]) 117 | 118 | m1[ii,ctr0]=1 119 | if ctr0 == 0: 120 | ctr0_up = 1 121 | fr_ground[ii, ctr0_up] = cost 122 | m1[ii, ctr0_up] = 1 123 | else: 124 | ctr0_up = ctr0 - 1 125 | fr_ground[ii, ctr0_up] = cost 126 | m1[ii, ctr0_up] = 1 127 | if ctr0 == np.shape(xgrid)[0] - 1: 128 | ctr0_down = np.shape(xgrid)[0] - 2 129 | fr_ground[ii, ctr0_down] = cost 130 | m1[ii, ctr0_down] = 1 131 | else: 132 | ctr0_down = ctr0 + 1 133 | fr_ground[ii, ctr0_down] = cost 134 | m1[ii, ctr0_down] = 1 135 | 136 | m2 = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') - m1 137 | return fr, fr_ground, m1, m2 138 | 139 | 140 | def triangle(f, xgrid, slope): 141 | """ 142 | Create a frequency representation with a triangle kernel. 143 | """ 144 | fr = np.zeros((f.shape[0], xgrid.shape[0])) 145 | for i in range(f.shape[1]): 146 | dist = np.abs(xgrid[None, :] - f[:, i][:, None]) 147 | rdist = np.abs(xgrid[None, :] - (f[:, i][:, None] + 1)) 148 | ldist = np.abs(xgrid[None, :] - (f[:, i][:, None] - 1)) 149 | dist = np.minimum(dist, rdist, ldist) 150 | fr += np.clip(1 - slope * dist, 0, 1) 151 | return fr 152 | 153 | 154 | def find_freq_m(fr, nfreq, xgrid, max_freq=10): 155 | """ 156 | Extract frequencies from a frequency representation by locating the highest peaks. 157 | """ 158 | ff = -np.ones((1, max_freq)) 159 | for n in range(1): 160 | find_peaks_out = scipy.signal.find_peaks(fr, height=(None, None)) 161 | num_spikes = min(len(find_peaks_out[0]), nfreq) 162 | idx = np.argpartition(find_peaks_out[1]['peak_heights'], -num_spikes)[-num_spikes:] 163 | ff[n, :num_spikes] = np.sort(xgrid[find_peaks_out[0][idx]]) 164 | return ff 165 | 166 | 167 | def find_freq(fr, nfreq, xgrid, max_freq=10): 168 | """ 169 | Extract frequencies from a frequency representation by locating the highest peaks. 170 | """ 171 | ff = -np.ones((nfreq.shape[0], max_freq)) 172 | for n in range(len(nfreq)): 173 | 174 | if nfreq[n] < 1: # at least one frequency 175 | nf = 1 176 | else: 177 | nf = nfreq[n] 178 | 179 | find_peaks_out = scipy.signal.find_peaks(fr[n], height=(None, None)) 180 | num_spikes = min(len(find_peaks_out[0]), int(nf)) 181 | idx = np.argpartition(find_peaks_out[1]['peak_heights'], -num_spikes)[-num_spikes:] 182 | ff[n, :num_spikes] = np.sort(xgrid[find_peaks_out[0][idx]]) 183 | return ff 184 | 185 | 186 | def periodogram(signal, xgrid): 187 | """ 188 | Compute periodogram. 189 | """ 190 | js = np.arange(signal.shape[1]) 191 | return (np.abs(np.exp(-2.j * np.pi * xgrid[:, None] * js).dot(signal.T) / signal.shape[1]) ** 2).T 192 | 193 | 194 | def make_hankel(signal, m): 195 | """ 196 | Auxiliary function used in MUSIC. 197 | """ 198 | n = len(signal) 199 | h = np.zeros((m, n - m + 1), dtype='complex128') 200 | for r in range(m): 201 | for c in range(n - m + 1): 202 | h[r, c] = signal[r + c] 203 | return h 204 | 205 | 206 | def music(signal, xgrid, nfreq, m=20): 207 | """ 208 | Compute frequency representation obtained with MUSIC. 209 | """ 210 | music_fr = np.zeros((signal.shape[0], len(xgrid))) 211 | for n in range(signal.shape[0]): 212 | hankel = make_hankel(signal[n], m) 213 | _, _, V = np.linalg.svd(hankel) 214 | v = np.exp(-2.0j * np.pi * np.outer(xgrid[:, None], np.arange(0, signal.shape[1] - m + 1))) 215 | u = V[nfreq[n]:] 216 | fr = -np.log(np.linalg.norm(np.tensordot(u, v, axes=(1, 1)), axis=0) ** 2) 217 | music_fr[n] = fr 218 | return music_fr 219 | -------------------------------------------------------------------------------- /Fig1_Fig4/matlab_imag1.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/matlab_imag1.h5 -------------------------------------------------------------------------------- /Fig1_Fig4/matlab_imag2.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/matlab_imag2.h5 -------------------------------------------------------------------------------- /Fig1_Fig4/matlab_real1.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/matlab_real1.h5 -------------------------------------------------------------------------------- /Fig1_Fig4/matlab_real2.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/matlab_real2.h5 -------------------------------------------------------------------------------- /Fig1_Fig4/music.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/music.fig -------------------------------------------------------------------------------- /Fig1_Fig4/music.m: -------------------------------------------------------------------------------- 1 | clc 2 | clear all 3 | close all 4 | format long 5 | rng('default'); 6 | 7 | L=64; 8 | nfft=L*64; 9 | x_label=-0.5:1/nfft:0.5-1/nfft; 10 | % w=2*pi*[0,1/L,5/L,5.7/L]; 11 | w=2*pi*[-5/L,0/L,5/L,5.7/L]; 12 | y=w/2/pi; 13 | tgt_num=length(w); 14 | amp=ones(1,tgt_num); 15 | amp(tgt_num)=10^(-10/20); 16 | sig=zeros(1,L); 17 | nfft=4096; 18 | search_f=-0.5:1/nfft:0.5-1/nfft; 19 | for i=1:tgt_num 20 | theta=2*pi*rand(); 21 | sig=sig+amp(i)*exp(1i*theta)*exp(1i*w(i)*(0:(L-1))); 22 | end 23 | sig=sig/sqrt(mean(abs(sig.^2))); 24 | %% 25 | SNR=20; 26 | noise=wgn(size(sig,1),size(sig,2),0,'complex'); 27 | noisedSig_20dB=sig*10^(SNR/20)+noise; 28 | SNR=0; 29 | noise=wgn(size(sig,1),size(sig,2),0,'complex'); 30 | noisedSig_0dB=sig*10^(SNR/20)+noise; 31 | 32 | % load noisedSig_20dB 33 | % load noisedSig_0dB 34 | 35 | %% MUSIC 36 | musicWinLen=L/2; 37 | snapNum=L-musicWinLen+1; 38 | x=0; 39 | sk=zeros(musicWinLen,snapNum); 40 | for i=1:snapNum 41 | B1=noisedSig_20dB(i:(i+musicWinLen-1)); 42 | x=x+1; 43 | z1=B1(:); 44 | sk(:,x)=z1; 45 | end 46 | Rss= sk*sk'/snapNum; 47 | 48 | [EV,D] = eig(Rss); 49 | [EVA,I] = sort(diag(D).'); 50 | EV = fliplr(EV(:,I)); 51 | G = EV(:,tgt_num+1:end); 52 | P_music_20dB=zeros(1,nfft); 53 | for i=1:length(search_f) 54 | steeringVec=exp(1i*2*pi*search_f(i)*(0:musicWinLen-1)).'; 55 | P_music_20dB(i)=1/(steeringVec'*G*G'*steeringVec); 56 | end 57 | 58 | %% 59 | musicWinLen=L/2; 60 | snapNum=L-musicWinLen+1; 61 | x=0; 62 | sk=zeros(musicWinLen,snapNum); 63 | for i=1:snapNum 64 | B1=noisedSig_0dB(i:(i+musicWinLen-1)); 65 | x=x+1; 66 | z1=B1(:); 67 | sk(:,x)=z1; 68 | end 69 | Rss= sk*sk'/snapNum; 70 | 71 | [EV,D] = eig(Rss); 72 | [EVA,I] = sort(diag(D).'); 73 | EV = fliplr(EV(:,I)); 74 | G = EV(:,tgt_num+1:end); 75 | P_music_0dB=zeros(1,nfft); 76 | for i=1:length(search_f) 77 | steeringVec=exp(1i*2*pi*search_f(i)*(0:musicWinLen-1)).'; 78 | P_music_0dB(i)=1/(steeringVec'*G*G'*steeringVec); 79 | end 80 | %% 81 | h=figure(2) 82 | set(h,'position',[100 100 1000 600]); 83 | 84 | for i=1:tgt_num 85 | h1=stem(y(i),-80,'r-','Marker','none','linewidth',2); 86 | hold on; 87 | h2=stem(y(i),3,'r-','Marker','none','linewidth',2); 88 | hold on; 89 | set(get(get(h1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 90 | set(get(get(h2,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 91 | end 92 | axis([-0.1 0.15 -40 3]) 93 | set(gca,'FontSize',20); 94 | set(get(gca,'XLabel'),'FontSize',20); 95 | set(get(gca,'YLabel'),'FontSize',20); 96 | normMusic=10*log10(P_music_20dB/max(P_music_20dB)+1e-13); 97 | plot(x_label,real(normMusic).','b:.','linewidth',3); 98 | hold on 99 | normMusic=10*log10(P_music_0dB/max(P_music_0dB)+1e-13); 100 | plot(x_label,real(normMusic).','k:.','linewidth',3); 101 | legend('SNR = 20dB','SNR = 0dB'); 102 | ylabel('Normalized Power / dB'); 103 | xlabel('Normalized freq. / Hz'); 104 | grid on; 105 | hold on; 106 | 107 | % save music.mat P_music_20dB P_music_0dB -------------------------------------------------------------------------------- /Fig1_Fig4/noisedSig_0dB.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/noisedSig_0dB.mat -------------------------------------------------------------------------------- /Fig1_Fig4/noisedSig_20dB.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/noisedSig_20dB.mat -------------------------------------------------------------------------------- /Fig1_Fig4/omp_main.m: -------------------------------------------------------------------------------- 1 | clc 2 | clear all 3 | close all 4 | format long 5 | rng('default'); 6 | 7 | L=64; 8 | nfft=L*64; 9 | x_label=-0.5:1/nfft:0.5-1/nfft; 10 | w=2*pi*[-5/L,0/L,5/L,5.7/L]; 11 | 12 | y=w/2/pi; 13 | tgt_num=length(w); 14 | amp=ones(1,tgt_num); 15 | amp(tgt_num)=10^(-10/20); 16 | sig=zeros(1,L); 17 | nfft=4096; 18 | search_f=-0.5:1/nfft:0.5-1/nfft; 19 | for i=1:tgt_num 20 | theta=2*pi*rand(); 21 | sig=sig+amp(i)*exp(1i*theta)*exp(1i*w(i)*(0:(L-1))); 22 | end 23 | sig=sig/sqrt(mean(abs(sig.^2))); 24 | 25 | SNR=20; 26 | noise=wgn(size(sig,1),size(sig,2),0,'complex'); 27 | noisedSig_20dB=sig*10^(SNR/20); 28 | SNR=0; 29 | noise=wgn(size(sig,1),size(sig,2),0,'complex'); 30 | noisedSig_0dB=sig*10^(SNR/20)+noise; 31 | 32 | %% dictionary construction(1) 33 | nfft=4096; 34 | dict_freq=-0.5:1/nfft:0.5-1/nfft; 35 | t=0:(L-1); 36 | dict=exp(1i*2*pi*dict_freq.'*t).'; 37 | [omp20]=(OMP(dict,noisedSig_20dB.',tgt_num)); 38 | [omp0]=(OMP(dict,noisedSig_0dB.',tgt_num)); 39 | 40 | 41 | %% 42 | h=figure(1) 43 | set(h,'position',[100 100 1000 600]); 44 | 45 | for i=1:tgt_num 46 | h1=stem(y(i),-80,'r-','Marker','none','linewidth',2); 47 | hold on; 48 | h2=stem(y(i),3,'r-','Marker','none','linewidth',2); 49 | hold on; 50 | set(get(get(h1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 51 | set(get(get(h2,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 52 | end 53 | axis([-0.1 0.15 -40 3]) 54 | set(gca,'FontSize',20); 55 | set(get(gca,'XLabel'),'FontSize',20); 56 | set(get(gca,'YLabel'),'FontSize',20); 57 | normomp=20*log10(omp20/max(omp20)+1e-13); 58 | plot(x_label,real(normomp).','b:.','linewidth',3); 59 | hold on 60 | normomp=20*log10(omp0/max(omp0)+1e-13); 61 | plot(x_label,real(normomp).','k:.','linewidth',3); 62 | legend('SNR = 20dB','SNR = 0dB'); 63 | ylabel('Normalized Power / dB'); 64 | xlabel('Normalized freq. / Hz'); 65 | grid on; 66 | hold on; 67 | 68 | % save omp.mat omp20 omp0 -------------------------------------------------------------------------------- /Fig1_Fig4/plot_figure.m: -------------------------------------------------------------------------------- 1 | clc 2 | clear 3 | close all 4 | format long 5 | rng('default') 6 | load peri.mat 7 | load music.mat 8 | load omp.mat 9 | load p_ah.mat 10 | load deepfreq.mat 11 | 12 | h=figure(); 13 | set(h,'position',[100 100 2200 400]); 14 | ha=tight_subplot(1,5,[0.022 0.022],[.24 .08],[.04 .03]); 15 | %% periodogram 16 | tgt_num=4; 17 | nfft=4096; 18 | x_label=-0.5:1/nfft:0.5-1/nfft; 19 | L=64; 20 | w=2*pi*[-1/L,0/L,5/L,6/L]; 21 | y=w/2/pi; 22 | fontsz=16; 23 | axes(ha(1)) 24 | for i=1:tgt_num 25 | h1=stem(y(i),-80,'r-','Marker','none','linewidth',2); 26 | hold on; 27 | h2=stem(y(i),5,'r-','Marker','none','linewidth',2); 28 | hold on; 29 | set(get(get(h1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 30 | set(get(get(h2,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 31 | end 32 | 33 | set(gca,'FontSize',fontsz); 34 | set(get(gca,'XLabel'),'FontSize',fontsz); 35 | set(get(gca,'YLabel'),'FontSize',fontsz); 36 | normPeriodogram=10*log10(periodogram_nowin_20dB/max(periodogram_nowin_20dB)+1e-13); 37 | plot(x_label,normPeriodogram,'b:.','linewidth',2); 38 | hold on; 39 | normPeriodogram_win=10*log10(periodogram_win_20dB/max(periodogram_win_20dB)+1e-13); 40 | plot(x_label,normPeriodogram_win,'k:','linewidth',3); 41 | hold on; 42 | axis([-0.1 0.18 -50 5]) 43 | hh=legend('Rect.','Hamm.'); 44 | set(hh,'Fontsize',fontsz) 45 | ylabel('Normalized Power / dB'); 46 | xlabel({'Normalized freq. / Hz','(a)'}); 47 | grid on; 48 | 49 | %% MUSIC 50 | axes(ha(2)) 51 | w=2*pi*[-5/L,0/L,5/L,5.7/L]; 52 | y=w/2/pi; 53 | for i=1:tgt_num 54 | h1=stem(y(i),-80,'r-','Marker','none','linewidth',2); 55 | hold on; 56 | h2=stem(y(i),5,'r-','Marker','none','linewidth',2); 57 | hold on; 58 | set(get(get(h1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 59 | set(get(get(h2,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 60 | end 61 | axis([-0.1 0.18 -50 5]) 62 | set(gca,'FontSize',fontsz); 63 | set(get(gca,'XLabel'),'FontSize',fontsz); 64 | set(get(gca,'YLabel'),'FontSize',fontsz); 65 | normMusic=10*log10(P_music_20dB/max(P_music_20dB)+1e-13); 66 | plot(x_label,real(normMusic).','b:.','linewidth',2); 67 | hold on 68 | normMusic=10*log10(P_music_0dB/max(P_music_0dB)+1e-13); 69 | plot(x_label,real(normMusic).','k:','linewidth',3); 70 | legend('SNR = 20dB','SNR = 0dB'); 71 | % ylabel('Normalized Power / dB'); 72 | xlabel({'Normalized freq. / Hz','(b)'}); 73 | grid on; 74 | hold on; 75 | 76 | %% omp 77 | axes(ha(3)) 78 | 79 | for i=1:tgt_num 80 | h1=stem(y(i),-80,'r-','Marker','none','linewidth',2); 81 | hold on; 82 | h2=stem(y(i),5,'r-','Marker','none','linewidth',2); 83 | hold on; 84 | set(get(get(h1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 85 | set(get(get(h2,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 86 | end 87 | axis([-0.1 0.18 -50 5]) 88 | set(gca,'FontSize',fontsz); 89 | set(get(gca,'XLabel'),'FontSize',fontsz); 90 | set(get(gca,'YLabel'),'FontSize',fontsz); 91 | normomp=20*log10(omp20/max(omp20)+1e-13); 92 | plot(x_label,real(normomp).','b:.','linewidth',2); 93 | hold on 94 | normomp=20*log10(omp0/max(omp0)+1e-13); 95 | plot(x_label,real(normomp).','k:','linewidth',3); 96 | legend('SNR = 20dB','SNR = 0dB'); 97 | % ylabel('Normalized Power / dB'); 98 | xlabel({'Normalized freq. / Hz','(c)'}); 99 | grid on; 100 | hold on; 101 | 102 | %% cvnn 103 | axes(ha(4)) 104 | 105 | for i=1:tgt_num 106 | h1=stem(y(i),-50,'r-','Marker','none','linewidth',2); 107 | hold on; 108 | h2=stem(y(i),5,'r-','Marker','none','linewidth',2); 109 | hold on; 110 | set(get(get(h1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 111 | set(get(get(h2,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 112 | end 113 | axis([-0.1 0.18 -50 5]) 114 | set(gca,'FontSize',fontsz); 115 | set(get(gca,'XLabel'),'FontSize',fontsz); 116 | set(get(gca,'YLabel'),'FontSize',fontsz); 117 | normah=20*log10(P_ah20/max(P_ah20)+1e-13); 118 | plot(x_label,real(normah).','b:.','linewidth',2); 119 | hold on 120 | normah=20*log10(P_ah0/max(P_ah0)+1e-13); 121 | plot(x_label,real(normah).','k:','linewidth',3); 122 | legend('SNR = 20dB','SNR = 0dB'); 123 | % ylabel('Normalized Power / dB'); 124 | xlabel({'Normalized freq. / Hz','(d)'}); 125 | grid on; 126 | hold on; 127 | 128 | %% DeepFreq 129 | tgt_num=6; 130 | w=2*pi*[-5/L,0/L,5/L,5.7/L,8/L,13/L]; 131 | y=w/2/pi; 132 | 133 | axes(ha(5)) 134 | for i=1:tgt_num 135 | h1=stem(y(i),-80,'r-','Marker','none','linewidth',2); 136 | hold on; 137 | h2=stem(y(i),5,'r-','Marker','none','linewidth',2); 138 | hold on; 139 | set(get(get(h1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 140 | set(get(get(h2,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 141 | end 142 | 143 | set(gca,'FontSize',fontsz); 144 | set(get(gca,'XLabel'),'FontSize',fontsz); 145 | set(get(gca,'YLabel'),'FontSize',fontsz); 146 | 147 | 148 | normDeepFreq=10*log10(data1_deepfreq20.^2/max(data1_deepfreq20.^2)+1e-13); 149 | plot(x_label,real(normDeepFreq),'b:.','linewidth',2); 150 | axis([-0.1 0.25 -50 5]) 151 | % ylabel('Normalized PSD / dB'); 152 | 153 | grid on; 154 | hold on 155 | 156 | normDeepFreq=10*log10(data1_deepfreq0.^2/max(data1_deepfreq0.^2)+1e-13); 157 | plot(x_label,real(normDeepFreq),'k:','linewidth',3); 158 | legend('SNR = 20dB','SNR = 0dB'); 159 | % ylabel('Normalized Power / dB'); 160 | xlabel({'Normalized freq. / Hz','(e)'}); 161 | grid on; 162 | 163 | 164 | -------------------------------------------------------------------------------- /Fig1_Fig4/prdgrm.m: -------------------------------------------------------------------------------- 1 | clc 2 | clear all 3 | close all 4 | format long 5 | rng('default'); 6 | 7 | L=64; 8 | nfft=L*64; 9 | x_label=-0.5:1/nfft:0.5-1/nfft; 10 | 11 | w=2*pi*[-1/L,0/L,5/L,6/L]; 12 | y=w/2/pi; 13 | tgt_num=length(w); 14 | amp=ones(1,tgt_num); 15 | amp(tgt_num-1:tgt_num)=10^(-15/20); 16 | sig=zeros(1,L); 17 | 18 | for i=1:tgt_num 19 | theta=2*pi*rand(); 20 | sig=sig+amp(i)*exp(1i*theta)*exp(1i*w(i)*(0:(L-1))); 21 | end 22 | sig=sig/sqrt(mean(abs(sig.^2))); 23 | %% 24 | SNR=20; 25 | noise=wgn(size(sig,1),size(sig,2),0,'complex'); 26 | noisedSig_20dB=sig*10^(SNR/20)+noise; 27 | 28 | %% periodogram 29 | win=hamming(length(noisedSig_20dB)).'; 30 | periodogram_win_20dB=abs(fftshift(fft(noisedSig_20dB.*win,nfft))).^2/nfft; 31 | periodogram_nowin_20dB=abs(fftshift(fft(noisedSig_20dB,nfft))).^2/nfft; 32 | 33 | h=figure() 34 | set(h,'position',[100 100 1000 600]); 35 | 36 | 37 | for i=1:tgt_num 38 | h1=stem(y(i),-80,'r-','Marker','none','linewidth',2); 39 | hold on; 40 | h2=stem(y(i),3,'r-','Marker','none','linewidth',2); 41 | hold on; 42 | set(get(get(h1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 43 | set(get(get(h2,'Annotation'),'LegendInformation'),'IconDisplayStyle','off'); 44 | end 45 | 46 | set(gca,'FontSize',20); 47 | set(get(gca,'XLabel'),'FontSize',20); 48 | set(get(gca,'YLabel'),'FontSize',20); 49 | normPeriodogram=10*log10(periodogram_nowin_20dB/max(periodogram_nowin_20dB)+1e-13); 50 | plot(x_label,normPeriodogram,'b:.','linewidth',3); 51 | hold on; 52 | normPeriodogram_win=10*log10(periodogram_win_20dB/max(periodogram_win_20dB)+1e-13); 53 | plot(x_label,normPeriodogram_win,'k:.','linewidth',3); 54 | hold on; 55 | axis([-0.1 0.15 -40 3]) 56 | hh=legend('Rect.','Hamm.'); 57 | set(hh,'Fontsize',20) 58 | ylabel('Normalized Power / dB'); 59 | xlabel('Normalized freq. / Hz'); 60 | grid on; 61 | 62 | % save peri.mat periodogram_nowin_20dB periodogram_win_20dB -------------------------------------------------------------------------------- /Fig1_Fig4/readme: -------------------------------------------------------------------------------- 1 | 1. Run music.m, cvnn.m, prdgrm.m, omp_main.m first, and the results are saved. 2 | 2. Run plot_figure.m 3 | -------------------------------------------------------------------------------- /Fig1_Fig4/resfreq_390.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig1_Fig4/resfreq_390.pth -------------------------------------------------------------------------------- /Fig1_Fig4/resfreq_model.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import util 4 | import numpy as np 5 | import fr 6 | import h5py 7 | import scipy.io as sio 8 | 9 | # In[2]: 10 | def myModel(): 11 | fr_path = 'cResFreq_epoch_60.pth' 12 | xgrid = np.linspace(-0.5, 0.5, 4096, endpoint=False) 13 | # load models 14 | fr_module, _, _, _, _ = util.load(fr_path, 'skip') 15 | fr_module.cpu() 16 | fr_module.eval() 17 | 18 | f = h5py.File('matlab_real2.h5', 'r') 19 | real_data2 = f['matlab_real2'][:] 20 | f.close() 21 | f = h5py.File('matlab_imag2.h5', 'r') 22 | imag_data2 = f['matlab_imag2'][:] 23 | f.close() 24 | bz=1; 25 | N = 64 26 | 27 | 28 | signal_50dB2 = np.zeros([int(bz), 2, N]).astype(np.float32) 29 | signal_50dB2[:, 0,:] = (real_data2.astype(np.float32)).T 30 | signal_50dB2[:, 1,:] = (imag_data2.astype(np.float32)).T 31 | 32 | 33 | with torch.no_grad(): 34 | 35 | fr_50dB2 = fr_module(torch.tensor(signal_50dB2)) 36 | fr_50dB2 = fr_50dB2.cpu().data.numpy() 37 | 38 | dataNew = 'data1_resfreq.mat' 39 | sio.savemat(dataNew, {'data1_resfreq':fr_50dB2}) 40 | 41 | 42 | 43 | myModel() -------------------------------------------------------------------------------- /Fig1_Fig4/tight_subplot.m: -------------------------------------------------------------------------------- 1 | function ha = tight_subplot(Nh, Nw, gap, marg_h, marg_w) 2 | 3 | % tight_subplot creates "subplot" axes with adjustable gaps and margins 4 | % 5 | % ha = tight_subplot(Nh, Nw, gap, marg_h, marg_w) 6 | % 7 | % in: Nh number of axes in hight (vertical direction) 8 | % Nw number of axes in width (horizontaldirection) 9 | % gap gaps between the axes in normalized units (0...1) 10 | % or [gap_h gap_w] for different gaps in height and width 11 | % marg_h margins in height in normalized units (0...1) 12 | % or [lower upper] for different lower and upper margins 13 | % marg_w margins in width in normalized units (0...1) 14 | % or [left right] for different left and right margins 15 | % 16 | % out: ha array of handles of the axes objects 17 | % starting from upper left corner, going row-wise as in 18 | % going row-wise as in 19 | % 20 | % Example: ha = tight_subplot(3,2,[.01 .03],[.1 .01],[.01 .01]) 21 | % for ii = 1:6; axes(ha(ii)); plot(randn(10,ii)); end 22 | % set(ha(1:4),'XTickLabel',''); set(ha,'YTickLabel','') 23 | 24 | % Pekka Kumpulainen 20.6.2010 @tut.fi 25 | % Tampere University of Technology / Automation Science and Engineering 26 | 27 | 28 | if nargin<3; gap = .02; end 29 | if nargin<4 || isempty(marg_h); marg_h = .05; end 30 | if nargin<5; marg_w = .05; end 31 | 32 | if numel(gap)==1; 33 | gap = [gap gap]; 34 | end 35 | if numel(marg_w)==1; 36 | marg_w = [marg_w marg_w]; 37 | end 38 | if numel(marg_h)==1; 39 | marg_h = [marg_h marg_h]; 40 | end 41 | 42 | axh = (1-sum(marg_h)-(Nh-1)*gap(1))/Nh; 43 | axw = (1-sum(marg_w)-(Nw-1)*gap(2))/Nw; 44 | 45 | py = 1-marg_h(2)-axh; 46 | 47 | ha = zeros(Nh*Nw,1); 48 | ii = 0; 49 | for ih = 1:Nh 50 | px = marg_w(1); 51 | 52 | for ix = 1:Nw 53 | ii = ii+1; 54 | ha(ii) = axes('Units','normalized', ... 55 | 'Position',[px py axw axh], ... 56 | 'XTickLabel','', ... 57 | 'YTickLabel',''); 58 | px = px+axw+gap(2); 59 | end 60 | py = py-axh-gap(1); 61 | end -------------------------------------------------------------------------------- /Fig1_Fig4/util.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import errno 4 | import complexModules,modules 5 | 6 | def model_parameters(model): 7 | num_params = 0 8 | for param in model.parameters(): 9 | num_params += param.numel() 10 | return num_params 11 | 12 | 13 | def symlink_force(target, link_name): 14 | try: 15 | os.symlink(target, link_name) 16 | except OSError as e: 17 | if e.errno == errno.EEXIST: 18 | os.remove(link_name) 19 | os.symlink(target, link_name) 20 | else: 21 | raise e 22 | 23 | 24 | def save(model, optimizer, scheduler, args, epoch, module_type): 25 | checkpoint = { 26 | 'epoch': epoch, 27 | 'model': model.state_dict(), 28 | 'optimizer': optimizer.state_dict(), 29 | 'scheduler': scheduler.state_dict(), 30 | 'args': args, 31 | } 32 | if scheduler is not None: 33 | checkpoint["scheduler"] = scheduler.state_dict() 34 | if not os.path.exists(os.path.join(args.output_dir, module_type)): 35 | os.makedirs(os.path.join(args.output_dir, module_type)) 36 | cp = os.path.join(args.output_dir, module_type, 'last.pth') 37 | fn = os.path.join(args.output_dir, module_type, 'epoch_'+str(epoch)+'.pth') 38 | torch.save(checkpoint, fn) 39 | symlink_force(fn, cp) 40 | 41 | 42 | def load(fn, module_type, device = torch.device('cuda')): 43 | checkpoint = torch.load(fn, map_location=device) 44 | args = checkpoint['args'] 45 | if device == torch.device('cpu'): 46 | args.use_cuda = False 47 | if module_type == 'fr': 48 | model = modules.set_fr_module(args) 49 | elif module_type == 'skip': 50 | model = complexModules.set_skip_module(args) 51 | elif module_type == 'fc': 52 | model = complexModules.set_fc_module(args) 53 | elif module_type == 'rdn': 54 | model = complexModules.set_rdn_module(args) 55 | elif module_type == 'layer1': 56 | model = modules.set_layer1_module(args) 57 | elif module_type == 'deepfreqRes': 58 | model = modules.set_deepfreqRes_module(args) 59 | elif module_type == 'freq': 60 | model = modules.set_freq_module(args) 61 | else: 62 | raise NotImplementedError('Module type not recognized') 63 | model.load_state_dict(checkpoint['model']) 64 | optimizer, scheduler = set_optim(args, model, module_type) 65 | if checkpoint["scheduler"] is not None: 66 | scheduler.load_state_dict(checkpoint["scheduler"]) 67 | optimizer.load_state_dict(checkpoint["optimizer"]) 68 | return model, optimizer, scheduler, args, checkpoint['epoch'] 69 | 70 | 71 | def set_optim(args, module, module_type): 72 | if module_type == 'fr': 73 | # params = list(module.parameters()) + list(adaptive.parameters()) 74 | optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fr) 75 | elif module_type == 'fc': 76 | optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fc) 77 | elif module_type == 'skip': 78 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 79 | # optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fr) 80 | elif module_type == 'rdn': 81 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 82 | # optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fr) 83 | elif module_type == 'freq': 84 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 85 | # optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fr) 86 | elif module_type == 'deepfreqRes': 87 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 88 | elif module_type == 'layer1': 89 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 90 | 91 | else: 92 | raise(ValueError('Expected module_type to be fr or fc but got {}'.format(module_type))) 93 | scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=7, factor=0.5, verbose=True) 94 | return optimizer, scheduler 95 | 96 | 97 | def print_args(logger, args): 98 | message = '' 99 | for k, v in sorted(vars(args).items()): 100 | message += '\n{:>30}: {:<30}'.format(str(k), str(v)) 101 | logger.info(message) 102 | 103 | args_path = os.path.join(args.output_dir, 'run.args') 104 | with open(args_path, 'wt') as args_file: 105 | args_file.write(message) 106 | args_file.write('\n') 107 | -------------------------------------------------------------------------------- /Fig9/Copy_of_doa_cvnn_module_CP10.m: -------------------------------------------------------------------------------- 1 | 2 | function [wHI, wOH, zO_set] = Copy_of_doa_cvnn_module_CP10 (zI_set, zO_teach_set) 3 | len=size(zI_set,3); 4 | bsz=size(zI_set,1); 5 | sizeI=size(zI_set,2); 6 | sizeH=12; 7 | sizeO=1; 8 | TDL_n=29; 9 | fc=500e3; 10 | k1= 0.03; % learning constant 11 | k2= 0.03; 12 | Ts=1e-7; 13 | rng(123) 14 | wHI = rand(sizeH, sizeI); 15 | wOH = rand(sizeO, sizeH); 16 | wHI(:,1)=1; 17 | wOH(:,1)=1; 18 | 19 | % Power inversion initiation 20 | % zI=zI_set; 21 | % Rxx=squeeze(zI(1,:,:))*squeeze(zI(1,:,:))'/8; 22 | % S=[1,0,0,0,0,0,0,0]'; 23 | % Wopt=Rxx\S; 24 | % Wopt=Wopt/abs(Wopt(1)); 25 | % for j=1:sizeH 26 | % for nn=1:TDL_n 27 | % wHI(j,:,nn)=Wopt; 28 | % end 29 | % end 30 | % wOH_amp=randn(sizeO, sizeH, TDL_n); 31 | % wOH_phase=randn(sizeO, sizeH, TDL_n); 32 | % wOH =wOH_amp.*exp(1i*wOH_phase); 33 | % wHI(:,:,1)=1; 34 | % wOH(:,:,1)=1; 35 | 36 | % wHI_amp=randn(sizeH, sizeI, TDL_n); 37 | % wHI_phase=randn(sizeH, sizeI, TDL_n); 38 | % wHI =wHI_amp.*exp(1i*wHI_phase); 39 | % wOH_amp=randn(sizeO, sizeH, TDL_n); 40 | % wOH_phase=randn(sizeO, sizeH, TDL_n); 41 | % wOH =wOH_amp.*exp(1i*wOH_phase); 42 | % wHI(:,:,1)=1; 43 | % wOH(:,:,1)=1; 44 | 45 | 46 | iteration =501; 47 | counter = 1; 48 | er_matrix = zeros(); 49 | %% input normalization 50 | % for row=1:s 51 | % zI_set(row, 1:end-1) = zI_set(row, 1:end-1)/ max(abs(zI_set(row, 1:end-1))); 52 | % zO_teach_set(row, :) = zO_teach_set(row, :) / max(abs(zO_teach_set(row, :))); 53 | % end 54 | %% 55 | min_er=10000; 56 | while counter < iteration 57 | er = 0; 58 | for iter=1:bsz 59 | for ti=1:len 60 | uHI=zeros(sizeH,len); 61 | yHI=zeros(sizeH,len); 62 | xin=zeros(sizeI,len); 63 | for j=1:sizeH 64 | uj=zeros(1,len); 65 | for i=1:sizeI 66 | uji=zeros(1,len); 67 | if ~(i==1) 68 | ss=squeeze(zI_set(iter,i,:)).'; 69 | xin(i,:)=ss; 70 | wgt_xin=wHI(j,i)*ss; 71 | uji=uji+wgt_xin; 72 | else 73 | uji=squeeze(zI_set(iter,i,:)).'; 74 | end 75 | uj=uj+uji; 76 | end 77 | uHI(j,:)=uj; 78 | yHI(j,:)=tanh(abs(uHI(j,:))).*exp(1i*angle(uHI(j,:))); 79 | end 80 | 81 | % output zO 82 | uOH=zeros(sizeO,len); 83 | yOH=zeros(sizeO,len); 84 | xin2=zeros(sizeH,len); 85 | for j=1:sizeO 86 | uj=zeros(1,len); 87 | for i=1:sizeH 88 | uji=zeros(1,len); 89 | if ~(i==1) 90 | ss=yHI(i,:); 91 | xin2(i,:)=ss; 92 | wgt_xin2=wOH(j,i)*ss; 93 | uji=uji+wgt_xin2; 94 | 95 | else 96 | uji=yHI(i,:); 97 | end 98 | uj=uj+uji; 99 | end 100 | uOH(j,:)=uj; 101 | yOH(j,:)=tanh(abs(uOH(j,:))).*exp(1i*angle(uOH(j,:))); 102 | end 103 | 104 | %loss 105 | temp = yOH(ti)*yOH(ti)'; 106 | er = (1/2) .* sum( temp )+er ; 107 | 108 | zOt = zO_teach_set(iter, :); 109 | zO=yOH; 110 | for jj = 1:sizeO 111 | for ii = 1:sizeH 112 | 113 | if ii==1 114 | deltaEwOH1(jj,ii)=0; 115 | else 116 | deltaEwOH1(jj,ii) = (1- abs(zO(jj,ti)).^2) .* (abs(zO(jj,ti)) - abs(zOt(jj,ti)) .* ... 117 | cos(angle(zO(jj,ti)) - angle(zOt(jj,ti)))) .* abs((xin2(ii,ti))) .* ... 118 | cos(angle(zO(jj,ti)) - angle((xin2(ii,ti))) - angle(wOH(jj,ii))) - ... 119 | abs(zO(jj,ti)) .* abs(zOt(jj,ti)) .* sin(angle(zO(jj,ti)) - angle(zOt(jj,ti))) .* ... 120 | (abs((xin2(ii,ti))) ./ (abs(uOH(jj,ti)))).* ... 121 | sin(angle(zO(jj,ti)) - angle((xin2(ii,ti))) - angle(wOH(jj,ii))); 122 | end 123 | 124 | end 125 | end 126 | 127 | for jj = 1:sizeO 128 | for ii = 1:sizeH 129 | if ii==1 130 | deltaEwOH2(jj,ii)=0; 131 | else 132 | deltaEwOH2(jj,ii) = (1- abs(zO(jj,ti)).^2) .* (abs(zO(jj,ti)) - abs(zOt(jj,ti)) .* ... 133 | cos(angle(zO(jj,ti)) - angle(zOt(jj,ti))) ) .* abs((xin2(ii,ti))) .* ... 134 | sin(angle(zO(jj,ti)) - angle((xin2(ii,ti))) - angle(wOH(jj,ii))) + ... 135 | abs(zO(jj,ti)) .* abs(zOt(jj,ti)) .* sin(angle(zO(jj,ti)) - angle(zOt(jj,ti))) .* ... 136 | (abs((xin2(ii,ti))) ./ (abs(uOH(jj,ti)))).* ... 137 | cos(angle(zO(jj,ti)) - angle((xin2(ii,ti))) - angle(wOH(jj,ii))); 138 | end 139 | end 140 | end 141 | 142 | 143 | % Hermite conjugate 144 | for h = 1:sizeH 145 | zHt(h,:) = zeros(1,len); 146 | end 147 | 148 | zH=yHI; 149 | for jj = 1:sizeH 150 | for ii = 1:sizeI 151 | 152 | if ii==1 153 | deltaEwHI1(jj,ii)=0; 154 | else 155 | deltaEwHI1(jj,ii) = (1- abs(zH(jj,ti)).^2) .* (abs(zH(jj,ti)) - abs(zHt(jj,ti)).* ... 156 | cos(angle(zH(jj,ti)) - angle(zHt(jj,ti)))) .* abs((xin(ii,ti))) .* ... 157 | cos(angle(zH(jj,ti)) - angle((xin(ii,ti))) - angle(wHI(jj,ii))) - ... 158 | abs(zH(jj,ti)) .* abs(zHt(jj,ti)) .* sin(angle(zH(jj,ti)) - angle(zHt(jj,ti))) .* ... 159 | (abs((xin(ii,ti))) ./ (abs(uHI(jj,ti)))).* ... 160 | sin(angle(zH(jj,ti)) - angle((xin(ii,ti))) - angle(wHI(jj,ii))); 161 | end 162 | 163 | end 164 | end 165 | 166 | 167 | 168 | for jj = 1:sizeH 169 | for ii=1:sizeI 170 | 171 | if ii==1 172 | deltaEwHI2(jj,ii)=0; 173 | else 174 | deltaEwHI2(jj,ii) = (1- abs(zH(jj,ti)).^2) .* (abs(zH(jj,ti)) - abs(zHt(jj,ti)) .* ... 175 | cos(angle(zH(jj,ti)) - angle(zHt(jj,ti)))) .* abs((xin(ii,ti))) .* ... 176 | sin(angle(zH(jj,ti)) - angle((xin(ii,ti))) - angle(wHI(jj,ii))) + ... 177 | abs(zH(jj,ti)) .* abs(zHt(jj,ti)) .* sin(angle(zH(jj,ti)) - angle(zHt(jj,ti))) .* ... 178 | (abs((xin(ii,ti))) ./ (abs(uHI(jj,ti)))).* ... 179 | cos(angle(zH(jj,ti)) - angle((xin(ii,ti))) - angle(wHI(jj,ii))); 180 | end 181 | 182 | end 183 | end 184 | 185 | 186 | wHI1 = abs(wHI) - k1 * deltaEwHI1; 187 | wOH1 = abs(wOH) - k2 * deltaEwOH1; 188 | 189 | wHI2 = angle(wHI) - k1 * deltaEwHI2; 190 | wOH2 = angle(wOH) - k2 * deltaEwOH2; 191 | 192 | wHI = wHI1 .* exp(1i* wHI2); 193 | wOH = wOH1 .* exp(1i* wOH2); 194 | zO_set(iter, :) = zO; 195 | end 196 | end 197 | if counter==4000 198 | x=1; 199 | end 200 | er_matrix(counter) = er; 201 | counter = counter +1; 202 | 203 | if er<=min_er 204 | min_er=er; 205 | flag_count=1; 206 | else 207 | flag_count=flag_count+1; 208 | if flag_count>=16 209 | k2=k2/1.2; 210 | k1=k1/1.2; 211 | flag_count=0; 212 | min_er=er; 213 | end 214 | end 215 | hint=[counter,er,k1,k2] 216 | if rem(counter,100)==0 217 | save wgt_freq22.mat wHI wOH 218 | end 219 | end 220 | 221 | end -------------------------------------------------------------------------------- /Fig9/Copy_of_doa_cvnn_module_test_CP10.m: -------------------------------------------------------------------------------- 1 | 2 | function [zO_set,signal] = Copy_of_doa_cvnn_module_test_CP10 (zI_set, wHI,wOH) 3 | len=size(zI_set,3); 4 | N_ang=size(zI_set,1); 5 | sizeI=size(zI_set,2); 6 | sizeH=12; 7 | sizeO=1; 8 | TDL_n=29; 9 | fc=500e3; 10 | Ts=1e-7; 11 | fs=1/Ts; 12 | df=fs/len; 13 | factor=exp(-1i*2*pi*(0:len-1)*df*Ts); 14 | 15 | %% 16 | 17 | for iter=1:N_ang 18 | %TDL output/hidden layer output 19 | uHI=zeros(sizeH,len); 20 | yHI=zeros(sizeH,len); 21 | xin=zeros(sizeI,len); 22 | for j=1:sizeH 23 | uj=zeros(1,len); 24 | for i=1:sizeI 25 | uji=zeros(1,len); 26 | if ~(i==1) 27 | ss=squeeze(zI_set(iter,i,:)).'; 28 | xin(i,:)=ss; 29 | wgt_xin=wHI(j,i)*ss; 30 | uji=uji+wgt_xin; 31 | else 32 | uji=squeeze(zI_set(iter,i,:)).'; 33 | end 34 | uj=uj+uji; 35 | end 36 | uHI(j,:)=uj; 37 | 38 | yHI(j,:)=tanh(abs(uHI(j,:))).*exp(1i*angle(uHI(j,:))); 39 | end 40 | 41 | % output zO 42 | uOH=zeros(sizeO,len); 43 | yOH=zeros(sizeO,len); 44 | xin2=zeros(sizeH,len); 45 | for j=1:sizeO 46 | uj=zeros(1,len); 47 | for i=1:sizeH 48 | uji=zeros(1,len); 49 | if ~(i==1) 50 | ss=yHI(i,:); 51 | xin2(i,:)=ss; 52 | wgt_xin2=wOH(j,i)*ss; 53 | uji=uji+wgt_xin2; 54 | else 55 | uji=yHI(i,:); 56 | end 57 | uj=uj+uji; 58 | end 59 | uOH(j,:)=uj; 60 | % yOH(j,:)=tanh(abs(uOH(j,:))).*exp(1i*angle(uOH(j,:))); 61 | yOH(j,:)=uj; 62 | end 63 | 64 | 65 | temp = yOH*yOH'; 66 | zO_set(iter) = temp; 67 | signal(iter,:)=yOH; 68 | end 69 | 70 | 71 | 72 | end 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /Fig9/OMP.m: -------------------------------------------------------------------------------- 1 | function [A]=OMP(D,X,L) 2 | %============================================= 3 | % Sparse coding of a group of signals based on a given 4 | % dictionary and specified number of atoms to use. 5 | % ||X-DA|| 6 | % input arguments: 7 | % D - the dictionary (its columns MUST be normalized). 8 | % X - the signals to represent 9 | % L - the max. number of coefficients for each signal. 10 | % output arguments: 11 | % A - sparse coefficient matrix. 12 | %============================================= 13 | [n,P]=size(X); 14 | [n,K]=size(D); 15 | for k=1:1:P, 16 | a=[]; 17 | x=X(:,k); %the kth signal sample 18 | residual=x; %initial the residual vector 19 | indx=zeros(L,1); %initial the index vector 20 | 21 | %the jth iter 22 | for j=1:1:L, 23 | 24 | %compute the inner product 25 | proj=D'*residual; 26 | 27 | %find the max value and its index 28 | [maxVal,pos]=max(abs(proj)); 29 | 30 | %store the index 31 | pos=pos(1); 32 | indx(j)=pos; 33 | 34 | %solve the Least squares problem. 35 | a=pinv(D(:,indx(1:j)))*x; 36 | 37 | %compute the residual in the new dictionary 38 | residual=x-D(:,indx(1:j))*a; 39 | 40 | 41 | %the precision is fill our demand. 42 | % if sum(residual.^2) < 1e-6 43 | % break; 44 | % end 45 | end; 46 | temp=zeros(K,1); 47 | temp(indx(1:j))=a; 48 | A(:,k)=sparse(temp); 49 | end; 50 | return; -------------------------------------------------------------------------------- /Fig9/cResFreq_epoch_60.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig9/cResFreq_epoch_60.pth -------------------------------------------------------------------------------- /Fig9/complexFunctions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | @author: spopoff 6 | """ 7 | 8 | from torch.nn.functional import relu, max_pool2d, avg_pool2d, dropout, dropout2d 9 | import torch 10 | 11 | 12 | def complex_matmul(A, B): 13 | ''' 14 | Performs the matrix product between two complex matrices 15 | ''' 16 | 17 | outp_real = torch.matmul(A.real, B.real) - torch.matmul(A.imag, B.imag) 18 | outp_imag = torch.matmul(A.real, B.imag) + torch.matmul(A.imag, B.real) 19 | 20 | return outp_real.type(torch.complex64) + 1j * outp_imag.type(torch.complex64) 21 | 22 | 23 | def complex_avg_pool2d(input, *args, **kwargs): 24 | ''' 25 | Perform complex average pooling. 26 | ''' 27 | absolute_value_real = avg_pool2d(input.real, *args, **kwargs) 28 | absolute_value_imag = avg_pool2d(input.imag, *args, **kwargs) 29 | 30 | return absolute_value_real.type(torch.complex64) + 1j * absolute_value_imag.type(torch.complex64) 31 | 32 | 33 | def complex_relu(input): 34 | return relu(input.real).type(torch.complex64) + 1j * relu(input.imag).type(torch.complex64) 35 | 36 | 37 | def _retrieve_elements_from_indices(tensor, indices): 38 | flattened_tensor = tensor.flatten(start_dim=-2) 39 | output = flattened_tensor.gather(dim=-1, index=indices.flatten(start_dim=-2)).view_as(indices) 40 | return output 41 | 42 | 43 | def complex_max_pool2d(input, kernel_size, stride=None, padding=0, 44 | dilation=1, ceil_mode=False, return_indices=False): 45 | ''' 46 | Perform complex max pooling by selecting on the absolute value on the complex values. 47 | ''' 48 | absolute_value, indices = max_pool2d( 49 | input.abs(), 50 | kernel_size=kernel_size, 51 | stride=stride, 52 | padding=padding, 53 | dilation=dilation, 54 | ceil_mode=ceil_mode, 55 | return_indices=True 56 | ) 57 | # performs the selection on the absolute values 58 | absolute_value = absolute_value.type(torch.complex64) 59 | # retrieve the corresonding phase value using the indices 60 | # unfortunately, the derivative for 'angle' is not implemented 61 | angle = torch.atan2(input.imag, input.real) 62 | # get only the phase values selected by max pool 63 | angle = _retrieve_elements_from_indices(angle, indices) 64 | return absolute_value \ 65 | * (torch.cos(angle).type(torch.complex64) + 1j * torch.sin(angle).type(torch.complex64)) 66 | 67 | 68 | def complex_dropout(input, p=0.5, training=True): 69 | # need to have the same dropout mask for real and imaginary part, 70 | # this not a clean solution! 71 | mask = torch.ones_like(input).type(torch.float32) 72 | mask = dropout(mask, p, training) * 1 / (1 - p) 73 | return mask * input 74 | 75 | 76 | def complex_dropout2d(input, p=0.5, training=True): 77 | # need to have the same dropout mask for real and imaginary part, 78 | # this not a clean solution! 79 | mask = torch.ones_like(input).type(torch.float32) 80 | mask = dropout2d(mask, p, training) * 1 / (1 - p) 81 | return mask * input -------------------------------------------------------------------------------- /Fig9/deepfreq_epoch_120.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Fig9/deepfreq_epoch_120.pth -------------------------------------------------------------------------------- /Fig9/deepfreq_model.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | import torch 4 | import util 5 | import matplotlib.pyplot as plt 6 | import h5py 7 | import scipy.io as sio 8 | 9 | # In[2]: 10 | def myModel(): 11 | fr_path = 'deepfreq_epoch_120.pth' 12 | xgrid = np.linspace(-0.5, 0.5, 4096, endpoint=False) 13 | # load models 14 | fr_module, _, _, _, _ = util.load(fr_path, 'fr') 15 | fr_module.cpu() 16 | fr_module.eval() 17 | 18 | f = h5py.File('matlab_real1.h5', 'r') 19 | real_data = f['matlab_real1'][:] 20 | f.close() 21 | f = h5py.File('matlab_imag1.h5', 'r') 22 | imag_data = f['matlab_imag1'][:] 23 | f.close() 24 | bz=1; 25 | N = 64 26 | 27 | signal_50dB = np.zeros([int(bz), 2, N]).astype(np.float32) 28 | signal_50dB[:, 0,:] = (real_data.astype(np.float32)).T 29 | signal_50dB[:, 1,:] = (imag_data.astype(np.float32)).T 30 | signal_50dB_c = signal_50dB[:, 0] + 1j * signal_50dB[:, 1] 31 | 32 | with torch.no_grad(): 33 | fr_50dB = fr_module(torch.tensor(signal_50dB)) 34 | fr_50dB = fr_50dB.cpu().data.numpy() 35 | 36 | dataNew = 'data1_deepfreq.mat' 37 | sio.savemat(dataNew, {'data1_deepfreq':fr_50dB}) 38 | 39 | myModel() -------------------------------------------------------------------------------- /Fig9/fr.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import scipy.signal 3 | import matplotlib.pyplot as plt 4 | 5 | 6 | def freq2fr(f, xgrid, kernel_type='gaussian', param=None, r=None,nfreq=None): 7 | """ 8 | Convert an array of frequencies to a frequency representation discretized on xgrid. 9 | """ 10 | if kernel_type == 'gaussian': 11 | return gaussian_kernel(f, xgrid, param, r,nfreq) 12 | elif kernel_type == 'triangle': 13 | return triangle(f, xgrid, param) 14 | 15 | # def gaussian_kernel(f, xgrid, sigma, r,nfreq): 16 | # """ 17 | # Create a frequency representation with a Gaussian kernel. 18 | # """ 19 | # for i in range(f.shape[0]): 20 | # r[i,nfreq[i]:]=np.min(r[i,0:nfreq[i]]) 21 | # 22 | # fr = np.zeros((f.shape[0], xgrid.shape[0])) 23 | # # for i in range(f.shape[1]): 24 | # # dist = np.abs(xgrid[None, :] - f[:, i][:, None]) 25 | # # rdist = np.abs(xgrid[None, :] - (f[:, i][:, None] + 1)) 26 | # # ldist = np.abs(xgrid[None, :] - (f[:, i][:, None] - 1)) 27 | # # dist = np.minimum(dist, rdist, ldist) 28 | # # # fr += np.exp(- dist ** 2 / sigma ** 2) 29 | # # fr += np.exp(- dist ** 2 / sigma ** 2) 30 | # # fr=20*np.log10(fr+1e-2)+40*(r[:,i][:,None]) 31 | # # m1 = np.zeros((f.shape[0], xgrid.shape[0]), dtype='float32') 32 | # 33 | # fr_ground = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 34 | # for ii in range(fr.shape[0]): 35 | # 36 | # for i in range(f.shape[1]): 37 | # if f[ii, i] == -10: 38 | # continue 39 | # idx0 = (f[ii, i] + 0.5) / (1 / (np.shape(xgrid)[0])) 40 | # 41 | # ctr0 = int(np.round(idx0)) 42 | # if ctr0 == (np.shape(xgrid)[0]): 43 | # ctr0 = (np.shape(xgrid)[0]) - 1 44 | # 45 | # # if ctr0 == 0: 46 | # # ctr0_up = 1 47 | # # else: 48 | # # ctr0_up = ctr0 - 1 49 | # # if ctr0 == np.shape(xgrid)[0] - 1: 50 | # # ctr0_down = np.shape(xgrid)[0] - 2 51 | # # else: 52 | # # ctr0_down = ctr0 + 1 53 | # 54 | # FX=xgrid[ctr0] 55 | # dist = np.abs(xgrid - FX) 56 | # rdist = np.abs(xgrid - (FX + 1)) 57 | # ldist = np.abs(xgrid - (FX - 1)) 58 | # dist = np.minimum(dist, rdist, ldist) 59 | # fr[ii,:] += np.exp(- dist ** 2 / sigma ** 2)*20*np.log10(10*r[ii,i]+1) 60 | # cost = (np.power(20*np.log10(10*np.max(r[ii,:])+1),2)/ np.power(fr[ii,ctr0],2)) 61 | # fr_ground[ii, ctr0] = cost 62 | # 63 | # 64 | # 65 | # m2 = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 66 | # m1=m2 67 | # return fr, fr_ground.astype('float32'), m1, m2 68 | 69 | def gaussian_kernel(f, xgrid, sigma, r,nfreq): 70 | """ 71 | Create a frequency representation with a Gaussian kernel. 72 | """ 73 | for i in range(f.shape[0]): 74 | r[i,nfreq[i]:]=np.min(r[i,0:nfreq[i]]) 75 | 76 | fr = np.zeros((f.shape[0], xgrid.shape[0])) 77 | for i in range(f.shape[1]): 78 | dist = np.abs(xgrid[None, :] - f[:, i][:, None]) 79 | rdist = np.abs(xgrid[None, :] - (f[:, i][:, None] + 1)) 80 | ldist = np.abs(xgrid[None, :] - (f[:, i][:, None] - 1)) 81 | dist = np.minimum(dist, rdist, ldist) 82 | # fr += np.exp(- dist ** 2 / sigma ** 2) 83 | fr += np.exp(- dist ** 2 / sigma ** 2) 84 | # fr=20*np.log10(fr+1e-2)+40*(r[:,i][:,None]) 85 | m1 = np.zeros((f.shape[0], xgrid.shape[0]), dtype='float32') 86 | 87 | fr_ground = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 88 | fr_ground2 = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 89 | for ii in range(fr.shape[0]): 90 | # mv = -1 91 | # tol = 0 92 | # for k in range(f.shape[1]): 93 | # if f[ii, k] == -10: 94 | # break 95 | # tol += r[ii, k]/np.min(r[ii,:]) 96 | # if r[ii, k]/np.min(r[ii,:]) > mv: 97 | # mv = r[ii, k]/np.min(r[ii,:]) 98 | # mean_v = tol / k 99 | mv=np.max(fr[ii]) 100 | 101 | for i in range(f.shape[1]): 102 | # cost = (np.power(mv, 2) / np.abs(20 * np.log10(r[ii, i]) + 80)).astype('float32') 103 | # cost=1 104 | if f[ii, i] == -10: 105 | continue 106 | idx0 = (f[ii, i] + 0.5) / (1 / (np.shape(xgrid)[0])) 107 | 108 | ctr0 = int(np.round(idx0)) 109 | if ctr0 == (np.shape(xgrid)[0]): 110 | ctr0 = (np.shape(xgrid)[0]) - 1 111 | # if np.power(fr[ii,ctr0],2)==0: 112 | # xx=1 113 | cost = (np.power(mv, 2) / np.power(fr[ii,ctr0],2)).astype('float32') 114 | fr_ground[ii, ctr0] = cost 115 | # if r[ii, i]/np.min(r[ii,:])< mean_v:8 116 | # fr_ground2[ii, ctr0] = mean_v / (fr[ii,ctr0]) 117 | 118 | m1[ii,ctr0]=1 119 | if ctr0 == 0: 120 | ctr0_up = 1 121 | fr_ground[ii, ctr0_up] = cost 122 | m1[ii, ctr0_up] = 1 123 | else: 124 | ctr0_up = ctr0 - 1 125 | fr_ground[ii, ctr0_up] = cost 126 | m1[ii, ctr0_up] = 1 127 | if ctr0 == np.shape(xgrid)[0] - 1: 128 | ctr0_down = np.shape(xgrid)[0] - 2 129 | fr_ground[ii, ctr0_down] = cost 130 | m1[ii, ctr0_down] = 1 131 | else: 132 | ctr0_down = ctr0 + 1 133 | fr_ground[ii, ctr0_down] = cost 134 | m1[ii, ctr0_down] = 1 135 | 136 | m2 = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') - m1 137 | return fr, fr_ground, m1, m2 138 | 139 | 140 | def triangle(f, xgrid, slope): 141 | """ 142 | Create a frequency representation with a triangle kernel. 143 | """ 144 | fr = np.zeros((f.shape[0], xgrid.shape[0])) 145 | for i in range(f.shape[1]): 146 | dist = np.abs(xgrid[None, :] - f[:, i][:, None]) 147 | rdist = np.abs(xgrid[None, :] - (f[:, i][:, None] + 1)) 148 | ldist = np.abs(xgrid[None, :] - (f[:, i][:, None] - 1)) 149 | dist = np.minimum(dist, rdist, ldist) 150 | fr += np.clip(1 - slope * dist, 0, 1) 151 | return fr 152 | 153 | 154 | def find_freq_m(fr, nfreq, xgrid, max_freq=10): 155 | """ 156 | Extract frequencies from a frequency representation by locating the highest peaks. 157 | """ 158 | ff = -np.ones((1, max_freq)) 159 | for n in range(1): 160 | find_peaks_out = scipy.signal.find_peaks(fr, height=(None, None)) 161 | num_spikes = min(len(find_peaks_out[0]), nfreq) 162 | idx = np.argpartition(find_peaks_out[1]['peak_heights'], -num_spikes)[-num_spikes:] 163 | ff[n, :num_spikes] = np.sort(xgrid[find_peaks_out[0][idx]]) 164 | return ff 165 | 166 | 167 | def find_freq(fr, nfreq, xgrid, max_freq=10): 168 | """ 169 | Extract frequencies from a frequency representation by locating the highest peaks. 170 | """ 171 | ff = -np.ones((nfreq.shape[0], max_freq)) 172 | for n in range(len(nfreq)): 173 | 174 | if nfreq[n] < 1: # at least one frequency 175 | nf = 1 176 | else: 177 | nf = nfreq[n] 178 | 179 | find_peaks_out = scipy.signal.find_peaks(fr[n], height=(None, None)) 180 | num_spikes = min(len(find_peaks_out[0]), int(nf)) 181 | idx = np.argpartition(find_peaks_out[1]['peak_heights'], -num_spikes)[-num_spikes:] 182 | ff[n, :num_spikes] = np.sort(xgrid[find_peaks_out[0][idx]]) 183 | return ff 184 | 185 | 186 | def periodogram(signal, xgrid): 187 | """ 188 | Compute periodogram. 189 | """ 190 | js = np.arange(signal.shape[1]) 191 | return (np.abs(np.exp(-2.j * np.pi * xgrid[:, None] * js).dot(signal.T) / signal.shape[1]) ** 2).T 192 | 193 | 194 | def make_hankel(signal, m): 195 | """ 196 | Auxiliary function used in MUSIC. 197 | """ 198 | n = len(signal) 199 | h = np.zeros((m, n - m + 1), dtype='complex128') 200 | for r in range(m): 201 | for c in range(n - m + 1): 202 | h[r, c] = signal[r + c] 203 | return h 204 | 205 | 206 | def music(signal, xgrid, nfreq, m=20): 207 | """ 208 | Compute frequency representation obtained with MUSIC. 209 | """ 210 | music_fr = np.zeros((signal.shape[0], len(xgrid))) 211 | for n in range(signal.shape[0]): 212 | hankel = make_hankel(signal[n], m) 213 | _, _, V = np.linalg.svd(hankel) 214 | v = np.exp(-2.0j * np.pi * np.outer(xgrid[:, None], np.arange(0, signal.shape[1] - m + 1))) 215 | u = V[nfreq[n]:] 216 | fr = -np.log(np.linalg.norm(np.tensordot(u, v, axes=(1, 1)), axis=0) ** 2) 217 | music_fr[n] = fr 218 | return music_fr 219 | -------------------------------------------------------------------------------- /Fig9/readme: -------------------------------------------------------------------------------- 1 | Run Fig9_main_sidelobe_main.m 2 | -------------------------------------------------------------------------------- /Fig9/resfreq_model.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import util 4 | import numpy as np 5 | import fr 6 | import h5py 7 | import scipy.io as sio 8 | 9 | # In[2]: 10 | def myModel(): 11 | fr_path = 'cResFreq_epoch_60.pth' 12 | xgrid = np.linspace(-0.5, 0.5, 4096, endpoint=False) 13 | # load models 14 | fr_module, _, _, _, _ = util.load(fr_path, 'skip') 15 | fr_module.cpu() 16 | fr_module.eval() 17 | 18 | f = h5py.File('matlab_real2.h5', 'r') 19 | real_data2 = f['matlab_real2'][:] 20 | f.close() 21 | f = h5py.File('matlab_imag2.h5', 'r') 22 | imag_data2 = f['matlab_imag2'][:] 23 | f.close() 24 | bz=1; 25 | N = 64 26 | 27 | 28 | signal_50dB2 = np.zeros([int(bz), 2, N]).astype(np.float32) 29 | signal_50dB2[:, 0,:] = (real_data2.astype(np.float32)).T 30 | signal_50dB2[:, 1,:] = (imag_data2.astype(np.float32)).T 31 | 32 | 33 | with torch.no_grad(): 34 | 35 | fr_50dB2 = fr_module(torch.tensor(signal_50dB2)) 36 | fr_50dB2 = fr_50dB2.cpu().data.numpy() 37 | 38 | dataNew = 'data1_resfreq.mat' 39 | sio.savemat(dataNew, {'data1_resfreq':fr_50dB2}) 40 | 41 | 42 | 43 | myModel() -------------------------------------------------------------------------------- /Fig9/tight_subplot.m: -------------------------------------------------------------------------------- 1 | function ha = tight_subplot(Nh, Nw, gap, marg_h, marg_w) 2 | 3 | % tight_subplot creates "subplot" axes with adjustable gaps and margins 4 | % 5 | % ha = tight_subplot(Nh, Nw, gap, marg_h, marg_w) 6 | % 7 | % in: Nh number of axes in hight (vertical direction) 8 | % Nw number of axes in width (horizontaldirection) 9 | % gap gaps between the axes in normalized units (0...1) 10 | % or [gap_h gap_w] for different gaps in height and width 11 | % marg_h margins in height in normalized units (0...1) 12 | % or [lower upper] for different lower and upper margins 13 | % marg_w margins in width in normalized units (0...1) 14 | % or [left right] for different left and right margins 15 | % 16 | % out: ha array of handles of the axes objects 17 | % starting from upper left corner, going row-wise as in 18 | % going row-wise as in 19 | % 20 | % Example: ha = tight_subplot(3,2,[.01 .03],[.1 .01],[.01 .01]) 21 | % for ii = 1:6; axes(ha(ii)); plot(randn(10,ii)); end 22 | % set(ha(1:4),'XTickLabel',''); set(ha,'YTickLabel','') 23 | 24 | % Pekka Kumpulainen 20.6.2010 @tut.fi 25 | % Tampere University of Technology / Automation Science and Engineering 26 | 27 | 28 | if nargin<3; gap = .02; end 29 | if nargin<4 || isempty(marg_h); marg_h = .05; end 30 | if nargin<5; marg_w = .05; end 31 | 32 | if numel(gap)==1; 33 | gap = [gap gap]; 34 | end 35 | if numel(marg_w)==1; 36 | marg_w = [marg_w marg_w]; 37 | end 38 | if numel(marg_h)==1; 39 | marg_h = [marg_h marg_h]; 40 | end 41 | 42 | axh = (1-sum(marg_h)-(Nh-1)*gap(1))/Nh; 43 | axw = (1-sum(marg_w)-(Nw-1)*gap(2))/Nw; 44 | 45 | py = 1-marg_h(2)-axh; 46 | 47 | ha = zeros(Nh*Nw,1); 48 | ii = 0; 49 | for ih = 1:Nh 50 | px = marg_w(1); 51 | 52 | for ix = 1:Nw 53 | ii = ii+1; 54 | ha(ii) = axes('Units','normalized', ... 55 | 'Position',[px py axw axh], ... 56 | 'XTickLabel','', ... 57 | 'YTickLabel',''); 58 | px = px+axw+gap(2); 59 | end 60 | py = py-axh-gap(1); 61 | end -------------------------------------------------------------------------------- /Fig9/util.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import errno 4 | import complexModules,modules 5 | 6 | def model_parameters(model): 7 | num_params = 0 8 | for param in model.parameters(): 9 | num_params += param.numel() 10 | return num_params 11 | 12 | 13 | def symlink_force(target, link_name): 14 | try: 15 | os.symlink(target, link_name) 16 | except OSError as e: 17 | if e.errno == errno.EEXIST: 18 | os.remove(link_name) 19 | os.symlink(target, link_name) 20 | else: 21 | raise e 22 | 23 | 24 | def save(model, optimizer, scheduler, args, epoch, module_type): 25 | checkpoint = { 26 | 'epoch': epoch, 27 | 'model': model.state_dict(), 28 | 'optimizer': optimizer.state_dict(), 29 | 'scheduler': scheduler.state_dict(), 30 | 'args': args, 31 | } 32 | if scheduler is not None: 33 | checkpoint["scheduler"] = scheduler.state_dict() 34 | if not os.path.exists(os.path.join(args.output_dir, module_type)): 35 | os.makedirs(os.path.join(args.output_dir, module_type)) 36 | cp = os.path.join(args.output_dir, module_type, 'last.pth') 37 | fn = os.path.join(args.output_dir, module_type, 'epoch_'+str(epoch)+'.pth') 38 | torch.save(checkpoint, fn) 39 | symlink_force(fn, cp) 40 | 41 | 42 | def load(fn, module_type, device = torch.device('cuda')): 43 | checkpoint = torch.load(fn, map_location=device) 44 | args = checkpoint['args'] 45 | if device == torch.device('cpu'): 46 | args.use_cuda = False 47 | if module_type == 'fr': 48 | model = modules.set_fr_module(args) 49 | elif module_type == 'skip': 50 | model = complexModules.set_skip_module(args) 51 | elif module_type == 'fc': 52 | model = complexModules.set_fc_module(args) 53 | elif module_type == 'rdn': 54 | model = complexModules.set_rdn_module(args) 55 | elif module_type == 'layer1': 56 | model = modules.set_layer1_module(args) 57 | elif module_type == 'deepfreqRes': 58 | model = modules.set_deepfreqRes_module(args) 59 | elif module_type == 'freq': 60 | model = modules.set_freq_module(args) 61 | else: 62 | raise NotImplementedError('Module type not recognized') 63 | model.load_state_dict(checkpoint['model']) 64 | optimizer, scheduler = set_optim(args, model, module_type) 65 | if checkpoint["scheduler"] is not None: 66 | scheduler.load_state_dict(checkpoint["scheduler"]) 67 | optimizer.load_state_dict(checkpoint["optimizer"]) 68 | return model, optimizer, scheduler, args, checkpoint['epoch'] 69 | 70 | 71 | def set_optim(args, module, module_type): 72 | if module_type == 'fr': 73 | # params = list(module.parameters()) + list(adaptive.parameters()) 74 | optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fr) 75 | elif module_type == 'fc': 76 | optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fc) 77 | elif module_type == 'skip': 78 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 79 | # optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fr) 80 | elif module_type == 'rdn': 81 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 82 | # optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fr) 83 | elif module_type == 'freq': 84 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 85 | # optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fr) 86 | elif module_type == 'deepfreqRes': 87 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 88 | elif module_type == 'layer1': 89 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 90 | 91 | else: 92 | raise(ValueError('Expected module_type to be fr or fc but got {}'.format(module_type))) 93 | scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=7, factor=0.5, verbose=True) 94 | return optimizer, scheduler 95 | 96 | 97 | def print_args(logger, args): 98 | message = '' 99 | for k, v in sorted(vars(args).items()): 100 | message += '\n{:>30}: {:<30}'.format(str(k), str(v)) 101 | logger.info(message) 102 | 103 | args_path = os.path.join(args.output_dir, 'run.args') 104 | with open(args_path, 'wt') as args_file: 105 | args_file.write(message) 106 | args_file.write('\n') 107 | -------------------------------------------------------------------------------- /Python codes/RDN-1D/ACCURACY.py: -------------------------------------------------------------------------------- 1 | 2 | import argparse 3 | import numpy as np 4 | from data import noise 5 | from data.data import gen_signal_accuracy 6 | import torch 7 | import util 8 | from numpy.fft import fft,fftshift 9 | import pickle 10 | from data import fr 11 | import matplotlib.pyplot as plt 12 | import matlab.engine 13 | import h5py 14 | eng = matlab.engine.start_matlab() 15 | 16 | def crlb(N,SNR): 17 | k=np.array(list(range(-1*int(N/2),int((N-1)/2)))) 18 | a0=10**(SNR/20) 19 | l1=k**2 20 | J=8*np.pi*np.pi*a0*a0*np.sum(l1) 21 | fc=np.sqrt(1/J) 22 | return fc 23 | 24 | 25 | if __name__ == '__main__': 26 | parser = argparse.ArgumentParser() 27 | 28 | parser.add_argument("--output_dir", default='./test_accuracy', type=str, 29 | help="The output directory where the data will be written.") 30 | parser.add_argument('--overwrite', action='store_true',default=1, 31 | help="Overwrite the content of the output directory") 32 | 33 | parser.add_argument("--n_test", default=1, type=int, 34 | help="Number of signals") 35 | parser.add_argument("--signal_dimension", default=64, type=int, 36 | help="Dimension of sinusoidal signal") 37 | parser.add_argument("--minimum_separation", default=0.5, type=float, 38 | help="Minimum distance between spikes, normalized by 1/signal_dim") 39 | parser.add_argument("--max_freq", default=10, type=int, 40 | help="Maximum number of frequency, the distribution is uniform between 1 and max_freq") 41 | parser.add_argument("--distance", default="normal", type=str, 42 | help="Distribution type of the inter-frequency distance") 43 | parser.add_argument("--amplitude", default="normal_floor", type=str, 44 | help="Distribution type of the spike amplitude") 45 | parser.add_argument("--floor_amplitude", default=0.1, type=float, 46 | help="Minimum spike amplitude (only used for the normal_floor distribution)") 47 | parser.add_argument('--dB', nargs='+', default=['-15', '-10','-5', '0', '5', '10', '15', '20', '25', '30'], 48 | help='additional dB levels') 49 | 50 | parser.add_argument("--numpy_seed", default=105, type=int, 51 | help="Numpy seed") 52 | parser.add_argument("--torch_seed", default=94, type=int, 53 | help="Numpy seed") 54 | 55 | args = parser.parse_args() 56 | np.random.seed(args.numpy_seed) 57 | torch.manual_seed(args.torch_seed) 58 | 59 | cResFreq_path = 'checkpoint/skipfreq_snr_big8/fr/epoch_60.pth' 60 | spcFreq_path = "checkpoint/freq_train_big8/fr/epoch_140.pth" 61 | deepfreq_path = "checkpoint/deepfreq_norm_snr40_big8/fr/deepfreq_epoch_120.pth" 62 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 63 | 64 | cResFreq_module, _, _, _, _ = util.load(cResFreq_path, 'skip', device) 65 | cResFreq_module.cpu() 66 | cResFreq_module.eval() 67 | spcFreq_module, _, _, _, _ = util.load(spcFreq_path, 'freq', device) 68 | spcFreq_module.cpu() 69 | spcFreq_module.eval() 70 | deepfreq_module, _, _, _, _ = util.load(deepfreq_path, 'fr', device) 71 | deepfreq_module.cpu() 72 | deepfreq_module.eval() 73 | x_len = 1024*4 74 | xgrid = np.linspace(-0.5, 0.5, x_len, endpoint=False) 75 | 76 | s, f, nfreq,r = gen_signal_accuracy( 77 | num_samples=args.n_test, 78 | signal_dim=args.signal_dimension, 79 | num_freq=args.max_freq, 80 | min_sep=args.minimum_separation, 81 | distance=args.distance, 82 | amplitude=args.amplitude, 83 | floor_amplitude=args.floor_amplitude, 84 | variable_num_freq=True) 85 | 86 | ff = 0.200001 87 | db=list(range(-15,18,3)) 88 | 89 | eval_snrs = [np.float(x) for x in db] 90 | iter_num = 1000 91 | deepfreq_est = np.zeros([len(eval_snrs),iter_num]) 92 | cResFreq_est = np.zeros([len(eval_snrs), iter_num]) 93 | fft_est = np.zeros([len(eval_snrs),iter_num]) 94 | spcFreq_est = np.zeros([len(eval_snrs),iter_num]) 95 | music_est = np.zeros([len(eval_snrs),iter_num]) 96 | omp_est = np.zeros([len(eval_snrs), iter_num]) 97 | fc=np.zeros(len(eval_snrs)) 98 | for k, snr in enumerate(eval_snrs): 99 | fc[k]=crlb(args.signal_dimension,snr) 100 | for iter in range(iter_num): 101 | print(k,iter) 102 | noisy_signals = noise.noise_torch(torch.tensor(s), snr, 'gaussian').cpu().numpy() 103 | signal_c = noisy_signals[:, 0] + 1j * noisy_signals[:, 1] 104 | 105 | with torch.no_grad(): 106 | mv = np.max(np.sqrt(pow(noisy_signals[0][0], 2) + pow(noisy_signals[0][1], 2))) 107 | noisy_signals[0][0] = noisy_signals[0][0] / mv 108 | noisy_signals[0][1] = noisy_signals[0][1] / mv 109 | file = h5py.File('signal.h5', 'w') # 创建一个h5文件,文件指针是f 110 | file['signal'] = noisy_signals[0] # 将数据写入文件的主键data下面 111 | file.close() 112 | file = h5py.File('tgt_num.h5', 'w') # 创建一个h5文件,文件指针是f 113 | file['tgt_num'] = nfreq[0] # 将数据写入文件的主键data下面 114 | file.close() 115 | fft_sig = fft(signal_c, 256, 1) 116 | fft_sig = np.abs(fft_sig / np.max(np.abs(fft_sig), 1)[:, None]) 117 | 118 | deepfreq_fr = deepfreq_module(torch.tensor(noisy_signals[0][None]))[0] 119 | spcFreq_fr = spcFreq_module(torch.tensor(fft_sig[0][None]).to(torch.float32))[0] 120 | cResFreq_fr = cResFreq_module(torch.tensor(noisy_signals[0][None]))[0] 121 | 122 | music_fr = fr.music(signal_c[0][None], xgrid, nfreq[0][None])[0] 123 | periodogram_fr = fr.periodogram(signal_c[0][None], xgrid)[0] 124 | omp_fr = eng.omp_func(nargout=1) 125 | omp_fr = omp_fr[0] 126 | 127 | deepfreq_fr = deepfreq_fr.cpu().data.numpy() 128 | f_hat = fr.find_freq_m(deepfreq_fr, nfreq[0], xgrid) 129 | deepfreq_est[k,iter]=f_hat[0,0] 130 | 131 | spcFreq_fr = spcFreq_fr.cpu().data.numpy() 132 | f_hat = fr.find_freq_m(spcFreq_fr, nfreq[0], xgrid) 133 | spcFreq_est[k,iter]=f_hat[0,0] 134 | 135 | 136 | cResFreq_fr = cResFreq_fr.cpu().data.numpy() 137 | f_hat = fr.find_freq_m(cResFreq_fr, nfreq[0], xgrid) 138 | cResFreq_est[k, iter] = f_hat[0,0] 139 | 140 | f_hat = fr.find_freq_m(music_fr, nfreq[0], xgrid) 141 | music_est[k, iter] =f_hat[0,0] 142 | 143 | 144 | f_hat = fr.find_freq_m(periodogram_fr, nfreq[0], xgrid) 145 | fft_est[k, iter] = f_hat[0,0] 146 | 147 | f_hat = fr.find_freq_m(omp_fr, nfreq[0], xgrid) 148 | omp_est[k, iter] = f_hat[0, 0] 149 | x=1 150 | 151 | 152 | # pickle.dump(fft_est, open('fft_acc.txt', 'wb')) 153 | # pickle.dump(music_est, open('music_acc.txt', 'wb')) 154 | # pickle.dump(deepfreq_est, open('deepfreq_acc.txt', 'wb')) 155 | # pickle.dump(spcFreq_est, open('spcFreq_acc.txt', 'wb')) 156 | # pickle.dump(cResFreq_est, open('cResFreq_acc.txt', 'wb')) 157 | # 158 | # fft_est = pickle.load(open('fft_acc.txt', 'rb')) 159 | # music_est = pickle.load(open('music_acc.txt', 'rb')) 160 | # deepfreq_est = pickle.load(open('deepfreq_acc.txt', 'rb')) 161 | # spcFreq_est = pickle.load(open('spcFreq_acc.txt', 'rb')) 162 | # cResFreq_est = pickle.load(open('cResFreq_acc.txt', 'rb')) 163 | 164 | acc_music=np.zeros([len(db),1]) 165 | acc_fft=np.zeros([len(db),1]) 166 | acc_deepfreq=np.zeros([len(db),1]) 167 | acc_spcFreq=np.zeros([len(db),1]) 168 | acc_cResFreq=np.zeros([len(db),1]) 169 | acc_omp = np.zeros([len(db), 1]) 170 | for i in range(len(db)): 171 | tmp=fft_est[i,:]-ff 172 | acc_fft[i]=np.sqrt(np.mean(pow(tmp,2))) 173 | tmp=music_est[i,:]-ff 174 | acc_music[i]=np.sqrt(np.mean(pow(tmp,2))) 175 | tmp=deepfreq_est[i,:]-ff 176 | acc_deepfreq[i]=np.sqrt(np.mean(pow(tmp,2))) 177 | tmp=spcFreq_est[i,:]-ff 178 | acc_spcFreq[i]=np.sqrt(np.mean(pow(tmp,2))) 179 | tmp=cResFreq_est[i,:]-ff 180 | acc_cResFreq[i]=np.sqrt(np.mean(pow(tmp,2))) 181 | tmp=omp_est[i,:]-ff 182 | acc_omp[i]=np.sqrt(np.mean(pow(tmp,2))) 183 | 184 | fig = plt.figure(figsize=(11, 7)) 185 | ax = fig.add_subplot(111) 186 | plt.subplots_adjust(left=None, bottom=0.1, right=None, top=0.98, wspace=None, hspace=None) 187 | plt.tick_params(labelsize=16) 188 | labels = ax.get_xticklabels() + ax.get_yticklabels() 189 | [label.set_fontname('Times New Roman') for label in labels] 190 | 191 | ax.set_xlabel('SNR / dB', size=20) 192 | ax.set_ylabel(r'RMSE / Hz', size=20) 193 | 194 | ax.semilogy(db,acc_fft[:,0],'--',c='m',marker='o',label='Periodogram',linewidth=4,markersize=10) 195 | ax.semilogy(db, acc_music[:, 0], '--', c='g', marker='o', label='MUSIC', linewidth=4, markersize=10) 196 | ax.semilogy(db, acc_omp[:, 0], '--', marker='o', label='OMP', linewidth=4, markersize=10) 197 | ax.semilogy(db,acc_spcFreq[:,0],'--',c='k',marker='o',label='spcFreq',linewidth=4,markersize=10) 198 | ax.semilogy(db, acc_deepfreq[:, 0], '--', c='b', marker='o', label='DeepFreq', linewidth=4, markersize=10) 199 | ax.semilogy(db, acc_cResFreq[:,0], '--', c='r', marker='o', label='cResFreq', linewidth=4,markersize=10) 200 | ax.semilogy(db, fc, '--', c='#EDB120', marker='o', label='CRLB', linewidth=5, markersize=10) 201 | # ax.set_ylim(2.8e-3,1e-1) 202 | plt.grid(linestyle='-.') 203 | 204 | plt.legend(frameon=True, prop={'size': 16}) 205 | x=1 -------------------------------------------------------------------------------- /Python codes/RDN-1D/Copy_of_doa_cvnn_module_CP10.m: -------------------------------------------------------------------------------- 1 | 2 | function [wHI, wOH, zO_set] = Copy_of_doa_cvnn_module_CP10 (zI_set, zO_teach_set) 3 | format long 4 | len=size(zI_set,3); 5 | bsz=size(zI_set,1); 6 | sizeI=size(zI_set,2); 7 | sizeH=12; 8 | sizeO=1; 9 | TDL_n=29; 10 | fc=500e3; 11 | k1= 0.01; % learning constant 12 | k2= 0.01; 13 | Ts=1e-7; 14 | rng(123) 15 | wHI = rand(sizeH, sizeI); 16 | wOH = rand(sizeO, sizeH); 17 | wHI(:,1)=1; 18 | wOH(:,1)=1; 19 | 20 | % Power inversion initiation 21 | % zI=zI_set; 22 | % Rxx=squeeze(zI(1,:,:))*squeeze(zI(1,:,:))'/8; 23 | % S=[1,0,0,0,0,0,0,0]'; 24 | % Wopt=Rxx\S; 25 | % Wopt=Wopt/abs(Wopt(1)); 26 | % for j=1:sizeH 27 | % for nn=1:TDL_n 28 | % wHI(j,:,nn)=Wopt; 29 | % end 30 | % end 31 | % wOH_amp=randn(sizeO, sizeH, TDL_n); 32 | % wOH_phase=randn(sizeO, sizeH, TDL_n); 33 | % wOH =wOH_amp.*exp(1i*wOH_phase); 34 | % wHI(:,:,1)=1; 35 | % wOH(:,:,1)=1; 36 | 37 | % wHI_amp=randn(sizeH, sizeI, TDL_n); 38 | % wHI_phase=randn(sizeH, sizeI, TDL_n); 39 | % wHI =wHI_amp.*exp(1i*wHI_phase); 40 | % wOH_amp=randn(sizeO, sizeH, TDL_n); 41 | % wOH_phase=randn(sizeO, sizeH, TDL_n); 42 | % wOH =wOH_amp.*exp(1i*wOH_phase); 43 | % wHI(:,:,1)=1; 44 | % wOH(:,:,1)=1; 45 | 46 | 47 | iteration =301; 48 | counter = 1; 49 | er_matrix = zeros(); 50 | %% input normalization 51 | % for row=1:s 52 | % zI_set(row, 1:end-1) = zI_set(row, 1:end-1)/ max(abs(zI_set(row, 1:end-1))); 53 | % zO_teach_set(row, :) = zO_teach_set(row, :) / max(abs(zO_teach_set(row, :))); 54 | % end 55 | %% 56 | min_er=10000; 57 | while counter < iteration 58 | er = 0; 59 | for iter=1:bsz 60 | for ti=1:len 61 | uHI=zeros(sizeH,len); 62 | yHI=zeros(sizeH,len); 63 | xin=zeros(sizeI,len); 64 | for j=1:sizeH 65 | uj=zeros(1,len); 66 | for i=1:sizeI 67 | uji=zeros(1,len); 68 | if ~(i==1) 69 | ss=squeeze(zI_set(iter,i,:)).'; 70 | xin(i,:)=ss; 71 | wgt_xin=wHI(j,i)*ss; 72 | uji=uji+wgt_xin; 73 | else 74 | uji=squeeze(zI_set(iter,i,:)).'; 75 | end 76 | uj=uj+uji; 77 | end 78 | uHI(j,:)=uj; 79 | yHI(j,:)=tanh(abs(uHI(j,:))).*exp(1i*angle(uHI(j,:))); 80 | end 81 | 82 | % output zO 83 | uOH=zeros(sizeO,len); 84 | yOH=zeros(sizeO,len); 85 | xin2=zeros(sizeH,len); 86 | for j=1:sizeO 87 | uj=zeros(1,len); 88 | for i=1:sizeH 89 | uji=zeros(1,len); 90 | if ~(i==1) 91 | ss=yHI(i,:); 92 | xin2(i,:)=ss; 93 | wgt_xin2=wOH(j,i)*ss; 94 | uji=uji+wgt_xin2; 95 | 96 | else 97 | uji=yHI(i,:); 98 | end 99 | uj=uj+uji; 100 | end 101 | uOH(j,:)=uj; 102 | yOH(j,:)=tanh(abs(uOH(j,:))).*exp(1i*angle(uOH(j,:))); 103 | end 104 | 105 | %loss 106 | temp = yOH(ti)*yOH(ti)'; 107 | er = (1/2) .* sum( temp )+er ; 108 | 109 | zOt = zO_teach_set(iter, :); 110 | zO=yOH; 111 | for jj = 1:sizeO 112 | for ii = 1:sizeH 113 | 114 | if ii==1 115 | deltaEwOH1(jj,ii)=0; 116 | else 117 | deltaEwOH1(jj,ii) = (1- abs(zO(jj,ti)).^2) .* (abs(zO(jj,ti)) - abs(zOt(jj,ti)) .* ... 118 | cos(angle(zO(jj,ti)) - angle(zOt(jj,ti)))) .* abs((xin2(ii,ti))) .* ... 119 | cos(angle(zO(jj,ti)) - angle((xin2(ii,ti))) - angle(wOH(jj,ii))) - ... 120 | abs(zO(jj,ti)) .* abs(zOt(jj,ti)) .* sin(angle(zO(jj,ti)) - angle(zOt(jj,ti))) .* ... 121 | (abs((xin2(ii,ti))) ./ (abs(uOH(jj,ti)))).* ... 122 | sin(angle(zO(jj,ti)) - angle((xin2(ii,ti))) - angle(wOH(jj,ii))); 123 | end 124 | 125 | end 126 | end 127 | 128 | for jj = 1:sizeO 129 | for ii = 1:sizeH 130 | if ii==1 131 | deltaEwOH2(jj,ii)=0; 132 | else 133 | deltaEwOH2(jj,ii) = (1- abs(zO(jj,ti)).^2) .* (abs(zO(jj,ti)) - abs(zOt(jj,ti)) .* ... 134 | cos(angle(zO(jj,ti)) - angle(zOt(jj,ti))) ) .* abs((xin2(ii,ti))) .* ... 135 | sin(angle(zO(jj,ti)) - angle((xin2(ii,ti))) - angle(wOH(jj,ii))) + ... 136 | abs(zO(jj,ti)) .* abs(zOt(jj,ti)) .* sin(angle(zO(jj,ti)) - angle(zOt(jj,ti))) .* ... 137 | (abs((xin2(ii,ti))) ./ (abs(uOH(jj,ti)))).* ... 138 | cos(angle(zO(jj,ti)) - angle((xin2(ii,ti))) - angle(wOH(jj,ii))); 139 | end 140 | end 141 | end 142 | 143 | 144 | % Hermite conjugate 145 | for h = 1:sizeH 146 | zHt(h,:) = zeros(1,len); 147 | end 148 | 149 | zH=yHI; 150 | for jj = 1:sizeH 151 | for ii = 1:sizeI 152 | 153 | if ii==1 154 | deltaEwHI1(jj,ii)=0; 155 | else 156 | deltaEwHI1(jj,ii) = (1- abs(zH(jj,ti)).^2) .* (abs(zH(jj,ti)) - abs(zHt(jj,ti)).* ... 157 | cos(angle(zH(jj,ti)) - angle(zHt(jj,ti)))) .* abs((xin(ii,ti))) .* ... 158 | cos(angle(zH(jj,ti)) - angle((xin(ii,ti))) - angle(wHI(jj,ii))) - ... 159 | abs(zH(jj,ti)) .* abs(zHt(jj,ti)) .* sin(angle(zH(jj,ti)) - angle(zHt(jj,ti))) .* ... 160 | (abs((xin(ii,ti))) ./ (abs(uHI(jj,ti)))).* ... 161 | sin(angle(zH(jj,ti)) - angle((xin(ii,ti))) - angle(wHI(jj,ii))); 162 | end 163 | 164 | end 165 | end 166 | 167 | 168 | 169 | for jj = 1:sizeH 170 | for ii=1:sizeI 171 | 172 | if ii==1 173 | deltaEwHI2(jj,ii)=0; 174 | else 175 | deltaEwHI2(jj,ii) = (1- abs(zH(jj,ti)).^2) .* (abs(zH(jj,ti)) - abs(zHt(jj,ti)) .* ... 176 | cos(angle(zH(jj,ti)) - angle(zHt(jj,ti)))) .* abs((xin(ii,ti))) .* ... 177 | sin(angle(zH(jj,ti)) - angle((xin(ii,ti))) - angle(wHI(jj,ii))) + ... 178 | abs(zH(jj,ti)) .* abs(zHt(jj,ti)) .* sin(angle(zH(jj,ti)) - angle(zHt(jj,ti))) .* ... 179 | (abs((xin(ii,ti))) ./ (abs(uHI(jj,ti)))).* ... 180 | cos(angle(zH(jj,ti)) - angle((xin(ii,ti))) - angle(wHI(jj,ii))); 181 | end 182 | 183 | end 184 | end 185 | 186 | 187 | wHI1 = abs(wHI) - k1 * deltaEwHI1; 188 | wOH1 = abs(wOH) - k2 * deltaEwOH1; 189 | 190 | wHI2 = angle(wHI) - k1 * deltaEwHI2; 191 | wOH2 = angle(wOH) - k2 * deltaEwOH2; 192 | 193 | wHI = wHI1 .* exp(1i* wHI2); 194 | wOH = wOH1 .* exp(1i* wOH2); 195 | zO_set(iter, :) = zO; 196 | end 197 | end 198 | if counter==4000 199 | x=1; 200 | end 201 | er_matrix(counter) = er; 202 | counter = counter +1; 203 | 204 | if er<=min_er 205 | min_er=er; 206 | flag_count=1; 207 | else 208 | flag_count=flag_count+1; 209 | if flag_count>=16 210 | k2=k2/1.2; 211 | k1=k1/1.2; 212 | flag_count=0; 213 | min_er=er; 214 | end 215 | end 216 | hint=[counter,er,k1,k2] 217 | if rem(counter,100)==0 218 | save wgt_freq22.mat wHI wOH 219 | end 220 | end 221 | 222 | end -------------------------------------------------------------------------------- /Python codes/RDN-1D/Copy_of_doa_cvnn_module_test_CP10.m: -------------------------------------------------------------------------------- 1 | 2 | function [zO_set,signal] = Copy_of_doa_cvnn_module_test_CP10 (zI_set, wHI,wOH) 3 | len=size(zI_set,3); 4 | N_ang=size(zI_set,1); 5 | sizeI=size(zI_set,2); 6 | sizeH=12; 7 | sizeO=1; 8 | TDL_n=29; 9 | fc=500e3; 10 | Ts=1e-7; 11 | fs=1/Ts; 12 | df=fs/len; 13 | factor=exp(-1i*2*pi*(0:len-1)*df*Ts); 14 | 15 | %% 16 | 17 | for iter=1:N_ang 18 | %TDL output/hidden layer output 19 | uHI=zeros(sizeH,len); 20 | yHI=zeros(sizeH,len); 21 | xin=zeros(sizeI,len); 22 | for j=1:sizeH 23 | uj=zeros(1,len); 24 | for i=1:sizeI 25 | uji=zeros(1,len); 26 | if ~(i==1) 27 | ss=squeeze(zI_set(iter,i,:)).'; 28 | xin(i,:)=ss; 29 | wgt_xin=wHI(j,i)*ss; 30 | uji=uji+wgt_xin; 31 | else 32 | uji=squeeze(zI_set(iter,i,:)).'; 33 | end 34 | uj=uj+uji; 35 | end 36 | uHI(j,:)=uj; 37 | 38 | yHI(j,:)=tanh(abs(uHI(j,:))).*exp(1i*angle(uHI(j,:))); 39 | end 40 | 41 | % output zO 42 | uOH=zeros(sizeO,len); 43 | yOH=zeros(sizeO,len); 44 | xin2=zeros(sizeH,len); 45 | for j=1:sizeO 46 | uj=zeros(1,len); 47 | for i=1:sizeH 48 | uji=zeros(1,len); 49 | if ~(i==1) 50 | ss=yHI(i,:); 51 | xin2(i,:)=ss; 52 | wgt_xin2=wOH(j,i)*ss; 53 | uji=uji+wgt_xin2; 54 | else 55 | uji=yHI(i,:); 56 | end 57 | uj=uj+uji; 58 | end 59 | uOH(j,:)=uj; 60 | % yOH(j,:)=tanh(abs(uOH(j,:))).*exp(1i*angle(uOH(j,:))); 61 | yOH(j,:)=uj; 62 | end 63 | 64 | 65 | temp = yOH*yOH'; 66 | zO_set(iter) = temp; 67 | signal(iter,:)=yOH; 68 | end 69 | 70 | 71 | 72 | end 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /Python codes/RDN-1D/checkpoint/deepfreq_norm_snr40_big8/fr/deepfreq_epoch_120.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Python codes/RDN-1D/checkpoint/deepfreq_norm_snr40_big8/fr/deepfreq_epoch_120.pth -------------------------------------------------------------------------------- /Python codes/RDN-1D/checkpoint/deepfreq_norm_snr40_big8/run.args: -------------------------------------------------------------------------------- 1 | 2 | amplitude: uniform 3 | batch_size: 64 4 | distance: normal 5 | fc_downsampling: 4 6 | fc_kernel_in: 25 7 | fc_kernel_size: 3 8 | fc_module_type: regression 9 | fc_n_filters: 32 10 | fc_n_layers: 20 11 | floor_amplitude: 0.1 12 | fr_inner_dim: 256 13 | fr_kernel_out: 25 14 | fr_kernel_size: 3 15 | fr_module_type: fr 16 | fr_n_filters: 32 17 | fr_n_layers: 24 18 | fr_size: 4096 19 | fr_upsampling: 16 20 | gaussian_std: 0.12 21 | kernel_type: gaussian 22 | lr_fc: 0.0003 23 | lr_fr: 0.0003 24 | max_n_freq: 10 25 | min_sep: 0.5 26 | n_epochs_fc: 100 27 | n_epochs_fr: 410 28 | n_training: 50000 29 | n_validation: 1000 30 | no_cuda: False 31 | noise: gaussian_blind 32 | numpy_seed: 100 33 | output_dir: ./checkpoint/deepfreq_norm_snr40_big8 34 | save_epoch_freq: 10 35 | signal_dim: 64 36 | snr: -10 37 | torch_seed: 76 38 | triangle_slope: 1000 39 | use_cuda: True 40 | -------------------------------------------------------------------------------- /Python codes/RDN-1D/checkpoint/freq_train_big8/events.out.tfevents.1615898021.DESKTOP-C7QQ9IB.31392.0: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Python codes/RDN-1D/checkpoint/freq_train_big8/events.out.tfevents.1615898021.DESKTOP-C7QQ9IB.31392.0 -------------------------------------------------------------------------------- /Python codes/RDN-1D/checkpoint/freq_train_big8/fr/epoch_140.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Python codes/RDN-1D/checkpoint/freq_train_big8/fr/epoch_140.pth -------------------------------------------------------------------------------- /Python codes/RDN-1D/checkpoint/freq_train_big8/run.args: -------------------------------------------------------------------------------- 1 | 2 | amplitude: uniform 3 | batch_size: 64 4 | distance: normal 5 | fc_downsampling: 4 6 | fc_kernel_in: 25 7 | fc_kernel_size: 3 8 | fc_module_type: regression 9 | fc_n_filters: 32 10 | fc_n_layers: 48 11 | floor_amplitude: 0.1 12 | fr_inner_dim: 256 13 | fr_kernel_out: 9 14 | fr_kernel_size: 3 15 | fr_module_type: fr 16 | fr_n_filters: 32 17 | fr_n_layers: 48 18 | fr_size: 4096 19 | fr_upsampling: 16 20 | gaussian_std: 0.12 21 | kernel_type: gaussian 22 | lr_fc: 0.0003 23 | lr_fr: 0.0003 24 | max_n_freq: 10 25 | min_sep: 0.5 26 | n_epochs_fc: 100 27 | n_epochs_fr: 410 28 | n_training: 50000 29 | n_validation: 1000 30 | no_cuda: False 31 | noise: gaussian_blind 32 | numpy_seed: 100 33 | output_dir: ./checkpoint/freq_train_big8 34 | save_epoch_freq: 10 35 | signal_dim: 64 36 | snr: -10 37 | torch_seed: 76 38 | triangle_slope: 4000 39 | use_cuda: True 40 | -------------------------------------------------------------------------------- /Python codes/RDN-1D/checkpoint/skipfreq_snr_big8/fr/epoch_60.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panpp-git/cResFreq/5648c3eb72347c368041279897ce5216d582a23a/Python codes/RDN-1D/checkpoint/skipfreq_snr_big8/fr/epoch_60.pth -------------------------------------------------------------------------------- /Python codes/RDN-1D/checkpoint/skipfreq_snr_big8/run.args: -------------------------------------------------------------------------------- 1 | 2 | amplitude: uniform 3 | batch_size: 64 4 | distance: normal 5 | floor_amplitude: 0.1 6 | fr_inner_dim: 256 7 | fr_kernel_out: 25 8 | fr_kernel_size: 3 9 | fr_module_type: fr 10 | fr_n_filters: 32 11 | fr_n_layers: 24 12 | fr_size: 4096 13 | fr_upsampling: 16 14 | gaussian_std: 0.12 15 | kernel_type: gaussian 16 | lr_fr: 0.003 17 | max_n_freq: 10 18 | min_sep: 0.5 19 | n_epochs_fr: 410 20 | n_training: 50000 21 | n_validation: 1000 22 | no_cuda: False 23 | noise: gaussian_blind 24 | numpy_seed: 100 25 | output_dir: ./checkpoint/skipfreq_snr_big8 26 | save_epoch_freq: 10 27 | signal_dim: 64 28 | snr: -10 29 | torch_seed: 76 30 | triangle_slope: 4000 31 | use_cuda: True 32 | -------------------------------------------------------------------------------- /Python codes/RDN-1D/complexFunctions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | @author: spopoff 6 | """ 7 | 8 | from torch.nn.functional import relu, max_pool2d, avg_pool2d, dropout, dropout2d 9 | import torch 10 | 11 | 12 | def complex_matmul(A, B): 13 | ''' 14 | Performs the matrix product between two complex matrices 15 | ''' 16 | 17 | outp_real = torch.matmul(A.real, B.real) - torch.matmul(A.imag, B.imag) 18 | outp_imag = torch.matmul(A.real, B.imag) + torch.matmul(A.imag, B.real) 19 | 20 | return outp_real.type(torch.complex64) + 1j * outp_imag.type(torch.complex64) 21 | 22 | 23 | def complex_avg_pool2d(input, *args, **kwargs): 24 | ''' 25 | Perform complex average pooling. 26 | ''' 27 | absolute_value_real = avg_pool2d(input.real, *args, **kwargs) 28 | absolute_value_imag = avg_pool2d(input.imag, *args, **kwargs) 29 | 30 | return absolute_value_real.type(torch.complex64) + 1j * absolute_value_imag.type(torch.complex64) 31 | 32 | 33 | def complex_relu(input): 34 | return relu(input.real).type(torch.complex64) + 1j * relu(input.imag).type(torch.complex64) 35 | 36 | 37 | def _retrieve_elements_from_indices(tensor, indices): 38 | flattened_tensor = tensor.flatten(start_dim=-2) 39 | output = flattened_tensor.gather(dim=-1, index=indices.flatten(start_dim=-2)).view_as(indices) 40 | return output 41 | 42 | 43 | def complex_max_pool2d(input, kernel_size, stride=None, padding=0, 44 | dilation=1, ceil_mode=False, return_indices=False): 45 | ''' 46 | Perform complex max pooling by selecting on the absolute value on the complex values. 47 | ''' 48 | absolute_value, indices = max_pool2d( 49 | input.abs(), 50 | kernel_size=kernel_size, 51 | stride=stride, 52 | padding=padding, 53 | dilation=dilation, 54 | ceil_mode=ceil_mode, 55 | return_indices=True 56 | ) 57 | # performs the selection on the absolute values 58 | absolute_value = absolute_value.type(torch.complex64) 59 | # retrieve the corresonding phase value using the indices 60 | # unfortunately, the derivative for 'angle' is not implemented 61 | angle = torch.atan2(input.imag, input.real) 62 | # get only the phase values selected by max pool 63 | angle = _retrieve_elements_from_indices(angle, indices) 64 | return absolute_value \ 65 | * (torch.cos(angle).type(torch.complex64) + 1j * torch.sin(angle).type(torch.complex64)) 66 | 67 | 68 | def complex_dropout(input, p=0.5, training=True): 69 | # need to have the same dropout mask for real and imaginary part, 70 | # this not a clean solution! 71 | mask = torch.ones_like(input).type(torch.float32) 72 | mask = dropout(mask, p, training) * 1 / (1 - p) 73 | return mask * input 74 | 75 | 76 | def complex_dropout2d(input, p=0.5, training=True): 77 | # need to have the same dropout mask for real and imaginary part, 78 | # this not a clean solution! 79 | mask = torch.ones_like(input).type(torch.float32) 80 | mask = dropout2d(mask, p, training) * 1 / (1 - p) 81 | return mask * input -------------------------------------------------------------------------------- /Python codes/RDN-1D/cvnn_func.m: -------------------------------------------------------------------------------- 1 | function [P_ah]=cvnn_func() 2 | n_tgt = double(h5read('tgt_num.h5','/tgt_num')); 3 | sig = (h5read('signal.h5','/signal')); 4 | sig_real=sig(:,1).'; 5 | sig_imag=sig(:,2).'; 6 | noisedSig=sig_real+1j*sig_imag; 7 | Ns=1; 8 | Nsnap=8; 9 | mv=max(abs(noisedSig)); 10 | RPP=noisedSig/mv; 11 | t=0:63; 12 | nfft=4096; 13 | len=size(RPP,2); 14 | snapLen=len-Nsnap+1; 15 | freqs = -0.5:1/nfft:0.5-1/nfft; 16 | final_ret=zeros(size(RPP,1),length(freqs)); 17 | for indix=1:size(RPP,1) 18 | % for indix=1:1 19 | ss=RPP(indix,:); 20 | zI=zeros(Ns,Nsnap,snapLen); 21 | for si=1:Ns 22 | for i=1:Nsnap 23 | zI(si,i,:)=ss(si,i:i+snapLen-1); 24 | end 25 | end 26 | zO_teach_set=zeros(Ns,snapLen); 27 | zI_set=zI; 28 | [wHI, wOH, zO_set_train] = Copy_of_doa_cvnn_module_CP10(zI_set, zO_teach_set); 29 | 30 | 31 | zI=zeros(length(freqs),Nsnap,snapLen); 32 | for tgt=1:length(freqs) 33 | zIk=exp(1i*(2*pi*freqs(tgt)*t)); 34 | zIk=zIk/max(abs(zIk)); 35 | for i=1:Nsnap 36 | zI(tgt,i,:)=zIk(i:i+snapLen-1); 37 | end 38 | end 39 | 40 | load wgt_freq22.mat 41 | zI_set = zI; 42 | [zO_set_test,signal] = Copy_of_doa_cvnn_module_test_CP10(zI,wHI,wOH); 43 | final_ret(indix,:)=ones(1,nfft)./(zO_set_test+1e-10); 44 | P_ah(indix,:)=final_ret(indix,:)/max(abs(final_ret(indix,:))); 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /Python codes/RDN-1D/data/dataset.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import numpy as np 3 | import torch.utils.data as data_utils 4 | from data import fr, data 5 | from .noise import noise_torch 6 | 7 | 8 | def load_dataloader(num_samples, signal_dim, max_n_freq, min_sep, distance, amplitude, floor_amplitude, 9 | kernel_type, kernel_param, batch_size, xgrid): 10 | clean_signals, f, nfreq ,r= data.gen_signal(num_samples, signal_dim, max_n_freq, min_sep, distance=distance, 11 | amplitude=amplitude, floor_amplitude=floor_amplitude, 12 | variable_num_freq=True) 13 | frequency_representation,fr_ground,m1,m2 = fr.freq2fr(f, xgrid, kernel_type, kernel_param,r,nfreq) 14 | 15 | clean_signals = torch.from_numpy(clean_signals).float() 16 | f = torch.from_numpy(f).float() 17 | frequency_representation = torch.from_numpy(frequency_representation).float() 18 | fr_ground = torch.from_numpy(fr_ground).float() 19 | m1 = torch.from_numpy(m1).float() 20 | m2 = torch.from_numpy(m2).float() 21 | dataset = data_utils.TensorDataset(clean_signals, frequency_representation, f,fr_ground,m1,m2) 22 | return data_utils.DataLoader(dataset, batch_size=batch_size, shuffle=True) 23 | 24 | 25 | def load_dataloader_fixed_noise(num_samples, signal_dim, max_n_freq, min_sep, distance, amplitude, floor_amplitude, 26 | kernel_type, kernel_param, batch_size, xgrid, snr, noise): 27 | clean_signals, f, nfreq,r = data.gen_signal(num_samples, signal_dim, max_n_freq, min_sep, distance=distance, 28 | amplitude=amplitude, floor_amplitude=floor_amplitude, 29 | variable_num_freq=True) 30 | frequency_representation,fr_ground,m1,m2 = fr.freq2fr(f, xgrid, kernel_type, kernel_param,r,nfreq) 31 | 32 | clean_signals = torch.from_numpy(clean_signals).float() 33 | f = torch.from_numpy(f).float() 34 | frequency_representation = torch.from_numpy(frequency_representation).float() 35 | fr_ground = torch.from_numpy(fr_ground).float() 36 | 37 | noisy_signals = noise_torch(clean_signals, snr, noise) 38 | m1 = torch.from_numpy(m1).float() 39 | m2 = torch.from_numpy(m2).float() 40 | dataset = data_utils.TensorDataset(noisy_signals, clean_signals, frequency_representation, f,fr_ground,m1,m2) 41 | return data_utils.DataLoader(dataset, batch_size=batch_size) 42 | 43 | 44 | def make_train_data(args): 45 | xgrid = np.linspace(-0.5, 0.5, args.fr_size, endpoint=False) 46 | if args.kernel_type == 'triangle': 47 | kernel_param = args.triangle_slope / args.signal_dim 48 | else: 49 | kernel_param = args.gaussian_std / args.signal_dim 50 | return load_dataloader(args.n_training, signal_dim=args.signal_dim, max_n_freq=args.max_n_freq, 51 | min_sep=args.min_sep, distance=args.distance, amplitude=args.amplitude, 52 | floor_amplitude=args.floor_amplitude, kernel_type=args.kernel_type, 53 | kernel_param=kernel_param, batch_size=args.batch_size, xgrid=xgrid) 54 | 55 | 56 | def make_eval_data(args): 57 | xgrid = np.linspace(-0.5, 0.5, args.fr_size, endpoint=False) 58 | if args.kernel_type == 'triangle': 59 | kernel_param = args.triangle_slope / args.signal_dim 60 | else: 61 | kernel_param = args.gaussian_std / args.signal_dim 62 | return load_dataloader_fixed_noise(args.n_validation, signal_dim=args.signal_dim, max_n_freq=args.max_n_freq, 63 | min_sep=args.min_sep, distance=args.distance, amplitude=args.amplitude, 64 | floor_amplitude=args.floor_amplitude, kernel_type=args.kernel_type, 65 | kernel_param=kernel_param, batch_size=args.batch_size, xgrid=xgrid, 66 | snr=args.snr, noise=args.noise) 67 | -------------------------------------------------------------------------------- /Python codes/RDN-1D/data/fr.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import scipy.signal 3 | import matplotlib.pyplot as plt 4 | 5 | 6 | def freq2fr(f, xgrid, kernel_type='gaussian', param=None, r=None,nfreq=None): 7 | """ 8 | Convert an array of frequencies to a frequency representation discretized on xgrid. 9 | """ 10 | if kernel_type == 'gaussian': 11 | return gaussian_kernel(f, xgrid, param, r,nfreq) 12 | elif kernel_type == 'triangle': 13 | return triangle(f, xgrid, param) 14 | 15 | # def gaussian_kernel(f, xgrid, sigma, r,nfreq): 16 | # """ 17 | # Create a frequency representation with a Gaussian kernel. 18 | # """ 19 | # for i in range(f.shape[0]): 20 | # r[i,nfreq[i]:]=np.min(r[i,0:nfreq[i]]) 21 | # 22 | # fr = np.zeros((f.shape[0], xgrid.shape[0])) 23 | # # for i in range(f.shape[1]): 24 | # # dist = np.abs(xgrid[None, :] - f[:, i][:, None]) 25 | # # rdist = np.abs(xgrid[None, :] - (f[:, i][:, None] + 1)) 26 | # # ldist = np.abs(xgrid[None, :] - (f[:, i][:, None] - 1)) 27 | # # dist = np.minimum(dist, rdist, ldist) 28 | # # # fr += np.exp(- dist ** 2 / sigma ** 2) 29 | # # fr += np.exp(- dist ** 2 / sigma ** 2) 30 | # # fr=20*np.log10(fr+1e-2)+40*(r[:,i][:,None]) 31 | # # m1 = np.zeros((f.shape[0], xgrid.shape[0]), dtype='float32') 32 | # 33 | # fr_ground = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 34 | # for ii in range(fr.shape[0]): 35 | # 36 | # for i in range(f.shape[1]): 37 | # if f[ii, i] == -10: 38 | # continue 39 | # idx0 = (f[ii, i] + 0.5) / (1 / (np.shape(xgrid)[0])) 40 | # 41 | # ctr0 = int(np.round(idx0)) 42 | # if ctr0 == (np.shape(xgrid)[0]): 43 | # ctr0 = (np.shape(xgrid)[0]) - 1 44 | # 45 | # # if ctr0 == 0: 46 | # # ctr0_up = 1 47 | # # else: 48 | # # ctr0_up = ctr0 - 1 49 | # # if ctr0 == np.shape(xgrid)[0] - 1: 50 | # # ctr0_down = np.shape(xgrid)[0] - 2 51 | # # else: 52 | # # ctr0_down = ctr0 + 1 53 | # 54 | # FX=xgrid[ctr0] 55 | # dist = np.abs(xgrid - FX) 56 | # rdist = np.abs(xgrid - (FX + 1)) 57 | # ldist = np.abs(xgrid - (FX - 1)) 58 | # dist = np.minimum(dist, rdist, ldist) 59 | # fr[ii,:] += np.exp(- dist ** 2 / sigma ** 2)*20*np.log10(10*r[ii,i]+1) 60 | # cost = (np.power(20*np.log10(10*np.max(r[ii,:])+1),2)/ np.power(fr[ii,ctr0],2)) 61 | # fr_ground[ii, ctr0] = cost 62 | # 63 | # 64 | # 65 | # m2 = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 66 | # m1=m2 67 | # return fr, fr_ground.astype('float32'), m1, m2 68 | import copy 69 | def gaussian_kernel(f, xgrid, sigma, r,nfreq): 70 | """ 71 | Create a frequency representation with a Gaussian kernel. 72 | """ 73 | # f1=copy.deepcopy(f) 74 | # for i in range(f.shape[0]): 75 | # r[i,nfreq[i]:]=np.min(r[i,0:nfreq[i]]) 76 | # for ii in range(f.shape[1]): 77 | # if r[i,ii]==0: 78 | # f1[i,ii]=-10 79 | 80 | fr = np.zeros((f.shape[0], xgrid.shape[0])) 81 | for i in range(f.shape[1]): 82 | dist = np.abs(xgrid[None, :] - f[:, i][:, None]) 83 | rdist = np.abs(xgrid[None, :] - (f[:, i][:, None] + 1)) 84 | ldist = np.abs(xgrid[None, :] - (f[:, i][:, None] - 1)) 85 | dist = np.minimum(dist, rdist, ldist) 86 | # fr += np.exp(- dist ** 2 / sigma ** 2) 87 | fr += np.exp(- dist ** 2 / sigma ** 2)*(r[:,i][:,None]/np.max(r,axis=1)[:,None]) 88 | # fr=20*np.log10(fr+1e-2)+40*(r[:,i][:,None])*(r[:,i][:,None]/np.max(r,axis=1)[:,None]) 89 | m1 = np.zeros((f.shape[0], xgrid.shape[0]), dtype='float32') 90 | 91 | fr_ground = 1*np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 92 | fr_ground2 = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') 93 | # for ii in range(fr.shape[0]): 94 | # # mv = -1 95 | # # tol = 0 96 | # # for k in range(f.shape[1]): 97 | # # if f[ii, k] == -10: 98 | # # break 99 | # # tol += r[ii, k]/np.min(r[ii,:]) 100 | # # if r[ii, k]/np.min(r[ii,:]) > mv: 101 | # # mv = r[ii, k]/np.min(r[ii,:]) 102 | # # mean_v = tol / k 103 | # mv=np.max(fr[ii]) 104 | # 105 | # 106 | # for i in range(f.shape[1]): 107 | # # cost = (np.power(mv, 2) / np.abs(20 * np.log10(r[ii, i]) + 80)).astype('float32') 108 | # # cost=1 109 | # if f[ii, i] == -10: 110 | # continue 111 | # idx0 = (f[ii, i] + 0.5) / (1 / (np.shape(xgrid)[0])) 112 | # 113 | # ctr0 = int(np.round(idx0)) 114 | # if ctr0 == (np.shape(xgrid)[0]): 115 | # ctr0 = (np.shape(xgrid)[0]) - 1 116 | # # if np.power(fr[ii,ctr0],2)==0: 117 | # # xx=1 118 | # cost = (np.power(mv, 1) / np.power(fr[ii,ctr0],1)).astype('float32') 119 | # fr_ground[ii, ctr0] = cost 120 | # # if r[ii, i]/np.min(r[ii,:])< mean_v:8 121 | # # fr_ground2[ii, ctr0] = mean_v / (fr[ii,ctr0]) 122 | # 123 | # m1[ii,ctr0]=1 124 | # if ctr0 == 0: 125 | # ctr0_up = 1 126 | # fr_ground[ii, ctr0_up] = cost 127 | # m1[ii, ctr0_up] = 1 128 | # else: 129 | # ctr0_up = ctr0 - 1 130 | # fr_ground[ii, ctr0_up] = cost 131 | # m1[ii, ctr0_up] = 1 132 | # if ctr0 == np.shape(xgrid)[0] - 1: 133 | # ctr0_down = np.shape(xgrid)[0] - 2 134 | # fr_ground[ii, ctr0_down] = cost 135 | # m1[ii, ctr0_down] = 1 136 | # else: 137 | # ctr0_down = ctr0 + 1 138 | # fr_ground[ii, ctr0_down] = cost 139 | # m1[ii, ctr0_down] = 1 140 | # # rep=fr_ground[ii] 141 | # # rep[rep==-1]=miv 142 | # # fr_ground[ii]=rep 143 | m2 = np.ones((f.shape[0], xgrid.shape[0]), dtype='float32') - m1 144 | return fr, fr_ground, m1, m2 145 | 146 | 147 | def triangle(f, xgrid, slope): 148 | """ 149 | Create a frequency representation with a triangle kernel. 150 | """ 151 | fr = np.zeros((f.shape[0], xgrid.shape[0])) 152 | for i in range(f.shape[1]): 153 | dist = np.abs(xgrid[None, :] - f[:, i][:, None]) 154 | rdist = np.abs(xgrid[None, :] - (f[:, i][:, None] + 1)) 155 | ldist = np.abs(xgrid[None, :] - (f[:, i][:, None] - 1)) 156 | dist = np.minimum(dist, rdist, ldist) 157 | fr += np.clip(1 - slope * dist, 0, 1) 158 | return fr 159 | 160 | 161 | def find_freq_m(fr, nfreq, xgrid, max_freq=10): 162 | """ 163 | Extract frequencies from a frequency representation by locating the highest peaks. 164 | """ 165 | ff = -np.ones((1, max_freq)) 166 | for n in range(1): 167 | find_peaks_out = scipy.signal.find_peaks(fr, height=(None, None)) 168 | num_spikes = min(len(find_peaks_out[0]), nfreq) 169 | idx = np.argpartition(find_peaks_out[1]['peak_heights'], -num_spikes)[-num_spikes:] 170 | ff[n, :num_spikes] = np.sort(xgrid[find_peaks_out[0][idx]]) 171 | return ff 172 | 173 | def find_freq_idx(fr, nfreq, xgrid, max_freq=10): 174 | """ 175 | Extract frequencies from a frequency representation by locating the highest peaks. 176 | """ 177 | ff = -np.ones((1, max_freq)) 178 | for n in range(1): 179 | find_peaks_out = scipy.signal.find_peaks(fr, height=(None, None)) 180 | num_spikes = min(len(find_peaks_out[0]), nfreq) 181 | idx = np.argpartition(find_peaks_out[1]['peak_heights'], -num_spikes)[-num_spikes:] 182 | freq_idx=find_peaks_out[0][idx] 183 | return np.sort(freq_idx) 184 | 185 | 186 | def find_freq(fr, nfreq, xgrid, max_freq=10): 187 | """ 188 | Extract frequencies from a frequency representation by locating the highest peaks. 189 | """ 190 | ff = -np.ones((nfreq.shape[0], max_freq)) 191 | for n in range(len(nfreq)): 192 | 193 | if nfreq[n] < 1: # at least one frequency 194 | nf = 1 195 | else: 196 | nf = nfreq[n] 197 | 198 | find_peaks_out = scipy.signal.find_peaks(fr[n], height=(None, None)) 199 | num_spikes = min(len(find_peaks_out[0]), int(nf)) 200 | idx = np.argpartition(find_peaks_out[1]['peak_heights'], -num_spikes)[-num_spikes:] 201 | ff[n, :num_spikes] = np.sort(xgrid[find_peaks_out[0][idx]]) 202 | return ff 203 | 204 | 205 | def periodogram(signal, xgrid): 206 | """ 207 | Compute periodogram. 208 | """ 209 | js = np.arange(signal.shape[1]) 210 | return (np.abs(np.exp(-2.j * np.pi * xgrid[:, None] * js).dot(signal.T) / signal.shape[1]) ** 2).T 211 | 212 | 213 | def make_hankel(signal, m): 214 | """ 215 | Auxiliary function used in MUSIC. 216 | """ 217 | n = len(signal) 218 | h = np.zeros((m, n - m + 1), dtype='complex128') 219 | for r in range(m): 220 | for c in range(n - m + 1): 221 | h[r, c] = signal[r + c] 222 | return h 223 | 224 | 225 | def music(signal, xgrid, nfreq, m=20): 226 | """ 227 | Compute frequency representation obtained with MUSIC. 228 | """ 229 | music_fr = np.zeros((signal.shape[0], len(xgrid))) 230 | for n in range(signal.shape[0]): 231 | hankel = make_hankel(signal[n], m) 232 | _, _, V = np.linalg.svd(hankel) 233 | v = np.exp(-2.0j * np.pi * np.outer(xgrid[:, None], np.arange(0, signal.shape[1] - m + 1))) 234 | u = V[nfreq[n]:] 235 | fr = -np.log(np.linalg.norm(np.tensordot(u, v, axes=(1, 1)), axis=0) ** 2) 236 | music_fr[n] = fr 237 | return music_fr 238 | -------------------------------------------------------------------------------- /Python codes/RDN-1D/data/loss.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def fnr(f1, f2, signal_dim): 5 | threshold = 1/(4*signal_dim) 6 | false_negative = np.zeros(f1.shape[0]) 7 | nfreq = np.sum(f2 > -0.5, axis=1) 8 | for i in range(f2.shape[1]): 9 | dist_i_direct = np.min(np.abs(f1 - f2[:, i][:, None]), axis=1) 10 | dist_i_rshift = np.min(np.abs((f1 + 1) - f2[:, i][:, None]), axis=1) 11 | dist_i_lshift = np.min(np.abs((f1 - 1) - f2[:, i][:, None]), axis=1) 12 | dist_i = np.min((dist_i_direct, dist_i_rshift, dist_i_lshift), axis=0) 13 | valid_freq = (f2[:, i] != -10) 14 | false_negative += (dist_i > threshold)*valid_freq 15 | return np.sum(false_negative/nfreq) 16 | 17 | 18 | def chamfer(f_estimate, f_target): 19 | f_estimate[f_estimate == -1] = -10. 20 | f_target[f_target == -1] = -10. 21 | dist_f_target = np.zeros(f_target.shape[0]) 22 | for i in range(f_target.shape[1]): 23 | dist_i_direct = np.min(np.abs(f_estimate - f_target[:, i][:, None]), axis=1) 24 | dist_i_rshift = np.min(np.abs((f_estimate + 1) - f_target[:, i][:, None]), axis=1) 25 | dist_i_lshift = np.min(np.abs((f_estimate - 1) - f_target[:, i][:, None]), axis=1) 26 | dist_i = np.min((dist_i_direct, dist_i_rshift, dist_i_lshift), axis=0) 27 | b = (f_target[:, i] != -10.) 28 | dist_f_target += dist_i*b 29 | dist_f_estimate = np.zeros(f_estimate.shape[0]) 30 | for i in range(f_estimate.shape[1]): 31 | dist_i_direct = np.min(np.abs(f_target - f_estimate[:, i][:, None]), axis=1) 32 | dist_i_rshift = np.min(np.abs((f_target + 1) - f_estimate[:, i][:, None]), axis=1) 33 | dist_i_lshift = np.min(np.abs((f_target - 1) - f_estimate[:, i][:, None]), axis=1) 34 | dist_i = np.min((dist_i_direct, dist_i_rshift, dist_i_lshift), axis=0) 35 | b = (f_estimate[:, i] != -10.) 36 | dist_f_estimate += dist_i*b 37 | dist = (dist_f_estimate + dist_f_target) 38 | return np.sum(dist) 39 | -------------------------------------------------------------------------------- /Python codes/RDN-1D/data/noise.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | 4 | 5 | def noise_torch(t, snr=1., kind='gaussian_b', n_corr=None): 6 | if kind == 'gaussian': 7 | return gaussian_noise(t, snr) 8 | elif kind == 'gaussian_blind': 9 | return gaussian_blind_noise(t, snr) 10 | elif kind == 'sparse': 11 | return sparse_noise(t, n_corr) 12 | elif kind == 'variable_sparse': 13 | return variable_sparse_noise(t, n_corr) 14 | 15 | 16 | # def gaussian_noise(s, snr): 17 | # """ 18 | # Add Gaussian noise to the input signal. 19 | # """ 20 | # bsz, _, signal_dim = s.size() 21 | # s = s.view(s.size(0), -1) 22 | # sigma = np.sqrt(1. / snr) 23 | # noise = torch.randn(s.size(), device=s.device, dtype=s.dtype) 24 | # mult = sigma * torch.norm(s, 2, dim=1) / (torch.norm(noise, 2, dim=1)) 25 | # noise = noise * mult[:, None] 26 | # return (s + noise).view(bsz, -1, signal_dim) 27 | # 28 | # 29 | # def gaussian_blind_noise(s, snr): 30 | # """ 31 | # Add Gaussian noise to the input signal. The std of the gaussian noise is uniformly chosen between 0 and 1/sqrt(snr). 32 | # """ 33 | # bsz, _, signal_dim = s.size() 34 | # s = s.view(bsz, -1) 35 | # sigma_max = np.sqrt(1. / snr) 36 | # sigmas = sigma_max * torch.rand(bsz, device=s.device, dtype=s.dtype) 37 | # noise = torch.randn(s.size(), device=s.device, dtype=s.dtype) 38 | # mult = sigmas * torch.norm(s, 2, dim=1) / (torch.norm(noise, 2, dim=1)) 39 | # noise = noise * mult[:, None] 40 | # return (s + noise).view(bsz, -1, signal_dim) 41 | 42 | def gaussian_blind_noise(s, snr): 43 | """ 44 | Add Gaussian noise to the input signal. The std of the gaussian noise is uniformly chosen between 0 and 1/sqrt(snr). 45 | """ 46 | bsz, _, signal_dim = s.size() 47 | s = s.view(bsz, -1) 48 | low=snr 49 | high=40 50 | # sigma_max = np.sqrt(1. / snr) 51 | # sigmas = sigma_max * torch.rand(bsz, device=s.device, dtype=s.dtype) 52 | scpu=s.cpu().numpy() 53 | snr_array = (low + (high - low) * torch.rand(bsz))[:, None] 54 | snr_array=snr_array.cpu().numpy() 55 | noise = torch.randn(s.size(), device=s.device, dtype=s.dtype) 56 | s = torch.from_numpy(scpu * (10 ** (snr_array / 20))).to(s.device) 57 | # mult = sigmas * torch.norm(s, 2, dim=1) / (torch.norm(noise, 2, dim=1)) 58 | # noise = noise * mult[:, None] 59 | return (s + noise).view(bsz, -1, signal_dim) 60 | 61 | def gaussian_noise(s, snr): 62 | """ 63 | Add Gaussian noise to the input signal. 64 | """ 65 | bsz, _, signal_dim = s.size() 66 | s = s.view(s.size(0), -1) 67 | # sigma = np.sqrt(1. / snr) 68 | noise = torch.randn(s.size(), device=s.device, dtype=s.dtype) 69 | scpu = s.cpu().numpy() 70 | snr_array = (snr * torch.ones(bsz))[:, None] 71 | snr_array = snr_array.cpu().numpy() 72 | s = torch.from_numpy(scpu * (10 ** (snr_array / 20))).to(s.device) 73 | # mult = sigma * torch.norm(s, 2, dim=1) / (torch.norm(noise, 2, dim=1)) 74 | # noise = noise * mult[:, None] 75 | return (s + noise).view(bsz, -1, signal_dim) 76 | 77 | 78 | def sparse_noise(s, n_corr): 79 | """ 80 | Add sparse noise to the input signal. The number of corrupted elements is equal to n_corr. 81 | """ 82 | noisy_signal = s.clone() 83 | corruption = 0.5 * torch.randn((s.size(0), s.size(1), n_corr), device=s.device, dtype=s.dtype) 84 | for i in range(s.size(0)): 85 | idx = torch.multinomial(torch.ones(s.size(-1)), n_corr, replacement=False) 86 | noisy_signal[i, :, idx] += corruption[i, :] 87 | return noisy_signal 88 | 89 | 90 | def variable_sparse_noise(s, max_corr): 91 | """ 92 | Add sparse noise to the input signal. The number of corrupted elements is drawn uniformaly between 1 and 93 | max_corruption. 94 | """ 95 | noisy_signal = s.clone() 96 | corruption = 0.5 * torch.randn((s.size(0), s.size(1), max_corr), device=s.device, dtype=s.dtype) 97 | n_corr = np.random.randint(1, max_corr + 1, (s.size(0))) 98 | for i in range(s.size(0)): 99 | idx = torch.multinomial(torch.ones(s.size(-1)), int(n_corr[i]), replacement=False) 100 | noisy_signal[i, :, idx] += corruption[i, :, :n_corr[i]] 101 | return noisy_signal 102 | -------------------------------------------------------------------------------- /Python codes/RDN-1D/data/source_number.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from data.fr import make_hankel 3 | 4 | EPS = 1e-10 5 | 6 | 7 | def SORTE(s, param=20): 8 | """ 9 | Based on https://www.ese.wustl.edu/~nehorai/paper/Han_Jackknifing_TSP_2013.pdf 10 | """ 11 | Y = make_hankel(s, param) 12 | sig = Y @ np.conj(Y.T) 13 | eig_values, _ = np.linalg.eigh(sig) 14 | eig_values = np.sort(eig_values)[::-1] # \lamda_1, ..., \lambda_N 15 | delta_lambda = -np.diff(eig_values) 16 | var = var_delta(delta_lambda) 17 | sorte = np.divide(var[1:], var[:-1]) 18 | return np.argmin(sorte) + 1 19 | 20 | 21 | def var_delta(delta_lambda): 22 | cummean = np.cumsum(delta_lambda[::-1]) / np.arange(1, len(delta_lambda) + 1) # mean( \delta_K, ..., \delta_{N-1} ) 23 | delta_lambda_norm = (delta_lambda[None] - cummean[:, None]) ** 2 24 | var = np.sum(np.triu(delta_lambda_norm), axis=1) / np.arange(1, len(delta_lambda) + 1) 25 | return var 26 | 27 | 28 | def AIC(s, param=20): 29 | """ 30 | Based on http://www.dsp-book.narod.ru/DSPMW/67.PDF 31 | """ 32 | Y = make_hankel(s, param) 33 | sig = Y @ np.conj(Y.T) 34 | eig_values, _ = np.linalg.eigh(sig) 35 | eig_values = np.sort(eig_values)[::-1] 36 | eig_values = np.clip(eig_values, EPS, np.inf) 37 | 38 | cumprod = np.cumprod(eig_values[::-1])[::-1] # , 1/np.arange(1, len(eig_values)+1))[::-1] 39 | cummean = (np.cumsum(eig_values[::-1]) / np.arange(1, len(eig_values) + 1)) 40 | cummean = np.power(cummean, np.arange(1, len(eig_values) + 1))[::-1] 41 | log_div = np.log(cumprod / cummean) 42 | n_s = np.arange(1, len(eig_values) + 1) 43 | m = len(s) 44 | n = sig.shape[0] 45 | k = np.argmin(-n * log_div + n_s * (2 * m - m)) 46 | return k 47 | 48 | 49 | def MDL(s, param=20): 50 | """ 51 | http://www.dsp-book.narod.ru/DSPMW/67.PDF 52 | """ 53 | Y = make_hankel(s, param) 54 | sigma = Y @ np.conj(Y.T) 55 | eig_values, _ = np.linalg.eigh(sigma) 56 | eig_values = np.sort(eig_values)[::-1] 57 | eig_values = np.clip(eig_values, EPS, np.inf) 58 | 59 | cumprod = np.cumprod(eig_values[::-1])[::-1] 60 | cummean = (np.cumsum(eig_values[::-1]) / np.arange(1, len(eig_values) + 1)) 61 | cummean = np.power(cummean, np.arange(1, len(eig_values) + 1))[::-1] 62 | log_div = np.log(cumprod / cummean) 63 | n_s = np.arange(1, len(eig_values) + 1) 64 | m = len(s) 65 | n = sigma.shape[0] 66 | 67 | k = np.argmin(-n * log_div + 0.5 * n_s * (2 * m - n_s) * np.log(n)) 68 | return k 69 | 70 | def sorte_arr(signals, param=20): 71 | result = [] 72 | for s in signals: 73 | result.append(SORTE(s, param)) 74 | return np.array(result) 75 | 76 | 77 | def mdl_arr(signals, param=20): 78 | result = [] 79 | for s in signals: 80 | result.append(MDL(s, param)) 81 | return np.array(result) 82 | 83 | 84 | def aic_arr(signals, param=20): 85 | result = [] 86 | for s in signals: 87 | result.append(AIC(s, param)) 88 | return np.array(result) 89 | -------------------------------------------------------------------------------- /Python codes/RDN-1D/util.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import errno 4 | import complexModules,modules 5 | 6 | def model_parameters(model): 7 | num_params = 0 8 | for param in model.parameters(): 9 | num_params += param.numel() 10 | return num_params 11 | 12 | 13 | def symlink_force(target, link_name): 14 | try: 15 | os.symlink(target, link_name) 16 | except OSError as e: 17 | if e.errno == errno.EEXIST: 18 | os.remove(link_name) 19 | os.symlink(target, link_name) 20 | else: 21 | raise e 22 | 23 | 24 | def save(model, optimizer, scheduler, args, epoch, module_type): 25 | checkpoint = { 26 | 'epoch': epoch, 27 | 'model': model.state_dict(), 28 | 'optimizer': optimizer.state_dict(), 29 | 'scheduler': scheduler.state_dict(), 30 | 'args': args, 31 | } 32 | if scheduler is not None: 33 | checkpoint["scheduler"] = scheduler.state_dict() 34 | if not os.path.exists(os.path.join(args.output_dir, module_type)): 35 | os.makedirs(os.path.join(args.output_dir, module_type)) 36 | cp = os.path.join(args.output_dir, module_type, 'last.pth') 37 | fn = os.path.join(args.output_dir, module_type, 'epoch_'+str(epoch)+'.pth') 38 | torch.save(checkpoint, fn) 39 | symlink_force(fn, cp) 40 | 41 | 42 | def load(fn, module_type, device = torch.device('cuda')): 43 | checkpoint = torch.load(fn, map_location=device) 44 | args = checkpoint['args'] 45 | if device == torch.device('cpu'): 46 | args.use_cuda = False 47 | if module_type == 'fr': 48 | model = modules.set_fr_module(args) 49 | elif module_type == 'skip': 50 | model = complexModules.set_skip_module(args) 51 | elif module_type == 'fc': 52 | model = complexModules.set_fc_module(args) 53 | elif module_type == 'rdn': 54 | model = complexModules.set_rdn_module(args) 55 | elif module_type == 'layer1': 56 | model = modules.set_layer1_module(args) 57 | elif module_type == 'deepfreqRes': 58 | model = modules.set_deepfreqRes_module(args) 59 | elif module_type == 'freq': 60 | model = modules.set_freq_module(args) 61 | else: 62 | raise NotImplementedError('Module type not recognized') 63 | model.load_state_dict(checkpoint['model']) 64 | optimizer, scheduler = set_optim(args, model, module_type) 65 | if checkpoint["scheduler"] is not None: 66 | scheduler.load_state_dict(checkpoint["scheduler"]) 67 | optimizer.load_state_dict(checkpoint["optimizer"]) 68 | return model, optimizer, scheduler, args, checkpoint['epoch'] 69 | 70 | 71 | def set_optim(args, module, module_type): 72 | if module_type == 'fr': 73 | # params = list(module.parameters()) + list(adaptive.parameters()) 74 | optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fr) 75 | elif module_type == 'fc': 76 | optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fc) 77 | elif module_type == 'skip': 78 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 79 | # optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fr) 80 | elif module_type == 'rdn': 81 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 82 | # optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fr) 83 | elif module_type == 'freq': 84 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 85 | # optimizer = torch.optim.Adam(module.parameters(), lr=args.lr_fr) 86 | elif module_type == 'deepfreqRes': 87 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 88 | elif module_type == 'layer1': 89 | optimizer = torch.optim.RMSprop(module.parameters(), lr=args.lr_fr, alpha=0.9) 90 | 91 | else: 92 | raise(ValueError('Expected module_type to be fr or fc but got {}'.format(module_type))) 93 | scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=7, factor=0.5, verbose=True) 94 | return optimizer, scheduler 95 | 96 | 97 | def print_args(logger, args): 98 | message = '' 99 | for k, v in sorted(vars(args).items()): 100 | message += '\n{:>30}: {:<30}'.format(str(k), str(v)) 101 | logger.info(message) 102 | 103 | args_path = os.path.join(args.output_dir, 'run.args') 104 | with open(args_path, 'wt') as args_file: 105 | args_file.write(message) 106 | args_file.write('\n') 107 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cResFreq 2 | Codes for Complex-Valued Spectrum Estimation Network and Applications in Super-Resolution HRRPs Analysis with Wideband Radars 3 | 4 | Refer to "G. Izacard, S. Mohan, and C. Fernandez-Granda, “Data-driven estimation of sinusoid frequencies,” arXiv:1906.00823. [Online]. Available: 5 | https://arxiv.org/abs/1906.00823, 2019." 6 | 7 | This repo. includes: 8 | ---Training Codes for the cResFreq, spcFreq and DeepFreq models. 9 | 1. complexTrain.py is the main function for cResFreq 10 | 2. freqDomainTrain.py for spcFreq 11 | 3. train.py for DeepFreq 12 | 13 | ---Experiments of Comparison in papers. 14 | 1. Fig.11(a) in the paper / rmse of frequency estimation of a single component is produced by "ACCURACY.py" 15 | 2. Fig.11(b) in the paper / FNR of multiple sinusoidals is produced by "FNR.py" 16 | 3. Fig. 10 in the paper / Resolution perfomance is produced by "RESOLUTION.py" 17 | 4. Fig. 8 in the paper / Visual verification of performance is produced by "VISUAL.py" 18 | 5. Fig. 12 in the paper / Detections of weak components is produced by "WEAK_DET2.py" 19 | 6. Fig. 6 in the paper / Weights characteristcs is produced by "WEIGHT.py" 20 | 21 | --Requirements required for running the codes. 22 | --------------------------------------------------------------------------------