diff --git a/src/sage/libs/singular/function.pyx b/src/sage/libs/singular/function.pyx index 7bf2afafbe8..766eb8826e1 100644 --- a/src/sage/libs/singular/function.pyx +++ b/src/sage/libs/singular/function.pyx @@ -97,7 +97,7 @@ from sage.rings.polynomial.multi_polynomial_sequence import PolynomialSequence_g from sage.libs.singular.decl cimport * from sage.libs.singular.option import opt_ctx from sage.libs.singular.polynomial cimport singular_vector_maximal_component -from sage.libs.singular.singular cimport sa2si, si2sa, si2sa_intvec, si2sa_bigintvec +from sage.libs.singular.singular cimport sa2si, si2sa, si2sa_intvec, si2sa_bigintvec, start_catch_error, check_error from sage.libs.singular.singular import error_messages from sage.interfaces.singular import get_docstring @@ -1450,10 +1450,8 @@ EXAMPLES:: cdef inline call_function(SingularFunction self, tuple args, object R, bint signal_handler=True, attributes=None): global currRingHdl - global errorreported global currentVoice global myynest - global error_messages cdef ring *si_ring if isinstance(R, MPolynomialRing_libsingular): @@ -1474,29 +1472,28 @@ cdef inline call_function(SingularFunction self, tuple args, object R, bint sign currentVoice = NULL myynest = 0 - errorreported = 0 - - while error_messages: - error_messages.pop() + start_catch_error() with opt_ctx: # we are preserving the global options state here if signal_handler: - sig_on() - _res = self.call_handler.handle_call(argument_list, si_ring) - sig_off() + try: + sig_on() + _res = self.call_handler.handle_call(argument_list, si_ring) + sig_off() + finally: + s = check_error() else: _res = self.call_handler.handle_call(argument_list, si_ring) + s = check_error() - if myynest: - myynest = 0 + myynest = 0 if currentVoice: currentVoice = NULL - if errorreported: - errorreported = 0 + if s: raise RuntimeError("error in Singular function call %r:\n%s" % - (self._name, "\n".join(error_messages))) + (self._name, "\n".join(s))) res = argument_list.to_python(_res) diff --git a/src/sage/libs/singular/ring.pyx b/src/sage/libs/singular/ring.pyx index f770cc483a5..fa7343f8dca 100644 --- a/src/sage/libs/singular/ring.pyx +++ b/src/sage/libs/singular/ring.pyx @@ -19,7 +19,7 @@ AUTHORS: from sage.cpython.string cimport str_to_bytes, bytes_to_str from sage.libs.gmp.types cimport __mpz_struct -from sage.libs.gmp.mpz cimport mpz_init_set_ui +from sage.libs.gmp.mpz cimport mpz_init_set from sage.libs.singular.decl cimport ring, currRing from sage.libs.singular.decl cimport rChangeCurrRing, rComplete, rDelete, idInit @@ -31,6 +31,7 @@ from sage.libs.singular.decl cimport n_coeffType from sage.libs.singular.decl cimport rDefault, GFInfo, ZnmInfo, nInitChar, AlgExtInfo, TransExtInfo +from sage.rings.integer cimport Integer from sage.rings.integer_ring cimport IntegerRing_class from sage.rings.integer_ring import ZZ import sage.rings.abc @@ -80,7 +81,7 @@ if bytes_to_str(rSimpleOrdStr(ringorder_ip)) == "rp": ############################################################################# cdef ring *singular_ring_new(base_ring, n, names, term_order) except NULL: - """ + r""" Create a new Singular ring over the ``base_ring`` in ``n`` variables with the names ``names`` and the term order ``term_order``. @@ -159,17 +160,136 @@ cdef ring *singular_ring_new(base_ring, n, names, term_order) except NULL: sage: R. = F[] sage: from sage.libs.singular.function import singular_function sage: sing_print = singular_function('print') - sage: sing_print(R) - 'polynomial ring, over a field, global ordering\n// coefficients: ZZ/7(a, b)\n// number of vars : 3\n// block 1 : ordering dp\n// : names x y z\n// block 2 : ordering C' + sage: print(sing_print(R)) + polynomial ring, over a field, global ordering + // coefficients: ZZ/7(a, b) + // number of vars : 3 + // block 1 : ordering dp + // : names x y z + // block 2 : ordering C :: sage: F = PolynomialRing(QQ, 's,t').fraction_field() sage: R. = F[] sage: from sage.libs.singular.function import singular_function - sage: sing_print = singular_function('print') - sage: sing_print(R) - 'polynomial ring, over a field, global ordering\n// coefficients: QQ(s, t)\n// number of vars : 3\n// block 1 : ordering dp\n// : names x y z\n// block 2 : ordering C' + sage: print(sing_print(R)) + polynomial ring, over a field, global ordering + // coefficients: QQ(s, t) + // number of vars : 3 + // block 1 : ordering dp + // : names x y z + // block 2 : ordering C + + Small primes:: + + sage: R = PolynomialRing(GF(2), ("a", "b"), implementation="singular"); print(sing_print(R)) + polynomial ring, over a field, global ordering + // coefficients: ZZ/2 + // number of vars : 2 + // block 1 : ordering dp + // : names a b + // block 2 : ordering C + sage: R = PolynomialRing(GF(3), ("a", "b"), implementation="singular"); print(sing_print(R)) + polynomial ring, over a field, global ordering + // coefficients: ZZ/3 + // number of vars : 2 + // block 1 : ordering dp + // : names a b + // block 2 : ordering C + sage: R = PolynomialRing(GF(1000000007), ("a", "b"), implementation="singular"); print(sing_print(R)) + polynomial ring, over a field, global ordering + // coefficients: ZZ/1000000007 + // number of vars : 2 + // block 1 : ordering dp + // : names a b + // block 2 : ordering C + + When ``Zmod`` is used, use a different Singular type + (note that the print is wrong, the field in fact doesn't have zero-divisors):: + + sage: R = PolynomialRing(Zmod(2), ("a", "b"), implementation="singular"); print(sing_print(R)) + polynomial ring, over a ring (with zero-divisors), global ordering + // coefficients: ZZ/(2) + // number of vars : 2 + // block 1 : ordering dp + // : names a b + // block 2 : ordering C + sage: R = PolynomialRing(Zmod(3), ("a", "b"), implementation="singular"); print(sing_print(R)) + polynomial ring, over a ring (with zero-divisors), global ordering + // coefficients: ZZ/(3) + // number of vars : 2 + // block 1 : ordering dp + // : names a b + // block 2 : ordering C + + Large prime (note that the print is wrong, the field in fact doesn't have zero-divisors):: + + sage: R = PolynomialRing(GF(2^128+51), ("a", "b"), implementation="singular"); print(sing_print(R)) + polynomial ring, over a ring (with zero-divisors), global ordering + // coefficients: ZZ/bigint(340282366920938463463374607431768211507) + // number of vars : 2 + // block 1 : ordering dp + // : names a b + // block 2 : ordering C + + Finite field with large degree (note that if stack size is too small and the exponent is too large + a stack overflow may happen inside libsingular):: + + sage: R = PolynomialRing(GF(2^160), ("a", "b"), implementation="singular"); print(sing_print(R)) + polynomial ring, over a field, global ordering + // coefficients: ZZ/2[z160]/(z160^160+z160^159+z160^155+z160^154+z160^153+z160^152+z160^151+z160^149+z160^148+z160^147+z160^146+z160^145+z160^144+z160^143+z160^141+z160^139+z160^137+z160^131+z160^129+z160^128+z160^127+z160^126+z160^123+z160^122+z160^121+z160^117+z160^116+z160^115+z160^113+z160^111+z160^110+z160^108+z160^106+z160^102+z160^100+z160^99+z160^97+z160^96+z160^95+z160^94+z160^93+z160^92+z160^91+z160^87+z160^86+z160^82+z160^80+z160^79+z160^78+z160^74+z160^73+z160^72+z160^71+z160^70+z160^67+z160^66+z160^65+z160^62+z160^59+z160^58+z160^57+z160^55+z160^54+z160^53+z160^52+z160^51+z160^49+z160^47+z160^44+z160^40+z160^35+z160^32+z160^30+z160^28+z160^27+z160^26+z160^24+z160^23+z160^21+z160^20+z160^18+z160^16+z160^11+z160^10+z160^8+z160^7+1) + // number of vars : 2 + // block 1 : ordering dp + // : names a b + // block 2 : ordering C + + Integer modulo small power of 2:: + + sage: R = PolynomialRing(Zmod(2^32), ("a", "b"), implementation="singular"); print(sing_print(R)) + polynomial ring, over a ring (with zero-divisors), global ordering + // coefficients: ZZ/(2^32) + // number of vars : 2 + // block 1 : ordering dp + // : names a b + // block 2 : ordering C + + Integer modulo large power of 2:: + + sage: R = PolynomialRing(Zmod(2^1000), ("a", "b"), implementation="singular"); print(sing_print(R)) + polynomial ring, over a ring (with zero-divisors), global ordering + // coefficients: ZZ/(bigint(2)^1000) + // number of vars : 2 + // block 1 : ordering dp + // : names a b + // block 2 : ordering C + + Integer modulo large power of odd prime:: + + sage: R = PolynomialRing(Zmod(3^300), ("a", "b"), implementation="singular"); print(sing_print(R)) + polynomial ring, over a ring (with zero-divisors), global ordering + // coefficients: ZZ/(bigint(3)^300) + // number of vars : 2 + // block 1 : ordering dp + // : names a b + // block 2 : ordering C + + Integer modulo non-prime:: + + sage: R = PolynomialRing(Zmod(15^20), ("a", "b"), implementation="singular"); print(sing_print(R)) + polynomial ring, over a ring (with zero-divisors), global ordering + // coefficients: ZZ/bigint(332525673007965087890625) + // number of vars : 2 + // block 1 : ordering dp + // : names a b + // block 2 : ordering C + + Non-prime finite field with large characteristic (not supported, see :issue:`33319`):: + + sage: PolynomialRing(GF((2^31+11)^2), ("a", "b"), implementation="singular") + Traceback (most recent call last): + ... + TypeError: characteristic must be <= 2147483647. """ cdef long cexponent cdef GFInfo* _param @@ -182,7 +302,7 @@ cdef ring *singular_ring_new(base_ring, n, names, term_order) except NULL: cdef int offset cdef int nvars cdef int characteristic - cdef int modbase + cdef Integer ch, modbase cdef int ringorder_column_pos cdef int ringorder_column_asc @@ -377,39 +497,57 @@ cdef ring *singular_ring_new(base_ring, n, names, term_order) except NULL: _cf = nInitChar( n_Z, NULL) # integer coefficient ring _ring = rDefault (_cf, nvars, _names, nblcks, _order, _block0, _block1, _wvhdl) - elif (isinstance(base_ring, FiniteField_generic) and base_ring.is_prime_field()): - if base_ring.characteristic() <= 2147483647: + elif isinstance(base_ring, sage.rings.abc.IntegerModRing): + + ch = base_ring.characteristic() + if ch < 2: + raise NotImplementedError(f"polynomials over {base_ring} are not supported in Singular") + + isprime = ch.is_prime() + + if isprime and ch <= 2147483647 and isinstance(base_ring, FiniteField_generic): + # don't use this branch for e.g. Zmod(5) characteristic = base_ring.characteristic() + + # example for simpler ring creation interface without monomial orderings: + #_ring = rDefault(characteristic, nvars, _names) + + _ring = rDefault(characteristic, nvars, _names, nblcks, _order, _block0, _block1, _wvhdl) + else: - raise TypeError("Characteristic p must be <= 2147483647.") + modbase, cexponent = ch.perfect_power() - # example for simpler ring creation interface without monomial orderings: - #_ring = rDefault(characteristic, nvars, _names) + if modbase == 2 and cexponent > 1: + _cf = nInitChar(n_Z2m, cexponent) - _ring = rDefault(characteristic, nvars, _names, nblcks, _order, _block0, _block1, _wvhdl) + elif modbase.is_prime() and cexponent > 1: + _info.base = <__mpz_struct *>omAlloc(sizeof(__mpz_struct)) + mpz_init_set(_info.base, modbase.value) + _info.exp = cexponent + _cf = nInitChar(n_Znm, &_info) + + else: + _info.base = <__mpz_struct *>omAlloc(sizeof(__mpz_struct)) + mpz_init_set(_info.base, ch.value) + _info.exp = 1 + _cf = nInitChar(n_Zn, &_info) + _ring = rDefault(_cf, nvars, _names, nblcks, _order, _block0, _block1, _wvhdl) elif isinstance(base_ring, FiniteField_generic): - if base_ring.characteristic() <= 2147483647: - characteristic = -base_ring.characteristic() # note the negative characteristic - else: + assert not base_ring.is_prime_field() # would have been handled above + if base_ring.characteristic() > 2147483647: raise TypeError("characteristic must be <= 2147483647.") # TODO: This is lazy, it should only call Singular stuff not PolynomialRing() k = PolynomialRing(base_ring.prime_subfield(), - name=base_ring.variable_name(), order='lex', implementation='singular') + name=base_ring.variable_name(), order='lex', + implementation='singular') minpoly = base_ring.polynomial()(k.gen()) - ch = base_ring.characteristic() - F = ch.factor() - assert(len(F)==1) - - modbase = F[0][0] - cexponent = F[0][1] - _ext_names = omAlloc0(sizeof(char*)) _name = str_to_bytes(k._names[0]) _ext_names[0] = omStrDup(_name) - _cfr = rDefault( modbase, 1, _ext_names ) + _cfr = rDefault(base_ring.characteristic(), 1, _ext_names) _cfr.qideal = idInit(1,1) rComplete(_cfr, 1) @@ -422,60 +560,6 @@ cdef ring *singular_ring_new(base_ring, n, names, term_order) except NULL: _ring = rDefault (_cf, nvars, _names, nblcks, _order, _block0, _block1, _wvhdl) - elif isinstance(base_ring, sage.rings.abc.IntegerModRing): - - ch = base_ring.characteristic() - if ch < 2: - raise NotImplementedError(f"polynomials over {base_ring} are not supported in Singular") - - isprime = ch.is_prime() - - if not isprime and ch.is_power_of(2): - exponent = ch.nbits() -1 - cexponent = exponent - - if exponent <= 30: - ringtype = n_Z2m - else: - ringtype = n_Znm - - if ringtype == n_Znm: - F = ch.factor() - - modbase = F[0][0] - cexponent = F[0][1] - - _info.base = <__mpz_struct*>omAlloc(sizeof(__mpz_struct)) - mpz_init_set_ui(_info.base, modbase) - _info.exp = cexponent - _cf = nInitChar(ringtype, &_info) - else: # ringtype == n_Z2m - _cf = nInitChar(ringtype, cexponent) - - elif not isprime and ch.is_prime_power() and ch < ZZ(2)**160: - F = ch.factor() - assert(len(F)==1) - - modbase = F[0][0] - cexponent = F[0][1] - - _info.base = <__mpz_struct*>omAlloc(sizeof(__mpz_struct)) - mpz_init_set_ui(_info.base, modbase) - _info.exp = cexponent - _cf = nInitChar( n_Znm, &_info ) - - else: - try: - characteristic = ch - except OverflowError: - raise NotImplementedError("Characteristic %d too big." % ch) - - _info.base = <__mpz_struct*>omAlloc(sizeof(__mpz_struct)) - mpz_init_set_ui(_info.base, characteristic) - _info.exp = 1 - _cf = nInitChar( n_Zn, &_info ) - _ring = rDefault(_cf, nvars, _names, nblcks, _order, _block0, _block1, _wvhdl) - else: raise NotImplementedError(f"polynomials over {base_ring} are not supported in Singular") diff --git a/src/sage/libs/singular/singular.pxd b/src/sage/libs/singular/singular.pxd index 9d764b51a6f..a0019fe4ede 100644 --- a/src/sage/libs/singular/singular.pxd +++ b/src/sage/libs/singular/singular.pxd @@ -55,6 +55,13 @@ cdef number *sa2si_NF(object element, ring *_ring) noexcept # dispatches to all the above. cdef number *sa2si(Element elem, ring * _ring) noexcept +# ============== +# Error handling +# ============== + +cdef int start_catch_error() except -1 +cdef object check_error() + # ============== # Initialisation # ============== diff --git a/src/sage/libs/singular/singular.pyx b/src/sage/libs/singular/singular.pyx index e2ca2b02e75..813765cff3d 100644 --- a/src/sage/libs/singular/singular.pyx +++ b/src/sage/libs/singular/singular.pyx @@ -25,6 +25,7 @@ cdef extern from "limits.h": long INT_MIN import os +from warnings import warn from libc.stdint cimport int64_t from sage.libs.singular.decl cimport * @@ -302,6 +303,9 @@ cdef object si2sa_GFq_generic(number *n, ring *_ring, object base): cdef object ret cdef ring *cfRing = _ring.cf.extRing + if _ring.cf.type in (n_Zn, n_Znm): + return si2sa_ZZmod(n, _ring, base) + if _ring.cf.cfIsZero(n,_ring.cf): return base.zero() elif _ring.cf.cfIsOne(n,_ring.cf): @@ -886,7 +890,7 @@ cdef number *sa2si_QQ(Rational r, ring *_ring) noexcept: - ``r`` -- a sage rational number - - ``_ ring`` -- a (pointer to) a singular ring, where the resul will live + - ``_ ring`` -- a (pointer to) a singular ring, where the result will live OUTPUT: @@ -916,7 +920,7 @@ cdef number *sa2si_GFqGivaro(int quo, ring *_ring) noexcept: - ``quo`` -- sage integer - - ``_ ring`` -- a (pointer to) a singular ring, where the resul will live + - ``_ ring`` -- a (pointer to) a singular ring, where the result will live OUTPUT: @@ -984,7 +988,7 @@ cdef number *sa2si_GFqNTLGF2E(FFgf2eE elem, ring *_ring) noexcept: - ``elem`` -- a sage element of a ntl_gf2e finite field - - ``_ ring`` -- a (pointer to) a singular ring, where the resul will live + - ``_ ring`` -- a (pointer to) a singular ring, where the result will live OUTPUT: @@ -1049,7 +1053,7 @@ cdef number *sa2si_GFq_generic(object elem, ring *_ring) noexcept: - ``elem`` -- a sage element of a generic finite field - - ``_ ring`` -- a (pointer to) a singular ring, where the resul will live + - ``_ ring`` -- a (pointer to) a singular ring, where the result will live OUTPUT: @@ -1075,6 +1079,9 @@ cdef number *sa2si_GFq_generic(object elem, ring *_ring) noexcept: cdef number *coeff cdef number *apow1 cdef number *apow2 + + if _ring.cf.type in (n_Zn, n_Znm): + return sa2si_ZZmod(elem, _ring) elem = elem.polynomial() if _ring != currRing: rChangeCurrRing(_ring) @@ -1115,7 +1122,7 @@ cdef number *sa2si_transext_QQ(object elem, ring *_ring) noexcept: - ``elem`` -- a sage element of a FractionField of polynomials over the rationals - - ``_ ring`` -- a (pointer to) a singular ring, where the resul will live + - ``_ ring`` -- a (pointer to) a singular ring, where the result will live OUTPUT: @@ -1265,7 +1272,7 @@ cdef number *sa2si_transext_FF(object elem, ring *_ring) noexcept: - ``elem`` -- a sage element of a FractionField of polynomials over the rationals - - ``_ ring`` -- a (pointer to) a singular ring, where the resul will live + - ``_ ring`` -- a (pointer to) a singular ring, where the result will live OUTPUT: @@ -1365,7 +1372,7 @@ cdef number *sa2si_NF(object elem, ring *_ring) noexcept: - ``elem`` -- a sage element of a NumberField - - ``_ ring`` -- a (pointer to) a singular ring, where the resul will live + - ``_ ring`` -- a (pointer to) a singular ring, where the result will live OUTPUT: @@ -1457,7 +1464,7 @@ cdef number *sa2si_ZZ(Integer d, ring *_ring) noexcept: - ``elem`` -- a sage Integer - - ``_ ring`` -- a (pointer to) a singular ring, where the resul will live + - ``_ ring`` -- a (pointer to) a singular ring, where the result will live OUTPUT: @@ -1488,7 +1495,7 @@ cdef inline number *sa2si_ZZmod(IntegerMod_abstract d, ring *_ring) noexcept: - ``elem`` -- a sage IntegerMod - - ``_ ring`` -- a (pointer to) a singular ring, where the resul will live + - ``_ ring`` -- a (pointer to) a singular ring, where the result will live TESTS:: @@ -1512,7 +1519,7 @@ cdef inline number *sa2si_ZZmod(IntegerMod_abstract d, ring *_ring) noexcept: sage: P. = Integers(2^32)[] sage: P(2^32-1) - 4294967295 + -1 sage: P(3) 3 @@ -1534,6 +1541,9 @@ cdef inline number *sa2si_ZZmod(IntegerMod_abstract d, ring *_ring) noexcept: cdef nMapFunc nMapFuncPtr = NULL + if _ring.cf.type == n_unknown: + return n_Init(int(d), _ring.cf) + if _ring.cf.type == n_Z2m: _d = d return nr2mMapZp(_d, currRing.cf, _ring.cf) @@ -1577,7 +1587,7 @@ cdef object si2sa(number *n, ring *_ring, object base): An element of ``base`` """ - if isinstance(base, FiniteField_prime_modn): + if isinstance(base, FiniteField_prime_modn) and _ring.cf.type == n_Zp: return base(_ring.cf.cfInt(n, _ring.cf)) elif isinstance(base, RationalField): @@ -1605,8 +1615,6 @@ cdef object si2sa(number *n, ring *_ring, object base): return si2sa_transext_FF(n, _ring, base) elif isinstance(base, IntegerModRing_generic): - if _ring.cf.type == n_unknown: - return base(_ring.cf.cfInt(n, _ring.cf)) return si2sa_ZZmod(n, _ring, base) else: @@ -1628,7 +1636,8 @@ cdef number *sa2si(Element elem, ring * _ring) noexcept: a (pointer to) a singular number """ cdef int i = 0 - if isinstance(elem._parent, FiniteField_prime_modn): + + if isinstance(elem._parent, FiniteField_prime_modn) and _ring.cf.type == n_Zp: return n_Init(int(elem),_ring.cf) elif isinstance(elem._parent, RationalField): @@ -1649,8 +1658,6 @@ cdef number *sa2si(Element elem, ring * _ring) noexcept: elif isinstance(elem._parent, NumberField) and elem._parent.is_absolute(): return sa2si_NF(elem, _ring) elif isinstance(elem._parent, IntegerModRing_generic): - if _ring.cf.type == n_unknown: - return n_Init(int(elem),_ring.cf) return sa2si_ZZmod(elem, _ring) elif isinstance(elem._parent, FractionField_generic) and isinstance(elem._parent.base(), (MPolynomialRing_libsingular, PolynomialRing_field)): if isinstance(elem._parent.base().base_ring(), RationalField): @@ -1806,9 +1813,99 @@ saved_PATH = os.environ["PATH"] init_libsingular() os.environ["PATH"] = saved_PATH +cdef bint catching_error = False + cdef void libsingular_error_callback(const_char_ptr s) noexcept: _s = char_to_str(s) - error_messages.append(_s) + if catching_error: + error_messages.append(_s) + else: + warn(f"error in Singular ignored: {_s}") + +cdef int start_catch_error() except -1: + """ + Helper function to convert Singular errors to Python exceptions. + + Must be used as follows:: + + start_catch_error() + ... + s = check_error() # nonempty tuple[str, ...] (error messages) or None + if s: + # at this point global variable ``error_messages`` is cleared + raise RuntimeError(...) + + Return value is ignored, only used for exception handling. + + Note that :func:`check_error` can only be called exactly once. + + Note that this *must not* be used in conjunction with :func:`sig_on` as follows:: + + start_catch_error() + sig_on() + ... + sig_off() + if check_error(): + raise RuntimeError(...) + + because if the code is interrupted, then :func:`check_error` is never called. + + Use the following instead:: + + start_catch_error() + try: + sig_on() + ... # long time + sig_off() + finally: + if check_error(): + raise RuntimeError(...) + + If the code inside (marked `# long time`) can also raise a Python exception, + the above is still wrong --- :func:`sig_off` may not be called. In this case + use a nested ``try`` as suggested in ``cysignals`` documentation:: + + start_catch_error() + try: + sig_on() # This must be OUTSIDE the inner try + try: + ... # long time + finally: + sig_off() + finally: + if check_error(): + raise RuntimeError(...) + """ + global errorreported, catching_error, error_messages + if catching_error: + warn("internal error: previous start_catch_error not ended with check_error") + catching_error = True + + if errorreported: + warn(f"error in Singular ignored: {', '.join(error_messages)}") + errorreported = False + error_messages.clear() + else: + assert not error_messages + return 0 + +cdef object check_error(): + """ + See :func:`start_catch_error`. + """ + global errorreported, catching_error, error_messages + if not catching_error: + warn("internal error: check_error not preceded with start_catch_error") + catching_error = False + + if errorreported: + result = tuple(error_messages) + assert result + errorreported = False + error_messages.clear() + return result + assert not error_messages + return None def get_resource(id): diff --git a/src/sage/rings/polynomial/multi_polynomial_element.py b/src/sage/rings/polynomial/multi_polynomial_element.py index a22330ef4b8..3b18664f505 100644 --- a/src/sage/rings/polynomial/multi_polynomial_element.py +++ b/src/sage/rings/polynomial/multi_polynomial_element.py @@ -636,12 +636,12 @@ def degree(self, x=None, std_grading=False): sage: GF(3037000453)['x','y'].gen(0).degree(x0) # needs sage.rings.finite_rings Traceback (most recent call last): ... - TypeError: x must canonically coerce to parent + TypeError: argument is not coercible to the parent sage: GF(3037000453)['x','y'].gen(0).degree(x^2) # needs sage.rings.finite_rings Traceback (most recent call last): ... - TypeError: x must be one of the generators of the parent + TypeError: argument is not a generator TESTS:: @@ -817,7 +817,7 @@ def monomial_coefficients(self, copy=None): ``dict`` is an alias:: - sage: f.dict() # needs sage.rings.number_field + sage: f.dict() # needs sage.rings.number_field {(1, 5, 2): 1, (2, 0, 1): 1, (4, 1, 3): 1} """ return self.element().dict() diff --git a/src/sage/rings/polynomial/multi_polynomial_ideal.py b/src/sage/rings/polynomial/multi_polynomial_ideal.py index 8db6eb03ea6..f4f26449941 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ideal.py +++ b/src/sage/rings/polynomial/multi_polynomial_ideal.py @@ -4528,8 +4528,7 @@ def groebner_basis(self, algorithm='', deg_bound=None, mult_bound=None, prot=Fal sage: R. = PolynomialRing(Zmod(2233497349584)) sage: I = R.ideal([z*(x-3*y), 3^2*x^2-y*z, z^2+y^2]) sage: I.groebner_basis() - [2*z^4, y*z^2 + 81*z^3, 248166372176*z^3, 9*x^2 - y*z, y^2 + z^2, x*z + - 2233497349581*y*z, 248166372176*y*z] + [2*z^4, y*z^2 + 81*z^3, 248166372176*z^3, 9*x^2 + 2233497349583*y*z, y^2 + z^2, x*z + 2233497349581*y*z, 248166372176*y*z] Sage also supports local orderings:: diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx index 9c940755987..0d2cf86deeb 100644 --- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx @@ -65,7 +65,7 @@ We show how to construct various multivariate polynomial rings:: sage: P. = Zmod(25213521351515232)[]; P Multivariate Polynomial Ring in x, y, z over Ring of integers modulo 25213521351515232 sage: type(P) - + We construct the Frobenius morphism on `\GF{5}[x,y,z]` over `\GF{5}`:: @@ -170,6 +170,8 @@ AUTHORS: # * pNext and pIter don't need currRing # * p_Normalize apparently needs currRing +from warnings import warn + from cpython.object cimport Py_NE from cysignals.memory cimport sig_malloc, sig_free from cysignals.signals cimport sig_on, sig_off @@ -183,7 +185,6 @@ from sage.libs.singular.decl cimport (ring, poly, ideal, intvec, number, # singular functions from sage.libs.singular.decl cimport ( - errorreported, n_Invers, n_GetChar, p_ISet, rChangeCurrRing, p_Copy, p_Init, p_SetCoeff, p_Setm, p_SetExp, p_Add_q, p_NSet, p_GetCoeff, p_Delete, p_GetExp, pNext, rRingVar, omAlloc0, omStrDup, @@ -198,7 +199,7 @@ from sage.libs.singular.decl cimport ( prCopyR, prCopyR_NoSort) # singular conversion routines -from sage.libs.singular.singular cimport si2sa, sa2si, overflow_check +from sage.libs.singular.singular cimport si2sa, sa2si, overflow_check, start_catch_error, check_error # singular poly arith from sage.libs.singular.polynomial cimport ( @@ -212,6 +213,8 @@ from sage.libs.singular.polynomial cimport ( # singular rings from sage.libs.singular.ring cimport singular_ring_new, singular_ring_reference, singular_ring_delete +from sage.rings.finite_rings.finite_field_prime_modn import FiniteField_prime_modn + # polynomial imports from sage.rings.polynomial.multi_polynomial_ring import MPolynomialRing_polydict, MPolynomialRing_polydict_domain from sage.rings.polynomial.multi_polynomial_ring_base import BooleanPolynomialRing_base @@ -340,11 +343,11 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base): Multivariate Polynomial Ring in x, y, z over Ring of integers modulo 25213521351515232 sage: type(P) - + sage: P. = PolynomialRing(Integers(2^32), order='lex') sage: P(2^32-1) - 4294967295 + -1 TESTS: @@ -4151,6 +4154,37 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): True sage: p*q//p == q True + + Test many base rings:: + + sage: R. = GF(2^32+15)[] + sage: ((x+y)^3+x+z)//(x+y) + Traceback (most recent call last): + ... + NotImplementedError: Division of multivariate polynomials over non fields by non-monomials not implemented. + sage: R. = Zmod(2^29-3)[] + sage: ((x+y)^3+x+z)//(x+y) + Traceback (most recent call last): + ... + NotImplementedError: Division of multivariate polynomials over non fields by non-monomials not implemented. + sage: R. = GF(2^29+11)[] + sage: ((x+y)^3+x+z)//(x+y) + Traceback (most recent call last): + ... + NotImplementedError: Division of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented. + sage: R. = Zmod(2^29+10)[] + sage: ((x+y)^3+x+z)//(x+y) + Traceback (most recent call last): + ... + NotImplementedError: Division of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented. + sage: R. = GF((2^29-3)^2)[] + sage: ((x+y)^3+x+z)//(x+y) + x^2 + 2*x*y + y^2 + sage: R. = Zmod(7^2)[] + sage: ((x+y)^3+x+z)//(x+y) + Traceback (most recent call last): + ... + NotImplementedError: Division of multivariate polynomials over non fields by non-monomials not implemented. """ cdef MPolynomialRing_libsingular parent = self._parent cdef MPolynomial_libsingular _right = right @@ -4461,12 +4495,58 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): sage: N = -a^4*z^8 + 2*a^2*b^2*z^8 - b^4*z^8 - 16*a^3*b*z^7 + 16*a*b^3*z^7 + 28*a^4*z^6 - 56*a^2*b^2*z^6 + 28*b^4*z^6 + 112*a^3*b*z^5 - 112*a*b^3*z^5 - 70*a^4*z^4 + 140*a^2*b^2*z^4 - 70*b^4*z^4 - 112*a^3*b*z^3 + 112*a*b^3*z^3 + 28*a^4*z^2 - 56*a^2*b^2*z^2 + 28*b^4*z^2 + 16*a^3*b*z - 16*a*b^3*z - a^4 + 2*a^2*b^2 - b^4 sage: N.factor() (-1) * (-a + b) * (a + b) * (-z^4*a + z^4*b - 4*z^3*a - 4*z^3*b + 6*z^2*a - 6*z^2*b + 4*z*a + 4*z*b - a + b) * (z^4*a + z^4*b - 4*z^3*a + 4*z^3*b - 6*z^2*a - 6*z^2*b + 4*z*a - 4*z*b + a + b) + + Test many base rings:: + + sage: R. = GF(2^32+15)[] + sage: ((x+y)^2*(x+z)^3).factor() + Traceback (most recent call last): + ... + NotImplementedError: Factorization of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented. + sage: R. = Zmod(2^29-3)[] + sage: ((x+y)^2*(x+z)^3).factor() + (x + y)^2 * (x + z)^3 + sage: R. = GF(2^29+11)[] + sage: ((x+y)^2*(x+z)^3).factor() + Traceback (most recent call last): + ... + NotImplementedError: Factorization of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented. + sage: R. = Zmod(2^29+10)[] + sage: ((x+y)^2*(x+z)^3).factor() + Traceback (most recent call last): + ... + NotImplementedError: Factorization of multivariate polynomials over Ring of integers modulo 536870922 is not implemented. + sage: R. = GF((2^29-3)^2)[] + sage: ((x+y)^2*(x+z)^3).factor() + (x + y)^2 * (x + z)^3 + sage: R. = Zmod(7^2)[] + sage: ((x+y)^2*(x+z)^3).factor() + Traceback (most recent call last): + ... + NotImplementedError: Factorization of multivariate polynomials over Ring of integers modulo 49 is not implemented. + + Ensure interrupt does not make the internal state inconsistent:: + + sage: R. = QQ[] + sage: n = 11 # chosen so that the computation takes > 1 second but not excessively long. + ....: # when Singular improves the algorithm or hardware gets faster, increase n. + sage: alarm(0.5); h = (x^2^n-y^2^n).factor() + Traceback (most recent call last): + ... + AlarmInterrupt + sage: alarm(0.5); h = (x^2^n-y^2^n).factor() + Traceback (most recent call last): + ... + AlarmInterrupt + sage: h = (x^2^n-y^2^n).factor() + sage: h + (x - y) * (x + y) * (x^2 + y^2) * (x^4 + y^4) * (x^8 + y^8) * (x^16 + y^16) * (x^32 + y^32) * (x^64 + y^64) * (x^128 + y^128) * (x^256 + y^256) * (x^512 + y^512) * (x^1024 + y^1024) """ cdef ring *_ring = self._parent_ring cdef poly *ptemp cdef intvec *iv cdef int *ivv - cdef ideal *I + cdef ideal *I = NULL cdef MPolynomialRing_libsingular parent = self._parent cdef int i @@ -4485,31 +4565,31 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): except Exception: raise NotImplementedError("Factorization of multivariate polynomials over %s is not implemented."%self._parent._base) - if n_GetChar(_ring.cf) > 1<<29: - raise NotImplementedError("Factorization of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented.") - - # I make a temporary copy of the poly in self because singclap_factorize appears to modify it's parameter - ptemp = p_Copy(self._poly, _ring) iv = NULL - sig_on() if _ring != currRing: rChangeCurrRing(_ring) # singclap_factorize - I = singclap_factorize(ptemp, &iv, 0, _ring) - sig_off() - - ivv = iv.ivGetVec() - v = [(new_MP(parent, p_Copy(I.m[i], _ring)), ivv[i]) - for i in range(1, I.ncols)] - v = [(f, m) for f, m in v if f != 0] # we might have zero in there - unit = new_MP(parent, p_Copy(I.m[0], _ring)) - - F = Factorization(v, unit) - F.sort() - - del iv - id_Delete(&I, _ring) - - return F + start_catch_error() + try: + try: + sig_on() + I = singclap_factorize(p_Copy(self._poly, _ring), &iv, 0, _ring) + sig_off() + finally: + if check_error(): + raise NotImplementedError("Factorization of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented.") + + ivv = iv.ivGetVec() + v = [(new_MP(parent, p_Copy(I.m[i], _ring)), ivv[i]) + for i in range(1, I.ncols)] + v = [(f, m) for f, m in v if f != 0] # we might have zero in there + unit = new_MP(parent, p_Copy(I.m[0], _ring)) + + F = Factorization(v, unit) + F.sort() + return F + finally: + del iv + id_Delete(&I, _ring) def lift(self, I): """ @@ -4559,7 +4639,6 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): sage: M [y^7, x^7*y^2 + x^8 + x^5*y^3 + x^6*y + x^3*y^4 + x^4*y^2 + x*y^5 + x^2*y^3 + y^4] - TESTS: Check that :issue:`13714` is fixed:: @@ -4573,16 +4652,32 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): sage: foo = I.complete_primary_decomposition() # indirect doctest sage: foo[0][0] Ideal (x1 + 1, x2^2 - 3) of Multivariate Polynomial Ring in x1, x2 over Rational Field - """ - global errorreported + Ensure interrupt does not make the internal state inconsistent:: + + sage: R. = QQ[] + sage: n = 17 # chosen so that the computation takes > 1 second but not excessively long. + ....: # when Singular improves the algorithm or hardware gets faster, increase n. + sage: I = R.ideal([(x-i)*(y-j) for i in (0..n) for j in (0..n)]) + sage: f = prod((x-i)*(y-j) for i in (0..n) for j in (0..n)) + sage: alarm(0.5); f.lift(I) + Traceback (most recent call last): + ... + AlarmInterrupt + sage: alarm(0.5); f.lift(I) + Traceback (most recent call last): + ... + AlarmInterrupt + sage: f.lift(I) + Polynomial Sequence with 324 Polynomials in 2 Variables + """ cdef ideal *fI = idInit(1, 1) cdef ideal *_I cdef MPolynomialRing_libsingular parent = self._parent cdef int i = 0 cdef int j cdef ring *r = self._parent_ring - cdef ideal *res + cdef ideal *res = NULL if isinstance(I, MPolynomialIdeal): I = I.gens() @@ -4606,24 +4701,25 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): if r != currRing: rChangeCurrRing(r) # idLift - sig_on() - res = idLift(_I, fI, NULL, 0, 0, 0) - sig_off() - if errorreported != 0: - errorcode = errorreported - errorreported = 0 - if errorcode == 1: + try: + start_catch_error() + try: + sig_on() + res = idLift(_I, fI, NULL, 0, 0, 0) + sig_off() + finally: + s = check_error() + if s: + if s != ('2nd module does not lie in the first',): + warn(f'unexpected error from singular: {s}') raise ValueError("polynomial is not in the ideal") - raise RuntimeError - - l = [] - for i from 0 <= i < IDELEMS(res): - for j from 1 <= j <= IDELEMS(_I): - l.append( new_MP(parent, pTakeOutComp(&res.m[i], 1)) ) - id_Delete(&fI, r) - id_Delete(&_I, r) - id_Delete(&res, r) + l = [new_MP(parent, pTakeOutComp(&res.m[i], 1)) + for i in range(IDELEMS(res)) for _ in range(IDELEMS(_I))] + finally: + id_Delete(&fI, r) + id_Delete(&_I, r) + id_Delete(&res, r) return Sequence(l, check=False, immutable=True) def reduce(self, I): @@ -4731,7 +4827,8 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): id_Delete(&_I,r) return new_MP(parent,res) - def divides(self, other): + @coerce_binop + def divides(self, MPolynomial_libsingular other): """ Return ``True`` if this polynomial divides ``other``. @@ -4763,27 +4860,21 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): rChangeCurrRing(r) _I = idInit(1, 1) - if not (isinstance(other,MPolynomial_libsingular) - and (other)._parent is parent): - try: - other = parent.coerce(other) - except TypeError as msg: - id_Delete(&_I,r) - raise TypeError(msg) - _I.m[0] = p_Copy(self._poly, r) if r != currRing: rChangeCurrRing(r) - sig_on() - rem = kNF(_I, NULL, (other)._poly, 0, 1) - sig_off() - id_Delete(&_I, r) + try: + sig_on() + rem = kNF(_I, NULL, other._poly, 0, 1) + sig_off() + finally: + id_Delete(&_I, r) res = new_MP(parent, rem).is_zero() return res @coerce_binop - def gcd(self, right, algorithm=None, **kwds): + def gcd(self, MPolynomial_libsingular right, algorithm=None, **kwds): """ Return the greatest common divisor of ``self`` and ``right``. @@ -4858,10 +4949,40 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): sage: q = -3*x^2*y^7*z + 2*x*y^6*z^3 + 2*x^2*y^3*z^4 + x^2*y^5 - 7*x*y^5*z sage: (21^3*p^2*q).gcd(35^2*p*q^2) == -49*p*q True + + Test many base rings:: + + sage: R. = GF(2^32+15)[] + sage: ((x+y)^2*(x+z)^3).gcd((x+y)^3*(y+z)^5) + Traceback (most recent call last): + ... + NotImplementedError: GCD over rings not implemented. + sage: R. = Zmod(2^29-3)[] + sage: ((x+y)^2*(x+z)^3).gcd((x+y)^3*(y+z)^5) + Traceback (most recent call last): + ... + NotImplementedError: GCD over rings not implemented. + sage: R. = GF(2^29+11)[] + sage: ((x+y)^2*(x+z)^3).gcd((x+y)^3*(y+z)^5) + Traceback (most recent call last): + ... + NotImplementedError: GCD of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented. + sage: R. = Zmod(2^29+10)[] + sage: ((x+y)^2*(x+z)^3).gcd((x+y)^3*(y+z)^5) + Traceback (most recent call last): + ... + NotImplementedError: GCD over rings not implemented. + sage: R. = GF((2^29-3)^2)[] + sage: ((x+y)^2*(x+z)^3).gcd((x+y)^3*(y+z)^5) + x^2 + 2*x*y + y^2 + sage: R. = Zmod(7^2)[] + sage: ((x+y)^2*(x+z)^3).gcd((x+y)^3*(y+z)^5) + Traceback (most recent call last): + ... + NotImplementedError: GCD over rings not implemented. """ cdef poly *_res cdef ring *_ring = self._parent_ring - cdef MPolynomial_libsingular _right = right if algorithm is None or algorithm == "modular": On(SW_USE_CHINREM_GCD) @@ -4872,13 +4993,13 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): else: raise TypeError("algorithm %s not supported" % algorithm) - if _right._poly == NULL: + if right._poly == NULL: return self elif self._poly == NULL: return right elif p_IsOne(self._poly, _ring): return self - elif p_IsOne(_right._poly, _ring): + elif p_IsOne(right._poly, _ring): return right if _ring.cf.type != n_unknown: @@ -4889,10 +5010,10 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): raise NotImplementedError("GCD of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented.") cdef int count = singular_polynomial_length_bounded(self._poly, 20) \ - + singular_polynomial_length_bounded(_right._poly,20) + + singular_polynomial_length_bounded(right._poly, 20) if count >= 20: sig_on() - _res = singclap_gcd(p_Copy(self._poly, _ring), p_Copy(_right._poly, _ring), _ring ) + _res = singclap_gcd(p_Copy(self._poly, _ring), p_Copy(right._poly, _ring), _ring) if count >= 20: sig_off() @@ -4944,6 +5065,37 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): 2*x*y sage: lcm(2*x, 2*x*y) 2*x*y + + Test many base rings:: + + sage: R. = GF(2^32+15)[] + sage: ((x+y)^2*(x+z)^3).lcm((x+y)^3*(y+z)^5) + Traceback (most recent call last): + ... + TypeError: LCM over non-integral domains not available. + sage: R. = Zmod(2^29-3)[] + sage: ((x+y)^2*(x+z)^3).lcm((x+y)^3*(y+z)^5) + Traceback (most recent call last): + ... + TypeError: LCM over non-integral domains not available. + sage: R. = GF(2^29+11)[] + sage: ((x+y)^2*(x+z)^3).lcm((x+y)^3*(y+z)^5) + Traceback (most recent call last): + ... + NotImplementedError: LCM of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented. + sage: R. = Zmod(2^29+10)[] + sage: ((x+y)^2*(x+z)^3).lcm((x+y)^3*(y+z)^5) + Traceback (most recent call last): + ... + TypeError: LCM over non-integral domains not available. + sage: R. = GF((2^29-3)^2)[] + sage: ((x+y)^2*(x+z)^3).lcm((x+y)^3*(y+z)^5) + x^6*y^5 + 3*x^5*y^6 + 3*x^4*y^7 + x^3*y^8 + 5*x^6*y^4*z + 18*x^5*y^5*z + 24*x^4*y^6*z + 14*x^3*y^7*z + 3*x^2*y^8*z + 10*x^6*y^3*z^2 + 45*x^5*y^4*z^2 + 78*x^4*y^5*z^2 + 64*x^3*y^6*z^2 + 24*x^2*y^7*z^2 + 3*x*y^8*z^2 + 10*x^6*y^2*z^3 + 60*x^5*y^3*z^3 + 135*x^4*y^4*z^3 + 146*x^3*y^5*z^3 + 78*x^2*y^6*z^3 + 18*x*y^7*z^3 + y^8*z^3 + 5*x^6*y*z^4 + 45*x^5*y^2*z^4 + 135*x^4*y^3*z^4 + 190*x^3*y^4*z^4 + 135*x^2*y^5*z^4 + 45*x*y^6*z^4 + 5*y^7*z^4 + x^6*z^5 + 18*x^5*y*z^5 + 78*x^4*y^2*z^5 + 146*x^3*y^3*z^5 + 135*x^2*y^4*z^5 + 60*x*y^5*z^5 + 10*y^6*z^5 + 3*x^5*z^6 + 24*x^4*y*z^6 + 64*x^3*y^2*z^6 + 78*x^2*y^3*z^6 + 45*x*y^4*z^6 + 10*y^5*z^6 + 3*x^4*z^7 + 14*x^3*y*z^7 + 24*x^2*y^2*z^7 + 18*x*y^3*z^7 + 5*y^4*z^7 + x^3*z^8 + 3*x^2*y*z^8 + 3*x*y^2*z^8 + y^3*z^8 + sage: R. = Zmod(7^2)[] + sage: ((x+y)^2*(x+z)^3).lcm((x+y)^3*(y+z)^5) + Traceback (most recent call last): + ... + TypeError: LCM over non-integral domains not available. """ cdef ring *_ring = self._parent_ring cdef poly *ret @@ -5026,6 +5178,56 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): Traceback (most recent call last): ... ZeroDivisionError + + Test many base rings:: + + sage: R. = GF(2^32+15)[] + sage: ((x+y)^3+x+z).quo_rem(x+y) + Traceback (most recent call last): + ... + NotImplementedError: Division of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented. + sage: R. = Zmod(2^29-3)[] + sage: ((x+y)^3+x+z).quo_rem(x+y) + (x^2 + 2*x*y + y^2, x + z) + sage: R. = GF(2^29+11)[] + sage: ((x+y)^3+x+z).quo_rem(x+y) + Traceback (most recent call last): + ... + NotImplementedError: Division of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented. + sage: R. = Zmod(2^29+10)[] + sage: ((x+y)^3+x+z).quo_rem(x+y) + Traceback (most recent call last): + ... + NotImplementedError: Division of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented. + sage: R. = GF((2^29-3)^2)[] + sage: ((x+y)^3+x+z).quo_rem(x+y) + (x^2 + 2*x*y + y^2, x + z) + sage: R. = Zmod(7^2)[] + sage: ((x+y)^3+x+z).quo_rem(x+y) + Traceback (most recent call last): + ... + NotImplementedError: Division of multivariate polynomials over non fields by non-monomials not implemented. + + Ensure interrupt does not make the internal state inconsistent:: + + sage: R. = PolynomialRing(QQ, order="lex") + sage: n = 300 # chosen so that the computation takes > 1 second but not excessively long. + ....: # when Singular improves the algorithm or hardware gets faster, increase n. + sage: f = z^n-2 + sage: g = z^2-z-x^2*y-x*y^3 + sage: alarm(0.5); f.quo_rem(g) + Traceback (most recent call last): + ... + AlarmInterrupt + sage: alarm(0.5); f.quo_rem(g) + Traceback (most recent call last): + ... + AlarmInterrupt + sage: q, r = f.quo_rem(g) + sage: len(dict(q)) + 307638 + sage: len(dict(r)) + 11409 """ cdef poly *quo cdef poly *rem @@ -5041,17 +5243,17 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): py_rem = self - right*py_quo return py_quo, py_rem - if n_GetChar(r.cf) > 1<<29: - raise NotImplementedError("Division of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented.") - - cdef int count = singular_polynomial_length_bounded(self._poly, 15) - if count >= 15: # note that _right._poly must be of shorter length than self._poly for us to care about this call + if r != currRing: + rChangeCurrRing(r) # singclap_pdivide + start_catch_error() + try: sig_on() - if r!=currRing: rChangeCurrRing(r) # singclap_pdivide - quo = singclap_pdivide( self._poly, right._poly, r ) - rem = p_Add_q(p_Copy(self._poly, r), p_Neg(pp_Mult_qq(right._poly, quo, r), r), r) - if count >= 15: + quo = singclap_pdivide(self._poly, right._poly, r) sig_off() + finally: + if check_error(): + raise NotImplementedError("Division of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented.") + rem = p_Add_q(p_Copy(self._poly, r), p_Neg(pp_Mult_qq(right._poly, quo, r), r), r) return new_MP(parent, quo), new_MP(parent, rem) def _singular_init_(self, singular=None): @@ -5424,6 +5626,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): _p = p_Add_q(_p, mon, _ring) return new_MP(self._parent, _p) + @coerce_binop def resultant(self, MPolynomial_libsingular other, variable=None): """ Compute the resultant of this polynomial and the first @@ -5479,40 +5682,91 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): sage: g=y^2+x sage: f.resultant(g,y) x^2 + x + + sage: R. = GF(2^32+15)[] + sage: (x-z).resultant(y-z,z) + Traceback (most recent call last): + ... + NotImplementedError: Resultants of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented. + sage: R. = Zmod(2^29-3)[] + sage: (x-z).resultant(y-z,z) + x + 536870908*y + sage: R. = GF(2^29+11)[] + sage: (x-z).resultant(y-z,z) + Traceback (most recent call last): + ... + NotImplementedError: Resultants of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented. + sage: R. = Zmod(2^29+10)[] + sage: (x-z).resultant(y-z,z) + Traceback (most recent call last): + ... + NotImplementedError: Resultants require base fields or integer base ring. + sage: R. = GF((2^29-3)^2)[] + sage: (x-z).resultant(y-z,z) + x - y + sage: R. = Zmod(7^2)[] + sage: (x-z).resultant(y-z,z) + Traceback (most recent call last): + ... + NotImplementedError: Resultants require base fields or integer base ring. + + Sometimes simple-looking computations can take a long time:: + + sage: R. = QQ[] + sage: n = 22 # chosen so that the computation takes > 1 second but not excessively long. + ....: # when Singular improves the algorithm or hardware gets faster, increase n. + sage: f = x^n+y^(n-1)+z^(n-2)+y^3*z^2 + sage: g = x^(n-3)+y^(n-4)+z^(n-5)+y*z + sage: h = f.resultant(g, x) + sage: len(dict(h)) + 89 + + As such we test the computation is interruptible (previously it wasn't):: + + sage: alarm(0.5); h = f.resultant(g, x) + Traceback (most recent call last): + ... + AlarmInterrupt + + Test again to ensure interrupt does not make the internal state inconsistent:: + + sage: alarm(0.5); h = f.resultant(g, x); cancel_alarm() + Traceback (most recent call last): + ... + AlarmInterrupt + sage: h = f.resultant(g, x) + sage: len(dict(h)) + 89 """ cdef ring *_ring = self._parent_ring cdef poly *rt if variable is None: variable = self.parent().gen(0) - - if self._parent is not other._parent: - raise TypeError("first parameter needs to be an element of self.parent()") - - if not variable.parent() is self.parent(): + elif variable.parent() is not self.parent(): raise TypeError("second parameter needs to be an element of self.parent() or None") - if n_GetChar(_ring.cf) > 1<<29: - raise NotImplementedError("Resultants of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented.") - if isinstance(self._parent._base, IntegerRing_class): ret = self.change_ring(QQ).resultant(other.change_ring(QQ), variable.change_ring(QQ)) return ret.change_ring(ZZ) - elif not self._parent._base.is_field(): - raise ValueError("Resultants require base fields or integer base ring.") - cdef int count = singular_polynomial_length_bounded(self._poly, 20) \ - + singular_polynomial_length_bounded(other._poly,20) - if count >= 20: + start_catch_error() + try: sig_on() - if _ring != currRing: rChangeCurrRing(_ring) # singclap_resultant - rt = singclap_resultant(p_Copy(self._poly, _ring), - p_Copy(other._poly, _ring), - p_Copy((variable)._poly, _ring ), - _ring) - if count >= 20: + if _ring != currRing: + rChangeCurrRing(_ring) # singclap_resultant + rt = singclap_resultant(p_Copy(self._poly, _ring), + p_Copy(other._poly, _ring), + p_Copy((variable)._poly, _ring), + _ring) sig_off() + finally: + if check_error(): + if isinstance(self._parent._base, FiniteField_prime_modn): + raise NotImplementedError("Resultants of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented.") + raise NotImplementedError("Resultants require base fields or integer base ring.") + return new_MP(self._parent, rt) def coefficients(self): diff --git a/src/sage/rings/quotient_ring.py b/src/sage/rings/quotient_ring.py index c867ba41bbc..7e3dd8c6d53 100644 --- a/src/sage/rings/quotient_ring.py +++ b/src/sage/rings/quotient_ring.py @@ -502,7 +502,7 @@ def __init__(self, R, I, names, category=None): # However, we don't just want to use the given category without mixing in # some quotient stuff - unless Parent.__init__ was called # previously, in which case the quotient ring stuff is just - # a vaste of time. This is the case for FiniteField_prime_modn. + # a waste of time. This is the case for FiniteField_prime_modn. if not self._is_category_initialized(): if category is None: try: