-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgiac.pyx
2053 lines (1667 loc) · 64.3 KB
/
giac.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
r"""
Interface to the c++ giac library.
Giac is a general purpose Computer algebra system by Bernard Parisse
released under GPLv3.
- http://www-fourier.ujf-grenoble.fr/~parisse/giac.html
- It is build on C and C++ libraries: NTL (arithmetic), GSL (numerics), GMP
(big integers), MPFR (bigfloats)
- It provides fast algorithms for multivariate polynomial operations
(product, GCD, factorisation) and
- symbolic computations: solver, simplifications, limits/series, integration,
summation...
- Linear Algebra with numerical or symbolic coefficients.
AUTHORS:
- Frederic Han (2013-09-23): initial version
- Vincent Delecroix (2020-09-02): move inside Sage source code
EXAMPLES:
The class Pygen is the main tool to interact from python/sage with the c++
library giac via cython. The initialisation of a Pygen just create an object
in giac, but the mathematical computation is not done. This class is mainly
for cython users. Here A is a Pygen element, and it is ready for any giac
function.::
>>> from sagemath_giac.giac import *
>>> A = Pygen('2+2')
>>> A
2+2
>>> A.eval()
4
In general, you may prefer to directly create a Pygen and execute the
evaluation in giac. This is exactly the meaning of the :func:`libgiac`
function.::
>>> a = libgiac('2+2')
>>> a
4
>>> isinstance(a, Pygen)
True
Most common usage of this package in sage will be with the libgiac() function.
This function is just the composition of the Pygen initialisation and the
evaluation of this object in giac.::
>>> x,y,z = libgiac('x,y,z') # add some giac objects
>>> f = (x+y*3)/(x+z+1)**2 - (x+z+1)**2 / (x+y*3)
>>> f.factor()
(3*y-x^2-2*x*z-x-z^2-2*z-1)*(3*y+x^2+2*x*z+3*x+z^2+2*z+1)/((x+z+1)^2*(3*y+x))
>>> f.normal()
(-x^4-4*x^3*z-4*x^3-6*x^2*z^2-12*x^2*z-5*x^2+6*x*y-4*x*z^3-12*x*z^2-12*x*z-4*x+9*y^2-z^4-4*z^3-6*z^2-4*z-1)/(x^3+3*x^2*y+2*x^2*z+2*x^2+6*x*y*z+6*x*y+x*z^2+2*x*z+x+3*y*z^2+6*y*z+3*y)
Some settings of giac are available via the ``giacsettings``
element. (Ex: maximal number of threads in computations, allowing
probabilistic algorithms or not...::
>>> from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
>>> from sage.rings.rational_field import QQ
>>> from sage.rings.ideal import Katsura as KatsuraIdeal
>>> R = PolynomialRing(QQ,8,'x')
>>> I = KatsuraIdeal(R,8)
>>> giacsettings.proba_epsilon = 1e-15 # faster, but can fail
>>> Igiac = libgiac(I.gens());
>>> Bgiac = Igiac.gbasis([R.gens()],'revlex')
>>> len(Bgiac)
74
>>> giacsettings.proba_epsilon = 0 # slower, but more reliable
>>> Igiac = libgiac(I.gens())
>>> Bgiac = Igiac.gbasis([R.gens()],'revlex')
>>> len(Bgiac)
74
>>> giacsettings.proba_epsilon = 1e-15
::
>>> x = libgiac('x')
>>> f = libgiac(1) / (libgiac.sin(x*5)+2)
>>> f.int()
2/5/sqrt(3)*(atan((-sqrt(3)*sin(5*x)+cos(5*x)+2*sin(5*x)+1)/(sqrt(3)*cos(5*x)+sqrt(3)-2*cos(5*x)+sin(5*x)+2))+5*x/2)
>>> f.series(x,0,3)
1/2-5/4*x+25/8*x^2-125/48*x^3+x^4*order_size(x)
>>> (libgiac.sqrt(5)+libgiac.pi).approx(100)
5.377660631089582934871817052010779119637787758986631545245841837718337331924013898042449233720899343
TESTS::
>>> from sagemath_giac.giac import libgiac
>>> libgiac(3**100)
515377520732011331036461129765621272702107522001
>>> libgiac(-3**100)
-515377520732011331036461129765621272702107522001
>>> libgiac(-11**1000)
-2469932918005826334124088385085221477709733385238396234869182951830739390375433175367866116456946191973803561189036523363533798726571008961243792655536655282201820357872673322901148243453211756020067624545609411212063417307681204817377763465511222635167942816318177424600927358163388910854695041070577642045540560963004207926938348086979035423732739933235077042750354729095729602516751896320598857608367865475244863114521391548985943858154775884418927768284663678512441565517194156946312753546771163991252528017732162399536497445066348868438762510366191040118080751580689254476068034620047646422315123643119627205531371694188794408120267120500325775293645416335230014278578281272863450085145349124727476223298887655183167465713337723258182649072572861625150703747030550736347589416285606367521524529665763903537989935510874657420361426804068643262800901916285076966174176854351055183740078763891951775452021781225066361670593917001215032839838911476044840388663443684517735022039957481918726697789827894303408292584258328090724141496484460001
Ensure that signed infinities get converted correctly::
>>> from sage.rings.infinity import Infinity
>>> libgiac(+Infinity)
+infinity
>>> libgiac(-Infinity)
-infinity
.. SEEALSO::
``libgiac``, ``giacsettings``, ``Pygen``,``loadgiacgen``
GETTING HELP:
- To obtain some help on a giac keyword use the help() method. In sage the
htmlhelp() method for Pygen element is disabled. Just use the ? or .help()
method.
- You can find full html documentation about the **giac** functions at:
- https://www-fourier.ujf-grenoble.fr/~parisse/giac/doc/en/cascmd_en/
- https://www-fourier.ujf-grenoble.fr/~parisse/giac/doc/fr/cascmd_fr/
- https://www-fourier.ujf-grenoble.fr/~parisse/giac/doc/el/cascmd_el/
"""
# ****************************************************************************
# Copyright (C) 2012, Frederic Han <[email protected]>
# 2020, Vincent Delecroix <[email protected]>
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
# https://www.gnu.org/licenses/
#*****************************************************************************
from cysignals.signals cimport *
from gmpy2 cimport import_gmpy2, mpz_set
from sys import maxsize as Pymaxint, version_info as Pyversioninfo
import os
import math
# sage includes
from sage.ext.stdsage cimport PY_NEW
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.finite_rings.integer_mod_ring import IntegerModRing
from sage.rings.integer cimport Integer
from sage.rings.infinity import AnInfinity
from sage.rings.rational cimport Rational
from sage.structure.element cimport Matrix
from sage.symbolic.expression import symbol_table
from sage.calculus.calculus import symbolic_expression_from_string, SR_parser_giac
from sage.symbolic.ring import SR
from sage.symbolic.expression import Expression
from sage.symbolic.expression_conversions import InterfaceInit
from sage.interfaces.giac import giac
# initialize the gmpy2 C-API
import_gmpy2()
# Python3 compatibility ############################
def encstring23(s):
return bytes(s, 'UTF-8')
# End of Python3 compatibility #####################
########################################################
# A global context pointer. One by giac session.
########################################################
cdef context * context_ptr = new context()
# Some global variables for optimisation
GIACNULL = Pygen('NULL')
# Create a giac setting instance
giacsettings = GiacSetting()
Pygen('I:=sqrt(-1)').eval() # WTF?
# A function to convert SR Expression with defined giac conversion to a string
# for giac/libgiac.
# NB: We want to do this without starting an external giac program and
# self._giac_() does.
SRexpressiontoGiac = InterfaceInit(giac)
#######################################################
# The wrapper to eval with giac
#######################################################
# in sage we don't export the giac function. We replace it by libgiac
def _giac(s):
"""
This function evaluate a python/sage object with the giac
library. It creates in python/sage a Pygen element and evaluate it
with giac:
EXAMPLES::
>>> from sagemath_giac.giac import libgiac
>>> x,y = libgiac('x,y')
>>> (x + y*2).cos().texpand()
cos(x)*(2*cos(y)^2-1)-sin(x)*2*cos(y)*sin(y)
Coercion, Pygen and internal giac variables: The most useful
objects will be the Python object of type Pygen::
>>> x,y,z = libgiac('x,y,z')
>>> f = sum([x[i] for i in range(5)], libgiac(0))**15/(y+z)
>>> f.coeff(x[0],12)
(455*(x[1])^3+1365*(x[1])^2*x[2]+1365*(x[1])^2*x[3]+1365*(x[1])^2*x[4]+1365*x[1]*(x[2])^2+2730*x[1]*x[2]*x[3]+2730*x[1]*x[2]*x[4]+1365*x[1]*(x[3])^2+2730*x[1]*x[3]*x[4]+1365*x[1]*(x[4])^2+455*(x[2])^3+1365*(x[2])^2*x[3]+1365*(x[2])^2*x[4]+1365*x[2]*(x[3])^2+2730*x[2]*x[3]*x[4]+1365*x[2]*(x[4])^2+455*(x[3])^3+1365*(x[3])^2*x[4]+1365*x[3]*(x[4])^2+455*(x[4])^3)/(y+z)
Warning: The complex number sqrt(-1) is available in SageMath as
``I``, but it may appears as ``i``::
>>> from sage.rings.imaginary_unit import I
>>> libgiac((libgiac.sqrt(3)*I + 1)**3).normal()
-8
>>> libgiac(1+I)
1+i
Python integers and reals can be directly converted to giac.::
>>> libgiac(2**1024).nextprime()
179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137859
>>> libgiac(1.234567).erf().approx(10)
0.9191788641
The Python object ``y`` defined above is of type Pygen. It is not
an internal giac variable. (Most of the time you won't need to use
internal giac variables)::
>>> libgiac('y:=1'); y
1
y
>>> libgiac.purge('y')
1
>>> libgiac('y')
y
There are some natural coercion to Pygen elements::
>>> libgiac.pi > 3.14
True
>>> libgiac.pi > 3.15
False
>>> libgiac(3) == 3
True
Linear Algebra. In Giac/Xcas vectors are just lists and matrices
are lists of list::
>>> x,y = libgiac('x,y')
>>> A = libgiac([[1,2],[3,4]]) # giac matrix
>>> v = libgiac([x,y]); v # giac vector
[x,y]
>>> A*v # matrix-vector product
[x+2*y,3*x+4*y]
>>> v*v # dot product
x*x+y*y
Remark that ``w=giac([[x],[y]])`` is a matrix of 1 column and 2
rows. It is not a vector so w*w doesn't make sense.::
>>> w = libgiac([[x],[y]])
>>> w.transpose()*w
matrix[[x*x+y*y]]
In sage, changing an entry doesn't create a new matrix (see also
the doc of ``Pygen.__setitem__``)::
>>> B1 = A
>>> B1[0,0]=43; B1 # in place affectation changes both B1 and A
[[43,2],[3,4]]
>>> A
[[43,2],[3,4]]
>>> A[0][0]=A[0][0]+1; A # similar as A[0,0]=A[0,0]+1
[[44,2],[3,4]]
>>> A.pcar(x) # compute the characteristic polynomial of A
x^2-48*x+170
>>> B2=A.copy() # use copy to create another object
>>> B2[0,0]=55; B2 # here A is not modified
[[55,2],[3,4]]
>>> A
[[44,2],[3,4]]
Sparse Matrices are available via the table function::
>>> A = libgiac.table(()); A # create an empty giac table
table(
)
>>> A[2,3] = 33; A[0,2] = '2/7' # set nonzero entries of the sparse matrix
>>> A*A # basic matrix operation are supported with sparse matrices
table(
(0,3) = 66/7
)
>>> D = libgiac.diag([22,3,'1/7']); D # some diagonal matrix
[[22,0,0],[0,3,0],[0,0,1/7]]
>>> libgiac.table(D) # to create a sparse matrix from an ordinary one
table(
(0,0) = 22,
(1,1) = 3,
(2,2) = 1/7
)
But many matrix functions apply only with ordinary matrices so
need conversions::
>>> B1 = A.matrix(); B1 # convert the sparse matrix to a matrix, but the size is minimal
[[0,0,2/7,0],[0,0,0,0],[0,0,0,33]]
>>> B2 = B1.redim(4,4) # so we may need to resize B1
>>> B2.pmin(x)
x^3
Lists of Pygen and Giac lists. Here l1 is a giac list and l2 is a
python list of Pygen type objects::
>>> l1 = libgiac(range(10))
>>> l2 = [libgiac(1)/(i**2+1) for i in l1]
>>> sum(l2, libgiac(0))
33054527/16762850
So l1+l1 is done in giac and means a vector addition. But l2+l2 is
done in Python so it is the list concatenation::
>>> l1+l1
[0,2,4,6,8,10,12,14,16,18]
>>> l2+l2
[1, 1/2, 1/5, 1/10, 1/17, 1/26, 1/37, 1/50, 1/65, 1/82, 1, 1/2, 1/5, 1/10, 1/17, 1/26, 1/37, 1/50, 1/65, 1/82]
Here V is not a Pygen element. We need to push it to giac to use a
giac method like dim, or we need to use an imported function::
>>> V = [ [x[i]**j for i in range(8)] for j in range(8)]
>>> libgiac(V).dim()
[8,8]
>>> libgiac.det_minor(V).factor()
(x[6]-(x[7]))*(x[5]-(x[7]))*(x[5]-(x[6]))*(x[4]-(x[7]))*(x[4]-(x[6]))*(x[4]-(x[5]))*(x[3]-(x[7]))*(x[3]-(x[6]))*(x[3]-(x[5]))*(x[3]-(x[4]))*(x[2]-(x[7]))*(x[2]-(x[6]))*(x[2]-(x[5]))*(x[2]-(x[4]))*(x[2]-(x[3]))*(x[1]-(x[7]))*(x[1]-(x[6]))*(x[1]-(x[5]))*(x[1]-(x[4]))*(x[1]-(x[3]))*(x[1]-(x[2]))*(x[0]-(x[7]))*(x[0]-(x[6]))*(x[0]-(x[5]))*(x[0]-(x[4]))*(x[0]-(x[3]))*(x[0]-(x[2]))*(x[0]-(x[1]))
Modular objects with ``%``::
>>> V = libgiac.ranm(5,6) % 2
>>> V.ker().rowdim()+V.rank()
6
>>> a = libgiac(7)%3
>>> a
1 % 3
>>> a % 0
1
>>> 7 % 3
1
Do not confuse with the python integers::
>>> type(7 % 3) == type(a)
False
>>> type(a) == type(7 % 3)
False
Syntax with reserved or unknown Python/sage symbols. In general
equations needs symbols such as ``=``, ``<`` or ``>`` that have
another meaning in Python or Sage. So those objects must be
quoted::
>>> x = libgiac('x')
>>> (libgiac.sin(x*3)*2 + 1).solve(x).simplify()
list[-pi/18,7*pi/18]
>>> libgiac.solve('x^3-x>x',x)
list[((x>(-sqrt(2))) and (x<0)),x>(sqrt(2))]
You can also add some hypothesis to a giac symbol::
>>> libgiac.assume('x>-pi && x<pi')
x
>>> libgiac.solve('sin(3*x)>2*sin(x)',x)
list[((x>(-5*pi/6)) and (x<(-pi/6))),((x>0) and (x<(pi/6))),((x>(5*pi/6)) and (x<pi))]
To remove those hypothesis use the giac function ``purge``::
>>> libgiac.purge('x')
assume[[],[line[-pi,pi]],[-pi,pi]]
>>> libgiac.solve('x>0')
list[x>0]
Same problems with the ``..``::
>>> x = libgiac('x')
>>> f = libgiac(1)/(libgiac.cos(x*4)+5)
>>> f.int()
1/2/(2*sqrt(6))*(atan((-sqrt(6)*sin(4*x)+2*sin(4*x))/(sqrt(6)*cos(4*x)+sqrt(6)-2*cos(4*x)+2))+4*x/2)
>>> libgiac.fMax(f,'x=-0..pi').simplify()
pi/4,3*pi/4
>>> libgiac.sum(libgiac(1)/(x**2+1),'x=0..infinity').simplify()
(pi*exp(pi)^2+pi+exp(pi)^2-1)/(2*exp(pi)^2-2)
From giac to sage. One can convert a Pygen element to sage with
the ``sage`` method::
>>> L = libgiac('[1,sqrt(5),[1.3,x]]')
>>> L.sage() # All entries are converted recursively
[1, sqrt(5), [1.30000000000000, x]]
>>> from sage.symbolic.ring import SR
>>> from sage.matrix.constructor import matrix
>>> n = SR.symbol('n')
>>> A = matrix([[1,2],[-1,1]])
>>> B = libgiac(A).matpow(n) # We compute the symbolic power on A via libgiac
>>> C = matrix(SR,B); C # We convert B to sage
[ 1/2*(I*sqrt(2) + 1)^n + 1/2*(-I*sqrt(2) + 1)^n -1/2*I*sqrt(2)*(I*sqrt(2) + 1)^n + 1/2*I*sqrt(2)*(-I*sqrt(2) + 1)^n]
[ 1/4*I*sqrt(2)*(I*sqrt(2) + 1)^n - 1/4*I*sqrt(2)*(-I*sqrt(2) + 1)^n 1/2*(I*sqrt(2) + 1)^n + 1/2*(-I*sqrt(2) + 1)^n]
>>> (C.subs(n=3)-A**3).expand()
[0 0]
[0 0]
**MEMENTO of usual GIAC functions**:
- *Expand with simplification*
* ``ratnormal``, ``normal``, ``simplify`` (from the fastest to the most sophisticated)
* NB: ``expand`` function doesn't regroup nor cancel terms, so it could be slow. (pedagogical purpose only?)
- *Factor/Regroup*
* ``factor``, ``factors``, ``regroup``, ``cfactor``, ``ifactor``
- *Misc*
* ``unapply``, ``op``, ``subst``
- *Polynomials/Fractions*
* ``coeff``, ``gbasis``, ``greduce``, ``lcoeff``, ``pcoeff``, ``canonical_form``,
* ``proot``, ``poly2symb``, ``symb2poly``, ``posubLMQ``, ``poslbdLMQ``, ``VAS``, ``tcoeff``, ``valuation``
* ``gcd``, ``egcd``, ``lcm``, ``quo``, ``rem``, ``quorem``, ``abcuv``, ``chinrem``,
* ``peval``, ``horner``, ``lagrange``, ``ptayl``, ``spline``, ``sturm``, ``sturmab``
* ``partfrac``, ``cpartfrac``
- *Memory/Variables*
* ``assume``, ``about``, ``purge``, ``ans``
- *Calculus/Exact*
* ``linsolve``, ``solve``, ``csolve``, ``desolve``, ``seqsolve``, ``reverse_rsolve``, ``matpow``
* ``limit``, ``series``, ``sum``, ``diff``, ``fMax``, ``fMin``,
* ``integrate``, ``subst``, ``ibpdv``, ``ibpu``, ``preval``
- *Calculus/Exp, Log, powers*
* ``exp2pow``, ``hyp2exp``, ``expexpand``, ``lin``, ``lncollect``, ``lnexpand``, ``powexpand``, ``pow2exp``
- *Trigo*
* ``trigexpand``, ``tsimplify``, ``tlin``, ``tcollect``,
* ``halftan``, ``cos2sintan``, ``sin2costan``, ``tan2sincos``, ``tan2cossin2``, ``tan2sincos2``, ``trigcos``, ``trigsin``, ``trigtan``, ``shift_phase``
* ``exp2trig``, ``trig2exp``
* ``atrig2ln``, ``acos2asin``, ``acos2atan``, ``asin2acos``, ``asin2atan``, ``atan2acos``, ``atan2asin``
- *Linear Algebra*
* ``identity``, ``matrix``, ``makemat``, ``syst2mat``, ``matpow``, ``table``, ``redim``
* ``det``, ``det_minor``, ``rank``, ``ker``, ``image``, ``rref``, ``simplex_reduce``,
* ``egv``, ``egvl``, ``eigenvalues``, ``pcar``, ``pcar_hessenberg``, ``pmin``,
* ``jordan``, ``adjoint_matrix``, ``companion``, ``hessenberg``, ``transpose``,
* ``cholesky``, ``lll``, ``lu``, ``qr``, ``svd``, ``a2q``, ``gauss``, ``gramschmidt``,
``q2a``, ``isom``, ``mkisom``
- *Finite Fields*
* ``%``, ``% 0``, ``mod``, ``GF``, ``powmod``
- *Integers*
* ``gcd``, ``iabcuv``, ``ichinrem``, ``idivis``, ``iegcd``,
* ``ifactor``, ``ifactors``, ``iquo``, ``iquorem``, ``irem``,
* ``is_prime, is_pseudoprime``, ``lcm``, ``mod``, ``nextprime``, ``pa2b2``, ``prevprime``,
``smod``, ``euler``, ``fracmod``
- *List*
* ``append``, ``accumulate_head_tail``, ``concat``, ``head``, ``makelist``, ``member``, ``mid``, ``revlist``, ``rotate``, ``shift``, ``size``, ``sizes``, ``sort``, ``suppress``, ``tail``
- *Set*
* ``intersect``, ``minus``, ``union``, ``is_element``, ``is_included``
"""
return Pygen(s).eval()
#######################################
# A class to adjust giac configuration
#######################################
cdef class GiacSetting(Pygen):
"""
A class to customise the Computer Algebra System settings.
EXAMPLES::
>>> from sagemath_giac.giac import giacsettings, libgiac
``threads`` (maximal number of allowed theads in giac)::
>>> import os
>>> try:
... ncpu = int(os.environ['SAGE_NUM_THREADS'])
... except KeyError:
... ncpu =1
>>> giacsettings.threads == ncpu
True
``digits`` (default digit number used for approximations)::
>>> giacsettings.digits = 20
>>> libgiac.approx('1/7')
0.14285714285714285714
>>> giacsettings.digits = 50
>>> libgiac.approx('1/7')
0.14285714285714285714285714285714285714285714285714
>>> giacsettings.digits = 12
``sqrtflag`` (flag to allow sqrt extractions during solve and
factorizations)::
>>> giacsettings.sqrtflag = False
>>> libgiac('x**2-2').factor()
x^2-2
>>> giacsettings.sqrtflag = True
>>> libgiac('x**2-2').factor()
(x-sqrt(2))*(x+sqrt(2))
``complexflag`` (flag to allow complex number in solving equations
or factorizations)::
>>> giacsettings.complexflag = False; giacsettings.complexflag
False
>>> libgiac('x**2+4').factor()
x^2+4
>>> giacsettings.complexflag = True
>>> libgiac('x**2+4').factor()
(x+2*i)*(x-2*i)
``eval_level`` (recursive level of substitution of variables
during an evaluation)::
>>> giacsettings.eval_level = 1
>>> libgiac("purge(a):;b:=a;a:=1;b")
"Done",a,1,a
>>> giacsettings.eval_level=25; giacsettings.eval_level
25
>>> libgiac("purge(a):;b:=a;a:=1;b")
"Done",a,1,1
``proba_epsilon`` (maximum probability of a wrong answer with a
probabilistic algorithm). Set this number to 0 to disable
probabilistic algorithms (slower)::
>>> giacsettings.proba_epsilon = 0
>>> libgiac('proba_epsilon')
0.0
>>> giacsettings.proba_epsilon = 10**(-13)
>>> libgiac('proba_epsilon') < 10**(-14)
False
``epsilon`` (value used by the ``epsilon2zero`` function)::
>>> giacsettings.epsilon = 1e-10
>>> P = libgiac('1e-11+x+5')
>>> P == x+5
False
>>> (P.epsilon2zero()).simplify()
x+5
"""
def __repr__(self):
return "Giac Settings"
def _sage_doc_(self):
return GiacSetting.__doc__
property digits:
r"""
Default digits number used for approximations.
EXAMPLES::
>>> from sagemath_giac.giac import giacsettings, libgiac
>>> giacsettings.digits = 20
>>> giacsettings.digits
20
>>> libgiac.approx('1/7')
0.14285714285714285714
>>> giacsettings.digits=12
"""
def __get__(self):
return (self.cas_setup()[6])._val
def __set__(self, value):
l = Pygen('cas_setup()').eval()
pl = [ i for i in l ]
pl[6] = value
Pygen('cas_setup(%s)' % pl).eval()
property sqrtflag:
r"""
Flag to allow square roots in solving equations or
factorizations.
"""
def __get__(self):
return (self.cas_setup()[9])._val == 1
def __set__(self, value):
l = Pygen('cas_setup()').eval()
pl = [ i for i in l ]
if value:
pl[9]=1
else:
pl[9]=0
Pygen('cas_setup(%s)' % pl).eval()
property complexflag:
r"""
Flag to allow complex number in solving equations or
factorizations.
EXAMPLES::
>>> from sagemath_giac.giac import libgiac, giacsettings
>>> giacsettings.complexflag = False
>>> giacsettings.complexflag
False
>>> libgiac('x**2+4').factor()
x^2+4
>>> giacsettings.complexflag=True;
>>> libgiac('x**2+4').factor()
(x+2*i)*(x-2*i)
"""
def __get__(self):
return (self.cas_setup()[2])._val == 1
def __set__(self, value):
l = Pygen('cas_setup()').eval()
pl = [ i for i in l ]
if value:
pl[2] = 1
else:
pl[2] = 0
Pygen('cas_setup(%s)' % pl).eval()
property eval_level:
r"""
Recursive level of substitution of variables during an evaluation.
EXAMPLES::
>>> from sagemath_giac.giac import giacsettings, libgiac
>>> giacsettings.eval_level=1
>>> libgiac("purge(a):;b:=a;a:=1;b")
"Done",a,1,a
>>> giacsettings.eval_level = 25
>>> giacsettings.eval_level
25
>>> libgiac("purge(a):;b:=a;a:=1;b")
"Done",a,1,1
>>> libgiac.purge('a,b')
1,a
"""
def __get__(self):
return (self.cas_setup()[7][3])._val
def __set__(self, value):
l = Pygen('cas_setup()').eval()
pl = [ i for i in l ]
pl[7] = [l[7][0],l[7][1],l[7][2], value]
Pygen('cas_setup(%s)' % pl).eval()
property proba_epsilon:
r"""
Maximum probability of a wrong answer with a probabilistic
algorithm.
Set this number to 0 to disable probabilistic algorithms
(this makes the computation slower).
EXAMPLES::
>>> from sagemath_giac.giac import giacsettings,libgiac
>>> giacsettings.proba_epsilon = 0
>>> libgiac('proba_epsilon')
0.0
>>> giacsettings.proba_epsilon = 10**(-13)
>>> libgiac('proba_epsilon') < 10**(-14)
False
"""
def __get__(self):
return (self.cas_setup()[5][1])._double
def __set__(self, value):
l = Pygen('cas_setup()').eval()
pl = [ i for i in l ]
pl[5] = [l[5][0],value]
Pygen('cas_setup(%s)' % pl).eval()
property epsilon:
r"""
Value used by the ``epsilon2zero`` function.
EXAMPLES::
>>> from sagemath_giac.giac import giacsettings, libgiac
>>> giacsettings.epsilon = 1e-10
>>> P = libgiac('1e-11+x+5')
>>> P == x+5
False
>>> (P.epsilon2zero()).simplify()
x+5
"""
def __get__(self):
return (self.cas_setup()[5][0])._double
def __set__(self, value):
l = Pygen('cas_setup()').eval()
pl = [ i for i in l ]
pl[5] = [value,l[5][1]]
Pygen('cas_setup(%s)' % pl).eval()
property threads:
r"""
Maximal number of allowed theads in giac.
"""
def __get__(self):
return (self.cas_setup()[7][0])._val
def __set__(self, value):
Pygen('threads:=%s' % str(value)).eval()
########################################################
# #
# The python class that points to a cpp giac gen #
# #
########################################################
include 'auto-methods.pxi'
cdef class Pygen(GiacMethods_base):
cdef gen * gptr #pointer to the corresponding C++ element of type giac::gen
def __cinit__(self, s=None):
#NB: the != here gives problems with the __richcmp__ function
#if (s!=None):
# so it's better to use isinstance
if (isinstance(s, None.__class__)):
# Do NOT replace with: self=GIACNULL (cf the doctest in __repr__
sig_on()
self.gptr = new gen ((<Pygen>GIACNULL).gptr[0])
sig_off()
return
if isinstance(s, int):
# This looks 100 faster than the str initialisation
if s.bit_length() < Pymaxint.bit_length():
sig_on()
self.gptr = new gen(<long long>s)
sig_off()
else:
sig_on()
self.gptr = new gen(pylongtogen(s))
sig_off()
elif isinstance(s, Integer): # for sage int (gmp)
sig_on()
if (abs(s)>Pymaxint):
self.gptr = new gen((<Integer>s).value)
else:
self.gptr = new gen(<long long>s) # important for pow to have a int
sig_off()
elif isinstance(s, Rational): # for sage rat (gmp)
#self.gptr = new gen((<Pygen>(Pygen(s.numerator())/Pygen(s.denominator()))).gptr[0])
# FIXME: it's slow
sig_on()
self.gptr = new gen(GIAC_rdiv(gen((<Integer>(s.numerator())).value),gen((<Integer>(s.denominator())).value)))
sig_off()
elif isinstance(s, Matrix):
s = Pygen(s.list()).list2mat(s.ncols())
sig_on()
self.gptr = new gen((<Pygen>s).gptr[0])
sig_off()
elif isinstance(s, float):
sig_on()
self.gptr = new gen(<double>s)
sig_off()
elif isinstance(s, Pygen):
# in the test: x,y=Pygen('x,y');((x+2*y).sin()).texpand()
# the y are lost without this case.
sig_on()
self.gptr = new gen((<Pygen>s).gptr[0])
sig_off()
elif isinstance(s, (list, range)):
sig_on()
self.gptr = new gen(_wrap_pylist(<list>s),<short int>0)
sig_off()
elif isinstance(s, tuple):
sig_on()
self.gptr = new gen(_wrap_pylist(<tuple>s),<short int>1)
sig_off()
# Other types are converted with strings.
else:
if isinstance(s, Expression):
# take account of conversions with key giac in the sage symbol dict
try:
s = s._giac_init_()
except AttributeError:
s = SRexpressiontoGiac(s)
elif isinstance(s, AnInfinity):
s = s._giac_init_()
if not isinstance(s, str):
s = s.__str__()
sig_on()
self.gptr = new gen(<string>encstring23(s),context_ptr)
sig_off()
def __dealloc__(self):
del self.gptr
def __repr__(self):
# fast evaluation of the complexity of the gen. (it's not the number of char )
sig_on()
t=GIAC_taille(self.gptr[0], 6000)
sig_off()
if t < 6000:
sig_on()
result = GIAC_print(self.gptr[0], context_ptr).c_str().decode()
sig_off()
return result
else:
sig_on()
result = str(self.type) + "\nResult is too big for Display. If you really want to see it use print"
sig_off()
return result
def __str__(self):
#if self.gptr == NULL:
# return ''
sig_on()
result = GIAC_print(self.gptr[0], context_ptr).c_str().decode()
sig_off()
return result
def __len__(self):
"""
TESTS::
>>> from sagemath_giac.giac import libgiac
>>> l=libgiac("seq[]"); len(l) # 29552 comment28
0
"""
if (self._type == 7):
sig_on()
rep=(self.gptr.ref_VECTptr()).size()
sig_off()
return rep
else:
sig_on()
rep=GIAC_size(self.gptr[0],context_ptr).val
sig_off()
#GIAC_size return a gen. we take the int: val
return rep
def __getitem__(self, i): #TODO?: add gen support for indexes
"""
Lists of 10**6 integers should be translated to giac easily
TESTS::
>>> from sagemath_giac.giac import libgiac
>>> l = libgiac(list(range(10**6))); l[5]
5
>>> l[35:50:7]
[35,42,49]
>>> l[-10**6]
0
>>> t = libgiac(tuple(range(10)))
>>> t[:4:-1]
9,8,7,6,5
>>> x = libgiac('x')
>>> sum([ x[i] for i in range(5) ], libgiac(0))**3
(x[0]+x[1]+x[2]+x[3]+x[4])^3
>>> A = libgiac.ranm(5,10)
>>> A[3,7]-A[3][7]
0
>>> A.transpose()[8,2]-A[2][8]
0
Crash test::
>>> from sagemath_giac.giac import Pygen
>>> l = Pygen()
>>> l[0]
Traceback (most recent call last):
...
IndexError: list index 0 out of range
"""
cdef gen result
if(self._type == 7) or (self._type == 12): #if self is a list or a string
if isinstance(i, (int, Integer)):
n=len(self)
if(i<n)and(-i<=n):
if(i<0):
i=i+n
sig_on()
result = self.gptr[0][<int>i]
sig_off()
return _wrap_gen(result)
else:
raise IndexError('list index %s out of range' % i)
else:
if isinstance(i, slice):
sig_on()
result = gen(_getgiacslice(self,i),<short int>self._subtype)
sig_off()
return _wrap_gen(result)
# add support for multi indexes
elif isinstance(i, tuple):
if(len(i)==2):
return self[i[0]][i[1]]
elif(len(i)==1):
# in case of a tuple like this: (3,)
return self[i[0]]
else:
return self[i[0],i[1]][tuple(i[2:])]
else:
raise TypeError('gen indexes are not yet implemented')
# Here we add support to formal variable indexes:
else:
cmd = '%s[%s]' % (self, i)
ans = Pygen(cmd).eval()
# if the answer is a string, it must be an error message because self is not a list or a string
if (ans._type == 12):
raise TypeError("Error executing code in Giac\nCODE:\n\t%s\nGiac ERROR:\n\t%s" % (cmd, ans))
return ans
def __setitem__(self, key, value):
"""
Set the value of a coefficient of a giac vector or matrix or list.
Warning: It is an in place affectation.
TESTS::
>>> from sagemath_giac.giac import libgiac
>>> from sage.rings.rational_field import QQ
>>> A = libgiac([ [ libgiac(j)+libgiac(i)*2 for i in range(3)] for j in range(3)]); A
[[0,2,4],[1,3,5],[2,4,6]]
>>> A[1,2] = 44; A
[[0,2,4],[1,3,44],[2,4,6]]
>>> A[2][2] = QQ(1)/QQ(3); A
[[0,2,4],[1,3,44],[2,4,1/3]]
>>> x = libgiac('x')
>>> A[0,0] = x + libgiac(1)/x; A
[[x+1/x,2,4],[1,3,44],[2,4,1/3]]
>>> A[0] = [-1,-2,-3]; A
[[-1,-2,-3],[1,3,44],[2,4,1/3]]
>>> B = A; A[2,2]