-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
hyperexpand.py
2495 lines (2066 loc) · 82 KB
/
hyperexpand.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
"""
Expand Hypergeometric (and Meijer G) functions into named
special functions.
The algorithm for doing this uses a collection of lookup tables of
hypergeometric functions, and various of their properties, to expand
many hypergeometric functions in terms of special functions.
It is based on the following paper:
Kelly B. Roach. Meijer G Function Representations.
In: Proceedings of the 1997 International Symposium on Symbolic and
Algebraic Computation, pages 205-211, New York, 1997. ACM.
It is described in great(er) detail in the Sphinx documentation.
"""
# SUMMARY OF EXTENSIONS FOR MEIJER G FUNCTIONS
#
# o z**rho G(ap, bq; z) = G(ap + rho, bq + rho; z)
#
# o denote z*d/dz by D
#
# o It is helpful to keep in mind that ap and bq play essentially symmetric
# roles: G(1/z) has slightly altered parameters, with ap and bq interchanged.
#
# o There are four shift operators:
# A_J = b_J - D, J = 1, ..., n
# B_J = 1 - a_j + D, J = 1, ..., m
# C_J = -b_J + D, J = m+1, ..., q
# D_J = a_J - 1 - D, J = n+1, ..., p
#
# A_J, C_J increment b_J
# B_J, D_J decrement a_J
#
# o The corresponding four inverse-shift operators are defined if there
# is no cancellation. Thus e.g. an index a_J (upper or lower) can be
# incremented if a_J != b_i for i = 1, ..., q.
#
# o Order reduction: if b_j - a_i is a non-negative integer, where
# j <= m and i > n, the corresponding quotient of gamma functions reduces
# to a polynomial. Hence the G function can be expressed using a G-function
# of lower order.
# Similarly if j > m and i <= n.
#
# Secondly, there are paired index theorems [Adamchik, The evaluation of
# integrals of Bessel functions via G-function identities]. Suppose there
# are three parameters a, b, c, where a is an a_i, i <= n, b is a b_j,
# j <= m and c is a denominator parameter (i.e. a_i, i > n or b_j, j > m).
# Suppose further all three differ by integers.
# Then the order can be reduced.
# TODO work this out in detail.
#
# o An index quadruple is called suitable if its order cannot be reduced.
# If there exists a sequence of shift operators transforming one index
# quadruple into another, we say one is reachable from the other.
#
# o Deciding if one index quadruple is reachable from another is tricky. For
# this reason, we use hand-built routines to match and instantiate formulas.
#
from collections import defaultdict
from itertools import chain, product
from .. import DIOFANT_DEBUG
from ..core import (Add, Dummy, EulerGamma, Expr, I, Integer, Mod, Mul,
Rational, Tuple, expand, expand_func, nan, oo, pi, symbols,
sympify, zoo)
from ..functions import (Chi, Ci, Ei, Piecewise, Shi, Si, besseli, besselj,
ceiling, cos, cosh, elliptic_e, elliptic_k, erf, exp,
exp_polar, expint, factorial, floor, fresnelc,
fresnels, gamma, lerchphi, log, lowergamma,
polar_lift, polarify, re, rf, root, sin, sinh, sqrt,
unpolarify, uppergamma)
from ..functions.special.hyper import (HyperRep_asin1, HyperRep_asin2,
HyperRep_atanh, HyperRep_cosasin,
HyperRep_log1, HyperRep_log2,
HyperRep_power1, HyperRep_power2,
HyperRep_sinasin, HyperRep_sqrts1,
HyperRep_sqrts2, hyper, meijerg)
from ..polys import Poly, cancel
from ..printing import sstr
from ..series import residue
from ..utilities import default_sort_key, sift
from .powsimp import powdenest
from .simplify import simplify
# function to define "buckets"
def _mod1(x):
# TODO see if this can work as Mod(x, 1); this will require
# different handling of the "buckets" since these need to
# be sorted and that fails when there is a mixture of
# integers and expressions with parameters. With the current
# Mod behavior, Mod(k, 1) == Mod(1, 1) == 0 if k is an integer.
# Although the sorting can be done with Basic.compare, this may
# still require different handling of the sorted buckets.
if x.is_Number:
return Mod(x, 1)
c, x = x.as_coeff_Add()
return Mod(c, 1) + x
# leave add formulae at the top for easy reference
def add_formulae(formulae):
"""Create our knowledge base."""
from ..matrices import Matrix
a, b, c, z = symbols('a b c, z', cls=Dummy)
def add(ap, bq, res):
func = Hyper_Function(ap, bq)
formulae.append(Formula(func, z, res, (a, b, c)))
def addb(ap, bq, B, C, M):
func = Hyper_Function(ap, bq)
formulae.append(Formula(func, z, None, (a, b, c), B, C, M))
# Luke, Y. L. (1969), The Special Functions and Their Approximations,
# Volume 1, section 6.2
# 0F0
add((), (), exp(z))
# 1F0
add((a, ), (), HyperRep_power1(-a, z))
# 2F1
addb((a, a - Rational(1, 2)), (2*a, ),
Matrix([HyperRep_power2(a, z),
HyperRep_power2(a + Rational(1, 2), z)/2]),
Matrix([[1, 0]]),
Matrix([[(a - Rational(1, 2))*z/(1 - z), (Rational(1, 2) - a)*z/(1 - z)],
[a/(1 - z), a*(z - 2)/(1 - z)]]))
addb((1, 1), (2, ),
Matrix([HyperRep_log1(z), 1]), Matrix([[-1/z, 0]]),
Matrix([[0, z/(z - 1)], [0, 0]]))
addb((Rational(1, 2), 1), (Rational(3, 2), ),
Matrix([HyperRep_atanh(z), 1]),
Matrix([[1, 0]]),
Matrix([[-Rational(1, 2), 1/(1 - z)/2], [0, 0]]))
addb((Rational(1, 2), Rational(1, 2)), (Rational(3, 2), ),
Matrix([HyperRep_asin1(z), HyperRep_power1(-Rational(1, 2), z)]),
Matrix([[1, 0]]),
Matrix([[-Rational(1, 2), Rational(1, 2)], [0, z/(1 - z)/2]]))
addb((a, Rational(1, 2) + a), (Rational(1, 2), ),
Matrix([HyperRep_sqrts1(-a, z), -HyperRep_sqrts2(-a - Rational(1, 2), z)]),
Matrix([[1, 0]]),
Matrix([[0, -a],
[z*(-2*a - 1)/2/(1 - z), Rational(1, 2) - z*(-2*a - 1)/(1 - z)]]))
# A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990).
# Integrals and Series: More Special Functions, Vol. 3,.
# Gordon and Breach Science Publisher
addb([a, -a], [Rational(1, 2)],
Matrix([HyperRep_cosasin(a, z), HyperRep_sinasin(a, z)]),
Matrix([[1, 0]]),
Matrix([[0, -a], [a*z/(1 - z), 1/(1 - z)/2]]))
addb([1, 1], [3*Rational(1, 2)],
Matrix([HyperRep_asin2(z), 1]), Matrix([[1, 0]]),
Matrix([[(z - Rational(1, 2))/(1 - z), 1/(1 - z)/2], [0, 0]]))
# Complete elliptic integrals K(z) and E(z), both a 2F1 function
addb([Rational(1, 2), Rational(1, 2)], [Integer(1)],
Matrix([elliptic_k(z), elliptic_e(z)]),
Matrix([[2/pi, 0]]),
Matrix([[-Rational(1, 2), -1/(2*z-2)],
[-Rational(1, 2), Rational(1, 2)]]))
addb([-Rational(1, 2), Rational(1, 2)], [Integer(1)],
Matrix([elliptic_k(z), elliptic_e(z)]),
Matrix([[0, 2/pi]]),
Matrix([[-Rational(1, 2), -1/(2*z-2)],
[-Rational(1, 2), Rational(1, 2)]]))
# 3F2
addb([-Rational(1, 2), 1, 1], [Rational(1, 2), 2],
Matrix([z*HyperRep_atanh(z), HyperRep_log1(z), 1]),
Matrix([[-Rational(2, 3), -1/(3*z), Rational(2, 3)]]),
Matrix([[Rational(1, 2), 0, z/(1 - z)/2],
[0, 0, z/(z - 1)],
[0, 0, 0]]))
# actually the formula for 3/2 is much nicer ...
addb([-Rational(1, 2), 1, 1], [2, 2],
Matrix([HyperRep_power1(Rational(1, 2), z), HyperRep_log2(z), 1]),
Matrix([[Rational(4, 9) - 16/(9*z), 4/(3*z), 16/(9*z)]]),
Matrix([[z/2/(z - 1), 0, 0], [1/(2*(z - 1)), 0, Rational(1, 2)], [0, 0, 0]]))
# 1F1
addb([1], [b], Matrix([z**(1 - b) * exp(z) * lowergamma(b - 1, z), 1]),
Matrix([[b - 1, 0]]), Matrix([[1 - b + z, 1], [0, 0]]))
addb([a], [2*a],
Matrix([z**(Rational(1, 2) - a)*exp(z/2)*besseli(a - Rational(1, 2), z/2)
* gamma(a + Rational(1, 2))/4**(Rational(1, 2) - a),
z**(Rational(1, 2) - a)*exp(z/2)*besseli(a + Rational(1, 2), z/2)
* gamma(a + Rational(1, 2))/4**(Rational(1, 2) - a)]),
Matrix([[1, 0]]),
Matrix([[z/2, z/2], [z/2, (z/2 - 2*a)]]))
mz = polar_lift(-1)*z
addb([a], [a + 1],
Matrix([mz**(-a)*a*lowergamma(a, mz), a*exp(z)]),
Matrix([[1, 0]]),
Matrix([[-a, 1], [0, z]]))
# This one is redundant.
add([-Rational(1, 2)], [Rational(1, 2)], exp(z) - sqrt(pi*z)*(-I)*erf(I*sqrt(z)))
# Added to get nice results for Laplace transform of Fresnel functions
# http://functions.wolfram.com/07.22.03.6437.01
# Basic rule
# add([1], [Rational(3, 4), Rational(5, 4)],
# sqrt(pi) * (cos(2*sqrt(polar_lift(-1)*z))*fresnelc(2*root(polar_lift(-1)*z,4)/sqrt(pi)) +
# sin(2*sqrt(polar_lift(-1)*z))*fresnels(2*root(polar_lift(-1)*z,4)/sqrt(pi)))
# / (2*root(polar_lift(-1)*z,4)))
# Manually tuned rule
addb([1], [Rational(3, 4), Rational(5, 4)],
Matrix([ sqrt(pi)*(I*sinh(2*sqrt(z))*fresnels(2*root(z, 4)*exp(I*pi/4)/sqrt(pi))
+ cosh(2*sqrt(z))*fresnelc(2*root(z, 4)*exp(I*pi/4)/sqrt(pi)))
* exp(-I*pi/4)/(2*root(z, 4)),
sqrt(pi)*root(z, 4)*(sinh(2*sqrt(z))*fresnelc(2*root(z, 4)*exp(I*pi/4)/sqrt(pi))
+ I*cosh(2*sqrt(z))*fresnels(2*root(z, 4)*exp(I*pi/4)/sqrt(pi)))
* exp(-I*pi/4)/2,
1 ]),
Matrix([[1, 0, 0]]),
Matrix([[-Rational(1, 4), 1, Rational(1, 4)],
[ z, Rational(1, 4), 0 ],
[ 0, 0, 0 ]]))
# 2F2
addb([Rational(1, 2), a], [Rational(3, 2), a + 1],
Matrix([a/(2*a - 1)*(-I)*sqrt(pi/z)*erf(I*sqrt(z)),
a/(2*a - 1)*(polar_lift(-1)*z)**(-a) *
lowergamma(a, polar_lift(-1)*z),
a/(2*a - 1)*exp(z)]),
Matrix([[1, -1, 0]]),
Matrix([[-Rational(1, 2), 0, 1], [0, -a, 1], [0, 0, z]]))
# We make a "basis" of four functions instead of three, and give EulerGamma
# an extra slot (it could just be a coefficient to 1). The advantage is
# that this way Polys will not see multivariate polynomials (it treats
# EulerGamma as an indeterminate), which is *way* faster.
addb([1, 1], [2, 2],
Matrix([Ei(z) - log(z), exp(z), 1, EulerGamma]),
Matrix([[1/z, 0, 0, -1/z]]),
Matrix([[0, 1, -1, 0], [0, z, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]))
# 0F1
add((), (Rational(1, 2), ), cosh(2*sqrt(z)))
addb([], [b],
Matrix([gamma(b)*z**((1 - b)/2)*besseli(b - 1, 2*sqrt(z)),
gamma(b)*z**(1 - b/2)*besseli(b, 2*sqrt(z))]),
Matrix([[1, 0]]), Matrix([[0, 1], [z, (1 - b)]]))
# 0F3
x = 4*root(z, 4)
def fp(a, z):
return besseli(a, x) + besselj(a, x)
def fm(a, z):
return besseli(a, x) - besselj(a, x)
# TODO branching
addb([], [Rational(1, 2), a, a + Rational(1, 2)],
Matrix([fp(2*a - 1, z), fm(2*a, z)*root(z, 4),
fm(2*a - 1, z)*sqrt(z), fp(2*a, z)*z**Rational(3, 4)])
* 2**(-2*a)*gamma(2*a)*z**((1 - 2*a)/4),
Matrix([[1, 0, 0, 0]]),
Matrix([[0, 1, 0, 0],
[0, Rational(1, 2) - a, 1, 0],
[0, 0, Rational(1, 2), 1],
[z, 0, 0, 1 - a]]))
x = 2*root(4*z, 4)*exp_polar(I*pi/4)
addb([], [a, a + Rational(1, 2), 2*a],
(2*sqrt(polar_lift(-1)*z))**(1 - 2*a)*gamma(2*a)**2 *
Matrix([besselj(2*a - 1, x)*besseli(2*a - 1, x),
x*(besseli(2*a, x)*besselj(2*a - 1, x)
- besseli(2*a - 1, x)*besselj(2*a, x)),
x**2*besseli(2*a, x)*besselj(2*a, x),
x**3*(besseli(2*a, x)*besselj(2*a - 1, x)
+ besseli(2*a - 1, x)*besselj(2*a, x))]),
Matrix([[1, 0, 0, 0]]),
Matrix([[0, Rational(1, 4), 0, 0],
[0, (1 - 2*a)/2, -Rational(1, 2), 0],
[0, 0, 1 - 2*a, Rational(1, 4)],
[-32*z, 0, 0, 1 - a]]))
# 1F2
addb([a], [a - Rational(1, 2), 2*a],
Matrix([z**(Rational(1, 2) - a)*besseli(a - Rational(1, 2), sqrt(z))**2,
z**(1 - a)*besseli(a - Rational(1, 2), sqrt(z))
* besseli(a - Rational(3, 2), sqrt(z)),
z**(Rational(3, 2) - a)*besseli(a - Rational(3, 2), sqrt(z))**2]),
Matrix([[-gamma(a + Rational(1, 2))**2/4**(Rational(1, 2) - a),
2*gamma(a - Rational(1, 2))*gamma(a + Rational(1, 2))/4**(1 - a),
0]]),
Matrix([[1 - 2*a, 1, 0], [z/2, Rational(1, 2) - a, Rational(1, 2)], [0, z, 0]]))
addb([Rational(1, 2)], [b, 2 - b],
pi*(1 - b)/sin(pi*b) *
Matrix([besseli(1 - b, sqrt(z))*besseli(b - 1, sqrt(z)),
sqrt(z)*(besseli(-b, sqrt(z))*besseli(b - 1, sqrt(z))
+ besseli(1 - b, sqrt(z))*besseli(b, sqrt(z))),
besseli(-b, sqrt(z))*besseli(b, sqrt(z))]),
Matrix([[1, 0, 0]]),
Matrix([[b - 1, Rational(1, 2), 0],
[z, 0, z],
[0, Rational(1, 2), -b]]))
addb([Rational(1, 2)], [Rational(3, 2), Rational(3, 2)],
Matrix([Shi(2*sqrt(z))/2/sqrt(z), sinh(2*sqrt(z))/2/sqrt(z),
cosh(2*sqrt(z))]),
Matrix([[1, 0, 0]]),
Matrix([[-Rational(1, 2), Rational(1, 2), 0], [0, -Rational(1, 2), Rational(1, 2)], [0, 2*z, 0]]))
# FresnelS
# Basic rule
# add([Rational(3, 4)], [Rational(3, 2),Rational(7, 4)], 6*fresnels( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) / ( pi * (exp(pi*I/4)*root(z,4)*2/sqrt(pi))**3 ) )
# Manually tuned rule
addb([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)],
Matrix(
[ fresnels(
exp(
pi*I/4)*root(
z, 4)*2/sqrt(
pi) ) / (
pi * (exp(pi*I/4)*root(z, 4)*2/sqrt(pi))**3 ),
sinh(2*sqrt(z))/sqrt(z),
cosh(2*sqrt(z)) ]),
Matrix([[6, 0, 0]]),
Matrix([[-Rational(3, 4), Rational(1, 16), 0],
[ 0, -Rational(1, 2), 1],
[ 0, z, 0]]))
# FresnelC
# Basic rule
# add([Rational(1, 4)], [Rational(1, 2),Rational(5, 4)], fresnelc( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) / ( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) )
# Manually tuned rule
addb([Rational(1, 4)], [Rational(1, 2), Rational(5, 4)],
Matrix(
[ sqrt(
pi)*exp(
-I*pi/4)*fresnelc(
2*root(z, 4)*exp(I*pi/4)/sqrt(pi))/(2*root(z, 4)),
cosh(2*sqrt(z)),
sinh(2*sqrt(z))*sqrt(z) ]),
Matrix([[1, 0, 0]]),
Matrix([[-Rational(1, 4), Rational(1, 4), 0 ],
[ 0, 0, 1 ],
[ 0, z, Rational(1, 2)]]))
# 2F3
# XXX with this five-parameter formula is pretty slow with the current
# Formula.find_instantiations (creates 2!*3!*3**(2+3) ~ 3000
# instantiations ... But it's not too bad.
addb([a, a + Rational(1, 2)], [2*a, b, 2*a - b + 1],
gamma(b)*gamma(2*a - b + 1) * (sqrt(z)/2)**(1 - 2*a) *
Matrix([besseli(b - 1, sqrt(z))*besseli(2*a - b, sqrt(z)),
sqrt(z)*besseli(b, sqrt(z))*besseli(2*a - b, sqrt(z)),
sqrt(z)*besseli(b - 1, sqrt(z))*besseli(2*a - b + 1, sqrt(z)),
besseli(b, sqrt(z))*besseli(2*a - b + 1, sqrt(z))]),
Matrix([[1, 0, 0, 0]]),
Matrix([[0, Rational(1, 2), Rational(1, 2), 0],
[z/2, 1 - b, 0, z/2],
[z/2, 0, b - 2*a, z/2],
[0, Rational(1, 2), Rational(1, 2), -2*a]]))
# (C/f above comment about eulergamma in the basis).
addb([1, 1], [2, 2, Rational(3, 2)],
Matrix([Chi(2*sqrt(z)) - log(2*sqrt(z)),
cosh(2*sqrt(z)), sqrt(z)*sinh(2*sqrt(z)), 1, EulerGamma]),
Matrix([[1/z, 0, 0, 0, -1/z]]),
Matrix([[0, Rational(1, 2), 0, -Rational(1, 2), 0],
[0, 0, 1, 0, 0],
[0, z, Rational(1, 2), 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]))
# 3F3
# This is rule: http://functions.wolfram.com/07.31.03.0134.01
# Initial reason to add it was a nice solution for
# integrate(erf(a*z)/z**2, z) and same for erfc and erfi.
# Basic rule
# add([1, 1, a], [2, 2, a+1], (a/(z*(a-1)**2)) *
# (1 - (-z)**(1-a) * (gamma(a) - uppergamma(a,-z))
# - (a-1) * (EulerGamma + uppergamma(0,-z) + log(-z))
# - exp(z)))
# Manually tuned rule
addb([1, 1, a], [2, 2, a+1],
Matrix([a*(log(-z) + expint(1, -z) + EulerGamma)/(z*(a**2 - 2*a + 1)),
a*(-z)**(-a)*(gamma(a) - uppergamma(a, -z))/(a - 1)**2,
a*exp(z)/(a**2 - 2*a + 1),
a/(z*(a**2 - 2*a + 1))]),
Matrix([[1-a, 1, -1/z, 1]]),
Matrix([[-1, 0, -1/z, 1],
[0, -a, 1, 0],
[0, 0, z, 0],
[0, 0, 0, -1]]))
def add_meijerg_formulae(formulae):
from ..matrices import Matrix
a, b, c, z = list(map(Dummy, 'abcz'))
rho = Dummy('rho')
def add(an, ap, bm, bq, B, C, M, matcher):
formulae.append(MeijerFormula(an, ap, bm, bq, z, [a, b, c, rho],
B, C, M, matcher))
def detect_uppergamma(func):
x = func.an[0]
y, z = func.bm
swapped = False
if not _mod1((x - y).simplify()):
swapped = True
(y, z) = (z, y)
if _mod1((x - z).simplify()) or x - z > 0:
return
l = [y, x]
if swapped:
l = [x, y]
return {rho: y, a: x - y}, G_Function([x], [], l, [])
add([a + rho], [], [rho, a + rho], [],
Matrix([gamma(1 - a)*z**rho*exp(z)*uppergamma(a, z),
gamma(1 - a)*z**(a + rho)]),
Matrix([[1, 0]]),
Matrix([[rho + z, -1], [0, a + rho]]),
detect_uppergamma)
def detect_3113(func):
"""http://functions.wolfram.com/07.34.03.0984.01"""
x = func.an[0]
u, v, w = func.bm
if _mod1((u - v).simplify()) == 0:
if _mod1((v - w).simplify()) == 0:
return
sig = (Rational(1, 2), Rational(1, 2), Integer(0))
x1, x2, y = u, v, w
else:
if _mod1((x - u).simplify()) == 0:
sig = (Rational(1, 2), Integer(0), Rational(1, 2))
x1, y, x2 = u, v, w
else:
sig = (Integer(0), Rational(1, 2), Rational(1, 2))
y, x1, x2 = u, v, w
if (_mod1((x - x1).simplify()) != 0 or
_mod1((x - x2).simplify()) != 0 or
_mod1((x - y).simplify()) != Rational(1, 2) or
x - x1 > 0 or x - x2 > 0):
return
return {a: x}, G_Function([x], [], [x - Rational(1, 2) + t for t in sig], [])
s = sin(2*sqrt(z))
c_ = cos(2*sqrt(z))
S_ = Si(2*sqrt(z)) - pi/2
C = Ci(2*sqrt(z))
add([a], [], [a, a, a - Rational(1, 2)], [],
Matrix([sqrt(pi)*z**(a - Rational(1, 2))*(c_*S_ - s*C),
sqrt(pi)*z**a*(s*S_ + c_*C),
sqrt(pi)*z**a]),
Matrix([[-2, 0, 0]]),
Matrix([[a - Rational(1, 2), -1, 0], [z, a, Rational(1, 2)], [0, 0, a]]),
detect_3113)
def make_simp(z):
"""Create a function that simplifies rational functions in ``z``."""
def simp(expr):
"""Efficiently simplify the rational function ``expr``."""
return cancel(expr, z)
return simp
def debug(*args):
if DIOFANT_DEBUG:
for a in args:
print(a, end='')
print()
class Hyper_Function(Expr):
"""A generalized hypergeometric function."""
def __new__(cls, ap, bq):
obj = super().__new__(cls)
obj.ap = Tuple(*list(map(expand, ap)))
obj.bq = Tuple(*list(map(expand, bq)))
return obj
@property
def args(self):
return self.ap, self.bq
@property
def sizes(self):
return len(self.ap), len(self.bq)
@property
def gamma(self):
"""
Number of upper parameters that are negative integers
This is a transformation invariant.
"""
return sum(bool(x.is_integer and x.is_negative) for x in self.ap)
def _hashable_content(self):
return super()._hashable_content() + (self.ap, self.bq)
def __call__(self, arg):
return hyper(self.ap, self.bq, arg)
def build_invariants(self):
"""
Compute the invariant vector.
The invariant vector is:
(gamma, ((s1, n1), ..., (sk, nk)), ((t1, m1), ..., (tr, mr)))
where gamma is the number of integer a < 0,
s1 < ... < sk
nl is the number of parameters a_i congruent to sl mod 1
t1 < ... < tr
ml is the number of parameters b_i congruent to tl mod 1
If the index pair contains parameters, then this is not truly an
invariant, since the parameters cannot be sorted uniquely mod1.
>>> ap = (Rational(1, 2), Rational(1, 3), Rational(-1, 2), -2)
>>> bq = (1, 2)
Here gamma = 1,
k = 3, s1 = 0, s2 = 1/3, s3 = 1/2
n1 = 1, n2 = 1, n2 = 2
r = 1, t1 = 0
m1 = 2:
>>> Hyper_Function(ap, bq).build_invariants()
(1, ((0, 1), (1/3, 1), (1/2, 2)), ((0, 2),))
"""
abuckets, bbuckets = sift(self.ap, _mod1), sift(self.bq, _mod1)
def tr(bucket):
bucket = list(bucket.items())
if not any(isinstance(x[0], Mod) for x in bucket):
bucket.sort(key=lambda x: default_sort_key(x[0]))
bucket = tuple((mod, len(values))
for mod, values in bucket if values)
return bucket
return self.gamma, tr(abuckets), tr(bbuckets)
def difficulty(self, func):
"""Estimate how many steps it takes to reach ``func`` from self.
Return -1 if impossible.
"""
if self.gamma != func.gamma:
return -1
oabuckets, obbuckets, abuckets, bbuckets = [sift(params, _mod1) for
params in (self.ap, self.bq, func.ap, func.bq)]
diff = 0
for bucket, obucket in [(abuckets, oabuckets), (bbuckets, obbuckets)]:
for mod in set(list(bucket) + list(obucket)):
if (mod not in bucket) or (mod not in obucket) \
or len(bucket[mod]) != len(obucket[mod]):
return -1
l1 = list(bucket[mod])
l2 = list(obucket[mod])
l1.sort()
l2.sort()
for i, j in zip(l1, l2):
diff += abs(i - j)
return diff
def _is_suitable_origin(self):
"""
Decide if ``self`` is a suitable origin.
A function is a suitable origin iff:
* none of the ai equals bj + n, with n a non-negative integer
* none of the ai is zero
* none of the bj is a non-positive integer
Note that this gives meaningful results only when none of the indices
are symbolic.
"""
for a in self.ap:
for b in self.bq:
if (a - b).is_integer and (a - b).is_negative is False:
return False
for a in self.ap:
if a == 0:
return False
for b in self.bq:
if b.is_integer and b.is_nonpositive:
return False
return True
class G_Function(Expr):
"""A Meijer G-function."""
def __new__(cls, an, ap, bm, bq):
obj = super().__new__(cls)
obj.an = Tuple(*list(map(expand, an)))
obj.ap = Tuple(*list(map(expand, ap)))
obj.bm = Tuple(*list(map(expand, bm)))
obj.bq = Tuple(*list(map(expand, bq)))
return obj
@property
def args(self):
return self.an, self.ap, self.bm, self.bq
def _hashable_content(self):
return super()._hashable_content() + self.args
def __call__(self, z):
return meijerg(self.an, self.ap, self.bm, self.bq, z)
def compute_buckets(self):
"""
Compute buckets for the fours sets of parameters.
We guarantee that any two equal Mod objects returned are actually the
same, and that the buckets are sorted by real part (an and bq
descendending, bm and ap ascending).
Examples
========
>>> a, b = [1, 3, 2, Rational(3, 2)], [1 + y, y, 2, y + 3]
>>> G_Function(a, b, [2], [y]).compute_buckets()
({0: [3, 2, 1], 1/2: [3/2]}, {0: [2], y: [y, y + 1, y + 3]},
{0: [2]}, {y: [y]})
"""
dicts = pan, pap, pbm, pbq = [defaultdict(list) for i in range(4)]
for dic, lis in zip(dicts, (self.an, self.ap, self.bm, self.bq)):
for x in lis:
dic[_mod1(x)].append(x)
for dic, flip in zip(dicts, (True, False, False, True)):
for m, items in dic.items():
x0 = items[0]
items.sort(key=lambda x: x - x0, reverse=flip)
dic[m] = items
return tuple(dict(w) for w in dicts)
@property
def signature(self):
return len(self.an), len(self.ap), len(self.bm), len(self.bq)
# Dummy variable.
_x = Dummy('dummy_for_hyperexpand')
class Formula:
"""
This class represents hypergeometric formulae.
Its data members are:
- z, the argument
- closed_form, the closed form expression
- symbols, the free symbols (parameters) in the formula
- func, the function
- B, C, M (see _compute_basis)
>>> func = Hyper_Function((a/2, a/3 + b, (1+a)/2), (a, b, (a+b)/7))
>>> f = Formula(func, z, None, [a, b])
"""
def _compute_basis(self, closed_form):
"""
Compute a set of functions B=(f1, ..., fn), a nxn matrix M
and a 1xn matrix C such that:
closed_form = C B
z d/dz B = M B.
"""
from ..matrices import Matrix, eye, zeros
afactors = [_x + a for a in self.func.ap]
bfactors = [_x + b - 1 for b in self.func.bq]
expr = _x*Mul(*bfactors) - self.z*Mul(*afactors)
poly = Poly(expr, _x)
n = poly.degree() - 1
b = [closed_form]
for _ in range(n):
b.append(self.z*b[-1].diff(self.z))
self.B = Matrix(b)
self.C = Matrix([[1] + [0]*n])
m = eye(n)
m = m.col_insert(0, zeros(n, 1))
l = poly.all_coeffs()[:-1]
self.M = m.row_insert(n, -Matrix([l])/poly.LC())
def __init__(self, func, z, res, symbols, B=None, C=None, M=None):
z = sympify(z)
res = sympify(res)
symbols = [x for x in sympify(symbols) if func.has(x)]
self.z = z
self.symbols = symbols
self.B = B
self.C = C
self.M = M
self.func = func
# TODO with symbolic parameters, it could be advantageous
# (for prettier answers) to compute a basis only *after*
# instantiation
if res is not None:
self._compute_basis(res)
@property
def closed_form(self):
return (self.C*self.B)[0]
def find_instantiations(self, func):
"""
Find substitutions of the free symbols that match ``func``.
Return the substitution dictionaries as a list. Note that the returned
instantiations need not actually match, or be valid!
"""
from ..solvers import solve
ap = func.ap
bq = func.bq
if len(ap) != len(self.func.ap) or len(bq) != len(self.func.bq):
raise TypeError('Cannot instantiate other number of parameters')
symbol_values = []
for a in self.symbols:
if a in self.func.ap.args:
symbol_values.append(ap)
elif a in self.func.bq.args:
symbol_values.append(bq)
else:
raise ValueError('At least one of the parameters of the '
f'formula must be equal to {(a,)}')
base_repl = [dict(zip(self.symbols, values))
for values in product(*symbol_values)]
abuckets, bbuckets = [sift(params, _mod1) for params in [ap, bq]]
a_inv, b_inv = [{a: len(vals) for a, vals in bucket.items()}
for bucket in [abuckets, bbuckets]]
critical_values = [[0] for _ in self.symbols]
result = []
_n = Dummy()
for repl in base_repl:
symb_a, symb_b = [sift(params, lambda x: _mod1(x.xreplace(repl)))
for params in [self.func.ap, self.func.bq]]
for bucket, obucket in [(abuckets, symb_a), (bbuckets, symb_b)]:
for mod in set(list(bucket) + list(obucket)):
if (mod not in bucket) or (mod not in obucket) \
or len(bucket[mod]) != len(obucket[mod]):
break
for a, vals in zip(self.symbols, critical_values):
if repl[a].free_symbols:
continue
exprs = [expr for expr in obucket[mod] if expr.has(a)]
repl0 = repl.copy()
repl0[a] += _n
for expr in exprs:
for target in bucket[mod]:
n0 = solve(expr.xreplace(repl0) - target, _n)[0][_n]
if n0.free_symbols:
raise ValueError('Value should not be true')
vals.append(n0)
else:
values = []
for a, vals in zip(self.symbols, critical_values):
a0 = repl[a]
min_ = floor(min(vals))
max_ = ceiling(max(vals))
values.append([a0 + n for n in range(min_, max_ + 1)])
result.extend(dict(zip(self.symbols, l)) for l in product(*values))
return result
class FormulaCollection:
"""A collection of formulae to use as origins."""
def __init__(self):
"""Doing this globally at module init time is a pain ..."""
self.symbolic_formulae = defaultdict(list)
self.concrete_formulae = defaultdict(dict)
self.formulae = []
add_formulae(self.formulae)
# Now process the formulae into a helpful form.
# These dicts are indexed by (p, q).
for f in self.formulae:
sizes = f.func.sizes
if len(f.symbols) > 0:
self.symbolic_formulae[sizes].append(f)
else:
inv = f.func.build_invariants()
self.concrete_formulae[sizes][inv] = f
def lookup_origin(self, func):
"""
Given the suitable target ``func``, try to find an origin in our
knowledge base.
>>> f = FormulaCollection()
>>> f.lookup_origin(Hyper_Function((), ())).closed_form
E**_z
>>> f.lookup_origin(Hyper_Function([1], ())).closed_form
HyperRep_power1(-1, _z)
>>> i = Hyper_Function([Rational(1, 4), Rational(3, 4) + 4], [Rational(1, 2)])
>>> f.lookup_origin(i).closed_form
HyperRep_sqrts1(-1/4, _z)
"""
inv = func.build_invariants()
sizes = func.sizes
if sizes in self.concrete_formulae and \
inv in self.concrete_formulae[sizes]:
return self.concrete_formulae[sizes][inv]
# We don't have a concrete formula. Try to instantiate.
if sizes not in self.symbolic_formulae:
return # Too bad...
possible = []
for f in self.symbolic_formulae[sizes]:
repls = f.find_instantiations(func)
for repl in repls:
func2 = f.func.xreplace(repl)
if not func2._is_suitable_origin():
continue
diff = func2.difficulty(func)
if diff == -1:
continue
possible.append((diff, repl, f, func2))
# find the nearest origin
possible.sort(key=lambda x: x[0])
for _, repl, f, func2 in possible:
f2 = Formula(func2, f.z, None, [], f.B.subs(repl),
f.C.subs(repl), f.M.subs(repl))
if not any(e.has(nan, oo, -oo, zoo) for e in [f2.B, f2.M, f2.C]):
return f2
class MeijerFormula:
"""
This class represents a Meijer G-function formula.
Its data members are:
- z, the argument
- symbols, the free symbols (parameters) in the formula
- func, the function
- B, C, M (c/f ordinary Formula)
"""
def __init__(self, an, ap, bm, bq, z, symbols, B, C, M, matcher):
an, ap, bm, bq = [Tuple(*list(map(expand, w))) for w in [an, ap, bm, bq]]
self.func = G_Function(an, ap, bm, bq)
self.z = z
self.symbols = symbols
self._matcher = matcher
self.B = B
self.C = C
self.M = M
@property
def closed_form(self):
return (self.C*self.B)[0]
def try_instantiate(self, func):
"""
Try to instantiate the current formula to (almost) match func.
This uses the _matcher passed on init.
"""
if func.signature != self.func.signature:
return
res = self._matcher(func)
if res is not None:
subs, newfunc = res
return MeijerFormula(newfunc.an, newfunc.ap, newfunc.bm, newfunc.bq,
self.z, [],
self.B.subs(subs), self.C.subs(subs),
self.M.subs(subs), None)
class MeijerFormulaCollection:
"""This class holds a collection of meijer g formulae."""
def __init__(self):
formulae = []
add_meijerg_formulae(formulae)
self.formulae = defaultdict(list)
for formula in formulae:
self.formulae[formula.func.signature].append(formula)
self.formulae = dict(self.formulae)
def lookup_origin(self, func):
"""Try to find a formula that matches func."""
if func.signature not in self.formulae:
return
for formula in self.formulae[func.signature]:
res = formula.try_instantiate(func)
if res is not None:
return res
class Operator:
"""
Base class for operators to be applied to our functions.
These operators are differential operators. They are by convention
expressed in the variable D = z*d/dz (although this base class does
not actually care).
Note that when the operator is applied to an object, we typically do
*not* blindly differentiate but instead use a different representation
of the z*d/dz operator (see make_derivative_operator).
To subclass from this, define a __init__ method that initalises a
self._poly variable. This variable stores a polynomial. By convention
the generator is z*d/dz, and acts to the right of all coefficients.
Thus this poly
x**2 + 2*z*x + 1
represents the differential operator
(z*d/dz)**2 + 2*z**2*d/dz.
This class is used only in the implementation of the hypergeometric
function expansion algorithm.
"""
def apply(self, obj, op):
"""
Apply ``self`` to the object ``obj``, where the generator is ``op``.
>>> op = Operator()
>>> op._poly = (x**2 + z*x + y).as_poly(x)
>>> op.apply(z**7, lambda f: f.diff(z))
y*z**7 + 7*z**7 + 42*z**5
"""
coeffs = self._poly.all_coeffs()
diffs = [obj]
for c in coeffs[1:]:
diffs.append(op(diffs[-1]))
r = coeffs[0]*diffs[0]
for c, d in zip(coeffs[1:], diffs[1:]):
r += c*d
return r
class MultOperator(Operator):
"""Simply multiply by a "constant"."""
def __init__(self, p):
self._poly = Poly(p, _x)
class ShiftA(Operator):
"""Increment an upper index."""
def __init__(self, ai):
ai = sympify(ai)
if ai == 0:
raise ValueError('Cannot increment zero upper index.')
self._poly = Poly(_x/ai + 1, _x)
def __str__(self):
return f'<Increment upper {sstr(1/self._poly.LC())}.>'
class ShiftB(Operator):
"""Decrement a lower index."""
def __init__(self, bi):
bi = sympify(bi)
if bi == 1:
raise ValueError('Cannot decrement unit lower index.')
self._poly = Poly(_x/(bi - 1) + 1, _x)
def __str__(self):
return f'<Decrement lower {sstr(1/self._poly.LC() + 1)}.>'