Path: blob/master/src/sage/libs/pari/pari_instance.pyx
8871 views
"""1PARI C-library interface23AUTHORS:45- William Stein (2006-03-01): updated to work with PARI 2.2.12-beta67- William Stein (2006-03-06): added newtonpoly89- Justin Walker: contributed some of the function definitions1011- Gonzalo Tornaria: improvements to conversions; much better error12handling.1314- Robert Bradshaw, Jeroen Demeyer, William Stein (2010-08-15):15Upgrade to PARI 2.4.3 (#9343)1617- Jeroen Demeyer (2011-11-12): rewrite various conversion routines18(#11611, #11854, #11952)1920- Peter Bruin (2013-11-17): split off this file from gen.pyx (#15185)212223EXAMPLES::2425sage: pari('5! + 10/x')26(120*x + 10)/x27sage: pari('intnum(x=0,13,sin(x)+sin(x^2) + x)')2885.188568195152729sage: f = pari('x^3-1')30sage: v = f.factor(); v31[x - 1, 1; x^2 + x + 1, 1]32sage: v[0] # indexing is 0-based unlike in GP.33[x - 1, x^2 + x + 1]~34sage: v[1]35[1, 1]~3637Arithmetic obeys the usual coercion rules::3839sage: type(pari(1) + 1)40<type 'sage.libs.pari.gen.gen'>41sage: type(1 + pari(1))42<type 'sage.libs.pari.gen.gen'>4344GUIDE TO REAL PRECISION AND THE PARI LIBRARY4546The default real precision in communicating with the Pari library47is the same as the default Sage real precision, which is 53 bits.48Inexact Pari objects are therefore printed by default to 15 decimal49digits (even if they are actually more precise).5051Default precision example (53 bits, 15 significant decimals)::5253sage: a = pari(1.23); a541.2300000000000055sage: a.sin()560.9424888019316985758Example with custom precision of 200 bits (60 significant59decimals)::6061sage: R = RealField(200)62sage: a = pari(R(1.23)); a # only 15 significant digits printed631.2300000000000064sage: R(a) # but the number is known to precision of 200 bits651.230000000000000000000000000000000000000000000000000000000066sage: a.sin() # only 15 significant digits printed670.94248880193169868sage: R(a.sin()) # but the number is known to precision of 200 bits690.942488801931697510023823565389244541461287405627650302135047071It is possible to change the number of printed decimals::7273sage: R = RealField(200) # 200 bits of precision in computations74sage: old_prec = pari.set_real_precision(60) # 60 decimals printed75sage: a = pari(R(1.23)); a761.2300000000000000000000000000000000000000000000000000000000077sage: a.sin()780.94248880193169751002382356538924454146128740562765030213503879sage: pari.set_real_precision(old_prec) # restore the default printing behavior80608182Unless otherwise indicated in the docstring, most Pari functions83that return inexact objects use the precision of their arguments to84decide the precision of the computation. However, if some of these85arguments happen to be exact numbers (integers, rationals, etc.),86an optional parameter indicates the precision (in bits) to which87these arguments should be converted before the computation. If this88precision parameter is missing, the default precision of 53 bits is89used. The following first converts 2 into a real with 53-bit90precision::9192sage: R = RealField()93sage: R(pari(2).sin())940.9092974268256829596We can ask for a better precision using the optional parameter::9798sage: R = RealField(150)99sage: R(pari(2).sin(precision=150))1000.90929742682568169539601986591174484270225497101102Warning regarding conversions Sage - Pari - Sage: Some care must be103taken when juggling inexact types back and forth between Sage and104Pari. In theory, calling p=pari(s) creates a Pari object p with the105same precision as s; in practice, the Pari library's precision is106word-based, so it will go up to the next word. For example, a107default 53-bit Sage real s will be bumped up to 64 bits by adding108bogus 11 bits. The function p.python() returns a Sage object with109exactly the same precision as the Pari object p. So110pari(s).python() is definitely not equal to s, since it has 64 bits111of precision, including the bogus 11 bits. The correct way of112avoiding this is to coerce pari(s).python() back into a domain with113the right precision. This has to be done by the user (or by Sage114functions that use Pari library functions in gen.pyx). For115instance, if we want to use the Pari library to compute sqrt(pi)116with a precision of 100 bits::117118sage: R = RealField(100)119sage: s = R(pi); s1203.1415926535897932384626433833121sage: p = pari(s).sqrt()122sage: x = p.python(); x # wow, more digits than I expected!1231.7724538509055160272981674833410973484124sage: x.prec() # has precision 'improved' from 100 to 128?125128126sage: x == RealField(128)(pi).sqrt() # sadly, no!127False128sage: R(x) # x should be brought back to precision 1001291.7724538509055160272981674833130sage: R(x) == s.sqrt()131True132133Elliptic curves and precision: If you are working with elliptic134curves and want to compute with a precision other than the default13553 bits, you should use the precision parameter of ellinit()::136137sage: R = RealField(150)138sage: e = pari([0,0,0,-82,0]).ellinit(precision=150)139sage: eta1 = e.elleta()[0]140sage: R(eta1)1413.6054636014326520859158205642077267748102690142143Number fields and precision: TODO144145TESTS:146147Check that output from PARI's print command is actually seen by148Sage (ticket #9636)::149150sage: pari('print("test")')151test152153"""154155include 'pari_err.pxi'156include 'sage/ext/stdsage.pxi'157include 'sage/ext/interrupt.pxi'158159import sys160161cimport libc.stdlib162cimport cython163164from sage.structure.parent cimport Parent165166from sage.libs.pari.gen cimport gen, objtogen167from sage.libs.pari.handle_error cimport pari_error_string, \168_pari_init_error_handling, _pari_check_warning, \169_pari_handle_exception, _pari_err_recover170171# so Galois groups are represented in a sane way172# See the polgalois section of the PARI users manual.173new_galois_format = 1174175# real precision in decimal digits: see documentation for176# get_real_precision() and set_real_precision(). This variable is used177# in gp to set the precision of input quantities (e.g. sqrt(2)), and for178# determining the number of digits to be printed. It is *not* used as179# a "default precision" for internal computations, which always use180# the actual precision of arguments together (where relevant) with a181# "prec" parameter. In ALL cases (for real computations) the prec182# parameter is a WORD precision and NOT decimal precision. Pari reals183# with word precision w have bit precision (of the mantissa) equal to184# 32*(w-2) or 64*(w-2).185#186# Hence the only relevance of this parameter in Sage is (1) for the187# output format of components of objects of type188# 'sage.libs.pari.gen.gen'; (2) for setting the precision of pari189# variables created from strings (e.g. via sage: pari('1.2')).190#191# WARNING: Many pari library functions take a last parameter "prec"192# which should be a words precision. In many cases this is redundant193# and is simply ignored. In our wrapping of these functions we use194# the variable prec here for convenience only.195cdef long prec196197#################################################################198# conversions between various real precision models199#################################################################200201def prec_bits_to_dec(unsigned long prec_in_bits):202r"""203Convert from precision expressed in bits to precision expressed in204decimal.205206EXAMPLES::207208sage: from sage.libs.pari.pari_instance import prec_bits_to_dec209sage: prec_bits_to_dec(53)21015211sage: [(32*n, prec_bits_to_dec(32*n)) for n in range(1, 9)]212[(32, 9),213(64, 19),214(96, 28),215(128, 38),216(160, 48),217(192, 57),218(224, 67),219(256, 77)]220"""221cdef double log_2 = 0.301029995663981222return int(prec_in_bits*log_2)223224def prec_dec_to_bits(unsigned long prec_in_dec):225r"""226Convert from precision expressed in decimal to precision expressed227in bits.228229EXAMPLES::230231sage: from sage.libs.pari.pari_instance import prec_dec_to_bits232sage: prec_dec_to_bits(15)23349234sage: [(n, prec_dec_to_bits(n)) for n in range(10, 100, 10)]235[(10, 33),236(20, 66),237(30, 99),238(40, 132),239(50, 166),240(60, 199),241(70, 232),242(80, 265),243(90, 298)]244"""245cdef double log_10 = 3.32192809488736246return int(prec_in_dec*log_10)247248cpdef long prec_bits_to_words(unsigned long prec_in_bits):249r"""250Convert from precision expressed in bits to pari real precision251expressed in words. Note: this rounds up to the nearest word,252adjusts for the two codewords of a pari real, and is253architecture-dependent.254255EXAMPLES::256257sage: from sage.libs.pari.pari_instance import prec_bits_to_words258sage: prec_bits_to_words(70)2595 # 32-bit2604 # 64-bit261262::263264sage: [(32*n, prec_bits_to_words(32*n)) for n in range(1, 9)]265[(32, 3), (64, 4), (96, 5), (128, 6), (160, 7), (192, 8), (224, 9), (256, 10)] # 32-bit266[(32, 3), (64, 3), (96, 4), (128, 4), (160, 5), (192, 5), (224, 6), (256, 6)] # 64-bit267"""268if not prec_in_bits:269return prec270cdef unsigned long wordsize = BITS_IN_LONG271272# This equals ceil(prec_in_bits/wordsize) + 2273return (prec_in_bits - 1)//wordsize + 3274275def prec_words_to_bits(long prec_in_words):276r"""277Convert from pari real precision expressed in words to precision278expressed in bits. Note: this adjusts for the two codewords of a279pari real, and is architecture-dependent.280281EXAMPLES::282283sage: from sage.libs.pari.pari_instance import prec_words_to_bits284sage: prec_words_to_bits(10)285256 # 32-bit286512 # 64-bit287sage: [(n, prec_words_to_bits(n)) for n in range(3, 10)]288[(3, 32), (4, 64), (5, 96), (6, 128), (7, 160), (8, 192), (9, 224)] # 32-bit289[(3, 64), (4, 128), (5, 192), (6, 256), (7, 320), (8, 384), (9, 448)] # 64-bit290"""291# see user's guide to the pari library, page 10292return (prec_in_words - 2) * BITS_IN_LONG293294def prec_dec_to_words(long prec_in_dec):295r"""296Convert from precision expressed in decimal to precision expressed297in words. Note: this rounds up to the nearest word, adjusts for the298two codewords of a pari real, and is architecture-dependent.299300EXAMPLES::301302sage: from sage.libs.pari.pari_instance import prec_dec_to_words303sage: prec_dec_to_words(38)3046 # 32-bit3054 # 64-bit306sage: [(n, prec_dec_to_words(n)) for n in range(10, 90, 10)]307[(10, 4), (20, 5), (30, 6), (40, 7), (50, 8), (60, 9), (70, 10), (80, 11)] # 32-bit308[(10, 3), (20, 4), (30, 4), (40, 5), (50, 5), (60, 6), (70, 6), (80, 7)] # 64-bit309"""310return prec_bits_to_words(prec_dec_to_bits(prec_in_dec))311312def prec_words_to_dec(long prec_in_words):313r"""314Convert from precision expressed in words to precision expressed in315decimal. Note: this adjusts for the two codewords of a pari real,316and is architecture-dependent.317318EXAMPLES::319320sage: from sage.libs.pari.pari_instance import prec_words_to_dec321sage: prec_words_to_dec(5)32228 # 32-bit32357 # 64-bit324sage: [(n, prec_words_to_dec(n)) for n in range(3, 10)]325[(3, 9), (4, 19), (5, 28), (6, 38), (7, 48), (8, 57), (9, 67)] # 32-bit326[(3, 19), (4, 38), (5, 57), (6, 77), (7, 96), (8, 115), (9, 134)] # 64-bit327"""328return prec_bits_to_dec(prec_words_to_bits(prec_in_words))329330331# The unique running Pari instance.332cdef PariInstance pari_instance, P333pari_instance = PariInstance()334P = pari_instance # shorthand notation335336# PariInstance.__init__ must not create gen objects because their parent is not constructed yet337pari_catch_sig_on()338pari_instance.PARI_ZERO = pari_instance.new_gen_noclear(gen_0)339pari_instance.PARI_ONE = pari_instance.new_gen_noclear(gen_1)340pari_instance.PARI_TWO = pari_instance.new_gen_noclear(gen_2)341pari_catch_sig_off()342343# Also a copy of PARI accessible from external pure python code.344pari = pari_instance345346347cdef unsigned long num_primes348349# Callbacks from PARI to print stuff using sys.stdout.write() instead350# of C library functions like puts().351cdef PariOUT sage_pariOut352353cdef void sage_putchar(char c):354cdef char s[2]355s[0] = c356s[1] = 0357sys.stdout.write(s)358# Let PARI think the last character was a newline,359# so it doesn't print one when an error occurs.360pari_set_last_newline(1)361362cdef void sage_puts(char* s):363sys.stdout.write(s)364pari_set_last_newline(1)365366cdef void sage_flush():367sys.stdout.flush()368369cdef PariOUT sage_pariErr370371cdef void sage_pariErr_putchar(char c):372cdef char s[2]373s[0] = c374s[1] = 0375global pari_error_string376pari_error_string += str(s)377pari_set_last_newline(1)378379cdef void sage_pariErr_puts(char *s):380global pari_error_string381pari_error_string += str(s)382pari_set_last_newline(1)383384cdef void sage_pariErr_flush():385pass386387388@cython.final389cdef class PariInstance(sage.structure.parent_base.ParentWithBase):390def __init__(self, long size=1000000, unsigned long maxprime=500000):391"""392Initialize the PARI system.393394INPUT:395396397- ``size`` -- long, the number of bytes for the initial398PARI stack (see note below)399400- ``maxprime`` -- unsigned long, upper limit on a401precomputed prime number table (default: 500000)402403404.. note::405406In Sage, the PARI stack is different than in GP or the407PARI C library. In Sage, instead of the PARI stack408holding the results of all computations, it *only* holds409the results of an individual computation. Each time a new410Python/PARI object is computed, it it copied to its own411space in the Python heap, and the memory it occupied on the412PARI stack is freed. Thus it is not necessary to make the413stack very large. Also, unlike in PARI, if the stack does414overflow, in most cases the PARI stack is automatically415increased and the relevant step of the computation rerun.416417This design obviously involves some performance penalties418over the way PARI works, but it scales much better and is419far more robust for large projects.420421.. note::422423If you do not want prime numbers, put ``maxprime=2``, but be424careful because many PARI functions require this table. If425you get the error message "not enough precomputed primes",426increase this parameter.427"""428if bot:429return # pari already initialized.430431global num_primes, top, bot432433# The size here doesn't really matter, because we will allocate434# our own stack anyway. We ask PARI not to set up signal and435# error handlers.436pari_init_opts(10000, maxprime, INIT_DFTm)437438_pari_init_error_handling()439440num_primes = maxprime441442# Free the PARI stack and allocate our own (using Cython)443pari_free(<void*>bot); bot = 0444init_stack(size)445446# Set printing functions447global pariOut, pariErr448449pariOut = &sage_pariOut450pariOut.putch = sage_putchar451pariOut.puts = sage_puts452pariOut.flush = sage_flush453454pariErr = &sage_pariErr455pariErr.putch = sage_pariErr_putchar456pariErr.puts = sage_pariErr_puts457pariErr.flush = sage_pariErr_flush458459# Display only 15 digits460sd_format("g.15", d_SILENT)461462# Init global prec variable (PARI's precision is always a463# multiple of the machine word size)464global prec465prec = prec_bits_to_words(64)466467# Disable pretty-printing468GP_DATA.fmt.prettyp = 0469470# This causes PARI/GP to use output independent of the terminal471# (which is want we want for the PARI library interface).472GP_DATA.flags = gpd_TEST473474475def debugstack(self):476r"""477Print the internal PARI variables ``top`` (top of stack), ``avma``478(available memory address, think of this as the stack pointer),479``bot`` (bottom of stack).480481EXAMPLE::482483sage: pari.debugstack() # random484top = 0x60b2c60485avma = 0x5875c38486bot = 0x57295e0487size = 1000000488"""489# We deliberately use low-level functions to minimize the490# chances that something goes wrong here (for example, if we491# are out of memory).492global avma, top, bot493printf("top = %p\navma = %p\nbot = %p\nsize = %lu\n", top, avma, bot, <unsigned long>(top) - <unsigned long>(bot))494fflush(stdout)495496def __dealloc__(self):497"""498Deallocation of the Pari instance.499500NOTE:501502Usually this deallocation happens only when Sage quits.503We do not provide a direct test, since usually there504is only one Pari instance, and when artificially creating505another instance, C-data are shared.506507The fact that Sage does not crash when quitting is an508indirect doctest. See the discussion at :trac:`13741`.509510"""511if bot:512sage_free(<void*>bot)513global top, bot, avma514top = 0515bot = 0516avma = 0517pari_close()518519def __repr__(self):520return "Interface to the PARI C library"521522def __hash__(self):523return 907629390 # hash('pari')524525cdef has_coerce_map_from_c_impl(self, x):526return True527528def __richcmp__(left, right, int op):529"""530EXAMPLES::531532sage: pari == pari533True534sage: pari == gp535False536sage: pari == 5537False538"""539return (<Parent>left)._richcmp(right, op)540541def default(self, variable, value=None):542if not value is None:543return self('default(%s, %s)'%(variable, value))544return self('default(%s)'%variable)545546def set_debug_level(self, level):547"""548Set the debug PARI C library variable.549"""550self.default('debug', int(level))551552def get_debug_level(self):553"""554Set the debug PARI C library variable.555"""556return int(self.default('debug'))557558def set_real_precision(self, long n):559"""560Sets the PARI default real precision in decimal digits.561562This is used both for creation of new objects from strings and for563printing. It is the number of digits *IN DECIMAL* in which real564numbers are printed. It also determines the precision of objects565created by parsing strings (e.g. pari('1.2')), which is *not* the566normal way of creating new pari objects in Sage. It has *no*567effect on the precision of computations within the pari library.568569Returns the previous PARI real precision.570571EXAMPLES::572573sage: pari.set_real_precision(60)57415575sage: pari('1.2')5761.20000000000000000000000000000000000000000000000000000000000577sage: pari.set_real_precision(15)57860579"""580prev = self.get_real_precision()581cdef bytes strn = str(n)582pari_catch_sig_on()583sd_realprecision(strn, d_SILENT)584pari_catch_sig_off()585return prev586587def get_real_precision(self):588"""589Returns the current PARI default real precision.590591This is used both for creation of new objects from strings and for592printing. It is the number of digits *IN DECIMAL* in which real593numbers are printed. It also determines the precision of objects594created by parsing strings (e.g. pari('1.2')), which is *not* the595normal way of creating new pari objects in Sage. It has *no*596effect on the precision of computations within the pari library.597598EXAMPLES::599600sage: pari.get_real_precision()60115602"""603pari_catch_sig_on()604cdef long prev = itos(sd_realprecision(NULL, d_RETURN))605pari_catch_sig_off()606return prev607608def set_series_precision(self, long n):609global precdl610precdl = n611612def get_series_precision(self):613return precdl614615cdef inline void clear_stack(self):616"""617Call ``pari_catch_sig_off()``, and clear the entire PARI stack618if we are leaving the outermost ``pari_catch_sig_on() ...619pari_catch_sig_off()`` block.620621"""622global top, avma623if _signals.sig_on_count <= 1:624avma = top625pari_catch_sig_off()626627cdef inline gen new_gen(self, GEN x):628"""629Create a new gen wrapping `x`, then call ``clear_stack()``.630"""631cdef gen g = self.new_gen_noclear(x)632self.clear_stack()633return g634635cdef inline gen new_gen_noclear(self, GEN x):636"""637Create a new gen, but don't free any memory on the stack and don't638call pari_catch_sig_off().639"""640cdef pari_sp address641cdef gen y = PY_NEW(gen)642y.g = self.deepcopy_to_python_heap(x, &address)643y.b = address644y._parent = self645# y.refers_to (a dict which is None now) is initialised as needed646return y647648cdef gen new_gen_from_mpz_t(self, mpz_t value):649"""650Create a new gen from a given MPIR-integer ``value``.651652EXAMPLES::653654sage: pari(42) # indirect doctest65542656657TESTS:658659Check that the hash of an integer does not depend on existing660garbage on the stack (#11611)::661662sage: foo = pari(2^(32*1024)); # Create large integer to put PARI stack in known state663sage: a5 = pari(5);664sage: foo = pari(0xDEADBEEF * (2^(32*1024)-1)//(2^32 - 1)); # Dirty PARI stack665sage: b5 = pari(5);666sage: a5.__hash__() == b5.__hash__()667True668"""669pari_catch_sig_on()670return self.new_gen(self._new_GEN_from_mpz_t(value))671672cdef inline GEN _new_GEN_from_mpz_t(self, mpz_t value):673r"""674Create a new PARI ``t_INT`` from a ``mpz_t``.675676For internal use only; this directly uses the PARI stack.677One should call ``pari_catch_sig_on()`` before and ``pari_catch_sig_off()`` after.678"""679cdef unsigned long limbs = mpz_size(value)680681cdef GEN z = cgeti(limbs + 2)682# Set sign and "effective length"683z[1] = evalsigne(mpz_sgn(value)) + evallgefint(limbs + 2)684mpz_export(int_LSW(z), NULL, -1, sizeof(long), 0, 0, value)685686return z687688cdef gen new_gen_from_int(self, int value):689pari_catch_sig_on()690return self.new_gen(stoi(value))691692cdef gen new_gen_from_mpq_t(self, mpq_t value):693"""694Create a new gen from a given MPIR-rational ``value``.695696EXAMPLES::697698sage: pari(-2/3)699-2/3700sage: pari(QQ(42))70142702sage: pari(QQ(42)).type()703't_INT'704sage: pari(QQ(1/42)).type()705't_FRAC'706707TESTS:708709Check that the hash of a rational does not depend on existing710garbage on the stack (#11854)::711712sage: foo = pari(2^(32*1024)); # Create large integer to put PARI stack in known state713sage: a5 = pari(5/7);714sage: foo = pari(0xDEADBEEF * (2^(32*1024)-1)//(2^32 - 1)); # Dirty PARI stack715sage: b5 = pari(5/7);716sage: a5.__hash__() == b5.__hash__()717True718"""719pari_catch_sig_on()720return self.new_gen(self._new_GEN_from_mpq_t(value))721722cdef inline GEN _new_GEN_from_mpq_t(self, mpq_t value):723r"""724Create a new PARI ``t_INT`` or ``t_FRAC`` from a ``mpq_t``.725726For internal use only; this directly uses the PARI stack.727One should call ``pari_catch_sig_on()`` before and ``pari_catch_sig_off()`` after.728"""729cdef GEN num = self._new_GEN_from_mpz_t(mpq_numref(value))730if mpz_cmpabs_ui(mpq_denref(value), 1) == 0:731# Denominator is 1, return the numerator (an integer)732return num733cdef GEN denom = self._new_GEN_from_mpz_t(mpq_denref(value))734return mkfrac(num, denom)735736cdef gen new_t_POL_from_int_star(self, int *vals, int length, long varnum):737"""738Note that degree + 1 = length, so that recognizing 0 is easier.739740varnum = 0 is the general choice (creates a variable in x).741"""742cdef GEN z743cdef int i744745pari_catch_sig_on()746z = cgetg(length + 2, t_POL)747z[1] = evalvarn(varnum)748if length != 0:749setsigne(z,1)750for i from 0 <= i < length:751set_gel(z,i+2, stoi(vals[i]))752else:753## polynomial is zero754setsigne(z,0)755756return self.new_gen(z)757758cdef gen new_gen_from_padic(self, long ordp, long relprec,759mpz_t prime, mpz_t p_pow, mpz_t unit):760cdef GEN z761pari_catch_sig_on()762z = cgetg(5, t_PADIC)763z[1] = evalprecp(relprec) + evalvalp(ordp)764set_gel(z, 2, self._new_GEN_from_mpz_t(prime))765set_gel(z, 3, self._new_GEN_from_mpz_t(p_pow))766set_gel(z, 4, self._new_GEN_from_mpz_t(unit))767return self.new_gen(z)768769def double_to_gen(self, x):770cdef double dx771dx = float(x)772return self.double_to_gen_c(dx)773774cdef gen double_to_gen_c(self, double x):775"""776Create a new gen with the value of the double x, using Pari's777dbltor.778779EXAMPLES::780781sage: pari.double_to_gen(1)7821.00000000000000783sage: pari.double_to_gen(1e30)7841.00000000000000 E30785sage: pari.double_to_gen(0)7860.E-15787sage: pari.double_to_gen(-sqrt(RDF(2)))788-1.41421356237310789"""790# Pari has an odd concept where it attempts to track the accuracy791# of floating-point 0; a floating-point zero might be 0.0e-20792# (meaning roughly that it might represent any number in the793# range -1e-20 <= x <= 1e20).794795# Pari's dbltor converts a floating-point 0 into the Pari real796# 0.0e-307; Pari treats this as an extremely precise 0. This797# can cause problems; for instance, the Pari incgam() function can798# be very slow if the first argument is very precise.799800# So we translate 0 into a floating-point 0 with 53 bits801# of precision (that's the number of mantissa bits in an IEEE802# double).803804pari_catch_sig_on()805if x == 0:806return self.new_gen(real_0_bit(-53))807else:808return self.new_gen(dbltor(x))809810cdef GEN double_to_GEN(self, double x):811if x == 0:812return real_0_bit(-53)813else:814return dbltor(x)815816def complex(self, re, im):817"""818Create a new complex number, initialized from re and im.819"""820cdef gen t0 = self(re)821cdef gen t1 = self(im)822pari_catch_sig_on()823return self.new_gen(mkcomplex(t0.g, t1.g))824825cdef GEN deepcopy_to_python_heap(self, GEN x, pari_sp* address):826cdef size_t s = <size_t> gsizebyte(x)827cdef pari_sp tmp_bot = <pari_sp> sage_malloc(s)828cdef pari_sp tmp_top = tmp_bot + s829address[0] = tmp_bot830return gcopy_avma(x, &tmp_top)831832cdef gen new_ref(self, GEN g, gen parent):833"""834Create a new gen pointing to the given GEN, which is allocated as a835part of parent.g.836837.. note::838839As a rule, there should never be more than one sage gen840pointing to a given Pari GEN. So that means there is only841one case where this function should be used: when a842complicated Pari GEN is allocated with a single gen843pointing to it, and one needs a gen pointing to one of its844components.845846For example, doing x = pari("[1,2]") allocates a gen pointing to847the list [1,2], but x[0] has no gen wrapping it, so new_ref848should be used there. Then parent would be x in this849case. See __getitem__ for an example of usage.850851EXAMPLES::852853sage: pari("[[1,2],3]")[0][1] ## indirect doctest8542855"""856cdef gen p = PY_NEW(gen)857p.g = g858p.b = 0859p._parent = self860p.refers_to = {-1: parent}861return p862863def __call__(self, s):864"""865Create the PARI object obtained by evaluating s using PARI.866867EXAMPLES::868869sage: pari([2,3,5])870[2, 3, 5]871sage: pari(Matrix(2,2,range(4)))872[0, 1; 2, 3]873sage: pari(x^2-3)874x^2 - 3875876::877878sage: a = pari(1); a, a.type()879(1, 't_INT')880sage: a = pari(1/2); a, a.type()881(1/2, 't_FRAC')882sage: a = pari(1/2); a, a.type()883(1/2, 't_FRAC')884885See :func:`pari` for more examples.886"""887return objtogen(s)888889cdef GEN _new_GEN_from_mpz_t_matrix(self, mpz_t** B, Py_ssize_t nr, Py_ssize_t nc):890r"""891Create a new PARI ``t_MAT`` with ``nr`` rows and ``nc`` columns892from a ``mpz_t**``.893894For internal use only; this directly uses the PARI stack.895One should call ``pari_catch_sig_on()`` before and ``pari_catch_sig_off()`` after.896"""897cdef GEN x898cdef GEN A = zeromatcopy(nr, nc)899cdef Py_ssize_t i, j900for i in range(nr):901for j in range(nc):902x = self._new_GEN_from_mpz_t(B[i][j])903set_gcoeff(A, i+1, j+1, x) # A[i+1, j+1] = x (using 1-based indexing)904return A905906cdef GEN _new_GEN_from_mpz_t_matrix_rotate90(self, mpz_t** B, Py_ssize_t nr, Py_ssize_t nc):907r"""908Create a new PARI ``t_MAT`` with ``nr`` rows and ``nc`` columns909from a ``mpz_t**`` and rotate the matrix 90 degrees910counterclockwise. So the resulting matrix will have ``nc`` rows911and ``nr`` columns. This is useful for computing the Hermite912Normal Form because Sage and PARI use different definitions.913914For internal use only; this directly uses the PARI stack.915One should call ``pari_catch_sig_on()`` before and ``pari_catch_sig_off()`` after.916"""917cdef GEN x918cdef GEN A = zeromatcopy(nc, nr)919cdef Py_ssize_t i, j920for i in range(nr):921for j in range(nc):922x = self._new_GEN_from_mpz_t(B[i][nc-j-1])923set_gcoeff(A, j+1, i+1, x) # A[j+1, i+1] = x (using 1-based indexing)924return A925926cdef gen integer_matrix(self, mpz_t** B, Py_ssize_t nr, Py_ssize_t nc, bint permute_for_hnf):927"""928EXAMPLES::929930sage: matrix(ZZ,2,[1..6])._pari_() # indirect doctest931[1, 2, 3; 4, 5, 6]932"""933pari_catch_sig_on()934cdef GEN g935if permute_for_hnf:936g = self._new_GEN_from_mpz_t_matrix_rotate90(B, nr, nc)937else:938g = self._new_GEN_from_mpz_t_matrix(B, nr, nc)939return self.new_gen(g)940941cdef GEN _new_GEN_from_mpq_t_matrix(self, mpq_t** B, Py_ssize_t nr, Py_ssize_t nc):942cdef GEN x943# Allocate zero matrix944cdef GEN A = zeromatcopy(nr, nc)945cdef Py_ssize_t i, j946for i in range(nr):947for j in range(nc):948x = self._new_GEN_from_mpq_t(B[i][j])949set_gcoeff(A, i+1, j+1, x) # A[i+1, j+1] = x (using 1-based indexing)950return A951952cdef gen rational_matrix(self, mpq_t** B, Py_ssize_t nr, Py_ssize_t nc):953"""954EXAMPLES::955956sage: matrix(QQ,2,[1..6])._pari_() # indirect doctest957[1, 2, 3; 4, 5, 6]958"""959pari_catch_sig_on()960cdef GEN g = self._new_GEN_from_mpq_t_matrix(B, nr, nc)961return self.new_gen(g)962963cdef _coerce_c_impl(self, x):964"""965Implicit canonical coercion into a PARI object.966"""967try:968return self(x)969except (TypeError, AttributeError):970raise TypeError("no canonical coercion of %s into PARI"%x)971972cdef _an_element_c_impl(self): # override this in Cython973return self.PARI_ZERO974975def new_with_bits_prec(self, s, long precision):976r"""977pari.new_with_bits_prec(self, s, precision) creates s as a PARI978gen with (at most) precision *bits* of precision.979"""980cdef unsigned long old_prec981old_prec = GP_DATA.fmt.sigd982precision = prec_bits_to_dec(precision)983if not precision:984precision = old_prec985self.set_real_precision(precision)986x = self(s)987self.set_real_precision(old_prec)988return x989990991992cdef long get_var(self, v):993"""994Converts a Python string into a PARI variable reference number. Or995if v = -1, returns -1.996"""997if v != -1:998s = str(v)999return fetch_user_var(s)1000return -110011002############################################################1003# Initialization1004############################################################10051006def stacksize(self):1007r"""1008Returns the current size of the PARI stack, which is `10^6`1009by default. However, the stack size is automatically doubled1010when needed. It can also be set directly using1011``pari.allocatemem()``.10121013EXAMPLES::10141015sage: pari.stacksize()1016100000010171018"""1019global top, bot1020return (<size_t>(top) - <size_t>(bot))10211022def _allocate_huge_mem(self):1023r"""1024This function tries to allocate an impossibly large amount of1025PARI stack in order to test ``init_stack()`` failing.10261027TESTS::10281029sage: pari.allocatemem(10^6, silent=True)1030sage: pari._allocate_huge_mem()1031Traceback (most recent call last):1032...1033MemoryError: Unable to allocate ... (instead, allocated 1000000 bytes)10341035Test that the PARI stack is sane after this failure::10361037sage: a = pari('2^10000000')1038sage: pari.allocatemem(10^6, silent=True)1039"""1040# Since size_t is unsigned, this should wrap over to a very1041# large positive number.1042init_stack(<size_t>(-4096))10431044def _setup_failed_retry(self):1045r"""1046This function pretends that the PARI stack is larger than it1047actually is such that allocatemem(0) will allocate much more1048than double the current stack. That allocation will then fail.1049This function is meant to be used only in this doctest.10501051TESTS::10521053sage: pari.allocatemem(4096, silent=True)1054sage: pari._setup_failed_retry()1055sage: try: # Any result is fine as long as it's not a segfault1056....: a = pari('2^1000000')1057....: except MemoryError:1058....: pass1059sage: pari.allocatemem(10^6, silent=True)1060"""1061global top1062# Pretend top is at a very high address1063top = <pari_sp>(<size_t>(-16))10641065def allocatemem(self, s=0, silent=False):1066r"""1067Change the PARI stack space to the given size (or double the1068current size if ``s`` is `0`).10691070If `s = 0` and insufficient memory is avaible to double, the1071PARI stack will be enlarged by a smaller amount. In any case,1072a ``MemoryError`` will be raised if the requested memory cannot1073be allocated.10741075The PARI stack is never automatically shrunk. You can use the1076command ``pari.allocatemem(10^6)`` to reset the size to `10^6`,1077which is the default size at startup. Note that the results of1078computations using Sage's PARI interface are copied to the1079Python heap, so they take up no space in the PARI stack.1080The PARI stack is cleared after every computation.10811082It does no real harm to set this to a small value as the PARI1083stack will be automatically doubled when we run out of memory.1084However, it could make some calculations slower (since they have1085to be redone from the start after doubling the stack until the1086stack is big enough).10871088INPUT:10891090- ``s`` - an integer (default: 0). A non-zero argument should1091be the size in bytes of the new PARI stack. If `s` is zero,1092try to double the current stack size.10931094EXAMPLES::10951096sage: pari.allocatemem(10^7)1097PARI stack size set to 10000000 bytes1098sage: pari.allocatemem() # Double the current size1099PARI stack size set to 20000000 bytes1100sage: pari.stacksize()1101200000001102sage: pari.allocatemem(10^6)1103PARI stack size set to 1000000 bytes11041105The following computation will automatically increase the PARI1106stack size::11071108sage: a = pari('2^100000000')11091110``a`` is now a Python variable on the Python heap and does not1111take up any space on the PARI stack. The PARI stack is still1112large because of the computation of ``a``::11131114sage: pari.stacksize()1115160000001116sage: pari.allocatemem(10^6)1117PARI stack size set to 1000000 bytes1118sage: pari.stacksize()1119100000011201121TESTS:11221123Do the same without using the string interface and starting1124from a very small stack size::11251126sage: pari.allocatemem(1)1127PARI stack size set to 1024 bytes1128sage: a = pari(2)^1000000001129sage: pari.stacksize()1130167772161131"""1132s = long(s)1133if s < 0:1134raise ValueError("Stack size must be nonnegative")1135init_stack(s)1136if not silent:1137print "PARI stack size set to", self.stacksize(), "bytes"11381139def pari_version(self):1140return str(PARIVERSION)11411142def init_primes(self, _M):1143"""1144Recompute the primes table including at least all primes up to M1145(but possibly more).11461147EXAMPLES::11481149sage: pari.init_primes(200000)11501151We make sure that ticket #11741 has been fixed, and double check to1152make sure that diffptr has not been freed::11531154sage: pari.init_primes(2^62)1155Traceback (most recent call last):1156...1157PariError: not enough memory # 64-bit1158OverflowError: long int too large to convert # 32-bit1159sage: pari.init_primes(200000)1160"""1161cdef unsigned long M1162cdef char *tmpptr1163M = _M1164global diffptr, num_primes1165if M <= num_primes:1166return1167pari_catch_sig_on()1168tmpptr = initprimes(M)1169pari_catch_sig_off()1170pari_free(<void*> diffptr)1171num_primes = M1172diffptr = tmpptr117311741175##############################################1176## Support for GP Scripts1177##############################################11781179def read(self, bytes filename):1180r"""1181Read a script from the named filename into the interpreter. The1182functions defined in the script are then available for use from1183Sage/PARI. The result of the last command in ``filename`` is1184returned.11851186EXAMPLES:11871188Create a gp file::11891190sage: import tempfile1191sage: gpfile = tempfile.NamedTemporaryFile(mode="w")1192sage: gpfile.file.write("mysquare(n) = {\n")1193sage: gpfile.file.write(" n^2;\n")1194sage: gpfile.file.write("}\n")1195sage: gpfile.file.write("polcyclo(5)\n")1196sage: gpfile.file.flush()11971198Read it in Sage, we get the result of the last line::11991200sage: pari.read(gpfile.name)1201x^4 + x^3 + x^2 + x + 112021203Call the function defined in the gp file::12041205sage: pari('mysquare(12)')12061441207"""1208pari_catch_sig_on()1209return self.new_gen(gp_read_file(filename))121012111212##############################################12131214def _primelimit(self):1215"""1216Return the number of primes already computed1217in this Pari instance.12181219EXAMPLES:1220sage: pari._primelimit()12215000001222sage: pari.init_primes(600000)1223sage: pari._primelimit()12246000001225"""1226global num_primes1227from sage.rings.all import ZZ1228return ZZ(num_primes)12291230def prime_list(self, long n):1231"""1232prime_list(n): returns list of the first n primes12331234To extend the table of primes use pari.init_primes(M).12351236INPUT:123712381239- ``n`` - C long124012411242OUTPUT:124312441245- ``gen`` - PARI list of first n primes124612471248EXAMPLES::12491250sage: pari.prime_list(0)1251[]1252sage: pari.prime_list(-1)1253[]1254sage: pari.prime_list(3)1255[2, 3, 5]1256sage: pari.prime_list(10)1257[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]1258sage: pari.prime_list(20)1259[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]1260sage: len(pari.prime_list(1000))126110001262"""1263if n >= 2:1264self.nth_prime(n)1265pari_catch_sig_on()1266return self.new_gen(primes(n))12671268def primes_up_to_n(self, long n):1269"""1270Return the primes <= n as a pari list.12711272EXAMPLES::12731274sage: pari.primes_up_to_n(1)1275[]1276sage: pari.primes_up_to_n(20)1277[2, 3, 5, 7, 11, 13, 17, 19]1278"""1279if n <= 1:1280return pari([])1281self.init_primes(n+1)1282return self.prime_list(pari(n).primepi())12831284## cdef long k1285## k = (n+10)/math.log(n)1286## p = 21287## while p <= n:1288## p = self.nth_prime(k)1289## k = 21290## v = self.prime_list(k)1291## return v[:pari(n).primepi()]12921293def __nth_prime(self, long n):1294"""1295nth_prime(n): returns the n-th prime, where n is a C-int1296"""1297global num_primes12981299if n <= 0:1300raise ValueError, "nth prime meaningless for non-positive n (=%s)"%n1301cdef GEN g1302pari_catch_sig_on()1303g = prime(n)1304return self.new_gen(g)130513061307def nth_prime(self, long n):1308from sage.libs.pari.all import PariError1309try:1310return self.__nth_prime(n)1311except PariError:1312self.init_primes(max(2*num_primes,20*n))1313return self.nth_prime(n)13141315def euler(self, unsigned long precision=0):1316"""1317Return Euler's constant to the requested real precision (in bits).13181319EXAMPLES::13201321sage: pari.euler()13220.5772156649015331323sage: pari.euler(precision=100).python()13240.577215664901532860606512090082...1325"""1326pari_catch_sig_on()1327return self.new_gen(mpeuler(prec_bits_to_words(precision)))13281329def pi(self, unsigned long precision=0):1330"""1331Return the value of the constant pi to the requested real precision1332(in bits).13331334EXAMPLES::13351336sage: pari.pi()13373.141592653589791338sage: pari.pi(precision=100).python()13393.1415926535897932384626433832...1340"""1341pari_catch_sig_on()1342return self.new_gen(mppi(prec_bits_to_words(precision)))13431344def pollegendre(self, long n, v=-1):1345"""1346pollegendre(n, v=x): Legendre polynomial of degree n (n C-integer),1347in variable v.13481349EXAMPLES::13501351sage: pari.pollegendre(7)1352429/16*x^7 - 693/16*x^5 + 315/16*x^3 - 35/16*x1353sage: pari.pollegendre(7, 'z')1354429/16*z^7 - 693/16*z^5 + 315/16*z^3 - 35/16*z1355sage: pari.pollegendre(0)135611357"""1358pari_catch_sig_on()1359return self.new_gen(pollegendre(n, self.get_var(v)))13601361def poltchebi(self, long n, v=-1):1362"""1363poltchebi(n, v=x): Chebyshev polynomial of the first kind of degree1364n, in variable v.13651366EXAMPLES::13671368sage: pari.poltchebi(7)136964*x^7 - 112*x^5 + 56*x^3 - 7*x1370sage: pari.poltchebi(7, 'z')137164*z^7 - 112*z^5 + 56*z^3 - 7*z1372sage: pari.poltchebi(0)137311374"""1375pari_catch_sig_on()1376return self.new_gen(polchebyshev1(n, self.get_var(v)))13771378def factorial(self, long n):1379"""1380Return the factorial of the integer n as a PARI gen.13811382EXAMPLES::13831384sage: pari.factorial(0)138511386sage: pari.factorial(1)138711388sage: pari.factorial(5)13891201390sage: pari.factorial(25)1391155112100433309859840000001392"""1393pari_catch_sig_on()1394return self.new_gen(mpfact(n))13951396def polcyclo(self, long n, v=-1):1397"""1398polcyclo(n, v=x): cyclotomic polynomial of degree n, in variable1399v.14001401EXAMPLES::14021403sage: pari.polcyclo(8)1404x^4 + 11405sage: pari.polcyclo(7, 'z')1406z^6 + z^5 + z^4 + z^3 + z^2 + z + 11407sage: pari.polcyclo(1)1408x - 11409"""1410pari_catch_sig_on()1411return self.new_gen(polcyclo(n, self.get_var(v)))14121413def polcyclo_eval(self, long n, v):1414"""1415polcyclo_eval(n, v): value of the nth cyclotomic polynomial at value v.14161417EXAMPLES::14181419sage: pari.polcyclo_eval(8, 2)1420171421sage: cyclotomic_polynomial(8)(2)1422171423"""1424cdef gen t0 = self(v)1425pari_catch_sig_on()1426return self.new_gen(polcyclo_eval(n, t0.g))14271428def polsubcyclo(self, long n, long d, v=-1):1429"""1430polsubcyclo(n, d, v=x): return the pari list of polynomial(s)1431defining the sub-abelian extensions of degree `d` of the1432cyclotomic field `\QQ(\zeta_n)`, where `d`1433divides `\phi(n)`.14341435EXAMPLES::14361437sage: pari.polsubcyclo(8, 4)1438[x^4 + 1]1439sage: pari.polsubcyclo(8, 2, 'z')1440[z^2 - 2, z^2 + 1, z^2 + 2]1441sage: pari.polsubcyclo(8, 1)1442[x - 1]1443sage: pari.polsubcyclo(8, 3)1444[]1445"""1446cdef gen plist1447pari_catch_sig_on()1448plist = self.new_gen(polsubcyclo(n, d, self.get_var(v)))1449if typ(plist.g) != t_VEC:1450return pari.vector(1, [plist])1451else:1452return plist1453#return self.new_gen(polsubcyclo(n, d, self.get_var(v)))14541455def polzagier(self, long n, long m):1456pari_catch_sig_on()1457return self.new_gen(polzag(n, m))14581459def setrand(self, seed):1460"""1461Sets PARI's current random number seed.14621463INPUT:14641465- ``seed`` -- either a strictly positive integer or a GEN of1466type ``t_VECSMALL`` as output by ``getrand()``14671468This should not be called directly; instead, use Sage's global1469random number seed handling in ``sage.misc.randstate``1470and call ``current_randstate().set_seed_pari()``.14711472EXAMPLES::14731474sage: pari.setrand(50)1475sage: a = pari.getrand(); a1476Vecsmall([...])1477sage: pari.setrand(a)1478sage: a == pari.getrand()1479True14801481TESTS:14821483Check that invalid inputs are handled properly (#11825)::14841485sage: pari.setrand(0)1486Traceback (most recent call last):1487...1488PariError: incorrect type in setrand1489sage: pari.setrand("foobar")1490Traceback (most recent call last):1491...1492PariError: incorrect type in setrand1493"""1494cdef gen t0 = self(seed)1495pari_catch_sig_on()1496setrand(t0.g)1497pari_catch_sig_off()14981499def getrand(self):1500"""1501Returns PARI's current random number seed.15021503OUTPUT:15041505GEN of type t_VECSMALL15061507EXAMPLES::15081509sage: pari.setrand(50)1510sage: a = pari.getrand(); a1511Vecsmall([...])1512sage: pari.setrand(a)1513sage: a == pari.getrand()1514True1515"""1516pari_catch_sig_on()1517return self.new_gen(getrand())15181519def vector(self, long n, entries=None):1520"""1521vector(long n, entries=None): Create and return the length n PARI1522vector with given list of entries.15231524EXAMPLES::15251526sage: pari.vector(5, [1, 2, 5, 4, 3])1527[1, 2, 5, 4, 3]1528sage: pari.vector(2, [x, 1])1529[x, 1]1530sage: pari.vector(2, [x, 1, 5])1531Traceback (most recent call last):1532...1533IndexError: length of entries (=3) must equal n (=2)1534"""1535cdef gen v = self._empty_vector(n)1536if entries is not None:1537if len(entries) != n:1538raise IndexError, "length of entries (=%s) must equal n (=%s)"%\1539(len(entries), n)1540for i, x in enumerate(entries):1541v[i] = x1542return v15431544cdef gen _empty_vector(self, long n):1545cdef gen v1546pari_catch_sig_on()1547v = self.new_gen(zerovec(n))1548return v15491550def matrix(self, long m, long n, entries=None):1551"""1552matrix(long m, long n, entries=None): Create and return the m x n1553PARI matrix with given list of entries.1554"""1555cdef long i, j, k1556cdef gen A1557cdef gen x15581559pari_catch_sig_on()1560A = self.new_gen(zeromatcopy(m,n))1561if entries is not None:1562if len(entries) != m*n:1563raise IndexError, "len of entries (=%s) must be %s*%s=%s"%(len(entries),m,n,m*n)1564k = 01565A.refers_to = {}1566for i from 0 <= i < m:1567for j from 0 <= j < n:1568x = pari(entries[k])1569A.refers_to[(i,j)] = x1570(<GEN>(A.g)[j+1])[i+1] = <long>(x.g)1571k = k + 11572return A157315741575cdef int init_stack(size_t requested_size) except -1:1576r"""1577Low-level Cython function to allocate the PARI stack. This1578function should not be called directly, use ``pari.allocatemem()``1579instead.1580"""1581global top, bot, avma15821583cdef size_t old_size = <size_t>(top) - <size_t>(bot)15841585cdef size_t new_size1586cdef size_t max_size = <size_t>(-1)1587if (requested_size == 0):1588if old_size < max_size/2:1589# Double the stack1590new_size = 2*old_size1591elif old_size < 4*(max_size/5):1592# We cannot possibly double since we already use over half1593# the addressable memory: take the average of current and1594# maximum size1595new_size = max_size/2 + old_size/21596else:1597# We already use 80% of the addressable memory => give up1598raise MemoryError("Unable to enlarge PARI stack (instead, kept the stack at %s bytes)"%(old_size))1599else:1600new_size = requested_size16011602# Align size to 16 bytes and take 1024 bytes as a minimum1603new_size = (new_size/16)*161604if (new_size < 1024):1605new_size = 102416061607# Disable interrupts1608sig_on()1609sig_block()16101611# If this is non-zero, the size we failed to allocate1612cdef size_t failed_size = 016131614try:1615# Free the current stack1616if bot:1617libc.stdlib.free(<void*>bot)16181619# Allocate memory for new stack.1620bot = <pari_sp> libc.stdlib.malloc(new_size)16211622# If doubling failed, instead add 25% to the current stack size.1623# We already checked that we use less than 80% of the maximum value1624# for s, so this will not overflow.1625if (bot == 0) and (requested_size == 0):1626new_size = (old_size/64)*801627bot = <pari_sp> libc.stdlib.malloc(new_size)16281629if not bot:1630failed_size = new_size1631# We lost our PARI stack and are not able to allocate the1632# requested size. If we just raise an exception now, we end up1633# *without* a PARI stack which is not good. We will raise an1634# exception later, after allocating *some* PARI stack.1635new_size = old_size1636while new_size >= 1024: # hope this never fails!1637bot = <pari_sp> libc.stdlib.malloc(new_size)1638if bot: break1639new_size = (new_size/32)*1616401641if not bot:1642top = 01643avma = 01644raise SystemError("Unable to allocate PARI stack, all subsequent PARI computations will crash")16451646top = bot + new_size1647avma = top16481649if failed_size:1650raise MemoryError("Unable to allocate %s bytes for the PARI stack (instead, allocated %s bytes)"%(failed_size, new_size))16511652return 01653finally:1654sig_unblock()1655sig_off()165616571658