-
Notifications
You must be signed in to change notification settings - Fork 15
/
math_functions.jl
1468 lines (1128 loc) · 41.8 KB
/
math_functions.jl
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
## First pass at math functions. There are more domain restrictions to be implemented.
### SetPrecision
@sjseealso_group(N, SetPrecision, GetPrecison, BigFloatInput, BigIntInput, BI, BF)
@mkapprule SetPrecision :nargs => 1
@sjdoc SetPrecision """
SetPrecison(n)
Set the precsion of BigFloat numbers to `n` decimal digits. If `N` does not give the result you
want, you can use `SetPrecision`.
"""
@doap function SetPrecision(n::Real)
setprecision(round(Int,3.322*n))
return n
end
### GetPrecision
@mkapprule GetPrecision :nargs => 0
@sjdoc GetPrecision """
GetPrecision(n)
Get the precsion of BigFloat numbers.
"""
@doap function GetPrecision()
return precision(BigFloat)
end
"""
evalmath(expr::Expr)
Evaluate `expr`. This is used for writing Symata interfaces
to math functions. Currently, it is equivalent to `eval`.
"""
evalmath(expr::Expr) = Symata.eval(expr::Expr)
## We also need to use these to convert Symata expressions to Julia
## This function writes apprules for math functions. Usally dispatches floating point
## args to Julia functions. Some have a fall through to SymPy
## These tuples have 1,2, or 3 members. Symbols are for Julia, Symata, and SymPy
## If only one member is present, the second is constructed by putting an inital capital on the first.
## If only one or two members are present, we do not fall back to SymPy.
## The last list has tuples with 2 args for which we do not use any Julia function.
# Typical symbols for Julia, Symata, SymPy
function mtr(sym::Symbol)
s = string(sym)
sjf = uppercasefirst(s)
(sym, Symbol(sjf), sym)
end
# We choose not to implement :cis. Julia has it. sympy and mma, not
# List of not yet implemented sympy functions from keys(sympy.functions)
# :E1,:Ei,:FallingFactorial,:Heaviside, :Id,
# :Max,:Min,:Piecewise,
# :Ynm_c,:Znm,
# :__builtins__,:__doc__,:__file__,:__name__,:__package__,:__path__,
# :acos,:acosh,:acot,:acoth,:acsc,:adjoint,
# :assoc_laguerre,:assoc_legendre,
# :bspline_basis, :bspline_basis_set, :ceiling,:chebyshevt_root,
# :chebyshevu_root,:combinatorial
# :elementary,
# :exp_polar, :factorial2,:ff
# :floor, :hyper,:im, :jacobi_normalized, :jn, :jn_zeros,
# :periodic_argument,:piecewise_fold,:polar_lift,
# :principal_branch,:re,:real_root,:rf,:root, :special,
# :transpose,:unbranched_argument,:yn
# TODO: FIX: sympy zeta may take two args
# two arg both float or complex : zeta(s,z) (with domain restrictions)
# BellB should be split into BellB and BellY
# TODO: Implement rewrite
# sympy.airyai(x)[:rewrite](sympy.hyper)
# PyObject -3**(2/3)*x*hyper((), (4/3,), x**3/9)/(3*gamma(1/3)) + 3**(1/3)*hyper((), (2/3,), x**3/9)/(3*gamma(2/3))
# TODO: rename these arrays. Name by number of args plus identifying number.
# ie. two_args1, two_args2. Then explain in comment the particulars. A naming
# scheme to capture all possibilities is to cumbersome.
# mtr(:exp) <-- trying with and without this
const single_arg_float_complex = # check, some of these can't take complex args
[ mtr(:sin), mtr(:cos), mtr(:tan), (:sind,:SinD), (:cosd,:CosD),(:tand,:TanD),
(:sinpi,:SinPi), (:cospi,:CosPi), mtr(:sinh), mtr(:cosh),
mtr(:tanh), (:acos,:ArcCos,:acos), (:asin,:ArcSin,:asin),
(:atan,:ArcTan,:atan),(:acosd,:ArcCosD), (:asind,:ArcSinD),
(:atand,:ArcTanD), mtr(:sec), mtr(:csc), mtr(:cot),(:secd,:SecD),(:csc,:CscD),(:cot,:CotD),
(:asec,:ArcSec),(:acsc,:ArcCsc),(:acot,:ArcCot), # (:acotd,:ArcCotD)
(:csch,), mtr(:coth,),(:asinh,:ASinh,:asinh), (:acosh,:ACosh, :acosh),(:atanh,:ATanh, :atanh),
(:asech,:ArcSech),(:acsch,:ArcCsch),(:acoth,:ArcCoth, :acoth),
(:cosc,),
(:log1p,),(:exp2,),(:exp10,),(:expm1,),(:abs2,),
mtr(:erfc), mtr(:erfi),(:erfcx,),(:dawson,),(:real,:Re, :re),(:imag,:Im, :im),
(:angle,:Arg,:arg), (:lgamma, :LogGamma, :loggamma),
(:lfact,:LogFactorial), mtr(:digamma), mtr(:trigamma),
(:airyai,:AiryAi,:airyai),
(:airybi,:AiryBi,:airybi),(:airyaiprime,:AiryAiPrime,:airyaiprime),(:airybiprime,:AiryBiPrime,:airybiprime),
(:besselj0,:BesselJ0),(:besselj1,:BesselJ1),(:bessely0,:BesselY0),(:bessely1,:BesselY1),
(:zeta,:Zeta,:zeta)
# (:eta,:DirichletEta,:dirichlet_eta)
]
# (:log,), removed from list above, because it must be treated specially (and others probably too!)
const single_arg_float_int_complex = [(:sinc,)]
const single_arg_float = [(:erfcinv,:InverseErfc,:erfcinv),(:invdigamma,:InverseDigamma)]
# FIXME Ceiling should probably return integer type. So it can't be included in generic code here (or punt to sympy for everything)
const single_arg_float_int = [(:signbit,:SignBit), (:ceil, :Ceiling, :ceiling), (:floor, :Floor, :floor)]
# (:factorial,:Factorial, :factorial), <--- we do this by hand
const single_arg_int = [(:isqrt,:ISqrt),(:ispow2,:IsPow2),(:nextpow2,:NextPow2),(:prevpow2,:PrevPow2),
(:isprime,:PrimeQ), (:(~), :BitNot)
]
const two_arg_int = [(:binomial,:Binomial,:binomial)
]
# Do NDigits by hand for now!
@mkapprule NDigits :nargs => 1:2
@doap NDigits(n::T,b::V) where {T<:Integer,V<:Integer} = ndigits(n, base=b)
@doap NDigits(n::T) where {T<:Integer} = ndigits(n)
@doap NDigits(n) = mx
@doap NDigits(n,b) = mx
# TODO
# Two or more args
# (:gcd,:GCD), (:lcm, :LCM), Also sympy does these for polynomials
# Complicated!
const one_or_two_args1 = [(:polygamma, :PolyGamma, :polygamma)]
const two_arg_float_and_float_or_complex =
[
(:besselj,:BesselJ, :besselj), (:besseljx,:BesselJx), (:bessely,:BesselY,:bessely),
(:besselyx,:BesselYx), (:hankelh1,:HankelH1,:hankel1), (:hankelh1x,:HankelH1x),
(:hankelh2,:HankelH2,:hankel2), (:hankelh2x,:HankelH2x), (:besseli,:BesselI, :besseli),
(:besselix,:BesselIx), (:besselk,:BesselK,:besselk), (:besselkx,:BesselKx),
(:atan2,:ArcTan2,:atan2)
]
const two_arg_float = [ (:beta,),(:lbeta,:LogBeta),(:hypot,)]
## There are no Julia functions for these (or at least we are not using them).
## First symbol is for Symata, Second is SymPy
# TODO: Migrate functions out this non-specific list
const no_julia_function = [ (:ExpIntegralE, :expint),
(:GegenbauerC, :gegenbauer), (:HermiteH, :hermite),
(:BellB, :bell), (:BernoulliB, :bernoulli), (:CatalanNumber, :catalan),
(:EulerE, :euler), (:Subfactorial, :subfactorial), (:Factorial2, :factorial2),
(:FactorialPower, :FallingFactorial), (:Pochhammer, :RisingFactorial),
(:LeviCivita, :LeviCivita),
(:KroneckerDelta, :KroneckerDelta), (:HypergeometricPFQ, :hyper), (:FactorSquareFree, :sqf), (:MellinTransform, :mellin_transform),
(:InverseMellinTransform, :inverse_mellin_transform), (:SineTransform, :sine_transform), (:InverseSineTransform, :inverse_sine_transform),
(:CosineTransform, :cosine_transform), (:InverseCosineTransform, :inverse_cosine_transform),
(:HankelTransform, :hankel_transform), (:InverseHankelTransform, :inverse_hankel_transform)
]
# LeviCivita is different than in mathematica
# Mobius needs filtering
const no_julia_function_one_arg = [ (:EllipticK, :elliptic_k), (:HeavisideTheta,:Heaviside),
(:CosIntegral, :Ci), (:SinIntegral, :Si),
(:FresnelC, :fresnelc), (:FresnelS, :fresnels), (:DiracDelta, :DiracDelta),
(:LogIntegral, :Li), (:Ei, :Ei), (:ExpandFunc, :expand_func), (:Denominator, :denom),
(:MoebiusMu, :mobius), (:EulerPhi, :totient), (:Divisors, :divisors), (:DivisorCount, :divisor_count),
(:SinhIntegral, :Shi),(:CoshIntegral, :Chi) ]
# elliptic_e take more than ints!
const no_julia_function_one_or_two_int = [ (:HarmonicNumber, :harmonic) , (:EllipticE, :elliptic_e) ]
# FIXME: DivisorSigma has arg order reversed in Mma
const no_julia_function_two_args = [(:LegendreP, :legendre_poly), (:EllipticF, :elliptic_f),
(:ChebyshevT, :chebyshevt), (:ChebyshevU, :chebyshevu),
(:Cyclotomic, :cyclotomic_poly), (:SwinnertonDyer, :swinnerton_dyer_poly),
(:SphericalBesselJ, :jn), (:SphericalBesselY, :yn), (:DivisorSigma, :divisor_sigma)
# (:PolyLog, :polylog), (:SphericalBesselJ, :jn), (:SphericalBesselY, :yn), (:DivisorSigma, :divisor_sigma)
]
const no_julia_function_two_or_three_args = [ (:EllipticPi, :elliptic_pi), (:LaguerreL, :laguerre_poly)]
const no_julia_function_three_args = [ (:LerchPhi, :lerchphi) ]
const no_julia_function_four_args = [ (:JacobiP, :jacobi), (:SphericalHarmonicY, :Ynm) ]
function make_math()
# Note: in Mma and Julia, catalan and Catalan are Catalan's constant. In sympy catalan is the catalan number
# can't find :stirling in sympy
for x in no_julia_function_one_arg
sjf = x[1]
eval(macroexpand(Symata, :( @mkapprule $sjf)))
write_sympy_apprule(x[1],x[2],1)
end
for x in no_julia_function_two_args
sjf = x[1]
eval(macroexpand(Symata, :( @mkapprule $sjf :nargs => 2)))
write_sympy_apprule(x[1],x[2],2)
end
for x in no_julia_function_four_args
nargs = 4
sjf = x[1]
eval(macroexpand(Symata, :( @mkapprule $sjf :nargs => $nargs)))
write_sympy_apprule(x[1],x[2],nargs)
end
for x in no_julia_function_three_args
nargs = 3
sjf = x[1]
eval(macroexpand(Symata, :( @mkapprule $sjf :nargs => $nargs)))
write_sympy_apprule(x[1],x[2],nargs)
end
for x in no_julia_function_two_or_three_args
sjf = x[1]
eval(macroexpand(Symata, :( @mkapprule $sjf)))
write_sympy_apprule(x[1],x[2],2)
write_sympy_apprule(x[1],x[2],3)
end
for x in no_julia_function_one_or_two_int
sjf = x[1]
eval(macroexpand(Symata, :( @mkapprule $sjf)))
write_sympy_apprule(x[1],x[2],1)
write_sympy_apprule(x[1],x[2],2)
end
# TODO: update this code
for x in no_julia_function
set_up_sympy_default(x...)
clear_attributes(x[1]) ## FIXME: Listable was set in previous line. Now we unset it. We need a better system for this.
set_sysattributes(x[1])
end
# Ok, this works. We need to clean it up
for x in single_arg_float_complex
jf,sjf = only_get_sjstr(x...)
eval(macroexpand(Symata, :( @mkapprule $sjf :nargs => 1 )))
write_julia_numeric_rule(jf,sjf,"AbstractFloat")
write_julia_numeric_rule(jf,sjf,"CAbstractFloat")
if length(x) == 3
write_sympy_apprule(sjf,x[3],1)
end
set_attribute(Symbol(sjf),:Listable)
end
for x in single_arg_float
jf,sjf = only_get_sjstr(x...)
eval(macroexpand(Symata, :( @mkapprule $sjf :nargs => 1 )))
write_julia_numeric_rule(jf,sjf,"AbstractFloat")
if length(x) == 3
write_sympy_apprule(sjf,x[3],1)
end
set_attribute(Symbol(sjf),:Listable)
end
for x in single_arg_float_int
jf,sjf = only_get_sjstr(x...)
eval(macroexpand(Symata, :( @mkapprule $sjf :nargs => 1 )))
write_julia_numeric_rule(jf,sjf,"Real")
if length(x) == 3
write_sympy_apprule(sjf,x[3],1)
end
end
# This is all numbers, I suppose
for x in single_arg_float_int_complex
jf,sjf = only_get_sjstr(x...)
eval(macroexpand(Symata, :( @mkapprule $sjf :nargs => 1 )))
write_julia_numeric_rule(jf,sjf,"Real")
write_julia_numeric_rule(jf,sjf,"CReal")
if length(x) == 3
write_sympy_apprule(sjf,x[3],1)
end
end
for x in single_arg_int
jf,sjf = only_get_sjstr(x...)
eval(macroexpand(Symata, :( @mkapprule $sjf :nargs => 1 :argtypes => [Integer] )))
write_julia_numeric_rule(jf,sjf,"Integer")
if length(x) == 3
write_sympy_apprule(sjf,x[3],1)
end
end
for x in two_arg_int
jf,sjf = only_get_sjstr(x...)
eval(macroexpand(Symata, :( @mkapprule $sjf :nargs => 2 )))
write_julia_numeric_rule(jf,sjf,"Integer", "Integer")
if length(x) == 3
write_sympy_apprule(sjf,x[3],2)
end
end
# Mma allows one arg, as well
for x in one_or_two_args1
jf,sjf = only_get_sjstr(x...)
eval(macroexpand(Symata, :( @mkapprule $sjf )))
write_julia_numeric_rule(jf,sjf,"Integer", "AbstractFloat")
write_julia_numeric_rule(jf,sjf,"Integer", "CAbstractFloat")
if length(x) == 3
write_sympy_apprule(sjf,x[3],2)
end
end
for x in two_arg_float
jf,sjf = only_get_sjstr(x...)
eval(macroexpand(Symata, :( @mkapprule $sjf :nargs => 2 )))
write_julia_numeric_rule(jf,sjf,"AbstractFloat", "AbstractFloat")
end
for x in two_arg_float_and_float_or_complex
jf,sjf = only_get_sjstr(x...)
eval(macroexpand(Symata, :( @mkapprule $sjf :nargs => 2 )))
write_julia_numeric_rule(jf,sjf,"AbstractFloat", "AbstractFloat")
write_julia_numeric_rule(jf,sjf,"AbstractFloat", "CAbstractFloat")
write_julia_numeric_rule(jf,sjf,"Integer", "AbstractFloat")
write_julia_numeric_rule(jf,sjf,"Integer", "CAbstractFloat")
if length(x) == 3
write_sympy_apprule(sjf,x[3],2)
end
end
end
Typei(i::Int) = "T" *string(i)
complex_type(t::AbstractString) = "Complex{" * t * "}"
function write_julia_numeric_rule(jf, sjf, types...)
annot = join(AbstractString[ "T" * string(i) * "<:" *
(types[i][1] == 'C' ? types[i][2:end] : types[i]) for i in 1:length(types)], ", ")
protargs = join(AbstractString[ "x" * string(i) * "::" *
(types[i][1] == 'C' ? complex_type(Typei(i)) : Typei(i))
for i in 1:length(types)], ", ")
callargs = join(AbstractString[ "x" * string(i) for i in 1:length(types)], ", ")
# appstr = "do_$sjf{$annot}(mx::Mxpr{:$sjf},$protargs) = $jf($callargs)"
appstr = "do_$sjf(mx::Mxpr{:$sjf},$protargs) where {$annot} = $jf($callargs)"
eval(Meta.parse(appstr))
end
function only_get_sjstr(jf,sjf,args...)
return jf, sjf
end
function only_get_sjstr(jf)
st = string(jf)
sjf = Symbol(uppercasefirst(st))
return jf, sjf
end
function get_sjstr(jf,sjf)
do_common(sjf)
return jf, sjf
end
function get_sjstr(jf)
st = string(jf)
sjf = String(uppercasefirst(st))
do_common(sjf)
return jf, sjf
end
## FIXME: This is outdated. Some of this is handled in @mkapprule
# Handle functions that do *not* fall back on SymPy
function do_common(sjf)
aprs = "Symata.apprules(mx::Mxpr{:$sjf}) = do_$sjf(mx,margs(mx)...)"
aprs1 = "do_$sjf(mx::Mxpr{:$sjf},x...) = mx"
evalmath(Meta.parse(aprs))
evalmath(Meta.parse(aprs1))
set_attribute(Symbol(sjf),:Protected)
set_attribute(Symbol(sjf),:Listable)
end
# Handle functions that fall back on SymPy
function get_sjstr(jf, sjf, sympyf)
set_up_sympy_default(sjf, sympyf)
return jf, sjf
end
# Faster if we don't do interpolation
function write_sympy_apprule(sjf, sympyf, nargs::Int)
callargs = Array{AbstractString}(undef, 0)
sympyargs = Array{AbstractString}(undef, 0)
for i in 1:nargs
xi = "x" * string(i)
push!(callargs, xi)
push!(sympyargs, "sjtopy(" * xi * ")")
end
cstr = join(callargs, ", ")
sstr = join(sympyargs, ", ")
aprpy = "function do_$sjf(mx::Mxpr{:$sjf},$cstr)
try
(sympy[:$sympyf]($sstr) |> pytosj)
catch e
showerror(stdout, e)
mx
end
end"
evalmath(Meta.parse(aprpy))
end
function set_up_sympy_default(sjf, sympyf)
aprs = "Symata.apprules(mx::Mxpr{:$sjf}) = do_$sjf(mx,margs(mx)...)"
aprs1 = "function do_$sjf(mx::Mxpr{:$sjf},x...)
try
(sympy[:$sympyf](map(sjtopy,x)...) |> pytosj)
catch
mx
end
end"
evalmath(Meta.parse(aprs))
evalmath(Meta.parse(aprs1))
set_attribute(Symbol(sjf),:Protected)
set_attribute(Symbol(sjf),:Listable)
end
make_math()
#### Gamma function
@mkapprule Gamma :nargs => 1:2
@doap Gamma(a) = sjgamma(a)
@doap Gamma(a,z) = sjgamma(a,z)
set_pytosj(:gamma, :Gamma)
set_pytosj(:uppergamma, :Gamma)
set_sjtopy(:Gamma, :sympy_gamma)
@sjdoc Gamma """
Gamma(a)
the gamma function.
Gamma(a,z)
the upper incomplete Gamma function.
"""
### GammaRegularized
## Implementation is not complete
@mkapprule GammaRegularized :nargs => 2:3
@doap function GammaRegularized(a,z::Number)
if z == 0
return _gammaregularizedzero(mx,a)
end
return _gammaregularizednozero(mx,a,z)
end
function _gammaregularizedzero(mx,a::Real)
a > 0 ? 1 : a == 0 ? 0 : ComplexInfinity
end
function _gammaregularizedzero(mx,a::Complex)
ra = real(a)
ra > 0 ? 1 : ra == 0 ? Indeterminate : ComplexInfinity
end
function _gammaregularizedzero(mx,a)
mx
end
function _gammaregularizednozero(mx,a::Real,z::Number)
a < 0 && return zero(a) ## need to consider type of z as well
mxpr(:Gamma,a,z)/mxpr(:Gamma,a)
end
function _gammaregularizednozero(mx,a::Number,z::Number)
mxpr(:Gamma,a,z)/mxpr(:Gamma,a)
end
function _gammaregularizednozero(mx,a,z)
mx
end
### Erf
@mkapprule Erf :nargs => 1:2
@doap Erf(x) = sjerf(x)
@doap Erf(x,y) = sjerf(x,y)
set_pytosj(:erf, :Erf)
set_pytosj(:erf2, :Erf)
set_sjtopy(:Erf, :sympy_erf)
### InverseErf
@mkapprule InverseErf :nargs => 1:2
@doap InverseErf(x::T) where {T<:AbstractFloat} = x < 1 && x > -1 ? erfinv(x) : mx
@doap InverseErf(x) = pytosj(sympy[:erfinv](sjtopy(x)))
@doap InverseErf(x,y) = pytosj(sympy[:erf2inv](sjtopy(x),sjtopy(y)))
register_sjfunc_pyfunc(:InverseErf,:erfinv)
register_only_pyfunc_to_sjfunc(:InverseErf,:erf2inv)
### IntegerDigits
@sjdoc IntegerDigits """
IntegerDigits(n,[, base][, pad])
return an array of the digits of `n` in the given `base`,
optionally padded with zeros to `pad` characters.
In contrast to Julia, more significant digits are at lower indexes.
"""
@mkapprule IntegerDigits :nargs => 1:3
set_sysattributes(:IntegerDigits, :Listable)
_intdig(args) = MList(reverse!(args)...) |> setfixed
@doap IntegerDigits(n::Integer) = digits(n) |> _intdig
@doap IntegerDigits(n::Integer,b::Integer) = digits(n, base=convert(Int, b)) |> _intdig
@doap IntegerDigits(n::Integer,b::Integer,p::Integer) = digits(n, base=convert(Int, b), convert(Int, p)) |> _intdig
@mkapprule Log :nargs => 1:2
# sjlog defined in wrappers.jl
@doap Log(x,y) = sjlog(x,y)
@doap Log(x) = sjlog(x)
### N
@sjdoc N """
N(expr)
try to give a the numerical value of `expr`.
N(expr,p)
try to give `p` decimal digits of precision.
Sometimes `N` does not give the number of digits requested. In this case, you can use `SetPrecision`.
"""
## TODO: call evalf(expr,n) on sympy functions to get arbitrary precision numbers.
## Eg. N(LogIntegral(4),30) does not give correct result.
## ... a list of heads all of which should be converted and then passed to evalf.
## N needs to be rewritten
function apprules(mx::Mxpr{:N})
outer_N(margs(mx)...)
end
function outer_N(expr)
do_N(expr)
end
function outer_N(expr, p)
if p > 16
pr = precision(BigFloat)
dig = round(Int,p*3.322)
set_mpmath_dps(dig) # This is for some SymPy math. But, it is not clear when this will help us
setprecision( BigFloat, dig) # new form
res = meval(do_N(expr,p))
setprecision(BigFloat, pr)
restore_mpmath_dps()
return res
else
do_N(expr)
end
end
do_N(x::Float64,dig) = x # Mma does this
do_N(x,dig) = x
do_N(x) = x
do_N(n::T) where {T<:AbstractFloat} = n
do_N(n::T) where {T<:Real} = float(n)
do_N(n::Complex{T}) where {T<:Real} = complex(float(real(n)), float(imag(n)))
do_N(n::T,p::V) where {T<:Real,V<:Integer} = float_with_precision(n,p)
# p is number of decimal digits of precision
# Julia doc says set_bigfloat_precision uses
# binary digits, but it looks more like decimal.
function float_with_precision(x,p)
res = BigFloat(x)
end
# These rely on fixed-point evaluation to continue with N, this is not efficient
# We need to do it all here.
function _make_N_body(d1,d2)
quote begin
get_attribute(mx,:NHoldAll) && return mx;
len = length(mx)
args = margs(mx)
nargs = newargs(len)
start::Int = 1
if get_attribute(mx,:NHoldFirst)
nargs[1] = args[1]
for i in 2:len
nargs[i] = $d2
end
elseif get_attribute(mx,:NHoldRest)
nargs[1] = $d1
for i in 2:len
nargs[i] = args[i]
end
else
@inbounds for i in 1:len
nargs[i] = $d2
end
end
res = mxpr(mhead(mx),nargs)
end
end
end
function make_Mxpr_N()
_Nbody = _make_N_body(:(do_N(args[1])), :(do_N(args[i])) )
@eval begin
function do_N(mx::Mxpr)
$_Nbody
res
end
end
_Nbody = _make_N_body(:(do_N(args[1],p)), :(do_N(args[i],p)) )
@eval begin
function do_N(mx::Mxpr,p::T) where T<:Integer
$_Nbody
res
end
end
end
make_Mxpr_N()
@sjdoc GoldenRatio """
GoldenRatio
equal to `(1+Sqrt(5))/2`.
"""
# We need to use dispatch as well, not conditionals
function do_N(s::SJSym)
if s == :Pi || s == :π
return float(MathConstants.pi)
elseif s == :E
return float(MathConstants.e)
elseif s == :EulerGamma
return float(MathConstants.eulergamma)
elseif s == :GoldenRatio
return float(MathConstants.golden)
elseif s == :Catalan
return float(MathConstants.catalan)
end
return s
end
function do_N(s::SJSym,pr::T) where T<:Integer
if s == :Pi || s == :π
return float_with_precision(MathConstants.pi, pr)
elseif s == :E
return float_with_precision(MathConstants.e, pr)
elseif s == :EulerGamma
return float_with_precision(MathConstants.eulergamma, pr)
elseif s == :GoldenRatio
return float_with_precision(MathConstants.golden, pr)
elseif s == :Catalan
return float_with_precision(MathConstants.catalan, pr)
end
return s
end
@sjdoc Precision """
Precision(x)
get the precision of a floating point number `x` in decimal digits
Precision()
get the current precision of `BigFloat` arithmetic
Precision(Binary => True)
Precision(x, Binary => True)
give precision as defined by the effective number of bits in the mantissa.
"""
@mkapprule Precision :nodefault => true, :options => Dict( :Binary => false )
#apprules(mx::Mxpr{:Precision}) = do_Precision(mx,margs(mx)...)
# TODO: mkapprule should write the correct default rule if keywords are present
do_Precision(mx::Mxpr{:Precision},args...; kws...) = mx
function do_Precision(mx::Mxpr{:Precision},x::AbstractFloat; Binary=false)
Binary ? precision(x) : round(Int,precision(x) * log10(2))
end
function do_Precision(mx::Mxpr{:Precision}; Binary=false)
pr = precision(BigFloat)
Binary ? pr : round(Int,pr * log10(2))
end
@sjdoc Re """
Re(z)
return the real part of `z`.
"""
@sjdoc Im """
Im(z)
return the imaginary part of `z`.
"""
# Using Julia would be faster in some cases for ReIm and AbsArg
@sjdoc ReIm """
ReIm(z)
returns `[Re(z),Im(z)]`.
"""
@mkapprule ReIm
@doap ReIm(z) = mxpr(:List,mxpr(:Re,z), mxpr(:Im,z))
# FIXME Abs(I-3) returns 10^(1/2) instead of (2^(1/2))*(5^(1/2)). i.e. does not evaluate to a fixed point
@sjdoc AbsArg """
AbsArg(z)
return `[Abs(z),Arg(z)]`.
"""
@mkapprule AbsArg
@doap AbsArg(z) = mxpr(:List,mxpr(:Abs,z), mxpr(:Arg,z))
# Re and Im code below is disabled so it does not interfere with SymPy.
# Mma allows complex numbers of mixed Real type. So does Julia: Complex{Real}(1//3, 3.0)
# Implementation not complete. eg Im(a + I *b) --> Im(a) + Re(b)
# do_Re{T<:Real}(mx::Mxpr{:Re}, x::Complex{T}) = real(x)
# do_Re(mx::Mxpr{:Re}, x::Real) = x
# function do_Re(mx::Mxpr{:Re}, m::Mxpr{:Times})
# f = m[1]
# return is_imaginary_integer(f) ? do_Re_imag_int(m,f) : mx
# end
# # dispatch on type of f. Maybe this is worth something.
# function do_Re_imag_int(m,f)
# nargs = copy(margs(m))
# popfirst!(nargs)
# if length(nargs) == 1
# return mxpr(:Times,-imag(f),mxpr(:Im,nargs))
# else
# return mxpr(:Times,-imag(f),mxpr(:Im,mxpr(:Times,nargs)))
# end
# end
# do_Im{T<:Real}(mx::Mxpr{:Im}, x::Complex{T}) = imag(x)
# do_Im(mx::Mxpr{:Im}, x::Real) = zero(x)
# function do_Im(mx::Mxpr{:Im}, m::Mxpr{:Times})
# f = m[1]
# return is_imaginary_integer(f) ? do_Im_imag_int(m,f) : mx
# end
# function do_Im_imag_int(m,f)
# nargs = copy(margs(m))
# popfirst!(nargs)
# if length(nargs) == 1
# return mxpr(:Times,imag(f),mxpr(:Re,nargs))
# else
# return mxpr(:Times,imag(f),mxpr(:Re,mxpr(:Times,nargs)))
# end
# end
#### Complex
@sjdoc Complex """
Complex(a,b)
return a complex number when `a` and `b` are Reals
The conversion is done when the expression is parsed, so it is much faster than `a + I*b`.
"""
# Complex with two numerical arguments is converted at parse time. But, the
# arguments may evaluate to numbers only at run time, so this is needed.
# mkapprule requires that the first parameter do_Complex be annotated with the Mxpr type.
@mkapprule Complex
do_Complex(mx::Mxpr{:Complex},a::T,b::T) where {T<:Number} = complex(a,b)
do_Complex(mx::Mxpr{:Complex},a::T) where {T<:Number} = complex(a)
@sjdoc Rational """
Rational(a,b), or a/b
return a `Rational` for `Integer`s `a` and `b`. This is done when the
expression is parsed, so it is much faster than `a/b`.
"""
# Same here. But we need to use mdiv to reduce rationals to ints if possible.
@mkapprule Rational
do_Rational(mx::Mxpr{:Rational},a::Number,b::Number) = mdiv(a,b)
#### Rationalize
@sjdoc Rationalize """
Rationalize(x)
return a `Rational` approximation of `x`.
Rationalize(x,tol)
return an approximation differing from `x` by no more than `tol`.
"""
@mkapprule Rationalize
do_Rationalize(mx::Mxpr{:Rationalize},x::AbstractFloat) = rationalize(x)
do_Rationalize(mx::Mxpr{:Rationalize},x::AbstractFloat,tol::Number) = rationalize(x,tol=float(tol))
function do_Rationalize(mx::Mxpr{:Rationalize},x::Symbolic)
r = doeval(mxpr(:N,x)) # we need to redesign do_N so that we can call it directly. See above
return isa(r,AbstractFloat) ? do_Rationalize(mx,r) : x
end
function do_Rationalize(mx::Mxpr{:Rationalize},x::Symbolic,tol::Number)
ndig = round(Int,-log10(tol)) # This is not quite correct.
r = doeval(mxpr(:N,x,ndig)) # we need to redesign do_N so that we can call it directly. See above.
return isa(r,AbstractFloat) ? do_Rationalize(mx,r,tol) : x
end
do_Rationalize(mx::Mxpr{:Rationalize},x) = x
#### Numerator
@sjdoc Numerator """
Numerator(expr)
return the numerator of `expr`.
"""
apprules(mx::Mxpr{:Numerator}) = do_Numerator(mx::Mxpr{:Numerator},margs(mx)...)
do_Numerator(mx::Mxpr{:Numerator},args...) = mx
do_Numerator(mx::Mxpr{:Numerator},x::Rational) = numerator(x)
do_Numerator(mx::Mxpr{:Numerator},x) = x
function do_Numerator(mx::Mxpr{:Numerator},x::Mxpr{:Power})
find_numerator(x)
end
function do_Numerator(mx::Mxpr{:Numerator},m::Mxpr{:Times})
nargsn = newargs()
args = margs(m)
for i in 1:length(args)
arg = args[i]
res = find_numerator(arg)
if res != 1
push!(nargsn,res)
end
end
if isempty(nargsn)
return 1 # which one ?
end
if length(nargsn) == 1
return nargsn[1]
end
return mxpr(mhead(m),nargsn)
end
find_numerator(x::Rational) = numerator(x)
find_numerator(x::Mxpr{:Power}) = pow_sign(x,expt(x)) > 0 ? x : 1
function pow_sign(x, texpt::Mxpr{:Times})
fac = texpt[1]
return is_Number(fac) && fac < 0 ? -1 : 1
end
pow_sign(x, texpt::Number) = texpt < 0 ? -1 : 1
pow_sign(x, texpt) = 1
find_numerator(x) = x
### Chop
@mkapprule Chop :nargs => 1:2
@sjdoc Chop """
Chop(expr)
set small floating point numbers in `expr` to zero.
Chop(expr,eps)
set floating point numbers smaller in magnitude than `eps` in `expr` to zero.
"""
do_Chop(mx::Mxpr{:Chop}, x) = zchop(x)
do_Chop(mx::Mxpr{:Chop}, x, zeps) = zchop(x,zeps)
const chop_eps = 1e-14
zchop(x::T, eps=chop_eps) where {T<:AbstractFloat} = abs(x) > eps ? x : 0 # don't follow abstract type
zchop(x::T, eps=chop_eps) where {T<:Number} = x
zchop(x::Complex{T}, eps=chop_eps) where {T<:AbstractFloat} = complex(zchop(real(x),eps),zchop(imag(x),eps))
zchop(a::T, eps=chop_eps) where {T<:AbstractArray} = (b = similar(a); for i in 1:length(a) b[i] = zchop(a[i],eps) end ; b)
zchop!(a::T, eps=chop_eps) where {T<:AbstractArray} = (for i in 1:length(a) a[i] = zchop(a[i],eps) end ; a)
zchop(x::Expr,eps=chop_eps) = Expr(x.head,zchop(x.args)...)
zchop(x) = x
zchop(x,eps) = x
function zchop(mx::T) where T<:Mxpr
nargs = similar(margs(mx))
for i in 1:length(nargs) nargs[i] = zchop(mx[i]) end
mxpr(mhead(mx), nargs)
end
function zchop(mx::T,zeps) where T<:Mxpr
nargs = similar(margs(mx))
for i in 1:length(nargs) nargs[i] = zchop(mx[i],zeps) end
mxpr(mhead(mx), nargs)
end
### Conjugate
@mkapprule Conjugate :nargs => 1
@doap Conjugate(z::Number) = conj(z)
@doap Conjugate(z::Mxpr{:Plus}) = mxpr(:Plus, mapmargs( x -> mxpr(:Conjugate, x), margs(z))...)
@doap Conjugate(z::Mxpr) = z |> sjtopy |> sympy[:conjugate] |> pytosj
### Exp
# The parser normally takes care of this,
# But, when converting expressions from Sympy, we get Exp, so we handle it here.
# TODO: don't throw away other args. (but, we hope this is only called with returns from Sympy)
apprules(mx::Mxpr{:Exp}) = mxpr(:Power,:E,mx[1])
# TODO: handle 3rd argument
#### Mod
@mkapprule Mod :nargs => 2
do_Mod(mx::Mxpr{:Mod}, x::T, y::V) where {T<:Integer, V<:Integer} = mod1(x,y)
#### DivRem
@mkapprule DivRem :nargs => 2
do_DivRem(mx::Mxpr{:DivRem}, x::T, y::V) where {T<:Integer, V<:Integer} = mxprcf(:List,divrem(x,y)...)
#### Abs
@sjdoc Abs """
Abs(z)
the absolute value of `z`.
"""
@mkapprule Abs :nargs => 1
@doap Abs(n::T) where {T<:Number} = mabs(n)
@doap function Abs(x)
x |> sjtopy |> sympy[:Abs] |> pytosj
end
# The following code may be useful, but it is not complete
# # Abs(x^n) --> Abs(x)^n for Real n
function do_Abs(mx::Mxpr{:Abs}, pow::Mxpr{:Power})
doabs_pow(mx,base(pow),expt(pow))
end
# SymPy does not do this one
doabs_pow(mx,b,e::T) where {T<:Real} = mxpr(:Power,mxpr(:Abs,b),e)
function doabs_pow(mx,b,e)
mx[1] |> sjtopy |> sympy[:Abs] |> pytosj
end
# do_Abs(mx::Mxpr{:Abs},prod::Mxpr{:Times}) = do_Abs(mx,prod,prod[1])
# #doabs(mx,prod,s::Symbol)
# function do_Abs{T<:Number}(mx::Mxpr{:Abs},prod,f::T)
# f >=0 && return mx
# if f == -1
# return doabsmone(mx,prod,f)
# end
# args = copy(margs(prod))
# args[1] = -args[1]
# return mxpr(:Abs,mxpr(:Times,args))
# end
# function doabsmone{T<:Integer}(mx,prod,f::T)
# args = copy(margs(prod))
# popfirst!(args)
# if length(args) == 1
# return mxpr(:Abs,args)
# else