Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/interfaces/giac.py
4054 views
1
r"""
2
Interface to Giac
3
4
(adapted by F. Han from William Stein and Gregg Musiker maple's interface)
5
6
You must have the optional Giac interpreter installed
7
and available as the command ``giac`` in your PATH in
8
order to use this interface. You need a giac version
9
supporting "giac --sage" ( roughly after 0.9.1 ). In this case you do not have
10
to install any optional Sage packages. If giac is not already installed, you can
11
download binaries or sources or spkg (follow the sources link) from the homepage:
12
13
Homepage http://www-fourier.ujf-grenoble.fr/~parisse/giac.html
14
15
Type ``giac.[tab]`` for a list of all the functions
16
available from your Giac install. Type
17
``giac.[tab]?`` for Giac's help about a given
18
function. Type ``giac(...)`` to create a new Giac
19
object, and ``giac.eval(...)`` to run a string using
20
Giac (and get the result back as a string).
21
22
If the giac spkg is installed, you should find the full html documentation there:
23
24
$SAGE_LOCAL/share/giac/doc/en/cascmd_local/index.html
25
26
27
EXAMPLES::
28
29
sage: giac('3 * 5') # optional - giac
30
15
31
sage: giac.eval('ifactor(2005)') # optional - giac
32
'5*401'
33
sage: giac.ifactor(2005) # optional - giac
34
2005
35
sage: l=giac.ifactors(2005) ; l; l[2] # optional - giac
36
[5,1,401,1]
37
401
38
sage: giac.fsolve('x^2=cos(x)+4', 'x','0..5') # optional - giac
39
1.9140206190...
40
sage: giac.factor('x^5 - y^5') # optional - giac
41
(x-y)*(x^4+x^3*y+x^2*y^2+x*y^3+y^4)
42
sage: R.<x,y>=QQ[];f=(x+y)^5;f2=giac(f);(f-f2).normal() #optional - giac
43
0
44
sage: x,y=giac('x,y'); giac.int(y/(cos(2*x)+cos(x)),x) #random; optional - giac
45
y*2*((-(tan(x/2)))/6+(-2*1/6/sqrt(3))*ln(abs(6*tan(x/2)-2*sqrt(3))/abs(6*tan(x/2)+2*sqrt(3))))
46
47
48
If the string "error" (case insensitive) occurs in the output of
49
anything from Giac, a RuntimeError exception is raised.
50
51
Tutorial
52
--------
53
54
AUTHORS:
55
56
- Gregg Musiker (2006-02-02): initial version.
57
58
(adapted to giac by F.Han)
59
60
This tutorial is based on the Maple Tutorial for number theory from
61
http://www.math.mun.ca/~drideout/m3370/numtheory.html.
62
63
There are several ways to use the Giac Interface in Sage. We will
64
discuss two of those ways in this tutorial.
65
66
67
#. If you have a giac expression such as
68
69
::
70
71
factor( (x^5-1));
72
73
We can write that in sage as
74
75
::
76
77
sage: giac('factor(x^5-1)') # optional - giac
78
(x-1)*(x^4+x^3+x^2+x+1)
79
80
Notice, there is no need to use a semicolon.
81
82
#. Since Sage is written in Python, we can also import giac
83
commands and write our scripts in a pythonic way. For example,
84
``factor()`` is a giac command, so we can also factor
85
in Sage using
86
87
::
88
89
sage: giac('(x^5-1)').factor() # optional - giac
90
(x-1)*(x^4+x^3+x^2+x+1)
91
92
where ``expression.command()`` means the same thing as
93
``command(expression)`` in Giac. We will use this
94
second type of syntax whenever possible, resorting to the first
95
when needed.
96
97
::
98
99
sage: giac('(x^12-1)/(x-1)').normal() # optional - giac
100
x^11+x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1
101
102
103
The normal command will reduce a rational function to the
104
lowest terms. In giac, simplify is slower than normal because it
105
tries more sophisticated simplifications (ex algebraic extensions)
106
The factor command will factor a polynomial with
107
rational coefficients into irreducible factors over the ring of
108
integers (if your default configuration of giac (cf .xcasrc) has not
109
allowed square roots). So for example,
110
111
112
::
113
114
sage: giac('(x^12-1)').factor( ) # optional - giac
115
(x-1)*(x+1)*(x^2+1)*(x^2-x+1)*(x^2+x+1)*(x^4-x^2+1)
116
117
::
118
119
sage: giac('(x^28-1)').factor( ) # optional - giac
120
(x-1)*(x+1)*(x^2+1)*(x^6-x^5+x^4-x^3+x^2-x+1)*(x^6+x^5+x^4+x^3+x^2+x+1)*(x^12-x^10+x^8-x^6+x^4-x^2+1)
121
122
Another important feature of giac is its online help. We can
123
access this through sage as well. After reading the description of
124
the command, you can press q to immediately get back to your
125
original prompt.
126
127
Incidentally you can always get into a giac console by the
128
command
129
130
::
131
132
sage: giac.console() # not tested
133
sage: !giac # not tested
134
135
Note that the above two commands are slightly different, and the
136
first is preferred.
137
138
For example, for help on the giac command factors, we type
139
140
::
141
142
sage: giac.help('factors') # not tested
143
144
::
145
146
sage: alpha = giac((1+sqrt(5))/2) # optional - giac
147
sage: beta = giac(1-sqrt(5))/2 # optional - giac
148
sage: f19 = alpha^19 - beta^19/sqrt(5) # optional - giac
149
sage: f19 # optional - giac
150
(sqrt(5)/2+1/2)^19-((-sqrt(5)+1)/2)^19/sqrt(5)
151
sage: (f19-(5778*sqrt(5)+33825)/5).normal() # optional - giac
152
0
153
154
Let's say we want to write a giac program now that squares a
155
number if it is positive and cubes it if it is negative. In giac,
156
that would look like
157
158
::
159
160
mysqcu := proc(x)
161
if x > 0 then x^2;
162
else x^3; fi;
163
end;
164
165
In Sage, we write
166
167
::
168
169
sage: mysqcu = giac('proc(x) if x > 0 then x^2 else x^3 fi end') # optional - giac
170
sage: mysqcu(5) # optional - giac
171
25
172
sage: mysqcu(-5) # optional - giac
173
-125
174
175
More complicated programs should be put in a separate file and
176
loaded.
177
"""
178
179
#############################################################################
180
# Copyright (C) 2005 William Stein <[email protected]>
181
#
182
# Distributed under the terms of the GNU General Public License (GPL)
183
#
184
# http://www.gnu.org/licenses/
185
#############################################################################
186
187
#from __future__ import with_statement
188
189
import os
190
191
from sage.interfaces.expect import Expect, ExpectElement, ExpectFunction, FunctionElement, gc_disabled
192
193
import pexpect
194
195
from sage.misc.misc import verbose, DOT_SAGE
196
from sage.misc.pager import pager
197
198
COMMANDS_CACHE = '%s/giac_commandlist_cache.sobj'%DOT_SAGE
199
200
class Giac(Expect):
201
r"""
202
Interface to the Giac interpreter.
203
204
You must have the optional Giac interpreter installed and available as the command ``giac`` in your PATH in order to use this interface. Try the command: print giac._install_hints() for more informations on giac installation.
205
206
Type ``giac.[tab]`` for a list of all the functions available from your Giac install.
207
Type ``giac.[tab]?`` for Giac's help about a given function.
208
Type ``giac(...)`` to create a new Giac object.
209
210
Full html documentation for giac is avaible from your giac installation at ``$PREFIX``/share/giac/doc/en/cascmd_en/index.html
211
212
EXAMPLES:
213
214
Any Giac instruction can be evaluated as a string by the giac command. You can access the giac functions by adding the ``giac.`` prefix to the usual Giac name.
215
216
::
217
218
sage: l=giac('normal((y+sqrt(2))^4)'); l # optional - giac
219
y^4+4*sqrt(2)*y^3+12*y^2+8*sqrt(2)*y+4
220
sage: f=giac('(u,v)->{ if (u<v){ [u,v] } else { [v,u] }}');f(1,2),f(3,1) # optional - giac
221
([1,2], [1,3])
222
223
The output of the giac command is a Giac object, and it can be used for another giac command.
224
225
::
226
227
sage: l.factors() #optional - giac
228
[y+sqrt(2),4]
229
sage: giac('(x^12-1)').factor( ) # optional - giac
230
(x-1)*(x+1)*(x^2+1)*(x^2-x+1)*(x^2+x+1)*(x^4-x^2+1)
231
sage: giac('assume(y>0)'); giac('y^2=3').solve('y') #optional - giac
232
y
233
[sqrt(3)]
234
235
You can create some Giac elements and avoid many quotes like this:
236
237
::
238
239
sage: x,y,z=giac('x,y,z');type(y) # optional - giac
240
<class 'sage.interfaces.giac.GiacElement'>
241
sage: I1=(1/(cos(2*y)+cos(y))).integral(y,0,pi/4).simplify() #optional - giac
242
sage: (I1-((-2*ln((sqrt(3)-3*tan(1/8*pi))/(sqrt(3)+3*tan(1/8*pi)))*sqrt(3)-3*tan(1/8*pi))/9)).normal() # optional - giac
243
0
244
sage: ((y+z*sqrt(5))*(y-sqrt(5)*z)).normal() # optional - giac
245
y^2-5*z^2
246
247
Polynomials or elements of SR can be evaluated directly by the giac interface.
248
249
::
250
251
sage: R.<a,b>=QQ[];f=(2+a+b);p=giac.gcd(f^3+5*f^5,f^2+f^5);p;R(p); #optional - giac
252
a^2+2*a*b+4*a+b^2+4*b+4
253
a^2 + 2*a*b + b^2 + 4*a + 4*b + 4
254
255
Variable names in python and giac are independant.
256
257
::
258
259
sage: a=sqrt(2);giac('Digits:=30;a:=5');a,giac('a'),giac(a),giac(a).evalf() # optional - giac
260
[...]
261
(sqrt(2), 5, sqrt(2), 1.414213562373095048801688724209)
262
263
264
"""
265
def __init__(self, maxread=10000, script_subdirectory="", server=None, server_tmpdir=None, logfile=None):
266
"""
267
Create an instance of the Giac interpreter.
268
269
EXAMPLES::
270
271
sage: giac == loads(dumps(giac)) # optional - giac
272
True
273
"""
274
Expect.__init__(self,
275
name = 'giac',
276
prompt = '[0-9]*>> ',
277
command = "giac --sage",
278
init_code= ['maple_mode(0);I:=i;'], # coercion could be broken in maple_mode
279
maxread = maxread,
280
# script_subdirectory = None,
281
script_subdirectory = script_subdirectory,
282
restart_on_ctrlc = False, server = server,
283
server_tmpdir = server_tmpdir,
284
verbose_start = False,
285
logfile = logfile,
286
eval_using_file_cutoff=1000)
287
288
def _function_class(self):
289
"""
290
EXAMPLES::
291
292
sage: giac._function_class() # optional - giac
293
<class 'sage.interfaces.giac.GiacFunction'>
294
295
::
296
297
sage: type(giac.diff) # optional - giac
298
<class 'sage.interfaces.giac.GiacFunction'>
299
"""
300
return GiacFunction
301
302
def _keyboard_interrupt(self):
303
"""
304
TESTS:
305
306
We check to make sure that the gap interface behaves correctly
307
after a keyboard interrupt.
308
309
sage: giac(2) # optional - giac
310
2
311
sage: try: # optional - giac
312
... giac._keyboard_interrupt()
313
... except:
314
... pass
315
...
316
Interrupting Giac...
317
sage: giac(2) # optional - giac
318
2
319
"""
320
print "Interrupting %s..."%self
321
self._expect.sendline(chr(3)) # send ctrl-c
322
self._expect.expect(self._prompt)
323
# self._expect.expect(self._prompt)
324
raise RuntimeError, "Ctrl-c pressed while running %s"%self
325
326
def __reduce__(self):
327
"""
328
EXAMPLES::
329
330
sage: giac.__reduce__()
331
(<function reduce_load_Giac at 0x...>, ())
332
sage: f, args = _
333
sage: f(*args)
334
Giac
335
"""
336
return reduce_load_Giac, tuple([])
337
338
def _read_in_file_command(self, filename):
339
r"""
340
Returns the string used to read filename into Giac.
341
342
EXAMPLES::
343
344
sage: giac._read_in_file_command('test') # optional - giac
345
'read "test"'
346
347
::
348
349
sage: filename = tmp_filename() # optional - giac
350
sage: f = open(filename,'w') # optional - giac
351
sage: f.write('xx := 22;\n') # optional - giac
352
sage: f.close() # optional - giac
353
sage: giac.read(filename) # optional - giac
354
sage: giac.get('xx').strip() # optional - giac
355
'22'
356
"""
357
return 'read "%s"'%filename
358
359
def _quit_string(self):
360
"""
361
EXAMPLES::
362
363
sage: giac._quit_string() # optional - giac
364
'@d'
365
366
::
367
368
sage: m = Giac()
369
sage: a = m(2) # optional - giac
370
sage: m.is_running() # optional - giac
371
True
372
sage: m.quit() # optional - giac
373
sage: m.is_running() # optional - giac
374
False
375
"""
376
return '@d'
377
378
def _install_hints(self):
379
"""
380
Hints for installing Giac on your computer.
381
382
EXAMPLES::
383
384
sage: print giac._install_hints()
385
In order...
386
"""
387
return r"""
388
389
In order to use the Giac interface you need to have Giac installed
390
and have a program called "giac" in your PATH. You need a giac version
391
supporting "giac --sage" ( roughly after 0.9.1 of march 2011). Some giac
392
instructions and the help's langage depend of you LANG variable. To obtain
393
inline help for giac commands, you also need to have the program "cas_help"
394
in your PATH.
395
396
397
If giac is not already installed, you can download binaries or sources
398
or a spkg ( for the spkg follow the sources link) from the homepage:
399
400
Homepage http://www-fourier.ujf-grenoble.fr/~parisse/giac.html
401
402
403
Full html documentation for giac is avaible from your giac installation at:
404
405
``$PREFIX``/share/giac/doc/en/cascmd_en/index.html
406
407
If you got giac from the spkg then ``$PREFIX`` is ``$SAGE_LOCAL``
408
409
"""
410
411
def expect(self):
412
"""
413
Returns the pexpect object for this Giac session.
414
415
EXAMPLES::
416
417
sage: m = Giac()
418
sage: m.expect() is None
419
True
420
sage: m._start() # optional - giac
421
sage: m.expect() # optional - giac
422
<pexpect.spawn instance at 0x...>
423
sage: m.quit() # optional - giac
424
"""
425
return self._expect
426
427
def console(self):
428
"""
429
Spawn a new Giac command-line session.
430
431
EXAMPLES::
432
433
sage: giac_console() # not tested - giac
434
...
435
Homepage http://www-fourier.ujf-grenoble.fr/~parisse/giac.html
436
Released under the GPL license 3.0 or above
437
See http://www.gnu.org for license details
438
-------------------------------------------------
439
Press CTRL and D simultaneously to finish session
440
Type ?commandname for help
441
0>>
442
443
"""
444
giac_console()
445
446
447
def completions(self, s):
448
"""
449
Return all commands that complete the command starting with the
450
string s.
451
452
EXAMPLES::
453
454
sage: c = giac.completions('cas') # optional - giac
455
sage: 'cas_setup' in c # optional - giac
456
True
457
"""
458
bs = chr(8)*len(s)
459
if self._expect is None:
460
self._start()
461
E = self._expect
462
E.sendline('%s%s%s'%(s,chr(63),chr(13)))
463
t = E.timeout
464
E.timeout=0.3 # since some things have no completion
465
try:
466
E.expect('----')
467
except pexpect.TIMEOUT:
468
E.timeout = t
469
return []
470
E.timeout = t
471
v = E.before
472
E.expect(self._prompt)
473
E.expect(self._prompt)
474
return v.split()[1:]
475
476
def _commands(self):
477
"""
478
Return list of all commands defined in Giac.
479
480
EXAMPLES::
481
482
sage: c = giac._commands() # optional - giac
483
sage: len(c) > 100 # optional - giac
484
True
485
sage: 'Psi' in c # optional - giac
486
True
487
"""
488
try:
489
v = sum([self.completions(chr(65+n)) for n in range(26)], []) + \
490
sum([self.completions(chr(97+n)) for n in range(26)], [])
491
except RuntimeError:
492
print "\n"*3
493
print "*"*70
494
print "WARNING: You do not have a working version of Giac installed!"
495
print "*"*70
496
v = []
497
v.sort()
498
return v
499
500
def trait_names(self, verbose=True, use_disk_cache=True):
501
"""
502
Returns a list of all the commands defined in Giac and optionally
503
(per default) store them to disk.
504
505
EXAMPLES::
506
507
sage: c = giac.trait_names(use_disk_cache=False, verbose=False) # optional - giac
508
sage: len(c) > 100 # optional - giac
509
True
510
sage: 'factors' in c # optional - giac
511
True
512
"""
513
try:
514
return self.__trait_names
515
except AttributeError:
516
import sage.misc.persist
517
if use_disk_cache:
518
try:
519
self.__trait_names = sage.misc.persist.load(COMMANDS_CACHE)
520
return self.__trait_names
521
except IOError:
522
pass
523
if verbose:
524
print "\nBuilding Giac command completion list (this takes"
525
print "a few seconds only the first time you do it)."
526
print "To force rebuild later, delete %s."%COMMANDS_CACHE
527
v = self._commands()
528
self.__trait_names = v
529
if len(v) > 200:
530
# Giac is actually installed.
531
sage.misc.persist.save(v, COMMANDS_CACHE)
532
return v
533
534
535
def cputime(self, t=None):
536
r"""
537
Returns the amount of CPU time that the Giac session has used. If
538
``t`` is not None, then it returns the difference
539
between the current CPU time and ``t``.
540
541
EXAMPLES::
542
543
sage: t = giac.cputime() # optional - giac
544
sage: t # random; optional - giac
545
0.02
546
sage: x = giac('x') # optional - giac
547
sage: giac.diff(x^2, x) # optional - giac
548
2*x
549
sage: giac.cputime(t) # random; optional - giac
550
0.0
551
"""
552
if t is None:
553
return float(self('time()'))
554
else:
555
return float(self('time() - %s'%float(t)))
556
557
558
def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True):
559
"""
560
EXAMPLES::
561
562
sage: giac._eval_line('2+2') # optional - giac
563
'4'
564
"""
565
with gc_disabled():
566
z = Expect._eval_line(self, line, allow_use_file=allow_use_file,
567
wait_for_prompt=wait_for_prompt)
568
if z.lower().find("error") != -1:
569
raise RuntimeError, "An error occurred running a Giac command:\nINPUT:\n%s\nOUTPUT:\n%s"%(line, z)
570
return z
571
572
573
def eval(self, code, strip=True, **kwds):
574
"""
575
Send the code x to the Giac interpreter.
576
Remark: To enable multi-lines codes in the notebook magic mode: %giac,
577
the \\n are removed before sending the code to giac.
578
579
INPUT:
580
code -- str
581
strip -- Default is True and removes \n
582
583
EXAMPLES:
584
sage: giac.eval("2+2;\n3") #optional - giac
585
'4,3'
586
sage: giac.eval("2+2;\n3",False) # optional - giac
587
'4\n3'
588
sage: s='g(x):={\nx+1;\nx+2;\n}'
589
sage: giac(s) # optional - giac
590
(x)->{
591
x+1;
592
x+2;
593
}
594
sage: giac.g(5) # optional - giac
595
7
596
"""
597
#we remove \n to enable multiline code in the notebook magic mode %giac
598
if strip:
599
code = code.replace("\n","").strip()
600
ans = Expect.eval(self, code, strip=strip, **kwds).strip()
601
return ans
602
603
604
605
def set(self, var, value):
606
"""
607
Set the variable var to the given value.
608
609
EXAMPLES::
610
611
sage: giac.set('xx', '2') # optional - giac
612
sage: giac.get('xx') # optional - giac
613
'2'
614
"""
615
cmd = '%s:=%s:;'%(var,value) #if giac is not in maple mode ( maple_mode(0))
616
out = self.eval(cmd)
617
if out.find("error") != -1:
618
raise TypeError, "Error executing code in Giac\nCODE:\n\t%s\nGiac ERROR:\n\t%s"%(cmd, out)
619
620
621
def get(self, var):
622
"""
623
Get the value of the variable var.
624
625
EXAMPLES::
626
627
sage: giac.set('xx', '2') # optional - giac
628
sage: giac.get('xx') # optional - giac
629
'2'
630
"""
631
s = self.eval('%s'%var)
632
return s
633
634
def _object_class(self):
635
"""
636
Returns the class of GiacElements.
637
638
EXAMPLES::
639
640
sage: giac._object_class()
641
<class 'sage.interfaces.giac.GiacElement'>
642
643
::
644
645
sage: m = giac(2) # optional - giac
646
sage: type(m) # optional - giac
647
<class 'sage.interfaces.giac.GiacElement'>
648
"""
649
return GiacElement
650
651
def _function_element_class(self):
652
"""
653
Returns the GiacFunctionElement class.
654
655
EXAMPLES::
656
657
sage: giac._function_element_class()
658
<class 'sage.interfaces.giac.GiacFunctionElement'>
659
660
::
661
662
sage: two = giac(2) # optional - giac
663
sage: type(two.gcd) # optional - giac
664
<class 'sage.interfaces.giac.GiacFunctionElement'>
665
"""
666
return GiacFunctionElement
667
668
def _equality_symbol(self):
669
"""
670
Returns the symbol used for equality testing in Giac.
671
672
EXAMPLES::
673
674
sage: giac._equality_symbol() # optional - giac
675
'=='
676
677
sage: giac(2) == giac(2) # optional -- requires giac
678
True
679
"""
680
return '=='
681
682
def _true_symbol(self):
683
"""
684
Returns the symbol used for truth in Giac.
685
686
EXAMPLES::
687
688
sage: giac._true_symbol()
689
'1'
690
691
::
692
693
sage: giac(2) == giac(2) # optional - giac
694
True
695
"""
696
return '1'
697
698
def _assign_symbol(self):
699
"""
700
Returns the symbol used for assignment in Giac.
701
702
EXAMPLES::
703
704
sage: giac._assign_symbol()
705
':='
706
"""
707
return ":="
708
709
def _help(self, str):
710
r"""
711
Returns the Giac help on ``str``.
712
713
EXAMPLES::
714
715
sage: giac._help('gcd') # not tested ; output may vary (LANG)
716
"...gcd - greatest common divisor of polynomials...
717
"""
718
return os.popen('cas_help %s'%str).read()
719
# return os.popen('echo "?%s" | giac'%str).read()
720
721
def help(self, str):
722
"""
723
Display Giac help about str. This is the same as typing "?str" in
724
the Giac console.
725
726
INPUT:
727
728
729
- ``str`` - a string to search for in the giac help
730
system
731
732
733
EXAMPLES::
734
735
sage: giac.help('Psi') # not tested - depends of giac and $LANG
736
Psi(a,n)=nth-derivative of the function DiGamma (=ln@Gamma) at point a (Psi(a,0)=Psi(a))...
737
"""
738
pager()(self._help(str))
739
740
def clear(self, var):
741
"""
742
Clear the variable named var.
743
744
EXAMPLES::
745
746
sage: giac.set('xx', '2') # optional - giac
747
sage: giac.get('xx') # optional - giac
748
'2'
749
sage: giac.clear('xx') # optional - giac
750
sage: giac.get('xx') # optional - giac
751
'xx'
752
"""
753
self.eval('purge(%s)'%var)
754
755
def version(self):
756
"""
757
Wrapper for giac's version().
758
759
EXAMPLES::
760
761
sage: giac.version() # optional - giac
762
"giac...
763
764
"""
765
return giac('version()')
766
767
class GiacFunction(ExpectFunction):
768
def _sage_doc_(self):
769
"""
770
Returns the Giac help for this function. This gets called when
771
doing "?" on self.
772
773
EXAMPLES::
774
775
sage: giac.gcd._sage_doc_() # not tested ; output may vary LANG
776
"gcd - greatest common divisor of polynomials...
777
"""
778
M = self._parent
779
return M._help(self._name)
780
781
class GiacFunctionElement(FunctionElement):
782
def _sage_doc_(self):
783
"""
784
Returns the Giac help for this function. This gets called when
785
doing "?" on self.
786
787
EXAMPLES::
788
789
sage: two = giac(2) # optional - giac
790
sage: two.gcd._sage_doc_() # not tested; output may vary LANG
791
"...gcd - greatest common divisor of polynomials...
792
"""
793
return self._obj.parent()._help(self._name)
794
795
class GiacElement(ExpectElement):
796
def __float__(self):
797
"""
798
Returns a floating point version of self.
799
800
EXAMPLES::
801
802
sage: float(giac(1/2)) # optional - giac
803
0.5
804
sage: type(_) # optional - giac
805
<type 'float'>
806
"""
807
M = self.parent()
808
return float(giac.eval('evalf(%s)'%self.name()))
809
810
811
def unapply(self,var):
812
"""
813
Creates a Giac function in the given arguments from a Giac symbol.
814
815
EXAMPLES::
816
817
sage: f=giac('y^3+1+t') # optional - giac
818
sage: g=(f.unapply('y,t')) # optional - giac
819
sage: g # optional - giac
820
(y,t)->y^3+1+t
821
sage: g(1,2) # optional - giac
822
4
823
"""
824
return giac('unapply(%s,%s)'%(self,var))
825
826
827
def __hash__(self):
828
"""
829
Returns a integer representing the hash of self.
830
831
These examples are optional, and require Giac to be installed. You
832
don't need to install any Sage packages for this.
833
834
EXAMPLES::
835
836
sage: m = giac('x^2+y^2') # optional - giac
837
sage: hash(m) # random; optional - giac
838
4614285348919569149
839
"""
840
return hash(giac.eval('string(%s);'%self.name()))
841
842
843
def __cmp__(self, other):
844
"""
845
Compare equality between self and other, using giac.
846
847
These examples are optional, and require Giac to be installed. You
848
don't need to install any Sage packages for this.
849
850
EXAMPLES::
851
852
sage: a = giac(5) # optional - giac
853
sage: b = giac(5) # optional - giac
854
sage: a == b # optional - giac
855
True
856
sage: a == 5 # optional - giac
857
True
858
859
::
860
861
sage: c = giac(3) # optional - giac
862
sage: a == c # optional - giac
863
False
864
sage: a < c # optional - giac
865
False
866
sage: a < 6 # optional - giac
867
True
868
sage: c <= a # optional - giac
869
True
870
871
::
872
873
TESTS::
874
875
sage: x = var('x') # optional - giac
876
sage: t = giac((x+1)^2) # optional - giac
877
sage: u = giac(x^2+2*x+1) # optional - giac
878
sage: u == t # optional - giac
879
False
880
"""
881
P = self.parent()
882
if P.eval("evalb(%s %s %s)"%(self.name(), P._equality_symbol(),
883
other.name())) == P._true_symbol():
884
return 0
885
# (to be tested with giac). Maple does not allow comparing objects of different types and
886
# it raises an error in this case.
887
# We catch the error, and return True for <
888
try:
889
if P.eval("evalb(%s %s %s)"%(self.name(), P._lessthan_symbol(), other.name())) == P._true_symbol():
890
return -1
891
except RuntimeError, e:
892
msg = str(e)
893
if 'is not valid' in msg and 'to < or <=' in msg:
894
if (hash(str(self)) < hash(str(other))):
895
return -1
896
else:
897
return 1
898
else:
899
raise RuntimeError, e
900
if P.eval("evalb(%s %s %s)"%(self.name(), P._greaterthan_symbol(), other.name())) == P._true_symbol():
901
return 1
902
# everything is supposed to be comparable in Python, so we define
903
# the comparison thus when no comparable in interfaced system.
904
if (hash(self) < hash(other)):
905
return -1
906
else:
907
return 1
908
909
def trait_names(self):
910
"""
911
EXAMPLES::
912
913
sage: a = giac(2) # optional - giac
914
sage: 'sin' in a.trait_names() # optional - giac
915
True
916
"""
917
return self.parent().trait_names()
918
919
920
def __len__(self):
921
"""
922
EXAMPLES::
923
924
sage: len(giac([1,2,3])) # optional - giac
925
3
926
"""
927
return int(self.size())
928
929
def __iter__(self):
930
"""
931
EXAMPLES:
932
sage: l = giac([1,2,3]) #optional
933
sage: list(iter(l)) #optional
934
[1, 2, 3]
935
"""
936
for i in range(len(self)): # zero-indexed if giac is maple_mode(0)
937
yield self[i]
938
939
def __del__(self):
940
"""
941
Note that clearing object is pointless since it wastes time.
942
(Ex: otherwise doing a=0 after a = (giac('x+y+z')^40).normal() is very slow )
943
944
EXAMPLES::
945
946
sage: a = giac(2) # optional - giac
947
sage: a.__del__() # optional - giac
948
sage: a # optional - giac
949
2
950
sage: del a # optional - giac
951
sage: a
952
Traceback (most recent call last):
953
...
954
NameError: name 'a' is not defined
955
"""
956
return
957
958
def __repr__(self):
959
"""
960
Return a string representation of self.
961
962
These examples are optional, and require Giac to be installed. You
963
don't need to install any Sage packages for this.
964
965
EXAMPLES::
966
967
sage: x = var('x')
968
sage: giac(x) # optional - giac
969
x
970
sage: giac(5) # optional - giac
971
5
972
sage: M = matrix(QQ,2,range(4))
973
sage: giac(M) # optional - giac
974
[[0,1],[2,3]]
975
"""
976
self._check_valid()
977
return self.parent().get(self._name)
978
979
def _latex_(self):
980
r"""
981
You can output Giac expressions in latex.
982
983
EXAMPLES::
984
985
sage: print latex(giac('(x^4 - y)/(y^2-3*x)')) # optional - giac
986
"\frac{(x^{4}-y)}{(y^{2}-3 x)}"
987
988
"""
989
return self.parent().eval('latex(%s)'%self.name())
990
991
992
def _matrix_(self, R):
993
r"""
994
Return matrix over the (Sage) ring R determined by self, where self
995
should be a Giac matrix.
996
Warning: It is slow, don't convert big matrices.
997
998
EXAMPLES::
999
1000
sage: R.<x,y>=QQ[]
1001
sage: M=giac('matrix(4,4,(k,l)->(x^k-y^l))'); M # optional - giac
1002
matrix[[0,1-y,1-y^2,1-y^3],[x-1,x-y,x-y^2,x-y^3],[x^2-1,x^2-y,x^2-y^2,x^2-y^3],[x^3-1,x^3-y,x^3-y^2,x^3-y^3]]
1003
sage: M.eigenvals() # random; optional - giac
1004
0,0,(x^3+x^2+x-y^3-y^2-y+sqrt(x^6+2*x^5+3*x^4-14*x^3*y^3+2*x^3*y^2+2*x^3*y+6*x^3+2*x^2*y^3-14*x^2*y^2+2*x^2*y+5*x^2+2*x*y^3+2*x*y^2-14*x*y+4*x+y^6+2*y^5+3*y^4+6*y^3+5*y^2+4*y-12))/2,(x^3+x^2+x-y^3-y^2-y-sqrt(x^6+2*x^5+3*x^4-14*x^3*y^3+2*x^3*y^2+2*x^3*y+6*x^3+2*x^2*y^3-14*x^2*y^2+2*x^2*y+5*x^2+2*x*y^3+2*x*y^2-14*x*y+4*x+y^6+2*y^5+3*y^4+6*y^3+5*y^2+4*y-12))/2
1005
sage: Z=matrix(M,R);Z # optional - giac
1006
[ 0 -y + 1 -y^2 + 1 -y^3 + 1]
1007
[ x - 1 x - y -y^2 + x -y^3 + x]
1008
[ x^2 - 1 x^2 - y x^2 - y^2 -y^3 + x^2]
1009
[ x^3 - 1 x^3 - y x^3 - y^2 x^3 - y^3]
1010
sage: parent(Z) # optional - giac
1011
Full MatrixSpace of 4 by 4 dense matrices over Multivariate Polynomial Ring in x, y over Rational Field
1012
"""
1013
P = self.parent()
1014
v = self.dim()
1015
n = int(v[0])
1016
m = int(v[1])
1017
1018
from sage.matrix.matrix_space import MatrixSpace
1019
M = MatrixSpace(R, n, m)
1020
entries = [[R(self[r,c]) for c in range(m)] for r in range(n)]
1021
return M(entries)
1022
1023
1024
def _sage_(self):
1025
r"""
1026
Convert a giac expression back to a Sage expression.
1027
1028
This currently does not implement a parser for the Giac output language,
1029
therefore only very simple expressions will convert successfully.
1030
Warning: List conversion is slow.
1031
1032
EXAMPLE::
1033
1034
sage: m = giac('x^2 + 5*y') # optional - requires giac
1035
sage: m.sage() # optional - requires giac
1036
x^2 + 5*y
1037
1038
::
1039
1040
sage: m = giac('sin(2*sqrt(1-x^2)) * (1 - cos(1/x))^2') # optional - requires giac
1041
sage: m.trigexpand().sage() # optional - requires giac
1042
2*(cos(1/x) - 1)^2*sin(sqrt(-x^2 + 1))*cos(sqrt(-x^2 + 1))
1043
1044
"""
1045
result = repr(self)
1046
if str(self.type()) != 'DOM_LIST' :
1047
try:
1048
from sage.symbolic.all import SR
1049
return SR(result)
1050
except:
1051
raise NotImplementedError, "Unable to parse Giac output: %s" % result
1052
else:
1053
return [entry.sage() for entry in self]
1054
1055
def integral(self, var='x', min=None, max=None):
1056
r"""
1057
Return the integral of self with respect to the variable x.
1058
1059
INPUT:
1060
1061
1062
- ``var`` - variable
1063
1064
- ``min`` - default: None
1065
1066
- ``max`` - default: None
1067
1068
1069
Returns the definite integral if xmin is not None, otherwise
1070
returns an indefinite integral.
1071
1072
EXAMPLES::
1073
1074
sage: y=giac('y');f=(sin(2*y)/y).integral(y).simplify(); f # optional - giac
1075
Si(2*y)
1076
sage: f.diff(y).simplify() # optional - giac
1077
sin(2*y)/y
1078
1079
::
1080
1081
sage: f = giac('exp(x^2)').integral('x',0,1) ; f # optional - giac
1082
integra...
1083
sage: f.evalf(100) # optional - giac
1084
1.4626517459071819025155758073473096674669301007326185820691973210905694258465619632003390265815626744
1085
sage: x,y=giac('x'),giac('y');integrate(cos(x+y),'x=0..pi').simplify() # optional - giac
1086
-2*sin(y)
1087
"""
1088
if min is None:
1089
return giac('int(%s,%s)'%(self.name(),var))
1090
else:
1091
if max is None:
1092
raise ValueError, "neither or both of min/max must be specified."
1093
return giac('int(%s,%s,%s,%s)'%(self.name(),var,giac(min),giac(max)))
1094
1095
integrate=integral
1096
1097
1098
def sum(self, var, min=None, max=None):
1099
r"""
1100
Return the sum of self with respect to the variable x.
1101
1102
INPUT:
1103
1104
1105
- ``var`` - variable
1106
1107
- ``min`` - default: None
1108
1109
- ``max`` - default: None
1110
1111
1112
Returns the definite integral if xmin is not None, otherwise
1113
returns an indefinite integral.
1114
1115
EXAMPLES::
1116
sage: giac('1/(1+k^2)').sum('k',-oo,+infinity).simplify() # optional - giac
1117
(pi*exp(pi)^2+pi)/(exp(pi)^2-1)
1118
1119
"""
1120
if min is None:
1121
return giac('sum(%s,%s)'%(self.name(),var))
1122
else:
1123
if max is None:
1124
raise ValueError, "neither or both of min/max must be specified."
1125
return giac('sum(%s,%s,%s,%s)'%(self.name(),var,giac(min),giac(max)))
1126
1127
1128
# An instance
1129
giac = Giac(script_subdirectory='user')
1130
1131
def reduce_load_Giac():
1132
"""
1133
Returns the giac object created in sage.interfaces.giac.
1134
1135
EXAMPLES::
1136
1137
sage: from sage.interfaces.giac import reduce_load_Giac
1138
sage: reduce_load_Giac()
1139
Giac
1140
"""
1141
return giac
1142
1143
1144
import os
1145
def giac_console():
1146
"""
1147
Spawn a new Giac command-line session.
1148
1149
EXAMPLES::
1150
1151
sage: giac.console() # not tested - giac
1152
...
1153
Homepage http://www-fourier.ujf-grenoble.fr/~parisse/giac.html
1154
Released under the GPL license 3.0 or above
1155
See http://www.gnu.org for license details
1156
-------------------------------------------------
1157
Press CTRL and D simultaneously to finish session
1158
Type ?commandname for help
1159
"""
1160
os.system('giac')
1161
1162
1163
def __doctest_cleanup():
1164
"""
1165
EXAMPLES::
1166
1167
sage: from sage.interfaces.giac import __doctest_cleanup
1168
sage: m = giac(2) # optional - giac
1169
sage: giac.is_running() # optional - giac
1170
True
1171
sage: __doctest_cleanup()
1172
sage: giac.is_running()
1173
False
1174
"""
1175
import sage.interfaces.quit
1176
sage.interfaces.quit.expect_quitall()
1177
1178
1179
1180
1181