├── Codes in NC2021 ├── Auditory Toolbox.zip ├── DM_RC_sim.m ├── DynamicMemristor.m ├── HenonMap.m ├── README.md ├── Voice Data.zip └── exdata.mat ├── Codes in NE2022 ├── Simulations │ ├── DGRdataset.mat │ ├── DGRpara.mat │ ├── DMnode.py │ ├── ECGdataset.mat │ ├── ECGpara.mat │ ├── Sim_DGR.py │ ├── Sim_ECG.py │ ├── Sim_IV.py │ └── Sim_WFC.py └── Upper computer program │ ├── Addr.csv │ ├── DGR_test.py │ ├── DGRdataset.mat │ ├── ECG_test.py │ ├── ECGdataset.mat │ ├── IO_test.py │ ├── Interface.py │ ├── Mylayers.py │ ├── NoiseAwareTrain.py │ └── RRAM_prog.py └── README.md /Codes in NC2021/Auditory Toolbox.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tsinghua-LEMON-Lab/Reservoir-computing/ec5518d07b70af4d843c1c4925d20da93bfc67e8/Codes in NC2021/Auditory Toolbox.zip -------------------------------------------------------------------------------- /Codes in NC2021/DM_RC_sim.m: -------------------------------------------------------------------------------- 1 | %% I-V 2 | clc; 3 | clear; 4 | % ----------------------Model Parameters---------------------- 5 | para.r = 0.99; 6 | para.G0 = 0.5; 7 | para.Kp = 9.13; 8 | para.Kn = 0.32; 9 | para.alpha = 0.23; 10 | 11 | % ----------------------Voltage Sequence---------------------- 12 | Vmin = -3; 13 | Vmax = 3; 14 | inv = 0.099; 15 | V = -[0:inv:Vmax-inv, Vmax:-inv:Vmin+inv, Vmin:inv:0]; 16 | 17 | % ----------------------Start Simulation---------------------- 18 | step = length(V); 19 | I = zeros(1, step); 20 | G = para.G0; 21 | for i = 1:step 22 | [I(i), G] = DynamicMemristor(V(i), G, para); 23 | end 24 | 25 | % ----------------------Experimental Data---------------------- 26 | load('exdata.mat'); 27 | 28 | % ----------------------Plot---------------------- 29 | figure; 30 | semilogy(V, abs(I)+10^-5, 'b'); 31 | hold on; 32 | semilogy(Vex, Iex, 'r'); 33 | str1 = '\color{blue}Simulation'; 34 | str2 = '\color{red}Experiment'; 35 | lg = legend(str1, str2); 36 | set(lg, 'box', 'off'); 37 | xlabel('Voltage (V)'); 38 | ylabel('Current (μA)'); 39 | axis([-3, 3, -inf, inf]); 40 | set(gca, 'FontName', 'Arial', 'FontSize', 20); 41 | set(gcf, 'unit', 'normalized', 'position', [0.2,0.2,0.3,0.45]); 42 | %% Waveform classification 43 | clear;clc; 44 | % ----------------------Model Parameters---------------------- 45 | para.r = 0.99; 46 | para.G0 = 0.5; 47 | para.Kp = 9.13; 48 | para.Kn = 0.32; 49 | para.alpha = 0.23; 50 | 51 | % ----------------------DM_RC Parameters---------------------- 52 | ML = 4; 53 | N = 10; 54 | Vmax = 3; 55 | Vmin = -2; 56 | 57 | % ----------------------DATASET---------------------- 58 | sample = 8; 59 | step = 2000; 60 | Data = zeros(1, 2*step); 61 | p1 = sin(pi*2*(0:sample-1)/sample); 62 | p2(1:sample/2) = 1; 63 | p2(sample/2+1:sample) = -1; 64 | for i = 1:2*step/sample 65 | q = unidrnd(2); 66 | if q == 1 67 | Data(sample*(i-1)+1:sample*i) = p1; 68 | Label(sample*(i-1)+1:sample*i) = 0; 69 | else 70 | Data(sample*(i-1)+1:sample*i) = p2; 71 | Label(sample*(i-1)+1:sample*i) = 1; 72 | end 73 | end 74 | 75 | % ----------------------TRAIN---------------------- 76 | % initialize input stream 77 | Input = Data(1:step); 78 | 79 | % generate target 80 | Target = Label(1:step); 81 | 82 | % mask process 83 | Mask = 2*unidrnd(2, N, ML)-3; 84 | Input_ex = []; 85 | for j = 1:N 86 | for i = 1:step 87 | Input_ex(j, (i-1)*ML+1:ML*i) = Input(i)*Mask(j, :); 88 | end 89 | end 90 | UL = max(max(Input_ex)); 91 | DL = min(min(Input_ex)); 92 | Input_ex = (Input_ex-DL)/(UL-DL)*(Vmax - Vmin)+Vmin; 93 | 94 | % memristor output 95 | memout = []; 96 | G = para.G0; 97 | for i = 1:length(Input_ex(1, :)) 98 | [memout(:,i), G] = DynamicMemristor(Input_ex(:,i), G, para); 99 | sprintf('%s', ['train:', num2str(i), ', Vmax:', num2str(Vmax), ', ML:', num2str(ML)]) 100 | end 101 | 102 | % states collection 103 | states = []; 104 | for i = 1:step 105 | a = memout(:, ML*(i-1)+1:ML*i); 106 | states(:, i) = a(:); 107 | end 108 | X = [ones(1,step); states]; 109 | 110 | % linear regression 111 | Wout = Target*pinv(X); 112 | 113 | % ----------------------TEST---------------------- 114 | % initialize input stream 115 | Input = Data(step+1:end); 116 | 117 | % generate target 118 | Target = Label(step+1:end); 119 | 120 | % mask process 121 | Input_ex = []; 122 | for j = 1:N 123 | for i = 1:step 124 | Input_ex(j, (i-1)*ML+1:ML*i) = Input(i)*Mask(j, :); 125 | end 126 | end 127 | UL = max(max(Input_ex)); 128 | DL = min(min(Input_ex)); 129 | Input_ex = (Input_ex-DL)/(UL-DL)*(Vmax - Vmin)+Vmin; 130 | 131 | % memristor output 132 | memout = []; 133 | states = []; 134 | G = para.G0; 135 | for i = 1:length(Input_ex(1, :)) 136 | [memout(:, i), G] = DynamicMemristor(Input_ex(:,i),G,para); 137 | sprintf('%s',['test:', num2str(i), ', Vmax:', num2str(Vmax), ', ML:', num2str(ML)]) 138 | end 139 | 140 | % states collection 141 | for i = 1:step 142 | a = memout(:, ML*(i-1)+1:ML*i); 143 | states(:,i) = a(:); 144 | end 145 | X = [ones(1,step);states]; 146 | 147 | % system output 148 | Out = Wout*X; 149 | NRMSE = sqrt(mean((Out(10:end)-Target(10:end)).^2)./var(Target(10:end))); 150 | sprintf('%s',['NRMSE:',num2str(NRMSE)]) 151 | 152 | % ----------------------PLOT---------------------- 153 | figure; 154 | subplot(2, 1, 1); 155 | plot(Input, 'b', 'linewidth', 1); 156 | hold on; 157 | plot(Input, '.r'); 158 | axis([0, 400, -1.2, 1.2]) 159 | ylabel('Input') 160 | set(gca,'FontName', 'Arial', 'FontSize', 20); 161 | subplot(2, 1, 2); 162 | plot(Target, 'k', 'linewidth', 2); 163 | hold on; 164 | plot(Out, 'r', 'linewidth',1); 165 | axis([0, 400, -0.2, 1.2]) 166 | str1 = '\color{black}Target'; 167 | str2 = '\color{red}Output'; 168 | lg = legend(str1, str2); 169 | set(lg, 'Orientation', 'horizon'); 170 | ylabel('Prediction') 171 | xlabel('Time (\tau)') 172 | set(gca,'FontName', 'Arial', 'FontSize', 20); 173 | set(gcf, 'unit', 'normalized', 'position', [0.2, 0.2, 0.6, 0.35]); 174 | %% Spoken-digit recognition 175 | clc; 176 | clear; 177 | addpath('Auditory Toolbox\'); 178 | 179 | % ----------------------Model Parameters---------------------- 180 | para.r = 0.99; 181 | para.G0 = 0.5; 182 | para.Kp = 9.13; 183 | para.Kn = 0.32; 184 | para.alpha = 0.23; 185 | 186 | % ----------------------DM_RC Parameters---------------------- 187 | ML = 10; 188 | N = 40; 189 | Vmax = 3; 190 | Vmin = 0; 191 | Mask = 2*randi([0,1],64,ML,N)-1; 192 | 193 | % ----------------------DATASET---------------------- 194 | for i = 1:5 195 | for j = 1:10 196 | for k = 1:10 197 | filename(k+(i-1)*10,j) = {['Voice Data\train\f',num2str(i),'\','0',num2str(j-1),'f',num2str(i),'set',num2str(k-1),'.wav']}; 198 | end 199 | end 200 | end 201 | 202 | % ----------------------CROSS-VALIDATION---------------------- 203 | WRR = 0; 204 | TF=zeros(10,10); 205 | for u=1:10 206 | % SHUFFLE DATASET 207 | S = []; 208 | for i = 1:10 209 | r = randperm(size(filename,1)); 210 | res = filename(:,i); 211 | res = res(r,:); 212 | S = [S,res]; 213 | end 214 | 215 | % TRAIN 216 | words = 450; 217 | VL = zeros(words); 218 | Target = [];X = []; 219 | q = 0;p = 1; 220 | for j = 1:words 221 | q = q+1; 222 | if q > 10 223 | q = 1; 224 | p = p+1; 225 | end 226 | 227 | % data preprocess 228 | a = audioread(S{p,q}); 229 | a = resample(a,8000,12500); 230 | f = LyonPassiveEar(a,8000,250); 231 | L = zeros(10,length(f(1,:))); 232 | L(q,:) = ones(1,length(f(1,:))); 233 | VL(j) = length(f(1,:)); 234 | Target(:,sum(VL(1:j))-VL(j)+1:sum(VL(1:j))) = L; 235 | 236 | % mask process 237 | Input = []; 238 | for k = 1:N 239 | for i = 1:VL(j) 240 | Input(k, ML*(i-1)+1:ML*i) = abs(f(:,i))'*Mask(:,:,k); 241 | end 242 | end 243 | UL = max(max(Input)); 244 | DL = min(min(Input)); 245 | Input = (Input-DL)/(UL-DL)*(Vmax - Vmin)+Vmin; 246 | 247 | % memristor output 248 | memout = []; 249 | G = para.G0; 250 | for i = 1:length(Input(1, :)) 251 | [memout(:,i), G] = DynamicMemristor(Input(:,i), G, para); 252 | end 253 | 254 | % states collection 255 | for i = 1:VL(j) 256 | a = memout(:, ML*(i-1)+1:ML*i); 257 | X(:,sum(VL(1:j))-VL(j)+i) = a(:); 258 | end 259 | 260 | sprintf('%s',['loop:',num2str(u),',train:',num2str(j),',',num2str(u-1),'acc:',num2str(WRR)]) 261 | end 262 | 263 | % linear regression 264 | Wout = Target*X'*pinv(X*X'); 265 | 266 | % TEST 267 | clc; 268 | VL = zeros(words); 269 | Target = [];X=[]; 270 | words = 50;q = 0;p = 46; 271 | for j=1:words 272 | q = q+1; 273 | if q > 10 274 | q = 1; 275 | p = p+1; 276 | end 277 | 278 | % data preprocess 279 | a = audioread(S{p,q}); 280 | a = resample(a,8000,12500); 281 | f = LyonPassiveEar(a,8000,250); 282 | L = zeros(10,length(f(1,:))); 283 | L(q,:) = ones(1,length(f(1,:))); 284 | VL(j) = length(f(1,:)); 285 | Target(:,sum(VL(1:j))-VL(j)+1:sum(VL(1:j))) = L; 286 | 287 | % mask process 288 | Input = []; 289 | for k=1:N 290 | for i=1:VL(j) 291 | Input(k, ML*(i-1)+1:ML*i) = abs(f(:,i))'*Mask(:,:,k); 292 | end 293 | end 294 | UL = max(max(Input)); 295 | DL = min(min(Input)); 296 | Input = (Input-DL)/(UL-DL)*(Vmax - Vmin)+Vmin; 297 | 298 | % memristor output 299 | memout = []; 300 | G = para.G0; 301 | for i = 1:length(Input(1, :)) 302 | [memout(:,i), G] = DynamicMemristor(Input(:,i), G, para); 303 | end 304 | 305 | % states collection 306 | for i = 1:VL(j) 307 | a = memout(:, ML*(i-1)+1:ML*i); 308 | X(:,sum(VL(1:j))-VL(j)+i) = a(:); 309 | end 310 | 311 | sprintf('%s',['loop:',num2str(u),',test:',num2str(j)]) 312 | end 313 | 314 | % system output 315 | Y = Wout*X; 316 | 317 | % accuracy calculation 318 | Mout = []; 319 | rl = zeros(10,10); 320 | real = zeros(10,words); 321 | for i=1:words 322 | Mout(:,i) = mean(Y(:,sum(VL(1:i))-VL(i)+1:sum(VL(1:i))),2); 323 | [~,id] = max(Mout(:,i)); 324 | real(id,i) = 1; 325 | if mod(i,10) == 0 326 | rl = rl+real(:,(i/10-1)*10+1:i); 327 | end 328 | end 329 | WRR = 100*sum(sum(rl.*eye(10,10)))/words; 330 | TF= TF+rl; 331 | end 332 | WRR = 100*sum(sum(TF.*eye(10,10)))/(u*words); 333 | 334 | % ----------------------PLOT---------------------- 335 | figure(1); 336 | x = [0 9];y = [0 9]; 337 | imagesc(x, y, TF); 338 | ylabel('Predicted output digit') 339 | xlabel('Correct output digit') 340 | title(['Acc: ',num2str(WRR),'%']) 341 | colorbar; 342 | colormap(flipud(hot)); 343 | set(gca,'FontName', 'Arial', 'FontSize', 15); 344 | 345 | figure(2); 346 | subplot(2,1,1) 347 | plot(Input(1, :)); 348 | ylabel('Input (V)') 349 | axis([0,inf,-inf,inf]); 350 | set(gca,'FontName', 'Arial', 'FontSize', 15); 351 | subplot(2,1,2) 352 | plot(memout(1, :), 'r'); 353 | xlabel('Time step') 354 | ylabel('Output (μA)') 355 | axis([0,inf,-inf,inf]); 356 | set(gca,'FontName', 'Arial', 'FontSize', 15); 357 | %% Henon Map prediction 358 | clc; 359 | clear; 360 | % ----------------------Model Parameters---------------------- 361 | para.r = 0.99; 362 | para.G0 = 0.5; 363 | para.Kp = 9.13; 364 | para.Kn = 0.32; 365 | para.alpha = 0.23; 366 | 367 | % ----------------------DM_RC Parameters---------------------- 368 | ML = 4; 369 | N = 25; 370 | Vmax = 2.5; 371 | Vmin = 0; 372 | 373 | % ----------------------DATASET---------------------- 374 | step = 1000; 375 | dataset = HenonMap(2*step+1); 376 | 377 | % ----------------------TRAIN---------------------- 378 | % initialize input stream 379 | Input = dataset(1:step+1); 380 | 381 | % generate target 382 | Target = Input(2:end); 383 | 384 | % mask process 385 | Mask = 2*unidrnd(2, N, ML)-3; 386 | Input_ex = []; 387 | for j = 1:N 388 | for i = 1:step 389 | Input_ex(j, (i-1)*ML+1:ML*i) = Input(i)*Mask(j, :); 390 | end 391 | end 392 | UL = max(max(Input_ex)); 393 | DL = min(min(Input_ex)); 394 | Input_ex = (Input_ex-DL)/(UL-DL)*(Vmax - Vmin)+Vmin; 395 | 396 | % memristor output 397 | memout = []; 398 | states = []; 399 | G = para.G0; 400 | for i = 1:length(Input_ex(1, :)) 401 | [memout(:,i), G] = DynamicMemristor(Input_ex(:,i), G, para); 402 | sprintf('%s', ['train:', num2str(i), ', Vmax:', num2str(Vmax), ', ML:', num2str(ML)]) 403 | end 404 | 405 | % linear regression 406 | for i = 1:step 407 | a = memout(:, ML*(i-1)+1:ML*i); 408 | states(:, i) = a(:); 409 | end 410 | X = [ones(1, step); states]; 411 | Wout = Target*pinv(X); 412 | 413 | % ----------------------TEST---------------------- 414 | % initialize input stream 415 | Input = dataset(step+1:2*step+1); 416 | % generate target 417 | Target = Input(2:end); 418 | 419 | % mask process 420 | Input_ex = []; 421 | for j = 1:N 422 | for i = 1:step 423 | Input_ex(j, (i-1)*ML+1:ML*i) = Input(i)*Mask(j, :); 424 | end 425 | end 426 | UL = max(max(Input_ex)); 427 | DL = min(min(Input_ex)); 428 | Input_ex = (Input_ex-DL)/(UL-DL)*(Vmax - Vmin)+Vmin; 429 | 430 | % memristor output 431 | memout = []; 432 | states = []; 433 | G = para.G0; 434 | for i = 1:length(Input_ex(1, :)) 435 | [memout(:, i), G] = DynamicMemristor(Input_ex(:,i),G,para); 436 | sprintf('%s',['test:', num2str(i), ', Vmax:', num2str(Vmax), ', ML:', num2str(ML)]) 437 | end 438 | 439 | % system output 440 | for i = 1:step 441 | a = memout(:, ML*(i-1)+1:ML*i); 442 | states(:,i) = a(:); 443 | end 444 | X = [ones(1, step); states]; 445 | Out = Wout*X; 446 | NRMSE = sqrt(mean((Out(10:end)-Target(10:end)).^2)./var(Target(10:end))); 447 | sprintf('%s',['NRMSE:',num2str(NRMSE)]) 448 | 449 | % ----------------------PLOT---------------------- 450 | % time series 451 | figure(1); 452 | plot(Target(1:200), 'k', 'linewidth', 2); 453 | hold on; 454 | plot(Out(1:200), 'r', 'linewidth',1); 455 | axis([0, 200, -2, 2]) 456 | str1 = '\color{black}Target'; 457 | str2 = '\color{red}Output'; 458 | lg = legend(str1, str2); 459 | set(lg, 'Orientation', 'horizon', 'box', 'off'); 460 | ylabel('Prediction') 461 | xlabel('Time (\tau)') 462 | set(gca,'FontName', 'Arial', 'FontSize', 20); 463 | set(gcf, 'unit', 'normalized', 'position', [0.2, 0.2, 0.6, 0.35]); 464 | 465 | % 2D map 466 | figure(2); 467 | plot(Target(2:end), 0.3*Target(1:end-1), '.k', 'markersize', 12); 468 | hold on; 469 | plot(Out(2:end), 0.3*Out(1:end-1), '.r', 'markersize', 12); 470 | str1 = '\color{black}Target'; 471 | str2 = '\color{red}Output'; 472 | lg = legend(str1,str2); 473 | set(lg, 'box', 'off'); 474 | ylabel('{\ity} (n)'); 475 | xlabel('{\itx} (n)'); 476 | axis([-2, 2, -0.4, 0.4]); 477 | set(gca, 'FontName', 'Arial', 'FontSize', 20); 478 | set(gcf, 'unit', 'normalized', 'position', [0.2,0.2,0.3,0.45]); 479 | -------------------------------------------------------------------------------- /Codes in NC2021/DynamicMemristor.m: -------------------------------------------------------------------------------- 1 | function [I,G]=DynamicMemristor(V,G,para) 2 | G=para.r*G+(1-para.r)*para.G0+updata(V,para.alpha).*(binaryFunc(V)-G); 3 | I=G.*(para.Kp*NL(max(V,0))+para.Kn*NL(min(V,0))); 4 | end 5 | 6 | function y=binaryFunc(x) 7 | id=x>0; 8 | y(id,1)=1; 9 | y(~id,1)=0; 10 | end 11 | 12 | function y=updata(x,a) 13 | y=a*abs(x)./(a*abs(x)+1); 14 | end 15 | 16 | function y=NL(x) 17 | y=x.^3; 18 | end 19 | -------------------------------------------------------------------------------- /Codes in NC2021/HenonMap.m: -------------------------------------------------------------------------------- 1 | function y = HenonMap(x) 2 | wn=normrnd(0,0.05^2,1,x); 3 | y=zeros(1,x+2); 4 | for i=3:x+2 5 | y(i)=1-1.4*y(i-1)^2+0.3*y(i-2)+wn(i-2); 6 | end 7 | y=y(3:end); 8 | end -------------------------------------------------------------------------------- /Codes in NC2021/README.md: -------------------------------------------------------------------------------- 1 | # Reservoir-computing 2 | Unzip 'Auditory Toolbox.zip' and 'Voice Data.zip'. 3 | Run 'DM_RC_sim.m' for simulation. 4 | -------------------------------------------------------------------------------- /Codes in NC2021/Voice Data.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tsinghua-LEMON-Lab/Reservoir-computing/ec5518d07b70af4d843c1c4925d20da93bfc67e8/Codes in NC2021/Voice Data.zip -------------------------------------------------------------------------------- /Codes in NC2021/exdata.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tsinghua-LEMON-Lab/Reservoir-computing/ec5518d07b70af4d843c1c4925d20da93bfc67e8/Codes in NC2021/exdata.mat -------------------------------------------------------------------------------- /Codes in NE2022/Simulations/DGRdataset.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tsinghua-LEMON-Lab/Reservoir-computing/ec5518d07b70af4d843c1c4925d20da93bfc67e8/Codes in NE2022/Simulations/DGRdataset.mat -------------------------------------------------------------------------------- /Codes in NE2022/Simulations/DGRpara.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tsinghua-LEMON-Lab/Reservoir-computing/ec5518d07b70af4d843c1c4925d20da93bfc67e8/Codes in NE2022/Simulations/DGRpara.mat -------------------------------------------------------------------------------- /Codes in NE2022/Simulations/DMnode.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | class DM_node: 5 | def __init__(self, T, S, alpha): 6 | self.T = T 7 | self.S = S 8 | self.alpha = alpha 9 | 10 | def test(self, Vi, Vm): 11 | Vm = Vm+self.alpha*(Vi-self.T-Vm) 12 | Vt = self.T-Vm 13 | Vo = np.clip(self.S*(Vi-Vt), 0, 1) 14 | return Vo, Vm 15 | -------------------------------------------------------------------------------- /Codes in NE2022/Simulations/ECGdataset.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tsinghua-LEMON-Lab/Reservoir-computing/ec5518d07b70af4d843c1c4925d20da93bfc67e8/Codes in NE2022/Simulations/ECGdataset.mat -------------------------------------------------------------------------------- /Codes in NE2022/Simulations/ECGpara.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tsinghua-LEMON-Lab/Reservoir-computing/ec5518d07b70af4d843c1c4925d20da93bfc67e8/Codes in NE2022/Simulations/ECGpara.mat -------------------------------------------------------------------------------- /Codes in NE2022/Simulations/Sim_DGR.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import io 3 | import matplotlib.pyplot as plt 4 | import DMnode as DM 5 | 6 | 7 | ################################################## 8 | # GLOBAL VARIABLES 9 | ################################################## 10 | 11 | # Task 12 | N_CLASSES = 4 13 | SEED = 18 14 | 15 | # Hyperparameters optimized 16 | ML = 8 17 | N = 8 18 | T = -0.05 19 | S = 0.9 20 | alpha = 0.03 21 | 22 | 23 | ################################################## 24 | # NETWORK MODEL 25 | ################################################## 26 | Mask = io.loadmat('DGRpara.mat')['Mask'] 27 | u = DM.DM_node(T, S, alpha) 28 | 29 | 30 | def DMClassifier(Input): 31 | L = len(Input[0, :]) 32 | Input_ex = np.zeros((3*N, L*ML)) 33 | for j in range(N): 34 | ax = np.dot(Input[[0], :].T, Mask[:, [j]].T).reshape((1, -1)) 35 | ay = np.dot(Input[[1], :].T, Mask[:, [j]].T).reshape((1, -1)) 36 | az = np.dot(Input[[2], :].T, Mask[:, [j]].T).reshape((1, -1)) 37 | Input_ex[j*3:(j+1)*3, :] = np.vstack([ax, ay, az]) 38 | 39 | memout = np.zeros((3*N, L*ML)) 40 | Vm = 0 41 | for i in range(L*ML): 42 | memout[:, i], Vm = u.test(Input_ex[:, i], Vm) 43 | 44 | neuout = np.zeros((3*N*ML, L)) 45 | for i in range(L): 46 | neuout[:, i] = memout[:, i*ML:(i+1)*ML].reshape((-1, 1))[:, 0] 47 | 48 | return neuout 49 | 50 | 51 | ################################################## 52 | # DATA PROCESSING 53 | ################################################## 54 | def DataProcess(x, y): 55 | Input = x.reshape((1, -1, 3))[0, :, :].T 56 | Target = y.reshape((1, -1, N_CLASSES))[0, :, :].T 57 | return Input, Target 58 | 59 | 60 | def DataGen(): 61 | # LOAD DATA 62 | data = io.loadmat('DGRdataset.mat')['dataset'] 63 | np.random.seed(SEED) 64 | np.random.shuffle(data) 65 | np.random.seed() 66 | data_test = data[:300, :, :] 67 | data_train = data[300:, :, :] 68 | 69 | # DATA PREPROCESSING 70 | X_train = data_train[:, :, :3]/np.max(np.abs(data_train[:, :, :3])) 71 | X_test = data_test[:, :, :3]/np.max(np.abs(data_test[:, :, :3])) 72 | Y_train = data_train[:, :, 3] 73 | Y_test = data_test[:, :, 3] 74 | print("X train size: ", len(X_train)) 75 | print("X test size: ", len(X_test)) 76 | print("Y train size: ", len(Y_train)) 77 | print("Y test size: ", len(Y_test)) 78 | return X_train, X_test, Y_train, Y_test 79 | 80 | 81 | ################################################## 82 | # SYSTEM RUN 83 | ################################################## 84 | def Train(Input, Target): 85 | Input = Input.reshape((1, -1, 3))[0, :, :].T 86 | States = DMClassifier(Input) 87 | States = np.vstack([np.ones((1, len(Input[0, :]))), States]) 88 | Wout = Target.dot(States.T).dot(np.linalg.pinv(np.dot(States, States.T))) 89 | Output = np.dot(Wout, States) 90 | NRMSE = np.mean(np.sqrt(np.mean((Output-Target)**2, axis=1)/np.var(Target, axis=1))) 91 | print('Train_error: ' + str(NRMSE)) 92 | return Wout, NRMSE 93 | 94 | 95 | def Test(Wout, Input, Target): 96 | Input = Input.reshape((1, -1, 3))[0, :, :].T 97 | States = DMClassifier(Input) 98 | States = np.vstack([np.ones((1, len(Input[0, :]))), States]) 99 | Output = np.dot(Wout, States) 100 | NRMSE = np.mean(np.sqrt(np.mean((Output-Target)**2, axis=1)/np.var(Target, axis=1))) 101 | print('Test_error: ' + str(NRMSE)) 102 | return Output 103 | 104 | 105 | ################################################## 106 | # MAIN 107 | ################################################## 108 | if __name__ == '__main__': 109 | 110 | # LOAD DATA 111 | X_train, X_test, Y_train, Y_test = DataGen() 112 | 113 | # TRAINING PROCESURE 114 | Target_train = [] 115 | for i in range(1, N_CLASSES+1): 116 | Target = Y_train/i 117 | Target[Target[:, 15] != 1, :] = 0 118 | Target = Target.reshape((1, -1)) 119 | Target_train.append(Target[0, :]) 120 | Target_train = np.array(Target_train) 121 | Wout, _ = Train(X_train, Target_train) 122 | 123 | # TESTING PROCESURE 124 | Target_test = [] 125 | for i in range(1, N_CLASSES+1): 126 | Target = Y_test/i 127 | Target[Target[:, 15] != 1, :] = 0 128 | Target = Target.reshape((1, -1)) 129 | Target_test.append(Target[0, :]) 130 | Target_test = np.array(Target_test) 131 | Output = Test(Wout, X_test, Target_test) 132 | 133 | # ACC CACULATING 134 | LEN = 30 135 | ACC = np.zeros((60, 9, N_CLASSES)) 136 | j = 0 137 | for TH in np.arange(0.21, 0.8, 0.01): 138 | k = 0 139 | for THS in np.arange(1, 10): 140 | for i in range(N_CLASSES): 141 | Fout = np.heaviside(Output[i, :].reshape(-1, LEN)-TH, 1) 142 | Fout = np.heaviside(np.sum(Fout, axis=1)-THS, 1) 143 | Ftar = np.max(Target_test[i, :].reshape(-1, LEN), axis=1) 144 | Fbox = Fout-Ftar 145 | ACC[j, k, i] = len(Fbox[Fbox == 0])/len(Fbox) 146 | k = k+1 147 | j = j+1 148 | for i in range(N_CLASSES): 149 | print(np.max(ACC[:, :, i])) 150 | 151 | # PLOT 152 | plt.figure() 153 | plt.subplot(5, 1, 1) 154 | plt.plot(X_test.reshape((-1, 3))) 155 | plt.axis([0, 2000, -1.1, 1.1]) 156 | plt.ylabel('Input') 157 | plt.subplot(5, 1, 2) 158 | plt.plot(Target_test[0, :]) 159 | plt.plot(Output[0, :]) 160 | plt.axis([0, 2000, -0.2, 1.2]) 161 | plt.ylabel('O1') 162 | plt.subplot(5, 1, 3) 163 | plt.plot(Target_test[1, :]) 164 | plt.plot(Output[1, :]) 165 | plt.axis([0, 2000, -0.2, 1.2]) 166 | plt.ylabel('O2') 167 | plt.subplot(5, 1, 4) 168 | plt.plot(Target_test[2, :]) 169 | plt.plot(Output[2, :]) 170 | plt.axis([0, 2000, -0.2, 1.2]) 171 | plt.ylabel('O3') 172 | plt.subplot(5, 1, 5) 173 | plt.plot(Target_test[3, :]) 174 | plt.plot(Output[3, :]) 175 | plt.axis([0, 2000, -0.2, 1.2]) 176 | plt.ylabel('O4') 177 | plt.xlabel('Time Step') 178 | plt.show() 179 | -------------------------------------------------------------------------------- /Codes in NE2022/Simulations/Sim_ECG.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import io 3 | import matplotlib.pyplot as plt 4 | import DMnode as DM 5 | from sklearn.model_selection import train_test_split 6 | 7 | 8 | ################################################## 9 | # GLOBAL VARIABLES 10 | ################################################## 11 | 12 | # Task 13 | N_CLASSES = 1 14 | STEP = 1000 15 | 16 | # Hyperparameters optimized 17 | ML = 5 18 | N = 24 19 | T = 0.08 20 | S = 2 21 | alpha = 0.035 22 | 23 | ################################################## 24 | # NETWORK MODEL 25 | ################################################## 26 | Mask = io.loadmat('ECGpara.mat')['Mask'] 27 | u = DM.DM_node(T, S, alpha) 28 | 29 | 30 | def DMClassifier(Input): 31 | L = len(Input[0, :]) 32 | Input_ex = np.zeros((N, L*ML)) 33 | for j in range(N): 34 | Input_ex[j, :] = np.dot(Input[[0], :].T, Mask[:, [j]].T).reshape((1, -1)) 35 | 36 | memout = np.zeros((N, L*ML)) 37 | Vm = 0 38 | for i in range(L*ML): 39 | memout[:, i], Vm = u.test(Input_ex[:, i], Vm) 40 | 41 | neuout = np.zeros((N*ML, L)) 42 | for i in range(L): 43 | neuout[:, i] = memout[:, i*ML:(i+1)*ML].reshape((-1, 1))[:, 0] 44 | 45 | return neuout 46 | 47 | 48 | ################################################## 49 | # DATA PROCESSING 50 | ################################################## 51 | def DataProcess(x, y): 52 | Input = x.reshape((1, -1, 1))[0, :, :].T 53 | Target = y.reshape((1, -1, N_CLASSES))[0, :, :].T 54 | return Input, Target 55 | 56 | 57 | def DataGen(): 58 | # LOAD DATA 59 | data = io.loadmat('ECGdataset.mat')['dataset'][:STEP, :, :] 60 | 61 | # DATA PREPROCESSING 62 | inputs = data[:, :, 0]/np.max(np.abs(data[:, :, 0]), axis=1).reshape((-1, 1)) 63 | labels = data[:, :, 1:] 64 | 65 | print("Data shape: ", inputs.shape) 66 | print("Labels shape:", labels.shape) 67 | 68 | # SPLIT INTO TRAINING AND TEST SETS 69 | X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, test_size=0.3) 70 | print("X train size: ", len(X_train)) 71 | print("X test size: ", len(X_test)) 72 | print("Y train size: ", len(Y_train)) 73 | print("Y test size: ", len(Y_test)) 74 | return X_train, X_test, Y_train, Y_test 75 | 76 | 77 | ################################################## 78 | # SYSTEM RUN 79 | ################################################## 80 | def Train(Input, Target): 81 | States = DMClassifier(Input) 82 | States = np.vstack([np.ones((1, len(Input[0, :]))), States]) 83 | Wout = Target.dot(States.T).dot(np.linalg.pinv(np.dot(States, States.T))) 84 | Output = np.dot(Wout, States) 85 | NRMSE = np.mean(np.sqrt(np.mean((Output-Target)**2, axis=1)/np.var(Target, axis=1))) 86 | print('Train_error: ' + str(NRMSE)) 87 | return Wout, NRMSE 88 | 89 | 90 | def Test(Wout, Input, Target): 91 | States = DMClassifier(Input) 92 | States = np.vstack([np.ones((1, len(Input[0, :]))), States]) 93 | Output = np.dot(Wout, States) 94 | NRMSE = np.mean(np.sqrt(np.mean((Output-Target)**2, axis=1)/np.var(Target, axis=1))) 95 | print('Test_error: ' + str(NRMSE)) 96 | return Output, States, NRMSE 97 | 98 | 99 | ################################################## 100 | # MAIN 101 | ################################################## 102 | if __name__ == '__main__': 103 | 104 | # LOAD DATA 105 | X_train, X_test, Y_train, Y_test = DataGen() 106 | 107 | # TRAINING PROCESURE 108 | Input, Target = DataProcess(X_train, Y_train) 109 | Wout, _ = Train(Input, Target) 110 | 111 | # TESTING PROCESURE 112 | Input, Target = DataProcess(X_test, Y_test) 113 | Output, States, _ = Test(Wout, Input, Target) 114 | 115 | # ACC CACULATING 116 | LEN = 50 117 | ACC = np.zeros((60, 5)) 118 | TH_list = np.zeros(2) 119 | TH_box = np.arange(0.21, 0.8, 0.01) 120 | THS_box = np.arange(1, 6) 121 | j = 0 122 | for TH in TH_box: 123 | k = 0 124 | for THS in THS_box: 125 | Fout = np.heaviside(Output[0, :].reshape(-1, LEN)-TH, 1) 126 | Fout = np.heaviside(np.sum(Fout, axis=1)-THS, 1) 127 | Ftar = np.max(Target[0, :].reshape(-1, LEN), axis=1) 128 | Fbox = Fout-Ftar 129 | ACC[j, k] = len(Fbox[Fbox == 0])/len(Fbox) 130 | k = k+1 131 | j = j+1 132 | print(np.max(ACC)) 133 | 134 | # PLOT 135 | plt.figure() 136 | plt.subplot(2, 1, 1) 137 | plt.plot(Input.T) 138 | plt.axis([0, 5000, -1, 1]) 139 | plt.ylabel('Input') 140 | plt.subplot(2, 1, 2) 141 | plt.plot(Target[0, :]) 142 | plt.plot(Output[0, :]) 143 | plt.axis([0, 5000, -0.2, 1.2]) 144 | plt.ylabel('Output') 145 | plt.show() 146 | -------------------------------------------------------------------------------- /Codes in NE2022/Simulations/Sim_IV.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | import DMnode as DM 4 | 5 | ################################################## 6 | # GLOBAL VARIABLES 7 | ################################################## 8 | 9 | # Hyperparameters optimized 10 | ML = 1 11 | N = 1 12 | T = 0.0 13 | S = 3 14 | alpha = 0.02 15 | 16 | ################################################## 17 | # NETWORK MODEL 18 | ################################################## 19 | Mask = np.ones((ML, N)) 20 | u = DM.DM_node(T, S, alpha) 21 | 22 | 23 | def DMClassifier(Input): 24 | L = len(Input) 25 | Input_ex = np.zeros((N, L * ML)) 26 | for j in range(N): 27 | Input_ex[j, :] = np.dot(Input.reshape((-1, 1)), 28 | Mask[:, [j]].T).reshape((1, -1)) 29 | 30 | memout = np.zeros((N, L * ML)) 31 | Vm = 0 32 | for i in range(L * ML): 33 | memout[:, i], Vm = u.test(Input_ex[:, i], Vm) 34 | 35 | neuout = np.zeros((N * ML, L)) 36 | for i in range(L): 37 | neuout[:, i] = memout[:, i * ML:(i + 1) * ML].reshape((-1, 1))[:, 0] 38 | 39 | return neuout 40 | 41 | 42 | ################################################## 43 | # DATA PROCESSING 44 | ################################################## 45 | def DataGen(): 46 | cycle = 1 47 | p = list(range(0, 255, 1)) + list(range(255, 0, -1)) 48 | Input = (np.array(cycle * p) / 255 - 0.5) * 2 49 | return Input 50 | 51 | 52 | ################################################## 53 | # MAIN 54 | ################################################## 55 | if __name__ == '__main__': 56 | 57 | # LOAD DATA 58 | Input = DataGen() 59 | 60 | # I-V 61 | Output = DMClassifier(Input) 62 | Output = Output[0, :] 63 | 64 | # PLOT 65 | plt.figure() 66 | plt.plot(Input, Output, c='b') 67 | plt.xticks(np.arange(-1, 1.2, 0.5)) 68 | plt.yticks(np.arange(0, 1.2, 0.2)) 69 | plt.xlim(-1.1, 1.1) 70 | plt.ylim(-0.1, 1.1) 71 | plt.xlabel('Input') 72 | plt.ylabel('Output') 73 | plt.show() 74 | -------------------------------------------------------------------------------- /Codes in NE2022/Simulations/Sim_WFC.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | import DMnode as DM 4 | 5 | ################################################## 6 | # GLOBAL VARIABLES 7 | ################################################## 8 | # Test control 9 | SEED = 20 10 | STEP = 400 11 | WUP = 50 12 | 13 | # Hyperparameters optimized 14 | ML = 5 15 | N = 24 16 | T = 0.25 17 | S = 2 18 | alpha = 0.2 19 | 20 | 21 | ################################################## 22 | # NETWORK MODEL 23 | ################################################## 24 | # Mask setup 25 | Mask = 2*np.random.randint(2, size=(ML, N)) - 1 26 | u = DM.DM_node(T, S, alpha) 27 | 28 | 29 | def DMClassifier(Input): 30 | L = len(Input[0, :]) 31 | Input_ex = np.zeros((N, L*ML)) 32 | for j in range(N): 33 | Input_ex[j, :] = np.dot(Input[[0], :].T, Mask[:, [j]].T).reshape((1, -1)) 34 | 35 | memout = np.zeros((N, L*ML)) 36 | Vm = 0 37 | for i in range(L*ML): 38 | memout[:, i], Vm = u.test(Input_ex[:, i], Vm) 39 | 40 | neuout = np.zeros((N*ML, L)) 41 | for i in range(L): 42 | neuout[:, i] = memout[:, i*ML:(i+1)*ML].reshape((-1, 1))[:, 0] 43 | 44 | return neuout 45 | 46 | 47 | ################################################## 48 | # DATASET 49 | ################################################## 50 | def DataGen(step): 51 | sample = 8 52 | np.random.seed(SEED) 53 | p1 = (np.random.rand(sample)-0.5)*2 54 | p2 = (np.random.rand(sample)-0.5)*2 55 | np.random.seed() 56 | Input = np.zeros((1, step)) 57 | Target = np.zeros((1, step)) 58 | for i in range(int(step/sample)): 59 | q = np.random.randint(2) 60 | if q == 1: 61 | Input[0, sample*i:sample*(i+1)] = p1 62 | Target[0, sample*i:sample*(i+1)] = 1 63 | else: 64 | Input[0, sample*i:sample*(i+1)] = p2 65 | Target[0, sample*i:sample*(i+1)] = 0 66 | Input = np.vstack([Input, Input, Input]) 67 | return Input, Target 68 | 69 | 70 | ################################################## 71 | # SYSTEM RUN 72 | ################################################## 73 | def Train(Input, Target): 74 | States = DMClassifier(Input) 75 | States = np.vstack([np.ones((1, STEP)), States]) 76 | Wout = Target[:, WUP:].dot(States[:, WUP:].T).dot(np.linalg.pinv(np.dot(States[:, WUP:], States[:, WUP:].T))) 77 | Output = np.dot(Wout, States) 78 | NRMSE = np.mean(np.sqrt(np.mean((Output[:, WUP:]-Target[:, WUP:])**2, axis=1)/np.var(Target[:, WUP:], axis=1))) 79 | print('Train_error: ' + str(NRMSE)) 80 | return Wout, NRMSE 81 | 82 | 83 | def Test(Wout, Input, Target): 84 | States = DMClassifier(Input) 85 | States = np.vstack([np.ones((1, STEP)), States]) 86 | Output = np.dot(Wout, States) 87 | NRMSE = np.mean(np.sqrt(np.mean((Output[:, WUP:]-Target[:, WUP:])**2, axis=1)/np.var(Target[:, WUP:], axis=1))) 88 | print('Test_error: ' + str(NRMSE)) 89 | return Output, States 90 | 91 | 92 | ################################################## 93 | # MAIN 94 | ################################################## 95 | if __name__ == '__main__': 96 | # TRAINING PROCESURE 97 | Input, Target_train = DataGen(STEP) 98 | Wout, _ = Train(Input, Target_train) 99 | 100 | # TESTING PROCESURE 101 | Input, Target_test = DataGen(STEP) 102 | Output, States = Test(Wout, Input, Target_test) 103 | 104 | # PLOT 105 | plt.figure() 106 | plt.subplot(2, 1, 1) 107 | plt.plot(Input.T) 108 | plt.ylabel('Input') 109 | plt.xlim(0, STEP) 110 | plt.subplot(2, 1, 2) 111 | plt.plot(Target_test.T) 112 | plt.plot(Output.T) 113 | plt.axis([0, STEP, -0.2, 1.2]) 114 | plt.xlabel('Time Step') 115 | plt.ylabel('Output') 116 | 117 | plt.figure() 118 | plt.plot(States.T) 119 | plt.xlim(0, 200) 120 | 121 | plt.show() 122 | -------------------------------------------------------------------------------- /Codes in NE2022/Upper computer program/Addr.csv: -------------------------------------------------------------------------------- 1 | wl_addr,bl_addr 2 | 0.0,0.0 3 | 0.0,4.0 4 | 0.0,6.0 5 | 1.0,1.0 6 | 1.0,4.0 7 | 1.0,7.0 8 | 2.0,2.0 9 | 2.0,5.0 10 | 3.0,1.0 11 | 3.0,3.0 12 | 3.0,6.0 13 | 4.0,1.0 14 | 4.0,4.0 15 | 4.0,7.0 16 | 5.0,2.0 17 | 5.0,5.0 18 | 6.0,0.0 19 | 6.0,3.0 20 | 6.0,6.0 21 | 7.0,1.0 22 | 7.0,4.0 23 | 7.0,7.0 24 | 8.0,2.0 25 | 8.0,5.0 26 | 9.0,0.0 27 | 9.0,3.0 28 | 9.0,6.0 29 | 10.0,1.0 30 | 10.0,4.0 31 | 10.0,7.0 32 | 11.0,2.0 33 | 11.0,5.0 34 | 12.0,0.0 35 | 12.0,3.0 36 | 12.0,6.0 37 | 13.0,1.0 38 | 13.0,4.0 39 | 13.0,7.0 40 | 14.0,2.0 41 | 14.0,5.0 42 | 15.0,0.0 43 | 15.0,3.0 44 | 15.0,6.0 45 | 16.0,1.0 46 | 16.0,4.0 47 | 17.0,0.0 48 | 17.0,2.0 49 | 17.0,5.0 50 | 18.0,0.0 51 | 18.0,3.0 52 | 18.0,6.0 53 | 19.0,1.0 54 | 19.0,4.0 55 | 19.0,7.0 56 | 20.0,2.0 57 | 20.0,5.0 58 | 21.0,0.0 59 | 21.0,3.0 60 | 21.0,6.0 61 | 22.0,1.0 62 | 22.0,4.0 63 | 22.0,7.0 64 | 23.0,2.0 65 | 23.0,5.0 66 | 24.0,0.0 67 | 24.0,3.0 68 | 24.0,6.0 69 | 25.0,1.0 70 | 25.0,4.0 71 | 25.0,7.0 72 | 26.0,2.0 73 | 26.0,5.0 74 | 27.0,0.0 75 | 27.0,4.0 76 | 27.0,6.0 77 | 28.0,1.0 78 | 28.0,4.0 79 | 28.0,7.0 80 | 29.0,2.0 81 | 29.0,5.0 82 | 30.0,0.0 83 | 30.0,3.0 84 | 30.0,6.0 85 | 31.0,1.0 86 | 31.0,4.0 87 | 31.0,7.0 88 | 32.0,2.0 89 | 32.0,5.0 90 | 33.0,0.0 91 | 33.0,3.0 92 | 33.0,6.0 93 | 34.0,1.0 94 | 34.0,4.0 95 | 34.0,7.0 96 | 35.0,2.0 97 | 35.0,5.0 98 | 36.0,0.0 99 | 36.0,3.0 100 | 36.0,6.0 101 | 37.0,1.0 102 | 37.0,4.0 103 | 37.0,7.0 104 | 38.0,2.0 105 | 38.0,5.0 106 | 39.0,0.0 107 | 39.0,3.0 108 | 39.0,6.0 109 | 40.0,1.0 110 | 40.0,4.0 111 | 40.0,7.0 112 | 41.0,2.0 113 | 41.0,5.0 114 | 42.0,0.0 115 | 42.0,3.0 116 | 42.0,6.0 117 | 43.0,1.0 118 | 43.0,4.0 119 | 43.0,7.0 120 | 44.0,2.0 121 | 44.0,5.0 122 | 45.0,1.0 123 | 45.0,3.0 124 | 45.0,6.0 125 | 46.0,1.0 126 | 46.0,5.0 127 | 46.0,7.0 128 | 47.0,2.0 129 | 47.0,5.0 130 | 48.0,0.0 131 | 48.0,3.0 132 | 48.0,6.0 133 | 49.0,1.0 134 | 49.0,4.0 135 | 49.0,7.0 136 | 50.0,2.0 137 | 50.0,5.0 138 | 51.0,0.0 139 | 51.0,3.0 140 | 51.0,6.0 141 | 52.0,1.0 142 | 52.0,4.0 143 | 52.0,7.0 144 | 53.0,2.0 145 | 53.0,5.0 146 | 54.0,0.0 147 | 54.0,3.0 148 | 54.0,6.0 149 | 55.0,1.0 150 | 55.0,4.0 151 | 55.0,7.0 152 | 56.0,2.0 153 | 56.0,5.0 154 | 57.0,0.0 155 | 57.0,3.0 156 | 57.0,6.0 157 | 58.0,1.0 158 | 58.0,4.0 159 | 58.0,7.0 160 | 59.0,2.0 161 | 59.0,5.0 162 | 60.0,0.0 163 | 60.0,3.0 164 | 60.0,6.0 165 | 61.0,1.0 166 | 61.0,4.0 167 | 61.0,7.0 168 | 62.0,2.0 169 | 62.0,5.0 170 | 63.0,0.0 171 | 63.0,3.0 172 | 63.0,6.0 173 | 64.0,1.0 174 | 64.0,4.0 175 | 64.0,7.0 176 | 65.0,2.0 177 | 65.0,5.0 178 | 66.0,0.0 179 | 66.0,3.0 180 | 66.0,6.0 181 | 67.0,1.0 182 | 67.0,4.0 183 | 67.0,7.0 184 | 68.0,2.0 185 | 68.0,5.0 186 | 69.0,0.0 187 | 69.0,4.0 188 | 69.0,6.0 189 | 70.0,1.0 190 | 70.0,4.0 191 | 70.0,7.0 192 | 71.0,2.0 193 | 71.0,5.0 194 | -------------------------------------------------------------------------------- /Codes in NE2022/Upper computer program/DGR_test.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | from scipy import io 4 | import serial 5 | import time 6 | import Interface as MI 7 | from datetime import datetime 8 | 9 | 10 | ################################################## 11 | # GLOBAL VARIABLES 12 | ################################################## 13 | 14 | # Dataset related 15 | N_CLASSES = 4 16 | STEP = 200 17 | SEED = 18 18 | 19 | # Hyperparameters optimized 20 | ML = 8 21 | N = 8 22 | 23 | 24 | ################################################## 25 | # OBJECTS 26 | ################################################## 27 | class strcture: 28 | pass 29 | 30 | 31 | OPMethod = strcture() 32 | s = serial.Serial('com6', 115200, timeout=15) 33 | 34 | 35 | ################################################## 36 | # HARDWARE RC SETUP 37 | ################################################## 38 | 39 | # DMReservoir setup 40 | def DMClassifier(Input, Delay_s, Delay_m, Delay_w, TestOnly): 41 | Input = Input.reshape((1, -1)) 42 | Input = np.uint8(255*(Input[0, :]+0.5)) 43 | memout = MI.DMRC_tb(MI.DMRCtest(OPMethod, Input, ML, Delay_s, Delay_m, Delay_w, TestOnly), s) 44 | memout = np.array(list(memout)) 45 | if TestOnly==1: 46 | states = [] 47 | out = memout.reshape((4, -1), order='F') 48 | else: 49 | states = memout[:8*len(Input)*ML].reshape((3*N*ML, -1), order='F') 50 | out = memout[8*len(Input)*ML:].reshape((4, -1), order='F') 51 | return states, out 52 | 53 | 54 | ################################################## 55 | # DATA LOADING 56 | ################################################## 57 | def DataGen(): 58 | # LOAD DATA 59 | data = io.loadmat('DGRdataset.mat')['dataset'] 60 | np.random.seed(SEED) 61 | np.random.shuffle(data) 62 | np.random.seed() 63 | data_test = data[:300, :, :] 64 | data_train = data[300:, :, :] 65 | 66 | # DATA PREPROCESSING 67 | X_train = 0.5*data_train[:, :, :3]/np.max(np.abs(data_train[:, :, :3])) 68 | X_test = 0.5*data_test[:, :, :3]/np.max(np.abs(data_test[:, :, :3])) 69 | Y_train = data_train[:, :, 3] 70 | Y_test = data_test[:, :, 3] 71 | print("X train size: ", len(X_train)) 72 | print("X test size: ", len(X_test)) 73 | print("Y train size: ", len(Y_train)) 74 | print("Y test size: ", len(Y_test)) 75 | return X_train, X_test, Y_train, Y_test 76 | 77 | 78 | ################################################## 79 | # SYSTEM RUN 80 | ################################################## 81 | def Train(X_train, Target, Delay_s, Delay_m, Delay_w, TestOnly): 82 | L = len(X_train[0, :, 0]) 83 | Num = len(X_train[:, 0, 0]) 84 | States = np.ones((Num, L, 3*N*ML)) 85 | for i in range(Num): 86 | a, _ = DMClassifier(X_train[i, :, :], Delay_s, Delay_m, Delay_w, TestOnly) 87 | States[i, :, :] = a.T 88 | print('Train_num: ' + str(i)) 89 | Sdata = np.zeros((Num, L, 3*N*ML+1)) 90 | Sdata[:, :, :3*N*ML] = States 91 | Sdata[:, :, 3*N*ML] = Target 92 | NRMSE = np.ones(N_CLASSES) 93 | for i in range(N_CLASSES): 94 | Goaldata = Sdata[Target[:, 15]==i+1, :, :] 95 | Compdata = Sdata[Target[:, 15]!=i+1, :, :] 96 | data = np.vstack([Goaldata[:STEP, :, :], Compdata[:STEP, :, :]]) 97 | np.random.shuffle(data) 98 | States_ = data[:, :, :-1].reshape((-1, 3*N*ML)).T 99 | Target_ = data[:, :, -1]/(i+1) 100 | Target_[Target_[:, 15]!=1, :] = 0 101 | Target_ = Target_.reshape((1, -1)) 102 | Wout = Target_.dot(States_.T).dot(np.linalg.pinv(np.dot(States_, States_.T))) 103 | Output = np.dot(Wout, States_) 104 | NRMSE[i] = np.mean(np.sqrt(np.mean((Output-Target_)**2, axis=1)/np.var(Target_, axis=1))) 105 | print('Train_error: ' + str(np.mean(NRMSE))) 106 | return States, np.mean(NRMSE) 107 | 108 | 109 | def Test(X_test, Target, Delay_s, Delay_m, Delay_w, TestOnly): 110 | L = len(X_test[0, :, 0]) 111 | Num = len(X_test[:, 0, 0]) 112 | Output = np.zeros((N_CLASSES, L*Num)) 113 | States = np.ones((3*N*ML, L*Num)) 114 | for i in range(Num): 115 | if TestOnly==1: 116 | _, Output[:, L*i:L*(i+1)] = DMClassifier(X_test[i, :, :], Delay_s, Delay_m, Delay_w, TestOnly) 117 | # time.sleep(0.4) 118 | else: 119 | States[:, L*i:L*(i+1)], Output[:, L*i:L*(i+1)] = DMClassifier(X_test[i, :, :], Delay_s, Delay_m, Delay_w, TestOnly) 120 | print('Test_num: ' + str(i)) 121 | NRMSE = np.mean(np.sqrt(np.mean((Output-Target)**2, axis=1)/np.var(Target, axis=1))) 122 | print('Test_error: ' + str(NRMSE)) 123 | return Output, States, NRMSE 124 | 125 | 126 | def main(Av_out, Bias_out, Av_in, Bias_in, Delay_s, Delay_m, Delay_w, TestOnly, SAVE, FIX): 127 | 128 | # Mask setup 129 | if FIX == 1: 130 | Mask = io.loadmat('DGRpara.mat')['Mask'][0, :] 131 | else: 132 | Mask = np.uint8(np.random.randint(0, 255, 3*ML)) 133 | 134 | # Addr setup 135 | Addr = np.uint8(np.zeros(int(4.5*ML*N))) 136 | if TestOnly==1: 137 | AddrData = pd.read_csv('Addr.csv') 138 | Addr0 = np.array([AddrData['wl_addr'].values, AddrData['bl_addr'].values]).T 139 | Addr[:3*ML*N] = np.uint8(Addr0[:, 0]) 140 | for i in range(3*ML*N): 141 | if i % 2 == 1: 142 | Addr[int(3*ML*N+(i-1)/2)] = np.uint8(Addr0[i, 1]*8) | np.uint8(Addr0[i-1, 1]) 143 | 144 | # LOAD DATA 145 | X_train, X_test, Y_train, Y_test = DataGen() 146 | 147 | # GAIN ADJUST 148 | MI.A_init(0, s) 149 | time.sleep(0.1) 150 | MI.Am_adj(Av_in, s) 151 | time.sleep(0.1) 152 | MI.A_init(1, s) 153 | time.sleep(0.1) 154 | MI.Am_adj(Bias_in, s) 155 | time.sleep(0.1) 156 | MI.A_init(2, s) 157 | time.sleep(0.1) 158 | MI.Am_adj(Av_out, s) 159 | time.sleep(0.1) 160 | MI.A_init(3, s) 161 | time.sleep(0.1) 162 | MI.Am_adj(Bias_out, s) 163 | time.sleep(0.1) 164 | 165 | # MASK LOAD 166 | MI.LoadMask(Mask, s) 167 | time.sleep(0.1) 168 | 169 | # ADDR LOAD 170 | MI.LoadAddr(Addr, s) 171 | time.sleep(0.1) 172 | 173 | # Device select 174 | DMid = range(24) 175 | DMid_ = [] 176 | DMlist = np.zeros((1, 24)) 177 | DMlist[:, DMid] = 1 178 | DMlist[:, DMid_] = 0 179 | ind = np.arange(0, 24, 3) 180 | temp = np.array([1, 2, 4, 8, 16, 32, 64, 128]).reshape(-1, 1) 181 | S = np.dot(np.vstack([DMlist[:, ind], DMlist[:, ind+1], DMlist[:, ind+2]]), temp) 182 | 183 | # TRAINING PROCESURE 184 | MI.F_init(list(np.uint(S[:, 0])), s) 185 | time.sleep(0.1) 186 | NRMSE_train = 0 187 | if TestOnly != 1: 188 | States_train, NRMSE_train = Train(X_train, Y_train, Delay_s, Delay_m, Delay_w, TestOnly) 189 | 190 | # TESTING PROCESURE 191 | Target_test = [] 192 | for i in range(1, N_CLASSES+1): 193 | Target = Y_test/i 194 | Target[Target[:, 15]!=1, :] = 0 195 | Target = Target.reshape((1, -1)) 196 | Target_test.append(Target[0, :]) 197 | Target_test = np.array(Target_test) 198 | Output, States_test, NRMSE_test = Test(X_test, Target_test, Delay_s, Delay_m, Delay_w, TestOnly) 199 | OMAX = np.max(Output[:, :], axis=1).reshape((-1, 1)) 200 | Output = Output/OMAX 201 | 202 | # SAVE 203 | curr_time = datetime.now().strftime("%Y%m%d_%H%M") 204 | if SAVE == 1: 205 | if TestOnly == 1: 206 | Filename = 'data/DGRdata/DGR_test_'+curr_time+'.mat' 207 | io.savemat(Filename, {'Input_test': X_test, 'Target_test': Target_test, 'Output_test': Output}) 208 | else: 209 | Filename = 'data/DGRdata/DGR_train_'+curr_time+'.mat' 210 | io.savemat('DGRpara.mat', {'Mask': Mask, 'ML': ML, 'N': N, 'States_train': States_train, 211 | 'Target_train': Y_train, 'States_test': States_test, 'Target_test': Target_test}) 212 | io.savemat(Filename, {'States_train': States_train, 'Target_train': Y_train, 'Input_train': X_train, 213 | 'States_test': States_test, 'Target_test': Target_test, 'Input_test': X_test}) 214 | 215 | # ACC CACULATING 216 | ACC = np.zeros((60, 9, 4)) 217 | TH_list = np.zeros((4, 2)) 218 | ACC_list = np.zeros(4) 219 | if TestOnly == 1: 220 | TH_box = np.arange(0.21, 0.8, 0.01) 221 | THS_box = np.arange(1, 10) 222 | j = 0 223 | for TH in TH_box: 224 | k = 0 225 | for THS in THS_box: 226 | for i in range(4): 227 | Fout = np.heaviside(Output[i, :].reshape(-1, 30)-TH, 1) 228 | Fout = np.heaviside(np.sum(Fout, axis=1)-THS, 1) 229 | Ftar = np.max(Target_test[i, :].reshape(-1, 30), axis=1) 230 | Fbox = Fout-Ftar 231 | ACC[j, k, i] = len(Fbox[Fbox==0])/len(Fbox) 232 | k = k+1 233 | j = j+1 234 | for i in range(4): 235 | index = np.unravel_index(ACC[:, :, i].argmax(), ACC[:, :, i].shape) 236 | index = list(index) 237 | TH_list[i, 0] = TH_box[index[0]] 238 | TH_list[i, 1] = THS_box[index[1]] 239 | io.savemat('DGR_THlist.mat', {'TH_list': TH_list}) 240 | 241 | for i in range(4): 242 | print(np.max(ACC[:, :, i])) 243 | ACC_list[i] = np.max(ACC[:, :, i]) 244 | 245 | Ta_list = list(TH_list[:, 0]) 246 | Tb_list = list(TH_list[:, 1]) 247 | ACC_list = list(ACC_list) 248 | Input_list1 = list(X_test.reshape((-1, 3))[:, 0]) 249 | Input_list2 = list(X_test.reshape((-1, 3))[:, 1]) 250 | Input_list3 = list(X_test.reshape((-1, 3))[:, 2]) 251 | Target_list1 = list(Target_test[0, :]) 252 | Output_list1 = list(Output[0, :]) 253 | Target_list2 = list(Target_test[1, :]) 254 | Output_list2 = list(Output[1, :]) 255 | Target_list3 = list(Target_test[2, :]) 256 | Output_list3 = list(Output[2, :]) 257 | Target_list4 = list(Target_test[3, :]) 258 | Output_list4 = list(Output[3, :]) 259 | return (Input_list1, Input_list2, Input_list3, Target_list1, Output_list1, Target_list2, Output_list2, Target_list3, 260 | Output_list3, Target_list4, Output_list4, Ta_list, Tb_list, NRMSE_train, NRMSE_test, ACC_list) 261 | 262 | 263 | ################################################## 264 | # MAIN 265 | ################################################## 266 | if __name__ == '__main__': 267 | main(Av_out=50, Bias_out=160, Av_in=255, Bias_in=230, Delay_s=1, Delay_m=0, Delay_w=1, TestOnly=1, SAVE=0, FIX=1) -------------------------------------------------------------------------------- /Codes in NE2022/Upper computer program/DGRdataset.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tsinghua-LEMON-Lab/Reservoir-computing/ec5518d07b70af4d843c1c4925d20da93bfc67e8/Codes in NE2022/Upper computer program/DGRdataset.mat -------------------------------------------------------------------------------- /Codes in NE2022/Upper computer program/ECG_test.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | from scipy import io 4 | import matplotlib.pyplot as plt 5 | import serial 6 | import time 7 | import Interface as MI 8 | from datetime import datetime 9 | from sklearn.model_selection import train_test_split 10 | 11 | 12 | ################################################## 13 | # GLOBAL VARIABLES 14 | ################################################## 15 | 16 | # Task 17 | STEP = 10000 18 | RANDOM_SEED = 18 19 | 20 | # Hardware setting 21 | CS = 0 22 | ML = 5 23 | N = 8 24 | 25 | 26 | ################################################## 27 | # OBJECTS 28 | ################################################## 29 | class strcture: 30 | pass 31 | 32 | 33 | OPMethod = strcture() 34 | s = serial.Serial('com6', 115200, timeout=15) 35 | 36 | 37 | ################################################## 38 | # HARDWARE RC SETUP 39 | ################################################## 40 | 41 | # DMReservoir setup 42 | def DMClassifier(Input, Delay_s, Delay_m, Delay_w, TestOnly): 43 | Input = Input.reshape((1, -1)) 44 | Input = np.uint8(255*(Input[0, :]+0.5)) 45 | memout = MI.DMRC_tb(MI.DMRCtest(OPMethod, Input, ML, Delay_s, Delay_m, Delay_w, TestOnly), s) 46 | memout = np.array(list(memout)) 47 | if TestOnly==1: 48 | states = [] 49 | out = memout.reshape((4, -1), order='F')[CS, :] 50 | else: 51 | states = memout[:8*len(Input)*ML].reshape((3*N*ML, -1), order='F') 52 | out = memout[8*len(Input)*ML:].reshape((4, -1), order='F')[CS, :] 53 | return states, out 54 | 55 | 56 | ################################################## 57 | # DATA PROCESSING 58 | ################################################## 59 | def DataProcess(x, y): 60 | Input = np.zeros((len(x[:, 0]), len(x[0, :]), 3)) 61 | Target = y.reshape((1, -1, 1))[0, :, :].T 62 | Input[:, :, 0] = x 63 | Input[:, :, 1] = x 64 | Input[:, :, 2] = x 65 | return Input, Target 66 | 67 | 68 | def DataGen(): 69 | # LOAD DATA 70 | data = io.loadmat('ECGdataset.mat')['dataset'][:STEP, :, :] 71 | 72 | # DATA PREPROCESSING 73 | inputs = 0.5*data[:, :, 0]/np.max(np.abs(data[:, :, 0]), axis=1).reshape((-1, 1)) 74 | labels = data[:, :, 1] 75 | 76 | print("Data shape: ", inputs.shape) 77 | print("Labels shape:", labels.shape) 78 | 79 | # SPLIT INTO TRAINING AND TEST SETS 80 | X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, test_size=0.9, random_state=RANDOM_SEED) 81 | print("X train size: ", len(X_train)) 82 | print("X test size: ", len(X_test)) 83 | print("Y train size: ", len(Y_train)) 84 | print("Y test size: ", len(Y_test)) 85 | return X_train, X_test, Y_train, Y_test 86 | 87 | 88 | ################################################## 89 | # SYSTEM RUN 90 | ################################################## 91 | def Train(Input, Target, Delay_s, Delay_m, Delay_w, TestOnly): 92 | L = len(Input[0, :, 0]) 93 | Num = len(Input[:, 0, 0]) 94 | States = np.ones((3*N*ML, L*Num)) 95 | for i in range(Num): 96 | States[:, L*i:L*(i+1)], _ = DMClassifier(Input[i, :, :], Delay_s, Delay_m, Delay_w, TestOnly) 97 | print('Train_num: ' + str(i)) 98 | Wout = Target.dot(States.T).dot(np.linalg.pinv(np.dot(States, States.T))) 99 | Output = np.dot(Wout, States) 100 | NRMSE = np.mean(np.sqrt(np.mean((Output-Target)**2, axis=1)/np.var(Target, axis=1))) 101 | print('Train_error: ' + str(NRMSE)) 102 | return States, NRMSE 103 | 104 | 105 | def Test(Input, Target, Delay_s, Delay_m, Delay_w, TestOnly): 106 | L = len(Input[0, :, 0]) 107 | Num = len(Input[:, 0, 0]) 108 | Output = np.zeros((1, L*Num)) 109 | States = np.ones((3*N*ML, L*Num)) 110 | for i in range(Num): 111 | if TestOnly==1: 112 | _, Output[:, L*i:L*(i+1)] = DMClassifier(Input[i, :, :], Delay_s, Delay_m, Delay_w, TestOnly) 113 | else: 114 | States[:, L*i:L*(i+1)], Output[:, L*i:L*(i+1)] = DMClassifier(Input[i, :, :], Delay_s, Delay_m, Delay_w, TestOnly) 115 | print('Test_num: ' + str(i)) 116 | NRMSE = np.mean(np.sqrt(np.mean((Output-Target)**2, axis=1)/np.var(Target, axis=1))) 117 | print('Test_error: ' + str(NRMSE)) 118 | return Output, States, NRMSE 119 | 120 | def main(Av_out, Bias_out, Av_in, Bias_in, Delay_s, Delay_m, Delay_w, TestOnly, SAVE, FIX): 121 | 122 | # Mask setup 123 | if FIX == 1: 124 | Mask = io.loadmat('ECGpara.mat')['Mask'][0, :] 125 | else: 126 | Mask = np.uint8(np.random.randint(0, 255, 3*ML)) 127 | 128 | # Addr setup 129 | Addr = np.uint8(np.zeros(int(4.5*ML*N))) 130 | if TestOnly==1: 131 | AddrData = pd.read_csv('Addr.csv') 132 | Addr0 = np.array([AddrData['wl_addr'].values, AddrData['bl_addr'].values]).T 133 | Addr[:3*ML*N] = np.uint8(Addr0[:, 0]) 134 | for i in range(3*ML*N): 135 | if i % 2 == 1: 136 | Addr[int(3*ML*N+(i-1)/2)] = np.uint8(Addr0[i, 1]*8) | np.uint8(Addr0[i-1, 1]) 137 | 138 | # LOAD DATA 139 | X_train, X_test, Y_train, Y_test = DataGen() 140 | 141 | # GAIN ADJUST 142 | MI.A_init(0, s) 143 | time.sleep(0.1) 144 | MI.Am_adj(Av_in, s) 145 | time.sleep(0.1) 146 | MI.A_init(1, s) 147 | time.sleep(0.1) 148 | MI.Am_adj(Bias_in, s) 149 | time.sleep(0.1) 150 | MI.A_init(2, s) 151 | time.sleep(0.1) 152 | MI.Am_adj(Av_out, s) 153 | time.sleep(0.1) 154 | MI.A_init(3, s) 155 | time.sleep(0.1) 156 | MI.Am_adj(Bias_out, s) 157 | time.sleep(0.1) 158 | 159 | # MASK LOAD 160 | MI.LoadMask(Mask, s) 161 | time.sleep(0.1) 162 | 163 | # ADDR LOAD 164 | MI.LoadAddr(Addr, s) 165 | time.sleep(0.1) 166 | 167 | # Device select 168 | DMid = range(24) 169 | DMid_ = [] 170 | DMlist = np.zeros((1, 24)) 171 | DMlist[:, DMid] = 1 172 | DMlist[:, DMid_] = 0 173 | ind = np.arange(0, 24, 3) 174 | temp = np.array([1, 2, 4, 8, 16, 32, 64, 128]).reshape(-1, 1) 175 | S = np.dot(np.vstack([DMlist[:, ind], DMlist[:, ind+1], DMlist[:, ind+2]]), temp) 176 | 177 | # TRAINING PROCESURE 178 | MI.F_init(list(np.uint(S[:, 0])), s) 179 | time.sleep(0.1) 180 | NRMSE_train = 0 181 | if TestOnly != 1: 182 | Input, Target_train = DataProcess(X_train, Y_train) 183 | States_train, NRMSE_train = Train(Input, Target_train, Delay_s, Delay_m, Delay_w, TestOnly) 184 | 185 | # TESTING PROCESURE 186 | if TestOnly != 1: 187 | X_test = X_test[:200, :] 188 | Y_test = Y_test[:200, :] 189 | Input, Target_test = DataProcess(X_test, Y_test) 190 | Output, States_test, NRMSE_test = Test(Input, Target_test, Delay_s, Delay_m, Delay_w, TestOnly) 191 | OMAX = np.max(Output, axis=1).reshape((-1, 1)) 192 | Output = Output/OMAX 193 | 194 | # SAVE 195 | curr_time = datetime.now().strftime("%Y%m%d_%H%M") 196 | if SAVE == 1: 197 | if TestOnly == 1: 198 | Filename = 'data/ECGdata/ECG_test_'+curr_time+'.mat' 199 | io.savemat(Filename, {'Input_test': X_test, 'Target_test': Target_test, 'Output_test': Output}) 200 | else: 201 | Filename = 'data/ECGdata/ECG_train_'+curr_time+'.mat' 202 | io.savemat('ECGpara.mat', {'Mask': Mask, 'ML': ML, 'N': N, 'States_train': States_train, 203 | 'Target_train': Target_train, 'States_test': States_test, 'Target_test': Target_test}) 204 | io.savemat(Filename, {'States_train': States_train, 'Target_train': Target_train, 'Input_train': X_train, 205 | 'States_test': States_test, 'Target_test': Target_test, 'Input_test': X_test}) 206 | 207 | # ACC CACULATING 208 | ACC = np.zeros((60, 5)) 209 | TH_list = np.zeros(2) 210 | if TestOnly == 1: 211 | TH_box = np.arange(0.21, 0.8, 0.01) 212 | THS_box = np.arange(1, 6) 213 | j = 0 214 | for TH in TH_box: 215 | k = 0 216 | for THS in THS_box: 217 | Fout = np.heaviside(Output[0, :].reshape(-1, 50)-TH, 1) 218 | Fout = np.heaviside(np.sum(Fout, axis=1)-THS, 1) 219 | Ftar = np.max(Target_test[0, :].reshape(-1, 50), axis=1) 220 | Fbox = Fout-Ftar 221 | ACC[j, k] = len(Fbox[Fbox==0])/len(Fbox) 222 | k = k+1 223 | j = j+1 224 | index = np.unravel_index(ACC.argmax(), ACC.shape) 225 | index = list(index) 226 | TH_list[0] = TH_box[index[0]] 227 | TH_list[1] = THS_box[index[1]] 228 | io.savemat('ECG_THlist.mat', {'TH_list': TH_list}) 229 | print(np.max(ACC)) 230 | 231 | Input_list = list(X_test.reshape((1, -1, 1))[0, :, 0]) 232 | Target_list = list(Target_test[0, :]) 233 | Output_list = list(Output[0, :]) 234 | return Input_list, Target_list, Output_list, TH_list.tolist(), NRMSE_train, NRMSE_test, np.max(ACC) 235 | 236 | 237 | ################################################## 238 | # MAIN 239 | ################################################## 240 | if __name__ == '__main__': 241 | main(Av_out=50, Bias_out=160, Av_in=255, Bias_in=230, Delay_s=10, Delay_m=2, Delay_w=1, TestOnly=1, SAVE=0, FIX=0) 242 | -------------------------------------------------------------------------------- /Codes in NE2022/Upper computer program/ECGdataset.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tsinghua-LEMON-Lab/Reservoir-computing/ec5518d07b70af4d843c1c4925d20da93bfc67e8/Codes in NE2022/Upper computer program/ECGdataset.mat -------------------------------------------------------------------------------- /Codes in NE2022/Upper computer program/IO_test.py: -------------------------------------------------------------------------------- 1 | import Interface as MI 2 | import numpy as np 3 | import serial 4 | import time 5 | 6 | 7 | class strcture: 8 | pass 9 | 10 | 11 | OPMethod = strcture() 12 | s = serial.Serial('com6', 115200, timeout=15) 13 | 14 | 15 | def main(Av_out, Bias_out, Av_in, Bias_in, Delay_s, Delay_m, Delay_w): 16 | 17 | # Device select 18 | DMid = range(24) 19 | DMid_ = [] 20 | DMlist = np.zeros((1, 24)) 21 | DMlist[:, DMid] = 1 22 | DMlist[:, DMid_] = 0 23 | ind = np.arange(0, 24, 3) 24 | temp = np.array([1, 2, 4, 8, 16, 32, 64, 128]).reshape(-1, 1) 25 | S = np.dot(np.vstack([DMlist[:, ind], DMlist[:, ind+1], DMlist[:, ind+2]]), temp) 26 | 27 | # Input config 28 | cycle = 1 29 | inv = 1 30 | p = list(range(0, 255, inv))+ list(range(255, 0, -inv)) 31 | Input = np.uint8(np.array(cycle*p)) 32 | Input_ex = np.vstack((Input, Input, Input)).reshape((1, -1), order='F')[0, :] 33 | 34 | # Start test 35 | MI.A_init(0, s) 36 | time.sleep(0.1) 37 | MI.Am_adj(Av_in, s) 38 | time.sleep(0.1) 39 | MI.A_init(1, s) 40 | time.sleep(0.1) 41 | MI.Am_adj(Bias_in, s) 42 | time.sleep(0.1) 43 | MI.A_init(2, s) 44 | time.sleep(0.1) 45 | MI.Am_adj(Av_out, s) 46 | time.sleep(0.1) 47 | MI.A_init(3, s) 48 | time.sleep(0.1) 49 | MI.Am_adj(Bias_out, s) 50 | time.sleep(0.1) 51 | 52 | Mask = np.uint8(np.zeros(3)) 53 | MI.LoadMask(Mask, s) 54 | 55 | MI.D_init(list(np.uint(S[:, 0])), s) 56 | time.sleep(0.1) 57 | out = MI.DM_tb(MI.DMtest(OPMethod, Input_ex, MaskLength=1, Delay_s=Delay_s, Delay_m=Delay_m, Delay_w=Delay_w), s) 58 | out = np.array(list(out)) 59 | Vout = (3.3*out/255).reshape((24, -1), order='F') 60 | 61 | return Input.tolist(), Vout.tolist() 62 | 63 | if __name__ == '__main__': 64 | main(Av_out=10, Bias_out=160, Av_in=255, Bias_in=200, Delay_s=1, Delay_m=0, Delay_w=1) -------------------------------------------------------------------------------- /Codes in NE2022/Upper computer program/Interface.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import time 3 | 4 | 5 | def Reg_prog(RegData, ch, s): 6 | Tmode = [ord('I')] 7 | IN = [RegData] 8 | ReadFlag = [ch] 9 | m = 1 10 | STH = [m >> 8] 11 | STL = [m & 255] 12 | Z = [0] 13 | wstr = STH + STL + ReadFlag + Z + Z + Z + Z + Z + Z + Z + Z + Tmode + Z + IN 14 | s.write(bytes(wstr)) 15 | 16 | 17 | def D_init(DS, s): 18 | Reg_prog(2, 4, s) 19 | time.sleep(0.1) 20 | Reg_prog(DS[0], 0, s) 21 | time.sleep(0.1) 22 | Reg_prog(DS[1], 1, s) 23 | time.sleep(0.1) 24 | Reg_prog(DS[2], 2, s) 25 | 26 | 27 | def R_init(CS, Rmode, s): 28 | Reg_prog(16 | Rmode, 4, s) 29 | time.sleep(0.1) 30 | if CS[1] == 'A': 31 | Reg_prog(1 << int(CS[0])*2, 3, s) 32 | elif CS[1] == 'B': 33 | Reg_prog(2 << int(CS[0])*2, 3, s) 34 | elif CS[1] == 'C': 35 | Reg_prog(3 << int(CS[0])*2, 3, s) 36 | time.sleep(0.1) 37 | 38 | 39 | 40 | def F_init(DS, s): 41 | Reg_prog(35, 4, s) 42 | time.sleep(0.1) 43 | Reg_prog(255, 3, s) 44 | time.sleep(0.1) 45 | Reg_prog(DS[0], 0, s) 46 | time.sleep(0.1) 47 | Reg_prog(DS[1], 1, s) 48 | time.sleep(0.1) 49 | Reg_prog(DS[2], 2, s) 50 | 51 | 52 | def A_init(CS, s): 53 | Reg_prog(CS << 2, 4, s) 54 | 55 | 56 | def Am_adj(ResValue, s): 57 | Tmode = [ord('A')] 58 | IN = [ResValue] 59 | m = 1 60 | STH = [m >> 8] 61 | STL = [m & 255] 62 | Z = [0] 63 | wstr = STH + STL + Z + Z + Z + Z + Z + Z + Z + Z + Z + Tmode + Z + IN 64 | s.write(bytes(wstr)) 65 | 66 | 67 | def DM_tb(OPMethods, s): 68 | Tmode = [ord('D')] 69 | ReadFlag = [OPMethods.ReadFlag] 70 | DP = OPMethods.DP 71 | DR = OPMethods.DR 72 | WAIT = OPMethods.WAIT 73 | 74 | m = len(OPMethods.IN) 75 | STH = [m >> 8] 76 | STL = [m & 255] 77 | 78 | DPH = [DP >> 8] 79 | DPL = [DP & 255] 80 | 81 | DRH = [DR >> 8] 82 | DRL = [DR & 255] 83 | 84 | WAITH = [WAIT >> 8] 85 | WAITL = [WAIT & 255] 86 | 87 | IN = OPMethods.IN.tolist() 88 | wstr = STH + STL + ReadFlag + DPH + DPL + DRH + DRL + [0] + [0] + WAITH + WAITL + Tmode + [0] + IN 89 | s.write(bytes(wstr)) 90 | out = s.read(8*m*ReadFlag[0]) 91 | return out 92 | 93 | 94 | def DMtest(OPMethods, Input, MaskLength, Delay_s, Delay_m, Delay_w): 95 | OPMethods.DP = Delay_s 96 | OPMethods.DR = Delay_m 97 | OPMethods.WAIT = Delay_w 98 | OPMethods.IN = Input 99 | OPMethods.ReadFlag = MaskLength 100 | return OPMethods 101 | 102 | 103 | def LoadMask(Mask, s): 104 | Tmode = [ord('M')] 105 | m = len(Mask) 106 | STH = [m >> 8] 107 | STL = [m & 255] 108 | Z = [0] 109 | IN = Mask.tolist() 110 | wstr = STH + STL + Z + Z + Z + Z + Z + Z + Z + Z + Z + Tmode + Z + IN 111 | s.write(bytes(wstr)) 112 | 113 | 114 | def RRAM_tb(OPMethods, s): 115 | Tmode = [ord('R')] 116 | IsRead = OPMethods.IsRead 117 | WL_Addr = OPMethods.WL_Addr 118 | BL_Addr = OPMethods.BL_Addr 119 | IsForm = OPMethods.IsForm 120 | WLref = OPMethods.WLref 121 | BLref = OPMethods.BLref 122 | SL_Mode = OPMethods.SLmode 123 | WAIT = OPMethods.SRDelay 124 | RTW = OPMethods.FormDelay 125 | 126 | ReadFlag = [IsRead*128 | IsForm*64 | BL_Addr] 127 | 128 | STH = [1 >> 8] 129 | STL = [1 & 255] 130 | 131 | DPH = [WL_Addr] 132 | DPL = [WLref] 133 | 134 | DRH = [BLref] 135 | DRL = [SL_Mode & 3] 136 | 137 | RTWH = [RTW >> 8] 138 | RTWL = [RTW & 255] 139 | 140 | WAITH = [WAIT >> 8] 141 | WAITL = [WAIT & 255] 142 | 143 | wstr = STH + STL + ReadFlag + DPH + DPL + DRH + DRL + RTWH + RTWL + WAITH + WAITL + Tmode + [0] + [0] 144 | s.write(bytes(wstr)) 145 | if IsRead: 146 | out = s.read(1) 147 | else: 148 | out = 0 149 | return out 150 | 151 | 152 | def Read(OPMethods, Vwl, Vbl, wl_addr, bl_addr): 153 | OPMethods.IsRead = True 154 | OPMethods.IsForm = False 155 | OPMethods.WL_Addr = wl_addr 156 | OPMethods.BL_Addr = bl_addr 157 | OPMethods.WLref = int(255*Vwl/5) 158 | OPMethods.BLref = int(255*Vbl/0.5) 159 | OPMethods.SLmode = 3 160 | OPMethods.SRDelay = 50 161 | OPMethods.FormDelay = 500 162 | return OPMethods 163 | 164 | 165 | def Set(OPMethods, Vwl, Vbl, wl_addr, bl_addr): 166 | OPMethods.IsRead = False 167 | OPMethods.IsForm = False 168 | OPMethods.WL_Addr = wl_addr 169 | OPMethods.BL_Addr = bl_addr 170 | OPMethods.WLref = int(255*Vwl/5) 171 | OPMethods.BLref = int(255*Vbl/5) 172 | OPMethods.SLmode = 0 173 | OPMethods.SRDelay = 50 174 | OPMethods.FormDelay = 500 175 | return OPMethods 176 | 177 | 178 | def Reset(OPMethods, Vwl, Vsl, wl_addr, bl_addr): 179 | OPMethods.Rmode = 0 180 | OPMethods.IsRead = False 181 | OPMethods.IsForm = False 182 | OPMethods.WL_Addr = wl_addr 183 | OPMethods.BL_Addr = bl_addr 184 | OPMethods.WLref = int(255*Vwl/5) 185 | OPMethods.BLref = int(255*Vsl/5) 186 | OPMethods.SLmode = 1 187 | OPMethods.SRDelay = 50 188 | OPMethods.FormDelay = 500 189 | return OPMethods 190 | 191 | 192 | def Mapping(OPMethods, Weight, Vr, wl_addr, bl_addr, s): 193 | S = 12 194 | L = np.array([[Weight-S/2, 0], [Weight+S/2, 0]]) 195 | i = 0 196 | sm = -1 197 | rm = -1 198 | Scnt = 0 199 | Rcnt = 0 200 | while i < 100: 201 | out = RRAM_tb(Read(OPMethods, 5, Vr, wl_addr, bl_addr), s) 202 | out = np.array(list(out)) 203 | n = np.vstack([np.array([[out[0], 1]]), L]) 204 | n = n[n[:, 0].argsort()] 205 | ind = np.dot(np.array([[1, 2, 3]]), n[:, [1]]) 206 | if ind == 1: 207 | if (i-sm) == 1: 208 | Scnt = Scnt+1 209 | else: 210 | Scnt = 1 211 | Svolt = np.minimum(0.5+(Scnt-1)*0.1, 2.8) 212 | RRAM_tb(Set(OPMethods, Svolt, 5, wl_addr, bl_addr), s) 213 | sm = i 214 | elif ind == 2: 215 | state = 1 216 | print('wl_addr:' + str(wl_addr) + ',bl_addr:' + str(bl_addr) + ',Successful') 217 | break 218 | elif ind == 3: 219 | if (i-rm) == 1: 220 | Rcnt = Rcnt+1 221 | else: 222 | Rcnt = 1 223 | Rvolt = np.minimum(1.5+(Rcnt-1)*0.1, 3) 224 | RRAM_tb(Reset(OPMethods, 5, Rvolt, wl_addr, bl_addr), s) 225 | rm = i 226 | i = i+1 227 | 228 | if ind != 2: 229 | state = 0 230 | print('wl_addr:' + str(wl_addr) + ',bl_addr:' + str(bl_addr) + ',Failed') 231 | return out, state 232 | 233 | 234 | def LoadAddr(Addr, s): 235 | Tmode = [ord('W')] 236 | m = len(Addr) 237 | STH = [m >> 8] 238 | STL = [m & 255] 239 | Z = [0] 240 | IN = Addr.tolist() 241 | wstr = STH + STL + Z + Z + Z + Z + Z + Z + Z + Z + Z + Tmode + Z + IN 242 | s.write(bytes(wstr)) 243 | 244 | 245 | def DMRC_tb(OPMethods, s): 246 | Tmode = [ord('F')] 247 | ReadFlag = [OPMethods.ReadFlag] 248 | DP = OPMethods.DP 249 | DR = OPMethods.DR 250 | WAIT = OPMethods.WAIT 251 | Rmode = [OPMethods.Rmode] 252 | 253 | m = len(OPMethods.IN) 254 | STH = [m >> 8] 255 | STL = [m & 255] 256 | 257 | DPH = [DP >> 8] 258 | DPL = [DP & 255] 259 | 260 | DRH = [DR >> 8] 261 | DRL = [DR & 255] 262 | 263 | WAITH = [WAIT >> 8] 264 | WAITL = [WAIT & 255] 265 | 266 | IN = OPMethods.IN.tolist() 267 | wstr = STH + STL + ReadFlag + DPH + DPL + DRH + DRL + [0] + [0] + WAITH + WAITL + Tmode + Rmode + IN 268 | s.write(bytes(wstr)) 269 | if Rmode[0]==1: 270 | out = s.read(int(4*m/3)) 271 | else: 272 | out = s.read(8*m*ReadFlag[0]+int(4*m/3)) 273 | return out 274 | 275 | 276 | def DMRCtest(OPMethods, Input, MaskLength, Delay_s, Delay_m, Delay_w, TestOnly): 277 | OPMethods.DP = Delay_s 278 | OPMethods.DR = Delay_m 279 | OPMethods.WAIT = Delay_w 280 | OPMethods.IN = Input 281 | OPMethods.ReadFlag = MaskLength 282 | OPMethods.Rmode = TestOnly 283 | return OPMethods 284 | -------------------------------------------------------------------------------- /Codes in NE2022/Upper computer program/Mylayers.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | 4 | 5 | class RRAMsim(torch.nn.Module): 6 | 7 | def __init__(self, in_features, out_features, bias=True): 8 | super(RRAMsim, self).__init__() 9 | self.in_features = in_features 10 | self.out_features = out_features 11 | self.weight = torch.nn.Parameter(torch.randn(in_features, out_features)) 12 | self.Av = torch.nn.Parameter(0.1*torch.ones(out_features)) 13 | if bias: 14 | self.isbias = True 15 | self.bias = torch.nn.Parameter(torch.zeros(out_features)) 16 | else: 17 | self.isbias = False 18 | 19 | def forward(self, input): 20 | self.weight_ = F.hardtanh(self.weight+0.04*(2*torch.rand(self.in_features, self.out_features)-1), min_val=-1, max_val=1) 21 | if self.isbias: 22 | y = self.Av*torch.matmul(input, self.weight_) + self.bias 23 | else: 24 | y = self.Av*torch.matmul(input, self.weight_) 25 | return y 26 | -------------------------------------------------------------------------------- /Codes in NE2022/Upper computer program/NoiseAwareTrain.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import io 3 | import torch 4 | import torch.optim as optim 5 | import torch.nn as nn 6 | import Mylayers as myl 7 | 8 | 9 | ################################################## 10 | # NETWORK MODEL 11 | ################################################## 12 | class NNClassifier(nn.Module): 13 | def __init__(self, input_size, output_size): 14 | super(NNClassifier, self).__init__() 15 | self.out = myl.RRAMsim(input_size, output_size, bias=False) 16 | 17 | def forward(self, x): 18 | y = self.out(x) 19 | return y 20 | 21 | 22 | ################################################## 23 | # SYSTEM RUN 24 | ################################################## 25 | def Train_LR(States, Target): 26 | Wout = Target.dot(States.T).dot(np.linalg.pinv(np.dot(States, States.T))) 27 | Output = np.dot(Wout, States) 28 | NRMSE = np.mean(np.sqrt(np.mean((Output-Target)**2, axis=1)/np.var(Target, axis=1))) 29 | print('Train_error: ' + str(NRMSE)) 30 | return Wout, NRMSE 31 | 32 | 33 | def Train_GD(States, Target, N_EPOCHS, LEARNING_RATE): 34 | Input = torch.from_numpy(np.float32(States.T)) 35 | model = NNClassifier(input_size=len(Input[0, :]), output_size=len(Target[:, 0])) 36 | optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE) 37 | loss_func = nn.MSELoss() 38 | 39 | train_error_ = [] 40 | for epoch in range(N_EPOCHS): 41 | Output = model(Input) 42 | loss = loss_func(Output, torch.from_numpy(np.float32(Target.T))) 43 | optimizer.zero_grad() 44 | loss.backward() 45 | optimizer.step() 46 | 47 | Out = Output.data.numpy().T 48 | NRMSE = np.mean(np.sqrt(np.mean((Out-Target)**2, axis=1)/np.var(Target, axis=1))) 49 | train_error_.append(NRMSE) 50 | 51 | print('[Epoch: %3d/%3d] Training Error: %.3f' 52 | % (epoch+1, N_EPOCHS, train_error_[epoch])) 53 | 54 | Wout = (model.out.Av*model.out.weight_).detach().numpy().T 55 | Av = np.array([model.out.Av.detach().numpy()]).T 56 | return Wout, Av 57 | 58 | 59 | def Test(Wout, States, Target): 60 | Output = np.dot(Wout, States) 61 | NRMSE = np.mean(np.sqrt(np.mean((Output-Target)**2, axis=1)/np.var(Target, axis=1))) 62 | print('Test_error: ' + str(NRMSE)) 63 | return Output, States, NRMSE 64 | 65 | 66 | def main(TASKNAME, GOAL, SAVE, TrainMethod): 67 | # TRAINING PROCESURE 68 | States = io.loadmat(TASKNAME+'para.mat')['States_train'] 69 | States = States.reshape((-1, len(States[0, 0, :]))).T 70 | States = States + 25*(np.random.rand(len(States[:, 0]), len(States[0, :]))-0.5)*2 71 | Target = io.loadmat(TASKNAME+'para.mat')['Target_train'] 72 | if TASKNAME == 'DGR': 73 | Target_list = [] 74 | for i in range(1, 5): 75 | Target_ = Target/i 76 | Target_[Target_[:, 15] != 1, :] = 0 77 | Target_ = Target_.reshape((1, -1)) 78 | Target_list.append(Target_[0, :]) 79 | Target = np.array(Target_list) 80 | if TrainMethod == 'LR': 81 | Wout, NRMSE_train = Train_LR(States, Target) 82 | Av = np.max(np.abs(Wout), axis=1).reshape((-1, 1)) 83 | elif TrainMethod == 'GD': 84 | Wout, Av = Train_GD(States, Target, 80000, 0.001) 85 | 86 | # TESTING PROCESURE 87 | States = io.loadmat(TASKNAME+'para.mat')['States_test'] 88 | Target = io.loadmat(TASKNAME+'para.mat')['Target_test'] 89 | Wout_ = Av*np.clip(Wout/Av + 0.04*(2*np.random.rand(len(Wout[:, 0]), len(Wout[0, :]))-1), -1, 1) 90 | Output, States, NRMSE_test = Test(Wout_, States, Target) 91 | 92 | # SAVE 93 | if SAVE == 1: 94 | io.savemat(TASKNAME+'_NATpara.mat', {'Wout': Wout, 'Av': Av, 'States': States, 'Target': Target}) 95 | 96 | Target_list = list(Target[GOAL-1, :]) 97 | Output_list = list(Output[GOAL-1, :]) 98 | return Target_list, Output_list, NRMSE_train, NRMSE_test 99 | 100 | 101 | ################################################## 102 | # MAIN 103 | ################################################## 104 | if __name__ == '__main__': 105 | main(TASKNAME='DGR', GOAL=3, SAVE=0, TrainMethod='LR') 106 | -------------------------------------------------------------------------------- /Codes in NE2022/Upper computer program/RRAM_prog.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import Interface as MI 3 | import numpy as np 4 | import serial 5 | import time 6 | from scipy import io 7 | from datetime import datetime 8 | 9 | 10 | ################################################## 11 | # GLOBAL VARIABLES 12 | ################################################## 13 | Vr = 0.2 14 | 15 | 16 | ################################################## 17 | # OBJECTS 18 | ################################################## 19 | class strcture: 20 | pass 21 | 22 | 23 | OPMethod = strcture() 24 | s = serial.Serial('com6', 115200, timeout=3) 25 | 26 | 27 | ################################################## 28 | # MAPPING 29 | ################################################## 30 | def WeightMapping(w, addr): 31 | out = np.zeros((len(w), 3)) 32 | for i in range(len(w)): 33 | wl_addr = int(addr[i, 0]) 34 | bl_addr = int(addr[i, 1]) 35 | _, state = MI.Mapping(OPMethod, w[i], Vr, wl_addr, bl_addr, s) 36 | out[i, :] = np.array([wl_addr, bl_addr, state], dtype=np.float32) 37 | return out 38 | 39 | 40 | ################################################## 41 | # READ 42 | ################################################## 43 | def WeightRead(addr): 44 | out = np.zeros((len(addr[:, 0]), 3)) 45 | for i in range(len(addr[:, 0])): 46 | wl_addr = int(addr[i, 0]) 47 | bl_addr = int(addr[i, 1]) 48 | weight = np.array(list(MI.RRAM_tb(MI.Read(OPMethod, 5, Vr, wl_addr, bl_addr), s))) 49 | out[i, :] = np.array([wl_addr, bl_addr, weight], dtype=np.float32) 50 | print('wl_addr:' + str(wl_addr) + ',bl_addr:' + str(bl_addr)) 51 | return out 52 | 53 | 54 | ################################################## 55 | # MAIN 56 | ################################################## 57 | def main(TASKNAME, CS, isMapping, ForceZero, Save): 58 | 59 | # GAIN ADJUST 60 | MI.A_init(2, s) 61 | time.sleep(0.1) 62 | MI.Am_adj(50, s) 63 | time.sleep(0.1) 64 | MI.A_init(3, s) 65 | time.sleep(0.1) 66 | MI.Am_adj(145, s) 67 | time.sleep(0.1) 68 | 69 | BF = 3 70 | ER = 10 71 | MX = 250 72 | if isMapping==1: 73 | # WEIGHT MAPPING 74 | if ForceZero==1: 75 | Av_out = 200 76 | MI.A_init(2, s) 77 | time.sleep(0.1) 78 | MI.Am_adj(Av_out, s) 79 | time.sleep(0.1) 80 | MI.R_init(CS=CS, Rmode=0, s=s) 81 | time.sleep(0.1) 82 | 83 | usenewaddr = False 84 | bplen = 1 85 | ind = [] 86 | newaddr = [] 87 | while usenewaddr|(bplen!=0): 88 | Wout = io.loadmat(TASKNAME+'_NATpara.mat')['Wout'][int(CS[0]), :] 89 | A = io.loadmat(TASKNAME+'_NATpara.mat')['Av'][int(CS[0]), :] 90 | W = np.round(np.clip(MX*(Wout/np.abs(A)), -255, 255)) 91 | if CS[1] == 'A': 92 | W[W < 0] = 0 93 | sign = 1 94 | elif CS[1] == 'B': 95 | W[W > 0] = 0 96 | sign = -1 97 | addr = np.zeros((len(W), 2)) 98 | for i in range(len(W)): 99 | for j in range(BF): 100 | addr[i, 0] = int(np.floor((BF*i+j)/8)) 101 | addr[i, 1] = (BF*i+j) % 8 102 | break 103 | if ForceZero==1: 104 | TP = np.arange(len(W))[W == 0] 105 | addr = addr[TP, :] 106 | W = W[TP] 107 | if usenewaddr&(bplen==0): 108 | usenewaddr = False 109 | if usenewaddr: 110 | W = W[ind] 111 | addr = newaddr 112 | state = WeightMapping(np.abs(W), addr) 113 | out = WeightRead(addr) 114 | W_ = sign*out[:, 2] 115 | newaddr = out[np.abs(W-W_)>ER, :2] 116 | bplen = len(newaddr[:, 0]) 117 | print(bplen) 118 | 119 | ind = np.arange(len(W))[np.abs(W-W_)>ER] 120 | if bool(1-usenewaddr)&(bplen!=0): 121 | usenewaddr = True 122 | 123 | # READ 124 | MI.R_init(CS=CS, Rmode=0, s=s) 125 | time.sleep(0.1) 126 | 127 | Wout = io.loadmat(TASKNAME+'_NATpara.mat')['Wout'][int(CS[0]), :] 128 | A = io.loadmat(TASKNAME+'_NATpara.mat')['Av'][int(CS[0]), :] 129 | W = np.round(MX*(Wout/np.abs(A))) 130 | if CS[1] == 'A': 131 | W[W < 0] = 0 132 | sign = 1 133 | elif CS[1] == 'B': 134 | W[W > 0] = 0 135 | sign = -1 136 | else: 137 | sign = 1 138 | addr = np.zeros((len(W), 2)) 139 | for i in range(len(W)): 140 | for j in range(BF): 141 | addr[i, 0] = int(np.floor((BF*i+j)/8)) 142 | addr[i, 1] = (BF*i+j) % 8 143 | break 144 | if ForceZero==1: 145 | TP = np.arange(len(W))[W == 0] 146 | addr = addr[TP, :] 147 | W = W[TP] 148 | out = WeightRead(addr) 149 | W_ = sign*out[:, 2] 150 | 151 | # SAVE 152 | if ForceZero!=1: 153 | Addr = out[:, :2] 154 | name = ['wl_addr', 'bl_addr'] 155 | data = pd.DataFrame(columns=name, data=list(Addr)) 156 | data.to_csv('Addr.csv', index=False) 157 | if Save==1: 158 | curr_time = datetime.now().strftime("%Y%m%d_%H%M") 159 | if CS[1]=='A': 160 | wstr = '_PosW'+CS[0]+'_' 161 | else: 162 | wstr = '_NegW'+CS[0]+'_' 163 | Filename = 'data/'+TASKNAME+'data/'+TASKNAME+wstr+curr_time+'.mat' 164 | io.savemat(Filename, {'W': W, 'W_': W_}) 165 | return W.tolist(), W_.tolist() 166 | 167 | if __name__ == '__main__': 168 | main(TASKNAME='HAR', CS='0A', isMapping=1, ForceZero=0, Save=0) 169 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Reservoir-computing codes used in published works 2 | --------------------------------------------------------------------------------