-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDuffing_base_script.py
More file actions
executable file
·2200 lines (1968 loc) · 93.9 KB
/
Duffing_base_script.py
File metadata and controls
executable file
·2200 lines (1968 loc) · 93.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##!pip install pysindy
# Van der Pol RN with Fext
# Importar bibliotecas necesarias
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
#import pysindy as ps
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from scipy.integrate import solve_ivp
import pysindy as ps
print(ps.__version__)
from pysindy.feature_library import PolynomialLibrary
from pysindy.feature_library import CustomLibrary
from pysindy.feature_library import ParameterizedLibrary
from pysindy.feature_library import IdentityLibrary
from pysindy.optimizers import ConstrainedSR3
from pysindy import AxesArray
from pysindy.optimizers import STLSQ
from pysindy import SINDy
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from numpy.polynomial.legendre import legvander
from scipy.signal import savgol_filter
from scipy.special import comb # For binomial coefficients
import os
import copy
import time
#from google.colab import drive
#drive.mount('/content/drive')
#output_path = "/content/drive/My Drive/Colab Notebooks/Second_order_noise/Python"
#output_path = "/content/drive/Shared with me/Federico2024_System_Identification/Python"
output_path = "./"
output_file_log = open("output_log.txt", "w")
from pysr import PySRRegressor
import sympy as sp
# Check for GPU availability
if torch.cuda.is_available():
print("GPU is available, using GPU")
else:
print("GPU is not available, using CPU.")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Free GPU memory if using CUDA
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
# Initialization of random number generators for reproducibility
np.random.seed(0)
torch.manual_seed(10) # any integer
time_chaos_x_SR_list=[]
time_chaos_x_parametric_list=[]
time_chaos_x_NN_list =[]
time_chaos_x_NN_nosym_list =[]
time_chaos_x_NN_SR_list =[]
time_chaos_x_Sindy_list =[]
time_chaos_x_LS_list =[]
time_chaos_x_Sindy_ku0_list=[]
rmse_x_SR_list = []
rmse_x_dot_SR_list = []
rmse_x_parametric_list = []
rmse_x_dot_parametric_list = []
rmse_x_NN_list = []
rmse_x_dot_NN_list = []
rmse_x_NN_nosym_list = []
rmse_x_dot_NN_nosym_list = []
rmse_x_NN_SR_list = []
rmse_x_dot_NN_SR_list = []
rmse_x_Sindy_list = []
rmse_x_dot_Sindy_list = []
rmse_x_LS_list = []
rmse_x_dot_LS_list = []
rmse_x_Sindy_k0_list = []
rmse_x_dot_Sindy_k0_list = []
print("ODE: x'' + f1(x') + f2(x) = F_ext(t)")
print("Duffing System")
print("f1(x')= delta x'")
print("f2(x)= alpha x + beta x^3")
print("F_ext(t)=Aext cos(Omega t)")
#parameters stick slip
#m=1.0 # kg
#cval=0.1 # Ns/m (viscous damping coefficient)
#kval=1.0 # N/m (stiffness)
#Aext=2 # N (forcing amplitude)
#Omega=0.3 # 0.3 and 0.15 rad/s (forcing frequency)
#x0=0.1 # m (initial displacement)
#v0=0.1 # m/s (initial velocity)
#mu_N = 0.5 #0.5
#m=1.0
#parameters duffing
#Aext=0.5
#alpha=-1.0
#beta=1.0
#delta=0.3
#Omega=1.2
#x0=0.5
#v0=-0.5
#y0 = [x0, v0] # [x(0), x'(0)]
Tsimul=40 # for generating the training database
Nsimul=1000
Tval=2*Tsimul # for forward simulations with trained models
Nval=2*Nsimul
NevalCC=1000 # number of evaluating points for the CCs from min to max values
t_span = (0, Tsimul) # time interval for training dataset
t_simul = np.linspace(*t_span, Nsimul)
t_span_val = (0, Tval) # time interval for forward simulation
t_val = np.linspace(*t_span_val, Nval)
# parameters for evaluating CCs for extrapolation
n_window = 50 # number of points to calculate the envelope around each edge
range_interp = 0.2 # percentage of values near edges for obtaining the envelope
range_extrap = 0.5 # percentage of extrapolated range with respect to total range
n_extra = 50 # number of new data points for each direction
deg_extrap = 1 # degree of polynomial extrapolation
# Hyperparameters for NN-CC methods
learning_rate = 1e-4
epochs_max = 1000
neurons=100
error_threshold = 1e-8
f1_symmetry='odd'
f2_symmetry='odd'
lambda_penalty = 1e-4 # You can adjust this weight if needed
lambda_penalty_symm = 1e1
apply_restriction=False #True
N_constraint = 1000 # number of points for evaluating symmetry constraints
#for testing other activation functions
#weight_decay = 1e-6 # 0.0 # 1e-6 was the better, 0.0 default
#momentum=0.99
#SNR_dB_list = [np.inf] + list(np.linspace(40, -20, 61 )) # ∞, 20, 17.5, ..., -5
SNR_dB_list = [np.inf] + list(np.linspace(40, 5, 36 )) # ∞, 20, 17.5, ..., -5
#SNR_dB_list = list(np.linspace(-18, -20, 3 )) # ∞, 20, 17.5, ..., -5
SNR_dB_list = list(np.linspace(5, -20, 26 )) # ∞, 20, 17.5, ..., -5
SNR_dB_list = [20.0]
#repeat 3 times each value in the list
SNR_dB_list = np.repeat(SNR_dB_list, 1)
#SNR_dB_list = np.repeat(SNR_dB_list,B_list = list(np.linspace(5, -5, 3)) # ∞, 20, 17.5, ..., -5
for SNR_dB in SNR_dB_list:
Aext=0.5
alpha=-1.0
beta=1.0
delta=0.3
Omega=1.2
x0=0.5
v0=-0.5
y0 = [x0, v0] # [x(0), x'(0)]
print(f"SNR_dB={SNR_dB}")
print(f"alpha={alpha}, beta={beta}, delta={delta}")
print(f"Omega={Omega}, Aext={Aext}, x₀={x0}, v₀={v0}")
#Definition of the theoretical functions
def F1(x_dot):
return delta * x_dot
def F2(x):
return alpha*x+beta*x**3
def F_ext(t):
return Aext*np.cos(Omega*t)
def eq_2nd_ord_veloc(t,y):
x, x_dot = y # y=[x, x']
x_ddot = (F_ext(t) - F1(x_dot) - F2(x))*1.0
return [x_dot, x_ddot]
# ODE: x'' + F1(x_dot) + F2(x) = F_ext(t)
# ODE: x'' + delta x_dot + alpha x + beta x^3 = F_ext(t)
# F_ext(t) = Aext cos(Omega t)
#Integrate forward the theoretical equation to generate training dataset
sol = solve_ivp(eq_2nd_ord_veloc, t_span, y0, t_eval=t_simul,method='LSODA')
# other integration methods:
#, method='BDF', rtol=1e-6, atol=1e-8, dense_output=True)
#, method='DOP853', rtol=1e-9, atol=1e-12)
#, method='Radau', rtol=1e-6, atol=1e-8
#verify that integration was succesful
print(sol.status) # 0 = success, 1 = reached event, -1 = failed
print(sol.message)
# extract variables
x_data = sol.y[0]
x_dot_data = sol.y[1]
time_data = sol.t
x_ddot_data = np.array([eq_2nd_ord_veloc(t, y)[1] for t, y in zip(sol.t, sol.y.T)])
F1_th=F1(x_dot_data)
F2_th=F2(x_data)
# linear range of data to plot identified CCs
x_vals = np.linspace(np.min(x_data), np.max(x_data), NevalCC)
xdot_vals = np.linspace(np.min(x_dot_data), np.max(x_dot_data), NevalCC)
# plot theoretical integrations
plt.figure()
plt.title("Theoretical ODE integration: Consistency Check")
plt.plot(time_data, (x_ddot_data + F1_th + F2_th - F_ext(time_data))**2)
plt.xlabel("t")
plt.ylabel(r"MSE $(\ddot{x} + F_1(\dot{x}) + F_2(x) - F_{ext})^2$")#$(\ddot{x} - \ddot{x}_{model})^2$")
plt.grid(True, alpha=0.3)
plt.show()
#plt.plot(time_data, x_data)
#plt.xlabel("Time")
#plt.ylabel("x(t)")
#plt.title("Theoretical data")
#plt.grid(True)
#plt.show()
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 5), sharex=True)
ax1.plot(time_data, x_data, color='black')
ax1.set_ylabel("x(t)")
ax1.set_title("Theoretical Data (without noise)")
ax1.grid(True)
ax2.plot(time_data, F_ext(time_data), color='black', linestyle='-')
ax2.set_xlabel("t")
ax2.set_ylabel(r"F$_{ext}(t)$")
ax2.grid(True)
plt.tight_layout()
plt.show()
# Add noise to F_ext with a given SNR (in dB)
if np.isinf(SNR_dB):
print("Running with SNR = ∞ dB (no noise)")
#print("noise=",noise)
F_ext_noise_data = F_ext(time_data)
noise_percentage=0.0
noise_percentage_th=0.0
else:
print(f"Running with SNR = {SNR_dB:.2f} dB")
# Add noise based on a predefined SNR_dB
Fext_signal_power = np.mean(F_ext(time_data)**2)
noise_power = Fext_signal_power / (10**(SNR_dB / 10))
noise_std = np.sqrt(noise_power)
#add noise
F_ext_val_noisy = F_ext(time_data) + np.random.normal(0, noise_std, size=time_data.shape)
#compute measured noise
Fext_noise_substraction = F_ext_val_noisy - F_ext(time_data)
signal_power = np.mean(F_ext(time_data)**2)
noise_power = np.mean(Fext_noise_substraction**2)
snr_measured = 10 * np.log10(signal_power / noise_power)
# Compute noise percentage relative to RMS signal
signal_rms = np.sqrt(signal_power)
noise_rms= np.sqrt(noise_power)
noise_percentage_th=100*10**(-SNR_dB / 20.0)
noise_percentage = 100 * (noise_rms / signal_rms)
print(f"Desired SNR in Fext: {SNR_dB} dB")
print(f"Measured SNR in Fext: {snr_measured:.2f} dB")
print(f"Desired noise percentage in Fext: {noise_percentage_th:.2f}%")
print(f"Measured noise percentage in Fext: {noise_percentage:.2f}%")
# --- now apply a Savitzky–Golay filter (not used, only for testing) ---
# choose an odd window length and a small polynomial order
window_length = 51 # must be odd, e.g. 5, 11, 51, …
polyorder = 3 # < window_length
F_ext_filtered = savgol_filter(
F_ext_val_noisy,
window_length=window_length,
polyorder=polyorder,
mode='interp' # avoids edge artifacts
)
# measure the SNR *after* filtering (optional)
noise_after = F_ext_filtered - F_ext(time_data)
snr_after = 10 * np.log10(
np.mean(F_ext(time_data)**2) / np.mean(noise_after**2)
)
print(f"SNR after SG filter: {snr_after:.1f} dB")
plt.figure(figsize=(6, 4))
plt.plot(time_data, F_ext(time_data), label='Fext (true)')
plt.plot(time_data, F_ext_val_noisy, label='Fext + noise', alpha=0.7)
plt.plot(time_data, F_ext_filtered, label='SG-filtered', linewidth=2)
plt.xlabel('Time')
plt.ylabel(r'F$_{ext}$(t)')
plt.title('Original vs Noisy vs SG-Filtered Forcing')
plt.legend()
plt.tight_layout()
plt.show()
# Here we can select different options for the noisy Fext
#F_ext_noise_data = F_ext(time_data)
#F_ext_noise_data = F_ext_filtered
F_ext_noise_data = F_ext_val_noisy
# plot Training dataset
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 5), sharex=True)
ax1.plot(time_data, x_data, color='black')
ax1.set_ylabel("x(t)")
ax1.set_title("Theoretical Data (with noise) : Training dataset")
ax1.grid(True)
ax2.plot(time_data, F_ext_noise_data, color='black', linestyle='-')
ax2.set_xlabel("t")
ax2.set_ylabel(r"F$_{ext}$(t)")
ax2.grid(True)
plt.tight_layout()
plt.show()
# plot
plt.figure()
plt.title(r"MSE of F$_{ext}$ with and without noise")
plt.plot(time_data, (F_ext(time_data) - F_ext_noise_data )**2)
plt.xlabel("t")
plt.ylabel(r"Squared Error (F$_{ext}^{noiseless}$ - F$_{ext}^{noise}$)$^2$")
plt.grid(True, alpha=0.3)
plt.show()
# range of training data values
print("min(x) , max(x)=", np.min(x_data),",",np.max(x_data))
print(f"min(ẋ) , max(ẋ)= {np.min(x_dot_data)} , {np.max(x_dot_data)}")
############################################
########### IDENTIFICATION #################
############################################
####################################################
############# Parametric-CC ################# least squares
# Right-hand side
rhs = F_ext_noise_data - x_ddot_data
# Design matrix: [x_dot, x, x^3]
A = np.vstack([
x_dot_data,
x_data,
x_data**3
]).T # shape: (N, 3)
# Solve least squares: A x [delta, alpha, beta] = rhs
start = time.time()
params, _, _, _ = np.linalg.lstsq(A, rhs, rcond=None)
delta_ident_param, alpha_ident_param, beta_ident_param = params
print("Parametric-CC model")
end = time.time()
elapsed = end - start
print(f"Training finished in {elapsed:.3f} seconds")
print("Theoretical params:")
print(f"delta = {delta:.6e}, alpha = {alpha:.6e}, beta = {beta:.6e}")
print(" ")
print("Identified params from Parametric-CC:")
print(f"delta = {delta_ident_param:.6e}, alpha = {alpha_ident_param:.6e}, beta = {beta_ident_param:.6e}")
#defining the Parametric-CC functions for forward simulations
def ode_param(t, state):
x, xdot = state
xddot = (F_ext(t) - delta_ident_param*xdot - alpha_ident_param*x - beta_ident_param*x**3) # / m
return [xdot, xddot]
def f1_param(x_dot):
return delta_ident_param * x_dot
def f2_param(x):
return alpha_ident_param * x + beta_ident_param * x**3
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(5, 8))
ax1.plot(xdot_vals, f1_param(xdot_vals), label="Identified", linewidth=2)
ax1.plot(xdot_vals, F1(xdot_vals), '--',color='black', label="Theor.", linewidth=2)
ax1.set_title("Obtained CCs from Parametric-CC method")
ax1.set_xlabel(r"$\dot{x}$")
ax1.set_ylabel(r"f$_1(\dot{x})$")
ax1.legend()
ax1.grid(True, alpha=0.3)
ax2.plot(x_vals, f2_param(x_vals), label="Identified", linewidth=2)
ax2.plot(x_vals, F2(x_vals), '--',color='black', label="Theor.", linewidth=3)
ax2.set_ylabel(r"f$_2$(x)")
ax2.set_xlabel("x")
ax2.legend()
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# Integrate forward the obtained Parametric-CC model for verification
# (using the same ICs and driven force as the training data)
sol = solve_ivp(ode_param, t_span, y0, t_eval=t_simul,method='LSODA')
x_sim = sol.y[0]
xdot_sim = sol.y[1]
plt.figure(figsize=(8,5))
plt.plot(time_data, x_sim, label="Parametric-CC", linewidth=2)
plt.plot(time_data, x_data, "--", color='black', label="Training data", linewidth=2)
plt.xlabel("t")
plt.ylabel("x(t)")
plt.legend()
plt.title("Simulation with Parametric-CC model")
plt.show()
####################################################
############# Poly-CC ################# least squares
# This method uses the Polynomial expansions for f1 and f2
# but normalizing the data ranges to [-1,1] interval,
# according to the approach discussed in Refs.
# Gonzalez, F.J. Nonlinear Dyn 112, 16167–16197 (2024).
# Gonzalez, F.J., Lara, L.P. Nonlinear Dyn 113, 33063–33086 (2025).
N_order=10
min_x = np.min(np.abs(x_data))
max_x = np.max(np.abs(x_data))
min_xd = np.min(np.abs(x_dot_data))
max_xd = np.max(np.abs(x_dot_data))
A0_x=(max_x+min_x)/2.0
A1_x=(max_x-min_x)/2.0
A0_xd=(max_xd+min_xd)/2.0
A1_xd=(max_xd-min_xd)/2.0
X_poly = np.vstack([((x_data-A0_x)/A1_x)**i for i in range(N_order + 1)]).T
X_dot_poly = np.vstack([((x_dot_data-A0_xd)/A1_xd)**i for i in range(N_order + 1)]).T # [N x (N_order+1)]
# Combine both: A @ coeffs = b
Amat = np.hstack([-X_dot_poly, -X_poly]) # Minus signs because x'' = F_ext - f1 - f2
bmat = x_ddot_data - F_ext_noise_data #F_ext(t_simul) # Leftover = f1(x') + f2(x)
# ---- Least squares fit ---- #
start=time.time()
coeffs, _, _, _ = np.linalg.lstsq(Amat, bmat, rcond=None)
end = time.time()
elapsed = end - start
print('End Training Poly-CC')
print(f"Training finished in {elapsed:.3f} seconds")
# Separate coefficients
c_f1 = coeffs[:N_order+1]
c_f2 = coeffs[N_order+1:]
print(f"Coefficients of f1(x') (order {N_order}): {c_f1}")
print(f"Coefficients of f2(x) (order {N_order}): {c_f2}")
# Print coefficients for f1_fit and f2_fit
print("Coefficients for f1_fit($\\dot{x}$):")
for i, c in enumerate(c_f1):
print(f" c[{i}] = {c:.6e}")
print("\nCoefficients for f2_fit(x):")
for i, c in enumerate(c_f2):
print(f" c[{i}] = {c:.6e}")
# Transform scaled polynomial back to real x space
def transform_coefficients(c_scaled, A0, A1):
N = len(c_scaled)
c_real = np.zeros(N)
for j in range(N):
for k in range(j, N):
c_real[j] += c_scaled[k] * comb(k, j) * ((-A0) ** (k - j)) / (A1 ** k)
return c_real
c_f1_transformed = transform_coefficients(c_f1, A0_xd, A1_xd)
c_f2_transformed = transform_coefficients(c_f2, A0_x, A1_x)
print("\nTransformed (real x) coefficients for f1:")
for i, coef in enumerate(c_f1_transformed):
print(f" coef[{i}] = {coef:.6e}")
print("\nTransformed (real x) coefficients for f2:")
for i, coef in enumerate(c_f2_transformed):
print(f" coef[{i}] = {coef:.6e}")
def f1_fit(x_dot):
return sum(c * ((x_dot-A0_xd)/A1_xd)**i for i, c in enumerate(c_f1))
def f2_fit(x):
return sum(c * ((x-A0_x)/A1_x)**i for i, c in enumerate(c_f2))
def fitted_model_LS(t, y):
x, x_dot = y
x_ddot = F_ext(t) - f1_fit(x_dot) - f2_fit(x)
return [x_dot, x_ddot]
shift_poly=f1_fit(0)
f1_fit_shifted=f1_fit(xdot_vals)-shift_poly
f2_fit_shifted=f2_fit(x_vals)+shift_poly
# plotting obtained CCs
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(5, 8))
ax1.plot(xdot_vals, f1_fit_shifted, label="Identified", linewidth=2)
ax1.plot(xdot_vals, F1(xdot_vals), '--',color='black', label="Theor.", linewidth=2)
ax1.set_title("Obtained CCs from Poly-CC method")
ax1.set_xlabel(r"$\dot{x}$")
ax1.set_ylabel(r"f$_1(\dot{x})$")
ax1.legend()
ax1.grid(True, alpha=0.3)
ax2.plot(x_vals, f2_fit_shifted, label="Identified", linewidth=2)
ax2.plot(x_vals, F2(x_vals), '--',color='black', label="Theor.", linewidth=3)
ax2.set_ylabel(r"f$_2$(x)")
ax2.set_xlabel("x")
ax2.legend()
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
sol = solve_ivp(fitted_model_LS, t_span, y0, t_eval=t_simul,method='LSODA')
x_sim = sol.y[0]
xdot_sim = sol.y[1]
plt.figure(figsize=(8,5))
plt.plot(time_data, x_sim, label="Poly-CC", linewidth=2)
plt.plot(time_data, x_data,"--",color='black', label="Training data", linewidth=2)
plt.xlabel("t")
plt.ylabel("x(t)")
plt.legend()
plt.title("Simulation with Poly-CC model")
plt.show()
##############################################
############# SINDY variants ################
##############################################
##############################################
############# SINDY with u0 #################
#data = np.stack((x_data, x_dot_data), axis=-1)
# define dataset
data = np.stack((x_data, x_dot_data,time_data), axis=-1)
#X_dot_sindy=np.array([x_dot_data,x_ddot_data for i, t in enumerate(t_simul)])
X_sindy = np.stack((x_data,x_dot_data),axis=1) #time_data # sol.y.T # Transpose to get shape (N, 2)
X_dot_sindy = np.stack((x_dot_data, x_ddot_data), axis=1)
u_sindy = F_ext_noise_data # np.stack((F_ext_noise_data),axis=1)
u_sindy_resh = F_ext_noise_data.reshape(-1,1) #flatten()
X_combined = np.hstack((X_sindy, u_sindy_resh))
#polynomials and not crossed terms
# fourier_library = ps.FourierLibrary(n_frequencies=1)
#combined_library = ps.GeneralizedLibrary([poly_library, fourier_library])
print("Sindy polynomial basis with external force u0")
poly_library = ps.PolynomialLibrary(degree=10, include_interaction=False,order='c',include_bias=False) #, include_input=False) #, include_input=False)#,interaction_only=True
optimizer_sindy = ps.STLSQ(threshold=1e-4, max_iter=10000)
model = ps.SINDy(feature_library=poly_library,optimizer=optimizer_sindy)
start = time.time()
model.fit(X_sindy, t=time_data, x_dot=X_dot_sindy, u=u_sindy)
end = time.time()
elapsed = end - start
print('End Training SINDy with u0')
print(f"Training finished in {elapsed:.3f} seconds")
#model = ps.SINDy(feature_library=combined_library)
#model.fit(X_sindy, t=sol.t, u=u_sindy, x_dot=X_dot_sindy) # ¡Aquí pasamos u!
print("\nIdentified SINDy model (exponential format, no labels):")
model.print()
print(" ")
print("Sindy with term k*u0")
poly_library = ps.PolynomialLibrary(degree=10, include_interaction=False,include_bias=False) #, include_input=False) #, include_input=False)#,interaction_only=True
input_library = ps.IdentityLibrary()
inputs_idx = np.array([[0, 1], [2, 2]], dtype=int)
combined_library = ps.GeneralizedLibrary([poly_library, input_library],inputs_per_library=inputs_idx)
optimizer = ps.STLSQ(threshold=1e-4, max_iter=10000)
model_sindy_ku0 = ps.SINDy(feature_library=combined_library, optimizer=optimizer)
start=time.time()
model_sindy_ku0.fit(
X_sindy, t=time_data, x_dot=X_dot_sindy,
u=u_sindy
)
model_sindy_ku0.print()
end = time.time()
elapsed = end - start
print('End Training SINDy with k*u0')
print(f"Training finished in {elapsed:.3f} seconds")
################ SINDY without restrictions ###### validation of the model
print("Simulating Sindy without restrictions")
x_simulated_Sindy_ku0 = []
x_dot_simulated_Sindy_ku0 = []
start = time.time()
try:
u_val_sindy = F_ext(time_data)
x_val_sindy_ku0 = model_sindy_ku0.simulate(y0, t_simul, u=u_val_sindy)
x_simulated_Sindy_ku0 = x_val_sindy_ku0[:, 0]
x_dot_simulated_Sindy_ku0 = x_val_sindy_ku0[:, 1]
# check for NaNs or infs just in case
if np.any(np.isnan(x_val_sindy_ku0)) or np.any(np.isinf(x_val_sindy_ku0)):
print(f"Skipping trial {i+1}: SINDy simulation returned NaNs or infs.")
except Exception as e:
print(f"Skipping trial {i+1}: Exception during SINDy simulation -> {e}")
end = time.time()
elapsed = end - start
print(f"Solve_ivp finished in {elapsed:.3f} seconds")
plt.figure(figsize=(8,5))
plt.plot(time_data[0:len(x_simulated_Sindy_ku0)], x_simulated_Sindy_ku0, label="SINDy", linewidth=2)
plt.plot(time_data, x_data,"--",color='black', label="Training data", linewidth=2)
plt.xlabel("t")
plt.ylabel("x(t)")
plt.legend()
plt.title("Simulation with baseline SINDy model")
plt.show()
#######################################################################
############# SINDY with u0 + SR3constraint (+1.0*u0) #################
print(" ")
print("Sindy restricted to +1.0*u0")
F_p = poly_library.n_output_features_ # number of state‐only features
F_u = input_library.n_output_features_ # should be 1 (just u₀)
F = F_p + F_u # total features per target
T = X_sindy.shape[1] # number of state equations, here 2
C = np.zeros((1, F * T), dtype=float)
d = np.array([1.0]) # RHS: force coefficient == 1
idx = F + F_p
C[0, idx] = 1.0
# Instantiate optimizer with correct keywords
optimizer = ConstrainedSR3(
constraint_lhs=C,
constraint_rhs=d,
constraint_order="target", # default, but explicit is clearer
#reg_weight_lam=1e-3,
#reg_weight_lam=1e-3,
#relax_coeff_nu=1e-6,
threshold=1e-5,
max_iter=10000,
equality_constraints=True # enforce Cw = d strictly
)
# Fit exactly as before
start= time.time()
model = SINDy(feature_library=combined_library, optimizer=optimizer, feature_names=['x0', 'x1', 'u0'])
model.fit(X_sindy, t=time_data, x_dot=X_dot_sindy, u=u_sindy)
model.print()
end = time.time()
elapsed = end - start
print('End Training SINDy with 1*u0')
print(f"Training finished in {elapsed:.3f} seconds")
# === 2) Extract coefficients and feature names ===
# model.coefficients() → shape (n_states, n_features)
# model.get_feature_names() → list of length n_features
# 1) Retrieve the feature‐name list
features = model.get_feature_names()
# 2) Retrieve the coefficient matrix
# shape = (n_states, n_features)
coefs = np.array(model.coefficients())
# Check shapes
n_states, n_features = coefs.shape
assert n_states >= 2, "Need at least two state equations"
# === 3) Build f1(x0) and f2(x1) from eqn 1 (second row) ===
row = coefs[1] # coefficients for x1'
f1_terms = [] # collect (power, coef) for x0
f2_terms = [] # collect (power, coef) for x1
for feat, c in zip(features, row):
if feat.startswith("x0"):
# feature names look like 'x0', 'x0^2', 'x0^3', etc.
# extract power:
if feat == "x0":
p = 1
else:
p = int(feat.split("^")[1])
f2_terms.append((p, c))
elif feat.startswith("x1"):
if feat == "x1":
p = 1
else:
p = int(feat.split("^")[1])
f1_terms.append((p, c))
# ignore u0 (you’ve already fixed its coef = 1)
print("\nModel coefficients with more precision:")
print(model.coefficients()) # This should show the coefficients with more decimals
# Extract coefficients and feature names
coeffs = model.coefficients()
features = model.get_feature_names()
# Define a small threshold to exclude near-zero values
threshold = 1e-20 # You can adjust this as needed
print("\nIdentified SINDy model (nonzero terms only, exponential format):")
for eq_idx in range(coeffs.shape[1]):
terms = []
for coef, name in zip(coeffs[:, eq_idx], features):
# terms.append(f"({coef:.12e}) * {name}")
if np.abs(coef) > threshold:
terms.append(f"({coef:.12e}) * {name}")
eq_str = " + ".join(terms) if terms else ""
print(eq_str)
# Define functions f1 and f2
def f1_sindy(x):
y = np.zeros_like(x)
for p, c in f1_terms:
y += -c * x**p # the
return y
def f2_sindy(x):
y = np.zeros_like(x)
for p, c in f2_terms:
y += -c * x**p
return y
def fitted_model_sindy(t, y):
x, x_dot = y
x_ddot = F_ext(t) - f1_sindy(x_dot) - f2_sindy(x)
return [x_dot, x_ddot]
# plotting obtained CCs
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(5, 8))
ax1.plot(xdot_vals, f1_sindy(xdot_vals), label="Identified", linewidth=2)
ax1.plot(xdot_vals, F1(xdot_vals), '--',color='black', label="Theor.", linewidth=2)
ax1.set_title("Obtained CCs from SINDy-CC method")
ax1.set_xlabel(r"$\dot{x}$")
ax1.set_ylabel(r"f$_1(\dot{x})$")
ax1.legend()
ax1.grid(True, alpha=0.3)
ax2.plot(x_vals, f2_sindy(x_vals), label="Identified", linewidth=2)
ax2.plot(x_vals, F2(x_vals), '--',color='black', label="Theor.", linewidth=3)
ax2.set_ylabel(r"f$_2$(x)")
ax2.set_xlabel("x")
ax2.legend()
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
sol = solve_ivp(fitted_model_sindy, t_span, y0, t_eval=t_simul,method='LSODA')
x_sim = sol.y[0]
xdot_sim = sol.y[1]
plt.figure(figsize=(8,5))
plt.plot(time_data, x_sim, label="SINDy-CC", linewidth=2)
plt.plot(time_data, x_data,"--",color='black', label="Training data", linewidth=2)
plt.xlabel("t")
plt.ylabel("x(t)")
plt.legend()
plt.title("Simulation with SINDy-CC model")
plt.show()
############# SR black box #################
target_SR=F_ext_noise_data-x_ddot_data
X_SR = np.column_stack([x_data, x_dot_data])
model = PySRRegressor(
niterations=200,
binary_operators=["+", "-", "*", "pow"], #"/"
#unary_operators=["log", "abs","sign","sin", "cos", "exp"],
loss="loss(x, y) = (x - y)^2", # MSE
populations=10,
population_size=100,
maxsize=20,
progress=True
)
print("Start Training SR")
start = time.time()
model.fit(X_SR, target_SR, variable_names=["x", "xdot"])
end = time.time()
elapsed = end - start
print('End Training SR')
print(f"Training finished in {elapsed:.3f} seconds")
print(model)
print(model.get_best())
y_pred_SR = model.predict(X_SR)
best_expr = model.sympy()
print("\nSymbolic expression")
print("f(x, xdot):", best_expr)
x_sym, xdot_sym = sp.symbols("x xdot")
# comment the following for high noise values where SR fails
#separating f1 and f2 function terms
expr_sr = sp.simplify(best_expr.expand())
f1_terms_sr = [] # only xdot
f2_terms_sr = [] # only x
mixed_terms_sr = [] # contain both
for term in expr_sr.as_ordered_terms():
free_syms = term.free_symbols
if free_syms == {xdot_sym}:
f1_terms_sr.append(term)
elif free_syms == {x_sym}:
f2_terms_sr.append(term)
else:
mixed_terms_sr.append(term)
f1_expr_sr = sum(f1_terms_sr)
f2_expr_sr = sum(f2_terms_sr)
f1_fun_sr = sp.lambdify(xdot_sym, f1_expr_sr, "numpy")
f2_fun_sr = sp.lambdify(x_sym, f2_expr_sr, "numpy")
# plotting obtained CCs
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(5, 8))
ax1.plot(xdot_vals, f1_fun_sr(xdot_vals), label="Identified", linewidth=2)
ax1.plot(xdot_vals, F1(xdot_vals), '--',color='black', label="Theor.", linewidth=2)
ax1.set_title("Obtained CCs from SR method")
ax1.set_xlabel(r"$\dot{x}$")
ax1.set_ylabel(r"f$_1(\dot{x})$")
ax1.legend()
ax1.grid(True, alpha=0.3)
ax2.plot(x_vals, f2_fun_sr(x_vals), label="Identified", linewidth=2)
ax2.plot(x_vals, F2(x_vals), '--',color='black', label="Theor.", linewidth=3)
ax2.set_ylabel(r"f$_2$(x)")
ax2.set_xlabel("x")
ax2.legend()
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
f_SR = sp.lambdify((x_sym, xdot_sym), best_expr, "numpy")
def ode_sr(t, state):
x, xdot = state
xddot = F_ext(t) - f_SR(x, xdot)
return [xdot, xddot]
sol = solve_ivp(ode_sr, t_span, y0, t_eval=t_simul,method='LSODA')
x_sim = sol.y[0]
xdot_sim = sol.y[1]
plt.figure(figsize=(8,5))
plt.plot(time_data, x_sim, label="SR", linewidth=2)
plt.plot(time_data, x_data,"--",color='black', label="Training data", linewidth=2)
plt.xlabel("t")
plt.ylabel("x(t)")
plt.legend()
plt.title("Simulation with SR model")
plt.show()
##############################################
############# NN-CC WITHOUT SYMMETRIES ######### this next part is for training NNS
# Redefining Hyperparameters (for testing proposes only)
#for neurons in [150,20,50,100,200]:
#Nlearning_rate = 1e-4
#epochs_max = 20000
#N_constraint = 1000
# Convert data to tensors
t_max = np.max(t_simul)
t_tensor = torch.tensor(t_simul, dtype=torch.float32).unsqueeze(1).to(device)
x_tensor = torch.tensor(x_data, dtype=torch.float32).unsqueeze(1).to(device)
x_dot_tensor = torch.tensor(x_dot_data, dtype=torch.float32).unsqueeze(1).to(device)
x_ddot_tensor = torch.tensor(x_ddot_data, dtype=torch.float32).unsqueeze(1).to(device)
F_ext_tensor = torch.tensor(F_ext_noise_data, dtype=torch.float32).unsqueeze(1).to(device)
# define tensors from linear space to then evaluate CCs
x_vals_tensor = torch.tensor(x_vals, dtype=torch.float32).unsqueeze(1).to('cpu')
xdot_vals_tensor = torch.tensor(xdot_vals, dtype=torch.float32).unsqueeze(1).to('cpu')
#x_dot_constraint = torch.linspace(min(x_dot_data), max(x_dot_data), N_constraint).unsqueeze(1).to(device)
#x_constraint = torch.linspace(min(x_data), max(x_data), N_constraint).unsqueeze(1).to(device)
# Define the Neural Network architectures
class NN1(nn.Module):
def __init__(self):
super(NN1, self).__init__()
self.fc1 = nn.Linear(1, neurons)
self.fc2 = nn.Linear(neurons, neurons)
self.fc3 = nn.Linear(neurons, neurons)
self.fc4 = nn.Linear(neurons, 1)
# self.fc5 = nn.Linear(neurons, 1)
def forward(self, x):
#x = torch.relu(self.fc1(x))
#x = torch.relu(self.fc2(x))
#x = torch.nn.functional.leaky_relu(self.fc1(x),0.01)
#x = torch.nn.functional.leaky_relu(self.fc2(x),0.01)
#x = torch.nn.functional.leaky_relu(self.fc3(x),0.01)
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = torch.relu(self.fc3(x))
#x = torch.relu(self.fc3(x))
#x = torch.relu(self.fc4(x))
return self.fc4(x)
# relu tanh sigmoid(good) rrelu nn.functional.softplus
# rrelu nn.functional.silu rrelu nn.functional.selu
# rrelu nn.functional.gelu
class NN2(nn.Module):
def __init__(self):
super(NN2, self).__init__()
self.fc1 = nn.Linear(1, neurons)
self.fc2 = nn.Linear(neurons, neurons)
self.fc3 = nn.Linear(neurons, neurons)
self.fc4 = nn.Linear(neurons, 1)
#self.fc4 = nn.Linear(neurons, neurons)
#self.fc5 = nn.Linear(neurons, 1)
def forward(self, x):
#x = torch.nn.functional.leaky_relu(self.fc1(x),0.01)
#x = torch.nn.functional.leaky_relu(self.fc2(x),0.01)
#x = torch.nn.functional.leaky_relu(self.fc3(x),0.01)
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = torch.relu(self.fc3(x))
#x = torch.relu(self.fc3(x))
#x = torch.relu(self.fc4(x))
return self.fc4(x)
# Instantiate the model
model1_nosym = NN1().to(device)
model2_nosym = NN2().to(device)
criterion = nn.MSELoss()
optimizer1 = optim.Adam(model1_nosym.parameters(), lr=learning_rate )
# , weight_decay=weight_decay) # working well with lr=1e-4
optimizer2 = optim.Adam(model2_nosym.parameters(), lr=learning_rate )
#other optimizers (for testing purposes)
#optimizer1 = optim.AdamW(model1_nosym.parameters(), lr=learning_rate , weight_decay=weight_decay)
#optimizer2 = optim.AdamW(model2_nosym.parameters(), lr=learning_rate , weight_decay=weight_decay)
#optimizer1 = optim.SGD(model1_nosym.parameters(), lr=learning_rate , momentum=momentum) # working well with lr=1e-1
#optimizer2 = optim.SGD(model2_nosym.parameters(), lr=learning_rate , momentum=momentum)
# Training loop
zero_input = torch.tensor([[0.0]], dtype=torch.float32).to(device)
time_start=time.time()
for epoch in range(epochs_max):
model1_nosym.train()
model2_nosym.train()
predictions = x_ddot_tensor + model1_nosym(x_dot_tensor) + model2_nosym(x_tensor)
loss = criterion(predictions, F_ext_tensor)
# Add constraint: model2(0.0) ≈ 0
restriction_loss=0.0*model2_nosym(zero_input)
if(apply_restriction):
model2_at_zero = model2_nosym(zero_input)
model1_at_zero = model1_nosym(zero_input)
restriction_loss = lambda_penalty * ((model2_at_zero ** 2).mean() + (model1_at_zero ** 2).mean()) # squared penalty
#constraint_loss = lambda_penalty * (model2_at_zero ** 2).mean() # squared penalty
total_loss = loss + restriction_loss
else:
total_loss = loss
constraint_loss = restriction_loss
# Backward pass and optimization
optimizer1.zero_grad()
optimizer2.zero_grad()
total_loss.backward()
optimizer1.step()
optimizer2.step()
# Print the loss
if epoch == 0 or (epoch + 1) % 100 == 0:
print(f"Epoch [{epoch+1}], Loss: {loss.item():.4e}, Constraints: {constraint_loss.item():.4e}")
if total_loss.item() < error_threshold:
print(f"Training stopped at epoch {epoch}, Total Loss: {total_loss.item()}")
break
time_end=time.time()
print(" ")
print("End training baseline NN-CC")
print("Neurons :",neurons)
print(f"Training time: {time_end-time_start} seconds")
# Move to cpu after training
model1_nosym=model1_nosym.to('cpu')
model2_nosym=model2_nosym.to('cpu')
t_tensor = t_tensor.to('cpu')
x_tensor = x_tensor.to('cpu')
x_dot_tensor = x_dot_tensor.to('cpu')
x_ddot_tensor = x_ddot_tensor.to('cpu')
F_ext_tensor = F_ext_tensor.to('cpu')
zero_input = zero_input.to('cpu')
model1_nosym.eval()
model2_nosym.eval()
with torch.no_grad():
predicted_F1_nosym = model1_nosym(xdot_vals_tensor).numpy()
predicted_F2_nosym = model2_nosym(x_vals_tensor).numpy()
shift_NN=model2_nosym(zero_input).numpy()
predicted_F1_nosym_shifted = predicted_F1_nosym+shift_NN
predicted_F2_nosym_shifted = predicted_F2_nosym-shift_NN
def NN_nosym_model(t, y):
x = torch.tensor([[y[0]]], dtype=torch.float32)
x_dot = torch.tensor([[y[1]]], dtype=torch.float32)
t_tensor = torch.tensor([[t]], dtype=torch.float32)
F_ext_tensor = torch.tensor([[F_ext(t)]], dtype=torch.float32)
model1_nosym.eval()
model2_nosym.eval()
with torch.no_grad(): # Neural net-based force computation
force = F_ext_tensor - model1_nosym(x_dot) - model2_nosym(x)
x_ddot = force.item()
return [y[1], x_ddot]
# plotting obtained CCs
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(5, 8))
ax1.plot(xdot_vals, predicted_F1_nosym_shifted , label="Identified", linewidth=2)
ax1.plot(xdot_vals, F1(xdot_vals), '--',color='black', label="Theor.", linewidth=2)
ax1.set_title("Obtained CCs from baseline NN-CC method")
ax1.set_xlabel(r"$\dot{x}$")
ax1.set_ylabel(r"f$_1(\dot{x})$")
ax1.legend()
ax1.grid(True, alpha=0.3)
ax2.plot(x_vals, predicted_F2_nosym_shifted , label="Identified", linewidth=2)
ax2.plot(x_vals, F2(x_vals), '--',color='black', label="Theor.", linewidth=3)
ax2.set_ylabel(r"f$_2$(x)")
ax2.set_xlabel("x")
ax2.legend()
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
sol = solve_ivp(NN_nosym_model, t_span, y0, t_eval=t_simul,method='LSODA')
x_sim = sol.y[0]
xdot_sim = sol.y[1]
plt.figure(figsize=(8,5))
plt.plot(time_data, x_sim, label="NN-CC", linewidth=2)
plt.plot(time_data, x_data,"--",color='black', label="Training data", linewidth=2)
plt.xlabel("t")
plt.ylabel("x(t)")
plt.legend()
plt.title("Simulation with baseline NN-CC model")
plt.show()
#######################################################
############# NN-CC+sym (WITH SYMMETRIES) #########
#for neurons in [150,20,50,100,200]:
#neurons=2
#neurons=100
# Hyperparameters
#learning_rate = 1e-4
#epochs_max = 20000
#N_constraint = 1000
# Many the lines here are repeated for reusability,
# i.e. NN-CC without symmetries block can be commented
t_max = np.max(t_simul)
t_tensor = torch.tensor(t_simul, dtype=torch.float32).unsqueeze(1).to(device)
x_tensor = torch.tensor(x_data, dtype=torch.float32).unsqueeze(1).to(device)
x_dot_tensor = torch.tensor(x_dot_data, dtype=torch.float32).unsqueeze(1).to(device)
x_ddot_tensor = torch.tensor(x_ddot_data, dtype=torch.float32).unsqueeze(1).to(device)
F_ext_tensor = torch.tensor(F_ext_noise_data, dtype=torch.float32).unsqueeze(1).to(device)
# define tensors from linear space to then evaluate CCs
x_vals_tensor = torch.tensor(x_vals, dtype=torch.float32).unsqueeze(1).to('cpu')
xdot_vals_tensor = torch.tensor(xdot_vals, dtype=torch.float32).unsqueeze(1).to('cpu')
#x_dot_constraint = torch.linspace(min(x_dot_data), max(x_dot_data), N_constraint).unsqueeze(1).to(device)
#x_constraint = torch.linspace(min(x_data), max(x_data), N_constraint).unsqueeze(1).to(device)
x_dot_constraint = torch.linspace(x_dot_data.min(), x_dot_data.max(), N_constraint, device=device).unsqueeze(1)
x_constraint = torch.linspace(x_data.min(), x_data.max(), N_constraint, device=device).unsqueeze(1)
# Define the Neural Network
class NN1(nn.Module):
def __init__(self):
super(NN1, self).__init__()
self.fc1 = nn.Linear(1, neurons)
self.fc2 = nn.Linear(neurons, neurons)
self.fc3 = nn.Linear(neurons, neurons)