-
Notifications
You must be signed in to change notification settings - Fork 0
/
Magnus_Solver_adaptive_stepsize_v9.py
1539 lines (1380 loc) · 43.4 KB
/
Magnus_Solver_adaptive_stepsize_v9.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
# Magnus Solver
"""
To solve
x'(t) = A(t) x(t)
"""
"""
Using Magnus expansion derived numerical methods from
"the Magnus expansion and some of its applications"
pg. 91 - 95
and new related methods.
"""
import numpy as np
from numpy.lib.scimath import sqrt as csqrt
import time
import sympy as sym
from scipy import special, linalg
# choose numerical integrator
from scipy.integrate import quadrature as quad
from scipy.integrate import complex_ode
from scipy import optimize
#import matplotlib
#matplotlib.use("Agg")
from matplotlib import rc
rc('text', usetex=True)
import matplotlib.pyplot as plt
from matplotlib import ticker
from matplotlib import gridspec
from sys import exit as sysexit
T_start = time.time()
############# Set up Equations / A matrices ########################
"""
Define a function for the A matrix and the true solution
"""
def A_from_w2(w2, num_vs_sym):
def f(t):
if num_vs_sym:
# numpy matrix
M = np.matrix([[0, 1], [-w2(t), 0]])
elif num_vs_sym == False:
# sympy matrix
M = sym.Matrix([[0, 1], [-w2(t), 0]])
return M
return f
def Simplify(Expr):
#E1 = sym.powsimp(Expr, deep=True, force=True)
E1 = sym.simplify(Expr)
E2 = sym.nsimplify(E1)
return E2
ts0 = sym.Symbol('ts0', real=True)
ts = sym.Symbol('ts', real=True)
ts1 = sym.Symbol('ts1', real=True)
array2mat = [{'ImmutableDenseMatrix': np.matrix}, 'numpy']
array2mat_c = [{'ImmutableDenseMatrix': np.matrix}, {'sqrt': csqrt}, 'numpy']
# -- PhotonCDM equation stuff -- #
eta_0 = 0.01
k = 200
Og0 = 0.5
Ob0 = 0.5
variable = "Theta0"
def Apcdm():
A = sym.Matrix(
[[-2*Og0/ts, -k, -Ob0/2, 0, -ts*(k**2)/3 - 1/ts],
[k/3, 0, 0, 0, k/3],
[-6*Og0/ts, 0, -3*Ob0/2, -sym.I*k, -ts*k**2 - 3/ts],
[0, 0, 0, -1/(ts**2), -sym.I*k],
[-2*Og0/ts, 0, -Ob0/2, 0, -ts*(k**2)/3 - 1/ts]])
return A
A_sym_pcdm = Apcdm()
A_num_pcdm = sym.lambdify((ts), A_sym_pcdm, modules=array2mat_c)
PhotonCDM = {}
PhotonCDM["x0"] = np.array([1, 2, 1, 2, 1])
x0_string = str(PhotonCDM["x0"][0])
for i in range(1,5):
x0_string = x0_string + "_" + str(PhotonCDM["x0"][i])
if variable == "Phi":
Index = 4 # index of x_i variable to plot
PhotonCDM["name"] = "PhotonCDM_Phi_k=" + str(k) + "_x0=" + x0_string
PhotonCDM["title"] = "Radiation dominated photon and CDM system : $\\Phi$, $k = $" + str(k)
PhotonCDM["ylim"] = (-0.2, 1.00)
elif variable == "Theta0":
Index = 0 # index of x_i variable to plot
PhotonCDM["name"] = "PhotonCDM_Theta0_k=" + str(k) + "_x0=" + x0_string
PhotonCDM["title"] = "Radiation dominated photon and CDM system : $\\Theta_0$, $k = $" + str(k)
PhotonCDM["ylim"] = (-0.75, 1.05)
PhotonCDM["A_sym"] = A_sym_pcdm
PhotonCDM["A_num"] = A_num_pcdm
PhotonCDM["t_start"] = eta_0
PhotonCDM["t_stop"] = 0.5
PhotonCDM["Theta0_sol_coeff"] = [0, -1]
PhotonCDM["Phi_sol_coeff"] = [0.5, -0.5]
def PhotonCDM_Theta0_sol(t, a, b):
# define the solution for Theta0
C = a*np.cos(k*t/np.sqrt(3)) + b*np.sin(k*t/np.sqrt(3))
return C
def PhotonCDM_Phi_sol(t, a, b):
t0 = PhotonCDM["t_start"]
q = k*t/np.sqrt(3)
q0 = k*t0/np.sqrt(3)
J0 = special.spherical_jn(1,q0)/(q0)
Y0 = special.spherical_yn(1,q0)/(q0)
J = special.spherical_jn(1,q)/q
Y = special.spherical_yn(1,q)/q
C = a*(J/J0) + b*(Y/Y0)
return C
def PhotonCDM_true_sol(t):
x = np.ones((t.size, 5))
a0, b0 = PhotonCDM["Theta0_sol_coeff"]
a4, b4 = PhotonCDM["Phi_sol_coeff"]
x[:,0] = PhotonCDM_Theta0_sol(t, a0, b0)
x[:,4] = PhotonCDM_Phi_sol(t, a4, b4)
return x
PhotonCDM["true_sol"] = PhotonCDM_true_sol
# ---------------------------- #
################### Choose equation #########################
Eq = PhotonCDM
############# define some functions ##########
def eg(A, dt):
# compute the elementwise derivative of a matrix valued function
def dA(t):
dA_ = (A(t + 0.5*dt) - A(t - 0.5*dt))/dt
return dA_
return dA
def Com(A, B):
return (A*B - B*A)
#------> set up alpha functions
def alpha_D(t0, t, A, order=4):
# compute the alpha coefficients using the autograd
# derivative
h = t - t0
dt = 0.000001*h
a_1 = h*A(t0 + 0.5*h)
dA = eg(A, dt)
a_2 = (h**2)*dA(t0 + 0.5*h)
if order == 4:
return (a_1, a_2)
elif order == 6:
ddA = eg(dA, dt)
a_3 = (1/2)*(h**3)*ddA(t0 + 0.5*h)
return (a_1, a_2, a_3)
def alpha_GL(t0, t, A, order=4):
# compute the alpha coefficients using the Gauss-Legendre quadrature
# rule
h = t - t0
if order == 4:
A1 = A(t0 + (0.5 - np.sqrt(3)/6)*h)
A2 = A(t0 + (0.5 + np.sqrt(3)/6)*h)
a_1 = 0.5*h*(A1 + A2)
a_2 = (np.sqrt(3)/12)*h*(A2 - A1)
return (a_1, a_2)
elif order == 6:
A1 = A(t0 + (0.5 - 0.1*np.sqrt(15))*h)
A2 = A(t0 + 0.5*h)
A3 = A(t0 + (0.5 + 0.1*np.sqrt(15))*h)
a_1 = h*A2
a_2 = (np.sqrt(15)/3)*h*(A3 - A1)
a_3 = (10/3)*h*(A3 - 2*A2 + A1)
return (a_1, a_2, a_3)
def alpha_SNC(t0, t, A, order=4):
# compute the alpha coefficients using the Simpson and Newton–
# Cotes quadrature rules using equidistant A(t) points
h = t - t0
if order == 4:
A1 = A(t0)
A2 = A(t0 + 0.5*h)
A3 = A(t0 + h)
a_1 = (h/6)*(A1 + 4*A2 + A3)
a_2 = h*(A3 - A1)
return (a_1, a_2)
elif order == 6:
A1 = A(t0)
A2 = A(t0 + 0.25*h)
A3 = A(t0 + 0.5*h)
A4 = A(t0 + 0.75*h)
A5 = A(t0 + h)
a_1 = (1/60)*(-7*(A1 + A5) + 28*(A2 + A4) + 18*A3)
a_2 = (1/15)*(7*(A5 - A1) + 16*(A4 - A2))
a_3 = (1/3)*(7*(A1 + A5) - 4*(A2 + A4) - 6*A3)
return (a_1, a_2, a_3)
#------> set up quadrature integragrators
scipy_quad_maxiter=200
def scipy_c_quad(f, t0, t, ARGS=()):
# integrate complex valued function f(t) from t0 to t using scipy.integrate.quadrature
MAXITER=scipy_quad_maxiter
def f_real(x, *args):
f_ = f(x, *args)
return np.real(f_)
def f_imag(x, *args):
f_ = f(x, *args)
return np.imag(f_)
Int_real = quad(f_real, t0, t, args=ARGS, maxiter=MAXITER, vec_func=False)[0]
Int_imag = 1j*quad(f_imag, t0, t, args=ARGS, maxiter=MAXITER, vec_func=False)[0]
Int_ = Int_real + Int_imag
return Int_
def scipy_M_quad(A, t0, t, ARGS=()):
# integrate complex matrix valued function f(t) from t0 to t using scipy.integrate.quadrature
MAXITER=scipy_quad_maxiter
ni, nj = A(1).shape
def f_real(x, I, J, *args):
f_ = A(x, *args)[I, J]
return np.real(f_)
def f_imag(x, I, J, *args):
f_ = A(x, *args)[I, J]
return np.imag(f_)
Int_M = np.zeros((ni, nj))*(1.0+0.j)
for I in range(ni):
for J in range(nj):
IJ_ARGS = (I, J) + ARGS
Int_M[I, J] = quad(f_real, t0, t, args=IJ_ARGS, maxiter=MAXITER, vec_func=False)[0] + 1j*quad(f_imag, t0, t, args=IJ_ARGS, maxiter=MAXITER, vec_func=False)[0]
return Int_M
# set quadrature integrator (for the moment just set one)
c_quad = scipy_c_quad
#----> other functions
def Omega_num(A, alpha, order):
# function to return an Omega(t0, t) function
def Omega(t0, t):
# the Magnus expansion Omega truncated to the appropriate order in h
if order == 4:
a_1, a_2 = alpha(t0, t, A, 4)
Om = a_1 - (1/12)*Com(a_1, a_2)
return Om
elif order == 6:
a_1, a_2, a_3 = alpha(t0, t, A, 6)
C1 = Com(a_1, a_2)
C2 = -(1/60)*Com(a_1, 2*a_3 + C1)
Om = a_1 + (1/12)*a_3 + (1/240)*Com(-20*a_1-a_3+C1, a_2+C2)
return Om
return Omega
def ferr(x_0, x_l):
# a function to evaluate an error between step estimates
# returns a vector
err = np.abs(x_0 - x_l)
return err
def log_minor_ticks(ax):
locmin = ticker.LogLocator(base=10.0, subs=(0.1,0.2,0.4,0.6,0.8,1,2,4,6,8,10))
ax.yaxis.set_minor_locator(locmin)
ax.yaxis.set_minor_formatter(ticker.NullFormatter())
###################### Symbolics #########################
#
# Symbolic manipulation using sympy
A_sym = Eq["A_sym"]
print("A = ", A_sym)
print()
A_num = Eq["A_num"]
"""
define the first and second terms of the Magnus expansion (symbolic form)
Ω_1(t) = \int_t_0^t ( A(t') ) dt'
Ω_2(t) = 0.5 \int_t_0^t( \int_t_0^t'( [A(t'),A(t'')] )dt'' )dt'
"""
made_Om_1 = False
def Omega_1_sym(A):
integral = sym.integrate(A.subs(ts, ts1), (ts1, ts0, ts))
return integral
def Omega_2_sym(A):
ts2 = sym.Symbol('ts2')
integral_1 = sym.integrate(Com(A.subs(ts, ts1),A.subs(ts, ts2)), (ts2, ts0, ts1))
print("integral_1 = ", integral_1)
print()
integral_2 = sym.integrate(integral_1, (ts1, ts0, ts))
return 0.5*integral_2
def Magnus1(alpha):
def Make_func():
if alpha == "analytic":
global made_Om_1
if not made_Om_1:
Om_1 = Omega_1_sym(A_sym)
print("Omega 1 = ", sym.nsimplify(Om_1))
print()
global Omega_1_exact
Omega_1_exact = sym.lambdify((ts0, ts), Om_1, modules=array2mat)
made_Om_1 = True
Omega = Omega_1_exact
elif alpha != "analytic":
Omega = Omega_num(A_num, alpha, 4)
def Mf(t0, t):
Om = Omega(t0, t)
return linalg.expm(Om)
return Mf
return Make_func
def Magnus2(alpha):
def Make_func():
if alpha == "analytic":
global made_Om_1
if not made_Om_1:
Om_1 = Omega_1_sym(A_sym)
print("Omega 1 = ", sym.nsimplify(Om_1))
print()
global Omega_1_exact
Omega_1_exact = sym.lambdify((ts0, ts), Om_1, modules=array2mat)
made_Om_1 = True
Om_2 = Omega_2_sym(A_sym)
print("Omega 2 = ", sym.nsimplify(Om_2))
print()
Omega_2_exact = sym.lambdify((ts0, ts), Om_2, modules=array2mat)
def Omega(t0, t):
Om = Omega_1_exact(t0, t) + Omega_2_exact(t0, t)
return Om
elif alpha != "analytic":
Omega = Omega_num(A_num, alpha, 6)
def Mf(t0, t):
Om = Omega(t0, t)
return linalg.expm(Om)
return Mf
return Make_func
def Cayley(alpha, order):
# Caley method
def Make_func():
if alpha == "analytic":
# only a order 4 method available
A = A_sym.subs(ts, ts0)
Ndim = A.shape[0]
Om = Omega_1_sym(A_sym) + Omega_2_sym(A_sym)
Id = sym.eye(Ndim)
C_ = Om*(Id - (1/12)*(Om**2)*(Id - (1/10)*(Om**2)))
M_sym = (Id - (1/2)*C_).inv()*(Id + (1/2)*C_)
print("4th order Cayley matrix = ", M_sym)
print()
Mf = sym.lambdify((ts0, ts), M_sym, modules=array2mat)
return Mf
elif alpha != "analytic":
# order 4 or order 6 methods available
Omega = Omega_num(A_num, alpha, order)
Ndim = Eq["x0"].size
Id = np.identity(Ndim)
def Mf(t0, t):
Om = Omega(t0, t)
if order == 4:
C_ = Om*(Id - (1/12)*(Om**2))
elif order ==6:
C_ = Om*(Id - (1/12)*(Om**2)*(1 - (1/10)*(Om**2)))
M_ = np.linalg.inv(Id - 0.5*C_)*(Id + 0.5*C_)
return Mf
return Make_func
def w1_func(t):
return sym.sqrt(Eq["w2"](t))
def WKB_analytic():
xA = sym.cos(sym.integrate(w1_func(ts1), (ts1, ts0, ts)))/sym.sqrt(w1_func(ts))
xB = sym.sin(sym.integrate(w1_func(ts1), (ts1, ts0, ts)))/sym.sqrt(w1_func(ts))
dxA = sym.diff(xA, ts)
dxB = sym.diff(xB, ts)
x_mat = sym.Matrix([[xA, xB], [dxA, dxB]])
x_mat_0 = x_mat.subs(ts, ts0)
M_sym = x_mat*x_mat_0.inv()
print("WKB matrix = ", M_sym)
print()
Mf = sym.lambdify((ts0, ts), M_sym, modules=array2mat)
return Mf
### new methods
def Jordan_WKB(Use_numerics):
Use_Aprime2_or_J = False
def Make_func():
# symbolics
A = A_sym.subs(ts, ts0)
Aprime = sym.diff(A, ts0) + A*A
Ndim = A.shape[0]
P_0, J_0 = Aprime.jordan_form() # compute Jordan Normal form (next best thing to diagonalisation)
if Use_numerics == 0 or Use_numerics == 1:
J = sym.simplify(J_0)
P = sym.simplify(P_0)
print("JWKB:")
print("J = ", J)
print()
print("P = ", P)
print()
Pinv = P.inv()
print("Pinv = ", Pinv)
print()
dPinv = sym.diff(Pinv, ts0)
print("dPinv = ", dPinv)
print()
if Use_Aprime2_or_J:
ddPinv = sym.diff(dPinv, ts0)
print("ddPinv = ", ddPinv)
print()
Aprime2 = ddPinv*P + 2*dPinv*A*P + J
print("A'' = ", Aprime2)
print()
W2 = -Aprime2
elif not Use_Aprime2_or_J:
W2 = -J
w1_sym = []
for i in range(0, Ndim):
w2 = W2[i,i]
print("w2 = ", w2)
w1 = sym.sqrt(w2)
w1_sym.append(w1)
if Use_numerics == 0:
# symbolic version
M11 = sym.eye(Ndim)
M12 = sym.eye(Ndim)
for i in range(0, Ndim):
w1 = w1_sym[i]
C = sym.cos(sym.integrate(w1.subs(ts0, ts1), (ts1, ts0, ts)))*sym.sqrt(w1/w1.subs(ts0, ts))
S = sym.sin(sym.integrate(w1.subs(ts0, ts1), (ts1, ts0, ts)))*sym.sqrt(w1/w1.subs(ts0, ts))
dw1 = sym.diff(w1, ts0)
M11[i,i] = C + S*dw1/(2*w1**2)
M12[i,i] = S/w1
M_sym = (P.subs(ts0, ts))*(M11*Pinv + M12*(dPinv + Pinv*A))
print()
print("Jordan_WKB matrix = ", M_sym)
print()
Mf = sym.lambdify((ts0, ts), M_sym, modules=array2mat)
elif Use_numerics == 1:
# semi-numerical version
A_num = Eq["A_num"]
P_num = sym.lambdify((ts0), P, modules=array2mat_c)
Pinv_num = sym.lambdify((ts0), Pinv, modules=array2mat_c)
dPinv_num = sym.lambdify((ts0), dPinv, modules=array2mat_c)
if Use_Aprime2_or_J:
Aprime2_num = sym.lambdify((ts0), Aprime2, modules=array2mat_c)
elif not Use_Aprime2_or_J:
J_num = sym.lambdify((ts0), J, modules=array2mat_c)
Id = np.identity(Ndim)
M11 = Id.astype(np.complex64)
M12 = Id.astype(np.complex64)
w1_num = []
dw1_num = []
# convert symbolic form into numerical functions
for i in range(0, Ndim):
w1_num.append(sym.lambdify((ts0), w1_sym[i], modules=array2mat_c))
dw1_num.append(eg(w1_num[i], 0.00001))
def Mf(t0, t):
# define a function to compute the M matrix
for i in range(Ndim):
w1 = w1_num[i](t)
w10 = w1_num[i](t0)
dw10 = dw1_num[i](t0)
Int_w1 = c_quad(w1_num[i], t0, t, ARGS=())
C = np.cos(Int_w1)*csqrt(w10/w1)
S = np.sin(Int_w1)*csqrt(w10/w1)
M11[i,i] = C + S*dw10/(2*(w10)**2)
M12[i,i] = S/w10
M_ = P_num(t) @ (M11 @ Pinv_num(t0) + M12 @ (dPinv_num(t0) + Pinv_num(t0) @ A_num(t0)))
return M_
elif Use_numerics == 2:
# version minimising the amount of symbolic manipulation required
J = J_0
P = P_0
print("JWKB:")
print("J = ", J)
print()
print("P = ", P)
print()
#Pinv = P.inv()
#print("Pinv = ", Pinv)
#print()
P_num = sym.lambdify((ts0), P, modules=array2mat_c)
def Pinv_num(t):
Pt = P_num(t)
Pinvt = np.linalg.inv(Pt)
return Pinvt
J_num = sym.lambdify((ts0), J, modules=array2mat_c)
dPinv_num = eg(Pinv_num, 0.00001)
if Use_Aprime2_or_J:
ddPinv_num = eg(dP_num, 0.00001)
A_num = Eq["A_num"]
def Aprime2_num(t):
ddPinvt = ddPinv_num(t)
Pt = P_num(t)
Pinvt = np.linalg.inv(Pt)
At = A_num(t)
Jt = J_num(t)
Aprime2t = ddPinvt @ Pt + 2*dPinvt @ At @ Pt + Jt
return Aprim2t
negW2 = Aprime2_num
elif not Use_Aprime2_or_J:
negW2 = J_num
def w1_num(t, n):
return csqrt(-negW2(t)[n,n])
def w1_vec(t):
w1 = np.ones(Ndim)
W2 = - -negW2(t)
for i in range(0, Ndim):
w1[i] = csqrt(W2[i, i])
return w1
dw1 = eg(w1_vec, 0.00001)
def Mf(t0, t):
# define a function to compute the M matrix
w1 = w1_vec(t)
w10 = w1_vec(t0)
dw10 = dw1(t0)
for i in range(Ndim):
Int_w1 = c_quad(w1_sing, t0, t, ARGS=(i))
C = np.cos(Int_w1)*csqrt(w10[i]/w1[i])
S = np.sin(Int_w1)*csqrt(w10[i]/w1[i])
M11[i,i] = C + S*dw10[i]/(2*(w10[i])**2)
M12[i,i] = S/w10[i]
Pinvt0 = dPinv_num(t0)
M_ = P_num(t) @ (M11 @ Pinvt0 + M12 @ () + Pinvt0 @ A_num(t0))
return M_
return Mf
return Make_func
def Pseudo_WKB(Use_numerics):
# Pseudo-WKB method
def Make_func():
A = A_sym.subs(ts, ts0)
Ndim = A.shape[0]
Aprime = sym.diff(A, ts0) + A*A
print("A' = ", Aprime)
print()
w1_sym = []
for i in range(0, Ndim):
w2 = -Aprime[i,i]
print("w2 = ", w2)
w1 = sym.sqrt(w2)
w1_sym.append(w1)
if Use_numerics == 0:
# symbolic version
M11 = sym.eye(Ndim)
M12 = sym.eye(Ndim)
for i in range(0, Ndim):
w1 = w1_sym[i]
C = sym.cos(sym.integrate(w1.subs(ts0, ts1), (ts1, ts0, ts)))*sym.sqrt(w1/w1.subs(ts0, ts))
S = sym.sin(sym.integrate(w1.subs(ts0, ts1), (ts1, ts0, ts)))*sym.sqrt(w1/w1.subs(ts0, ts))
dw1 = sym.diff(w1, ts0)
M11[i,i] = C + S*dw1/(2*w1**2)
M12[i,i] = S/w1
M_sym = M11 + M12*A
print()
print("Pseudo-WKB matrix = ", M_sym)
print()
Mf = sym.lambdify((ts0, ts), M_sym, modules=array2mat)
elif Use_numerics == 1:
# numerical version
Ap = sym.lambdify((ts0), Aprime, modules=array2mat)
Id = np.identity(Ndim)
M11 = Id.astype(np.complex64)
M12 = Id.astype(np.complex64)
w1_num = []
dw1_num = []
# convert symbolic form into numerical functions
for i in range(0, Ndim):
w1_num.append(sym.lambdify((ts0), w1_sym[i], modules=array2mat_c))
dw1_num.append(eg(w1_num[i], 0.00001))
def Mf(t0, t):
# define a function to compute the M matrix
for i in range(Ndim):
w1 = w1_num[i](t)
w10 = w1_num[i](t0)
dw10 = dw1_num[i](t0)
Int_w1 = c_quad(w1_num[i], t0, t, ARGS=())
C = np.cos(Int_w1)*csqrt(w10/w1)
S = np.sin(Int_w1)*csqrt(w10/w1)
M11[i,i] = C + S*dw10/(2*(w10)**2)
M12[i,i] = S/w10
M_ = (M11 + M12 @ A_num(t0))
return M_
return Mf
return Make_func
def Jordan_Magnus(Lambda_only, Use_numerics):
def Make_func():
# symbolics
A = A_sym.subs(ts, ts0)
Ndim = A.shape[0]
P_, J_ = A.jordan_form() # compute Jordan Normal form (next best thing to diagonalisation)
P = sym.simplify(P_)
J = sym.simplify(J_)
print("J = ", J)
print()
print("P = ", P)
print()
Pinv = P.inv()
LK_ = J + sym.diff(Pinv, ts0)*P
LK = sym.simplify(LK_)
print("LK = ", LK)
print()
if Lambda_only:
# only use the diagonal elements
LK = sym.eye(Ndim).multiply_elementwise(LK)
print("L = ", LK)
print()
if Use_numerics == 0:
Om1 = sym.integrate(LK.subs(ts0, ts1), (ts1, ts0, ts))
print("Ω1 = ", Om1)
print()
Om1_num = sym.lambdify((ts0, ts), Om1, modules=array2mat_c)
#JM1["name"] = JM1["name"] + " (analytic)"
elif Use_numerics == 1:
LK_num = sym.lambdify((ts0), LK, modules=array2mat_c)
#
"""
for the moment just use GL quadrature order 4 (?) here
"""
Om1_num = Omega_num(LK_num, alpha_GL, 4)
P_num = sym.lambdify((ts0), P, modules=array2mat_c)
#
def Mf(t0, t):
M_ = P_num(t) @ linalg.expm(Om1_num(t0, t)) @ np.linalg.inv(P_num(t0))
return M_.astype(np.float64)
return Mf
return Make_func
def T_Jordan_Magnus(Lambda_only, Use_numerics):
def Make_func():
"""
The Jordan-Magnus method, but approximate P(t) as
P(t) = P(0) + t*P'(0) + 0.5*t^2*P''(0) + ...
"""
global started_TJM # have we started integrating?
global count_TJM # how many times have we recalculated P?
global P_TJM # current P estimate
global Mf_TJM # current Mf
#
def get_P(tp):
A_t_num = A_num(tp)
Ndim = A_t_num.shape[0]
# extract P matrix using np.linalg.
w, v = linalg.eig(A_t_num)
P = v
print("found P")
return P
dt = 0.001*0.001
def get_diffP(t):
P1 = get_P(t - 1.5*dt)
P1inv = np.linalg.inv(P1)
P2 = get_P(t - 0.5*dt)
P2inv = np.linalg.inv(P2)
P3 = get_P(t + 0.5*dt)
P3inv = np.linalg.inv(P3)
P4 = get_P(t + 1.5*dt)
P4inv = np.linalg.inv(P4)
#
dP = (P3 - P2)/(dt)
ddP = (P4 + P1 - P2 - P3)/(2*dt**2)
dddP = (P4 - 3*P3 + 3*P2 - P1)/(dt**3)
dPinv = (P3inv - P2inv)/(dt)
ddPinv = (P4inv + P1inv - P2inv - P3inv)/(2*dt**2)
dddPinv = (P4inv - 3*P3inv + 3*P2inv - P1inv)/(dt**3)
P_list = [dP, ddP, dddP, dPinv, ddPinv, dddPinv]
for P in P_list:
P = sym.sympify(P).tomatrix()
print("made P_list")
return [dP, ddP, dddP, dPinv, ddPinv, dddPinv]
#
def Make_M_from_new_P(tp):
global P_TJM
P0 = sym.sympify(get_P(tp)).tomatrix()
Pinv0 = P0.inv()
dP0, ddP0, dddP0, dPinv0, ddPinv0, dddPinv0 = get_diffP(tp)
P_sym = P0 + (ts-tp)*dP0 + 0.5*((ts-tp)**2)*ddP0 + (1/6)*((ts-tp)**3)*dddP0
print("P_sym = ", P_sym)
Pinv_sym = Pinv0 + (ts-tp)*dPinv0 + 0.5*((ts-tp)**2)*ddPinv0 + (1/6)*((ts-tp)**3)*dddPinv0
print("Pinv_sym = ", Pinv_sym)
dPinv_sym = dPinv0 + (ts-tp)*ddPinv0 + 0.5*((ts-tp)**2)*dddPinv0
print("dPinv_sym = ", dPinv_sym)
LK_sym = Pinv_sym @ A_sym @ P_sym + dPinv_sym @ P_sym
print("LK_sym = ", LK_sym)
sysexit()
if Use_numerics == 0:
if Lambda_only:
# only use the diagonal elements
LK_sym = sym.eye(Ndim).multiply_elementwise(LK_sym)
print("L = ", LK_sym)
print()
Om1 = sym.integrate(LK_sym.subs(ts, ts1), (ts1, ts0, ts))
Om1_num = sym.lambdify((ts0, ts), Om1, modules=array2mat_c)
elif Use_numerics == 1:
LK_num = sym.lambdify((ts), LK_sym, modules=array2mat_c)
def Omega_num(t0, t):
Om = M_quad(LK_num, t0, t, MAXITER=quad_maxiter)
return Om
Om1_num = Omega_num
P_num = sym.lambdify((ts), P_sym, modules=array2mat_c)
Pinv_num = sym.lambdify((ts), Pinv_sym, modules=array2mat_c)
P0_num = P_num(tp)
P_TJM = P_num # store the P_num function
def Mf(t0, t):
M_ = P_num(t) @ linalg.expm(Om1_num(t0, t)) @ Pinv_num(t0)
return M_ #.astype(np.complex128)
return Mf
#
started_TJM = False
count_TJM = 0
def M_func_adaptive(t0, t):
global started_TJM, count_TJM, P_TJM, Mf_TJM
t_mid = 0.5*(t + t0)
# get first P matrix at t=t0
if not started_TJM:
Mf_TJM = Make_M_from_new_P(t_mid)
started_TJM = True
# check 10 times to see if P(t) need to be re-evaluated
count = np.floor(10*(t_mid - Eq["t_start"])/((Eq["t_stop"] - Eq["t_start"])))
# do I need to check if we need to change P?
if count > count_TJM:
count_TJM = count
# check to see if we need to change P
P_old = P_TJM(t_mid)
P_new = sym.matrix2numpy(get_P(t_mid), dtype=np.complex128)
dP_norm = np.linalg.norm(P_new - P_old, ord='fro')
#print(" count = " + str(count) + ", dP_norm = ", dP_norm)
if dP_norm > 0:
#print(P_new)
#print(" making new P estimate, t_mid = ", t_mid)
Mf_TJM = Make_M_from_new_P(t_mid)
M_ = Mf_TJM(t0, t)
return M_
return M_func_adaptive
return Make_func
def Ext_Pseudo_WKB(Use_numerics):
# Extended Pseudo-WKB method
def Make_func():
A = A_sym.subs(ts, ts0)
Ndim = A.shape[0]
Id_sym = sym.eye(Ndim)
Aprime = sym.diff(A, ts0) + A*A
print("A' = ", Aprime)
print()
Ainv = A.inv()
w1d_sym = []
gamma_sym = []
for i in range(0, Ndim):
# extract diagonal elements of various matrices
Ap_ = Aprime[i, i]
A_ = A[i, i]
Ainv_ = Ainv[i, i]
ApAinv_ = (Aprime @ Ainv)[i, i]
#
w2 = (ApAinv_*A_ - Ap_)/(1 - A_*Ainv_)
gamma = (Ainv_*Ap_ - ApAinv_)/(1 - A_*Ainv_)
#w1 = sym.sqrt(w2)
print("w2 = ", w2)
print("gamma = ", gamma)
w1d = sym.sqrt(w2 - (gamma**2)/4)
w1d_sym.append(w1d)
gamma_sym.append(gamma)
if Use_numerics == 0:
# symbolic version
M11 = sym.eye(Ndim)
M12 = sym.eye(Ndim)
for i in range(0, Ndim):
w1d = w1d_sym[i]
gamma = gamma_sym[i]
Int_gamma = sym.integrate(gamma.subs(ts0, ts1), (ts1, ts0, ts))
C = sym.exp(-(1/2)*Int_gamma)*sym.cos(sym.integrate(w1d.subs(ts0, ts1), (ts1, ts0, ts)))*sym.sqrt(w1d/w1d.subs(ts0, ts))
S = sym.exp(-(1/2)*Int_gamma)*sym.sin(sym.integrate(w1d.subs(ts0, ts1), (ts1, ts0, ts)))*sym.sqrt(w1d/w1d.subs(ts0, ts))
dw1d = sym.diff(w1d, ts0)
M11[i,i] = C + S*(gamma/2*w1d + dw1d/(2*w1d**2))
M12[i,i] = S/w1d
M_sym = M11 + M12*A
print()
print("Ext-Pseudo-WKB matrix = ", M_sym)
print()
Mf = sym.lambdify((ts0, ts), M_sym, modules=array2mat)
elif Use_numerics == 1:
# numerical version
Id = np.identity(Ndim)
M11 = Id.astype(np.complex64)
M12 = Id.astype(np.complex64)
w1d_num = []
gamma_num = []
dw1d_num = []
# convert symbolic forms into numerical functions
for i in range(0, Ndim):
w1d_num.append(sym.lambdify((ts0), w1d_sym[i], modules=array2mat_c))
gamma_num.append(sym.lambdify((ts0), gamma_sym[i], modules=array2mat_c))
dw1d_num.append(eg(w1d_num[i], 0.00001))
def Mf(t0, t):
# define a function to compute the M matrix
Int_w1d = Id
for i in range(Ndim):
w1d = w1d_num[i](t)
w1d0 = w1d_num[i](t0)
dw1d0 = dw1d_num[i](t0)
g0 = gamma_num[i](t0)
Int_gamma = c_quad(gamma_num[i], t0, t)
Int_w1d = c_quad(w1d_num[i], t0, t)
C = np.exp(-0.5*Int_gamma)*np.cos(Int_w1d)*csqrt(w1d0/w1d)
S = np.exp(-0.5*Int_gamma)*np.sin(Int_w1d)*csqrt(w1d0/w1d)
M11[i,i] = C + S*(g0/(2*w1d0) + dw1d0/(2*(w1d0)**2))
M12[i,i] = S/w1d0
M_ = (M11 + M12 @ A_num(t0))
return M_
return Mf
return Make_func
def Modified_M1(Use_numerics, alpha):
# modified Magnus expansion from Iserles 2002a
# "ON THE GLOBAL ERROR OF DISCRETIZATION METHODS ... "
def Make_func():
A = A_sym.subs(ts, ts0)
h = sym.Symbol("h", nonzero=True)
t_half = sym.Symbol("t_half")
A_half = A.subs(ts0, t_half)
"""
def B(t):
A_t = A.subs(ts0, t)
B = sym.exp((ts0 - t)*A_half)*(A_t - A_half)*sym.exp((t - ts0)*A_half)
return B
"""
B_ = sym.exp(-h*A_half)*(A.subs(ts0, ts1) - A_half)*sym.exp(h*A_half)
B_ = sym.nsimplify(B_)
B_ = B_.rewrite(sym.cos)
B_ = sym.simplify(B_)
print("B = ", B_)
print()
if Use_numerics == 0:
Om = sym.integrate(B_, (ts1, ts0, ts))
Om_ = Om.subs({h:ts - ts0, t_half: (1/2)*(ts + ts0)})
print("Om = ", Om_)
print()
M_sym = sym.exp(h*A_half)*sym.exp(Om)
M_sym_ = M_sym.subs({h:ts - ts0, t_half: (1/2)*(ts + ts0)})
print("Modified Magnus 1 matrix = ", M_sym_)
print()
Mf = sym.lambdify((ts0, ts), M_sym_, modules=array2mat_c)
elif Use_numerics == 1:
A_half_ = A_half.subs(t_half, (1/2)*(ts0 + ts))
A_half_num = sym.lambdify((ts0, ts), A_half_, modules=array2mat)
def B_num(t1, t0, t):
A_t = Eq["A_num"](t1)
A_h = A_half_num(t0, t)
B = linalg.expm((t0 - t)*A_h) @ (A_t - A_h) @ linalg.expm((t - t0)*A_h)
return B
"""
B_ = B(ts1)
B_num = sym.lambdify((ts1, ts0, ts), B_, modules=array2mat_c)
"""
def Omega_B_num(t0, t):
def A(t1):
A_ = B_num(t1, t0, t)
return A_
a_1, a_2 = alpha(t0, t, A, 4)
Om = a_1 - (1/12)*Com(a_1, a_2)
return Om
#
def Mf(t0, t):
M_ = linalg.expm((t-t0)*A_half_num(t0, t)) @ linalg.expm(Omega_B_num(t0, t))
return M_
return Mf
return Make_func
###### set up integrator dictionaries #########################
"""
maybe put some other settings in here to make using different integrators easier?
"""
RKF45 = {
"name" : "RKF 4(5)",
"fname" : "RKF45"
}
M1 = {
"name" : "Magnus with $\\Omega_1$, analytic func.",
"fname" : "M1",
"alpha" : "analytic",
"order" : 2,
"Mfunc" : Magnus1("analytic")
}
M2 = {
"name" : "Magnus with $\\Omega_1+\\Omega_2$, analytic func.",
"fname" : "M2",
"alpha" : "analytic",
"order" : 4,
"Mfunc" : Magnus2("analytic")
}
M4_GL = {
"name" : "Magnus 4$^\\circ$, GL quad",
"fname" : "M4GL",
"alpha" : alpha_GL,
"order" : 4,
"Mfunc" : Magnus1(alpha_GL)
}
M4_D = {
"name" : "Magnus 4$^\\circ$, num. diff",
"fname" : "M4D",
"alpha" : alpha_D,
"order" : 4,
"Mfunc" : Magnus1(alpha_D)
}
M4_SNC = {
"name" : "Magnus 4$^\\circ$, Simpson quad",
"fname" : "M4SNC",
"alpha" : alpha_SNC,
"order" : 4,
"Mfunc" : Magnus1(alpha_SNC)
}
M6_D = {
"name" : "Magnus 6$^\\circ$, num. diff",
"fname" : "M6D",
"alpha" : alpha_D,
"order" : 6,
"Mfunc" : Magnus2(alpha_D)
}
M6_GL = {
"name" : "Magnus 6$^\\circ$, GL quad",
"fname" : "M6GL",
"alpha" : alpha_GL,
"order" : 6,
"Mfunc" : Magnus2(alpha_GL)
}
M6_SNC = {
"name" : "Magnus 6$^\\circ$, NC quad",
"fname" : "M6SNC",
"alpha" : alpha_SNC,
"order" : 6,
"Mfunc" : Magnus2(alpha_SNC)
}
WKB = {
"name" : "WKB, analytic",
"fname" : "WKB",
"order" : 4,
"Mfunc" : WKB_analytic
}
C4_GL = {
"name" : "Cayley 4$^\\circ$, GL quad",
"fname" : "C4GL",
"alpha" : alpha_GL,
"order" : 4,
"Mfunc" : Cayley(alpha_GL, 4)
}