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