From db4139091e9c524779271c45aa8450892107fc3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Thu, 28 Oct 2021 21:12:10 +0200 Subject: [PATCH 01/15] fix most E722 (first pass) --- .../dynamics/arithmetic_dynamics/berkovich_ds.py | 12 ++++++------ src/sage/geometry/polyhedron/base.py | 2 +- src/sage/geometry/polyhedron/library.py | 2 +- src/sage/graphs/digraph.py | 6 +++--- src/sage/interfaces/polymake.py | 4 ++-- src/sage/modules/free_module.py | 2 +- src/sage/modules/matrix_morphism.py | 6 ++---- src/sage/rings/qqbar.py | 2 +- src/sage/schemes/berkovich/berkovich_space.py | 2 +- .../schemes/product_projective/rational_point.py | 7 ++++--- src/sage/schemes/projective/projective_space.py | 4 ++-- 11 files changed, 24 insertions(+), 25 deletions(-) diff --git a/src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py b/src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py index 8f8578ef8b9..c1cb33e12b5 100644 --- a/src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py +++ b/src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py @@ -238,21 +238,21 @@ def __classcall_private__(cls, dynamical_system, domain=None, ideal=None): if not isinstance(dynamical_system, DynamicalSystem_affine): try: dynamical_system = DynamicalSystem_affine(dynamical_system) - except: + except (TypeError, ValueError): raise TypeError('domain was affine Berkovich space, but dynamical_system did not ' + \ 'convert to an affine dynamical system') if isinstance(domain, Berkovich_Cp_Projective): if not isinstance(dynamical_system, DynamicalSystem_projective): try: dynamical_system = DynamicalSystem_projective(dynamical_system) - except: + except (TypeError, ValueError): raise TypeError('domain was projective Berkovich space, but dynamical_system did not convert ' + \ 'to a projective dynamical system') if not isinstance(dynamical_system, DynamicalSystem): try: dynamical_system = DynamicalSystem(dynamical_system) - except: + except (TypeError, ValueError): raise TypeError('dynamical_system did not convert to a dynamical system') morphism_domain = dynamical_system.domain() @@ -803,7 +803,7 @@ def __call__(self, x, type_3_pole_check=True): if not isinstance(x.parent(), Berkovich_Cp_Projective): try: x = self.domain()(x) - except: + excep (TypeError, ValueError)t: raise TypeError('action of dynamical system not defined on %s' %x.parent()) if x.parent().is_padic_base() != self.domain().is_padic_base(): raise ValueError('x was not backed by the same type of field as f') @@ -893,7 +893,7 @@ def __call__(self, x, type_3_pole_check=True): try: factor_root_field = factor.root_field('a') factor = factor.change_ring(factor_root_field) - except: + except (TypeError, ValueError): raise NotImplementedError('cannot check if poles lie in type III disk') else: factor_root_field = factor.base_ring() @@ -1078,7 +1078,7 @@ def __call__(self, x): if not isinstance(x, Berkovich_Element_Cp_Affine): try: x = self.domain()(x) - except: + except (TypeError, ValueError): raise ValueError('action of dynamical system not defined on %s' %x) proj_system = self.homogenize(1) return proj_system(x.as_projective_point()).as_affine_point() diff --git a/src/sage/geometry/polyhedron/base.py b/src/sage/geometry/polyhedron/base.py index e2e6772defb..2b547775b43 100644 --- a/src/sage/geometry/polyhedron/base.py +++ b/src/sage/geometry/polyhedron/base.py @@ -5275,7 +5275,7 @@ def _test_dilation(self, tester=None, **options): new_ring = None try: new_ring = self.base_ring().composite_fields()[0] - except: + except (KeyError, AttributeError): # This isn't about testing composite fields. pass if new_ring: diff --git a/src/sage/geometry/polyhedron/library.py b/src/sage/geometry/polyhedron/library.py index 31cec880ccf..8c90ca857db 100644 --- a/src/sage/geometry/polyhedron/library.py +++ b/src/sage/geometry/polyhedron/library.py @@ -2720,7 +2720,7 @@ def generalized_permutahedron(self, coxeter_type, point=None, exact=True, regula from sage.combinat.root_system.coxeter_group import CoxeterGroup try: W = CoxeterGroup(coxeter_type) - except: + except (TypeError, ValueError): raise ValueError("cannot build a Coxeter group from {}".format(coxeter_type)) n = W.one().canonical_matrix().rank() weights = W.fundamental_weights() diff --git a/src/sage/graphs/digraph.py b/src/sage/graphs/digraph.py index bcf919c4a7d..00bf0246033 100644 --- a/src/sage/graphs/digraph.py +++ b/src/sage/graphs/digraph.py @@ -3352,7 +3352,7 @@ def layout_acyclic_dummy(self, heights=None, rankdir='up', **options): try: l = sorted(levels[i]) levels[i] = l - except: + except TypeError: continue if rankdir=='down' or rankdir=='left': levels.reverse() @@ -3997,7 +3997,7 @@ def _rec_out_branchings(depth): # 2) Pick an edge e outgoing from the source try: s, x, l = next(D.outgoing_edge_iterator(source)) - except: + except StopIteration: return # 3) Find all out_branchings that do not contain e # by first removing it @@ -4214,7 +4214,7 @@ def _rec_in_branchings(depth): # 2) Pick an edge e incoming to the source try: x, s, l = next(D.incoming_edge_iterator(source)) - except: + except StopIteration: return # 3) Find all in_branchings that do not contain e # by first removing it diff --git a/src/sage/interfaces/polymake.py b/src/sage/interfaces/polymake.py index 632455564b2..1e20583a6ca 100644 --- a/src/sage/interfaces/polymake.py +++ b/src/sage/interfaces/polymake.py @@ -362,7 +362,7 @@ def to_str(x): try: x = RDF(x) return '{}'.format(x) - except: + except (TypeError, ValueError): pass raise NotImplementedError @@ -1593,7 +1593,7 @@ def str_to_base_ring(s): if r == '': return matrix(base_ring) return matrix(base_ring, [[str_to_base_ring(s) for s in t.split(' ')] for t in r.split('\n')]) - except: + except Exception: pass if T1: diff --git a/src/sage/modules/free_module.py b/src/sage/modules/free_module.py index 1e3c73da128..b3aa531d9b7 100644 --- a/src/sage/modules/free_module.py +++ b/src/sage/modules/free_module.py @@ -463,7 +463,7 @@ def FreeModule(base_ring, rank_or_basis_keys=None, sparse=False, inner_product_m if rank_or_basis_keys is not None: try: rank = sage.rings.integer_ring.ZZ(rank_or_basis_keys) - except: + except (TypeError, ValueError): basis_keys = rank_or_basis_keys if not with_basis: if inner_product_matrix is not None: diff --git a/src/sage/modules/matrix_morphism.py b/src/sage/modules/matrix_morphism.py index 58e670812ff..897eccb6878 100644 --- a/src/sage/modules/matrix_morphism.py +++ b/src/sage/modules/matrix_morphism.py @@ -1418,11 +1418,9 @@ def restrict_domain(self, sub): H = sub.Hom(self.codomain()) try: return H(A, side=self.side()) - except: + except Exception: return H(A) - - def restrict_codomain(self, sub): """ Restrict this matrix morphism to a subspace sub of the codomain. @@ -1503,7 +1501,7 @@ def restrict_codomain(self, sub): return H(self.matrix().transpose().restrict_codomain(V).transpose(), side="right") else: return H(self.matrix().restrict_codomain(V)) - except: + except Exception: return H(self.matrix().restrict_codomain(V)) def restrict(self, sub): diff --git a/src/sage/rings/qqbar.py b/src/sage/rings/qqbar.py index ae926cde625..01ba94413f8 100644 --- a/src/sage/rings/qqbar.py +++ b/src/sage/rings/qqbar.py @@ -2650,7 +2650,7 @@ def mk_algebraic(x): aa_numbers = [AA(_) for _ in numbers] numbers = aa_numbers real_case = True - except: + except (ValueError, TypeError): real_case = False # Make the numbers algebraic numbers = [mk_algebraic(_) for _ in numbers] diff --git a/src/sage/schemes/berkovich/berkovich_space.py b/src/sage/schemes/berkovich/berkovich_space.py index 51a0df0a14a..97b8a8266b7 100644 --- a/src/sage/schemes/berkovich/berkovich_space.py +++ b/src/sage/schemes/berkovich/berkovich_space.py @@ -619,7 +619,7 @@ def __init__(self, base, ideal=None): if not is_ProjectiveSpace(base): try: base = ProjectiveSpace(base) - except: + except (TypeError, ValueError): raise ValueError("base of projective Berkovich space must be projective space") if not (is_pAdicField(base.base_ring())): if base.base_ring() not in NumberFields(): diff --git a/src/sage/schemes/product_projective/rational_point.py b/src/sage/schemes/product_projective/rational_point.py index 5239fd88203..8f56fcd8637 100644 --- a/src/sage/schemes/product_projective/rational_point.py +++ b/src/sage/schemes/product_projective/rational_point.py @@ -494,11 +494,12 @@ def parallel_function_combination(point_p_max): continue try: - rat_points.add(X(point)) # checks if this point lies on X or not - except: + rat_points.add(X(point)) + # checks if this point lies on X or not + except (TypeError, ValueError): pass - return [list(_) for _ in rat_points] + return [list(pt) for pt in rat_points] def lift_all_points(): r""" diff --git a/src/sage/schemes/projective/projective_space.py b/src/sage/schemes/projective/projective_space.py index 82763ef7344..36deeab7827 100644 --- a/src/sage/schemes/projective/projective_space.py +++ b/src/sage/schemes/projective/projective_space.py @@ -1693,10 +1693,10 @@ def hyperplane_transformation_matrix(self, plane_1, plane_2): if len(source_points) == N: try: plane(point) - except: + except ValueError: source_points.append(self(point)) base_list = [list(s) for s in source_points] - elif len(source_points) == N+1: + elif len(source_points) == N + 1: Ms = matrix(base_list + [point]) if not any([m == 0 for m in Ms.minors(N + 1)]): source_points.append(self(point)) From cffd35e12c9fd4ef535654947ee167d3f9dfe55a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Thu, 28 Oct 2021 21:24:45 +0200 Subject: [PATCH 02/15] no except: in most pyx files --- src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx | 2 +- src/sage/graphs/graph_decompositions/tree_decomposition.pyx | 2 +- src/sage/plot/plot3d/shapes.pyx | 2 +- src/sage/rings/complex_arb.pyx | 2 +- src/sage/rings/polynomial/multi_polynomial_libsingular.pyx | 4 ++-- src/sage/rings/ring_extension_element.pyx | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx b/src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx index 7a6ee5aa51a..75358e0987c 100644 --- a/src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx +++ b/src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx @@ -763,7 +763,7 @@ cpdef polynomial_mandelbrot(f, parameter=None, double x_center=0, df = f.derivative(z).univariate_polynomial() critical_pts = df.roots(multiplicities=False) constant_c = True - except: + except PariError: constant_c = False # If c is in the constant term of the polynomial, then the critical points diff --git a/src/sage/graphs/graph_decompositions/tree_decomposition.pyx b/src/sage/graphs/graph_decompositions/tree_decomposition.pyx index e2608da8995..ac4248c00d9 100644 --- a/src/sage/graphs/graph_decompositions/tree_decomposition.pyx +++ b/src/sage/graphs/graph_decompositions/tree_decomposition.pyx @@ -209,7 +209,7 @@ def is_valid_tree_decomposition(G, T): for X in T: try: _ = list(X) - except: + except TypeError: raise ValueError("the vertices of T must be iterables") # 1. The union of the bags equals V diff --git a/src/sage/plot/plot3d/shapes.pyx b/src/sage/plot/plot3d/shapes.pyx index d45770c61b7..340f034c235 100644 --- a/src/sage/plot/plot3d/shapes.pyx +++ b/src/sage/plot/plot3d/shapes.pyx @@ -1360,7 +1360,7 @@ def _validate_threejs_text_style(style): if weight not in ['normal', 'bold']: try: weight = int(weight) - except: + except (TypeError, ValueError): from matplotlib.font_manager import weight_dict try: weight = weight_dict[weight] diff --git a/src/sage/rings/complex_arb.pyx b/src/sage/rings/complex_arb.pyx index 4e09e548f0a..a8f574439ff 100644 --- a/src/sage/rings/complex_arb.pyx +++ b/src/sage/rings/complex_arb.pyx @@ -295,7 +295,7 @@ cdef int acb_calc_func_callback(acb_ptr out, const acb_t inp, void * param, if not isinstance(y, ComplexBall): y = ctx.parent.coerce(y) acb_set(out, ( y).value) - except: + except Exception: ctx.exn_type, ctx.exn_obj, ctx.exn_tb = sys.exc_info() acb_indeterminate(out) return 0 diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx index 2c69227760c..5adfc245b92 100644 --- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx @@ -856,7 +856,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base): #we can use "Merge" because the monomials are distinct sBucketClearMerge(bucket, &_p, &e) sBucketDestroy(&bucket) - except: + except Exception: sBucketDeleteAndDestroy(&bucket) raise return new_MP(self, _p) @@ -5646,7 +5646,7 @@ def unpickle_MPolynomial_libsingular(MPolynomialRing_libsingular R, d): ln=0 sBucketClearMerge(bucket, &p, &ln) sBucketDestroy(&bucket) - except: + except Exception: sBucketDeleteAndDestroy(&bucket) raise return new_MP(R, p) diff --git a/src/sage/rings/ring_extension_element.pyx b/src/sage/rings/ring_extension_element.pyx index 610291dc620..a0dc7efc39e 100644 --- a/src/sage/rings/ring_extension_element.pyx +++ b/src/sage/rings/ring_extension_element.pyx @@ -162,7 +162,7 @@ cdef class RingExtensionElement(CommutativeAlgebraElement): attribute = getattr(self._backend, name) if callable(attribute): d.append(name) - except: + except AttributeError: pass return sorted(set(d)) From 279b5927981a98f698b7fc7a90ac842b0b3a7721 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Thu, 28 Oct 2021 21:27:09 +0200 Subject: [PATCH 03/15] fix typo --- src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py b/src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py index c1cb33e12b5..ce540d77f73 100644 --- a/src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py +++ b/src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py @@ -803,8 +803,8 @@ def __call__(self, x, type_3_pole_check=True): if not isinstance(x.parent(), Berkovich_Cp_Projective): try: x = self.domain()(x) - excep (TypeError, ValueError)t: - raise TypeError('action of dynamical system not defined on %s' %x.parent()) + except (TypeError, ValueError): + raise TypeError('action of dynamical system not defined on %s' % x.parent()) if x.parent().is_padic_base() != self.domain().is_padic_base(): raise ValueError('x was not backed by the same type of field as f') if x.prime() != self.domain().prime(): From eb4ae950f6caa27cef7b1d04c5b0473d36139ae3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Thu, 28 Oct 2021 21:48:08 +0200 Subject: [PATCH 04/15] add import --- src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx b/src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx index 75358e0987c..3d649be8f6f 100644 --- a/src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx +++ b/src/sage/dynamics/complex_dynamics/mandel_julia_helper.pyx @@ -38,8 +38,10 @@ from sage.symbolic.ring import SR from sage.calculus.var import var from sage.rings.fraction_field import is_FractionField from sage.categories.function_fields import FunctionFields +from sage.libs.all import PariError from math import sqrt + def _color_to_RGB(color): """ Convert a color to an RGB triple with values in the interval [0,255]. From bcdb6201a705715c7b995270064b1d734b9ef81c Mon Sep 17 00:00:00 2001 From: Thierry Monteil Date: Thu, 28 Oct 2021 22:51:10 +0200 Subject: [PATCH 05/15] #32788 : fix intentations for libs/giac/giac.pyx --- src/sage/libs/giac/giac.pyx | 1294 +++++++++++++++++------------------ 1 file changed, 647 insertions(+), 647 deletions(-) diff --git a/src/sage/libs/giac/giac.pyx b/src/sage/libs/giac/giac.pyx index 916b66f3bd1..b6f143404fb 100644 --- a/src/sage/libs/giac/giac.pyx +++ b/src/sage/libs/giac/giac.pyx @@ -172,22 +172,22 @@ from sage.interfaces.giac import giac #### Python3 compatibility ############################# if Pyversioninfo[0]>2 : - PythonVersion3 = True + PythonVersion3 = True else: - PythonVersion3 = False + PythonVersion3 = False def decstring23(s): - if PythonVersion3 : - return s.decode() - else: - return s + if PythonVersion3 : + return s.decode() + else: + return s def encstring23(s): - if PythonVersion3 : - return bytes(s,'UTF-8') - else: - return s + if PythonVersion3 : + return bytes(s,'UTF-8') + else: + return s if PythonVersion3: listrange=list,range @@ -810,128 +810,128 @@ include 'auto-methods.pxi' cdef class Pygen(GiacMethods_base): - cdef gen * gptr #pointer to the corresponding C++ element of type giac::gen + cdef gen * gptr #pointer to the corresponding C++ element of type giac::gen - def __cinit__(self, s=None): + def __cinit__(self, s=None): - #NB: the != here gives problems with the __richcmp__ function - #if (s!=None): - # so it's better to use isinstance - if (isinstance(s,None.__class__)): - # Do NOT replace with: self=GIACNULL (cf the doctest in __repr__ - sig_on() - self.gptr = new gen ((GIACNULL).gptr[0]) - sig_off() - return - - if isinstance(s,int): # This looks 100 faster than the str initialisation - if PythonVersion3: - #in python3 int and long are int - if s.bit_length()< Pymaxint.bit_length(): - sig_on() - self.gptr = new gen(s) - sig_off() - else: - sig_on() - self.gptr = new gen(pylongtogen(s)) - sig_off() - else: + #NB: the != here gives problems with the __richcmp__ function + #if (s!=None): + # so it's better to use isinstance + if (isinstance(s,None.__class__)): + # Do NOT replace with: self=GIACNULL (cf the doctest in __repr__ + sig_on() + self.gptr = new gen ((GIACNULL).gptr[0]) + sig_off() + return + + if isinstance(s,int): # This looks 100 faster than the str initialisation + if PythonVersion3: + #in python3 int and long are int + if s.bit_length()< Pymaxint.bit_length(): + sig_on() + self.gptr = new gen(s) + sig_off() + else: + sig_on() + self.gptr = new gen(pylongtogen(s)) + sig_off() + else: sig_on() self.gptr = new gen(s) sig_off() - # - elif isinstance(s,Integer): # for sage int (gmp) - sig_on() - if (abs(s)>Pymaxint): - self.gptr = new gen((s).value) - else: + # + elif isinstance(s,Integer): # for sage int (gmp) + sig_on() + if (abs(s)>Pymaxint): + self.gptr = new gen((s).value) + else: self.gptr = new gen(s) #important for pow to have a int - sig_off() + sig_off() - elif isinstance(s,Rational): # for sage rat (gmp) - #self.gptr = new gen(((Pygen(s.numerator())/Pygen(s.denominator()))).gptr[0]) - # FIXME: it's slow - sig_on() - self.gptr = new gen(GIAC_rdiv(gen(((s.numerator())).value),gen(((s.denominator())).value))) - sig_off() + elif isinstance(s,Rational): # for sage rat (gmp) + #self.gptr = new gen(((Pygen(s.numerator())/Pygen(s.denominator()))).gptr[0]) + # FIXME: it's slow + sig_on() + self.gptr = new gen(GIAC_rdiv(gen(((s.numerator())).value),gen(((s.denominator())).value))) + sig_off() - elif isinstance(s, Matrix): - s = Pygen(s.list()).list2mat(s.ncols()) - sig_on() - self.gptr = new gen((s).gptr[0]) - sig_off() + elif isinstance(s, Matrix): + s = Pygen(s.list()).list2mat(s.ncols()) + sig_on() + self.gptr = new gen((s).gptr[0]) + sig_off() - elif isinstance(s,float): - sig_on() - self.gptr = new gen(s) - sig_off() + elif isinstance(s,float): + sig_on() + self.gptr = new gen(s) + sig_off() - elif isinstance(s,long): - #s=str(s) - #self.gptr = new gen(s,context_ptr) - sig_on() - self.gptr = new gen(pylongtogen(s)) - sig_off() + elif isinstance(s,long): + #s=str(s) + #self.gptr = new gen(s,context_ptr) + sig_on() + self.gptr = new gen(pylongtogen(s)) + sig_off() - elif isinstance(s,Pygen): - #in the test: x,y=Pygen('x,y');((x+2*y).sin()).texpand() - # the y are lost without this case. - sig_on() - self.gptr = new gen((s).gptr[0]) - sig_off() + elif isinstance(s,Pygen): + #in the test: x,y=Pygen('x,y');((x+2*y).sin()).texpand() + # the y are lost without this case. + sig_on() + self.gptr = new gen((s).gptr[0]) + sig_off() - elif isinstance(s, listrange): - sig_on() - self.gptr = new gen(_wrap_pylist(s),0) - sig_off() + elif isinstance(s, listrange): + sig_on() + self.gptr = new gen(_wrap_pylist(s),0) + sig_off() - elif isinstance(s,tuple): - sig_on() - self.gptr = new gen(_wrap_pylist(s),1) - sig_off() + elif isinstance(s,tuple): + sig_on() + self.gptr = new gen(_wrap_pylist(s),1) + sig_off() - # Other types are converted with strings. - else: - if isinstance(s,Expression): - # take account of conversions with key giac in the sage symbol dict - s=SRexpressiontoGiac(s) - if not(isinstance(s,str)): #modif python3 - s=s.__str__() - sig_on() - self.gptr = new gen(encstring23(s),context_ptr) - sig_off() + # Other types are converted with strings. + else: + if isinstance(s,Expression): + # take account of conversions with key giac in the sage symbol dict + s=SRexpressiontoGiac(s) + if not(isinstance(s,str)): #modif python3 + s=s.__str__() + sig_on() + self.gptr = new gen(encstring23(s),context_ptr) + sig_off() - def __dealloc__(self): - del self.gptr + def __dealloc__(self): + del self.gptr - def __repr__(self): + def __repr__(self): try: - # fast evaluation of the complexity of the gen. (it's not the number of char ) - sig_on() - t=GIAC_taille(self.gptr[0], 6000) - sig_off() + # fast evaluation of the complexity of the gen. (it's not the number of char ) + sig_on() + t=GIAC_taille(self.gptr[0], 6000) + sig_off() except: - raise RuntimeError + raise RuntimeError if (t<6000) : - sig_on() - result=decstring23(GIAC_print(self.gptr[0], context_ptr).c_str()) #python3 - sig_off() - return result + sig_on() + result=decstring23(GIAC_print(self.gptr[0], context_ptr).c_str()) #python3 + sig_off() + return result else: - sig_on() - result=str(self.type)+"\nResult is too big for Display. If you really want to see it use print" - sig_off() - return result + sig_on() + result=str(self.type)+"\nResult is too big for Display. If you really want to see it use print" + sig_off() + return result - def __str__(self): + def __str__(self): #if self.gptr == NULL: # return '' sig_on() @@ -939,7 +939,7 @@ cdef class Pygen(GiacMethods_base): sig_off() return result - def __len__(self): + def __len__(self): """ TESTS:: @@ -954,17 +954,17 @@ cdef class Pygen(GiacMethods_base): sig_off() return rep else: - try: - sig_on() - rep=GIAC_size(self.gptr[0],context_ptr).val - sig_off() - #GIAC_size return a gen. we take the int: val - return rep - except: - raise RuntimeError + try: + sig_on() + rep=GIAC_size(self.gptr[0],context_ptr).val + sig_off() + #GIAC_size return a gen. we take the int: val + return rep + except: + raise RuntimeError - def __getitem__(self,i): #TODO?: add gen support for indexes + def __getitem__(self,i): #TODO?: add gen support for indexes """ Lists of 10^6 integers should be translated to giac easily @@ -999,48 +999,48 @@ cdef class Pygen(GiacMethods_base): cdef gen result if(self._type == 7) or (self._type == 12): #if self is a list or a string - if isinstance(i,int) or isinstance(i,Integer): - n=len(self) - if(ii] - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError - else: - raise IndexError('list index %s out of range'%(i)) - else: - if isinstance(i,slice): - sig_on() - result=gen(_getgiacslice(self,i),self._subtype) - sig_off() - return _wrap_gen(result) - # add support for multi indexes - elif isinstance(i,tuple): - if(len(i)==2): - return self[i[0]][i[1]] - elif(len(i)==1): - # in case of a tuple like this: (3,) - return self[i[0]] - else: - return self[i[0],i[1]][tuple(i[2:])] + if isinstance(i,int) or isinstance(i,Integer): + n=len(self) + if(ii] + sig_off() + return _wrap_gen(result) + except: + raise RuntimeError + else: + raise IndexError('list index %s out of range'%(i)) else: - raise TypeError('gen indexes are not yet implemented') + if isinstance(i,slice): + sig_on() + result=gen(_getgiacslice(self,i),self._subtype) + sig_off() + return _wrap_gen(result) + # add support for multi indexes + elif isinstance(i,tuple): + if(len(i)==2): + return self[i[0]][i[1]] + elif(len(i)==1): + # in case of a tuple like this: (3,) + return self[i[0]] + else: + return self[i[0],i[1]][tuple(i[2:])] + else: + raise TypeError('gen indexes are not yet implemented') # Here we add support to formal variable indexes: else: - cmd='%s[%s]'%(self,i) - ans=Pygen(cmd).eval() - # if the answer is a string, it must be an error message because self is not a list or a string - if (ans._type == 12): - raise TypeError("Error executing code in Giac\nCODE:\n\t%s\nGiac ERROR:\n\t%s"%(cmd, ans)) - return ans + cmd='%s[%s]'%(self,i) + ans=Pygen(cmd).eval() + # if the answer is a string, it must be an error message because self is not a list or a string + if (ans._type == 12): + raise TypeError("Error executing code in Giac\nCODE:\n\t%s\nGiac ERROR:\n\t%s"%(cmd, ans)) + return ans - def __setitem__(self,key,value): + def __setitem__(self,key,value): """ Set the value of a coefficient of a giac vector or matrix or list. Warning: It is an in place affectation. @@ -1092,238 +1092,238 @@ cdef class Pygen(GiacMethods_base): - def __iter__(self): - """ - Pygen lists of 10^6 elements should be yield + def __iter__(self): + """ + Pygen lists of 10^6 elements should be yield - TESTS:: + TESTS:: - sage: from sage.libs.giac.giac import libgiac - sage: l = libgiac(range(10^6)) - sage: [ i for i in l ] == list(range(10^6)) - True + sage: from sage.libs.giac.giac import libgiac + sage: l = libgiac(range(10^6)) + sage: [ i for i in l ] == list(range(10^6)) + True - Check for :trac:`18841`:: + Check for :trac:`18841`:: - sage: L = libgiac(range(10)) - sage: next(iter(L)) - 0 - """ - cdef int i - for i in range(len(self)): - yield self[i] + sage: L = libgiac(range(10)) + sage: next(iter(L)) + 0 + """ + cdef int i + for i in range(len(self)): + yield self[i] - def eval(self): + def eval(self): cdef gen result try: - sig_on() - result=GIAC_protecteval(self.gptr[0],giacsettings.eval_level,context_ptr) - sig_off() - return _wrap_gen(result) + sig_on() + result=GIAC_protecteval(self.gptr[0],giacsettings.eval_level,context_ptr) + sig_off() + return _wrap_gen(result) except: - raise RuntimeError + raise RuntimeError - def __add__(self, right): - cdef gen result - if isinstance(right,Pygen)==False: + def __add__(self, right): + cdef gen result + if isinstance(right,Pygen)==False: right=Pygen(right) - # Curiously this case is important: - # otherwise: f=1/(2+sin(5*x)) crash - if isinstance(self,Pygen)==False: + # Curiously this case is important: + # otherwise: f=1/(2+sin(5*x)) crash + if isinstance(self,Pygen)==False: self=Pygen(self) - try: - sig_on() - result= (self).gptr[0] + (right).gptr[0] - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError - - - def __call__(self, *args): - cdef gen result - n=len(args) - if (n>1): - #FIXME? improve with a vector, or improve Pygen(list) - right=Pygen(args).eval() - elif (n==1): - right=Pygen(args[0]) - else: - right=GIACNULL - if isinstance(self,Pygen)==False: - self=Pygen(self) + try: + sig_on() + result= (self).gptr[0] + (right).gptr[0] + sig_off() + return _wrap_gen(result) + except: + raise RuntimeError + + + def __call__(self, *args): + cdef gen result + n=len(args) + if (n>1): + #FIXME? improve with a vector, or improve Pygen(list) + right=Pygen(args).eval() + elif (n==1): + right=Pygen(args[0]) + else: + right=GIACNULL + if isinstance(self,Pygen)==False: + self=Pygen(self) # Some giac errors such as pari_locked are caught by the try # so we can't put the sig_on() in the try. # But now a keyboard interrupt fall back to this sig_on so # it may have left the giac pari locked. - sig_on() - try: - result= ((self).gptr[0])((right).gptr[0],context_ptr) - sig_off() - return _wrap_gen(result) - except: + sig_on() + try: + result= ((self).gptr[0])((right).gptr[0],context_ptr) + sig_off() + return _wrap_gen(result) + except: # The previous computation might have failed due to a pari_lock # So we will not raise an exception yet. tmp=Pygen('pari_unlock()').eval() # if pari was not locked in giac, we have locked it, so unlock it. if(tmp==0): - Pygen('pari_unlock()').eval() - sig_off() - raise + Pygen('pari_unlock()').eval() + sig_off() + raise else: - try: - result= GIAC_eval((right).gptr[0],1,context_ptr) - result= ((self).gptr[0])(result,context_ptr) - sig_off() - return _wrap_gen(result) - except: - sig_off() - raise - - - def __sub__(self, right): - cdef gen result - if isinstance(right,Pygen)==False: + try: + result= GIAC_eval((right).gptr[0],1,context_ptr) + result= ((self).gptr[0])(result,context_ptr) + sig_off() + return _wrap_gen(result) + except: + sig_off() + raise + + + def __sub__(self, right): + cdef gen result + if isinstance(right,Pygen)==False: right=Pygen(right) - if isinstance(self,Pygen)==False: + if isinstance(self,Pygen)==False: self=Pygen(self) - try: - sig_on() - result= (self).gptr[0] - (right).gptr[0] - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError - - def __mul__(self, right): - """ - TESTS:: - - sage: from sage.libs.giac.giac import libgiac - sage: (sqrt(5)*libgiac('x')).factor() # BUG test could give 0 - sqrt(5)*x - sage: (libgiac('x')*sqrt(5)).factor() - sqrt(5)*x - """ - cdef gen result - if isinstance(right,Pygen)==False: + try: + sig_on() + result= (self).gptr[0] - (right).gptr[0] + sig_off() + return _wrap_gen(result) + except: + raise RuntimeError + + def __mul__(self, right): + """ + TESTS:: + + sage: from sage.libs.giac.giac import libgiac + sage: (sqrt(5)*libgiac('x')).factor() # BUG test could give 0 + sqrt(5)*x + sage: (libgiac('x')*sqrt(5)).factor() + sqrt(5)*x + """ + cdef gen result + if isinstance(right,Pygen)==False: right=Pygen(right) - if isinstance(self,Pygen)==False: + if isinstance(self,Pygen)==False: self=Pygen(self) - try: - #result= (self).gptr[0] * (right).gptr[0] - #NB: with the natural previous method, the following error generated by - #giac causes python to quit instead of an error message. - #l=Pygen([1,2]);l.transpose()*l; - sig_on() - result= GIAC_giacmul((self).gptr[0] , (right).gptr[0],context_ptr) - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + try: + #result= (self).gptr[0] * (right).gptr[0] + #NB: with the natural previous method, the following error generated by + #giac causes python to quit instead of an error message. + #l=Pygen([1,2]);l.transpose()*l; + sig_on() + result= GIAC_giacmul((self).gptr[0] , (right).gptr[0],context_ptr) + sig_off() + return _wrap_gen(result) + except: + raise RuntimeError #PB / in python3 is truediv - def __div__(self, right): - """ - TESTS:: - - sage: from sage.libs.giac.giac import libgiac - sage: (sqrt(3)/libgiac('x')).factor() # BUG test could give 0 - sqrt(3)/x - sage: (libgiac('x')/sqrt(3)).factor() - sqrt(3)*x/3 - """ - cdef gen result - if isinstance(right,Pygen)==False: + def __div__(self, right): + """ + TESTS:: + + sage: from sage.libs.giac.giac import libgiac + sage: (sqrt(3)/libgiac('x')).factor() # BUG test could give 0 + sqrt(3)/x + sage: (libgiac('x')/sqrt(3)).factor() + sqrt(3)*x/3 + """ + cdef gen result + if isinstance(right,Pygen)==False: right=Pygen(right) - if isinstance(self,Pygen)==False: + if isinstance(self,Pygen)==False: self=Pygen(self) - try: - sig_on() - result= GIAC_giacdiv((self).gptr[0] , (right).gptr[0],context_ptr) - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError - - def __truediv__(self, right): - cdef gen result - if isinstance(right,Pygen)==False: + try: + sig_on() + result= GIAC_giacdiv((self).gptr[0] , (right).gptr[0],context_ptr) + sig_off() + return _wrap_gen(result) + except: + raise RuntimeError + + def __truediv__(self, right): + cdef gen result + if isinstance(right,Pygen)==False: right=Pygen(right) - if isinstance(self,Pygen)==False: + if isinstance(self,Pygen)==False: self=Pygen(self) - try: - sig_on() - result= (self).gptr[0] / (right).gptr[0] - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + try: + sig_on() + result= (self).gptr[0] / (right).gptr[0] + sig_off() + return _wrap_gen(result) + except: + raise RuntimeError - def __pow__(self, right ,ignored): - cdef gen result - if isinstance(right,Pygen)==False: + def __pow__(self, right ,ignored): + cdef gen result + if isinstance(right,Pygen)==False: right=Pygen(right) - if isinstance(self,Pygen)==False: + if isinstance(self,Pygen)==False: self=Pygen(self) - try: - sig_on() - result= GIAC_pow((self).gptr[0],(right).gptr[0], context_ptr ) - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError - - def __mod__(self, right): - cdef gen result - if not isinstance(right,Pygen): + try: + sig_on() + result= GIAC_pow((self).gptr[0],(right).gptr[0], context_ptr ) + sig_off() + return _wrap_gen(result) + except: + raise RuntimeError + + def __mod__(self, right): + cdef gen result + if not isinstance(right,Pygen): right=Pygen(right) - if not isinstance(self,Pygen): + if not isinstance(self,Pygen): self=Pygen(self) - try: - #result= gen(GIAC_makenewvecteur((self).gptr[0],(right).gptr[0]),1) - #to have an integer output: - #result= GIAC_smod(result,context_ptr) - #we give a modular output: - sig_on() - result= GIAC_giacmod((self).gptr[0],(right).gptr[0],context_ptr) - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError - - def __neg__(self): - cdef gen result - if isinstance(self,Pygen)==False: + try: + #result= gen(GIAC_makenewvecteur((self).gptr[0],(right).gptr[0]),1) + #to have an integer output: + #result= GIAC_smod(result,context_ptr) + #we give a modular output: + sig_on() + result= GIAC_giacmod((self).gptr[0],(right).gptr[0],context_ptr) + sig_off() + return _wrap_gen(result) + except: + raise RuntimeError + + def __neg__(self): + cdef gen result + if isinstance(self,Pygen)==False: self=Pygen(self) - try: - sig_on() - result= GIAC_neg((self).gptr[0]) - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + try: + sig_on() + result= GIAC_neg((self).gptr[0]) + sig_off() + return _wrap_gen(result) + except: + raise RuntimeError - def __pos__(self): - return self + def __pos__(self): + return self - # To be able to use the eval function before the GiacMethods initialisation - def cas_setup(self,*args): + # To be able to use the eval function before the GiacMethods initialisation + def cas_setup(self,*args): return Pygen('cas_setup')(self,*args) - def savegen(self, str filename): + def savegen(self, str filename): """ Archive a Pygen element to a file in giac compressed format. @@ -1349,13 +1349,13 @@ cdef class Pygen(GiacMethods_base): GIAC_archive( encstring23(filename), (self).gptr[0], context_ptr) sig_off() except: - raise RuntimeError + raise RuntimeError - # NB: with giac <= 1.2.3-57 redim doesn't have a non evaluated for so Pygen('redim') fails. - # hence replacement for redim: - def redim(self,a,b=None): + # NB: with giac <= 1.2.3-57 redim doesn't have a non evaluated for so Pygen('redim') fails. + # hence replacement for redim: + def redim(self,a,b=None): """ Increase the size of a matrix when possible, otherwise return self. @@ -1370,58 +1370,58 @@ cdef class Pygen(GiacMethods_base): """ d=self.dim() if d.type()==7: - if(a>d[0] and b>=d[1]): - A=self.semi_augment(Pygen((a-d[0],d[1])).matrix()) - if(b>d[1]): - A=A.augment(Pygen((a,b-d[1])).matrix()) - return A - elif(b>d[1] and a==d[0]): - return self.augment(Pygen((d[0],b-d[1])).matrix()) - else: - return self + if(a>d[0] and b>=d[1]): + A=self.semi_augment(Pygen((a-d[0],d[1])).matrix()) + if(b>d[1]): + A=A.augment(Pygen((a,b-d[1])).matrix()) + return A + elif(b>d[1] and a==d[0]): + return self.augment(Pygen((d[0],b-d[1])).matrix()) + else: + return self else: - raise TypeError("self is not a giac List") + raise TypeError("self is not a giac List") - # def htmlhelp(self, str lang='en'): - # """ - # Open the giac html detailled help about self in an external browser + # def htmlhelp(self, str lang='en'): + # """ + # Open the giac html detailled help about self in an external browser - # There are currently 3 supported languages: 'en', 'fr', 'el' + # There are currently 3 supported languages: 'en', 'fr', 'el' - # """ - # l={'fr':1 , 'en':2, 'el':4} - # if (not lang in ['en', 'fr', 'el']): - # lang='en' - # try: - # url=decstring23(browser_help(self.gptr[0],l[lang])) #python3 - # giacbasedir=decstring23(GIAC_giac_aide_dir()) # python3 - # except: - # raise RuntimeError('giac docs dir not found') - # print(url) - # if os.access(giacbasedir,os.F_OK): - # url='file:'+url - # wwwbrowseropen(url) + # """ + # l={'fr':1 , 'en':2, 'el':4} + # if (not lang in ['en', 'fr', 'el']): + # lang='en' + # try: + # url=decstring23(browser_help(self.gptr[0],l[lang])) #python3 + # giacbasedir=decstring23(GIAC_giac_aide_dir()) # python3 + # except: + # raise RuntimeError('giac docs dir not found') + # print(url) + # if os.access(giacbasedir,os.F_OK): + # url='file:'+url + # wwwbrowseropen(url) - def _help(self): + def _help(self): return self.findhelp().__str__() # def help(self): # return self._help() - def _sage_doc_(self): + def _sage_doc_(self): return self._help() - def __doc__(self): + def __doc__(self): return self._help() - # # # # # # # # # # # # # # # # # - # sage addons - # # # # # # # # # # # # # # # # # - def _latex_(self): + # # # # # # # # # # # # # # # # # + # sage addons + # # # # # # # # # # # # # # # # # + def _latex_(self): r""" You can output Giac expressions in latex. @@ -1447,7 +1447,7 @@ cdef class Pygen(GiacMethods_base): return result - def _integer_(self,Z=None): + def _integer_(self,Z=None): """ Convert giac integers or modular integers to sage Integers (via gmp) @@ -1494,10 +1494,10 @@ cdef class Pygen(GiacMethods_base): return result else: - raise TypeError("Cannot convert non giac integers to Integer") + raise TypeError("Cannot convert non giac integers to Integer") - def _rational_(self,Z=None): + def _rational_(self,Z=None): """ Convert giac rationals to sage rationals @@ -1514,20 +1514,20 @@ cdef class Pygen(GiacMethods_base): # _INT_ or _ZINT if(typ == 0 or typ == 2): - return QQ(ZZ(self)) + return QQ(ZZ(self)) # _FRAC_ elif(typ == 10): # giac _RAT_ try: - result=ZZ(self.numer())/ZZ(self.denom()) - return result + result=ZZ(self.numer())/ZZ(self.denom()) + return result except: - RuntimeError("Failed to convert to QQ") + RuntimeError("Failed to convert to QQ") else: - raise TypeError("Cannot convert non giac _FRAC_ to QQ") + raise TypeError("Cannot convert non giac _FRAC_ to QQ") - def sage(self): + def sage(self): r""" Convert a libgiac expression back to a Sage expression. (could be slow) @@ -1590,29 +1590,29 @@ cdef class Pygen(GiacMethods_base): if (typ != 7) : # self is not a list if ( typ == 0 or typ == 2): - return ZZ(self) + return ZZ(self) elif (typ == 10): - return QQ(self) + return QQ(self) elif (typ == 15): - # modular integer - sig_on() - a = _wrap_gen( (self.gptr.ref_MODptr())[0]) - b = _wrap_gen( (self.gptr.ref_MODptr())[1]) - result = IntegerModRing(ZZ(b))(ZZ(a)) - sig_off() - return result + # modular integer + sig_on() + a = _wrap_gen( (self.gptr.ref_MODptr())[0]) + b = _wrap_gen( (self.gptr.ref_MODptr())[1]) + result = IntegerModRing(ZZ(b))(ZZ(a)) + sig_off() + return result elif (typ == 12): - # string - sig_on() - result=eval(self.__str__()) - sig_off() - return result + # string + sig_on() + result=eval(self.__str__()) + sig_off() + return result else: - return SR(self) + return SR(self) else: # self is a list @@ -1622,7 +1622,7 @@ cdef class Pygen(GiacMethods_base): return result - def _symbolic_(self, R): + def _symbolic_(self, R): r""" Convert self object to the ring R via a basic string evaluation. (slow) @@ -1650,28 +1650,28 @@ cdef class Pygen(GiacMethods_base): sin(π) """ if isinstance(R,SR.__class__): - # Try to convert some functions names to the symbolic ring - lsymbols = symbol_table['giac'].copy() - #lsymbols.update(locals) - try: - result = symbolic_expression_from_string(self.__str__(), lsymbols, - accept_sequence=True, - parser=SR_parser_giac) - return result - - except Exception: - raise NotImplementedError("Unable to parse Giac output: %s" % self.__repr__()) + # Try to convert some functions names to the symbolic ring + lsymbols = symbol_table['giac'].copy() + #lsymbols.update(locals) + try: + result = symbolic_expression_from_string(self.__str__(), lsymbols, + accept_sequence=True, + parser=SR_parser_giac) + return result + + except Exception: + raise NotImplementedError("Unable to parse Giac output: %s" % self.__repr__()) else: - try: - result=R(self.__str__()) - return result + try: + result=R(self.__str__()) + return result - except Exception: - raise NotImplementedError("Unable to parse Giac output: %s" % self.__repr__()) + except Exception: + raise NotImplementedError("Unable to parse Giac output: %s" % self.__repr__()) - def _matrix_(self, R=ZZ): + def _matrix_(self, R=ZZ): r""" Return matrix over the (Sage) ring R where self should be a Giac matrix. The default ring is ZZ. @@ -1706,7 +1706,7 @@ cdef class Pygen(GiacMethods_base): sig_off() return M(entries) - def _vector_(self, R=None): + def _vector_(self, R=None): r""" Return vector over the (Sage) ring R where self should be a Giac matrix. The default ring is ZZ. @@ -1726,19 +1726,19 @@ cdef class Pygen(GiacMethods_base): v = self.dim() try: - n = v._val + n = v._val except: - raise TypeError("Entry is not a giac vector") + raise TypeError("Entry is not a giac vector") from sage.modules.free_module_element import vector sig_on() entries = [R(self[c]) for c in range(n)] sig_off() return vector(R,entries) - # # # # # # # # # # # # # # # + # # # # # # # # # # # # # # # - def mplot(self): + def mplot(self): """ Basic export of some 2D plots to sage. Only generic plots are supported. lines, circles, ... are not implemented @@ -1747,28 +1747,28 @@ cdef class Pygen(GiacMethods_base): xyplot=[] plotdata=self if not plotdata.type()=='DOM_LIST': - plotdata=[plotdata] + plotdata=[plotdata] sig_on() for G in plotdata: - if G.dim()>2: # it is not a pnt. Ex: scatterplot + if G.dim()>2: # it is not a pnt. Ex: scatterplot for g in G: xyscat=xyscat+[[(g.real())._double,(g.im())._double]] - else: + else: if G[1].type()=='DOM_LIST': - l=G[1].op() + l=G[1].op() else: - l=G[1][2].op() + l=G[1][2].op() xyplot=[[(u.real())._double,(u.im())._double] for u in l] if (xyscat != []): - result=scatter_plot(xyscat) + result=scatter_plot(xyscat) else: - result=line(xyplot) + result=line(xyplot) sig_off() return result @@ -1776,45 +1776,45 @@ cdef class Pygen(GiacMethods_base): - # # # # # # # # # # # # # # # # # # # # # # # # # - # WARNING: - # - # Do not use things like != in Pygen's __cinit__ - # with this __richcmp__ enabled - # The methods will bug: a=Pygen(2); a.sin() - # - # # # # # # # # # # # # # # # # # # # # # # # # # + # # # # # # # # # # # # # # # # # # # # # # # # # + # WARNING: + # + # Do not use things like != in Pygen's __cinit__ + # with this __richcmp__ enabled + # The methods will bug: a=Pygen(2); a.sin() + # + # # # # # # # # # # # # # # # # # # # # # # # # # - def __richcmp__( self, other,op): - if isinstance(other,Pygen)==False: + def __richcmp__( self, other,op): + if isinstance(other,Pygen)==False: other=Pygen(other) - if isinstance(self,Pygen)==False: + if isinstance(self,Pygen)==False: self=Pygen(self) - try: - sig_on() - result= giacgenrichcmp((self).gptr[0],(other).gptr[0], op, context_ptr ) - sig_off() - except: - raise RuntimeError - if result==1 : - return True - else: - return False - - # - # Some attributes of the gen class: - # - property _type: - def __get__(self): + try: + sig_on() + result= giacgenrichcmp((self).gptr[0],(other).gptr[0], op, context_ptr ) + sig_off() + except: + raise RuntimeError + if result==1 : + return True + else: + return False + + # + # Some attributes of the gen class: + # + property _type: + def __get__(self): sig_on() result=self.gptr.type sig_off() return result - property _subtype: - def __get__(self): + property _subtype: + def __get__(self): sig_on() result=self.gptr.subtype sig_off() @@ -1822,57 +1822,57 @@ cdef class Pygen(GiacMethods_base): - property _val: # immediate int (type _INT_) - """ - immediate int value of an _INT_ type gen. - """ - def __get__(self): + property _val: # immediate int (type _INT_) + """ + immediate int value of an _INT_ type gen. + """ + def __get__(self): if(self._type == 0): - sig_on() - result=self.gptr.val - sig_off() - return result + sig_on() + result=self.gptr.val + sig_off() + return result else: - raise TypeError("Cannot convert non _INT_ giac gen") + raise TypeError("Cannot convert non _INT_ giac gen") - property _double: # immediate double (type _DOUBLE_) - """ - immediate conversion to float for a gen of _DOUBLE_ type. - """ - def __get__(self): + property _double: # immediate double (type _DOUBLE_) + """ + immediate conversion to float for a gen of _DOUBLE_ type. + """ + def __get__(self): if(self._type == 1): - sig_on() - result=self.gptr._DOUBLE_val - sig_off() - return result + sig_on() + result=self.gptr._DOUBLE_val + sig_off() + return result else: - raise TypeError("Cannot convert non _DOUBLE_ giac gen") + raise TypeError("Cannot convert non _DOUBLE_ giac gen") - property help: - def __get__(self): - return self._help() + property help: + def __get__(self): + return self._help() - ################################################### - # Add the others methods - ################################################### - # - # NB: with __getattr__ this is about 10 times slower: [a.normal() for i in range(10**4)] - # than [GiacMethods["normal"](a) for i in range(10**4)] - # - # def __getattr__(self, name): - # return GiacMethods[str(name)](self) - ## + ################################################### + # Add the others methods + ################################################### + # + # NB: with __getattr__ this is about 10 times slower: [a.normal() for i in range(10**4)] + # than [GiacMethods["normal"](a) for i in range(10**4)] + # + # def __getattr__(self, name): + # return GiacMethods[str(name)](self) + ## - #test - def giacAiry_Ai(self, *args): + #test + def giacAiry_Ai(self, *args): cdef gen result=GIAC_Airy_Ai(self.gptr[0], context_ptr) return _wrap_gen(result) - def giacifactor(self, *args): + def giacifactor(self, *args): cdef gen result sig_on() result=GIAC_eval(self.gptr[0], 1, context_ptr) @@ -1929,79 +1929,79 @@ cdef inline _wrap_gen(gen g)except +: ################################################################ cdef vecteur _wrap_pylist(L) except +: - cdef vecteur * V - cdef int i + cdef vecteur * V + cdef int i - if (isinstance(L, tuple) or isinstance(L, listrange)): - n=len(L) - V=new vecteur() + if (isinstance(L, tuple) or isinstance(L, listrange)): + n=len(L) + V=new vecteur() - sig_on() - for i in range(n): - V.push_back((Pygen(L[i])).gptr[0]) - sig_off() - return V[0] - else: - raise TypeError("argument must be a tuple or a list") + sig_on() + for i in range(n): + V.push_back((Pygen(L[i])).gptr[0]) + sig_off() + return V[0] + else: + raise TypeError("argument must be a tuple or a list") ################################# # slice wrapper for a giac list ################################# cdef vecteur _getgiacslice(Pygen L,slice sl) except +: - cdef vecteur * V - cdef int u + cdef vecteur * V + cdef int u - if (L.type()=="DOM_LIST"): - n=len(L) - V=new vecteur() + if (L.type()=="DOM_LIST"): + n=len(L) + V=new vecteur() - sig_on() + sig_on() # for u in range(n)[sl]: #pb python3 - (b,e,st)=sl.indices(n) - for u in range(b,e,st): - V.push_back((L.gptr[0])[u]) - sig_off() - return V[0] - else: - raise TypeError("argument must be a Pygen list and a slice") + (b,e,st)=sl.indices(n) + for u in range(b,e,st): + V.push_back((L.gptr[0])[u]) + sig_off() + return V[0] + else: + raise TypeError("argument must be a Pygen list and a slice") cdef gen pylongtogen(a) except +: - # # - # basic conversion of Python long integers to gen via Horner's Method # - # # - - aneg=False - cdef gen g=gen(0) - cdef gen M - - if (a<0): - aneg=True - a=-a - if Pyversioninfo >= (2,7): - size=a.bit_length() # bit_length python >= 2.7 required. - shift=Pymaxint.bit_length()-1 - else: - size=math.trunc(math.log(a,2))+1 - shift=math.trunc(math.log(Pymaxint)) - M=gen((1<=shift): - size=size-shift - i=int(a>>size) - g=(g*M+gen(i)) - a=a-(i<(1< a) - if aneg: - # when cythonizing with cython 0.24: - # g=-g gives an Invalid operand type for '-' (gen) - g=GIAC_neg(g) - return g; + # # + # basic conversion of Python long integers to gen via Horner's Method # + # # + + aneg=False + cdef gen g=gen(0) + cdef gen M + + if (a<0): + aneg=True + a=-a + if Pyversioninfo >= (2,7): + size=a.bit_length() # bit_length python >= 2.7 required. + shift=Pymaxint.bit_length()-1 + else: + size=math.trunc(math.log(a,2))+1 + shift=math.trunc(math.log(Pymaxint)) + M=gen((1<=shift): + size=size-shift + i=int(a>>size) + g=(g*M+gen(i)) + a=a-(i<(1< a) + if aneg: + # when cythonizing with cython 0.24: + # g=-g gives an Invalid operand type for '-' (gen) + g=GIAC_neg(g) + return g; @@ -2066,78 +2066,78 @@ GiacMethods={} class GiacFunction(Pygen): - # a class to evaluate args before call - """ - A Subclass of Pygen to create functions with evaluating all the args - before call so that they are substitued by their value. - - EXAMPLES:: - - sage: from sage.libs.giac.giac import * - sage: libgiac.simplify(exp(I*pi)) # simplify is a GiacFunction - -1 - sage: libgiac('a:=1') - 1 - sage: libgiac.purge('a') # purge is not a GiacFunction - 1 - sage: libgiac('a') - a - """ - def __call__(self, *args): - cdef gen result - n=len(args) - if (n>1): - #FIXME? improve with a vector, or improve Pygen(list) - right=Pygen(args).eval() - elif (n==1): - right=Pygen(args[0]).eval() - else: - right=GIACNULL - if isinstance(self,Pygen)==False: - self=Pygen(self) + # a class to evaluate args before call + """ + A Subclass of Pygen to create functions with evaluating all the args + before call so that they are substitued by their value. + + EXAMPLES:: + + sage: from sage.libs.giac.giac import * + sage: libgiac.simplify(exp(I*pi)) # simplify is a GiacFunction + -1 + sage: libgiac('a:=1') + 1 + sage: libgiac.purge('a') # purge is not a GiacFunction + 1 + sage: libgiac('a') + a + """ + def __call__(self, *args): + cdef gen result + n=len(args) + if (n>1): + #FIXME? improve with a vector, or improve Pygen(list) + right=Pygen(args).eval() + elif (n==1): + right=Pygen(args[0]).eval() + else: + right=GIACNULL + if isinstance(self,Pygen)==False: + self=Pygen(self) # Some giac errors such as pari_locked are caught by the try # so we can't put the sig_on() in the try. # But now a keyboard interrupt fall back to this sig_on so # it may have left the giac pari locked. - sig_on() - try: - result= ((self).gptr[0])((right).gptr[0],context_ptr) - sig_off() - return _wrap_gen(result) - except: + sig_on() + try: + result= ((self).gptr[0])((right).gptr[0],context_ptr) + sig_off() + return _wrap_gen(result) + except: # The previous computation might have failed due to a pari_lock # So we will not raise an exception yet. tmp=Pygen('pari_unlock()').eval() # if pari was not locked in giac, we have locked it, so unlock it. if(tmp==0): - Pygen('pari_unlock()').eval() - sig_off() - raise + Pygen('pari_unlock()').eval() + sig_off() + raise else: - try: - result= GIAC_eval((right).gptr[0],1,context_ptr) - result= ((self).gptr[0])(result,context_ptr) - sig_off() - return _wrap_gen(result) - except: - sig_off() - raise + try: + result= GIAC_eval((right).gptr[0],1,context_ptr) + result= ((self).gptr[0])(result,context_ptr) + sig_off() + return _wrap_gen(result) + except: + sig_off() + raise class GiacFunctionNoEV(Pygen): - # a class to allow to write the __doc__ attribute. - """ - A Subclass of Pygen to create functions + # a class to allow to write the __doc__ attribute. + """ + A Subclass of Pygen to create functions - EXAMPLES:: + EXAMPLES:: - sage: from sage.libs.giac.giac import * - sage: libgiac('a:=1') - 1 - sage: libgiac.purge('a') # purge is a GiacFunctionNoEV - 1 - sage: libgiac('a') - a - """ + sage: from sage.libs.giac.giac import * + sage: libgiac('a:=1') + 1 + sage: libgiac.purge('a') # purge is a GiacFunctionNoEV + 1 + sage: libgiac('a') + a + """ ############################################################# # Some convenient settings @@ -2150,22 +2150,22 @@ Pygen('add_language(1)').eval(); # Add the french keywords in the giac library l NoEvArgsFunc=['purge','assume','quote'] for i in mostkeywords: - if i in NoEvArgsFunc: - # do not eval args before calling this function. Ex purge - #tmp=Pygen(i) - tmp=GiacFunctionNoEV(i) - else: - tmp=GiacFunction(i) - # in the sage version we remove: globals()[i]=tmp - GiacMethods[i]=tmp + if i in NoEvArgsFunc: + # do not eval args before calling this function. Ex purge + #tmp=Pygen(i) + tmp=GiacFunctionNoEV(i) + else: + tmp=GiacFunction(i) + # in the sage version we remove: globals()[i]=tmp + GiacMethods[i]=tmp # We put the giac names that should not be exported to Python in moremethods. for i in moremethods: - tmp=GiacFunction(i) - GiacMethods[i]=tmp + tmp=GiacFunction(i) + GiacMethods[i]=tmp for i in mostkeywords+moremethods: - GiacMethods[i].__doc__=eval("Pygen."+i+".__doc__") + GiacMethods[i].__doc__=eval("Pygen."+i+".__doc__") # To avoid conflicts we export only these few ones. Most giac keywords will be # avaible through: libgiac.keywordname @@ -2174,36 +2174,36 @@ __all__=['Pygen','giacsettings','libgiac','loadgiacgen','GiacFunction','GiacMeth def loadgiacgen(str filename): - """ - Open a file in giac compressed format to create a Pygen element. - - Use the save method from Pygen elements to create such files. - - In C++ these files can be opened with giac::unarchive and created with - ``giac::archive``. - - EXAMPLES:: - - sage: from sage.libs.giac.giac import * - sage: g=libgiac.texpand('cos(10*a+5*b)') - sage: g.save("fichiertest") # doctest: +SKIP - sage: a=loadgiacgen("fichiertest") # doctest: +SKIP - sage: from tempfile import NamedTemporaryFile - sage: F=NamedTemporaryFile() # chose a temporary file for a test - sage: g.savegen(F.name) - sage: a=loadgiacgen(F.name) - sage: a.tcollect() - cos(10*a+5*b) - sage: F.close() - """ - cdef gen result - try: - sig_on() - result=GIAC_unarchive( encstring23(filename), context_ptr) - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + """ + Open a file in giac compressed format to create a Pygen element. + + Use the save method from Pygen elements to create such files. + + In C++ these files can be opened with giac::unarchive and created with + ``giac::archive``. + + EXAMPLES:: + + sage: from sage.libs.giac.giac import * + sage: g=libgiac.texpand('cos(10*a+5*b)') + sage: g.save("fichiertest") # doctest: +SKIP + sage: a=loadgiacgen("fichiertest") # doctest: +SKIP + sage: from tempfile import NamedTemporaryFile + sage: F=NamedTemporaryFile() # chose a temporary file for a test + sage: g.savegen(F.name) + sage: a=loadgiacgen(F.name) + sage: a.tcollect() + cos(10*a+5*b) + sage: F.close() + """ + cdef gen result + try: + sig_on() + result=GIAC_unarchive( encstring23(filename), context_ptr) + sig_off() + return _wrap_gen(result) + except: + raise RuntimeError @@ -2227,21 +2227,21 @@ class GiacInstance: """ def __init__(self): - self.__dict__.update(GiacMethods) + self.__dict__.update(GiacMethods) def __call__(self,s): - return _giac(s) + return _giac(s) def _sage_doc_(self): - return _giac.__doc__ + return _giac.__doc__ def eval(self, code, strip=True, **kwds): if strip: - code = code.replace("\n","").strip() + code = code.replace("\n","").strip() return self(code) @@ -2254,8 +2254,8 @@ libgiac=GiacInstance() # trac #23976 (bound threads with SAGE_NUM_THREADS) import os try: - ncpus = int(os.environ['SAGE_NUM_THREADS']) + ncpus = int(os.environ['SAGE_NUM_THREADS']) except KeyError: - ncpus = 1 + ncpus = 1 giacsettings.threads = ncpus From da3e43762af6b5d0b40547d382cbbac3375988fc Mon Sep 17 00:00:00 2001 From: Thierry Monteil Date: Thu, 28 Oct 2021 23:24:29 +0200 Subject: [PATCH 06/15] #32788 : remove useless try/except statements in src/sage/libs/giac/giac.pyx --- src/sage/libs/giac/giac.pyx | 206 +++++++++++++----------------------- 1 file changed, 72 insertions(+), 134 deletions(-) diff --git a/src/sage/libs/giac/giac.pyx b/src/sage/libs/giac/giac.pyx index b6f143404fb..d2104a562d4 100644 --- a/src/sage/libs/giac/giac.pyx +++ b/src/sage/libs/giac/giac.pyx @@ -913,13 +913,10 @@ cdef class Pygen(GiacMethods_base): def __repr__(self): - try: - # fast evaluation of the complexity of the gen. (it's not the number of char ) - sig_on() - t=GIAC_taille(self.gptr[0], 6000) - sig_off() - except: - raise RuntimeError + # fast evaluation of the complexity of the gen. (it's not the number of char ) + sig_on() + t=GIAC_taille(self.gptr[0], 6000) + sig_off() if (t<6000) : sig_on() result=decstring23(GIAC_print(self.gptr[0], context_ptr).c_str()) #python3 @@ -954,14 +951,11 @@ cdef class Pygen(GiacMethods_base): sig_off() return rep else: - try: - sig_on() - rep=GIAC_size(self.gptr[0],context_ptr).val - sig_off() - #GIAC_size return a gen. we take the int: val - return rep - except: - raise RuntimeError + sig_on() + rep=GIAC_size(self.gptr[0],context_ptr).val + sig_off() + #GIAC_size return a gen. we take the int: val + return rep def __getitem__(self,i): #TODO?: add gen support for indexes @@ -1004,13 +998,10 @@ cdef class Pygen(GiacMethods_base): if(ii] - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + sig_on() + result=self.gptr[0][i] + sig_off() + return _wrap_gen(result) else: raise IndexError('list index %s out of range'%(i)) else: @@ -1116,13 +1107,10 @@ cdef class Pygen(GiacMethods_base): def eval(self): cdef gen result - try: - sig_on() - result=GIAC_protecteval(self.gptr[0],giacsettings.eval_level,context_ptr) - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + sig_on() + result=GIAC_protecteval(self.gptr[0],giacsettings.eval_level,context_ptr) + sig_off() + return _wrap_gen(result) def __add__(self, right): @@ -1133,14 +1121,10 @@ cdef class Pygen(GiacMethods_base): # otherwise: f=1/(2+sin(5*x)) crash if isinstance(self,Pygen)==False: self=Pygen(self) - - try: - sig_on() - result= (self).gptr[0] + (right).gptr[0] - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + sig_on() + result= (self).gptr[0] + (right).gptr[0] + sig_off() + return _wrap_gen(result) def __call__(self, *args): @@ -1190,14 +1174,10 @@ cdef class Pygen(GiacMethods_base): right=Pygen(right) if isinstance(self,Pygen)==False: self=Pygen(self) - - try: - sig_on() - result= (self).gptr[0] - (right).gptr[0] - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + sig_on() + result= (self).gptr[0] - (right).gptr[0] + sig_off() + return _wrap_gen(result) def __mul__(self, right): """ @@ -1214,18 +1194,14 @@ cdef class Pygen(GiacMethods_base): right=Pygen(right) if isinstance(self,Pygen)==False: self=Pygen(self) - - try: - #result= (self).gptr[0] * (right).gptr[0] - #NB: with the natural previous method, the following error generated by - #giac causes python to quit instead of an error message. - #l=Pygen([1,2]);l.transpose()*l; - sig_on() - result= GIAC_giacmul((self).gptr[0] , (right).gptr[0],context_ptr) - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + #result= (self).gptr[0] * (right).gptr[0] + #NB: with the natural previous method, the following error generated by + #giac causes python to quit instead of an error message. + #l=Pygen([1,2]);l.transpose()*l; + sig_on() + result= GIAC_giacmul((self).gptr[0] , (right).gptr[0],context_ptr) + sig_off() + return _wrap_gen(result) #PB / in python3 is truediv def __div__(self, right): @@ -1243,14 +1219,10 @@ cdef class Pygen(GiacMethods_base): right=Pygen(right) if isinstance(self,Pygen)==False: self=Pygen(self) - - try: - sig_on() - result= GIAC_giacdiv((self).gptr[0] , (right).gptr[0],context_ptr) - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + sig_on() + result= GIAC_giacdiv((self).gptr[0] , (right).gptr[0],context_ptr) + sig_off() + return _wrap_gen(result) def __truediv__(self, right): cdef gen result @@ -1258,14 +1230,10 @@ cdef class Pygen(GiacMethods_base): right=Pygen(right) if isinstance(self,Pygen)==False: self=Pygen(self) - - try: - sig_on() - result= (self).gptr[0] / (right).gptr[0] - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + sig_on() + result= (self).gptr[0] / (right).gptr[0] + sig_off() + return _wrap_gen(result) def __pow__(self, right ,ignored): @@ -1274,14 +1242,10 @@ cdef class Pygen(GiacMethods_base): right=Pygen(right) if isinstance(self,Pygen)==False: self=Pygen(self) - - try: - sig_on() - result= GIAC_pow((self).gptr[0],(right).gptr[0], context_ptr ) - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + sig_on() + result= GIAC_pow((self).gptr[0],(right).gptr[0], context_ptr ) + sig_off() + return _wrap_gen(result) def __mod__(self, right): cdef gen result @@ -1289,31 +1253,23 @@ cdef class Pygen(GiacMethods_base): right=Pygen(right) if not isinstance(self,Pygen): self=Pygen(self) - - try: - #result= gen(GIAC_makenewvecteur((self).gptr[0],(right).gptr[0]),1) - #to have an integer output: - #result= GIAC_smod(result,context_ptr) - #we give a modular output: - sig_on() - result= GIAC_giacmod((self).gptr[0],(right).gptr[0],context_ptr) - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + #result= gen(GIAC_makenewvecteur((self).gptr[0],(right).gptr[0]),1) + #to have an integer output: + #result= GIAC_smod(result,context_ptr) + #we give a modular output: + sig_on() + result= GIAC_giacmod((self).gptr[0],(right).gptr[0],context_ptr) + sig_off() + return _wrap_gen(result) def __neg__(self): cdef gen result if isinstance(self,Pygen)==False: self=Pygen(self) - - try: - sig_on() - result= GIAC_neg((self).gptr[0]) - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + sig_on() + result= GIAC_neg((self).gptr[0]) + sig_off() + return _wrap_gen(result) def __pos__(self): return self @@ -1344,12 +1300,9 @@ cdef class Pygen(GiacMethods_base): (x+y+z+2)^10 sage: F.close() """ - try: - sig_on() - GIAC_archive( encstring23(filename), (self).gptr[0], context_ptr) - sig_off() - except: - raise RuntimeError + sig_on() + GIAC_archive( encstring23(filename), (self).gptr[0], context_ptr) + sig_off() @@ -1511,18 +1464,13 @@ cdef class Pygen(GiacMethods_base): True """ typ = self._type - # _INT_ or _ZINT - if(typ == 0 or typ == 2): + if typ == 0 or typ == 2: return QQ(ZZ(self)) # _FRAC_ - elif(typ == 10): + elif typ == 10: # giac _RAT_ - try: - result=ZZ(self.numer())/ZZ(self.denom()) - return result - except: - RuntimeError("Failed to convert to QQ") + return ZZ(self.numer()) / ZZ(self.denom()) else: raise TypeError("Cannot convert non giac _FRAC_ to QQ") @@ -1727,7 +1675,7 @@ cdef class Pygen(GiacMethods_base): v = self.dim() try: n = v._val - except: + except AttributeError: raise TypeError("Entry is not a giac vector") from sage.modules.free_module_element import vector sig_on() @@ -1790,17 +1738,10 @@ cdef class Pygen(GiacMethods_base): other=Pygen(other) if isinstance(self,Pygen)==False: self=Pygen(self) - - try: - sig_on() - result= giacgenrichcmp((self).gptr[0],(other).gptr[0], op, context_ptr ) - sig_off() - except: - raise RuntimeError - if result==1 : - return True - else: - return False + sig_on() + result= giacgenrichcmp((self).gptr[0],(other).gptr[0], op, context_ptr ) + sig_off() + return result == 1 # # Some attributes of the gen class: @@ -2197,13 +2138,10 @@ def loadgiacgen(str filename): sage: F.close() """ cdef gen result - try: - sig_on() - result=GIAC_unarchive( encstring23(filename), context_ptr) - sig_off() - return _wrap_gen(result) - except: - raise RuntimeError + sig_on() + result=GIAC_unarchive( encstring23(filename), context_ptr) + sig_off() + return _wrap_gen(result) From 66ec40edd4ac85ab46852a7d79b9f1ea68b4e17f Mon Sep 17 00:00:00 2001 From: Jonathan Kliem Date: Fri, 29 Oct 2021 10:52:43 +0200 Subject: [PATCH 07/15] codestyle --- src/sage/libs/giac/giac.pyx | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/sage/libs/giac/giac.pyx b/src/sage/libs/giac/giac.pyx index d2104a562d4..a6f4b54509a 100644 --- a/src/sage/libs/giac/giac.pyx +++ b/src/sage/libs/giac/giac.pyx @@ -1129,38 +1129,38 @@ cdef class Pygen(GiacMethods_base): def __call__(self, *args): cdef gen result - n=len(args) - if (n>1): - #FIXME? improve with a vector, or improve Pygen(list) - right=Pygen(args).eval() - elif (n==1): - right=Pygen(args[0]) + n = len(args) + if n > 1: + # FIXME? improve with a vector, or improve Pygen(list) + right = Pygen(args).eval() + elif n == 1: + right = Pygen(args[0]) else: - right=GIACNULL - if isinstance(self,Pygen)==False: - self=Pygen(self) -# Some giac errors such as pari_locked are caught by the try -# so we can't put the sig_on() in the try. -# But now a keyboard interrupt fall back to this sig_on so -# it may have left the giac pari locked. + right = GIACNULL + if isinstance(self, Pygen) == False: + self = Pygen(self) + # Some giac errors such as pari_locked are caught by the try + # so we can't put the sig_on() in the try. + # But now a keyboard interrupt fall back to this sig_on so + # it may have left the giac pari locked. sig_on() try: - result= ((self).gptr[0])((right).gptr[0],context_ptr) + result = (( self).gptr[0])(( right).gptr[0], context_ptr) sig_off() return _wrap_gen(result) except: # The previous computation might have failed due to a pari_lock # So we will not raise an exception yet. - tmp=Pygen('pari_unlock()').eval() + tmp = Pygen('pari_unlock()').eval() # if pari was not locked in giac, we have locked it, so unlock it. - if(tmp==0): + if tmp == 0: Pygen('pari_unlock()').eval() sig_off() raise else: try: - result= GIAC_eval((right).gptr[0],1,context_ptr) - result= ((self).gptr[0])(result,context_ptr) + result = GIAC_eval((right).gptr[0], 1, context_ptr) + result = ((self).gptr[0])(result, context_ptr) sig_off() return _wrap_gen(result) except: From be872c16d193602a548c98b1b18deb24dc2e0d37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Fri, 29 Oct 2021 13:42:46 +0200 Subject: [PATCH 08/15] some fixes in giac, schemes, geometry --- src/sage/geometry/polyhedron/base.py | 2 +- src/sage/libs/giac/giac.pyx | 20 ++++--------------- .../schemes/projective/projective_space.py | 2 +- 3 files changed, 6 insertions(+), 18 deletions(-) diff --git a/src/sage/geometry/polyhedron/base.py b/src/sage/geometry/polyhedron/base.py index adb0c82959a..e9370d55e35 100644 --- a/src/sage/geometry/polyhedron/base.py +++ b/src/sage/geometry/polyhedron/base.py @@ -5276,7 +5276,7 @@ def _test_dilation(self, tester=None, **options): new_ring = None try: new_ring = self.base_ring().composite_fields()[0] - except (KeyError, AttributeError): + except (KeyError, AttributeError, TypeError): # This isn't about testing composite fields. pass if new_ring: diff --git a/src/sage/libs/giac/giac.pyx b/src/sage/libs/giac/giac.pyx index d2104a562d4..f736b4b421e 100644 --- a/src/sage/libs/giac/giac.pyx +++ b/src/sage/libs/giac/giac.pyx @@ -171,28 +171,16 @@ from sage.interfaces.giac import giac #### Python3 compatibility ############################# -if Pyversioninfo[0]>2 : - PythonVersion3 = True -else: - PythonVersion3 = False +PythonVersion3 = True def decstring23(s): - if PythonVersion3 : - return s.decode() - else: - return s + return s.decode() def encstring23(s): - if PythonVersion3 : - return bytes(s,'UTF-8') - else: - return s + return bytes(s,'UTF-8') -if PythonVersion3: - listrange=list,range -else: - listrange=list +listrange = list,range ####End of Python3 compatibility######################## diff --git a/src/sage/schemes/projective/projective_space.py b/src/sage/schemes/projective/projective_space.py index 36deeab7827..f1f89b4513c 100644 --- a/src/sage/schemes/projective/projective_space.py +++ b/src/sage/schemes/projective/projective_space.py @@ -1693,7 +1693,7 @@ def hyperplane_transformation_matrix(self, plane_1, plane_2): if len(source_points) == N: try: plane(point) - except ValueError: + except (ValueError, TypeError): source_points.append(self(point)) base_list = [list(s) for s in source_points] elif len(source_points) == N + 1: From 0113b72725babbf822e7be0831c8281db4253a57 Mon Sep 17 00:00:00 2001 From: Jonathan Kliem Date: Fri, 29 Oct 2021 14:14:06 +0200 Subject: [PATCH 09/15] code style again --- src/sage/libs/giac/giac.pyx | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/sage/libs/giac/giac.pyx b/src/sage/libs/giac/giac.pyx index a80d9c92907..b888e7e3c9e 100644 --- a/src/sage/libs/giac/giac.pyx +++ b/src/sage/libs/giac/giac.pyx @@ -2014,38 +2014,38 @@ class GiacFunction(Pygen): """ def __call__(self, *args): cdef gen result - n=len(args) - if (n>1): - #FIXME? improve with a vector, or improve Pygen(list) - right=Pygen(args).eval() - elif (n==1): - right=Pygen(args[0]).eval() + n = len(args) + if n > 1: + # FIXME? improve with a vector, or improve Pygen(list) + right = Pygen(args).eval() + elif n == 1: + right = Pygen(args[0]) else: - right=GIACNULL - if isinstance(self,Pygen)==False: - self=Pygen(self) -# Some giac errors such as pari_locked are caught by the try -# so we can't put the sig_on() in the try. -# But now a keyboard interrupt fall back to this sig_on so -# it may have left the giac pari locked. + right = GIACNULL + if isinstance(self, Pygen) == False: + self = Pygen(self) + # Some giac errors such as pari_locked are caught by the try + # so we can't put the sig_on() in the try. + # But now a keyboard interrupt fall back to this sig_on so + # it may have left the giac pari locked. sig_on() try: - result= ((self).gptr[0])((right).gptr[0],context_ptr) + result = (( self).gptr[0])(( right).gptr[0], context_ptr) sig_off() return _wrap_gen(result) except: # The previous computation might have failed due to a pari_lock # So we will not raise an exception yet. - tmp=Pygen('pari_unlock()').eval() + tmp = Pygen('pari_unlock()').eval() # if pari was not locked in giac, we have locked it, so unlock it. - if(tmp==0): + if tmp == 0: Pygen('pari_unlock()').eval() sig_off() raise else: try: - result= GIAC_eval((right).gptr[0],1,context_ptr) - result= ((self).gptr[0])(result,context_ptr) + result = GIAC_eval((right).gptr[0], 1, context_ptr) + result = ((self).gptr[0])(result, context_ptr) sig_off() return _wrap_gen(result) except: From 6c08ce185d4a44e89cf8d2804f0be658a8e95dee Mon Sep 17 00:00:00 2001 From: Jonathan Kliem Date: Fri, 29 Oct 2021 15:02:06 +0200 Subject: [PATCH 10/15] remove blank except in GIAC call --- src/sage/libs/giac/giac.pyx | 58 ++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/src/sage/libs/giac/giac.pyx b/src/sage/libs/giac/giac.pyx index b888e7e3c9e..eb6fed7697e 100644 --- a/src/sage/libs/giac/giac.pyx +++ b/src/sage/libs/giac/giac.pyx @@ -1117,6 +1117,9 @@ cdef class Pygen(GiacMethods_base): def __call__(self, *args): cdef gen result + cdef Pygen pari_unlock = Pygen('pari_unlock()') + cdef gen pari_unlock_result + cdef Pygen right n = len(args) if n > 1: # FIXME? improve with a vector, or improve Pygen(list) @@ -1133,27 +1136,23 @@ cdef class Pygen(GiacMethods_base): # it may have left the giac pari locked. sig_on() try: - result = (( self).gptr[0])(( right).gptr[0], context_ptr) - sig_off() - return _wrap_gen(result) - except: + result = self.gptr[0](right.gptr[0], context_ptr) + except RuntimeError: # The previous computation might have failed due to a pari_lock # So we will not raise an exception yet. - tmp = Pygen('pari_unlock()').eval() + pari_unlock_result = GIAC_eval(pari_unlock.gptr[0], 1, context_ptr) + tmp = _wrap_gen(result) # if pari was not locked in giac, we have locked it, so unlock it. if tmp == 0: - Pygen('pari_unlock()').eval() - sig_off() + pari_unlock_result = GIAC_eval(pari_unlock.gptr[0], 1, context_ptr) + tmp = _wrap_gen(result) raise else: - try: - result = GIAC_eval((right).gptr[0], 1, context_ptr) - result = ((self).gptr[0])(result, context_ptr) - sig_off() - return _wrap_gen(result) - except: - sig_off() - raise + result = GIAC_eval(right.gptr[0], 1, context_ptr) + result = self.gptr[0](result, context_ptr) + finally: + sig_off() + return _wrap_gen(result) def __sub__(self, right): @@ -2014,6 +2013,9 @@ class GiacFunction(Pygen): """ def __call__(self, *args): cdef gen result + cdef Pygen pari_unlock = Pygen('pari_unlock()') + cdef gen pari_unlock_result + cdef Pygen right n = len(args) if n > 1: # FIXME? improve with a vector, or improve Pygen(list) @@ -2030,27 +2032,23 @@ class GiacFunction(Pygen): # it may have left the giac pari locked. sig_on() try: - result = (( self).gptr[0])(( right).gptr[0], context_ptr) - sig_off() - return _wrap_gen(result) - except: + result = ( self).gptr[0](right.gptr[0], context_ptr) + except RuntimeError: # The previous computation might have failed due to a pari_lock # So we will not raise an exception yet. - tmp = Pygen('pari_unlock()').eval() + pari_unlock_result = GIAC_eval(pari_unlock.gptr[0], 1, context_ptr) + tmp = _wrap_gen(result) # if pari was not locked in giac, we have locked it, so unlock it. if tmp == 0: - Pygen('pari_unlock()').eval() - sig_off() + pari_unlock_result = GIAC_eval(pari_unlock.gptr[0], 1, context_ptr) + tmp = _wrap_gen(result) raise else: - try: - result = GIAC_eval((right).gptr[0], 1, context_ptr) - result = ((self).gptr[0])(result, context_ptr) - sig_off() - return _wrap_gen(result) - except: - sig_off() - raise + result = GIAC_eval(right.gptr[0], 1, context_ptr) + result = ( self).gptr[0](result, context_ptr) + finally: + sig_off() + return _wrap_gen(result) class GiacFunctionNoEV(Pygen): # a class to allow to write the __doc__ attribute. From 04a1f01de963dbc6a7c8f67bcbcfadbf1cd9a9c7 Mon Sep 17 00:00:00 2001 From: Jonathan Kliem Date: Fri, 29 Oct 2021 22:32:15 +0200 Subject: [PATCH 11/15] fix distinction between two calls --- src/sage/libs/giac/giac.pyx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/libs/giac/giac.pyx b/src/sage/libs/giac/giac.pyx index eb6fed7697e..8b81a39c700 100644 --- a/src/sage/libs/giac/giac.pyx +++ b/src/sage/libs/giac/giac.pyx @@ -2021,7 +2021,7 @@ class GiacFunction(Pygen): # FIXME? improve with a vector, or improve Pygen(list) right = Pygen(args).eval() elif n == 1: - right = Pygen(args[0]) + right = Pygen(args[0]).eval() else: right = GIACNULL if isinstance(self, Pygen) == False: From 9905930022910ded1dbd483896a4a171968eded1 Mon Sep 17 00:00:00 2001 From: Jonathan Kliem Date: Fri, 29 Oct 2021 22:39:46 +0200 Subject: [PATCH 12/15] remove code duplication --- src/sage/libs/giac/giac.pyx | 39 +++---------------------------------- 1 file changed, 3 insertions(+), 36 deletions(-) diff --git a/src/sage/libs/giac/giac.pyx b/src/sage/libs/giac/giac.pyx index 8b81a39c700..fc705f9e733 100644 --- a/src/sage/libs/giac/giac.pyx +++ b/src/sage/libs/giac/giac.pyx @@ -2012,43 +2012,10 @@ class GiacFunction(Pygen): a """ def __call__(self, *args): - cdef gen result - cdef Pygen pari_unlock = Pygen('pari_unlock()') - cdef gen pari_unlock_result - cdef Pygen right n = len(args) - if n > 1: - # FIXME? improve with a vector, or improve Pygen(list) - right = Pygen(args).eval() - elif n == 1: - right = Pygen(args[0]).eval() - else: - right = GIACNULL - if isinstance(self, Pygen) == False: - self = Pygen(self) - # Some giac errors such as pari_locked are caught by the try - # so we can't put the sig_on() in the try. - # But now a keyboard interrupt fall back to this sig_on so - # it may have left the giac pari locked. - sig_on() - try: - result = ( self).gptr[0](right.gptr[0], context_ptr) - except RuntimeError: - # The previous computation might have failed due to a pari_lock - # So we will not raise an exception yet. - pari_unlock_result = GIAC_eval(pari_unlock.gptr[0], 1, context_ptr) - tmp = _wrap_gen(result) - # if pari was not locked in giac, we have locked it, so unlock it. - if tmp == 0: - pari_unlock_result = GIAC_eval(pari_unlock.gptr[0], 1, context_ptr) - tmp = _wrap_gen(result) - raise - else: - result = GIAC_eval(right.gptr[0], 1, context_ptr) - result = ( self).gptr[0](result, context_ptr) - finally: - sig_off() - return _wrap_gen(result) + if n == 1: + args = (Pygen(args[0]).eval(),) + return Pygen.__call__(self, *args) class GiacFunctionNoEV(Pygen): # a class to allow to write the __doc__ attribute. From d3df701affc8d1b24775fca5d1ae9bb8d9135e1a Mon Sep 17 00:00:00 2001 From: Thierry Monteil Date: Sat, 30 Oct 2021 14:25:21 +0200 Subject: [PATCH 13/15] #32788 : ensure bare except: statements will not reappear --- src/tox.ini | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tox.ini b/src/tox.ini index 08abc70e5f6..55b12a974b0 100644 --- a/src/tox.ini +++ b/src/tox.ini @@ -84,9 +84,10 @@ description = # E711: comparison to None should be ‘if cond is None:’ # E712: comparison to True should be ‘if cond is True:’ or ‘if cond:’ # E721: do not compare types, use isinstance() + # E722: do not use bare except, specify exception instead # See https://pycodestyle.pycqa.org/en/latest/intro.html#error-codes deps = pycodestyle -commands = pycodestyle --select E401,E70,W605,E711,E712,E721 {posargs:{toxinidir}/sage/} +commands = pycodestyle --select E401,E70,W605,E711,E712,E721,E722 {posargs:{toxinidir}/sage/} [pycodestyle] max-line-length = 160 From e92b905a359977dce92a0b8118d26fd41877ac48 Mon Sep 17 00:00:00 2001 From: Jonathan Kliem Date: Wed, 10 Nov 2021 18:56:22 +0100 Subject: [PATCH 14/15] mark polymake_expect import as optional --- src/sage/interfaces/polymake.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/interfaces/polymake.py b/src/sage/interfaces/polymake.py index c5da77ddd23..6cbcb62d7b1 100644 --- a/src/sage/interfaces/polymake.py +++ b/src/sage/interfaces/polymake.py @@ -2114,7 +2114,7 @@ def _eval_line(self, line, allow_use_file=True, wait_for_prompt=True, restart_if EXAMPLES:: - sage: from sage.interfaces.polymake import polymake_expect as polymake + sage: from sage.interfaces.polymake import polymake_expect as polymake # optional - polymake_expect sage: p = polymake.cube(3) # optional - polymake_expect # indirect doctest Here we see that remarks printed by polymake are displayed if From f463e49b287475f9751e16d8d241fc030b606953 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Thu, 18 Nov 2021 11:19:21 +0100 Subject: [PATCH 15/15] comment before --- src/sage/schemes/product_projective/rational_point.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/schemes/product_projective/rational_point.py b/src/sage/schemes/product_projective/rational_point.py index 8f56fcd8637..fd9153da37e 100644 --- a/src/sage/schemes/product_projective/rational_point.py +++ b/src/sage/schemes/product_projective/rational_point.py @@ -494,8 +494,8 @@ def parallel_function_combination(point_p_max): continue try: - rat_points.add(X(point)) # checks if this point lies on X or not + rat_points.add(X(point)) except (TypeError, ValueError): pass