Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/sage/libs/pari/pari_instance.pyx
8871 views
1
"""
2
PARI C-library interface
3
4
AUTHORS:
5
6
- William Stein (2006-03-01): updated to work with PARI 2.2.12-beta
7
8
- William Stein (2006-03-06): added newtonpoly
9
10
- Justin Walker: contributed some of the function definitions
11
12
- Gonzalo Tornaria: improvements to conversions; much better error
13
handling.
14
15
- Robert Bradshaw, Jeroen Demeyer, William Stein (2010-08-15):
16
Upgrade to PARI 2.4.3 (#9343)
17
18
- Jeroen Demeyer (2011-11-12): rewrite various conversion routines
19
(#11611, #11854, #11952)
20
21
- Peter Bruin (2013-11-17): split off this file from gen.pyx (#15185)
22
23
24
EXAMPLES::
25
26
sage: pari('5! + 10/x')
27
(120*x + 10)/x
28
sage: pari('intnum(x=0,13,sin(x)+sin(x^2) + x)')
29
85.1885681951527
30
sage: f = pari('x^3-1')
31
sage: v = f.factor(); v
32
[x - 1, 1; x^2 + x + 1, 1]
33
sage: v[0] # indexing is 0-based unlike in GP.
34
[x - 1, x^2 + x + 1]~
35
sage: v[1]
36
[1, 1]~
37
38
Arithmetic obeys the usual coercion rules::
39
40
sage: type(pari(1) + 1)
41
<type 'sage.libs.pari.gen.gen'>
42
sage: type(1 + pari(1))
43
<type 'sage.libs.pari.gen.gen'>
44
45
GUIDE TO REAL PRECISION AND THE PARI LIBRARY
46
47
The default real precision in communicating with the Pari library
48
is the same as the default Sage real precision, which is 53 bits.
49
Inexact Pari objects are therefore printed by default to 15 decimal
50
digits (even if they are actually more precise).
51
52
Default precision example (53 bits, 15 significant decimals)::
53
54
sage: a = pari(1.23); a
55
1.23000000000000
56
sage: a.sin()
57
0.942488801931698
58
59
Example with custom precision of 200 bits (60 significant
60
decimals)::
61
62
sage: R = RealField(200)
63
sage: a = pari(R(1.23)); a # only 15 significant digits printed
64
1.23000000000000
65
sage: R(a) # but the number is known to precision of 200 bits
66
1.2300000000000000000000000000000000000000000000000000000000
67
sage: a.sin() # only 15 significant digits printed
68
0.942488801931698
69
sage: R(a.sin()) # but the number is known to precision of 200 bits
70
0.94248880193169751002382356538924454146128740562765030213504
71
72
It is possible to change the number of printed decimals::
73
74
sage: R = RealField(200) # 200 bits of precision in computations
75
sage: old_prec = pari.set_real_precision(60) # 60 decimals printed
76
sage: a = pari(R(1.23)); a
77
1.23000000000000000000000000000000000000000000000000000000000
78
sage: a.sin()
79
0.942488801931697510023823565389244541461287405627650302135038
80
sage: pari.set_real_precision(old_prec) # restore the default printing behavior
81
60
82
83
Unless otherwise indicated in the docstring, most Pari functions
84
that return inexact objects use the precision of their arguments to
85
decide the precision of the computation. However, if some of these
86
arguments happen to be exact numbers (integers, rationals, etc.),
87
an optional parameter indicates the precision (in bits) to which
88
these arguments should be converted before the computation. If this
89
precision parameter is missing, the default precision of 53 bits is
90
used. The following first converts 2 into a real with 53-bit
91
precision::
92
93
sage: R = RealField()
94
sage: R(pari(2).sin())
95
0.909297426825682
96
97
We can ask for a better precision using the optional parameter::
98
99
sage: R = RealField(150)
100
sage: R(pari(2).sin(precision=150))
101
0.90929742682568169539601986591174484270225497
102
103
Warning regarding conversions Sage - Pari - Sage: Some care must be
104
taken when juggling inexact types back and forth between Sage and
105
Pari. In theory, calling p=pari(s) creates a Pari object p with the
106
same precision as s; in practice, the Pari library's precision is
107
word-based, so it will go up to the next word. For example, a
108
default 53-bit Sage real s will be bumped up to 64 bits by adding
109
bogus 11 bits. The function p.python() returns a Sage object with
110
exactly the same precision as the Pari object p. So
111
pari(s).python() is definitely not equal to s, since it has 64 bits
112
of precision, including the bogus 11 bits. The correct way of
113
avoiding this is to coerce pari(s).python() back into a domain with
114
the right precision. This has to be done by the user (or by Sage
115
functions that use Pari library functions in gen.pyx). For
116
instance, if we want to use the Pari library to compute sqrt(pi)
117
with a precision of 100 bits::
118
119
sage: R = RealField(100)
120
sage: s = R(pi); s
121
3.1415926535897932384626433833
122
sage: p = pari(s).sqrt()
123
sage: x = p.python(); x # wow, more digits than I expected!
124
1.7724538509055160272981674833410973484
125
sage: x.prec() # has precision 'improved' from 100 to 128?
126
128
127
sage: x == RealField(128)(pi).sqrt() # sadly, no!
128
False
129
sage: R(x) # x should be brought back to precision 100
130
1.7724538509055160272981674833
131
sage: R(x) == s.sqrt()
132
True
133
134
Elliptic curves and precision: If you are working with elliptic
135
curves and want to compute with a precision other than the default
136
53 bits, you should use the precision parameter of ellinit()::
137
138
sage: R = RealField(150)
139
sage: e = pari([0,0,0,-82,0]).ellinit(precision=150)
140
sage: eta1 = e.elleta()[0]
141
sage: R(eta1)
142
3.6054636014326520859158205642077267748102690
143
144
Number fields and precision: TODO
145
146
TESTS:
147
148
Check that output from PARI's print command is actually seen by
149
Sage (ticket #9636)::
150
151
sage: pari('print("test")')
152
test
153
154
"""
155
156
include 'pari_err.pxi'
157
include 'sage/ext/stdsage.pxi'
158
include 'sage/ext/interrupt.pxi'
159
160
import sys
161
162
cimport libc.stdlib
163
cimport cython
164
165
from sage.structure.parent cimport Parent
166
167
from sage.libs.pari.gen cimport gen, objtogen
168
from sage.libs.pari.handle_error cimport pari_error_string, \
169
_pari_init_error_handling, _pari_check_warning, \
170
_pari_handle_exception, _pari_err_recover
171
172
# so Galois groups are represented in a sane way
173
# See the polgalois section of the PARI users manual.
174
new_galois_format = 1
175
176
# real precision in decimal digits: see documentation for
177
# get_real_precision() and set_real_precision(). This variable is used
178
# in gp to set the precision of input quantities (e.g. sqrt(2)), and for
179
# determining the number of digits to be printed. It is *not* used as
180
# a "default precision" for internal computations, which always use
181
# the actual precision of arguments together (where relevant) with a
182
# "prec" parameter. In ALL cases (for real computations) the prec
183
# parameter is a WORD precision and NOT decimal precision. Pari reals
184
# with word precision w have bit precision (of the mantissa) equal to
185
# 32*(w-2) or 64*(w-2).
186
#
187
# Hence the only relevance of this parameter in Sage is (1) for the
188
# output format of components of objects of type
189
# 'sage.libs.pari.gen.gen'; (2) for setting the precision of pari
190
# variables created from strings (e.g. via sage: pari('1.2')).
191
#
192
# WARNING: Many pari library functions take a last parameter "prec"
193
# which should be a words precision. In many cases this is redundant
194
# and is simply ignored. In our wrapping of these functions we use
195
# the variable prec here for convenience only.
196
cdef long prec
197
198
#################################################################
199
# conversions between various real precision models
200
#################################################################
201
202
def prec_bits_to_dec(unsigned long prec_in_bits):
203
r"""
204
Convert from precision expressed in bits to precision expressed in
205
decimal.
206
207
EXAMPLES::
208
209
sage: from sage.libs.pari.pari_instance import prec_bits_to_dec
210
sage: prec_bits_to_dec(53)
211
15
212
sage: [(32*n, prec_bits_to_dec(32*n)) for n in range(1, 9)]
213
[(32, 9),
214
(64, 19),
215
(96, 28),
216
(128, 38),
217
(160, 48),
218
(192, 57),
219
(224, 67),
220
(256, 77)]
221
"""
222
cdef double log_2 = 0.301029995663981
223
return int(prec_in_bits*log_2)
224
225
def prec_dec_to_bits(unsigned long prec_in_dec):
226
r"""
227
Convert from precision expressed in decimal to precision expressed
228
in bits.
229
230
EXAMPLES::
231
232
sage: from sage.libs.pari.pari_instance import prec_dec_to_bits
233
sage: prec_dec_to_bits(15)
234
49
235
sage: [(n, prec_dec_to_bits(n)) for n in range(10, 100, 10)]
236
[(10, 33),
237
(20, 66),
238
(30, 99),
239
(40, 132),
240
(50, 166),
241
(60, 199),
242
(70, 232),
243
(80, 265),
244
(90, 298)]
245
"""
246
cdef double log_10 = 3.32192809488736
247
return int(prec_in_dec*log_10)
248
249
cpdef long prec_bits_to_words(unsigned long prec_in_bits):
250
r"""
251
Convert from precision expressed in bits to pari real precision
252
expressed in words. Note: this rounds up to the nearest word,
253
adjusts for the two codewords of a pari real, and is
254
architecture-dependent.
255
256
EXAMPLES::
257
258
sage: from sage.libs.pari.pari_instance import prec_bits_to_words
259
sage: prec_bits_to_words(70)
260
5 # 32-bit
261
4 # 64-bit
262
263
::
264
265
sage: [(32*n, prec_bits_to_words(32*n)) for n in range(1, 9)]
266
[(32, 3), (64, 4), (96, 5), (128, 6), (160, 7), (192, 8), (224, 9), (256, 10)] # 32-bit
267
[(32, 3), (64, 3), (96, 4), (128, 4), (160, 5), (192, 5), (224, 6), (256, 6)] # 64-bit
268
"""
269
if not prec_in_bits:
270
return prec
271
cdef unsigned long wordsize = BITS_IN_LONG
272
273
# This equals ceil(prec_in_bits/wordsize) + 2
274
return (prec_in_bits - 1)//wordsize + 3
275
276
def prec_words_to_bits(long prec_in_words):
277
r"""
278
Convert from pari real precision expressed in words to precision
279
expressed in bits. Note: this adjusts for the two codewords of a
280
pari real, and is architecture-dependent.
281
282
EXAMPLES::
283
284
sage: from sage.libs.pari.pari_instance import prec_words_to_bits
285
sage: prec_words_to_bits(10)
286
256 # 32-bit
287
512 # 64-bit
288
sage: [(n, prec_words_to_bits(n)) for n in range(3, 10)]
289
[(3, 32), (4, 64), (5, 96), (6, 128), (7, 160), (8, 192), (9, 224)] # 32-bit
290
[(3, 64), (4, 128), (5, 192), (6, 256), (7, 320), (8, 384), (9, 448)] # 64-bit
291
"""
292
# see user's guide to the pari library, page 10
293
return (prec_in_words - 2) * BITS_IN_LONG
294
295
def prec_dec_to_words(long prec_in_dec):
296
r"""
297
Convert from precision expressed in decimal to precision expressed
298
in words. Note: this rounds up to the nearest word, adjusts for the
299
two codewords of a pari real, and is architecture-dependent.
300
301
EXAMPLES::
302
303
sage: from sage.libs.pari.pari_instance import prec_dec_to_words
304
sage: prec_dec_to_words(38)
305
6 # 32-bit
306
4 # 64-bit
307
sage: [(n, prec_dec_to_words(n)) for n in range(10, 90, 10)]
308
[(10, 4), (20, 5), (30, 6), (40, 7), (50, 8), (60, 9), (70, 10), (80, 11)] # 32-bit
309
[(10, 3), (20, 4), (30, 4), (40, 5), (50, 5), (60, 6), (70, 6), (80, 7)] # 64-bit
310
"""
311
return prec_bits_to_words(prec_dec_to_bits(prec_in_dec))
312
313
def prec_words_to_dec(long prec_in_words):
314
r"""
315
Convert from precision expressed in words to precision expressed in
316
decimal. Note: this adjusts for the two codewords of a pari real,
317
and is architecture-dependent.
318
319
EXAMPLES::
320
321
sage: from sage.libs.pari.pari_instance import prec_words_to_dec
322
sage: prec_words_to_dec(5)
323
28 # 32-bit
324
57 # 64-bit
325
sage: [(n, prec_words_to_dec(n)) for n in range(3, 10)]
326
[(3, 9), (4, 19), (5, 28), (6, 38), (7, 48), (8, 57), (9, 67)] # 32-bit
327
[(3, 19), (4, 38), (5, 57), (6, 77), (7, 96), (8, 115), (9, 134)] # 64-bit
328
"""
329
return prec_bits_to_dec(prec_words_to_bits(prec_in_words))
330
331
332
# The unique running Pari instance.
333
cdef PariInstance pari_instance, P
334
pari_instance = PariInstance()
335
P = pari_instance # shorthand notation
336
337
# PariInstance.__init__ must not create gen objects because their parent is not constructed yet
338
pari_catch_sig_on()
339
pari_instance.PARI_ZERO = pari_instance.new_gen_noclear(gen_0)
340
pari_instance.PARI_ONE = pari_instance.new_gen_noclear(gen_1)
341
pari_instance.PARI_TWO = pari_instance.new_gen_noclear(gen_2)
342
pari_catch_sig_off()
343
344
# Also a copy of PARI accessible from external pure python code.
345
pari = pari_instance
346
347
348
cdef unsigned long num_primes
349
350
# Callbacks from PARI to print stuff using sys.stdout.write() instead
351
# of C library functions like puts().
352
cdef PariOUT sage_pariOut
353
354
cdef void sage_putchar(char c):
355
cdef char s[2]
356
s[0] = c
357
s[1] = 0
358
sys.stdout.write(s)
359
# Let PARI think the last character was a newline,
360
# so it doesn't print one when an error occurs.
361
pari_set_last_newline(1)
362
363
cdef void sage_puts(char* s):
364
sys.stdout.write(s)
365
pari_set_last_newline(1)
366
367
cdef void sage_flush():
368
sys.stdout.flush()
369
370
cdef PariOUT sage_pariErr
371
372
cdef void sage_pariErr_putchar(char c):
373
cdef char s[2]
374
s[0] = c
375
s[1] = 0
376
global pari_error_string
377
pari_error_string += str(s)
378
pari_set_last_newline(1)
379
380
cdef void sage_pariErr_puts(char *s):
381
global pari_error_string
382
pari_error_string += str(s)
383
pari_set_last_newline(1)
384
385
cdef void sage_pariErr_flush():
386
pass
387
388
389
@cython.final
390
cdef class PariInstance(sage.structure.parent_base.ParentWithBase):
391
def __init__(self, long size=1000000, unsigned long maxprime=500000):
392
"""
393
Initialize the PARI system.
394
395
INPUT:
396
397
398
- ``size`` -- long, the number of bytes for the initial
399
PARI stack (see note below)
400
401
- ``maxprime`` -- unsigned long, upper limit on a
402
precomputed prime number table (default: 500000)
403
404
405
.. note::
406
407
In Sage, the PARI stack is different than in GP or the
408
PARI C library. In Sage, instead of the PARI stack
409
holding the results of all computations, it *only* holds
410
the results of an individual computation. Each time a new
411
Python/PARI object is computed, it it copied to its own
412
space in the Python heap, and the memory it occupied on the
413
PARI stack is freed. Thus it is not necessary to make the
414
stack very large. Also, unlike in PARI, if the stack does
415
overflow, in most cases the PARI stack is automatically
416
increased and the relevant step of the computation rerun.
417
418
This design obviously involves some performance penalties
419
over the way PARI works, but it scales much better and is
420
far more robust for large projects.
421
422
.. note::
423
424
If you do not want prime numbers, put ``maxprime=2``, but be
425
careful because many PARI functions require this table. If
426
you get the error message "not enough precomputed primes",
427
increase this parameter.
428
"""
429
if bot:
430
return # pari already initialized.
431
432
global num_primes, top, bot
433
434
# The size here doesn't really matter, because we will allocate
435
# our own stack anyway. We ask PARI not to set up signal and
436
# error handlers.
437
pari_init_opts(10000, maxprime, INIT_DFTm)
438
439
_pari_init_error_handling()
440
441
num_primes = maxprime
442
443
# Free the PARI stack and allocate our own (using Cython)
444
pari_free(<void*>bot); bot = 0
445
init_stack(size)
446
447
# Set printing functions
448
global pariOut, pariErr
449
450
pariOut = &sage_pariOut
451
pariOut.putch = sage_putchar
452
pariOut.puts = sage_puts
453
pariOut.flush = sage_flush
454
455
pariErr = &sage_pariErr
456
pariErr.putch = sage_pariErr_putchar
457
pariErr.puts = sage_pariErr_puts
458
pariErr.flush = sage_pariErr_flush
459
460
# Display only 15 digits
461
sd_format("g.15", d_SILENT)
462
463
# Init global prec variable (PARI's precision is always a
464
# multiple of the machine word size)
465
global prec
466
prec = prec_bits_to_words(64)
467
468
# Disable pretty-printing
469
GP_DATA.fmt.prettyp = 0
470
471
# This causes PARI/GP to use output independent of the terminal
472
# (which is want we want for the PARI library interface).
473
GP_DATA.flags = gpd_TEST
474
475
476
def debugstack(self):
477
r"""
478
Print the internal PARI variables ``top`` (top of stack), ``avma``
479
(available memory address, think of this as the stack pointer),
480
``bot`` (bottom of stack).
481
482
EXAMPLE::
483
484
sage: pari.debugstack() # random
485
top = 0x60b2c60
486
avma = 0x5875c38
487
bot = 0x57295e0
488
size = 1000000
489
"""
490
# We deliberately use low-level functions to minimize the
491
# chances that something goes wrong here (for example, if we
492
# are out of memory).
493
global avma, top, bot
494
printf("top = %p\navma = %p\nbot = %p\nsize = %lu\n", top, avma, bot, <unsigned long>(top) - <unsigned long>(bot))
495
fflush(stdout)
496
497
def __dealloc__(self):
498
"""
499
Deallocation of the Pari instance.
500
501
NOTE:
502
503
Usually this deallocation happens only when Sage quits.
504
We do not provide a direct test, since usually there
505
is only one Pari instance, and when artificially creating
506
another instance, C-data are shared.
507
508
The fact that Sage does not crash when quitting is an
509
indirect doctest. See the discussion at :trac:`13741`.
510
511
"""
512
if bot:
513
sage_free(<void*>bot)
514
global top, bot, avma
515
top = 0
516
bot = 0
517
avma = 0
518
pari_close()
519
520
def __repr__(self):
521
return "Interface to the PARI C library"
522
523
def __hash__(self):
524
return 907629390 # hash('pari')
525
526
cdef has_coerce_map_from_c_impl(self, x):
527
return True
528
529
def __richcmp__(left, right, int op):
530
"""
531
EXAMPLES::
532
533
sage: pari == pari
534
True
535
sage: pari == gp
536
False
537
sage: pari == 5
538
False
539
"""
540
return (<Parent>left)._richcmp(right, op)
541
542
def default(self, variable, value=None):
543
if not value is None:
544
return self('default(%s, %s)'%(variable, value))
545
return self('default(%s)'%variable)
546
547
def set_debug_level(self, level):
548
"""
549
Set the debug PARI C library variable.
550
"""
551
self.default('debug', int(level))
552
553
def get_debug_level(self):
554
"""
555
Set the debug PARI C library variable.
556
"""
557
return int(self.default('debug'))
558
559
def set_real_precision(self, long n):
560
"""
561
Sets the PARI default real precision in decimal digits.
562
563
This is used both for creation of new objects from strings and for
564
printing. It is the number of digits *IN DECIMAL* in which real
565
numbers are printed. It also determines the precision of objects
566
created by parsing strings (e.g. pari('1.2')), which is *not* the
567
normal way of creating new pari objects in Sage. It has *no*
568
effect on the precision of computations within the pari library.
569
570
Returns the previous PARI real precision.
571
572
EXAMPLES::
573
574
sage: pari.set_real_precision(60)
575
15
576
sage: pari('1.2')
577
1.20000000000000000000000000000000000000000000000000000000000
578
sage: pari.set_real_precision(15)
579
60
580
"""
581
prev = self.get_real_precision()
582
cdef bytes strn = str(n)
583
pari_catch_sig_on()
584
sd_realprecision(strn, d_SILENT)
585
pari_catch_sig_off()
586
return prev
587
588
def get_real_precision(self):
589
"""
590
Returns the current PARI default real precision.
591
592
This is used both for creation of new objects from strings and for
593
printing. It is the number of digits *IN DECIMAL* in which real
594
numbers are printed. It also determines the precision of objects
595
created by parsing strings (e.g. pari('1.2')), which is *not* the
596
normal way of creating new pari objects in Sage. It has *no*
597
effect on the precision of computations within the pari library.
598
599
EXAMPLES::
600
601
sage: pari.get_real_precision()
602
15
603
"""
604
pari_catch_sig_on()
605
cdef long prev = itos(sd_realprecision(NULL, d_RETURN))
606
pari_catch_sig_off()
607
return prev
608
609
def set_series_precision(self, long n):
610
global precdl
611
precdl = n
612
613
def get_series_precision(self):
614
return precdl
615
616
cdef inline void clear_stack(self):
617
"""
618
Call ``pari_catch_sig_off()``, and clear the entire PARI stack
619
if we are leaving the outermost ``pari_catch_sig_on() ...
620
pari_catch_sig_off()`` block.
621
622
"""
623
global top, avma
624
if _signals.sig_on_count <= 1:
625
avma = top
626
pari_catch_sig_off()
627
628
cdef inline gen new_gen(self, GEN x):
629
"""
630
Create a new gen wrapping `x`, then call ``clear_stack()``.
631
"""
632
cdef gen g = self.new_gen_noclear(x)
633
self.clear_stack()
634
return g
635
636
cdef inline gen new_gen_noclear(self, GEN x):
637
"""
638
Create a new gen, but don't free any memory on the stack and don't
639
call pari_catch_sig_off().
640
"""
641
cdef pari_sp address
642
cdef gen y = PY_NEW(gen)
643
y.g = self.deepcopy_to_python_heap(x, &address)
644
y.b = address
645
y._parent = self
646
# y.refers_to (a dict which is None now) is initialised as needed
647
return y
648
649
cdef gen new_gen_from_mpz_t(self, mpz_t value):
650
"""
651
Create a new gen from a given MPIR-integer ``value``.
652
653
EXAMPLES::
654
655
sage: pari(42) # indirect doctest
656
42
657
658
TESTS:
659
660
Check that the hash of an integer does not depend on existing
661
garbage on the stack (#11611)::
662
663
sage: foo = pari(2^(32*1024)); # Create large integer to put PARI stack in known state
664
sage: a5 = pari(5);
665
sage: foo = pari(0xDEADBEEF * (2^(32*1024)-1)//(2^32 - 1)); # Dirty PARI stack
666
sage: b5 = pari(5);
667
sage: a5.__hash__() == b5.__hash__()
668
True
669
"""
670
pari_catch_sig_on()
671
return self.new_gen(self._new_GEN_from_mpz_t(value))
672
673
cdef inline GEN _new_GEN_from_mpz_t(self, mpz_t value):
674
r"""
675
Create a new PARI ``t_INT`` from a ``mpz_t``.
676
677
For internal use only; this directly uses the PARI stack.
678
One should call ``pari_catch_sig_on()`` before and ``pari_catch_sig_off()`` after.
679
"""
680
cdef unsigned long limbs = mpz_size(value)
681
682
cdef GEN z = cgeti(limbs + 2)
683
# Set sign and "effective length"
684
z[1] = evalsigne(mpz_sgn(value)) + evallgefint(limbs + 2)
685
mpz_export(int_LSW(z), NULL, -1, sizeof(long), 0, 0, value)
686
687
return z
688
689
cdef gen new_gen_from_int(self, int value):
690
pari_catch_sig_on()
691
return self.new_gen(stoi(value))
692
693
cdef gen new_gen_from_mpq_t(self, mpq_t value):
694
"""
695
Create a new gen from a given MPIR-rational ``value``.
696
697
EXAMPLES::
698
699
sage: pari(-2/3)
700
-2/3
701
sage: pari(QQ(42))
702
42
703
sage: pari(QQ(42)).type()
704
't_INT'
705
sage: pari(QQ(1/42)).type()
706
't_FRAC'
707
708
TESTS:
709
710
Check that the hash of a rational does not depend on existing
711
garbage on the stack (#11854)::
712
713
sage: foo = pari(2^(32*1024)); # Create large integer to put PARI stack in known state
714
sage: a5 = pari(5/7);
715
sage: foo = pari(0xDEADBEEF * (2^(32*1024)-1)//(2^32 - 1)); # Dirty PARI stack
716
sage: b5 = pari(5/7);
717
sage: a5.__hash__() == b5.__hash__()
718
True
719
"""
720
pari_catch_sig_on()
721
return self.new_gen(self._new_GEN_from_mpq_t(value))
722
723
cdef inline GEN _new_GEN_from_mpq_t(self, mpq_t value):
724
r"""
725
Create a new PARI ``t_INT`` or ``t_FRAC`` from a ``mpq_t``.
726
727
For internal use only; this directly uses the PARI stack.
728
One should call ``pari_catch_sig_on()`` before and ``pari_catch_sig_off()`` after.
729
"""
730
cdef GEN num = self._new_GEN_from_mpz_t(mpq_numref(value))
731
if mpz_cmpabs_ui(mpq_denref(value), 1) == 0:
732
# Denominator is 1, return the numerator (an integer)
733
return num
734
cdef GEN denom = self._new_GEN_from_mpz_t(mpq_denref(value))
735
return mkfrac(num, denom)
736
737
cdef gen new_t_POL_from_int_star(self, int *vals, int length, long varnum):
738
"""
739
Note that degree + 1 = length, so that recognizing 0 is easier.
740
741
varnum = 0 is the general choice (creates a variable in x).
742
"""
743
cdef GEN z
744
cdef int i
745
746
pari_catch_sig_on()
747
z = cgetg(length + 2, t_POL)
748
z[1] = evalvarn(varnum)
749
if length != 0:
750
setsigne(z,1)
751
for i from 0 <= i < length:
752
set_gel(z,i+2, stoi(vals[i]))
753
else:
754
## polynomial is zero
755
setsigne(z,0)
756
757
return self.new_gen(z)
758
759
cdef gen new_gen_from_padic(self, long ordp, long relprec,
760
mpz_t prime, mpz_t p_pow, mpz_t unit):
761
cdef GEN z
762
pari_catch_sig_on()
763
z = cgetg(5, t_PADIC)
764
z[1] = evalprecp(relprec) + evalvalp(ordp)
765
set_gel(z, 2, self._new_GEN_from_mpz_t(prime))
766
set_gel(z, 3, self._new_GEN_from_mpz_t(p_pow))
767
set_gel(z, 4, self._new_GEN_from_mpz_t(unit))
768
return self.new_gen(z)
769
770
def double_to_gen(self, x):
771
cdef double dx
772
dx = float(x)
773
return self.double_to_gen_c(dx)
774
775
cdef gen double_to_gen_c(self, double x):
776
"""
777
Create a new gen with the value of the double x, using Pari's
778
dbltor.
779
780
EXAMPLES::
781
782
sage: pari.double_to_gen(1)
783
1.00000000000000
784
sage: pari.double_to_gen(1e30)
785
1.00000000000000 E30
786
sage: pari.double_to_gen(0)
787
0.E-15
788
sage: pari.double_to_gen(-sqrt(RDF(2)))
789
-1.41421356237310
790
"""
791
# Pari has an odd concept where it attempts to track the accuracy
792
# of floating-point 0; a floating-point zero might be 0.0e-20
793
# (meaning roughly that it might represent any number in the
794
# range -1e-20 <= x <= 1e20).
795
796
# Pari's dbltor converts a floating-point 0 into the Pari real
797
# 0.0e-307; Pari treats this as an extremely precise 0. This
798
# can cause problems; for instance, the Pari incgam() function can
799
# be very slow if the first argument is very precise.
800
801
# So we translate 0 into a floating-point 0 with 53 bits
802
# of precision (that's the number of mantissa bits in an IEEE
803
# double).
804
805
pari_catch_sig_on()
806
if x == 0:
807
return self.new_gen(real_0_bit(-53))
808
else:
809
return self.new_gen(dbltor(x))
810
811
cdef GEN double_to_GEN(self, double x):
812
if x == 0:
813
return real_0_bit(-53)
814
else:
815
return dbltor(x)
816
817
def complex(self, re, im):
818
"""
819
Create a new complex number, initialized from re and im.
820
"""
821
cdef gen t0 = self(re)
822
cdef gen t1 = self(im)
823
pari_catch_sig_on()
824
return self.new_gen(mkcomplex(t0.g, t1.g))
825
826
cdef GEN deepcopy_to_python_heap(self, GEN x, pari_sp* address):
827
cdef size_t s = <size_t> gsizebyte(x)
828
cdef pari_sp tmp_bot = <pari_sp> sage_malloc(s)
829
cdef pari_sp tmp_top = tmp_bot + s
830
address[0] = tmp_bot
831
return gcopy_avma(x, &tmp_top)
832
833
cdef gen new_ref(self, GEN g, gen parent):
834
"""
835
Create a new gen pointing to the given GEN, which is allocated as a
836
part of parent.g.
837
838
.. note::
839
840
As a rule, there should never be more than one sage gen
841
pointing to a given Pari GEN. So that means there is only
842
one case where this function should be used: when a
843
complicated Pari GEN is allocated with a single gen
844
pointing to it, and one needs a gen pointing to one of its
845
components.
846
847
For example, doing x = pari("[1,2]") allocates a gen pointing to
848
the list [1,2], but x[0] has no gen wrapping it, so new_ref
849
should be used there. Then parent would be x in this
850
case. See __getitem__ for an example of usage.
851
852
EXAMPLES::
853
854
sage: pari("[[1,2],3]")[0][1] ## indirect doctest
855
2
856
"""
857
cdef gen p = PY_NEW(gen)
858
p.g = g
859
p.b = 0
860
p._parent = self
861
p.refers_to = {-1: parent}
862
return p
863
864
def __call__(self, s):
865
"""
866
Create the PARI object obtained by evaluating s using PARI.
867
868
EXAMPLES::
869
870
sage: pari([2,3,5])
871
[2, 3, 5]
872
sage: pari(Matrix(2,2,range(4)))
873
[0, 1; 2, 3]
874
sage: pari(x^2-3)
875
x^2 - 3
876
877
::
878
879
sage: a = pari(1); a, a.type()
880
(1, 't_INT')
881
sage: a = pari(1/2); a, a.type()
882
(1/2, 't_FRAC')
883
sage: a = pari(1/2); a, a.type()
884
(1/2, 't_FRAC')
885
886
See :func:`pari` for more examples.
887
"""
888
return objtogen(s)
889
890
cdef GEN _new_GEN_from_mpz_t_matrix(self, mpz_t** B, Py_ssize_t nr, Py_ssize_t nc):
891
r"""
892
Create a new PARI ``t_MAT`` with ``nr`` rows and ``nc`` columns
893
from a ``mpz_t**``.
894
895
For internal use only; this directly uses the PARI stack.
896
One should call ``pari_catch_sig_on()`` before and ``pari_catch_sig_off()`` after.
897
"""
898
cdef GEN x
899
cdef GEN A = zeromatcopy(nr, nc)
900
cdef Py_ssize_t i, j
901
for i in range(nr):
902
for j in range(nc):
903
x = self._new_GEN_from_mpz_t(B[i][j])
904
set_gcoeff(A, i+1, j+1, x) # A[i+1, j+1] = x (using 1-based indexing)
905
return A
906
907
cdef GEN _new_GEN_from_mpz_t_matrix_rotate90(self, mpz_t** B, Py_ssize_t nr, Py_ssize_t nc):
908
r"""
909
Create a new PARI ``t_MAT`` with ``nr`` rows and ``nc`` columns
910
from a ``mpz_t**`` and rotate the matrix 90 degrees
911
counterclockwise. So the resulting matrix will have ``nc`` rows
912
and ``nr`` columns. This is useful for computing the Hermite
913
Normal Form because Sage and PARI use different definitions.
914
915
For internal use only; this directly uses the PARI stack.
916
One should call ``pari_catch_sig_on()`` before and ``pari_catch_sig_off()`` after.
917
"""
918
cdef GEN x
919
cdef GEN A = zeromatcopy(nc, nr)
920
cdef Py_ssize_t i, j
921
for i in range(nr):
922
for j in range(nc):
923
x = self._new_GEN_from_mpz_t(B[i][nc-j-1])
924
set_gcoeff(A, j+1, i+1, x) # A[j+1, i+1] = x (using 1-based indexing)
925
return A
926
927
cdef gen integer_matrix(self, mpz_t** B, Py_ssize_t nr, Py_ssize_t nc, bint permute_for_hnf):
928
"""
929
EXAMPLES::
930
931
sage: matrix(ZZ,2,[1..6])._pari_() # indirect doctest
932
[1, 2, 3; 4, 5, 6]
933
"""
934
pari_catch_sig_on()
935
cdef GEN g
936
if permute_for_hnf:
937
g = self._new_GEN_from_mpz_t_matrix_rotate90(B, nr, nc)
938
else:
939
g = self._new_GEN_from_mpz_t_matrix(B, nr, nc)
940
return self.new_gen(g)
941
942
cdef GEN _new_GEN_from_mpq_t_matrix(self, mpq_t** B, Py_ssize_t nr, Py_ssize_t nc):
943
cdef GEN x
944
# Allocate zero matrix
945
cdef GEN A = zeromatcopy(nr, nc)
946
cdef Py_ssize_t i, j
947
for i in range(nr):
948
for j in range(nc):
949
x = self._new_GEN_from_mpq_t(B[i][j])
950
set_gcoeff(A, i+1, j+1, x) # A[i+1, j+1] = x (using 1-based indexing)
951
return A
952
953
cdef gen rational_matrix(self, mpq_t** B, Py_ssize_t nr, Py_ssize_t nc):
954
"""
955
EXAMPLES::
956
957
sage: matrix(QQ,2,[1..6])._pari_() # indirect doctest
958
[1, 2, 3; 4, 5, 6]
959
"""
960
pari_catch_sig_on()
961
cdef GEN g = self._new_GEN_from_mpq_t_matrix(B, nr, nc)
962
return self.new_gen(g)
963
964
cdef _coerce_c_impl(self, x):
965
"""
966
Implicit canonical coercion into a PARI object.
967
"""
968
try:
969
return self(x)
970
except (TypeError, AttributeError):
971
raise TypeError("no canonical coercion of %s into PARI"%x)
972
973
cdef _an_element_c_impl(self): # override this in Cython
974
return self.PARI_ZERO
975
976
def new_with_bits_prec(self, s, long precision):
977
r"""
978
pari.new_with_bits_prec(self, s, precision) creates s as a PARI
979
gen with (at most) precision *bits* of precision.
980
"""
981
cdef unsigned long old_prec
982
old_prec = GP_DATA.fmt.sigd
983
precision = prec_bits_to_dec(precision)
984
if not precision:
985
precision = old_prec
986
self.set_real_precision(precision)
987
x = self(s)
988
self.set_real_precision(old_prec)
989
return x
990
991
992
993
cdef long get_var(self, v):
994
"""
995
Converts a Python string into a PARI variable reference number. Or
996
if v = -1, returns -1.
997
"""
998
if v != -1:
999
s = str(v)
1000
return fetch_user_var(s)
1001
return -1
1002
1003
############################################################
1004
# Initialization
1005
############################################################
1006
1007
def stacksize(self):
1008
r"""
1009
Returns the current size of the PARI stack, which is `10^6`
1010
by default. However, the stack size is automatically doubled
1011
when needed. It can also be set directly using
1012
``pari.allocatemem()``.
1013
1014
EXAMPLES::
1015
1016
sage: pari.stacksize()
1017
1000000
1018
1019
"""
1020
global top, bot
1021
return (<size_t>(top) - <size_t>(bot))
1022
1023
def _allocate_huge_mem(self):
1024
r"""
1025
This function tries to allocate an impossibly large amount of
1026
PARI stack in order to test ``init_stack()`` failing.
1027
1028
TESTS::
1029
1030
sage: pari.allocatemem(10^6, silent=True)
1031
sage: pari._allocate_huge_mem()
1032
Traceback (most recent call last):
1033
...
1034
MemoryError: Unable to allocate ... (instead, allocated 1000000 bytes)
1035
1036
Test that the PARI stack is sane after this failure::
1037
1038
sage: a = pari('2^10000000')
1039
sage: pari.allocatemem(10^6, silent=True)
1040
"""
1041
# Since size_t is unsigned, this should wrap over to a very
1042
# large positive number.
1043
init_stack(<size_t>(-4096))
1044
1045
def _setup_failed_retry(self):
1046
r"""
1047
This function pretends that the PARI stack is larger than it
1048
actually is such that allocatemem(0) will allocate much more
1049
than double the current stack. That allocation will then fail.
1050
This function is meant to be used only in this doctest.
1051
1052
TESTS::
1053
1054
sage: pari.allocatemem(4096, silent=True)
1055
sage: pari._setup_failed_retry()
1056
sage: try: # Any result is fine as long as it's not a segfault
1057
....: a = pari('2^1000000')
1058
....: except MemoryError:
1059
....: pass
1060
sage: pari.allocatemem(10^6, silent=True)
1061
"""
1062
global top
1063
# Pretend top is at a very high address
1064
top = <pari_sp>(<size_t>(-16))
1065
1066
def allocatemem(self, s=0, silent=False):
1067
r"""
1068
Change the PARI stack space to the given size (or double the
1069
current size if ``s`` is `0`).
1070
1071
If `s = 0` and insufficient memory is avaible to double, the
1072
PARI stack will be enlarged by a smaller amount. In any case,
1073
a ``MemoryError`` will be raised if the requested memory cannot
1074
be allocated.
1075
1076
The PARI stack is never automatically shrunk. You can use the
1077
command ``pari.allocatemem(10^6)`` to reset the size to `10^6`,
1078
which is the default size at startup. Note that the results of
1079
computations using Sage's PARI interface are copied to the
1080
Python heap, so they take up no space in the PARI stack.
1081
The PARI stack is cleared after every computation.
1082
1083
It does no real harm to set this to a small value as the PARI
1084
stack will be automatically doubled when we run out of memory.
1085
However, it could make some calculations slower (since they have
1086
to be redone from the start after doubling the stack until the
1087
stack is big enough).
1088
1089
INPUT:
1090
1091
- ``s`` - an integer (default: 0). A non-zero argument should
1092
be the size in bytes of the new PARI stack. If `s` is zero,
1093
try to double the current stack size.
1094
1095
EXAMPLES::
1096
1097
sage: pari.allocatemem(10^7)
1098
PARI stack size set to 10000000 bytes
1099
sage: pari.allocatemem() # Double the current size
1100
PARI stack size set to 20000000 bytes
1101
sage: pari.stacksize()
1102
20000000
1103
sage: pari.allocatemem(10^6)
1104
PARI stack size set to 1000000 bytes
1105
1106
The following computation will automatically increase the PARI
1107
stack size::
1108
1109
sage: a = pari('2^100000000')
1110
1111
``a`` is now a Python variable on the Python heap and does not
1112
take up any space on the PARI stack. The PARI stack is still
1113
large because of the computation of ``a``::
1114
1115
sage: pari.stacksize()
1116
16000000
1117
sage: pari.allocatemem(10^6)
1118
PARI stack size set to 1000000 bytes
1119
sage: pari.stacksize()
1120
1000000
1121
1122
TESTS:
1123
1124
Do the same without using the string interface and starting
1125
from a very small stack size::
1126
1127
sage: pari.allocatemem(1)
1128
PARI stack size set to 1024 bytes
1129
sage: a = pari(2)^100000000
1130
sage: pari.stacksize()
1131
16777216
1132
"""
1133
s = long(s)
1134
if s < 0:
1135
raise ValueError("Stack size must be nonnegative")
1136
init_stack(s)
1137
if not silent:
1138
print "PARI stack size set to", self.stacksize(), "bytes"
1139
1140
def pari_version(self):
1141
return str(PARIVERSION)
1142
1143
def init_primes(self, _M):
1144
"""
1145
Recompute the primes table including at least all primes up to M
1146
(but possibly more).
1147
1148
EXAMPLES::
1149
1150
sage: pari.init_primes(200000)
1151
1152
We make sure that ticket #11741 has been fixed, and double check to
1153
make sure that diffptr has not been freed::
1154
1155
sage: pari.init_primes(2^62)
1156
Traceback (most recent call last):
1157
...
1158
PariError: not enough memory # 64-bit
1159
OverflowError: long int too large to convert # 32-bit
1160
sage: pari.init_primes(200000)
1161
"""
1162
cdef unsigned long M
1163
cdef char *tmpptr
1164
M = _M
1165
global diffptr, num_primes
1166
if M <= num_primes:
1167
return
1168
pari_catch_sig_on()
1169
tmpptr = initprimes(M)
1170
pari_catch_sig_off()
1171
pari_free(<void*> diffptr)
1172
num_primes = M
1173
diffptr = tmpptr
1174
1175
1176
##############################################
1177
## Support for GP Scripts
1178
##############################################
1179
1180
def read(self, bytes filename):
1181
r"""
1182
Read a script from the named filename into the interpreter. The
1183
functions defined in the script are then available for use from
1184
Sage/PARI. The result of the last command in ``filename`` is
1185
returned.
1186
1187
EXAMPLES:
1188
1189
Create a gp file::
1190
1191
sage: import tempfile
1192
sage: gpfile = tempfile.NamedTemporaryFile(mode="w")
1193
sage: gpfile.file.write("mysquare(n) = {\n")
1194
sage: gpfile.file.write(" n^2;\n")
1195
sage: gpfile.file.write("}\n")
1196
sage: gpfile.file.write("polcyclo(5)\n")
1197
sage: gpfile.file.flush()
1198
1199
Read it in Sage, we get the result of the last line::
1200
1201
sage: pari.read(gpfile.name)
1202
x^4 + x^3 + x^2 + x + 1
1203
1204
Call the function defined in the gp file::
1205
1206
sage: pari('mysquare(12)')
1207
144
1208
"""
1209
pari_catch_sig_on()
1210
return self.new_gen(gp_read_file(filename))
1211
1212
1213
##############################################
1214
1215
def _primelimit(self):
1216
"""
1217
Return the number of primes already computed
1218
in this Pari instance.
1219
1220
EXAMPLES:
1221
sage: pari._primelimit()
1222
500000
1223
sage: pari.init_primes(600000)
1224
sage: pari._primelimit()
1225
600000
1226
"""
1227
global num_primes
1228
from sage.rings.all import ZZ
1229
return ZZ(num_primes)
1230
1231
def prime_list(self, long n):
1232
"""
1233
prime_list(n): returns list of the first n primes
1234
1235
To extend the table of primes use pari.init_primes(M).
1236
1237
INPUT:
1238
1239
1240
- ``n`` - C long
1241
1242
1243
OUTPUT:
1244
1245
1246
- ``gen`` - PARI list of first n primes
1247
1248
1249
EXAMPLES::
1250
1251
sage: pari.prime_list(0)
1252
[]
1253
sage: pari.prime_list(-1)
1254
[]
1255
sage: pari.prime_list(3)
1256
[2, 3, 5]
1257
sage: pari.prime_list(10)
1258
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
1259
sage: pari.prime_list(20)
1260
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
1261
sage: len(pari.prime_list(1000))
1262
1000
1263
"""
1264
if n >= 2:
1265
self.nth_prime(n)
1266
pari_catch_sig_on()
1267
return self.new_gen(primes(n))
1268
1269
def primes_up_to_n(self, long n):
1270
"""
1271
Return the primes <= n as a pari list.
1272
1273
EXAMPLES::
1274
1275
sage: pari.primes_up_to_n(1)
1276
[]
1277
sage: pari.primes_up_to_n(20)
1278
[2, 3, 5, 7, 11, 13, 17, 19]
1279
"""
1280
if n <= 1:
1281
return pari([])
1282
self.init_primes(n+1)
1283
return self.prime_list(pari(n).primepi())
1284
1285
## cdef long k
1286
## k = (n+10)/math.log(n)
1287
## p = 2
1288
## while p <= n:
1289
## p = self.nth_prime(k)
1290
## k = 2
1291
## v = self.prime_list(k)
1292
## return v[:pari(n).primepi()]
1293
1294
def __nth_prime(self, long n):
1295
"""
1296
nth_prime(n): returns the n-th prime, where n is a C-int
1297
"""
1298
global num_primes
1299
1300
if n <= 0:
1301
raise ValueError, "nth prime meaningless for non-positive n (=%s)"%n
1302
cdef GEN g
1303
pari_catch_sig_on()
1304
g = prime(n)
1305
return self.new_gen(g)
1306
1307
1308
def nth_prime(self, long n):
1309
from sage.libs.pari.all import PariError
1310
try:
1311
return self.__nth_prime(n)
1312
except PariError:
1313
self.init_primes(max(2*num_primes,20*n))
1314
return self.nth_prime(n)
1315
1316
def euler(self, unsigned long precision=0):
1317
"""
1318
Return Euler's constant to the requested real precision (in bits).
1319
1320
EXAMPLES::
1321
1322
sage: pari.euler()
1323
0.577215664901533
1324
sage: pari.euler(precision=100).python()
1325
0.577215664901532860606512090082...
1326
"""
1327
pari_catch_sig_on()
1328
return self.new_gen(mpeuler(prec_bits_to_words(precision)))
1329
1330
def pi(self, unsigned long precision=0):
1331
"""
1332
Return the value of the constant pi to the requested real precision
1333
(in bits).
1334
1335
EXAMPLES::
1336
1337
sage: pari.pi()
1338
3.14159265358979
1339
sage: pari.pi(precision=100).python()
1340
3.1415926535897932384626433832...
1341
"""
1342
pari_catch_sig_on()
1343
return self.new_gen(mppi(prec_bits_to_words(precision)))
1344
1345
def pollegendre(self, long n, v=-1):
1346
"""
1347
pollegendre(n, v=x): Legendre polynomial of degree n (n C-integer),
1348
in variable v.
1349
1350
EXAMPLES::
1351
1352
sage: pari.pollegendre(7)
1353
429/16*x^7 - 693/16*x^5 + 315/16*x^3 - 35/16*x
1354
sage: pari.pollegendre(7, 'z')
1355
429/16*z^7 - 693/16*z^5 + 315/16*z^3 - 35/16*z
1356
sage: pari.pollegendre(0)
1357
1
1358
"""
1359
pari_catch_sig_on()
1360
return self.new_gen(pollegendre(n, self.get_var(v)))
1361
1362
def poltchebi(self, long n, v=-1):
1363
"""
1364
poltchebi(n, v=x): Chebyshev polynomial of the first kind of degree
1365
n, in variable v.
1366
1367
EXAMPLES::
1368
1369
sage: pari.poltchebi(7)
1370
64*x^7 - 112*x^5 + 56*x^3 - 7*x
1371
sage: pari.poltchebi(7, 'z')
1372
64*z^7 - 112*z^5 + 56*z^3 - 7*z
1373
sage: pari.poltchebi(0)
1374
1
1375
"""
1376
pari_catch_sig_on()
1377
return self.new_gen(polchebyshev1(n, self.get_var(v)))
1378
1379
def factorial(self, long n):
1380
"""
1381
Return the factorial of the integer n as a PARI gen.
1382
1383
EXAMPLES::
1384
1385
sage: pari.factorial(0)
1386
1
1387
sage: pari.factorial(1)
1388
1
1389
sage: pari.factorial(5)
1390
120
1391
sage: pari.factorial(25)
1392
15511210043330985984000000
1393
"""
1394
pari_catch_sig_on()
1395
return self.new_gen(mpfact(n))
1396
1397
def polcyclo(self, long n, v=-1):
1398
"""
1399
polcyclo(n, v=x): cyclotomic polynomial of degree n, in variable
1400
v.
1401
1402
EXAMPLES::
1403
1404
sage: pari.polcyclo(8)
1405
x^4 + 1
1406
sage: pari.polcyclo(7, 'z')
1407
z^6 + z^5 + z^4 + z^3 + z^2 + z + 1
1408
sage: pari.polcyclo(1)
1409
x - 1
1410
"""
1411
pari_catch_sig_on()
1412
return self.new_gen(polcyclo(n, self.get_var(v)))
1413
1414
def polcyclo_eval(self, long n, v):
1415
"""
1416
polcyclo_eval(n, v): value of the nth cyclotomic polynomial at value v.
1417
1418
EXAMPLES::
1419
1420
sage: pari.polcyclo_eval(8, 2)
1421
17
1422
sage: cyclotomic_polynomial(8)(2)
1423
17
1424
"""
1425
cdef gen t0 = self(v)
1426
pari_catch_sig_on()
1427
return self.new_gen(polcyclo_eval(n, t0.g))
1428
1429
def polsubcyclo(self, long n, long d, v=-1):
1430
"""
1431
polsubcyclo(n, d, v=x): return the pari list of polynomial(s)
1432
defining the sub-abelian extensions of degree `d` of the
1433
cyclotomic field `\QQ(\zeta_n)`, where `d`
1434
divides `\phi(n)`.
1435
1436
EXAMPLES::
1437
1438
sage: pari.polsubcyclo(8, 4)
1439
[x^4 + 1]
1440
sage: pari.polsubcyclo(8, 2, 'z')
1441
[z^2 - 2, z^2 + 1, z^2 + 2]
1442
sage: pari.polsubcyclo(8, 1)
1443
[x - 1]
1444
sage: pari.polsubcyclo(8, 3)
1445
[]
1446
"""
1447
cdef gen plist
1448
pari_catch_sig_on()
1449
plist = self.new_gen(polsubcyclo(n, d, self.get_var(v)))
1450
if typ(plist.g) != t_VEC:
1451
return pari.vector(1, [plist])
1452
else:
1453
return plist
1454
#return self.new_gen(polsubcyclo(n, d, self.get_var(v)))
1455
1456
def polzagier(self, long n, long m):
1457
pari_catch_sig_on()
1458
return self.new_gen(polzag(n, m))
1459
1460
def setrand(self, seed):
1461
"""
1462
Sets PARI's current random number seed.
1463
1464
INPUT:
1465
1466
- ``seed`` -- either a strictly positive integer or a GEN of
1467
type ``t_VECSMALL`` as output by ``getrand()``
1468
1469
This should not be called directly; instead, use Sage's global
1470
random number seed handling in ``sage.misc.randstate``
1471
and call ``current_randstate().set_seed_pari()``.
1472
1473
EXAMPLES::
1474
1475
sage: pari.setrand(50)
1476
sage: a = pari.getrand(); a
1477
Vecsmall([...])
1478
sage: pari.setrand(a)
1479
sage: a == pari.getrand()
1480
True
1481
1482
TESTS:
1483
1484
Check that invalid inputs are handled properly (#11825)::
1485
1486
sage: pari.setrand(0)
1487
Traceback (most recent call last):
1488
...
1489
PariError: incorrect type in setrand
1490
sage: pari.setrand("foobar")
1491
Traceback (most recent call last):
1492
...
1493
PariError: incorrect type in setrand
1494
"""
1495
cdef gen t0 = self(seed)
1496
pari_catch_sig_on()
1497
setrand(t0.g)
1498
pari_catch_sig_off()
1499
1500
def getrand(self):
1501
"""
1502
Returns PARI's current random number seed.
1503
1504
OUTPUT:
1505
1506
GEN of type t_VECSMALL
1507
1508
EXAMPLES::
1509
1510
sage: pari.setrand(50)
1511
sage: a = pari.getrand(); a
1512
Vecsmall([...])
1513
sage: pari.setrand(a)
1514
sage: a == pari.getrand()
1515
True
1516
"""
1517
pari_catch_sig_on()
1518
return self.new_gen(getrand())
1519
1520
def vector(self, long n, entries=None):
1521
"""
1522
vector(long n, entries=None): Create and return the length n PARI
1523
vector with given list of entries.
1524
1525
EXAMPLES::
1526
1527
sage: pari.vector(5, [1, 2, 5, 4, 3])
1528
[1, 2, 5, 4, 3]
1529
sage: pari.vector(2, [x, 1])
1530
[x, 1]
1531
sage: pari.vector(2, [x, 1, 5])
1532
Traceback (most recent call last):
1533
...
1534
IndexError: length of entries (=3) must equal n (=2)
1535
"""
1536
cdef gen v = self._empty_vector(n)
1537
if entries is not None:
1538
if len(entries) != n:
1539
raise IndexError, "length of entries (=%s) must equal n (=%s)"%\
1540
(len(entries), n)
1541
for i, x in enumerate(entries):
1542
v[i] = x
1543
return v
1544
1545
cdef gen _empty_vector(self, long n):
1546
cdef gen v
1547
pari_catch_sig_on()
1548
v = self.new_gen(zerovec(n))
1549
return v
1550
1551
def matrix(self, long m, long n, entries=None):
1552
"""
1553
matrix(long m, long n, entries=None): Create and return the m x n
1554
PARI matrix with given list of entries.
1555
"""
1556
cdef long i, j, k
1557
cdef gen A
1558
cdef gen x
1559
1560
pari_catch_sig_on()
1561
A = self.new_gen(zeromatcopy(m,n))
1562
if entries is not None:
1563
if len(entries) != m*n:
1564
raise IndexError, "len of entries (=%s) must be %s*%s=%s"%(len(entries),m,n,m*n)
1565
k = 0
1566
A.refers_to = {}
1567
for i from 0 <= i < m:
1568
for j from 0 <= j < n:
1569
x = pari(entries[k])
1570
A.refers_to[(i,j)] = x
1571
(<GEN>(A.g)[j+1])[i+1] = <long>(x.g)
1572
k = k + 1
1573
return A
1574
1575
1576
cdef int init_stack(size_t requested_size) except -1:
1577
r"""
1578
Low-level Cython function to allocate the PARI stack. This
1579
function should not be called directly, use ``pari.allocatemem()``
1580
instead.
1581
"""
1582
global top, bot, avma
1583
1584
cdef size_t old_size = <size_t>(top) - <size_t>(bot)
1585
1586
cdef size_t new_size
1587
cdef size_t max_size = <size_t>(-1)
1588
if (requested_size == 0):
1589
if old_size < max_size/2:
1590
# Double the stack
1591
new_size = 2*old_size
1592
elif old_size < 4*(max_size/5):
1593
# We cannot possibly double since we already use over half
1594
# the addressable memory: take the average of current and
1595
# maximum size
1596
new_size = max_size/2 + old_size/2
1597
else:
1598
# We already use 80% of the addressable memory => give up
1599
raise MemoryError("Unable to enlarge PARI stack (instead, kept the stack at %s bytes)"%(old_size))
1600
else:
1601
new_size = requested_size
1602
1603
# Align size to 16 bytes and take 1024 bytes as a minimum
1604
new_size = (new_size/16)*16
1605
if (new_size < 1024):
1606
new_size = 1024
1607
1608
# Disable interrupts
1609
sig_on()
1610
sig_block()
1611
1612
# If this is non-zero, the size we failed to allocate
1613
cdef size_t failed_size = 0
1614
1615
try:
1616
# Free the current stack
1617
if bot:
1618
libc.stdlib.free(<void*>bot)
1619
1620
# Allocate memory for new stack.
1621
bot = <pari_sp> libc.stdlib.malloc(new_size)
1622
1623
# If doubling failed, instead add 25% to the current stack size.
1624
# We already checked that we use less than 80% of the maximum value
1625
# for s, so this will not overflow.
1626
if (bot == 0) and (requested_size == 0):
1627
new_size = (old_size/64)*80
1628
bot = <pari_sp> libc.stdlib.malloc(new_size)
1629
1630
if not bot:
1631
failed_size = new_size
1632
# We lost our PARI stack and are not able to allocate the
1633
# requested size. If we just raise an exception now, we end up
1634
# *without* a PARI stack which is not good. We will raise an
1635
# exception later, after allocating *some* PARI stack.
1636
new_size = old_size
1637
while new_size >= 1024: # hope this never fails!
1638
bot = <pari_sp> libc.stdlib.malloc(new_size)
1639
if bot: break
1640
new_size = (new_size/32)*16
1641
1642
if not bot:
1643
top = 0
1644
avma = 0
1645
raise SystemError("Unable to allocate PARI stack, all subsequent PARI computations will crash")
1646
1647
top = bot + new_size
1648
avma = top
1649
1650
if failed_size:
1651
raise MemoryError("Unable to allocate %s bytes for the PARI stack (instead, allocated %s bytes)"%(failed_size, new_size))
1652
1653
return 0
1654
finally:
1655
sig_unblock()
1656
sig_off()
1657
1658