-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathintegration_esdirk.py
executable file
·1223 lines (1090 loc) · 54.8 KB
/
integration_esdirk.py
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
import numpy as np
import numpy.matlib
import ctypes as ct
from scipy.optimize import fsolve
import copy
import scipy.integrate
import scipy.interpolate
from damped_newton import damped_newton_solve
import newton
NEWTONCHOICE=2 #0: Scipy's fsolve 1: Scipy's newton (bad !), 2: custom damped Newton, 3: custom undamped quasi-Newton (weirdly works better than the damped one...)
def inverseERKintegration(fun, y0, t_span, nt, method, jacfun=None, bPrint=True,
vectorized=False, fullDebug=False, bPlotSubsteps=False):
""" Performs the integration of the system dy/dt = f(t,y)*
with a reversed explicit RK method
from t=t_span[0] to t_span[1], with initial condition y(t_span[0])=y0.
The RK method described by A,b,c is an explicit method (which we reverse)
- fun : (function handle) model function (time derivative of y)
- y0 : (1D-array) initial condition
- t_span : (1D-array) array of 2 values (start and end times)
- nt : (integer) number of time steps
- A : (2D-array) Butcher table of the chosen RK method
- b : (1D-array) weightings for the quadrature formula of the RK methods
- c : (1D-array) RK substeps time
"""
assert y0.ndim==1, 'y0 must be 0D or 1D'
out = scipy.integrate._ivp.ivp.OdeResult()
t = np.linspace(t_span[0], t_span[1], nt)
A,b,c = method['A'], method['b'], method['c'] # Butcher coefficients
n = y0.size # size of the problem
dt = (t_span[1]-t_span[0]) / (nt-1) # time step
s = np.size(b) # number of stages for the RK method
y = np.zeros((n, nt)) # solution accros all time steps
y[:,0] = y0
## make sure the function is vectorised
if vectorized:
fun_vectorised = fun
else:
def fun_vectorised(t,x):
""" Vectorize a non-vectorized function """
if x.ndim==1:
return fun(t,x)
else:
if not (isinstance(t, np.ndarray)):
t = t*np.ones((x.shape[1]))
res0 = fun(t[0],x[:,0])
res = np.zeros((res0.shape[0],x.shape[1]))
res[:,0]=res0
for i in range(1,x.shape[1]):
res[:,i] = fun(t[i],x[:,i])
return res
## define the residual function
def resfun(ynp1,yn,tn,dt,A,n,s, return_substeps=False):
""" Residuals for the substeps.
The input is Y = (y0[...], y1[...], ...).T """
# 1 - compute reverse stages explicitly
Y = np.zeros((n,s), order='F')
for i in range(s):
Y[:,i] = ynp1
for j in range(i+1): # explicit RK reversed
Y[:,i] = Y[:,i] - dt*A[i,j]*fun(tn+(1-c[j])*dt, Y[:,j])
# TODO use k's instead
# 2 - compute the reversed yn
# TODO: on est toujours stiffly accurate, non ?
ynrev = ynp1
for i in range(s):
ynrev = ynrev - dt*b[i]*fun(tn+(1-c[i])*dt, Y[:,i])
# ynrev = Y[:,-1]
print('ynrev=',ynrev)
# 2 - compute residuals as a matrix (one row for each step)
res = ynrev - yn
if return_substeps:
return res, Y
else:
return res
## advance in time
out.nfev = 0
out.njev = 0
unm1 = np.copy(y0)
# At = A.T
warm_start_dict = None
infodict_hist = {} # additonal optional debug storage
out.infodict_hist = infodict_hist
for it, tn in enumerate(t[:-1]):
if bPrint:
if np.mod(it,np.floor(nt/10))==0:
print('\n{:.1f} %'.format(100*it/nt), end='')
if np.mod(it,np.floor(nt/100))==0:
print('.', end='')
# solve the complete non-linear system via a Newton method
yini = unm1[:]
ynp1, infodict, warm_start_dict = damped_newton_solve(
fun=lambda x: resfun(ynp1=x,yn=unm1, tn=tn, dt=dt, A=A, n=n, s=s),
x0=np.copy(yini), rtol=1e-9, ftol=1e-30,
jacfun=None, warm_start_dict=warm_start_dict,
itmax=100, jacmax=20, tau_min=1e-4, convergenceMode=0,
bPrint=True)
out.nfev += infodict['nfev']
out.njev += infodict['njev']
if infodict['ier']!=0: # Newton did not converge
# restart the Newton solve with all outputs enabled
ynp1, infodict, warm_start_dict = damped_newton_solve(fun=lambda x: resfun(ynp1=x,y0=unm1, tn=tn, dt=dt, A=A, n=n, s=s),
x0=np.copy(yini), rtol=1e-9, ftol=1e-30,
jacfun=None, warm_start_dict=warm_start_dict,
itmax=100, jacmax=20, tau_min=1e-4, convergenceMode=0, bPrint=True)
msg = 'Newton did not converge'
# raise Exception(msg)
out.y = y[:,:it+1]
out.t = t[:it+1]
out.message = msg
return out
if fullDebug: # store additional informations about the Newton solve
if not bool(infodict_hist): # the debug dictionnary has not yet been initialised
for key in infodict.keys():
if not isinstance(infodict[key], np.ndarray) and (key!='ier' and key!='msg'): # only save single values
infodict_hist[key] = [infodict[key]]
else: # backup already initialised
for key in infodict_hist.keys():
infodict_hist[key].append(infodict[key])
# get the substeps to retrieve the error estimate
if bPlotSubsteps:
res, ysubsteps = resfun(ynp1=ynp1,yn=unm1, tn=tn, dt=dt, A=A, n=n, s=s, return_substeps=True)
time_stages = tn + (1-method['c'])*dt
plt.figure()
I=[0]
plt.plot(time_stages,ysubsteps[I,:].T, marker='.', label=['y0','y1'])
# plt.plot(time_stages,ysubsteps[1,:], marker='.', label='y1')
plt.plot( tn*np.ones(len(I)), unm1[I], marker='o', label='yn', linestyle='')
plt.plot( (tn+dt)*np.ones(len(I)), ynp1[I], marker='o', label='ynp1', linestyle='')
plt.grid()
plt.legend()
plt.xlabel('t')
plt.ylabel('y')
raise Exception('stop')
y[:,it+1] = ynp1
unm1=ynp1
# END OF INTEGRATION
out.y = y
out.t = t
# out.y_substeps = y_substeps # last substeps
return out
def adaptiveInverseERKintegration(fun, y0, t_span, method, method2=None,
atol=None,rtol=None,max_step=np.inf, first_step=None,
jacfun=None, bPrint=True,
vectorized=False, fullDebug=False, plotStagesAfter=np.inf,
bImplicitEmbedded=False,
nmax_steps=np.inf):
""" Performs the integration of the system dy/dt = f(t,y)*
with a reversed explicit RK method
from t=t_span[0] to t_span[1], with initial condition y(t_span[0])=y0.
The RK method described by A,b,c is an explicit method (which we reverse)
- fun : (function handle) model function (time derivative of y)
- y0 : (1D-array) initial condition
- t_span : (1D-array) array of 2 values (start and end times)
- nt : (integer) number of time steps
- A : (2D-array) Butcher table of the chosen RK method
- b : (1D-array) weightings for the quadrature formula of the RK methods
- c : (1D-array) RK substeps time
"""
assert y0.ndim==1, 'y0 must be 0D or 1D'
out = scipy.integrate._ivp.ivp.OdeResult()
t = np.linspace(t_span[0], t_span[1], nt)
n = y0.size # size of the problem
dt = (t_span[1]-t_span[0]) / (nt-1) # time step
# s = np.size(b) # number of stages for the RK method
y = np.zeros((n, nt)) # solution accros all time steps
y[:,0] = y0
## make sure the function is vectorised
if vectorized:
fun_vectorised = fun
else:
def fun_vectorised(t,x):
""" Vectorize a non-vectorized function """
if x.ndim==1:
return fun(t,x)
else:
if not (isinstance(t, np.ndarray)):
t = t*np.ones((x.shape[1]))
res0 = fun(t[0],x[:,0])
res = np.zeros((res0.shape[0],x.shape[1]))
res[:,0]=res0
for i in range(1,x.shape[1]):
res[:,i] = fun(t[i],x[:,i])
return res
## define the residual function
def resfun(ynp1,yn,tn,dt,method,return_substeps=False):
""" Residuals for the substeps.
The input is Y = (y0[...], y1[...], ...).T """
# 1 - compute reverse stages explicitly
A,b,c = method['A'], method['b'], method['c'] # Butcher coefficients
n = yn.size
s = b.size
Y = np.zeros((n,s), order='F')
for i in range(s):
Y[:,i] = ynp1
for j in range(i): # explicit RK reversed
Y[:,i] = Y[:,i] - dt*A[i,j]*fun(tn+(1-c[j])*dt, Y[:,j])
# TODO use k's instead
# 2 - compute the reversed yn
# TODO: on est toujours stiffly accurate, non ?
ynrev = ynp1
for i in range(s):
ynrev = ynrev - dt*b[i]*fun(tn+(1-c[i])*dt, Y[:,i])
# ynrev = Y[:,-1]
# print('ynrev=',ynrev)
# 2 - compute residuals as a matrix (one row for each step)
res = ynrev - yn
if return_substeps:
return res, Y, ynrev
else:
return res
## advance in time
out.nfev = 0
out.njev = 0
unm1 = np.copy(y0)
# At = A.T
warm_start_dict = None
infodict_hist = {} # additonal optional debug storage
out.infodict_hist = infodict_hist
rtol_newton=1e-9 #min(1e-5,rtol/10)
atol_newton=0 #min(1e-5,atol/10)
ftol_newton=1e-15
if first_step is None:
# estimate first step following Hairer & Wanner's book
lbda_estimate = np.linalg.norm(fun(t_span[0], y0*1.001)-fun(t_span[0],y0))/(1.001*np.linalg.norm(y0))
# choose first step such that lbda*dt is small
dt = 1e-2/lbda_estimate
print('first_dt=', dt)
out.nfev+=2
else:
dt = first_step
### initialize algorithm variables and outputs
tn = t_span[0]
tf = t_span[-1]
tsol = [tn]
ysol = [y0]
nt_rejected = 0 # number of time steps rejected (error too high or code error)
nt_accepted = 0 # number of accepted steps
nt_performed = 0 # total number of time steps computed (accepted+rejected)
unm1 = np.copy(ysol[-1])
# error_estimate = np.zeros((n,))
while tn < tf:
nt_performed = nt_accepted+nt_rejected
if nt_accepted>=nmax_steps:
print('Maximum number of steps reached')
break
if bPrint: # print progress
if np.mod(nt_performed,100)==0:
print('\nt={:.10e} '.format(tn), end='')
if np.mod(nt_performed,10)==0:
print('.', end='')
bAcceptedStep = False
# iterate on dt until the error estimation is sufficiently low
while not bAcceptedStep:
if dt<1e-15:
raise Exception('dt<1e-15 --> stopping to avoid underflows')
try:
yini = unm1[:]
ynp1_1, infodict, warm_start_dict = damped_newton_solve(
fun=lambda x: resfun(ynp1=x,yn=unm1, tn=tn, dt=dt,method=method),
x0=np.copy(yini), rtol=rtol_newton, atol=atol_newton, ftol=ftol_newton,
jacfun=None, warm_start_dict=warm_start_dict,
itmax=100, jacmax=2, tau_min=1e-4, convergenceMode=0,
bPrint=fullDebug)
out.nfev += infodict['nfev']
out.njev += infodict['njev']
if infodict['ier']!=0: # Newton did not converge
print('Newton did not converge\n\t--> reducing time step')
dt=dt/2
nt_rejected+=1
continue
except FloatingPointError as e:
print('{}\n\t--> reducing time step'.format(e))
dt = dt/4
nt_rejected+=1
continue # restart at the beginning of the while loop with a new dt value
if method2 is None:
# get the substeps to retrieve the error estimate
res, ysubsteps, yn_1 = resfun(ynp1=ynp1_1, yn=unm1, tn=tn, dt=dt,
method=method, return_substeps=True)
# WE COMPARE THE ERROR AT TN not TNP1 !!!!!!!
if method['embedded']['i_high']>=0:
high_order_sol = ysubsteps[:,method['embedded']['i_high']]
else:
high_order_sol = ynp1_1
if method['embedded']['i_low']>=0:
low_order_sol = ysubsteps[:,method['embedded']['i_low']]
else:
low_order_sol = ynp1_1
error_order = method['embedded']['p_low'] # ordre de l'estimateur d'erreur (global)
error_estimate = high_order_sol - low_order_sol
else:
# compute explicitly the other methods (backwards), starting from the same ynp1
if bImplicitEmbedded: # solve the embedded method implicitly
print('implicit embedded step')
try:
yini = ynp1_1[:]
ynp1_2, infodict, warm_start_dict = damped_newton_solve(
fun=lambda x: resfun(ynp1=x, yn=unm1, tn=tn, dt=dt, method=method2),
x0=np.copy(yini), rtol=rtol_newton, atol=atol_newton, ftol=ftol_newton,
jacfun=None, warm_start_dict=None,
itmax=10, jacmax=3, tau_min=1e-4, convergenceMode=0,
bPrint=fullDebug)
out.nfev += infodict['nfev']
out.njev += infodict['njev']
if infodict['ier']!=0: # Newton did not converge
raise Exception('Newton did not converge\n\t--> reducing time step')
except Exception as e:
print('Issue during embedded step: {}'.format(e))
raise e
res, ysubsteps, yn_1 = resfun(ynp1=ynp1_1, yn=unm1, tn=tn, dt=dt, method=method, return_substeps=True)
res2, ysubsteps2, yn_2 = resfun(ynp1=ynp1_2, yn=unm1, tn=tn, dt=dt, method=method2, return_substeps=True)
# WE COMPARE THE ERROR AT TN not TNP1 !!!!!!!
if method['order']>method2['order']:
high_order_sol = ynp1_1
low_order_sol = ynp1_2
else:
high_order_sol = ynp1_2
low_order_sol = ynp1_1
if method['order']==method2['order']:
print('Both methods have the same order... We assume they have different error constants ?')
error_order = min(method['order'], method2['order'])
error_estimate = high_order_sol - low_order_sol
else: # apply embedded scheme backwards and compare the yn's
ynp1_2 = ynp1_1
res, ysubsteps, yn_1 = resfun(ynp1=ynp1_1, yn=unm1, tn=tn, dt=dt, method=method, return_substeps=True)
res2, ysubsteps2, yn_2 = resfun(ynp1=ynp1_2, yn=unm1, tn=tn, dt=dt, method=method2, return_substeps=True)
# WE COMPARE THE ERROR AT TN not TNP1 !!!!!!!
if method['order']>method2['order']:
high_order_sol = yn_1
low_order_sol = yn_2
else:
high_order_sol = yn_2
low_order_sol = yn_1
if method['order']==method2['order']:
print('Both methods have the same order... We assume they have different error constants ?')
error_order = min(method['order'], method2['order'])
error_estimate = high_order_sol - low_order_sol
if nt_accepted>=plotStagesAfter:
time_stages = tn + (1-method['c'])*dt
plt.figure()
plt.plot(time_stages,ysubsteps[0,:], marker='.', label='sol1: y0')
# plt.plot(time_stages,ysubsteps[1,:], marker='.', label='sol1: y1')
if not ( method2 is None ):
time_stages2 = tn + (1-method2['c'])*dt
plt.plot(time_stages2,ysubsteps2[0,:], marker='.', label='sol2: y')
# plt.plot(time_stages,ysubsteps2[1,:], marker='.', label='sol2: y1')
# plt.plot( tn*np.ones(n), unm1, marker='o', label='yn', linestyle='')
plt.plot( (tn+dt)*np.ones(n), ynp1_1, marker='o', label='ynp1', linestyle='')
plt.plot( (tn)*np.ones(n), low_order_sol, marker='x', label='low', linestyle='')
plt.plot( (tn)*np.ones(n), high_order_sol, marker='+', label='high', linestyle='')
plt.grid()
plt.legend()
plt.xlabel('t')
plt.ylabel('y')
raise Exception('stop')
tol_vec = atol + rtol*abs(unm1) #np.maximum(abs(ynp1_1),abs(unm1))
err_vec = error_estimate / tol_vec
# estimation de l'erreur, basé sur Hairer/Norsett/Wanner, Solving ODEs vol I, page 167/168
err = np.linalg.norm( err_vec, ord=2 ) / np.sqrt(err_vec.size)
if bPrint:
print('|err|={:.2e}'.format(err))
# compute the factor by which delta_t is to be multiplied to obtain err~1
# a safety factor < 1 is used to ensure the new delta t leads to err < 1
# bounds are also applied on the factor so that the time step does not change to aggressively
factor = min(10, max(0.2, 0.9*(1/err)**(1/(error_order+1)) ))
dt_opt = dt*factor
if err>1:
dt=dt_opt
bAcceptedStep=False
nt_rejected+=1
if bPrint:
print('rejected step --> new dt={:.3e} ( = {} * old dt)'.format(dt, factor))
else:
bAcceptedStep=True
# we found an acceptable time step value, we can now move forward to the next time step
tn = tn+dt
tsol.append(tn)
ysol.append(np.copy(ynp1_1))
unm1[:] = ynp1_1
nt_accepted+=1
# take the new optimal time step lentgh, and ensure we respect the different bounds
dt = dt_opt
if tn+dt>tf:
dt = tf-tn
if dt>max_step: # avoid time steps too important
dt=max_step
if bPrint:
print('tn={}'.format(tn))
print('accepted step --> new dt={:.3e}'.format(dt))
# END OF INTEGRATION
out.y = np.array(ysol).T
out.t = np.array(tsol)
return out
# def solveInverseERKstep(unm1,yini,warm_start_dict):
# """ Résolution d'un pas de temps d'une méthode RK inversée"""
# # solve the complete non-linear system via a Newton method
# ynp1, infodict, warm_start_dict = damped_newton_solve(
# fun=lambda x: resfun(ynp1=x,yn=unm1, tn=tn, dt=dt, A=A, n=n, s=s),
# x0=np.copy(yini), rtol=1e-9, ftol=1e-30,
# jacfun=None, warm_start_dict=warm_start_dict,
# itmax=100, jacmax=20, tau_min=1e-4, convergenceMode=0,
# bPrint=True)
# out.nfev += infodict['nfev']
# out.njev += infodict['njev']
# if infodict['ier']!=0: # Newton did not converge
# # restart the Newton solve with all outputs enabled
# ynp1, infodict, warm_start_dict = damped_newton_solve(fun=lambda x: resfun(Y=x,y0=unm1, tn=tn, dt=dt, A=At, n=n, s=s),
# x0=np.copy(yini), rtol=1e-9, ftol=1e-30,
# jacfun=None, warm_start_dict=warm_start_dict,
# itmax=100, jacmax=20, tau_min=1e-4, convergenceMode=0, bPrint=True)
# msg = 'Newton did not converge'
# # raise Exception(msg)
# out.y = y[:,:it+1]
# out.t = t[:it+1]
# out.message = msg
# return out
def ERK_adapt_integration(fun, y0, t_span, method, atol=1e-6, rtol=1e-6, first_step=None, max_step=np.inf, bPrint=False):
if not method['isEmbedded']:
raise Exception('the chosen method is not able to perform time step adaptation')
if method['embedded']['mode']!=2:
raise Exception('Embedded method {} is not supported'.format(method['embedded']['mode']))
assert y0.ndim==1, 'y0 must be 0D or 1D'
A,b,c = method['A'], method['b'], method['c'] # Butcher coefficients
d = method['embedded']['d'] # coefficients for the error estimate
error_order = method['embedded']['error_order']
ysol = [np.copy(y0)]
tsol = [t_span[0]]
n = y0.size # size of the problem
s = np.size(b) # number of stages for the RK method
out = scipy.integrate._ivp.ivp.OdeResult()
out.nfev = 0
out.njev = 0
if first_step is None:
# estimate first step following Hairer & Wanner's book
lbda_estimate = np.linalg.norm(fun(t_span[0], y0*1.001)-fun(t_span[0],y0))/(1.001*np.linalg.norm(y0))
# choose first step such that lbda*dt is small
dt = 1e-2/lbda_estimate
print('first_dt=', dt)
out.nfev+=2
else:
dt = first_step
### initialize algorithm variables and outputs
tn = t_span[0]
tf = t_span[-1]
tsol = [tn]
ysol = [y0]
nt_rejected = 0 # number of time steps rejected (error too high or code error)
nt_accepted = 0 # number of accepted steps
nt_performed = 0 # total number of time steps computed (accepted+rejected)
Y = np.zeros((n, s), order='F')
K = np.zeros((n, s), order='F')
unm1 = np.copy(ysol[-1])
error_estimate = np.zeros((n,))
while tn < tf:
nt_performed = nt_accepted+nt_rejected
if bPrint: # print progress
if np.mod(nt_performed,100)==0:
print('\nt={:.10e} '.format(tn), end='')
if np.mod(nt_performed,10)==0:
print('.', end='')
bAcceptedStep = False
Y[:,0] = unm1[:]
if c[0]==0. and nt_performed>0:
K[:,0] = K[:,-1]
else:
K[:,0] = fun(tn+c[0]*dt, Y[:,0])
out.nfev+=1
# iterate on dt until the error estimation is sufficiently low
while not bAcceptedStep:
if dt<1e-15:
raise Exception('dt<1e-15 --> stopping to avoid underflows')
try:
for i in range(0,s):
# Yi = y0 + dt*sum_{j=1}^{i-1} a_{ij} f(Yj))$
# 1 - Clear for loop formulation
# Y[:,i] = unm1[:]
# for j in range(i):
# Y[:,i] += dt*K[:,j]*A[i,j]
# 2 - Compact matrix formulation
Y[:,i] = unm1[:] + dt * K[:,:i].dot( A[i,:i] )
K[:,i] = fun(tn+c[i]*dt, Y[:,i])
out.nfev+=1
## compute the new solution value at time t_{n+1}
# newY = np.copy(unm1)
# for j in range(s):
# newY[:] = newY[:] + dt*b[j]*K[:,j]
newY = unm1[:] + dt * K.dot( b )
except FloatingPointError as e:
print('{}\n\t--> reducing time step'.format(e))
dt = dt/4
nt_rejected+=1
continue # restart at the beginning of the while loop with a new dt value
error_estimate[:] = 0.
for j in range(s):
error_estimate[:] = error_estimate[:] + dt*d[j]*K[:,j]
tol = atol + rtol*np.abs(np.maximum(newY,unm1))
err_vec = error_estimate/tol
# estimation de l'erreur, basé sur Hairer/Norsett/Wanner, Solving ODEs vol I, page 167/168
err = np.linalg.norm( err_vec )
if bPrint:
print('|err|={:.2e}'.format(err))
# compute the factor by which delta_t is to be multiplied to obtain err~1
# a safety factor < 1 is used to ensure the new delta t leads to err < 1
# bounds are also applied on the factor so that the time step does not change to aggressively
factor = min(10, max(0.2, 0.9*(1/err)**(1/(error_order+1)) ))
dt_opt = dt*factor
if err>1:
dt=dt_opt
bAcceptedStep=False
nt_rejected+=1
if bPrint:
print('rejected step --> new dt={:.3e} ( = {} * old dt)'.format(dt, factor))
else:
bAcceptedStep=True
# we found an acceptable time step value, we can now move forward to the next time step
tn = tn+dt
tsol.append(tn)
ysol.append(np.copy(newY))
unm1[:] = newY
nt_accepted+=1
# take the new optimal time step lentgh, and ensure we respect the different bounds
dt = dt_opt
if tn+dt>tf:
dt = tf-tn
if dt>max_step: # avoid time steps too important
dt=max_step
if bPrint:
print('tn={}'.format(tn))
print('accepted step --> new dt={:.3e}'.format(dt))
# END OF INTEGRATION
out.y = np.array(ysol).T
out.t = np.array(tsol)
return out
def ERK_integration(fun, y0, t_span, nt, method, bPrint=True):
""" Performs the integration of the system dy/dt = f(t,y)
from t=t_span[0] to t_span[1], with initial condition y(t_span[0])=y0.
The RK method described by A,b,c is an explicit method
- fun : (function handle) model function (time derivative of y)
- y0 : (1D-array) initial condition
- t_span : (1D-array) array of 2 values (start and end times)
- nt : (integer) number of time steps
- A : (2D-array) Butcher table of the chosen RK method
- b : (1D-array) weightings for the quadrature formula of the RK methods
- c : (1D-array) RK substeps time
"""
assert y0.ndim==1, 'y0 must be 0D or 1D'
out = scipy.integrate._ivp.ivp.OdeResult()
t = np.linspace(t_span[0], t_span[1], nt)
A,b,c = method['A'], method['b'], method['c'] # Butcher coefficients
n = y0.size # size of the problem
dt = (t_span[1]-t_span[0]) / (nt-1) # time step
s = np.size(b) # number of stages for the RK method
y = np.zeros((n, nt), order='F') # solution accros all time steps
y[:,0] = y0
## advance in time
out.nfev = 0
out.njev = 0
Y = np.zeros((n, s), order='F')
K = np.zeros((n, s), order='F')
unm1 = np.copy(y0)
for it, tn in enumerate(t[:-1]):
if bPrint: # print progress
if np.mod(it,np.floor(nt/10))==0:
print('\n{:.1f} %'.format(100*it/nt), end='')
if np.mod(it,np.floor(nt/100))==0:
print('.', end='')
Y[:,0]=unm1[:]
K[:,0] = fun(tn+c[0]*dt, Y[:,0])
## compute each stage sequentially
for i in range(1,s):
# Yi = y0 + dt*sum_{j=1}^{i-1} a_{ij} f(Yj))$
# Y[:,i] = unm1[:]
# for j in range(i):
# Y[:,i] += dt*K[:,j]*A[i,j]
Y[:,i] = unm1[:] + dt * K[:,:i].dot( A[i,:i] )
K[:,i] = fun(tn+c[i]*dt, Y[:,i])
## compute the new solution value at time t_{n+1}
# for j in range(s):
# unm1[:] = unm1[:] + dt*b[j]*K[:,j]
unm1[:] = unm1[:] + dt * K.dot( b )
y[:,it+1] = unm1[:]
out.nfev += s
# END OF INTEGRATION
out.y = y
out.t = t
return out
def FIRK_integration(fun, y0, t_span, nt, method, jacfun=None, bPrint=True, vectorized=False,newtonchoice=NEWTONCHOICE,
fullDebug=False):
""" Performs the integration of the system dy/dt = f(t,y)
from t=t_span[0] to t_span[1], with initial condition y(t_span[0])=y0.
The RK method described by A,b,c is fully implicit (e.g RadauIIA ...).
/!\ it can also solve explicit methods ! (even though this is highly inefficient)
- fun : (function handle) model function (time derivative of y)
- y0 : (1D-array) initial condition
- t_span : (1D-array) array of 2 values (start and end times)
- nt : (integer) number of time steps
- A : (2D-array) Butcher table of the chosen RK method
- b : (1D-array) weightings for the quadrature formula of the RK methods
- c : (1D-array) RK substeps time
- jacfun : (function handle, optional) function returning a 2D-array (Jacobian df/dy)
TODO: take into account the jacfun argument
"""
assert y0.ndim==1, 'y0 must be 0D or 1D'
A,b,c = method['A'], method['b'], method['c']
out = scipy.integrate._ivp.ivp.OdeResult()
t = np.linspace(t_span[0], t_span[1], nt)
n = y0.size # size of the problem
dt = (t_span[1]-t_span[0]) / (nt-1) # time step
s = np.size(b) # number of stages for the RK method
y = np.zeros((n, nt)) # solution accros all time steps
y[:,0] = y0
## make sure the function is vectorised
if vectorized:
fun_vectorised = fun
else:
def fun_vectorised(t,x):
""" Vectorize a non-vectorized function """
if x.ndim==1:
return fun(t,x)
else:
if not (isinstance(t, np.ndarray)):
t = t*np.ones((x.shape[1]))
res0 = fun(t[0],x[:,0])
res = np.zeros((res0.shape[0],x.shape[1]))
res[:,0]=res0
for i in range(1,x.shape[1]):
res[:,i] = fun(t[i],x[:,i])
return res
## define the residual function
def resfun(Y,y0,tn,dt,A,n,s):
""" Residuals for the substeps.
The input is Y = (y0[...], y1[...], ...).T """
# 1 - recover all separates stages
Yr = Y.reshape((n,s), order='F') # each line of Yr is one stage
# 2 - compute residuals as a matrix (one row for each step)
res = Yr - y0[:,np.newaxis] - dt*fun_vectorised(tn+c*dt, Yr).dot(At)
# 3 - reshape the residuals to return a row vector
return res.reshape((n*s,), order='F')
## skirmish
bStifflyAccurate = np.all(b==A[-1,:]) # then the last stage is the solution at the next time point
## advance in time
out.nfev = 0
out.njev = 0
K= np.zeros((n, s), order='F')
unm1 = np.copy(y0)
At = A.T
warm_start_dict = None
infodict_hist = {} # additonal optional debug storage
out.infodict_hist = infodict_hist
for it, tn in enumerate(t[:-1]):
if bPrint:
if np.mod(it,np.floor(nt/10))==0:
print('\n{:.1f} %'.format(100*it/nt), end='')
if np.mod(it,np.floor(nt/100))==0:
print('.', end='')
# solve the complete non-linear system via a Newton method
yini = np.zeros((n*s,))
for i in range(s):
yini[i*n:(i+1)*n] = unm1[:]
if newtonchoice==0:
y_substeps, infodict, ier, msg = scipy.optimize.fsolve(func= lambda x: resfun(Y=x,y0=unm1, tn=tn, dt=dt, A=At, n=n, s=s),
x0=np.copy(yini), fprime=None, # band=(5,5), #gradFun
# epsfcn = 1e-7,
xtol=1e-9, full_output=True)
out.nfev += infodict['nfev']
elif newtonchoice==1:
# this approach is not suited, because scipy's newton considers each residual component independently...
y_substeps, converged, zero_der = scipy.optimize.newton(func= lambda x: resfun(Y=x,y0=unm1, tn=tn, dt=dt, A=At, n=n, s=s),
x0=np.copy(yini), fprime=None, # epsfcn = 1e-7,
tol=1e-20, rtol=1e-9, maxiter=100, full_output=True)
out.nfev += np.nan # not provided...
elif newtonchoice==2: # custom damped newton
y_substeps, infodict, warm_start_dict = damped_newton_solve(fun=lambda x: resfun(Y=x,y0=unm1, tn=tn, dt=dt, A=At, n=n, s=s),
x0=np.copy(yini), rtol=1e-9, ftol=1e-30,
jacfun=None, warm_start_dict=warm_start_dict,
itmax=100, jacmax=20, tau_min=1e-4, convergenceMode=0)
out.nfev += infodict['nfev']
out.njev += infodict['njev']
if infodict['ier']!=0: # Newton did not converge
# restart the Newton solve with all outputs enabled
y_substeps, infodict, warm_start_dict = damped_newton_solve(fun=lambda x: resfun(Y=x,y0=unm1, tn=tn, dt=dt, A=At, n=n, s=s),
x0=np.copy(yini), rtol=1e-9, ftol=1e-30,
jacfun=None, warm_start_dict=warm_start_dict,
itmax=100, jacmax=20, tau_min=1e-4, convergenceMode=0, bPrint=True)
msg = 'Newton did not converge'
# raise Exception(msg)
out.y = y[:,:it+1]
out.t = t[:it+1]
out.message = msg
return out
if fullDebug: # store additional informations about the Newton solve
if not bool(infodict_hist): # the debug dictionnary has not yet been initialised
for key in infodict.keys():
if not isinstance(infodict[key], np.ndarray) and (key!='ier' and key!='msg'): # only save single values
infodict_hist[key] = [infodict[key]]
else: # backup already initialised
for key in infodict_hist.keys():
infodict_hist[key].append(infodict[key])
elif newtonchoice==4:
y_substeps = scipy.optimize.newton_krylov(F=lambda x: resfun(Y=x,y0=unm1, tn=tn, dt=dt, A=At, n=n, s=s),
xin=np.copy(yini), iter=None, rdiff=1e-8,
method='lgmres',
inner_maxiter=20, inner_M=None,
outer_k=10,
verbose=True,
maxiter=None,
f_tol=1e-20, f_rtol=1e-8,
x_tol=1e-9, x_rtol=1e-9,
tol_norm=None,
line_search='armijo', callback=None)
else:
raise Exception('newton choice is not recognised')
K[:,:] = fun_vectorised(tn+c*dt, y_substeps.reshape((n,s), order='F'))
# out.njev += infodict['njev']
if bStifflyAccurate:
# the last stage is the value at t+dt
unm1 = y_substeps[-n:]
else:
# Y_{n+1} = Y_{n} + \Delta t \sum\limits_{i=1}^{s} b_i k_i
# for j in range(s):
# unm1[:] = unm1[:] + dt*b[j]*K[:,j]
unm1[:] = unm1[:] + dt * K.dot( b )
y[:,it+1] = unm1[:]
# END OF INTEGRATION
out.y = y
out.t = t
out.y_substeps = y_substeps # last substeps
return out
########################################################################################
def DIRK_integration(fun, y0, t_span, nt, method, jacfun=None, bPrint=True, newtonchoice=2, fullDebug=False):
""" Performs the integration of the system dy/dt = f(t,y)
from t=t_span[0] to t_span[1], with initial condition y(t_span[0])=y0.
The RK method described by A,b,c may be explicit or diagonally-implicit.
- fun : (function handle) model function (time derivative of y)
- y0 : (1D-array) initial condition
- t_span : (1D-array) array of 2 values (start and end times)
- nt : (integer) number of time steps
- A : (2D-array) Butcher table of the chosen RK method
- b : (1D-array) weightings for the quadrature formula of the RK methods
- c : (1D-array) RK substeps time
- jacfun : (function handle, optional) function returning a 2D-array (Jacobian df/dy)
"""
assert y0.ndim==1, 'y0 must be 0D or 1D'
A,b,c = method['A'], method['b'], method['c']
out = scipy.integrate._ivp.ivp.OdeResult()
t = np.linspace(t_span[0], t_span[1], nt)
nx = np.size(y0)
dt = (t_span[1]-t_span[0]) / (nt-1)
s = np.size(b)
y = np.zeros((y0.size, nt))
y[:,0] = y0
K= np.zeros((np.size(y0), s))
unm1 = np.copy(y0)
warm_start_dict=None
out.nfev = 0
out.njev = 0
infodict_hist = {} # additonal optional debug storage
out.infodict_hist = infodict_hist
# de quoi itnerfacer le view newton
solver = newton.newtonSolverObj()
Dres, LU, Dresinv = None, None, None
for it, tn in enumerate(t[:-1]):
if bPrint:
if np.mod(it,np.floor(nt/10))==0:
print('\n{:.1f} %'.format(100*it/nt), end='')
if np.mod(it,np.floor(nt/100))==0:
print('.', end='')
for isub in range(s): # go through each substep
# temp = np.zeros(np.shape(y0))
# for j in range(isub):
# temp = temp + A[isub,j] * K[:,j]
# vi = unm1 + dt*( temp )
vi = unm1[:] + dt * K[:,:isub].dot( A[isub,:isub] )
if A[isub,isub]==0: # explicit step
kni = fun(tn+c[isub]*dt, vi)
else:
# solve the complete non-linear system via a Newton method
tempfun = lambda kni: kni - fun(tn+c[isub]*dt, vi + dt*A[isub,isub]*kni)
if jacfun is None:
gradRes = None
else:
gradRes = lambda kni: scipy.sparse.csc_matrix( scipy.sparse.eye(kni.shape[0]) - dt*A[isub,isub]*jacfun(tn+c[isub]*dt, vi + dt*A[isub,isub]*kni) )
if newtonchoice==0:
kni = scipy.optimize.fsolve(func= tempfun,
x0=K[:,0],
fprime=gradRes,
# band=(5,5), #gradFun
# epsfcn = 1e-7,
args=(),)
elif newtonchoice==1:
kni = scipy.optimize.newton(func= tempfun,
x0=K[:,0],
fprime=gradRes, maxiter=100,
# band=(5,5), #gradFun
# epsfcn = 1e-7,
rtol=1e-8,
args=(),)
elif newtonchoice==2: # custom damped newton
kni, infodict, warm_start_dict2 = damped_newton_solve(
fun=tempfun, x0=K[:,0],rtol=1e-9, ftol=1e-30, jacfun=gradRes, warm_start_dict=warm_start_dict,
itmax=50, jacmax=10, tau_min=1e-3, convergenceMode=0)
if infodict['ier']!=0: # Newton did not converge
print('Newton did not converge')
# restart the Newton solve with all outputs enabled
kni, infodict, warm_start_dict = damped_newton_solve(
fun=tempfun, x0=K[:,0],rtol=1e-9, ftol=1e-30, jacfun=gradRes, warm_start_dict=warm_start_dict,
itmax=50, jacmax=10, tau_min=1e-3, convergenceMode=0, bPrint=True)
# raise Exception('Newton did not converge: infodict={}'.format(infodict))
msg = 'Newton did not converge'
# raise Exception(msg)
out.y = y[:,:it+1]
out.t = t[:it+1]
out.message = msg
return out
else:
warm_start_dict=warm_start_dict2 # pour ne aps interférer avec le debug en cas de non-convergence
if fullDebug: # store additional informations about the Newton solve
if not bool(infodict_hist): # the debug dictionnary has not yet been initialised
for key in infodict.keys():
if not isinstance(infodict[key], np.ndarray) and (key!='ier' and key!='msg'): # only save single values
infodict_hist[key] = [infodict[key]]
else: # backup already initialised
for key in infodict_hist.keys():
infodict_hist[key].append(infodict[key])
out.nfev += infodict['nfev']
out.njev += infodict['njev']
elif newtonchoice==3: # custom modified newton without damping
# gradFun = lambda kni: 1 - dt*A[isub,isub]*gradF(tn+c[isub]*dt, vi + dt*A[isub,isub]*kni)
kni, Dres, LU, Dresinv = solver.solveNewton(fun=tempfun,
x0=K[:,0],
initJac=Dres,
initLU=LU,
initInv=Dresinv,
jacfun=gradRes,
options={'eps':1e-8, 'bJustOutputJacobian':False, 'nIterMax':50, 'bVectorisedModelFun':False,
'bUseComplexStep':False, 'bUseLUdecomposition':True, 'bUseInvertJacobian':False,
'bModifiedNewton':True, 'bDampedNewton':False, 'limitSolution':None,
'bDebug':False, 'bDebugPlots':False, 'nMaxBadIters':2, 'nMaxJacRecomputePerTimeStep':5} )
out.nfev = solver.nSolverCall
out.njev = solver.nJacEval
# out.nLUsolve = solver.nLinearSolve
else:
raise Exception('newton choice is not recognised')
K[:,isub] = kni #fun(tn+c[isub]*dt, ui[:,isub])
## END OF QUADRATURE STEPS --> reaffect unm1
for j in range(s):
unm1[:] = unm1[:] + dt*b[j]*K[:,j]
K[:,:] = 0.
y[:,it+1] = unm1[:]
# END OF INTEGRATION
out.y = y
out.t = t
if bPrint:
print('done')
return out
if __name__=='__main__':
import matplotlib.pyplot as plt
import rk_coeffs
#%% Single method test
#### PARAMETERS ####
name2=None
problemtype = 'stiff'
NEWTONCHOICE=3
# mod ='FIRK'
# name='Radau5'
# # name='IE'
# mod ='reverseERK'
# name='EE-sub4-last'
mod='adapt_reverseERK'
# name="Heun-Euler-modif"
# name="Heun-Euler"
# name='RK45-modif' # works
# name='RK45-4'
# name='RK45-5'
# name2='RK45-4'
name = "RK10"
name2 = "RK23"
# name="Heun-Euler"
# name2="EE"
# stabilité infinie = 1/z^ordre !!!
# embedded complètement gratuit ?!
# mod = 'ERK'
# name= 'rk4'