This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
/
pynac.pyx
2515 lines (2095 loc) · 73.9 KB
/
pynac.pyx
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
"""
Pynac interface
"""
#*****************************************************************************
# Copyright (C) 2008 William Stein <wstein@gmail.com>
# Copyright (C) 2008 Burcin Erocal <burcin@erocal.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import absolute_import
from cpython cimport *
from libc cimport math
from .ginac cimport *
from sage.ext.stdsage cimport PY_NEW
from sage.libs.gmp.all cimport *
from sage.libs.gsl.types cimport *
from sage.libs.gsl.complex cimport *
from sage.libs.gsl.gamma cimport gsl_sf_lngamma_complex_e
from sage.arith.all import gcd, lcm, is_prime, factorial, bernoulli
from sage.structure.element cimport Element, parent_c
from sage.rings.integer_ring import ZZ
from sage.rings.integer cimport Integer
from sage.rings.rational cimport Rational
from sage.rings.real_mpfr import RR, RealField
from sage.rings.complex_field import ComplexField
from sage.rings.all import CC
from sage.symbolic.expression cimport Expression, new_Expression_from_GEx
from sage.symbolic.substitution_map cimport SubstitutionMap, new_SubstitutionMap_from_GExMap
from sage.symbolic.function import get_sfunction_from_serial
from sage.symbolic.function cimport Function
from sage.symbolic.constants_c cimport PynacConstant
from . import ring
from sage.rings.integer cimport Integer
from sage.libs.mpmath import utils as mpmath_utils
#################################################################
# Symbolic function helpers
#################################################################
cdef object ex_to_pyExpression(GEx juice):
"""
Convert given GiNaC::ex object to a python Expression instance.
Used to pass parameters to custom power and series functions.
"""
cdef Expression nex
nex = <Expression>Expression.__new__(Expression)
GEx_construct_ex(&nex._gobj, juice)
nex._parent = ring.SR
return nex
cdef object exprseq_to_PyTuple(GEx seq):
"""
Convert an exprseq to a Python tuple.
Used while converting arguments of symbolic functions to Python objects.
EXAMPLES::
sage: from sage.symbolic.function import BuiltinFunction
sage: class TFunc(BuiltinFunction):
....: def __init__(self):
....: BuiltinFunction.__init__(self, 'tfunc', nargs=0)
....:
....: def _eval_(self, *args):
....: print("len(args): %s, types: %s"%(len(args), str(map(type, args))))
....: for i, a in enumerate(args):
....: if isinstance(a, tuple):
....: print("argument %s is a tuple, with types %s"%(str(i), str(map(type, a))))
....:
sage: tfunc = TFunc()
sage: u = SR._force_pyobject((1, x+1, 2))
sage: tfunc(u, x, SR._force_pyobject((3.0, 2^x)))
len(args): 3, types: [<type 'tuple'>, <type 'sage.symbolic.expression.Expression'>, <type 'tuple'>]
argument 0 is a tuple, with types [<type 'sage.rings.integer.Integer'>, <type 'sage.symbolic.expression.Expression'>, <type 'sage.rings.integer.Integer'>]
argument 2 is a tuple, with types [<type 'sage.rings.real_mpfr.RealLiteral'>, <type 'sage.symbolic.expression.Expression'>]
tfunc((1, x + 1, 2), x, (3.00000000000000, 2^x))
"""
from sage.symbolic.ring import SR
res = []
for i in range(seq.nops()):
if is_a_numeric(seq.op(i)):
res.append(py_object_from_numeric(seq.op(i)))
elif is_exactly_a_exprseq(seq.op(i)):
res.append(exprseq_to_PyTuple(seq.op(i)))
else:
res.append(new_Expression_from_GEx(SR, seq.op(i)))
return tuple(res)
def unpack_operands(Expression ex):
"""
EXAMPLES::
sage: from sage.symbolic.pynac import unpack_operands
sage: t = SR._force_pyobject((1, 2, x, x+1, x+2))
sage: unpack_operands(t)
(1, 2, x, x + 1, x + 2)
sage: type(unpack_operands(t))
<type 'tuple'>
sage: map(type, unpack_operands(t))
[<type 'sage.rings.integer.Integer'>, <type 'sage.rings.integer.Integer'>, <type 'sage.symbolic.expression.Expression'>, <type 'sage.symbolic.expression.Expression'>, <type 'sage.symbolic.expression.Expression'>]
sage: u = SR._force_pyobject((t, x^2))
sage: unpack_operands(u)
((1, 2, x, x + 1, x + 2), x^2)
sage: type(unpack_operands(u)[0])
<type 'tuple'>
"""
return exprseq_to_PyTuple(ex._gobj)
cdef object exvector_to_PyTuple(GExVector seq):
"""
Converts arguments list given to a function to a PyTuple.
Used to pass arguments to python methods assigned to custom
evaluation, derivative, etc. functions of symbolic functions.
We convert Python objects wrapped in symbolic expressions back to regular
Python objects.
EXAMPLES::
sage: from sage.symbolic.function import BuiltinFunction
sage: class TFunc(BuiltinFunction):
....: def __init__(self):
....: BuiltinFunction.__init__(self, 'tfunc', nargs=0)
....:
....: def _eval_(self, *args):
....: print("len(args): %s, types: %s"%(len(args), str(map(type, args))))
sage: tfunc = TFunc()
sage: u = SR._force_pyobject((1, x+1, 2))
sage: tfunc(u, x, 3.0, 5.0r)
len(args): 4, types: [<type 'tuple'>, <type 'sage.symbolic.expression.Expression'>, <type 'sage.rings.real_mpfr.RealLiteral'>, <type 'float'>]
tfunc((1, x + 1, 2), x, 3.00000000000000, 5.0)
TESTS:
Check if symbolic functions in the arguments are preserved::
sage: tfunc(sin(x), tfunc(1, x^2))
len(args): 2, types: [<type 'sage.rings.integer.Integer'>, <type 'sage.symbolic.expression.Expression'>]
len(args): 2, types: [<type 'sage.symbolic.expression.Expression'>, <type 'sage.symbolic.expression.Expression'>]
tfunc(sin(x), tfunc(1, x^2))
"""
from sage.symbolic.ring import SR
res = []
for i in range(seq.size()):
if is_a_numeric(seq.at(i)):
res.append(py_object_from_numeric(seq.at(i)))
elif is_exactly_a_exprseq(seq.at(i)):
res.append(exprseq_to_PyTuple(seq.at(i)))
else:
res.append(new_Expression_from_GEx(SR, seq.at(i)))
return tuple(res)
cdef GEx pyExpression_to_ex(object res) except *:
"""
Converts an Expression object to a GiNaC::ex.
Used to pass return values of custom python evaluation, derivation
functions back to C++ level.
"""
if res is None:
raise TypeError("function returned None, expected return value of type sage.symbolic.expression.Expression")
try:
t = ring.SR.coerce(res)
except TypeError as err:
raise TypeError("function did not return a symbolic expression or an element that can be coerced into a symbolic expression")
return (<Expression>t)._gobj
cdef object paramset_to_PyTuple(const_paramset_ref s):
"""
Converts a std::multiset<unsigned> to a PyTuple.
Used to pass a list of parameter numbers with respect to which a function
is differentiated to the printing functions py_print_fderivative and
py_latex_fderivative.
"""
cdef GParamSetIter itr = s.begin()
res = []
while itr.is_not_equal(s.end()):
res.append(itr.obj())
itr.inc()
return res
def paramset_from_Expression(Expression e):
"""
EXAMPLES::
sage: from sage.symbolic.pynac import paramset_from_Expression
sage: f = function('f')
sage: paramset_from_Expression(f(x).diff(x))
[0L] # 32-bit
[0] # 64-bit
"""
return paramset_to_PyTuple(ex_to_fderivative(e._gobj).get_parameter_set())
cdef int GINAC_FN_SERIAL = 0
cdef set_ginac_fn_serial():
"""
Initialize the GINAC_FN_SERIAL variable to the number of functions
defined by GiNaC. This allows us to prevent collisions with C++ level
special functions when a user asks to construct a symbolic function
with the same name.
"""
global GINAC_FN_SERIAL
GINAC_FN_SERIAL = g_registered_functions().size()
cdef int py_get_ginac_serial():
"""
Returns the number of C++ level functions defined by GiNaC.
EXAMPLES::
sage: from sage.symbolic.pynac import get_ginac_serial
sage: get_ginac_serial() >= 35
True
"""
global GINAC_FN_SERIAL
return GINAC_FN_SERIAL
def get_ginac_serial():
"""
Number of C++ level functions defined by GiNaC. (Defined mainly for testing.)
EXAMPLES::
sage: sage.symbolic.pynac.get_ginac_serial() >= 35
True
"""
return py_get_ginac_serial()
cdef get_fn_serial_c():
"""
Return overall size of Pynac function registry.
"""
return g_registered_functions().size()
def get_fn_serial():
"""
Return the overall size of the Pynac function registry which
corresponds to the last serial value plus one.
EXAMPLE::
sage: from sage.symbolic.pynac import get_fn_serial
sage: from sage.symbolic.function import get_sfunction_from_serial
sage: get_fn_serial() > 125
True
sage: print(get_sfunction_from_serial(get_fn_serial()))
None
sage: get_sfunction_from_serial(get_fn_serial() - 1) is not None
True
"""
return get_fn_serial_c()
cdef object subs_args_to_PyTuple(const GExMap& map, unsigned options, const GExVector& seq):
"""
Convert arguments from ``GiNaC::subs()`` to a PyTuple.
EXAMPLES::
sage: from sage.symbolic.function import BuiltinFunction
sage: class TFunc(BuiltinFunction):
....: def __init__(self):
....: BuiltinFunction.__init__(self, 'tfunc', nargs=0)
....:
....: def _subs_(self, *args):
....: print("len(args): %s, types: %s"%(len(args), str(map(type, args))))
....: return args[-1]
sage: tfunc = TFunc()
sage: tfunc(x).subs(x=1)
len(args): 3, types: [<type 'sage.symbolic.substitution_map.SubstitutionMap'>,
<type 'int'>, # 64-bit
<type 'long'>, # 32-bit
<type 'sage.symbolic.expression.Expression'>]
x
"""
from sage.symbolic.ring import SR
res = []
res.append(new_SubstitutionMap_from_GExMap(map))
res.append(options)
return tuple(res) + exvector_to_PyTuple(seq)
#################################################################
# Printing helpers
#################################################################
##########################################################################
# Pynac's precedence levels, as extracted from the raw source code on
# 2009-05-15. If this changes in Pynac it could cause a bug in
# printing. But it's hardcoded in Pynac now, so there's not much to
# be done (at present).
# Container: 10
# Expairseq: 10
# Relational: 20
# Numeric: 30
# Pseries: 38
# Addition: 40
# Integral: 45
# Multiplication: 50
# Noncummative mult: 50
# Index: 55
# Power: 60
# Clifford: 65
# Function: 70
# Structure: 70
##########################################################################
cdef stdstring* py_repr(object o, int level) except +:
"""
Return string representation of o. If level > 0, possibly put
parentheses around the string.
"""
s = repr(o)
if level >= 20:
# s may need parens (e.g., is in an exponent), so decide if we
# have to put parentheses around s:
# A regexp might seem better, but I don't think it's really faster.
# It would be more readable. Python does the below (with in) very quickly.
if level <= 50:
t = s[1:] # ignore leading minus
else:
t = s
# Python complexes are always printed with parentheses
# we try to avoid double parantheses
if type(o) is not complex and \
(' ' in t or '/' in t or '+' in t or '-' in t or '*' in t \
or '^' in t):
s = '(%s)'%s
return string_from_pystr(s)
cdef stdstring* py_latex(object o, int level) except +:
"""
Return latex string representation of o. If level > 0, possibly
put parentheses around the string.
"""
from sage.misc.latex import latex
s = latex(o)
if level >= 20:
if ' ' in s or '/' in s or '+' in s or '-' in s or '*' in s or '^' in s or '\\frac' in s:
s = '\\left(%s\\right)'%s
return string_from_pystr(s)
cdef stdstring* string_from_pystr(object py_str):
"""
Creates a C++ string with the same contents as the given python string.
Used when passing string output to Pynac for printing, since we don't want
to mess with reference counts of the python objects and we cannot guarantee
they won't be garbage collected before the output is printed.
WARNING: You *must* call this with py_str a str type, or it will segfault.
"""
cdef char *t_str = PyString_AsString(py_str)
cdef Py_ssize_t slen = len(py_str)
cdef stdstring* sout = stdstring_construct_cstr(t_str, slen)
return sout
cdef stdstring* py_latex_variable(char* var_name) except +:
"""
Returns a c++ string containing the latex representation of the given
variable name.
Real work is done by the function sage.misc.latex.latex_variable_name.
EXAMPLES::
sage: from sage.symbolic.pynac import py_latex_variable_for_doctests
sage: py_latex_variable = py_latex_variable_for_doctests
sage: py_latex_variable('a')
a
sage: py_latex_variable('abc')
\mathit{abc}
sage: py_latex_variable('a_00')
a_{00}
sage: py_latex_variable('sigma_k')
\sigma_{k}
sage: py_latex_variable('sigma389')
\sigma_{389}
sage: py_latex_variable('beta_00')
\beta_{00}
"""
cdef Py_ssize_t slen
from sage.misc.latex import latex_variable_name
py_vlatex = latex_variable_name(var_name)
return string_from_pystr(py_vlatex)
def py_latex_variable_for_doctests(x):
"""
Internal function used so we can doctest a certain cdef'd method.
EXAMPLES::
sage: sage.symbolic.pynac.py_latex_variable_for_doctests('x')
x
sage: sage.symbolic.pynac.py_latex_variable_for_doctests('sigma')
\sigma
"""
assert isinstance(x, str)
cdef stdstring* ostr = py_latex_variable(PyString_AsString(x))
print(ostr.c_str())
stdstring_delete(ostr)
def py_print_function_pystring(id, args, fname_paren=False):
"""
Return a string with the representation of the symbolic function specified
by the given id applied to args.
INPUT:
- id -- serial number of the corresponding symbolic function
- params -- Set of parameter numbers with respect to which to take the
derivative.
- args -- arguments of the function.
EXAMPLES::
sage: from sage.symbolic.pynac import py_print_function_pystring, get_ginac_serial, get_fn_serial
sage: from sage.symbolic.function import get_sfunction_from_serial
sage: var('x,y,z')
(x, y, z)
sage: foo = function('foo', nargs=2)
sage: for i in range(get_ginac_serial(), get_fn_serial()):
... if get_sfunction_from_serial(i) == foo: break
sage: get_sfunction_from_serial(i) == foo
True
sage: py_print_function_pystring(i, (x,y))
'foo(x, y)'
sage: py_print_function_pystring(i, (x,y), True)
'(foo)(x, y)'
sage: def my_print(self, *args): return "my args are: " + ', '.join(map(repr, args))
sage: foo = function('foo', nargs=2, print_func=my_print)
sage: for i in range(get_ginac_serial(), get_fn_serial()):
... if get_sfunction_from_serial(i) == foo: break
sage: get_sfunction_from_serial(i) == foo
True
sage: py_print_function_pystring(i, (x,y))
'my args are: x, y'
"""
cdef Function func = get_sfunction_from_serial(id)
# This function is called from two places, from function::print in Pynac
# and from py_print_fderivative. function::print checks if the serial
# belongs to a function defined at the C++ level. There are no C++ level
# functions that return an instance of fderivative when derivated. Hence,
# func will never be None.
assert(func is not None)
# if function has a custom print function call it
if hasattr(func,'_print_'):
res = func._print_(*args)
# make sure the output is a string
if res is None:
return ""
if not isinstance(res, str):
return str(res)
return res
# otherwise use default output
if fname_paren:
olist = ['(', func._name, ')']
else:
olist = [func._name]
olist.extend(['(', ', '.join(map(repr, args)), ')'])
return ''.join(olist)
cdef stdstring* py_print_function(unsigned id, object args) except +:
return string_from_pystr(py_print_function_pystring(id, args))
def py_latex_function_pystring(id, args, fname_paren=False):
r"""
Return a string with the latex representation of the symbolic function
specified by the given id applied to args.
See documentation of py_print_function_pystring for more information.
EXAMPLES::
sage: from sage.symbolic.pynac import py_latex_function_pystring, get_ginac_serial, get_fn_serial
sage: from sage.symbolic.function import get_sfunction_from_serial
sage: var('x,y,z')
(x, y, z)
sage: foo = function('foo', nargs=2)
sage: for i in range(get_ginac_serial(), get_fn_serial()):
... if get_sfunction_from_serial(i) == foo: break
sage: get_sfunction_from_serial(i) == foo
True
sage: py_latex_function_pystring(i, (x,y^z))
'{\\rm foo}\\left(x, y^{z}\\right)'
sage: py_latex_function_pystring(i, (x,y^z), True)
'\\left({\\rm foo}\\right)\\left(x, y^{z}\\right)'
sage: py_latex_function_pystring(i, (int(0),x))
'{\\rm foo}\\left(0, x\\right)'
Test latex_name::
sage: foo = function('foo', nargs=2, latex_name=r'\mathrm{bar}')
sage: for i in range(get_ginac_serial(), get_fn_serial()):
... if get_sfunction_from_serial(i) == foo: break
sage: get_sfunction_from_serial(i) == foo
True
sage: py_latex_function_pystring(i, (x,y^z))
'\\mathrm{bar}\\left(x, y^{z}\\right)'
Test custom func::
sage: def my_print(self, *args): return "my args are: " + ', '.join(map(repr, args))
sage: foo = function('foo', nargs=2, print_latex_func=my_print)
sage: for i in range(get_ginac_serial(), get_fn_serial()):
... if get_sfunction_from_serial(i) == foo: break
sage: get_sfunction_from_serial(i) == foo
True
sage: py_latex_function_pystring(i, (x,y^z))
'my args are: x, y^z'
"""
cdef Function func = get_sfunction_from_serial(id)
# This function is called from two places, from function::print in Pynac
# and from py_latex_fderivative. function::print checks if the serial
# belongs to a function defined at the C++ level. There are no C++ level
# functions that return an instance of fderivative when derivated. Hence,
# func will never be None.
assert(func is not None)
# if function has a custom print method call it
if hasattr(func, '_print_latex_'):
res = func._print_latex_(*args)
# make sure the output is a string
if res is None:
return ""
if not isinstance(res, str):
return str(res)
return res
# otherwise, use the latex name if defined
if func._latex_name:
name = func._latex_name
else:
# if latex_name is not defined, then call
# latex_variable_name with "is_fname=True" flag
from sage.misc.latex import latex_variable_name
name = latex_variable_name(func._name, is_fname=True)
if fname_paren:
olist = [r'\left(', name, r'\right)']
else:
olist = [name]
# print the arguments
from sage.misc.latex import latex
olist.extend([r'\left(', ', '.join([latex(x) for x in args]),
r'\right)'] )
return ''.join(olist)
cdef stdstring* py_latex_function(unsigned id, object args) except +:
return string_from_pystr(py_latex_function_pystring(id, args))
def tolerant_is_symbol(a):
"""
Utility function to test if something is a symbol.
Returns False for arguments that do not have an is_symbol attribute.
Returns the result of calling the is_symbol method otherwise.
EXAMPLES::
sage: from sage.symbolic.pynac import tolerant_is_symbol
sage: tolerant_is_symbol(var("x"))
True
sage: tolerant_is_symbol(None)
False
sage: None.is_symbol()
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute 'is_symbol'
"""
try:
return a.is_symbol()
except AttributeError:
return False
cdef stdstring* py_print_fderivative(unsigned id, object params,
object args) except +:
"""
Return a string with the representation of the derivative of the symbolic
function specified by the given id, lists of params and args.
INPUT:
- id -- serial number of the corresponding symbolic function
- params -- Set of parameter numbers with respect to which to take the
derivative.
- args -- arguments of the function.
"""
if all([tolerant_is_symbol(a) for a in args]) and len(set(args))==len(args):
diffvarstr = ', '.join([repr(args[i]) for i in params])
py_res = ''.join(['diff(',py_print_function_pystring(id,args,False),', ',diffvarstr,')'])
else:
ostr = ''.join(['D[', ', '.join([repr(int(x)) for x in params]), ']'])
fstr = py_print_function_pystring(id, args, True)
py_res = ostr + fstr
return string_from_pystr(py_res)
def py_print_fderivative_for_doctests(id, params, args):
"""
Used for testing a cdef'd function.
EXAMPLES::
sage: from sage.symbolic.pynac import py_print_fderivative_for_doctests as py_print_fderivative, get_ginac_serial, get_fn_serial
sage: var('x,y,z')
(x, y, z)
sage: from sage.symbolic.function import get_sfunction_from_serial
sage: foo = function('foo', nargs=2)
sage: for i in range(get_ginac_serial(), get_fn_serial()):
....: if get_sfunction_from_serial(i) == foo: break
sage: get_sfunction_from_serial(i) == foo
True
sage: py_print_fderivative(i, (0, 1, 0, 1), (x, y^z))
D[0, 1, 0, 1](foo)(x, y^z)
Test custom print function::
sage: def my_print(self, *args): return "func_with_args(" + ', '.join(map(repr, args)) +')'
sage: foo = function('foo', nargs=2, print_func=my_print)
sage: for i in range(get_ginac_serial(), get_fn_serial()):
....: if get_sfunction_from_serial(i) == foo: break
sage: get_sfunction_from_serial(i) == foo
True
sage: py_print_fderivative(i, (0, 1, 0, 1), (x, y^z))
D[0, 1, 0, 1]func_with_args(x, y^z)
"""
cdef stdstring* ostr = py_print_fderivative(id, params, args)
print(ostr.c_str())
stdstring_delete(ostr)
cdef stdstring* py_latex_fderivative(unsigned id, object params,
object args) except +:
"""
Return a string with the latex representation of the derivative of the
symbolic function specified by the given id, lists of params and args.
See documentation of py_print_fderivative for more information.
"""
if all([tolerant_is_symbol(a) for a in args]) and len(set(args))==len(args):
param_iter=iter(params)
v=next(param_iter)
nv=1
diff_args=[]
for next_v in param_iter:
if next_v == v:
nv+=1
else:
if nv == 1:
diff_args.append(r"\partial %s"%(args[v]._latex_(),))
else:
diff_args.append(r"(\partial %s)^{%s}"%(args[v]._latex_(),nv))
v=next_v
nv=1
if nv == 1:
diff_args.append(r"\partial %s"%(args[v]._latex_(),))
else:
diff_args.append(r"(\partial %s)^{%s}"%(args[v]._latex_(),nv))
if len(params) == 1:
operator_string=r"\frac{\partial}{%s}"%(''.join(diff_args),)
else:
operator_string=r"\frac{\partial^{%s}}{%s}"%(len(params),''.join(diff_args))
py_res = operator_string+py_latex_function_pystring(id,args,False)
else:
ostr = ''.join(['\mathrm{D}_{',', '.join([repr(int(x)) for x in params]), '}'])
fstr = py_latex_function_pystring(id, args, True)
py_res = ostr + fstr
return string_from_pystr(py_res)
def py_latex_fderivative_for_doctests(id, params, args):
r"""
Used internally for writing doctests for certain cdef'd functions.
EXAMPLES::
sage: from sage.symbolic.pynac import py_latex_fderivative_for_doctests as py_latex_fderivative, get_ginac_serial, get_fn_serial
sage: var('x,y,z')
(x, y, z)
sage: from sage.symbolic.function import get_sfunction_from_serial
sage: foo = function('foo', nargs=2)
sage: for i in range(get_ginac_serial(), get_fn_serial()):
... if get_sfunction_from_serial(i) == foo: break
sage: get_sfunction_from_serial(i) == foo
True
sage: py_latex_fderivative(i, (0, 1, 0, 1), (x, y^z))
\mathrm{D}_{0, 1, 0, 1}\left({\rm foo}\right)\left(x, y^{z}\right)
Test latex_name::
sage: foo = function('foo', nargs=2, latex_name=r'\mathrm{bar}')
sage: for i in range(get_ginac_serial(), get_fn_serial()):
... if get_sfunction_from_serial(i) == foo: break
sage: get_sfunction_from_serial(i) == foo
True
sage: py_latex_fderivative(i, (0, 1, 0, 1), (x, y^z))
\mathrm{D}_{0, 1, 0, 1}\left(\mathrm{bar}\right)\left(x, y^{z}\right)
Test custom func::
sage: def my_print(self, *args): return "func_with_args(" + ', '.join(map(repr, args)) +')'
sage: foo = function('foo', nargs=2, print_latex_func=my_print)
sage: for i in range(get_ginac_serial(), get_fn_serial()):
... if get_sfunction_from_serial(i) == foo: break
sage: get_sfunction_from_serial(i) == foo
True
sage: py_latex_fderivative(i, (0, 1, 0, 1), (x, y^z))
\mathrm{D}_{0, 1, 0, 1}func_with_args(x, y^z)
"""
cdef stdstring* ostr = py_latex_fderivative(id, params, args)
print(ostr.c_str())
stdstring_delete(ostr)
#################################################################
# Archive helpers
#################################################################
from sage.structure.sage_object import loads, dumps
cdef stdstring* py_dumps(object o) except +:
s = dumps(o, compress=False)
# pynac archive format terminates atoms with zeroes.
# since pickle output can break the archive format
# we use the base64 data encoding
import base64
s = base64.b64encode(s)
return string_from_pystr(s)
cdef object py_loads(object s) except +:
import base64
s = base64.b64decode(s)
return loads(s)
cdef object py_get_sfunction_from_serial(unsigned s) except +:
"""
Return the Python object associated with a serial.
"""
return get_sfunction_from_serial(s)
cdef unsigned py_get_serial_from_sfunction(object f) except +:
"""
Given a Function object return its serial.
Python's unpickling mechanism is used to unarchive a symbolic function with
custom methods (evaluation, differentiation, etc.). Pynac extracts a string
representation from the archive, calls loads() to recreate the stored
function. This allows us to extract the serial from the Python object to
set the corresponding member variable of the C++ object representing this
function.
"""
return (<Function>f)._serial
cdef unsigned py_get_serial_for_new_sfunction(stdstring &s,
unsigned nargs) except +:
"""
Return a symbolic function with the given name and number of arguments.
When unarchiving a user defined symbolic function, Pynac goes through
the registry of existing functions. If there is no function already defined
with the archived name and number of arguments, this method is called to
create one and set up the function tables properly.
"""
from sage.symbolic.function_factory import function_factory
cdef Function fn = function_factory(s.c_str(), nargs)
return fn._serial
#################################################################
# Modular helpers
#################################################################
cdef int py_get_parent_char(o) except -1:
"""
TESTS:
We check that :trac:`21187` is resolved::
sage: p = next_prime(2^100)
sage: R.<y> = FiniteField(p)[]
sage: y = SR(y)
sage: x + y
x + y
sage: p * y
0
"""
if not isinstance(o, Element):
return 0
c = (<Element>o)._parent.characteristic()
# Pynac only differentiates between
# - characteristic 0
# - characteristic 2
# - characteristic > 0 but not 2
#
# To avoid integer overflow in the last case, we just return 3
# instead of the actual characteristic.
if not c:
return 0
elif c == 2:
return 2
else:
return 3
#################################################################
# power helpers
#################################################################
from sage.rings.rational cimport rational_power_parts
cdef object py_rational_power_parts(object base, object exp) except +:
if type(base) is not Rational:
base = Rational(base)
if type(exp) is not Rational:
exp = Rational(exp)
res= rational_power_parts(base, exp)
return res + (bool(res[0] == 1),)
#################################################################
# Binomial Coefficients
#################################################################
cdef object py_binomial_int(int n, unsigned int k) except +:
cdef bint sign
if n < 0:
n = -n + (k-1)
sign = k%2
else:
sign = 0
cdef Integer ans = PY_NEW(Integer)
# Compute the binomial coefficient using GMP.
mpz_bin_uiui(ans.value, n, k)
# Return the answer or the negative of it (only if k is odd and n is negative).
if sign:
return -ans
else:
return ans
cdef object py_binomial(object n, object k) except +:
# Keep track of the sign we should use.
cdef bint sign
if n < 0:
n = k-n-1
sign = k%2
else:
sign = 0
# Convert n and k to unsigned ints.
cdef unsigned int n_ = n, k_ = k
cdef Integer ans = PY_NEW(Integer)
# Compute the binomial coefficient using GMP.
mpz_bin_uiui(ans.value, n_, k_)
# Return the answer or the negative of it (only if k is odd and n is negative).
if sign:
return -ans
else:
return ans
def test_binomial(n, k):
"""
The Binomial coefficients. It computes the binomial coefficients. For
integer n and k and positive n this is the number of ways of choosing k
objects from n distinct objects. If n is negative, the formula
binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result.
INPUT:
- n, k -- integers, with k >= 0.
OUTPUT:
integer
EXAMPLES::
sage: import sage.symbolic.pynac
sage: sage.symbolic.pynac.test_binomial(5,2)
10
sage: sage.symbolic.pynac.test_binomial(-5,3)
-35
sage: -sage.symbolic.pynac.test_binomial(3-(-5)-1, 3)
-35
"""
return py_binomial(n, k)
#################################################################
# GCD
#################################################################
cdef object py_gcd(object n, object k) except +:
if isinstance(n, Integer) and isinstance(k, Integer):
if mpz_cmp_si((<Integer>n).value,1) == 0:
return n
elif mpz_cmp_si((<Integer>k).value,1) == 0:
return k
return n.gcd(k)
if type(n) is Rational and type(k) is Rational:
return n.content(k)
try:
return gcd(n,k)
except (TypeError, ValueError, AttributeError):
# some strange meaning in case of weird things with no usual lcm.
return 1
#################################################################
# LCM
#################################################################
cdef object py_lcm(object n, object k) except +:
if isinstance(n, Integer) and isinstance(k, Integer):
if mpz_cmp_si((<Integer>n).value,1) == 0:
return k
elif mpz_cmp_si((<Integer>k).value,1) == 0:
return n
return n.lcm(k)
try:
return lcm(n,k)
except (TypeError, ValueError, AttributeError):
# some strange meaning in case of weird things with no usual lcm, e.g.,
# elements of finite fields.
return 1
#################################################################
# Real Part
#################################################################
cdef object py_real(object x) except +:
"""
Returns the real part of x.
TESTS::
sage: from sage.symbolic.pynac import py_real_for_doctests as py_real
sage: py_real(I)
0
sage: py_real(CC(1,5))
1.00000000000000
sage: py_real(CC(1))
1.00000000000000
sage: py_real(RR(1))
1.00000000000000
sage: py_real(Mod(2,7))
2
sage: py_real(QQ['x'].gen())
x
sage: py_real(float(2))
2.0
sage: py_real(complex(2,2))
2.0
"""
if type(x) is float or type(x) is int or \
type(x) is long:
return x
elif type(x) is complex:
return x.real
try:
return x.real()
except AttributeError:
pass
try:
return x.real_part()
except AttributeError:
pass
return x # assume x is real