Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/interfaces/gp.py
4045 views
1
r"""
2
Interface to the GP calculator of PARI/GP
3
4
Type ``gp.[tab]`` for a list of all the functions
5
available from your Gp install. Type ``gp.[tab]?`` for
6
Gp's help about a given function. Type ``gp(...)`` to
7
create a new Gp object, and ``gp.eval(...)`` to evaluate a
8
string using Gp (and get the result back as a string).
9
10
EXAMPLES: We illustrate objects that wrap GP objects (gp is the
11
PARI interpreter)::
12
13
sage: M = gp('[1,2;3,4]')
14
sage: M
15
[1, 2; 3, 4]
16
sage: M * M
17
[7, 10; 15, 22]
18
sage: M + M
19
[2, 4; 6, 8]
20
sage: M.matdet()
21
-2
22
23
::
24
25
sage: E = gp.ellinit([1,2,3,4,5])
26
sage: E.ellglobalred()
27
[10351, [1, -1, 0, -1], 1]
28
sage: E.ellan(20)
29
[1, 1, 0, -1, -3, 0, -1, -3, -3, -3, -1, 0, 1, -1, 0, -1, 5, -3, 4, 3]
30
31
::
32
33
sage: primitive_root(7)
34
3
35
sage: x = gp("znlog( Mod(2,7), Mod(3,7))")
36
sage: 3^x % 7
37
2
38
39
::
40
41
sage: print gp("taylor(sin(x),x)")
42
x - 1/6*x^3 + 1/120*x^5 - 1/5040*x^7 + 1/362880*x^9 - 1/39916800*x^11 + 1/6227020800*x^13 - 1/1307674368000*x^15 + O(x^16)
43
44
GP has a powerful very efficient algorithm for numerical
45
computation of integrals.
46
47
::
48
49
sage: gp("a = intnum(x=0,6,sin(x))")
50
0.03982971334963397945434770208 # 32-bit
51
0.039829713349633979454347702077075594548 # 64-bit
52
sage: gp("a")
53
0.03982971334963397945434770208 # 32-bit
54
0.039829713349633979454347702077075594548 # 64-bit
55
sage: gp.kill("a")
56
sage: gp("a")
57
a
58
59
Note that gp ASCII plots *do* work in Sage, as follows::
60
61
sage: print gp.eval("plot(x=0,6,sin(x))")
62
<BLANKLINE>
63
0.9988963 |''''''''''''_x...x_''''''''''''''''''''''''''''''''''''''''''|
64
| x" "x |
65
| _" "_ |
66
| x x |
67
| " " |
68
| " " |
69
| _" "_ |
70
| _ _ |
71
| _ _ |
72
|_ _ |
73
_ |
74
`````````````````````````````````"``````````````````````````````
75
| " |
76
| " |
77
| " "
78
| "_ _"|
79
| _ _ |
80
| _ _ |
81
| x x |
82
| "_ _" |
83
| x_ _x |
84
-0.998955 |............................................."x____x".........|
85
0 6
86
87
The GP interface reads in even very long input (using files) in a
88
robust manner, as long as you are creating a new object.
89
90
::
91
92
sage: t = '"%s"'%10^10000 # ten thousand character string.
93
sage: a = gp.eval(t)
94
sage: a = gp(t)
95
96
In Sage, the PARI large galois groups datafiles should be installed
97
by default::
98
99
sage: f = gp('x^9 - x - 2')
100
sage: f.polgalois()
101
[362880, -1, 34, "S9"]
102
103
TESTS:
104
105
Test error recovery::
106
107
sage: x = gp('1/0')
108
Traceback (most recent call last):
109
...
110
TypeError: Error executing code in GP:
111
CODE:
112
sage[...]=1/0;
113
PARI/GP ERROR:
114
*** at top-level: sage[...]=1/0
115
*** ^--
116
*** _/_: division by zero
117
118
AUTHORS:
119
120
- William Stein
121
122
- David Joyner: some examples
123
124
- William Stein (2006-03-01): added tab completion for methods:
125
gp.[tab] and x = gp(blah); x.[tab]
126
127
- William Stein (2006-03-01): updated to work with PARI 2.2.12-beta
128
129
- William Stein (2006-05-17): updated to work with PARI 2.2.13-beta
130
"""
131
132
##########################################################################
133
#
134
# Copyright (C) 2005 William Stein <[email protected]>
135
#
136
# Distributed under the terms of the GNU General Public License (GPL)
137
#
138
# http://www.gnu.org/licenses/
139
#
140
##########################################################################
141
142
from expect import Expect, ExpectElement, ExpectFunction, FunctionElement
143
from sage.misc.misc import verbose
144
from sage.libs.pari.all import pari
145
import sage.rings.complex_field
146
## import sage.rings.all
147
148
class Gp(Expect):
149
"""
150
Interface to the PARI gp interpreter.
151
152
Type ``gp.[tab]`` for a list of all the functions
153
available from your Gp install. Type ``gp.[tab]?`` for
154
Gp's help about a given function. Type ``gp(...)`` to
155
create a new Gp object, and ``gp.eval(...)`` to evaluate a
156
string using Gp (and get the result back as a string).
157
158
INPUT:
159
160
- ``stacksize`` (int, default 10000000) -- the initial PARI
161
stacksize in bytes (default 10MB)
162
- ``maxread`` (int, default 100000) -- ??
163
- ``script_subdirectory`` (string, default None) -- name of the subdirectory of SAGE_ROOT/data/extcode/pari from which to read scripts
164
- ``logfile`` (string, default None) -- log file for the pexpect interface
165
- ``server`` -- name of remote server
166
- ``server_tmpdir`` -- name of temporary directory on remote server
167
- ``init_list_length`` (int, default 1024) -- length of initial list of local variables.
168
169
EXAMPLES::
170
171
sage: Gp()
172
PARI/GP interpreter
173
"""
174
def __init__(self, stacksize=10000000, # 10MB
175
maxread=100000, script_subdirectory=None,
176
logfile=None,
177
server=None,
178
server_tmpdir=None,
179
init_list_length=1024):
180
"""
181
Initialization of this PARI gp interpreter.
182
183
INPUT:
184
185
- ``stacksize`` (int, default 10000000) -- the initial PARI
186
stacksize in bytes (default 10MB)
187
- ``maxread`` (int, default 100000) -- ??
188
- ``script_subdirectory`` (string, default None) -- name of the subdirectory of SAGE_ROOT/data/extcode/pari from which to read scripts
189
- ``logfile`` (string, default None) -- log file for the pexpect interface
190
- ``server`` -- name of remote server
191
- ``server_tmpdir`` -- name of temporary directory on remote server
192
- ``init_list_length`` (int, default 1024) -- length of initial list of local variables.
193
194
EXAMPLES::
195
196
sage: gp == loads(dumps(gp))
197
True
198
"""
199
Expect.__init__(self,
200
name = 'pari',
201
prompt = '\\? ',
202
command = "gp --emacs --quiet --stacksize %s"%stacksize,
203
maxread = maxread,
204
server=server,
205
server_tmpdir=server_tmpdir,
206
script_subdirectory = script_subdirectory,
207
restart_on_ctrlc = False,
208
verbose_start = False,
209
logfile=logfile,
210
eval_using_file_cutoff=1024)
211
self.__seq = 0
212
self.__var_store_len = 0
213
self.__init_list_length = init_list_length
214
215
216
def _repr_(self):
217
"""
218
String representation of this PARI gp interpreter.
219
220
EXAMPLES::
221
222
sage: gp # indirect doctest
223
PARI/GP interpreter
224
"""
225
return 'PARI/GP interpreter'
226
227
def __reduce__(self):
228
"""
229
EXAMPLES::
230
231
sage: gp.__reduce__()
232
(<function reduce_load_GP at 0x...>, ())
233
sage: f, args = _
234
sage: f(*args)
235
PARI/GP interpreter
236
"""
237
return reduce_load_GP, tuple([])
238
239
def _function_class(self):
240
"""
241
Returns the GpFunction class.
242
243
EXAMPLES::
244
245
sage: gp._function_class()
246
<class 'sage.interfaces.gp.GpFunction'>
247
sage: type(gp.gcd)
248
<class 'sage.interfaces.gp.GpFunction'>
249
"""
250
return GpFunction
251
252
def _quit_string(self):
253
"""
254
Returns the string used to quit the GP interpreter.
255
256
EXAMPLES::
257
258
sage: gp._quit_string()
259
'\\q'
260
261
::
262
263
sage: g = Gp()
264
sage: a = g(2)
265
sage: g.is_running()
266
True
267
sage: g.quit()
268
sage: g.is_running()
269
False
270
"""
271
return r"\q"
272
273
def _read_in_file_command(self, filename):
274
r"""
275
Returns the string used to read filename into GP.
276
277
EXAMPLES::
278
279
sage: gp._read_in_file_command('test')
280
'read("test")'
281
282
::
283
284
sage: filename = tmp_filename()
285
sage: f = open(filename, 'w')
286
sage: f.write('x = 22;\n')
287
sage: f.close()
288
sage: gp.read(filename)
289
sage: gp.get('x').strip()
290
'22'
291
"""
292
return 'read("%s")'%filename
293
294
def trait_names(self):
295
"""
296
EXAMPLES::
297
298
sage: c = gp.trait_names()
299
sage: len(c) > 100
300
True
301
sage: 'gcd' in c
302
True
303
"""
304
try:
305
b = self.__builtin
306
except AttributeError:
307
b = self.eval('?*').split()
308
self.__builtin = b
309
return b + self.eval('?0').split()
310
311
def get_precision(self):
312
"""
313
Return the current PARI precision for real number computations.
314
315
EXAMPLES::
316
317
sage: gp.get_precision()
318
28 # 32-bit
319
38 # 64-bit
320
"""
321
return self.get_default('realprecision')
322
323
get_real_precision = get_precision
324
325
def set_precision(self, prec=None):
326
"""
327
Sets the PARI precision (in decimal digits) for real computations, and returns the old value.
328
329
EXAMPLES::
330
331
sage: old_prec = gp.set_precision(53); old_prec
332
28 # 32-bit
333
38 # 64-bit
334
sage: gp.get_precision()
335
53
336
sage: gp.set_precision(old_prec)
337
53
338
sage: gp.get_precision()
339
28 # 32-bit
340
38 # 64-bit
341
"""
342
return self.set_default('realprecision', prec)
343
344
set_real_precision = set_precision
345
346
def get_series_precision(self):
347
"""
348
Return the current PARI power series precision.
349
350
EXAMPLES::
351
352
sage: gp.get_series_precision()
353
16
354
"""
355
return self.get_default('seriesprecision')
356
357
def set_series_precision(self, prec=None):
358
"""
359
Sets the PARI power series precision, and returns the old precision.
360
361
EXAMPLES::
362
363
sage: old_prec = gp.set_series_precision(50); old_prec
364
16
365
sage: gp.get_series_precision()
366
50
367
sage: gp.set_series_precision(old_prec)
368
50
369
sage: gp.get_series_precision()
370
16
371
"""
372
return self.set_default('seriesprecision', prec)
373
374
def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if_needed=False):
375
"""
376
EXAMPLES::
377
378
sage: gp._eval_line('2+2')
379
'4'
380
381
TESTS:
382
383
We verify that trac 11617 is fixed::
384
385
sage: gp._eval_line('a='+str(range(2*10^5)))[:70]
386
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,'
387
"""
388
line = line.strip()
389
if len(line) == 0:
390
return ''
391
a = Expect._eval_line(self, line,
392
allow_use_file=allow_use_file,
393
wait_for_prompt=wait_for_prompt)
394
if a.find("the PARI stack overflows") != -1:
395
verbose("automatically doubling the PARI stack and re-executing current input line")
396
b = self.eval("allocatemem()")
397
if b.find("Warning: not enough memory") != -1:
398
raise RuntimeError, a
399
return self._eval_line(line, allow_use_file=allow_use_file,
400
wait_for_prompt=wait_for_prompt)
401
else:
402
return a
403
404
def cputime(self, t=None):
405
"""
406
cputime for pari - cputime since the pari process was started.
407
408
INPUT:
409
410
411
- ``t`` - (default: None); if not None, then returns
412
time since t
413
414
415
.. warning::
416
417
If you call gettime explicitly, e.g., gp.eval('gettime'),
418
you will throw off this clock.
419
420
EXAMPLES::
421
422
sage: gp.cputime() # random output
423
0.0080000000000000002
424
sage: gp.factor('2^157-1')
425
[852133201, 1; 60726444167, 1; 1654058017289, 1; 2134387368610417, 1]
426
sage: gp.cputime() # random output
427
0.26900000000000002
428
"""
429
try:
430
tm = self._last
431
except AttributeError:
432
tm = 0.0
433
m = eval(self.eval('gettime()/1000.0')) + tm
434
self._last = m
435
if t:
436
return m - t
437
return m
438
439
def set_default(self, var=None, value=None):
440
"""
441
Set a PARI gp configuration variable, and return the old value.
442
443
INPUT:
444
445
- ``var`` (string, default None) -- the name of a PARI gp
446
configuration variable. (See ``gp.default()`` for a list.)
447
- ``value`` -- the value to set the variable to.
448
449
EXAMPLES::
450
451
sage: old_prec = gp.set_default('realprecision',100); old_prec
452
28 # 32-bit
453
38 # 64-bit
454
sage: gp.get_default('realprecision')
455
100
456
sage: gp.set_default('realprecision',old_prec)
457
100
458
sage: gp.get_default('realprecision')
459
28 # 32-bit
460
38 # 64-bit
461
"""
462
old = self.get_default(var)
463
self._eval_line('default(%s,%s)'%(var,value))
464
return old
465
466
def get_default(self, var=None):
467
"""
468
Return the current value of a PARI gp configuration variable.
469
470
INPUT:
471
472
- ``var`` (string, default None) -- the name of a PARI gp
473
configuration variable. (See ``gp.default()`` for a list.)
474
475
OUTPUT:
476
477
(string) the value of the variable.
478
479
EXAMPLES::
480
481
sage: gp.get_default('log')
482
0
483
sage: gp.get_default('datadir')
484
'.../local/share/pari'
485
sage: gp.get_default('seriesprecision')
486
16
487
sage: gp.get_default('realprecision')
488
28 # 32-bit
489
38 # 64-bit
490
"""
491
return eval(self._eval_line('default(%s)'%var))
492
493
def set(self, var, value):
494
"""
495
Set the GP variable var to the given value.
496
497
INPUT:
498
499
- ``var`` (string) -- a valid GP variable identifier
500
- ``value`` -- a value for the variable
501
502
EXAMPLES::
503
504
sage: gp.set('x', '2')
505
sage: gp.get('x')
506
'2'
507
"""
508
cmd = '%s=%s;'%(var,value)
509
out = self.eval(cmd)
510
if out.find('***') != -1:
511
raise TypeError, "Error executing code in GP:\nCODE:\n\t%s\nPARI/GP ERROR:\n%s"%(cmd, out)
512
513
514
def get(self, var):
515
"""
516
Get the value of the GP variable var.
517
518
INPUT:
519
520
- ``var`` (string) -- a valid GP variable identifier
521
522
EXAMPLES::
523
524
sage: gp.set('x', '2')
525
sage: gp.get('x')
526
'2'
527
"""
528
return self.eval('print(%s)'%var)
529
530
def kill(self, var):
531
"""
532
Kill the value of the GP variable var.
533
534
INPUT:
535
536
- ``var`` (string) -- a valid GP variable identifier
537
538
EXAMPLES::
539
540
sage: gp.set('xx', '22')
541
sage: gp.get('xx')
542
'22'
543
sage: gp.kill('xx')
544
sage: gp.get('xx')
545
'xx'
546
"""
547
self.eval('kill(%s)'%var)
548
549
#def xclear(self, var):
550
#"""
551
#Clear the variable named var.
552
#"""
553
#for varname based memory -- only 65000 variables and then dead.
554
#self.eval('kill(%s)'%var)
555
# for array-based memory this is best:
556
#self.eval('%s=0'%var)
557
# However, I've commented it out, since PARI doesn't seem
558
# to ever free any memory on its stack anyways.
559
# Killing variables as above takes a lot of time in some
560
# cases, also.
561
562
def _next_var_name(self):
563
"""
564
Return the name of the next unused interface variable name.
565
566
EXAMPLES::
567
568
sage: g = Gp()
569
sage: g._next_var_name()
570
'sage[1]'
571
sage: g(2)^2
572
4
573
sage: g._next_var_name()
574
'sage[5]'
575
"""
576
self.__seq += 1
577
if self.__seq >= self.__var_store_len:
578
if self.__var_store_len == 0:
579
self.eval('sage=vector(%s,k,0);'%self.__init_list_length)
580
self.__var_store_len = self.__init_list_length
581
else:
582
self.eval('sage=concat(sage, vector(%s,k,0));'%self.__var_store_len)
583
self.__var_store_len *= 2
584
verbose("doubling PARI/sage object vector: %s"%self.__var_store_len)
585
return 'sage[%s]'%self.__seq
586
587
def quit(self, verbose=False, timeout=0.25):
588
"""
589
Terminate the GP process.
590
591
EXAMPLES::
592
593
sage: a = gp('10'); a
594
10
595
sage: gp.quit()
596
sage: a
597
Traceback (most recent call last):
598
...
599
ValueError: The pari session in which this object was defined is no longer running.
600
sage: gp(pi)
601
3.1415926535897932384626433832795028842 # 64-bit
602
3.141592653589793238462643383 # 32-bit
603
"""
604
self.__var_store_len = 0
605
Expect.quit(self, verbose=verbose, timeout=timeout)
606
607
def console(self):
608
"""
609
Spawn a new GP command-line session.
610
611
EXAMPLES::
612
613
sage: gp.console() # not tested
614
GP/PARI CALCULATOR Version 2.4.3 (development svn-12577)
615
amd64 running linux (x86-64/GMP-4.2.1 kernel) 64-bit version
616
compiled: Jul 21 2010, gcc-4.6.0 20100705 (experimental) (GCC)
617
(readline v6.0 enabled, extended help enabled)
618
"""
619
gp_console()
620
621
def version(self):
622
"""
623
Returns the version of GP being used.
624
625
EXAMPLES::
626
627
sage: gp.version() # not tested
628
((2, 4, 3), 'GP/PARI CALCULATOR Version 2.4.3 (development svn-12577)')
629
"""
630
return gp_version()
631
632
def _object_class(self):
633
"""
634
Returns the GpElement class.
635
636
EXAMPLES::
637
638
sage: gp._object_class()
639
<class 'sage.interfaces.gp.GpElement'>
640
sage: type(gp(2))
641
<class 'sage.interfaces.gp.GpElement'>
642
"""
643
return GpElement
644
645
def _function_element_class(self):
646
"""
647
Returns the GpFunctionElement class.
648
649
EXAMPLES::
650
651
sage: gp._function_element_class()
652
<class 'sage.interfaces.gp.GpFunctionElement'>
653
654
::
655
656
sage: type(gp(2).gcd)
657
<class 'sage.interfaces.gp.GpFunctionElement'>
658
"""
659
return GpFunctionElement
660
661
def _true_symbol(self):
662
"""
663
Returns the symbol used for truth in GP.
664
665
EXAMPLES::
666
667
sage: gp._true_symbol()
668
'1'
669
670
::
671
672
sage: gp(2) == gp(2)
673
True
674
"""
675
return '1'
676
677
def _false_symbol(self):
678
"""
679
Returns the symbol used for falsity in GP.
680
681
EXAMPLES::
682
683
sage: gp._false_symbol()
684
'0'
685
686
::
687
688
sage: gp(2) == gp(3)
689
False
690
"""
691
return '0'
692
693
def _equality_symbol(self):
694
"""
695
Returns the symbol used for equality in GP.
696
697
EXAMPLES::
698
699
sage: gp._equality_symbol()
700
'=='
701
702
::
703
704
sage: gp(2) == gp(2)
705
True
706
"""
707
return '=='
708
709
def _exponent_symbol(self):
710
"""
711
Returns the symbol to denote the exponent of a number in GP.
712
713
EXAMPLES::
714
715
sage: gp._exponent_symbol()
716
' E'
717
718
::
719
720
sage: repr(gp(10.^80)).replace(gp._exponent_symbol(), 'e')
721
'1.0000000000000000000000000000000000000e80' # 64-bit
722
'1.000000000000000000000000000e80' # 32-bit
723
"""
724
return ' E'
725
726
def help(self, command):
727
r"""
728
Returns GP's help for ``command``.
729
730
EXAMPLES::
731
732
sage: gp.help('gcd')
733
'gcd(x,{y}): greatest common divisor of x and y.'
734
"""
735
return self.eval('?%s'%command).strip()
736
737
def new_with_bits_prec(self, s, precision = 0):
738
r"""
739
Creates a GP object from s with ``precision`` bits of
740
precision. GP actually automatically increases this precision to
741
the nearest word (i.e. the next multiple of 32 on a 32-bit machine,
742
or the next multiple of 64 on a 64-bit machine).
743
744
EXAMPLES::
745
746
sage: pi_def = gp(pi); pi_def
747
3.141592653589793238462643383 # 32-bit
748
3.1415926535897932384626433832795028842 # 64-bit
749
sage: pi_def.precision()
750
28 # 32-bit
751
38 # 64-bit
752
sage: pi_150 = gp.new_with_bits_prec(pi, 150)
753
sage: new_prec = pi_150.precision(); new_prec
754
48 # 32-bit
755
57 # 64-bit
756
sage: old_prec = gp.set_precision(new_prec); old_prec
757
28 # 32-bit
758
38 # 64-bit
759
sage: pi_150
760
3.14159265358979323846264338327950288419716939938 # 32-bit
761
3.14159265358979323846264338327950288419716939937510582098 # 64-bit
762
sage: gp.set_precision(old_prec)
763
48 # 32-bit
764
57 # 64-bit
765
sage: gp.get_precision()
766
28 # 32-bit
767
38 # 64-bit
768
"""
769
if precision:
770
old_prec = self.get_real_precision()
771
prec = int(precision/3.321928095)
772
self.set_real_precision(prec)
773
x = self(s)
774
self.set_real_precision(old_prec)
775
else:
776
x = self(s)
777
return x
778
779
780
class GpElement(ExpectElement):
781
"""
782
EXAMPLES: This example illustrates dumping and loading GP elements
783
to compressed strings.
784
785
::
786
787
sage: a = gp(39393)
788
sage: loads(a.dumps()) == a
789
True
790
791
Since dumping and loading uses the string representation of the
792
object, it need not result in an identical object from the point of
793
view of PARI::
794
795
sage: E = gp('ellinit([1,2,3,4,5])')
796
sage: loads(dumps(E)) == E
797
False
798
sage: loads(E.dumps())
799
[1, 2, 3, 4, 5, 9, 11, 29, 35, -183, -3429, -10351, 6128487/10351, [-1.618909932267371342378000940, -0.3155450338663143288109995302 - 2.092547096911958607981689447*I, -0.3155450338663143288109995302 + 2.092547096911958607981689447*I]~, 2.780740013766729771063197627, 1.390370006883364885531598814 - 1.068749776356193066159263548*I, 3.109648242324380328550149122 + 1.009741959000000000000000000 E-28*I, 1.554824121162190164275074561 + 1.064374745210273756943885994*I, 2.971915267817909670771647951] # 32-bit
800
[1, 2, 3, 4, 5, 9, 11, 29, 35, -183, -3429, -10351, 6128487/10351, [-1.6189099322673713423780009396072169751, -0.31554503386631432881099953019639151248 - 2.0925470969119586079816894466366945829*I, -0.31554503386631432881099953019639151248 + 2.0925470969119586079816894466366945829*I]~, 2.7807400137667297710631976271813584994, 1.3903700068833648855315988135906792497 - 1.0687497763561930661592635474375038788*I, 3.1096482423243803285501491221965830079 + 2.3509887016445750160000000000000000000 E-38*I, 1.5548241211621901642750745610982915040 + 1.0643747452102737569438859937299427442*I, 2.9719152678179096707716479509361896060] # 64-bit
801
sage: E
802
[1, 2, 3, 4, 5, 9, 11, 29, 35, -183, -3429, -10351, 6128487/10351, [-1.618909932267371342378000940, -0.3155450338663143288109995302 - 2.092547096911958607981689447*I, -0.3155450338663143288109995302 + 2.092547096911958607981689447*I]~, 2.780740013766729771063197627, 1.390370006883364885531598814 - 1.068749776356193066159263548*I, 3.109648242324380328550149122 + 1.009741959 E-28*I, 1.554824121162190164275074561 + 1.064374745210273756943885994*I, 2.971915267817909670771647951] # 32-bit
803
[1, 2, 3, 4, 5, 9, 11, 29, 35, -183, -3429, -10351, 6128487/10351, [-1.6189099322673713423780009396072169751, -0.31554503386631432881099953019639151248 - 2.0925470969119586079816894466366945829*I, -0.31554503386631432881099953019639151248 + 2.0925470969119586079816894466366945829*I]~, 2.7807400137667297710631976271813584994, 1.3903700068833648855315988135906792497 - 1.0687497763561930661592635474375038788*I, 3.1096482423243803285501491221965830079 + 2.350988701644575016 E-38*I, 1.5548241211621901642750745610982915040 + 1.0643747452102737569438859937299427442*I, 2.9719152678179096707716479509361896060] # 64-bit
804
805
The two elliptic curves look the same, but internally the floating
806
point numbers are slightly different.
807
"""
808
809
def _sage_(self):
810
"""
811
Convert this GpElement into a Sage object, if possible.
812
813
EXAMPLES::
814
815
sage: gp(I).sage()
816
i
817
sage: gp(I).sage().parent()
818
Maximal Order in Number Field in i with defining polynomial x^2 + 1
819
820
::
821
822
sage: M = Matrix(ZZ,2,2,[1,2,3,4]); M
823
[1 2]
824
[3 4]
825
sage: gp(M)
826
[1, 2; 3, 4]
827
sage: gp(M).sage()
828
[1 2]
829
[3 4]
830
sage: gp(M).sage() == M
831
True
832
"""
833
return pari(str(self)).python()
834
835
def __long__(self):
836
"""
837
Return Python long.
838
839
EXAMPLES::
840
841
sage: long(gp(10))
842
10L
843
"""
844
return long(str(self))
845
846
def __float__(self):
847
"""
848
Return Python float.
849
850
EXAMPLES::
851
852
sage: float(gp(10))
853
10.0
854
"""
855
return float(pari(str(self)))
856
857
def bool(self):
858
"""
859
EXAMPLES::
860
861
sage: gp(2).bool()
862
True
863
sage: bool(gp(2))
864
True
865
sage: bool(gp(0))
866
False
867
"""
868
P = self._check_valid()
869
return P.eval('%s != 0'%(self.name())) == '1'
870
871
def _complex_mpfr_field_(self, CC):
872
"""
873
Return ComplexField element of self.
874
875
INPUT:
876
877
- ``CC`` -- a Complex or Real Field.
878
879
EXAMPLES::
880
881
sage: z = gp(1+15*I); z
882
1 + 15*I
883
sage: z._complex_mpfr_field_(CC)
884
1.00000000000000 + 15.0000000000000*I
885
sage: CC(z) # CC(gp(1+15*I))
886
1.00000000000000 + 15.0000000000000*I
887
sage: CC(gp(11243.9812+15*I))
888
11243.9812000000 + 15.0000000000000*I
889
sage: ComplexField(10)(gp(11243.9812+15*I))
890
11000. + 15.*I
891
"""
892
# Multiplying by CC(1) is necessary here since
893
# sage: pari(gp(1+I)).sage().parent()
894
# Maximal Order in Number Field in i with defining polynomial x^2 + 1
895
896
return CC((CC(1)*pari(self))._sage_())
897
898
def _complex_double_(self, CDF):
899
"""
900
Returns this value as a CDF element.
901
902
EXAMPLES::
903
904
sage: CDF(gp(pi+I*e))
905
3.14159265359 + 2.71828182846*I
906
"""
907
# Retrieving values from another computer algebra system is
908
# slow anyway, right?
909
cc_val = self._complex_mpfr_field_(sage.rings.complex_field.ComplexField())
910
return CDF(cc_val)
911
912
def __len__(self):
913
"""
914
EXAMPLES::
915
916
sage: len(gp([1,2,3]))
917
3
918
"""
919
return int(self.length())
920
921
def __del__(self):
922
"""
923
Note that clearing object is pointless since it wastes time and
924
PARI/GP doesn't really free used memory.
925
926
EXAMPLES::
927
928
sage: a = gp(2)
929
sage: a.__del__()
930
sage: a
931
2
932
sage: del a
933
sage: a
934
Traceback (most recent call last):
935
...
936
NameError: name 'a' is not defined
937
"""
938
return
939
940
# This is tempting -- but the (la)tex output is very very
941
# out of date, e.g., for matrices it uses \pmatrix (which
942
# causes an error if amsmath is loaded) and for rationals
943
# it does nothing, etc.
944
#def _latex_(self):
945
# P = self._check_valid()
946
# return P.eval('printtex(%s)'%self.name())
947
948
def trait_names(self):
949
"""
950
EXAMPLES::
951
952
sage: 'gcd' in gp(2).trait_names()
953
True
954
"""
955
return self.parent().trait_names()
956
957
958
class GpFunctionElement(FunctionElement):
959
pass
960
961
class GpFunction(ExpectFunction):
962
pass
963
964
965
966
def is_GpElement(x):
967
"""
968
Returns True of x is a GpElement.
969
970
EXAMPLES::
971
972
sage: from sage.interfaces.gp import is_GpElement
973
sage: is_GpElement(gp(2))
974
True
975
sage: is_GpElement(2)
976
False
977
"""
978
return isinstance(x, GpElement)
979
980
from sage.misc.all import DOT_SAGE, SAGE_ROOT
981
import os
982
983
# Set GPRC environment variable to $SAGE_ROOT/local/etc/gprc.expect
984
os.environ["GPRC"] = '%s/local/etc/gprc.expect'%SAGE_ROOT
985
986
# An instance
987
gp = Gp(logfile=DOT_SAGE+'/gp-expect.log') # useful for debugging!
988
989
def reduce_load_GP():
990
"""
991
Returns the GP interface object defined in sage.interfaces.gp.
992
993
EXAMPLES::
994
995
sage: from sage.interfaces.gp import reduce_load_GP
996
sage: reduce_load_GP()
997
PARI/GP interpreter
998
"""
999
return gp
1000
1001
def gp_console():
1002
"""
1003
Spawn a new GP command-line session.
1004
1005
EXAMPLES::
1006
1007
sage: gp.console() # not tested
1008
GP/PARI CALCULATOR Version 2.4.3 (development svn-12577)
1009
amd64 running linux (x86-64/GMP-4.2.1 kernel) 64-bit version
1010
compiled: Jul 21 2010, gcc-4.6.0 20100705 (experimental) (GCC)
1011
(readline v6.0 enabled, extended help enabled)
1012
"""
1013
os.system('gp')
1014
1015
1016
def gp_version():
1017
"""
1018
EXAMPLES::
1019
1020
sage: gp.version() # not tested
1021
((2, 4, 3), 'GP/PARI CALCULATOR Version 2.4.3 (development svn-12577)')
1022
"""
1023
v = gp.eval(r'\v')
1024
i = v.find("Version ")
1025
w = v[i+len("Version "):]
1026
i = w.find(' ')
1027
w = w[:i]
1028
t = tuple([int(n) for n in w.split('.')])
1029
k = v.find('\n')
1030
return t, v[:k].strip()
1031
1032