From 8291d2e1099b1963c31d9671d11dd165a7bbabba Mon Sep 17 00:00:00 2001 From: David Coudert Date: Wed, 11 Sep 2019 11:36:50 +0200 Subject: [PATCH 001/133] trac #28473: maximum_cardinality_search --- src/doc/en/reference/references/index.rst | 10 ++ src/sage/graphs/graph.py | 5 +- src/sage/graphs/traversals.pyx | 171 ++++++++++++++++++++++ 3 files changed, 184 insertions(+), 2 deletions(-) diff --git a/src/doc/en/reference/references/index.rst b/src/doc/en/reference/references/index.rst index 484ee12ae31..dca8a902294 100644 --- a/src/doc/en/reference/references/index.rst +++ b/src/doc/en/reference/references/index.rst @@ -2164,6 +2164,10 @@ REFERENCES: .. [HC2006] Mark van Hoeij and John Cremona, Solving Conics over function fields. J. Théor. Nombres Bordeaux, 2006. +.. [He2006] Pinar Heggernes. *Minimal triangulations of graphs: A survey*. + Discrete Mathematics, 306(3):297-317, 2006. + :doi:`10.1016/j.disc.2005.12.003` + .. [He2002] \H. Heys *A Tutorial on Linear and Differential Cryptanalysis* ; 2002' available at http://www.engr.mun.ca/~howard/PAPERS/ldc_tutorial.pdf @@ -4405,6 +4409,12 @@ REFERENCES: .. [TW1980] \A.D. Thomas and G.V. Wood, Group Tables (Exeter: Shiva Publishing, 1980) +.. [TY1984] Robert Endre Tarjan, Mihalis Yannakakis. *Simple linear-time + algorithms to test chordality of graphs, test acyclicity of + hypergraphs, and selectively reduce acyclic hypergraphs*. + SIAM Journal on Computing, 13:566-579, 1984. + :doi:`10.1137/0213035` + .. [TY2009] Hugh Thomas and Alexander Yong, *A jeu de taquin theory for increasing tableaux, with applications to K-theoretic Schubert calculus*, Algebra and Number Theory 3 (2009), 121-148, diff --git a/src/sage/graphs/graph.py b/src/sage/graphs/graph.py index fbc2b602106..c23b941fda2 100644 --- a/src/sage/graphs/graph.py +++ b/src/sage/graphs/graph.py @@ -8655,7 +8655,7 @@ def most_common_neighbors(self, nonedgesonly=True): from sage.graphs.connectivity import is_triconnected from sage.graphs.comparability import is_comparability from sage.graphs.comparability import is_permutation - + from sage.graphs.traversals import maximum_cardinality_search _additional_categories = { "is_long_hole_free" : "Graph properties", @@ -8683,7 +8683,8 @@ def most_common_neighbors(self, nonedgesonly=True): "bridges" : "Connectivity, orientations, trees", "cleave" : "Connectivity, orientations, trees", "spqr_tree" : "Connectivity, orientations, trees", - "is_triconnected" : "Connectivity, orientations, trees" + "is_triconnected" : "Connectivity, orientations, trees", + "maximum_cardinality_search" : "Traversals" } __doc__ = __doc__.replace("{INDEX_OF_METHODS}",gen_thematic_rest_table_index(Graph,_additional_categories)) diff --git a/src/sage/graphs/traversals.pyx b/src/sage/graphs/traversals.pyx index 0b92d2fde69..d18aab34aec 100644 --- a/src/sage/graphs/traversals.pyx +++ b/src/sage/graphs/traversals.pyx @@ -18,6 +18,7 @@ Graph traversals. :meth:`~lex_M` | Return an ordering of the vertices according the LexM graph traversal. :meth:`~lex_M_slow` | Return an ordering of the vertices according the LexM graph traversal. :meth:`~lex_M_fast` | Return an ordering of the vertices according the LexM graph traversal. + :meth:`~maximum_cardinality_search`| Return an ordering of the vertices according a maximum cardinality search. Methods ------- @@ -43,6 +44,9 @@ from sage.graphs.base.static_sparse_graph cimport free_short_digraph from sage.graphs.base.static_sparse_graph cimport out_degree, has_edge from libc.stdint cimport uint32_t +from libcpp.queue cimport priority_queue +from libcpp.pair cimport pair + def lex_BFS(G, reverse=False, tree=False, initial_vertex=None): r""" Perform a lexicographic breadth first search (LexBFS) on the graph. @@ -1326,3 +1330,170 @@ def is_valid_lex_M_order(G, alpha, F): if not K.is_clique(): return False return True + + +def maximum_cardinality_search(G, reverse=False, tree=False, initial_vertex=None): + r""" + Return an ordering of the vertices according a maximum cardinality search. + + Maximum cardinality search (MCS) is a graph traversal introduced in + [TY1984]_. It starts by assigning an arbitrary vertex (or the specified + ``initial_vertex``) of `G` the last position in the ordering `\alpha`. Every + vertex keeps a weight equal to the number of its already processed neighbors + (i.e., already added to `\alpha`), and a vertex of largest such number is + chosen at each step `i` to be placed in position `n - i` in `\alpha`. This + ordering can be computed in time `O(n + m)`. + + When the graph is chordal, the ordering returned by MCS is a *perfect + elimination ordering*, like :meth:`~sage.graphs.graph.Graph.lex_BFS`. So + this ordering can be used to recognize chordal graphs. See [He2006]_ for + more details. + + .. NOTE:: + + The current implementation is for connected graphs only. + + INPUT: + + - ``G`` -- a Sage Graph + + - ``reverse`` -- boolean (default: ``False``); whether to return the + vertices in discovery order, or the reverse + + - ``tree`` -- boolean (default: ``False``); whether to also return the + discovery directed tree (each vertex being linked to the one that saw + it for the first time) + + - ``initial_vertex`` -- (default: ``None``); the first vertex to consider + + OUPUT: by default, return the ordering `\alpha` as a list. When ``tree`` is + ``True``, the method returns a tuple `(\alpha, T)`, where `T` is a directed + tree with the same set of vertices as `G`and a directed edge from `u` to `v` + if `u` was the first vertex to saw `v`. + + EXAMPLES: + + When specified, the ``initial_vertex`` is placed at the end of the ordering, + unless parameter ``reverse`` is ``True``, in which case it is placed at the + beginning:: + + sage: G = graphs.PathGraph(4) + sage: G.maximum_cardinality_search(initial_vertex=0) + [3, 2, 1, 0] + sage: G.maximum_cardinality_search(initial_vertex=1) + [0, 3, 2, 1] + sage: G.maximum_cardinality_search(initial_vertex=2) + [0, 1, 3, 2] + sage: G.maximum_cardinality_search(initial_vertex=3) + [0, 1, 2, 3] + sage: G.maximum_cardinality_search(initial_vertex=3, reverse=True) + [3, 2, 1, 0] + + Returning the discovery tree:: + + sage: G = graphs.PathGraph(4) + sage: _, T = G.maximum_cardinality_search(tree=True, initial_vertex=0) + sage: T.order(), T.size() + (4, 3) + sage: T.edges(labels=False, sort=True) + [(1, 0), (2, 1), (3, 2)] + sage: _, T = G.maximum_cardinality_search(tree=True, initial_vertex=3) + sage: T.edges(labels=False, sort=True) + [(0, 1), (1, 2), (2, 3)] + + TESTS: + + sage: Graph().maximum_cardinality_search() + [] + sage: Graph(1).maximum_cardinality_search() + [0] + sage: Graph(2).maximum_cardinality_search() + Traceback (most recent call last): + ... + ValueError: the input graph is not connected + sage: graphs.PathGraph(2).maximum_cardinality_search(initial_vertex=17) + Traceback (most recent call last): + ... + ValueError: vertex (17) is not a vertex of the graph + """ + if tree: + from sage.graphs.digraph import DiGraph + + cdef int N = G.order() + if not N: + return ([], DiGraph()) if tree else [] + if N == 1: + return (list(G), DiGraph(G)) if tree else list(G) + + cdef list int_to_vertex = list(G) + + if initial_vertex is None: + initial_vertex = 0 + elif initial_vertex in G: + initial_vertex = int_to_vertex.index(initial_vertex) + else: + raise ValueError("vertex ({0}) is not a vertex of the graph".format(initial_vertex)) + + cdef short_digraph sd + init_short_digraph(sd, G, edge_labelled=False, vertex_list=int_to_vertex) + cdef uint32_t** p_vertices = sd.neighbors + cdef uint32_t* p_tmp + cdef uint32_t* p_end + + cdef MemoryAllocator mem = MemoryAllocator() + cdef int* weight = mem.calloc(N, sizeof(int)) + cdef bint* seen = mem.calloc(N, sizeof(bint)) + cdef int* pred = mem.allocarray(N, sizeof(int)) + + cdef int i, u, v + for i in range(G.order()): + weight[i] = 0 + seen[i] = False + pred[i] = i + + # We emulate a heap with decrease key operation using a priority queue. + # A vertex can be inserted multiple times (up to its degree), but only the + # first extraction (with maximum weight) matters. The size of the queue will + # never exceed O(m). + cdef priority_queue[pair[int, int]] pq + pq.push((0, initial_vertex)) + + # The ordering alpha is feed in reversed order and revert afterword + cdef list alpha = [] + + while not pq.empty(): + _, u = pq.top() + pq.pop() + if seen[u]: + # We use a lazy decrease key mode, so u can be several times in pq + continue + + alpha.append(int_to_vertex[u]) + seen[u] = True + + p_tmp = p_vertices[u] + p_end = p_vertices[u + 1] + while p_tmp < p_end: + v = p_tmp[0] + if not seen[v]: + weight[v] += 1 + pq.push((weight[v], v)) + if pred[v] == v: + pred[v] = u + p_tmp += 1 + + free_short_digraph(sd) + + if len(alpha) < N: + raise ValueError("the input graph is not connected") + + if not reverse: + alpha.reverse() + + if tree: + D = DiGraph([int_to_vertex, [(int_to_vertex[i], int_to_vertex[pred[i]]) + for i in range(N) if pred[i] != i]], + format="vertices_and_edges") + return alpha, D + + return alpha From cccded58088e93e661d978851a2b812711d5f13c Mon Sep 17 00:00:00 2001 From: David Coudert Date: Wed, 11 Sep 2019 13:59:28 +0200 Subject: [PATCH 002/133] trac #28473: maximum_cardinality_search_M --- src/doc/en/reference/references/index.rst | 10 + src/sage/graphs/graph.py | 4 +- src/sage/graphs/traversals.pyx | 330 ++++++++++++++++++++++ 3 files changed, 343 insertions(+), 1 deletion(-) diff --git a/src/doc/en/reference/references/index.rst b/src/doc/en/reference/references/index.rst index dca8a902294..e69d6868d07 100644 --- a/src/doc/en/reference/references/index.rst +++ b/src/doc/en/reference/references/index.rst @@ -370,6 +370,11 @@ REFERENCES: Thue-Morse sequence. Pure Math. Appl., 19(2-3):39--52, 2008. +.. [BBHP2004] Anne Berry, Jean R. S. Blair, Pinar Heggernes, + Barry W. Peyton. *Maximum Cardinality Search for Computing Minimal + Triangulations of Graphs*. Algorithmica 39(4):287-298, 2004. + :doi:`10.1007/s00453-004-1084-3` + .. [BBISHAR2015] \S. Banik, A. Bogdanov, T. Isobe, K. Shibutani, H. Hiwatari, \T. Akishita, and F. Regazzoni, *Midori: A block cipher for low energy*; in ASIACRYPT, (2015), pp. 411-436. @@ -832,6 +837,11 @@ REFERENCES: *Sequences with constant number of return words*. Monatsh. Math, 155 (2008) 251-263. +.. [BPS2010] Anne Berry, Romain Pogorelcnik and Genevieve Simonet. + *An Introduction to Clique Minimal Separator Decomposition*. + Algorithms 3(2):197-215, 2010. + :doi:`10.3390/a3020197` + .. [BPU2016] Alex Biryukov, Léo Perrin, Aleksei Udovenko, *Reverse-Engineering the S-Box of Streebog, Kuznyechik and STRIBOBr1*; in EuroCrypt'16, pp. 372-402. diff --git a/src/sage/graphs/graph.py b/src/sage/graphs/graph.py index c23b941fda2..0bd21dc0899 100644 --- a/src/sage/graphs/graph.py +++ b/src/sage/graphs/graph.py @@ -8656,6 +8656,7 @@ def most_common_neighbors(self, nonedgesonly=True): from sage.graphs.comparability import is_comparability from sage.graphs.comparability import is_permutation from sage.graphs.traversals import maximum_cardinality_search + from sage.graphs.traversals import maximum_cardinality_search_M _additional_categories = { "is_long_hole_free" : "Graph properties", @@ -8684,7 +8685,8 @@ def most_common_neighbors(self, nonedgesonly=True): "cleave" : "Connectivity, orientations, trees", "spqr_tree" : "Connectivity, orientations, trees", "is_triconnected" : "Connectivity, orientations, trees", - "maximum_cardinality_search" : "Traversals" + "maximum_cardinality_search" : "Traversals", + "maximum_cardinality_search_M" : "Traversals" } __doc__ = __doc__.replace("{INDEX_OF_METHODS}",gen_thematic_rest_table_index(Graph,_additional_categories)) diff --git a/src/sage/graphs/traversals.pyx b/src/sage/graphs/traversals.pyx index d18aab34aec..5ff05c3487a 100644 --- a/src/sage/graphs/traversals.pyx +++ b/src/sage/graphs/traversals.pyx @@ -43,9 +43,11 @@ from sage.graphs.base.static_sparse_graph cimport init_short_digraph from sage.graphs.base.static_sparse_graph cimport free_short_digraph from sage.graphs.base.static_sparse_graph cimport out_degree, has_edge from libc.stdint cimport uint32_t +from cysignals.signals cimport sig_on, sig_off, sig_check from libcpp.queue cimport priority_queue from libcpp.pair cimport pair +from libcpp.vector cimport vector def lex_BFS(G, reverse=False, tree=False, initial_vertex=None): r""" @@ -1497,3 +1499,331 @@ def maximum_cardinality_search(G, reverse=False, tree=False, initial_vertex=None return alpha, D return alpha + + +cdef inline int swap(int* alpha, int* alpha_inv, int u, int new_pos_u): + """ + Swap positions of u and v in alpha, where v is be the vertex occupying cell + new_pos_u in alpha. + """ + cdef int v = alpha[new_pos_u] + alpha[new_pos_u], alpha[alpha_inv[u]] = u, v + alpha_inv[u], alpha_inv[v] = alpha_inv[v], alpha_inv[u] + return v + +cdef maximum_cardinality_search_M_short_digraph(short_digraph sd, int initial_vertex, + int* alpha, int* alpha_inv, list F, bint* X): + r""" + Compute the ordering and the edges of the triangulation produced by MCS-M. + + Maximum cardinality search M (MCS-M) is an extension of MCS + (:meth:`~sage.graphs.traversals.maximum_cardinality_search`) in the same way + that Lex-M (:meth:`~sage.graphs.traversals.lex_M`) is an extension of + Lex-BFS (:meth:`~sage.graphs.traversalslex_BFS`). That is, in MCS-M when `u` + receives number `i` at step `n - i + 1`, it increments the weight of all + unnumbered vertices `v` for which there exists a path between `u` and `v` + consisting only of unnumbered vertices with weight strictly less than + `w^-(u)` and `w^-(v)`, where `w^-` is the number of times a vertex has been + reached during previous iterations. See [BBHP2004]_ for the details of this + `O(nm)` time algorithm. + + If `G` is not connected, the orderings of each of its connected components + are added consecutively. + + This method is the core of + :meth:`~sage.graphs.traversals.maximum_cardinality_search_M`. + + INPUT: + + - ``sd`` -- a ``short_digraph`` as documented in + :mod:`~sage.graphs.base.static_sparse_graph` + + - ``initial_vertex`` -- int; initial vertex for the search + + - ``alpha`` -- int array of size `N`; the computed ordering of MCS-M + + - ``alpha_inv`` -- int array of size `N`; the position of vertex ``u`` in + ``alpha``, that is the inverse function of alpha. So we have + ``alpha[alpha_inv[u]] == u`` for all `0 \leq u < N - 1`. + + - ``F`` -- list; to be filled with the edges of the triangulation + + - ``X`` -- boolean array of size `N`; ``X[u]`` is set to ``True`` if the + neighborhood of `u` is a separator of the graph + + TESTS:: + + sage: Graph().maximum_cardinality_search_M() + ([], [], []) + sage: Graph(1).maximum_cardinality_search_M() + ([0], [], []) + sage: graphs.PathGraph(2).maximum_cardinality_search_M(initial_vertex=17) + Traceback (most recent call last): + ... + ValueError: vertex (17) is not a vertex of the graph + + .. TODO:: + + Use a fast heap data structure with decrease-key operation. + """ + # Initialization of data structures + cdef int N = sd.n + cdef MemoryAllocator mem = MemoryAllocator() + # number of times a vertex is reached, initially 0 + cdef int* weight = mem.calloc(N, sizeof(int)) + # has a vertex been reached, initally False + cdef bint* reached = mem.calloc(N, sizeof(bint)) + + cdef int i, u, v, xi + for i in range(N): + weight[i] = 0 + alpha[i] = i + alpha_inv[i] = i + X[i] = False + + # If an initial vertex is specified, we put it at position 0 in alpha. + # This way, it will be the first vertex to be considered. + if initial_vertex: + swap(alpha, alpha_inv, initial_vertex, 0) + + # variables for the manipulation of the short digraph + cdef uint32_t** p_vertices = sd.neighbors + cdef uint32_t* p_tmp + cdef uint32_t* p_end + + cdef vector[vector[int]] reach + cdef int s = -1 + cdef int current_pos = N + + while current_pos: + + # Choose an unnumbered vertex of maximum weight. + # This could be done faster if we had a heap data structure with + # decrease key operation. + u = alpha[0] + for i in range(current_pos): + v = alpha[i] + if weight[u] < weight[v]: + u = v + + # Swap u and the vertex v occupying position current_pos in alpha + current_pos -= 1 + v = swap(alpha, alpha_inv, u, current_pos) + reached[u] = True + + # If the weight decreases, the neighborhood of u is a separator + if weight[u] <= s: + X[u] = True + s = weight[u] + + # Search for new edges of the triangulation. + # We add an edge to the triangulation between u and any unnumbered + # vertex v such that there is a path (v, x1, x2,... , xk, u) through + # unnumbered vertices such that count-[xi] < count-[v], 1 <= i <= k. If + # such an edge is found, we increase the count of v for next round. + + # Mark all unnumbered vertices unreached. These vertices occupy + # positions 0,..,current_pos-1 in alpha + reach.clear() + reach.resize(N) + for i in range(current_pos): + v = alpha[i] + reached[v] = False + + # Initialize reach with unnumbered neighbors of u + p_tmp = p_vertices[u] + p_end = p_vertices[u + 1] + while p_tmp < p_end: + v = p_tmp[0] + p_tmp += 1 + if not reached[v]: + reach[weight[v]].push_back(v) + reached[v] = True + weight[v] += 1 + + # Search + for i in range(N): + while not reach[i].empty(): + xi = reach[i].back() + reach[i].pop_back() + p_tmp = p_vertices[xi] + p_end = p_vertices[xi + 1] + while p_tmp < p_end: + v = p_tmp[0] + p_tmp += 1 + if reached[v]: + continue + reached[v] = True + if i < weight[v]: + reach[weight[v]].push_back(v) + weight[v] += 1 + F.append((u, v)) + else: + reach[i].push_back(v) + + reach.clear() + +def maximum_cardinality_search_M(G, initial_vertex=None): + r""" + Return the ordering and the edges of the triangulation produced by MCS-M. + + Maximum cardinality search M (MCS-M) is an extension of MCS + (:meth:`~sage.graphs.traversals.maximum_cardinality_search`) in the same way + that Lex-M (:meth:`~sage.graphs.traversals.lex_M`) is an extension of + Lex-BFS (:meth:`~sage.graphs.traversals.lex_BFS`). That is, in MCS-M when + `u` receives number `i` at step `n - i + 1`, it increments the weight of all + unnumbered vertices `v` for which there exists a path between `u` and `v` + consisting only of unnumbered vertices with weight strictly less than + `w^-(u)` and `w^-(v)`, where `w^-` is the number of times a vertex has been + reached during previous iterations. See [BBHP2004]_ for the details of this + `O(nm)` time algorithm. + + If `G` is not connected, the orderings of each of its connected components + are added consecutively. Furthermore, if `G` has `k` connected components + `C_i` for `0 \leq i < k`, `X` contains at least one vertex of `C_i` for each + `i \geq 1`. Hence, `|X| \geq k - 1`. In particular, some isolated vertices + (i.e., of degree 0) can appear in `X` as for such a vertex `x`, we have that + `G \setminus N(x) = G` is not connected. + + INPUT: + + - ``G`` -- a Sage graph + + - ``initial_vertex`` -- (default: ``None``); the first vertex to consider + + OUTPUT: a tuple `(\alpha, F, X)`, where + + - `\alpha` is the resulting ordering of the vertices. If an initial vertex + is specified, it gets the last position in the ordering `\alpha`. + + - `F` is the list of edges of a minimal triangulation of `G` according + `\alpha` + + - `X` is is a list of vertices such that for each `x \in X`, the + neighborhood of `x` in `G` is a separator (i.e., `G \setminus N(x)` is not + connected). Note that we may have `N(x) = \emptyset` if `G` is not + connected and `x` has degree 0. + + EXAMPLES: + + Chordal graphs have a perfect elimination ordering, and so the set `F` of + edges of the triangulation is empty:: + + sage: G = graphs.RandomChordalGraph(20) + sage: alpha, F, X = G.maximum_cardinality_search_M(); F + [] + + The cycle of order 4 is not chordal and so the triangulation has one edge:: + + sage: G = graphs.CycleGraph(4) + sage: alpha, F, X = G.maximum_cardinality_search_M(); len(F) + 1 + + The number of edges needed to triangulate of a cycle graph or order `n` is + `n - 3`, independently of the initial vertex:: + + sage: n = randint(3, 20) + sage: C = graphs.CycleGraph(n) + sage: _, F, X = C.maximum_cardinality_search_M() + sage: len(F) == n - 3 + True + sage: _, F, X = C.maximum_cardinality_search_M(initial_vertex=C.random_vertex()) + sage: len(F) == n - 3 + True + + When an initial vertex is specified, it gets the last position in the + ordering:: + + sage: G = graphs.PathGraph(4) + sage: G.maximum_cardinality_search_M(initial_vertex=0) + ([3, 2, 1, 0], [], [2, 3]) + sage: G.maximum_cardinality_search_M(initial_vertex=1) + ([3, 2, 0, 1], [], [2, 3]) + sage: G.maximum_cardinality_search_M(initial_vertex=2) + ([0, 1, 3, 2], [], [0, 1]) + sage: G.maximum_cardinality_search_M(initial_vertex=3) + ([0, 1, 2, 3], [], [0, 1]) + + + When `G` is not connected, the orderings of each of its connected components + are added consecutively, the vertices of the component containing the + initial vertex occupying the last positions:: + + sage: G = graphs.CycleGraph(4) * 2 + sage: G.maximum_cardinality_search_M()[0] + [5, 4, 6, 7, 2, 3, 1, 0] + sage: G.maximum_cardinality_search_M(initial_vertex=7)[0] + [2, 1, 3, 0, 5, 6, 4, 7] + + Furthermore, if `G` has `k` connected components, `X` contains at least one + vertex per connected component, except for the first one, and so at least `k + - 1` vertices:: + + sage: for k in range(1, 5): + ....: _, _, X = Graph(k).maximum_cardinality_search_M() + ....: if len(X) < k - 1: + ....: raise ValueError("something goes wrong") + sage: G = graphs.RandomGNP(10, .2) + sage: cc = G.connected_components() + sage: _, _, X = G.maximum_cardinality_search_M() + sage: len(X) >= len(cc) - 1 + True + + In the example of [BPS2010]_, the triangulation has 3 edges:: + + sage: G = Graph({'a': ['b', 'k'], 'b': ['c'], 'c': ['d', 'j', 'k'], + ....: 'd': ['e', 'f', 'j', 'k'], 'e': ['g'], + ....: 'f': ['g', 'j', 'k'], 'g': ['j', 'k'], 'h': ['i', 'j'], + ....: 'i': ['k'], 'j': ['k']}) + sage: _, F, _ = G.maximum_cardinality_search_M(initial_vertex='a') + sage: len(F) + 3 + + TESTS:: + + sage: Graph().maximum_cardinality_search_M() + ([], [], []) + sage: Graph(1).maximum_cardinality_search_M() + ([0], [], []) + sage: graphs.PathGraph(2).maximum_cardinality_search_M(initial_vertex=17) + Traceback (most recent call last): + ... + ValueError: vertex (17) is not a vertex of the graph + """ + cdef list int_to_vertex = list(G) + + if initial_vertex is None: + initial_vertex = 0 + elif initial_vertex in G: + initial_vertex = int_to_vertex.index(initial_vertex) + else: + raise ValueError("vertex ({0}) is not a vertex of the graph".format(initial_vertex)) + + cdef int N = G.order() + if not N: + return ([], [], []) + if N == 1: + return (list(G), [], []) + + # Copying the whole graph to obtain the list of neighbors quicker than by + # calling out_neighbors. This data structure is well documented in the + # module sage.graphs.base.static_sparse_graph + cdef short_digraph sd + init_short_digraph(sd, G, edge_labelled=False, vertex_list=int_to_vertex) + + cdef MemoryAllocator mem = MemoryAllocator() + cdef int* alpha = mem.calloc(N, sizeof(int)) + cdef int* alpha_inv = mem.calloc(N, sizeof(int)) + cdef bint* X = mem.calloc(N, sizeof(bint)) + cdef list F = [] + + sig_on() + maximum_cardinality_search_M_short_digraph(sd, initial_vertex, alpha, alpha_inv, F, X) + sig_off() + + free_short_digraph(sd) + + cdef int u, v + return ([int_to_vertex[alpha[u]] for u in range(N)], + [(int_to_vertex[u], int_to_vertex[v]) for u, v in F], + [int_to_vertex[u] for u in range(N) if X[u]]) From 5c0af63cd5d71d0ca9b960bd0317fa0af4e9f0a4 Mon Sep 17 00:00:00 2001 From: David Coudert Date: Wed, 11 Sep 2019 15:55:50 +0200 Subject: [PATCH 003/133] trac #28473: atoms_and_clique_separators --- src/doc/en/reference/graphs/index.rst | 1 + src/module_list.py | 3 + src/sage/graphs/graph.py | 2 + .../clique_separators.pyx | 598 ++++++++++++++++++ src/sage/graphs/traversals.pxd | 8 + src/sage/graphs/traversals.pyx | 4 +- 6 files changed, 614 insertions(+), 2 deletions(-) create mode 100644 src/sage/graphs/graph_decompositions/clique_separators.pyx create mode 100644 src/sage/graphs/traversals.pxd diff --git a/src/doc/en/reference/graphs/index.rst b/src/doc/en/reference/graphs/index.rst index 58bcae6868d..d70ba8951cb 100644 --- a/src/doc/en/reference/graphs/index.rst +++ b/src/doc/en/reference/graphs/index.rst @@ -86,6 +86,7 @@ Libraries of algorithms sage/graphs/graph_decompositions/bandwidth sage/graphs/graph_decompositions/cutwidth sage/graphs/graph_decompositions/graph_products + sage/graphs/graph_decompositions/clique_separators sage/graphs/convexity_properties sage/graphs/weakly_chordal sage/graphs/distances_all_pairs diff --git a/src/module_list.py b/src/module_list.py index 66977cb5b41..aa9095a711c 100644 --- a/src/module_list.py +++ b/src/module_list.py @@ -422,6 +422,9 @@ def uname_specific(name, value, alternative): language="c++", package = 'tdlib'), + Extension('sage.graphs.graph_decompositions.clique_separators', + sources = ['sage/graphs/graph_decompositions/clique_separators.pyx']), + Extension('sage.graphs.spanning_tree', sources = ['sage/graphs/spanning_tree.pyx']), diff --git a/src/sage/graphs/graph.py b/src/sage/graphs/graph.py index 0bd21dc0899..04d1125bc56 100644 --- a/src/sage/graphs/graph.py +++ b/src/sage/graphs/graph.py @@ -8640,6 +8640,7 @@ def most_common_neighbors(self, nonedgesonly=True): from sage.graphs.chrompoly import chromatic_polynomial from sage.graphs.graph_decompositions.rankwidth import rank_decomposition from sage.graphs.graph_decompositions.vertex_separation import pathwidth + from sage.graphs.graph_decompositions.clique_separators import atoms_and_clique_separators from sage.graphs.matchpoly import matching_polynomial from sage.graphs.cliquer import all_max_clique as cliques_maximum from sage.graphs.spanning_tree import random_spanning_tree @@ -8669,6 +8670,7 @@ def most_common_neighbors(self, nonedgesonly=True): "matching_polynomial" : "Algorithmically hard stuff", "all_max_clique" : "Clique-related methods", "cliques_maximum" : "Clique-related methods", + "atoms_and_clique_separators" : "Clique-related methods", "random_spanning_tree" : "Connectivity, orientations, trees", "is_cartesian_product" : "Graph properties", "is_distance_regular" : "Graph properties", diff --git a/src/sage/graphs/graph_decompositions/clique_separators.pyx b/src/sage/graphs/graph_decompositions/clique_separators.pyx new file mode 100644 index 00000000000..80ecc8af5e4 --- /dev/null +++ b/src/sage/graphs/graph_decompositions/clique_separators.pyx @@ -0,0 +1,598 @@ +# -*- coding: utf-8 -*- +# cython: binding=True +# distutils: language = c++ +r""" +Decomposition by clique minimal separators + +This module implements methods related to the decomposition of a graph by clique +minimal separators. See [TY1984]_ and [BPS2010]_ for more details. + +Methods +------- +""" +# **************************************************************************** +# Copyright (C) 2019 David Coudert +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# https://www.gnu.org/licenses/ +# **************************************************************************** + +from libcpp.pair cimport pair +from libcpp.vector cimport vector + +from sage.ext.memory_allocator cimport MemoryAllocator +from sage.graphs.base.static_sparse_graph cimport short_digraph +from sage.graphs.base.static_sparse_graph cimport init_short_digraph +from sage.graphs.base.static_sparse_graph cimport free_short_digraph +from sage.graphs.base.static_sparse_graph cimport has_edge +from libc.stdint cimport uint32_t + +from cysignals.signals cimport sig_on, sig_off, sig_check + +from sage.sets.set import Set + +from sage.graphs.traversals cimport maximum_cardinality_search_M_short_digraph + +def make_tree(atoms, cliques): + r""" + Return a tree of atoms and cliques. + + The atoms are the leaves of the tree and the cliques are the internal + vertices. The number of atoms is the number of cliques plus one. + + As a clique may appear several times in the list ``cliques``, vertices are + numbered by pairs `(i, S)`, where `0 \leq i < |atoms| + |cliques|` and `S` + is either an atom or a clique. + + The root of the tree is the only vertex with even or null degree, i.e., 0 if + ``cliques`` is empty and 2 otherwise. When ``cliques`` is not empty, other + internal vertices (each of which is a clique) have degree 3, and the + leaves (vertices of degree 1) are the atoms. + + INPUT: + + - ``atoms`` -- list of atoms + + - ``cliques`` -- list of cliques + + EXAMPLES:: + + sage: from sage.graphs.graph_decompositions.clique_separators import make_tree + sage: G = graphs.Grid2dGraph(2, 4) + sage: A, Sc = G.atoms_and_clique_separators() + sage: T = make_tree(A, Sc) + sage: all(u[1] in A for u in T if T.degree(u) == 1) + True + sage: all(u[1] in Sc for u in T if T.degree(u) != 1) + True + + TESTS:: + + sage: from sage.graphs.graph_decompositions.clique_separators import make_tree + sage: make_tree([0], [1, 2]) + Traceback (most recent call last): + ... + ValueError: the number of atoms must be the number of cliques plus one + """ + if (atoms or cliques) and len(atoms) != len(cliques) + 1: + raise ValueError("the number of atoms must be the number of cliques plus one") + + from sage.graphs.graph import Graph + T = Graph() + if cliques: + # As a clique can appear several times, we number the vertices by + # pairs (int, Set), with 0 <= int < |atoms| + |cliques| + T.add_path(list(enumerate(cliques))) + j = len(cliques) + T.add_edges((s, (i + j, a)) for s, (i, a) in zip(enumerate(cliques), enumerate(atoms))) + # We have |atoms| = |cliques| + 1. So |atoms| + |cliques| = 2 * j + 1 + T.add_edge((j - 1, cliques[-1]), ( 2 * j, atoms[-1])) + + elif atoms: + # The graph has no clique separator + T.add_vertex(atoms[0]) + + return T + +def make_labelled_rooted_tree(atoms, cliques): + r""" + Return a :class:`~LabelledRootedTree` of atoms and cliques. + + The atoms are the leaves of the tree and the cliques are the internal + vertices. The number of atoms is the number of cliques plus one. + + EXAMPLES:: + + sage: G = graphs.PathGraph(5) + sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) + _____{3}_____ + / / + {3, 4} ____{2}____ + / / + {2, 3} __{1}__ + / / + {0, 1} {1, 2} + + TESTS:: + + sage: from sage.graphs.graph_decompositions.clique_separators import make_labelled_rooted_tree + sage: make_labelled_rooted_tree([0], [1, 2]) + Traceback (most recent call last): + ... + ValueError: the number of atoms must be the number of cliques plus one + """ + from sage.combinat.rooted_tree import LabelledRootedTree + if not atoms and not cliques: + return LabelledRootedTree([]) + + if len(atoms) != len(cliques) + 1: + raise ValueError("the number of atoms must be the number of cliques plus one") + + def to_tree(i, n): + if i < n: + return LabelledRootedTree([LabelledRootedTree([], label=atoms[i]), to_tree(i + 1, n)], + label=cliques[i]) + return LabelledRootedTree([], label=atoms[i]) + + return to_tree(0, len(cliques)) + + + +def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=False): + r""" + Return the atoms of the decomposition of `G` by clique minimal separators. + + Let `G = (V, E)` be a graph. A set `S \subset V` is a clique separator if + `G[S]` is a clique and the graph `G \setminus S` has at least 2 connected + components. Let `C \subset V` be the vertices of a connected component of `G + \setminus S`. The graph `G[C + S]` is an *atom* if it has no clique + separator. + + This method implements the algorithm proposed in [BPS2010]_, that improves + upon the algorithm proposed in [TY1984]_, for computing the atoms and the + clique minimal separators of a graph. This algorithm is based on the + :meth:`maximum_cardinality_search_M` graph traversal and has time complexity + in `O(|V|\cdot|E|)`. + + If the graph is not connected, we insert empty separators between the lists + of separators of each connected components. See the examples below for more + details. + + INPUT: + + - ``G`` -- a Sage graph + + - ``tree`` -- boolean (default: ``False``); whether to return the result as + a directed tree in which internal nodes are clique separators and leaves + are the atoms of the decomposition. Since a clique separator is repeated + when its removal partition the graph into 3 or more connected components, + vertices are labels by tuples `(i, S)`, where `S` is the set of vertices + of the atom or the clique separator, and `0 \leq i \leq |T|`. + + - ``rooted_tree`` -- boolean (default: ``False``); whether to return the + result as a :class:`~sage.combinat.rooted_tree.LabelledRootedTree`. When + ``tree`` is ``True``, this parameter is ignored. + + - ``separators`` -- boolean (default: ``False``); whether to also return the + complete list of separators considered during the execution of the + algorithm. When ``tree`` or ``rooted_tree`` is ``True``, this parameter is + ignored. + + OUTPUT: + + - By default, return a tuple `(A, S_c)`, where `A` is the list of atoms of + the graph in the order of dicovery, and `S_c` is the list of clique + separators, with possible repetitions, in the order the separator has been + considered. If furthermore ``separators`` is ``True``, return a tuple `(A, + S_h, S_c)`, where `S_c` is the list of considered separators of the graph + in the order they have been considered. + + - When ``tree`` is ``True``, format the result as a directed tree + + - When ``rooted_tree`` is ``True`` and ``tree`` is ``False``, format the + ouput as a :class:`~sage.combinat.rooted_tree.LabelledRootedTree` + + EXAMPLES: + + Example of [BPS2010]_:: + + sage: G = Graph({'a': ['b', 'k'], 'b': ['c'], 'c': ['d', 'j', 'k'], + ....: 'd': ['e', 'f', 'j', 'k'], 'e': ['g'], + ....: 'f': ['g', 'j', 'k'], 'g': ['j', 'k'], 'h': ['i', 'j'], + ....: 'i': ['k'], 'j': ['k']}) + sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) # py2 + ____________________{'k', 'j'}_____________ + / / + {'i', 'h', 'k', 'j'} ____________________{'k', 'j', 'd'}_______ + / / + {'e', 'd', 'g', 'f', 'k', 'j'} _________{'c', 'k'}__ + / / + {'a', 'c', 'b', 'k'} {'c', 'j', 'k', 'd'} + sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) # py2 + ____________________{'k', 'j'}_____________ + / / + {'k', 'i', 'j', 'h'} ____________________{'k', 'j', 'd'}_______ + / / + {'k', 'g', 'j', 'f', 'd', 'e'} _________{'k', 'c'}__ + / / + {'k', 'a', 'b', 'c'} {'k', 'j', 'c', 'd'} + + sage: A, Sc = G.atoms_and_clique_separators() + sage: T = G.atoms_and_clique_separators(tree=True) + sage: T.is_tree() + True + sage: T.diameter() == len(A) + True + sage: all(u[1] in A for u in T if T.degree(u) == 1) + True + sage: all(u[1] in Sc for u in T if T.degree(u) != 1) + True + + A graph without clique separator:: + + sage: G = graphs.CompleteGraph(5) + sage: G.atoms_and_clique_separators() + ([{0, 1, 2, 3, 4}], []) + sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) + {0, 1, 2, 3, 4} + + Graphs with several biconnected components:: + + sage: G = graphs.PathGraph(4) + sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) + ____{2}____ + / / + {2, 3} __{1}__ + / / + {1, 2} {0, 1} + + sage: G = graphs.WindmillGraph(3, 4) + sage: G.atoms_and_clique_separators() + ([{0, 1, 2}, {0, 3, 4}, {0, 5, 6}, {0, 8, 7}], [{0}, {0}, {0}]) + sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) + ________{0}________ + / / + {0, 1, 2} _______{0}______ + / / + {0, 3, 4} ____{0}___ + / / + {0, 8, 7} {0, 5, 6} + + When the removal of a clique separator results in `k > 2` connected + components, this separator is repeated `k - 1` times, but the repetitions + are not necessarily contiguous:: + + sage: G = Graph(2) + sage: for i in range(5): + ....: G.add_cycle([0, 1, G.add_vertex()]) + sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) + _________{0, 1}_____ + / / + {0, 1, 4} ________{0, 1}_____ + / / + {0, 1, 2} _______{0, 1}___ + / / + {0, 1, 3} ____{0, 1} + / / + {0, 1, 5} {0, 1, 6} + + sage: G = graphs.StarGraph(3) + sage: G.subdivide_edges(G.edges(), 2) + sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) + ______{5}______ + / / + {1, 5} ______{7}______ + / / + {2, 7} ______{9}______ + / / + {9, 3} ______{6}______ + / / + {6, 7} ______{4}_____ + / / + {4, 5} _____{0}_____ + / / + {0, 6} ____{8}____ + / / + {8, 9} __{0}__ + / / + {0, 8} {0, 4} + + If the graph is not connected, we insert empty separators between the lists + of separators of each connected components. For instance, let `G` be a graph + with 3 connected components. The method returns the list `S_c = + [S_0,\cdots,S_{i},\ldots, S_{j},\ldots,S_{k-1}]` of `k` clique separators, + where `i` and `j` are the indexes of the inserted empty separators and `0 + \leq i < j < k - 1`. The method also returns the list `A = + [A_0,\ldots,S_{k}]` of the `k + 1` atoms, with `k + 1 \geq 3`. The lists of + atoms and clique separators of each of the connected components are + respectively `[A_0,\ldots,A_{i}]` and `[S_0,\ldots,S_{i-1}]`, + `[A_{i+1},\ldots,A_{j}]` and `[S_{i+1},\ldots,S_{j-1}]`, and + `[A_{j+1},\ldots,A_{k}]` and `[S_{j+1},\ldots,S_{k-1}]`. One can check that + for each connected component, we get one atom more than clique separators:: + + sage: G = graphs.PathGraph(3) * 3 + sage: A, Sc = G.atoms_and_clique_separators() + sage: A + [{1, 2}, {0, 1}, {4, 5}, {3, 4}, {8, 7}, {6, 7}] + sage: Sc + [{1}, {}, {4}, {}, {7}] + sage: i , j = [i for i, s in enumerate(Sc) if not s] + sage: i, j + (1, 3) + sage: A[:i+1], Sc[:i] + ([{1, 2}, {0, 1}], [{1}]) + sage: A[i+1:j+1], Sc[i+1:j] + ([{4, 5}, {3, 4}], [{4}]) + sage: A[j+1:], Sc[j+1:] + ([{8, 7}, {6, 7}], [{7}]) + sage: I = [-1, i, j, len(Sc)] + sage: for i, j in zip(I[:-1], I[1:]): + ....: print(A[i+1:j+1], Sc[i+1:j]) + [{1, 2}, {0, 1}] [{1}] + [{4, 5}, {3, 4}] [{4}] + [{8, 7}, {6, 7}] [{7}] + sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) + ______{1}______ + / / + {1, 2} ______{}______ + / / + {0, 1} _____{4}_____ + / / + {4, 5} ____{}_____ + / / + {3, 4} __{7}__ + / / + {6, 7} {8, 7} + + Loops and multiple edges are ignored:: + + sage: G.allow_loops(True) + sage: G.add_edges([(u, u) for u in G]) + sage: G.allow_multiple_edges(True) + sage: G.add_edges(G.edges()) + sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) + ______{1}______ + / / + {1, 2} ______{}______ + / / + {0, 1} _____{4}_____ + / / + {4, 5} ____{}_____ + / / + {3, 4} __{7}__ + / / + {6, 7} {8, 7} + + We can check that the returned list of separators is valid:: + + sage: G = graphs.RandomGNP(50, .1) + sage: while not G.is_connected(): + ....: G = graphs.RandomGNP(50, .1) + sage: _, separators, _ = G.atoms_and_clique_separators(separators=True) + sage: for S in separators: + ....: H = G.copy() + ....: H.delete_vertices(S) + ....: if H.is_connected(): + ....: raise ValueError("something goes wrong") + + TESTS:: + + sage: EmptyGraph = Graph() + sage: EmptyGraph.atoms_and_clique_separators() + ([], []) + sage: EmptyGraph.atoms_and_clique_separators(separators=True) + ([], [], []) + sage: EmptyGraph.atoms_and_clique_separators(tree=True) + Graph on 0 vertices + sage: EmptyGraph.atoms_and_clique_separators(rooted_tree=True) + None[] + sage: ascii_art(EmptyGraph.atoms_and_clique_separators(rooted_tree=True)) + None + sage: I4 = Graph(4) + sage: I4.atoms_and_clique_separators() + ([{0}, {1}, {2}, {3}], [{}, {}, {}]) + sage: I4.atoms_and_clique_separators(separators=True) + ([{0}, {1}, {2}, {3}], [{}, {}, {}], [{}, {}, {}]) + sage: I4.atoms_and_clique_separators(tree=True) + Graph on 7 vertices + sage: I4.atoms_and_clique_separators(rooted_tree=True) + {}[{0}[], {}[{1}[], {}[{3}[], {2}[]]]] + sage: ascii_art(I4.atoms_and_clique_separators(rooted_tree=True)) + ___{}___ + / / + {0} __{}___ + / / + {1} _{}_ + / / + {3} {2} + """ + cdef list A = [] # atoms + cdef list Sh = [] # separators + cdef list Sc = [] # clique separators + cdef bint first = True + + if not G.is_connected(): + from sage.graphs.graph import Graph + + for cc in G.connected_components(): + g = Graph([cc, G.edge_boundary(cc, cc, False, False)], + format='vertices_and_edges', + loops=True, multiedges=True) + res = g.atoms_and_clique_separators(tree=False, rooted_tree=False, separators=separators) + + # Update lists of atoms, separators and clique separators + A.extend(res[0]) + if separators: + if not first: + Sh.append(Set()) + Sh.extend(res[1]) + if not first: + Sc.append(Set()) + Sc.extend(res[2 if separators else 1]) + first = False + + # Format and return the result + if tree: + return make_tree(A, Sc) + elif rooted_tree: + return make_labelled_rooted_tree(A, Sc) + elif separators: + return A, Sh, Sc + return A, Sc + + cdef int N = G.order() + cdef list int_to_vertex = list(G) + + # Copying the whole graph to obtain the list of neighbors quicker than by + # calling out_neighbors. This data structure is well documented in the + # module sage.graphs.base.static_sparse_graph + cdef short_digraph sd + init_short_digraph(sd, G, edge_labelled=False, vertex_list=int_to_vertex) + + # variables for the manipulation of the short digraph + cdef uint32_t** p_vertices = sd.neighbors + cdef uint32_t* p_tmp + cdef uint32_t* p_end + + cdef MemoryAllocator mem = MemoryAllocator() + cdef int* alpha = mem.calloc(N, sizeof(int)) + cdef int* alpha_inv = mem.calloc(N, sizeof(int)) + cdef bint* X = mem.calloc(N, sizeof(bint)) + cdef bint* active = mem.calloc(N, sizeof(bint)) + cdef int* waiting_list = mem.calloc(N, sizeof(int)) + cdef int* seen = mem.calloc(N, sizeof(int)) + cdef list F = [] + cdef int u, v, waiting_begin, waiting_end + + sig_on() + maximum_cardinality_search_M_short_digraph(sd, 0, alpha, alpha_inv, F, X) + sig_off() + + # Instead of building the graph H of the triangulation, extracting the + # neighbors of vertex alpha[i] and then removing that vertex from H, we + # directly build the neighborhoods. Note that vertices are removed from the + # graph of the triangulation in the order of alpha. Hence, at step i, this + # graph has no vertex u such that alpha_inv[u] < i, and edge (u, v) is + # removed from the graph when min(alpha_inv[u], alpha_inv[v]) is removed. + # The neighborhood of x at step i is thus {v in N_H(x) | alpha_inv[v] > i}. + cdef vector[vector[int]] H + H.resize(N) + for u in range(N): + p_tmp = p_vertices[u] + p_end = p_vertices[u + 1] + while p_tmp < p_end: + v = p_tmp[0] + p_tmp += 1 + if u < v: + # We consider edge (u, v) only once, when u > v, and the + # short_digraph data structure ensures that neighbors are sorted + break + if alpha_inv[u] < alpha_inv[v]: + if X[u]: + H[u].push_back(v) + elif X[v]: + H[v].push_back(u) + for u, v in F: + if alpha_inv[u] < alpha_inv[v]: + if X[u]: + H[u].push_back(v) + elif X[v]: + H[v].push_back(u) + + # Instead of using a copy Gp of G and removing from it the vertices of the + # connected component of an atom after its discovery, we use an array of + # booleans to avoid visiting inactive vertices + for u in range(N): + active[u] = True + seen[u] = -1 + + cdef frozenset Sint + cdef vector[int] Sint_min + cdef vector[int] Cint + cdef int ui, vi + cdef bint stop + + for i in range(N): + sig_check() + x = alpha[i] + if X[x] and not H[x].empty(): + + if separators: + Sh.append(Set(int_to_vertex[u] for u in H[x])) + + # Check if the subgraph of G[H[x]] is a clique + stop = False + for ui in range(H[x].size() -1): + u = H[x][ui] + for vi in range(ui + 1, H[x].size()): + if not has_edge(sd, u, H[x][vi]): + stop = True + break + if stop: + break + + # Weird Python syntax which is useful once in a lifetime : if break + # was never called in the loop above, G[H[x]] = G[S] is a clique + else: + # Extract the connected component of Gp - S containing x + Sint = frozenset(H[x]) + Sint_min.clear() + Cint.clear() + Cint.push_back(x) + seen[x] = x + waiting_list[0] = x + waiting_begin = 0 + waiting_end = 0 + while waiting_begin <= waiting_end: + + u = waiting_list[waiting_begin] + waiting_begin += 1 + p_tmp = p_vertices[u] + end = p_vertices[u + 1] + + while p_tmp < end: + v = p_tmp[0] + p_tmp += 1 + + if active[v] and seen[v] != x: + seen[v] = x + if v in Sint: + # We keep only the vertices of the clique + # separator incident to the connected component + # containing x + Sint_min.push_back(v) + else: + Cint.push_back(v) + waiting_end += 1 + waiting_list[waiting_end] = v + + # Store the atom Smin + C and the minimal clique separator Smin + Smin = Set(int_to_vertex[u] for u in Sint_min) + A.append(Set(Smin.set().union(int_to_vertex[u] for u in Cint))) + Sc.append(Smin) + + # "Remove" the vertices of Cint from the graph Gp + for u in Cint: + active[u] = False + + free_short_digraph(sd) + H.clear() + + # We add the last atom + if Sc: + A.append(Set(int_to_vertex[x] for x in range(N) if active[x])) + elif G: + # The graph has no clique separator + A.append(Set(int_to_vertex)) + + # Format and return the result + if tree: + return make_tree(A, Sc) + elif rooted_tree: + return make_labelled_rooted_tree(A, Sc) + if separators: + return A, Sh, Sc + return A, Sc diff --git a/src/sage/graphs/traversals.pxd b/src/sage/graphs/traversals.pxd new file mode 100644 index 00000000000..a81c72dcd9d --- /dev/null +++ b/src/sage/graphs/traversals.pxd @@ -0,0 +1,8 @@ +from sage.graphs.base.static_sparse_graph cimport short_digraph + +cdef maximum_cardinality_search_M_short_digraph(short_digraph sd, + int initial_vertex, + int* alpha, + int* alpha_inv, + list F, + bint* X) diff --git a/src/sage/graphs/traversals.pyx b/src/sage/graphs/traversals.pyx index 5ff05c3487a..5aeb9f70e32 100644 --- a/src/sage/graphs/traversals.pyx +++ b/src/sage/graphs/traversals.pyx @@ -18,7 +18,8 @@ Graph traversals. :meth:`~lex_M` | Return an ordering of the vertices according the LexM graph traversal. :meth:`~lex_M_slow` | Return an ordering of the vertices according the LexM graph traversal. :meth:`~lex_M_fast` | Return an ordering of the vertices according the LexM graph traversal. - :meth:`~maximum_cardinality_search`| Return an ordering of the vertices according a maximum cardinality search. + :meth:`~maximum_cardinality_search` | Return an ordering of the vertices according a maximum cardinality search. + :meth:`~maximum_cardinality_search_M` | Return the ordering and the edges of the triangulation produced by MCS-M. Methods ------- @@ -38,7 +39,6 @@ import collections from libc.string cimport memset from sage.ext.memory_allocator cimport MemoryAllocator -from sage.graphs.base.static_sparse_graph cimport short_digraph from sage.graphs.base.static_sparse_graph cimport init_short_digraph from sage.graphs.base.static_sparse_graph cimport free_short_digraph from sage.graphs.base.static_sparse_graph cimport out_degree, has_edge From 82333b217ed4fc9d33d40d2d1374cde3cb126c64 Mon Sep 17 00:00:00 2001 From: David Coudert Date: Wed, 11 Sep 2019 17:02:53 +0200 Subject: [PATCH 004/133] trac #28473: cleaning --- src/sage/graphs/generic_graph.py | 2 - src/sage/graphs/graph.py | 2 + .../clique_separators.pyx | 105 ++++++++---------- src/sage/graphs/traversals.pyx | 2 +- 4 files changed, 51 insertions(+), 60 deletions(-) diff --git a/src/sage/graphs/generic_graph.py b/src/sage/graphs/generic_graph.py index f8797598f95..746c2806256 100644 --- a/src/sage/graphs/generic_graph.py +++ b/src/sage/graphs/generic_graph.py @@ -203,7 +203,6 @@ :meth:`~GenericGraph.lex_UP` | Perform a lexicographic UP search (LexUP) on the graph. :meth:`~GenericGraph.lex_DFS` | Perform a lexicographic depth first search (LexDFS) on the graph. :meth:`~GenericGraph.lex_DOWN` | Perform a lexicographic DOWN search (LexDOWN) on the graph. - :meth:`~GenericGraph.lex_M` | Return an ordering of the vertices according the LexM graph traversal. **Distances:** @@ -23432,7 +23431,6 @@ def is_self_complementary(self): from sage.graphs.traversals import lex_UP from sage.graphs.traversals import lex_DFS from sage.graphs.traversals import lex_DOWN - from sage.graphs.traversals import lex_M def katz_matrix(self, alpha, nonedgesonly=False, vertices=None): r""" diff --git a/src/sage/graphs/graph.py b/src/sage/graphs/graph.py index 04d1125bc56..83f14165864 100644 --- a/src/sage/graphs/graph.py +++ b/src/sage/graphs/graph.py @@ -8656,6 +8656,7 @@ def most_common_neighbors(self, nonedgesonly=True): from sage.graphs.connectivity import is_triconnected from sage.graphs.comparability import is_comparability from sage.graphs.comparability import is_permutation + from sage.graphs.traversals import lex_M from sage.graphs.traversals import maximum_cardinality_search from sage.graphs.traversals import maximum_cardinality_search_M @@ -8687,6 +8688,7 @@ def most_common_neighbors(self, nonedgesonly=True): "cleave" : "Connectivity, orientations, trees", "spqr_tree" : "Connectivity, orientations, trees", "is_triconnected" : "Connectivity, orientations, trees", + "lex_M" : "Traversals", "maximum_cardinality_search" : "Traversals", "maximum_cardinality_search_M" : "Traversals" } diff --git a/src/sage/graphs/graph_decompositions/clique_separators.pyx b/src/sage/graphs/graph_decompositions/clique_separators.pyx index 80ecc8af5e4..19145c2422b 100644 --- a/src/sage/graphs/graph_decompositions/clique_separators.pyx +++ b/src/sage/graphs/graph_decompositions/clique_separators.pyx @@ -5,7 +5,8 @@ r""" Decomposition by clique minimal separators This module implements methods related to the decomposition of a graph by clique -minimal separators. See [TY1984]_ and [BPS2010]_ for more details. +minimal separators. See [TY1984]_ and [BPS2010]_ for more details on the +algorithms. Methods ------- @@ -109,11 +110,11 @@ def make_labelled_rooted_tree(atoms, cliques): sage: G = graphs.PathGraph(5) sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) _____{3}_____ - / / + / / {3, 4} ____{2}____ - / / + / / {2, 3} __{1}__ - / / + / / {0, 1} {1, 2} TESTS:: @@ -154,8 +155,8 @@ def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=Fal This method implements the algorithm proposed in [BPS2010]_, that improves upon the algorithm proposed in [TY1984]_, for computing the atoms and the clique minimal separators of a graph. This algorithm is based on the - :meth:`maximum_cardinality_search_M` graph traversal and has time complexity - in `O(|V|\cdot|E|)`. + :meth:`~sage.graphs.traversals.maximum_cardinality_search_M` graph traversal + and has time complexity in `O(|V|\cdot|E|)`. If the graph is not connected, we insert empty separators between the lists of separators of each connected components. See the examples below for more @@ -203,32 +204,22 @@ def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=Fal ....: 'd': ['e', 'f', 'j', 'k'], 'e': ['g'], ....: 'f': ['g', 'j', 'k'], 'g': ['j', 'k'], 'h': ['i', 'j'], ....: 'i': ['k'], 'j': ['k']}) - sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) # py2 - ____________________{'k', 'j'}_____________ - / / - {'i', 'h', 'k', 'j'} ____________________{'k', 'j', 'd'}_______ - / / - {'e', 'd', 'g', 'f', 'k', 'j'} _________{'c', 'k'}__ - / / - {'a', 'c', 'b', 'k'} {'c', 'j', 'k', 'd'} - sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) # py2 - ____________________{'k', 'j'}_____________ - / / - {'k', 'i', 'j', 'h'} ____________________{'k', 'j', 'd'}_______ - / / - {'k', 'g', 'j', 'f', 'd', 'e'} _________{'k', 'c'}__ - / / - {'k', 'a', 'b', 'c'} {'k', 'j', 'c', 'd'} - - sage: A, Sc = G.atoms_and_clique_separators() + sage: atoms, cliques = G.atoms_and_clique_separators() + sage: sorted(sorted(a) for a in atoms) + [['a', 'b', 'c', 'k'], + ['c', 'd', 'j', 'k'], + ['d', 'e', 'f', 'g', 'j', 'k'], + ['h', 'i', 'j', 'k']] + sage: sorted(sorted(c) for c in cliques) + [['c', 'k'], ['d', 'j', 'k'], ['j', 'k']] sage: T = G.atoms_and_clique_separators(tree=True) sage: T.is_tree() True - sage: T.diameter() == len(A) + sage: T.diameter() == len(atoms) True - sage: all(u[1] in A for u in T if T.degree(u) == 1) + sage: all(u[1] in atoms for u in T if T.degree(u) == 1) True - sage: all(u[1] in Sc for u in T if T.degree(u) != 1) + sage: all(u[1] in cliques for u in T if T.degree(u) != 1) True A graph without clique separator:: @@ -244,9 +235,9 @@ def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=Fal sage: G = graphs.PathGraph(4) sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) ____{2}____ - / / + / / {2, 3} __{1}__ - / / + / / {1, 2} {0, 1} sage: G = graphs.WindmillGraph(3, 4) @@ -254,11 +245,11 @@ def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=Fal ([{0, 1, 2}, {0, 3, 4}, {0, 5, 6}, {0, 8, 7}], [{0}, {0}, {0}]) sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) ________{0}________ - / / + / / {0, 1, 2} _______{0}______ - / / + / / {0, 3, 4} ____{0}___ - / / + / / {0, 8, 7} {0, 5, 6} When the removal of a clique separator results in `k > 2` connected @@ -270,34 +261,34 @@ def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=Fal ....: G.add_cycle([0, 1, G.add_vertex()]) sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) _________{0, 1}_____ - / / + / / {0, 1, 4} ________{0, 1}_____ - / / + / / {0, 1, 2} _______{0, 1}___ - / / + / / {0, 1, 3} ____{0, 1} - / / + / / {0, 1, 5} {0, 1, 6} sage: G = graphs.StarGraph(3) sage: G.subdivide_edges(G.edges(), 2) sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) ______{5}______ - / / + / / {1, 5} ______{7}______ - / / + / / {2, 7} ______{9}______ - / / + / / {9, 3} ______{6}______ - / / + / / {6, 7} ______{4}_____ - / / + / / {4, 5} _____{0}_____ - / / + / / {0, 6} ____{8}____ - / / + / / {8, 9} __{0}__ - / / + / / {0, 8} {0, 4} If the graph is not connected, we insert empty separators between the lists @@ -336,15 +327,15 @@ def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=Fal [{8, 7}, {6, 7}] [{7}] sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) ______{1}______ - / / + / / {1, 2} ______{}______ - / / + / / {0, 1} _____{4}_____ - / / + / / {4, 5} ____{}_____ - / / + / / {3, 4} __{7}__ - / / + / / {6, 7} {8, 7} Loops and multiple edges are ignored:: @@ -355,15 +346,15 @@ def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=Fal sage: G.add_edges(G.edges()) sage: ascii_art(G.atoms_and_clique_separators(rooted_tree=True)) ______{1}______ - / / + / / {1, 2} ______{}______ - / / + / / {0, 1} _____{4}_____ - / / + / / {4, 5} ____{}_____ - / / + / / {3, 4} __{7}__ - / / + / / {6, 7} {8, 7} We can check that the returned list of separators is valid:: @@ -402,11 +393,11 @@ def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=Fal {}[{0}[], {}[{1}[], {}[{3}[], {2}[]]]] sage: ascii_art(I4.atoms_and_clique_separators(rooted_tree=True)) ___{}___ - / / + / / {0} __{}___ - / / + / / {1} _{}_ - / / + / / {3} {2} """ cdef list A = [] # atoms diff --git a/src/sage/graphs/traversals.pyx b/src/sage/graphs/traversals.pyx index 5aeb9f70e32..c4a8294acd5 100644 --- a/src/sage/graphs/traversals.pyx +++ b/src/sage/graphs/traversals.pyx @@ -1347,7 +1347,7 @@ def maximum_cardinality_search(G, reverse=False, tree=False, initial_vertex=None ordering can be computed in time `O(n + m)`. When the graph is chordal, the ordering returned by MCS is a *perfect - elimination ordering*, like :meth:`~sage.graphs.graph.Graph.lex_BFS`. So + elimination ordering*, like :meth:`~sage.graphs.traversals.lex_BFS`. So this ordering can be used to recognize chordal graphs. See [He2006]_ for more details. From cf2d7fb45798cd6979db684ac0abc4553edbd918 Mon Sep 17 00:00:00 2001 From: David Coudert Date: Thu, 12 Sep 2019 11:24:13 +0200 Subject: [PATCH 005/133] trac #28473: fix doctests in lex_M --- src/sage/graphs/traversals.pyx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/sage/graphs/traversals.pyx b/src/sage/graphs/traversals.pyx index 25a2e3774fe..1cebe2cca8d 100644 --- a/src/sage/graphs/traversals.pyx +++ b/src/sage/graphs/traversals.pyx @@ -852,16 +852,15 @@ def lex_M(self, triangulation=False, labels=False, initial_vertex=None, algorith ``'lex_M_fast'`` cannot return labels:: - sage: G = graphs.CompleteGraph(6) - sage: G.lex_M(labels=True, algorithm='lex_M_fast') + sage: Graph().lex_M(labels=True, algorithm='lex_M_fast') Traceback (most recent call last): ... ValueError: 'lex_M_fast' cannot return labels assigned to vertices The method works only for undirected graphs:: - sage: G = digraphs.Circuit(15) - sage: G.lex_M() + sage: from sage.graphs.traversals import lex_M + sage: lex_M(DiGraph()) Traceback (most recent call last): ... ValueError: input graph must be undirected @@ -883,8 +882,7 @@ def lex_M(self, triangulation=False, labels=False, initial_vertex=None, algorith ``initial_vertex`` should be a valid graph vertex:: - sage: G = graphs.CompleteGraph(6) - sage: G.lex_M(initial_vertex='foo') + sage: Graph().lex_M(initial_vertex='foo') Traceback (most recent call last): ... ValueError: 'foo' is not a graph vertex From 00d6f33ec4643ef8d60f8cab7a058b0175685f2a Mon Sep 17 00:00:00 2001 From: David Coudert Date: Thu, 12 Sep 2019 11:26:11 +0200 Subject: [PATCH 006/133] trac #28473: fix compilation warning in clique_separators.pyx --- src/sage/graphs/graph_decompositions/clique_separators.pyx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/graphs/graph_decompositions/clique_separators.pyx b/src/sage/graphs/graph_decompositions/clique_separators.pyx index 19145c2422b..bae829985f6 100644 --- a/src/sage/graphs/graph_decompositions/clique_separators.pyx +++ b/src/sage/graphs/graph_decompositions/clique_separators.pyx @@ -503,7 +503,7 @@ def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=Fal cdef frozenset Sint cdef vector[int] Sint_min cdef vector[int] Cint - cdef int ui, vi + cdef size_t ui, vi cdef bint stop for i in range(N): From 99ed665589229eb03b3da5dcd24c641697ad50d3 Mon Sep 17 00:00:00 2001 From: jdoyle Date: Tue, 19 Nov 2019 12:24:10 -0600 Subject: [PATCH 007/133] Cleaned up the branch --- src/doc/en/reference/references/index.rst | 4 ++ src/sage/dynamics/complex_dynamics/all.py | 2 +- .../dynamics/complex_dynamics/mandel_julia.py | 70 +++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) diff --git a/src/doc/en/reference/references/index.rst b/src/doc/en/reference/references/index.rst index a9221f58172..ecb842e481b 100644 --- a/src/doc/en/reference/references/index.rst +++ b/src/doc/en/reference/references/index.rst @@ -3531,6 +3531,10 @@ REFERENCES: IMA Volumes in Math and its Applications (D. Stanton, ED.). Southend on Sea, UK, 19 (1990). 125-144. +.. [LS1994] Eike Lau and Dierk Schleicher. + *Internal addresses in the Mandelbrot set and irreducibility of + polynomials*. Stony Brook Preprint #19 (1994). + .. [LS2007] Thomas Lam and Mark Shimozono. *Dual graded graphs for Kac-Moody algebras*. Algebra & Number Theory 1.4 (2007) pp. 451-488. diff --git a/src/sage/dynamics/complex_dynamics/all.py b/src/sage/dynamics/complex_dynamics/all.py index 02b2d44fc78..d118421375f 100644 --- a/src/sage/dynamics/complex_dynamics/all.py +++ b/src/sage/dynamics/complex_dynamics/all.py @@ -1,4 +1,4 @@ from __future__ import absolute_import from sage.misc.lazy_import import lazy_import lazy_import("sage.dynamics.complex_dynamics.mandel_julia", - ["mandelbrot_plot", "external_ray", "julia_plot"]) + ["mandelbrot_plot", "external_ray", "kneading_sequence", "julia_plot"]) diff --git a/src/sage/dynamics/complex_dynamics/mandel_julia.py b/src/sage/dynamics/complex_dynamics/mandel_julia.py index f26602e908b..7e8bfd0c62e 100644 --- a/src/sage/dynamics/complex_dynamics/mandel_julia.py +++ b/src/sage/dynamics/complex_dynamics/mandel_julia.py @@ -39,6 +39,7 @@ from sage.plot.colors import Color from sage.repl.image import Image from sage.functions.log import logb +from sage.functions.other import floor from sage.rings.all import QQ, CC from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.schemes.projective.projective_space import ProjectiveSpace @@ -321,6 +322,75 @@ def external_ray(theta, **kwds): pixel[int(k[0]), int(k[1])] = tuple(ray_color) return M +def kneading_sequence(theta): + r""" + Determines the kneading sequence for an angle theta in RR/ZZ which + is periodic under doubling. We use the definition for the kneading + sequence given in [LS1994]_. + + INPUT: + + - ``theta`` -- a rational number with odd denominator + + OUTPUT: + + a string representing the kneading sequence of theta in RR/ZZ + + REFERENCES: + + [LS1994]_ + + EXAMPLES:: + + sage: kneading_sequence(0) + '*' + + :: + + sage: kneading_sequence(1/3) + '1*' + + Since 1/3 and 7/3 are the same in RR/ZZ, they have the same kneading sequence:: + + sage: kneading_sequence(7/3) + '1*' + + We can also use (finite) decimal inputs, as long as the denominator in reduced form is odd:: + + sage: kneading_sequence(1.2) + '110*' + + Since rationals with even denominator are not periodic under doubling, we have not implemented kneading sequences for such rationals:: + + sage: kneading_sequence(1/4) + Traceback (most recent call last): + ... + ValueError: input must be a rational number with odd denominator + """ + + if theta not in QQ: + raise TypeError('input must be a rational number with odd denominator') + elif QQ(theta).valuation(2) < 0: + raise ValueError('input must be a rational number with odd denominator') + else: + theta = QQ(theta) + theta = theta - floor(theta) + KS = [] + not_done = True + left = theta/2 + right = (theta + 1)/2 + y = theta + while not_done: + if ((y < left) or (y > right)): + KS.append('0') + elif ((y > left) and (y < right)): + KS.append('1') + else: + not_done = False + y = 2*y - floor(2*y) + L = len(KS) + KS_str = ''.join(KS) + '*' + return KS_str def julia_plot(c=-1, x_center=0.0, From 05936462ca51aad623bd0dc12a041829fd198c7a Mon Sep 17 00:00:00 2001 From: Martin Albrecht Date: Sun, 15 Dec 2019 14:24:24 +0000 Subject: [PATCH 008/133] update FPLLL to 5.3.1 and FPYLLL to 0.5.1dev --- build/pkgs/fplll/checksums.ini | 6 +++--- build/pkgs/fplll/package-version.txt | 2 +- build/pkgs/fpylll/checksums.ini | 6 +++--- build/pkgs/fpylll/package-version.txt | 2 +- build/pkgs/fpylll/patches/cython3.patch | 25 ------------------------- 5 files changed, 8 insertions(+), 33 deletions(-) delete mode 100644 build/pkgs/fpylll/patches/cython3.patch diff --git a/build/pkgs/fplll/checksums.ini b/build/pkgs/fplll/checksums.ini index abd69023c55..dd08acd0fa1 100644 --- a/build/pkgs/fplll/checksums.ini +++ b/build/pkgs/fplll/checksums.ini @@ -1,4 +1,4 @@ tarball=fplll-VERSION.tar.gz -sha1=4144f5fa3d85132585b1b17aed18865c7a146611 -md5=bc3569303ce36d731d21b5419ec733ac -cksum=1239204327 +sha1=4169d6094f8722df73bdbe43c0ccc54d38bbd1f1 +md5=9da76b18f8cc551d42e70192c9582d03 +cksum=3051787648 diff --git a/build/pkgs/fplll/package-version.txt b/build/pkgs/fplll/package-version.txt index 26d99a283f2..c7cb1311a64 100644 --- a/build/pkgs/fplll/package-version.txt +++ b/build/pkgs/fplll/package-version.txt @@ -1 +1 @@ -5.2.1 +5.3.1 diff --git a/build/pkgs/fpylll/checksums.ini b/build/pkgs/fpylll/checksums.ini index 7a690a0a830..70998dc7e4a 100644 --- a/build/pkgs/fpylll/checksums.ini +++ b/build/pkgs/fpylll/checksums.ini @@ -1,4 +1,4 @@ tarball=fpylll-VERSION.tar.gz -sha1=2f8f83038f7015b2c55d0ec21448ffb27d1d233f -md5=83f57447a1643d0b5087ee3944ca90a8 -cksum=2076741335 +sha1=2d35022ac75457606d7e5d3497f6d9dd75deb19c +md5=1c0d100203cb340cb3160ab9692f9208 +cksum=1547949297 diff --git a/build/pkgs/fpylll/package-version.txt b/build/pkgs/fpylll/package-version.txt index d6f84d0ae4b..3eda70ef84a 100644 --- a/build/pkgs/fpylll/package-version.txt +++ b/build/pkgs/fpylll/package-version.txt @@ -1 +1 @@ -0.4.1dev +0.5.1dev diff --git a/build/pkgs/fpylll/patches/cython3.patch b/build/pkgs/fpylll/patches/cython3.patch deleted file mode 100644 index 844a8999c0c..00000000000 --- a/build/pkgs/fpylll/patches/cython3.patch +++ /dev/null @@ -1,25 +0,0 @@ -From 28e5fcaeabe26d46167e75815e0d9a4fdfa1a973 Mon Sep 17 00:00:00 2001 -From: "Martin R. Albrecht" -Date: Wed, 5 Dec 2018 11:47:33 +0000 -Subject: [PATCH] set language_version - -fixes #127 ---- - setup.py | 4 +++- - 1 file changed, 3 insertions(+), 1 deletion(-) - -diff --git a/setup.py b/setup.py -index 8f916a9..a5125f8 100755 ---- a/setup.py -+++ b/setup.py -@@ -110,7 +110,9 @@ def run(self): - self.extensions, - include_path=["src"], - build_dir=self.cythonize_dir, -- compiler_directives={'binding': True, "embedsignature": True}) -+ compiler_directives={'binding': True, -+ 'embedsignature': True, -+ 'language_level': 2}) - super(build_ext, self).run() - - def _generate_config_pxi(self): From 63ae7bce3bbdf292201b51f71a4c179ec4667efc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Wed, 18 Dec 2019 14:26:21 +0100 Subject: [PATCH 009/133] some details in the matrix folder --- src/sage/matrix/matrix0.pyx | 5 ++--- src/sage/matrix/matrix2.pyx | 2 +- src/sage/matrix/matrix_generic_sparse.pyx | 4 ++-- src/sage/matrix/matrix_integer_dense.pyx | 2 +- src/sage/matrix/matrix_integer_dense_hnf.py | 2 +- src/sage/matrix/special.py | 12 ++++++------ 6 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/sage/matrix/matrix0.pyx b/src/sage/matrix/matrix0.pyx index e9da77cc2c4..a163a7006c7 100644 --- a/src/sage/matrix/matrix0.pyx +++ b/src/sage/matrix/matrix0.pyx @@ -982,11 +982,10 @@ cdef class Matrix(sage.structure.element.Matrix): if single_col: col_list = [col] - if len(row_list) == 0 or len(col_list) == 0: + if not row_list or not col_list: return self.new_matrix(nrows=len(row_list), ncols=len(col_list)) - return self.matrix_from_rows_and_columns(row_list,col_list) - + return self.matrix_from_rows_and_columns(row_list, col_list) row_index = key if type(row_index) is list or type(row_index) is tuple: diff --git a/src/sage/matrix/matrix2.pyx b/src/sage/matrix/matrix2.pyx index ea139556d13..2b3f0a4eccc 100644 --- a/src/sage/matrix/matrix2.pyx +++ b/src/sage/matrix/matrix2.pyx @@ -9502,7 +9502,7 @@ cdef class Matrix(Matrix1): R[nnz, i] = 1 nnz = nnz + 1 R = R[0:nnz] - if Bstar == []: + if not Bstar: Q = matrix(F, 0, self.nrows()).transpose() else: Q = matrix(F, Bstar).transpose() diff --git a/src/sage/matrix/matrix_generic_sparse.pyx b/src/sage/matrix/matrix_generic_sparse.pyx index caac6abe66d..bbf0015ca8a 100644 --- a/src/sage/matrix/matrix_generic_sparse.pyx +++ b/src/sage/matrix/matrix_generic_sparse.pyx @@ -410,8 +410,8 @@ def Matrix_sparse_from_rows(X): cdef Py_ssize_t i, j if not isinstance(X, (list, tuple)): - raise TypeError("X (=%s) must be a list or tuple"%X) - if len(X) == 0: + raise TypeError("X (=%s) must be a list or tuple" % X) + if not X: raise ArithmeticError("X must be nonempty") from . import matrix_space diff --git a/src/sage/matrix/matrix_integer_dense.pyx b/src/sage/matrix/matrix_integer_dense.pyx index 3d5a70d24a7..27234d67639 100644 --- a/src/sage/matrix/matrix_integer_dense.pyx +++ b/src/sage/matrix/matrix_integer_dense.pyx @@ -5427,7 +5427,7 @@ cdef class Matrix_integer_dense(Matrix_dense): [ 1 0 3] [-1 0 5] """ - if len(cols) == 0: + if not cols: return self cdef Py_ssize_t i, c, r, nc = max(self._ncols + len(cols), max(cols)+1) cdef Matrix_integer_dense A = self.new_matrix(self._nrows, nc) diff --git a/src/sage/matrix/matrix_integer_dense_hnf.py b/src/sage/matrix/matrix_integer_dense_hnf.py index 18415cb4a95..64ba747a511 100644 --- a/src/sage/matrix/matrix_integer_dense_hnf.py +++ b/src/sage/matrix/matrix_integer_dense_hnf.py @@ -1084,7 +1084,7 @@ def hnf(A, include_zero_rows=True, proof=True): """ if A.nrows() <= 1: np = A.nonzero_positions() - if len(np) == 0: + if not np: pivots = [] if not include_zero_rows: A = A.new_matrix(0) # 0 rows diff --git a/src/sage/matrix/special.py b/src/sage/matrix/special.py index bc4adf081dc..2bb91c10d16 100644 --- a/src/sage/matrix/special.py +++ b/src/sage/matrix/special.py @@ -825,7 +825,7 @@ def diagonal_matrix(arg0=None, arg1=None, arg2=None, sparse=True): nrows = nentries # provide a default ring for an empty list - if len(entries) == 0 and ring is None: + if not entries and ring is None: ring = rings.ZZ # Convert entries to a list v over a common ring @@ -1614,7 +1614,7 @@ def _determine_block_matrix_rows(sub_matrices): raise ValueError("incompatible submatrix heights") elif not M: found_zeroes = True - if len(R) == 0: + if not R: height = 0 # If we have a height, then we know the dimensions of any @@ -1882,7 +1882,7 @@ def block_matrix(*args, **kwds): args = list(args) sparse = kwds.get('sparse', None) - if len(args) == 0: + if not args: if sparse is not None: return matrix_space.MatrixSpace(rings.ZZ, 0, 0, sparse=sparse)([]) else: @@ -1925,7 +1925,7 @@ def block_matrix(*args, **kwds): # Now the rest of the arguments are a list of rows, a flat list of # matrices, or a single value. - if len(args) == 0: + if not args: args = [[]] if len(args) > 1: print(args) @@ -1953,7 +1953,7 @@ def block_matrix(*args, **kwds): # Will we try to place the matrices in a rectangular grid? try_grid = True - if len(sub_matrices) == 0: + if not sub_matrices: if (nrows is not None and nrows != 0) or \ (ncols is not None and ncols != 0): raise ValueError("invalid nrows/ncols passed to block_matrix") @@ -3247,7 +3247,7 @@ def random_diagonalizable_matrix(parent,eigenvalues=None,dimensions=None): raise ValueError("the size of the matrix must equal the sum of the dimensions.") if min(dimensions) < 1: raise ValueError("eigenspaces must have a dimension of at least 1.") - if len(eigenvalues)!=len(dimensions): + if len(eigenvalues) != len(dimensions): raise ValueError("each eigenvalue must have a corresponding dimension and each dimension a corresponding eigenvalue.") #sort the dimensions in order of increasing size, and sort the eigenvalues list in an identical fashion, to maintain corresponding values. dimensions_sort = sorted(zip(dimensions, eigenvalues)) From 53f76ce9b45ca28ce4074d1d8cf7375dd5373398 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Thu, 19 Dec 2019 15:31:50 +0100 Subject: [PATCH 010/133] fix --- src/sage/matrix/special.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/matrix/special.py b/src/sage/matrix/special.py index 2bb91c10d16..6d6c2bdcf39 100644 --- a/src/sage/matrix/special.py +++ b/src/sage/matrix/special.py @@ -825,7 +825,7 @@ def diagonal_matrix(arg0=None, arg1=None, arg2=None, sparse=True): nrows = nentries # provide a default ring for an empty list - if not entries and ring is None: + if not len(entries) and ring is None: ring = rings.ZZ # Convert entries to a list v over a common ring From 52f8c9d3ff7fdc84be10151c2aa5a152698d26fa Mon Sep 17 00:00:00 2001 From: Markus Wageringel Date: Sun, 22 Dec 2019 17:16:28 +0100 Subject: [PATCH 011/133] 28907: fix return type/remove method MathematicaElement.N() This also fixes serialization of Mathematica elements which failed due to leading whitespace. --- src/sage/interfaces/mathematica.py | 50 ++++++++++-------------------- src/sage/symbolic/constants.py | 5 +-- 2 files changed, 18 insertions(+), 37 deletions(-) diff --git a/src/sage/interfaces/mathematica.py b/src/sage/interfaces/mathematica.py index f67d955a45e..0a3c869fb35 100644 --- a/src/sage/interfaces/mathematica.py +++ b/src/sage/interfaces/mathematica.py @@ -308,7 +308,7 @@ sage: def math_bessel_K(nu,x): ....: return mathematica(nu).BesselK(x).N(20) sage: math_bessel_K(2,I) # optional - mathematica - -2.5928861754911969782 + 0.1804899720669620266 I + -2.59288617549119697817 + 0.18048997206696202663*I :: @@ -339,6 +339,21 @@ - Felix Lawrence (2009-08-21): Added support for importing Mathematica lists and floats with exponents. + +TESTS: + +Check that numerical approximations via Mathematica's `N[]` function work +correctly (:trac:`18888`, :trac:`28907`):: + + sage: mathematica('Pi/2').N(10) # optional -- mathematica + 1.5707963268 + sage: mathematica('Pi').N(10) # optional -- mathematica + 3.1415926536 + sage: mathematica('Pi').N(50) # optional -- mathematica + 3.14159265358979323846264338327950288419716939937511 + sage: str(mathematica('Pi*x^2-1/2').N()) # optional -- mathematica + 2 + -0.5 + 3.14159 x """ #***************************************************************************** @@ -676,7 +691,7 @@ def __float__(self, precision=16): return float(P.eval('N[%s,%s]'%(self.name(),precision))) def _reduce(self): - return self.parent().eval('InputForm[%s]'%self.name()) + return self.parent().eval('InputForm[%s]' % self.name()).strip() def __reduce__(self): return reduce_load, (self._reduce(), ) @@ -999,37 +1014,6 @@ def __bool__(self): __nonzero__ = __bool__ - def N(self, precision=None): - r""" - Numerical approximation by calling Mathematica's `N[]` - - Calling Mathematica's `N[]` function, with optional precision in decimal digits. - Unlike Sage's `n()`, `N()` can be applied to symbolic Mathematica objects. - - A workaround for :trac:`18888` backtick issue, stripped away by `get()`, - is included. - - .. note:: - - The base class way up the hierarchy defines an `N` (modeled - after Mathematica's) which overwrites the Mathematica one, - and doesn't work at all. We restore it here. - - EXAMPLES:: - - sage: mathematica('Pi/2').N(10) # optional -- mathematica - 1.570796327 - sage: mathematica('Pi').N(50) # optional -- mathematica - 3.1415926535897932384626433832795028841971693993751 - sage: mathematica('Pi*x^2-1/2').N() # optional -- mathematica - 2 - -0.5 + 3.14159 x - """ - P = self.parent() - if precision is None: - return P.eval('N[%s]'%self.name()) - return P.eval('N[%s,%s]'%(self.name(),precision)) - def n(self, *args, **kwargs): r""" Numerical approximation by converting to Sage object first diff --git a/src/sage/symbolic/constants.py b/src/sage/symbolic/constants.py index 78e4a5a7283..8f882893092 100644 --- a/src/sage/symbolic/constants.py +++ b/src/sage/symbolic/constants.py @@ -1085,10 +1085,7 @@ class Khinchin(Constant): sage: m = mathematica(khinchin); m # optional - mathematica Khinchin sage: m.N(200) # optional - mathematica - 2.6854520010653064453097148354817956938203822939944629530511523455572 - > 188595371520028011411749318476979951534659052880900828976777164109630517 - > 925334832596683818523154213321194996260393285220448194096181 - + 2.685452001065306445309714835481795693820382293...32852204481940961807 """ def __init__(self, name='khinchin'): """ From 9fc8f1b29dc9372452b5baa1614553c9110b548f Mon Sep 17 00:00:00 2001 From: Kiran Kedlaya Date: Tue, 24 Dec 2019 19:05:06 -0800 Subject: [PATCH 012/133] Summary commit of Cythonization of HGMs --- src/module_list.py | 3 + src/sage/modular/hypergeometric_misc.pxd | 4 + src/sage/modular/hypergeometric_misc.pyx | 98 ++++++++ src/sage/modular/hypergeometric_motive.py | 156 +++++++++---- src/sage/rings/padics/misc.py | 1 + .../rings/padics/padic_generic_element.pxd | 3 + .../rings/padics/padic_generic_element.pyx | 211 +++++++++++++++--- 7 files changed, 404 insertions(+), 72 deletions(-) create mode 100644 src/sage/modular/hypergeometric_misc.pxd create mode 100644 src/sage/modular/hypergeometric_misc.pyx diff --git a/src/module_list.py b/src/module_list.py index fc8bb929567..791bcb8a2a2 100644 --- a/src/module_list.py +++ b/src/module_list.py @@ -927,6 +927,9 @@ def uname_specific(name, value, alternative): Extension('sage.modular.arithgroup.arithgroup_element', sources = ['sage/modular/arithgroup/arithgroup_element.pyx']), + Extension('sage.modular.hypergeometric_misc', + sources = ['sage/modular/hypergeometric_misc.pyx']), + Extension('sage.modular.modform.eis_series_cython', sources = ['sage/modular/modform/eis_series_cython.pyx']), diff --git a/src/sage/modular/hypergeometric_misc.pxd b/src/sage/modular/hypergeometric_misc.pxd new file mode 100644 index 00000000000..f3ef421fd11 --- /dev/null +++ b/src/sage/modular/hypergeometric_misc.pxd @@ -0,0 +1,4 @@ +from cpython cimport array + +cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, + gtable, bint use_longs) diff --git a/src/sage/modular/hypergeometric_misc.pyx b/src/sage/modular/hypergeometric_misc.pyx new file mode 100644 index 00000000000..cfb62caf716 --- /dev/null +++ b/src/sage/modular/hypergeometric_misc.pyx @@ -0,0 +1,98 @@ +""" +Some utility routines for the hypergeometric motives package that benefit +significantly from Cythonization. +""" + +from cpython cimport array + +cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, + gtable, bint use_longs): + r""" + Compute coefficients for the hypergeometric trace formula. + + This function is not intended for direct user access. + + TESTS:: + + sage: from sage.modular.hypergeometric_motive import HypergeometricData as Hyp + sage: import array + sage: from sage.modular.hypergeometric_misc import hgm_coeffs + sage: H = Hyp(cyclotomic=([3],[4])) + sage: H.euler_factor(2, 7, cache_p=True) + 7*T^2 - 3*T + 1 + sage: gamma = H.gamma_array() + sage: gtable = H.gauss_table(7, 1, 2) + sage: m = array.array('i', [0]*6) + sage: D = 1 + sage: hgm_coeffs(7, 1, 2, gamma, m, D, gtable, False) + [7, 2*7, 6*7, 7, 6, 4*7] + """ + cdef int gl, j, k, l, v, gv + cdef long long i, q1, w, w1, q2, r, r1 + cdef bint flip + + q1 = p ** f - 1 + gl = len(gamma) + cdef array.array gamma_array1 = array.array('i', gamma.keys()) + cdef array.array gamma_array2 = array.array('i', gamma.values()) + cdef array.array r_array = array.array('i', [0]) * gl + cdef array.array digit_count = array.array('Q', [0]) * q1 + cdef array.array gtab2 + + R = gtable[0].parent() + ans = [] + if use_longs: + q2 = p ** prec + gtab2 = array.array('Q', [0]) * q1 + for r in range(q1): gtab2[r] = gtable[r].lift() % q2 + if f == 1: + for r in range(q1): digit_count[r] = r + else: + for r in range(q1): + r1 = r + digit_count[r] = 0 + for i in range(f): + digit_count[r] += r1 % p + r1 //= p + flip = (f == 1 and prec == 1 and R.precision_cap() == 1) + for r in range(q1): + # First determine whether this term is forced to be zero + # for divisibility reasons. If so, skip the p-adic arithmetic. + i = 0 + for k in range(gl): + v = gamma_array1[k] + gv = gamma_array2[k] + r1 = v * r % q1 + r_array[k] = r1 + i += digit_count[r1] * gv + i //= (p - 1) + l = i + f * (D + m[0] - m[r]) + if l >= prec: + ans.append(R.zero()) + continue + if use_longs: + w = 1 + w1 = 1 + else: + u = R.one() + u1 = R.one() + for k in range(gl): + gv = gamma_array2[k] + r1 = r_array[k] + if (flip): gv = -gv + if use_longs: + if gv > 0: + for j in range(gv): w = w * gtab2[r1] % q2 + else: + for j in range(-gv): w1 = w1 * gtab2[r1] % q2 + else: + if gv > 0: + for j in range(gv): u *= gtable[r1] + else: + for j in range(-gv): u1 *= gtable[r1] + if use_longs: + u = R(w) + u1 = R(w1) + if i % 2: u = -u + ans.append((u / u1) << l) + return ans diff --git a/src/sage/modular/hypergeometric_motive.py b/src/sage/modular/hypergeometric_motive.py index 4234279b41e..c0688319657 100644 --- a/src/sage/modular/hypergeometric_motive.py +++ b/src/sage/modular/hypergeometric_motive.py @@ -62,6 +62,7 @@ from collections import defaultdict from itertools import combinations import array +import sys from sage.arith.misc import divisors, gcd, euler_phi, moebius, is_prime from sage.arith.misc import gauss_sum, kronecker_symbol @@ -72,11 +73,12 @@ from sage.misc.cachefunc import cached_method from sage.misc.functional import cyclotomic_polynomial from sage.misc.misc_c import prod +from sage.modular.hypergeometric_misc import hgm_coeffs from sage.rings.fraction_field import FractionField from sage.rings.finite_rings.integer_mod_ring import IntegerModRing from sage.rings.integer_ring import ZZ -from sage.rings.padics.factory import Qp -from sage.rings.padics.misc import gauss_sum as padic_gauss_sum +from sage.rings.padics.factory import Qp, Zp +from sage.rings.padics.padic_generic_element import gauss_table from sage.rings.polynomial.polynomial_ring import polygen from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.rings.power_series_ring import PowerSeriesRing @@ -85,7 +87,6 @@ from sage.rings.finite_rings.finite_field_constructor import GF from sage.rings.universal_cyclotomic_field import UniversalCyclotomicField - def characteristic_polynomial_from_traces(traces, d, q, i, sign): r""" Given a sequence of traces `t_1, \dots, t_k`, return the @@ -396,6 +397,8 @@ def gamma_list_to_cyclotomic(galist): class HypergeometricData(object): + _gauss_table = {} + def __init__(self, cyclotomic=None, alpha_beta=None, gamma_list=None): r""" Creation of hypergeometric motives. @@ -1063,7 +1066,7 @@ def primitive_data(self): .. SEEALSO:: - :meth:`is_primitive`, :meth:`primitive_index`, + :meth:`is_primitive`, :meth:`primitive_index` EXAMPLES:: @@ -1077,9 +1080,71 @@ def primitive_data(self): d = gcd(g) return HypergeometricData(gamma_list=[x / d for x in g]) +### L-functions + + def gauss_table(self, p, f, prec): + """ + Return (and cache) a table of Gauss sums used in the trace formula. + + .. SEEALSO:: + + :meth:`gauss_table_full` + + EXAMPLES:: + + sage: from sage.modular.hypergeometric_motive import HypergeometricData as Hyp + sage: H = Hyp(cyclotomic=([3],[4])) + sage: H.gauss_table(2, 2, 4) + [1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3] + """ + try: + (prec1, gtab) = self._gauss_table[(p, f)] + if prec1 < prec: raise KeyError + except (AttributeError, KeyError) as err: + if err.__class__ == AttributeError: + self._gauss_table = {} + gtab = gauss_table(p, f, prec, False) + self._gauss_table[(p, f)] = (prec, gtab) + return gtab + + def gauss_table_full(self): + """ + Return a dict of all stored tables of Gauss sums. + + The result is passed by reference, and is an attribute of the class; + consequently, modifying the result has global side effects. Use with + caution. + + .. SEEALSO:: + + :meth:`gauss_table` + + EXAMPLES:: + + sage: from sage.modular.hypergeometric_motive import HypergeometricData as Hyp + sage: H = Hyp(cyclotomic=([3],[4])) + sage: H.euler_factor(2, 7, cache_p=True) + 7*T^2 - 3*T + 1 + sage: H.gauss_table_full()[(7, 1)] + (2, [6 + 6*7, 6 + 2*7, 3 + 3*7, 1, 2, 6 + 3*7]) + + Clearing cached values:: + + sage: H = Hyp(cyclotomic=([3],[4])) + sage: H.euler_factor(2, 7, cache_p=True) + 7*T^2 - 3*T + 1 + sage: d = H.gauss_table_full() + sage: d.clear() # Delete all entries of this dict + sage: H1 = Hyp(cyclotomic=([5],[12])) + sage: d1 = H1.gauss_table_full() + sage: len(d1.keys()) # No cached values + 0 + """ + return self._gauss_table + # --- L-functions --- @cached_method - def padic_H_value(self, p, f, t, prec=None): + def padic_H_value(self, p, f, t, prec=None, cache_p=False): """ Return the `p`-adic trace of Frobenius, computed using the Gross-Koblitz formula. @@ -1087,6 +1152,11 @@ def padic_H_value(self, p, f, t, prec=None): If left unspecified, `prec` is set to the minimum `p`-adic precision needed to recover the Euler factor. + If `cache_p` is True, then the function caches an intermediate + result which depends only on `p` and `f`. This leads to a significant + speedup when iterating over `t`. (When iterating also over the + hypergeometric data, one should also use :meth:`set_gauss_table`.) + INPUT: - `p` -- a prime number @@ -1097,6 +1167,8 @@ def padic_H_value(self, p, f, t, prec=None): - ``prec`` -- precision (optional) + - ``cache_p`` - a boolean + OUTPUT: an integer @@ -1141,48 +1213,41 @@ def padic_H_value(self, p, f, t, prec=None): t = QQ(t) if 0 in alpha: return self._swap.padic_H_value(p, f, ~t, prec) - gamma = self.gamma_array() - q = p**f + q = p ** f + if q * p > 2 ** 64: + return ValueError("p^(f+1) cannot exceed 2^64") - # m = {r: beta.count(QQ((r, q - 1))) for r in range(q - 1)} - m = array.array('i', [0] * (q - 1)) + m = array.array('i', [0]) * int(q - 1) for b in beta: u = b * (q - 1) - if u.is_integer(): - m[u] += 1 + if u.is_integer(): m[u] += 1 M = self.M_value() D = -min(self.zigzag(x, flip_beta=True) for x in alpha + beta) # also: D = (self.weight() + 1 - m[0]) // 2 if prec is None: - prec = (self.weight() * f) // 2 + ceil(log(self.degree(), p)) + 1 - # For some reason, working in Qp instead of Zp is much faster; - # it appears to avoid some costly conversions. - p_ring = Qp(p, prec=prec) - teich = p_ring.teichmuller(M / t) - - gauss_table = [None] * (q - 1) - for r in range(q - 1): - if gauss_table[r] is None: - gauss_table[r] = padic_gauss_sum(r, p, f, prec, factored=True, - algorithm='sage', parent=p_ring) - r1 = (r * p) % (q - 1) - while r1 != r: - gauss_table[r1] = gauss_table[r] - r1 = (r1 * p) % (q - 1) - - sigma = p_ring.zero() - u1 = p_ring.one() - for r in range(q - 1): - i = int(0) - u = u1 - u1 *= teich - for v, gv in gamma.items(): - r1 = (v * r) % (q - 1) - i += gauss_table[r1][0] * gv - u *= gauss_table[r1][1] ** gv - sigma += (-p)**(i // (p - 1)) * u << (f * (D + m[0] - m[r])) - resu = ZZ(-1) ** m[0] / (1 - q) * sigma + prec = ceil((self.weight() * f) / 2 + log(2*self.degree()+1, p)) + use_longs = (p ** prec < 2 ** 31) + + gamma = self._gamma_array + if cache_p: + try: + trcoeffs = self._trace_coeffs[(p, f)] + except (AttributeError, KeyError) as err: + if err.__class__ == AttributeError: + self._trace_coeffs = {} + gtab = self.gauss_table(p, f, prec) + trcoeffs = hgm_coeffs(p, f, prec, gamma, m, D, gtab, use_longs) + self._trace_coeffs[(p,f)] = trcoeffs + else: + gtab = gauss_table(p, f, prec, use_longs) + trcoeffs = hgm_coeffs(p, f, prec, gamma, m, D, gtab, use_longs) + sigma = trcoeffs[q-2] + p_ring = sigma.parent() + teich = p_ring.teichmuller(M/t) + for i in range(q-3, -1, -1): + sigma = sigma * teich + trcoeffs[i] + resu = ZZ(-1) ** m[0] * sigma / (1 - q) return IntegerModRing(p**prec)(resu).lift_centered() @cached_method @@ -1334,7 +1399,7 @@ def sign(self, t, p): return sign @cached_method - def euler_factor(self, t, p): + def euler_factor(self, t, p, cache_p=False): """ Return the Euler factor of the motive `H_t` at prime `p`. @@ -1395,6 +1460,14 @@ def euler_factor(self, t, p): 279841*T^4 - 25392*T^3 + 1242*T^2 - 48*T + 1, 707281*T^4 - 7569*T^3 + 696*T^2 - 9*T + 1] + This is an example of higher degree:: + + sage: H = Hyp(cyclotomic=([11], [7, 12])) + sage: H.euler_factor(2, 13) + 371293*T^10 - 85683*T^9 + 26364*T^8 + 1352*T^7 - 65*T^6 + 394*T^5 - 5*T^4 + 8*T^3 + 12*T^2 - 3*T + 1 + sage: H.euler_factor(2, 19) # long time + 2476099*T^10 - 651605*T^9 + 233206*T^8 - 77254*T^7 + 20349*T^6 - 4611*T^5 + 1071*T^4 - 214*T^3 + 34*T^2 - 5*T + 1 + TESTS:: sage: H1 = Hyp(alpha_beta=([1,1,1],[1/2,1/2,1/2])) @@ -1427,7 +1500,8 @@ def euler_factor(self, t, p): # now p is good d = self.degree() bound = d // 2 - traces = [self.padic_H_value(p, i + 1, t) for i in range(bound)] + traces = [self.padic_H_value(p, i + 1, t, cache_p=cache_p) + for i in range(bound)] w = self.weight() sign = self.sign(t, p) diff --git a/src/sage/rings/padics/misc.py b/src/sage/rings/padics/misc.py index def3b8d177d..b2ffd91f2f8 100644 --- a/src/sage/rings/padics/misc.py +++ b/src/sage/rings/padics/misc.py @@ -139,6 +139,7 @@ def gauss_sum(a, p, f, prec=20, factored=False, algorithm='pari', parent=None): s = sum(a.digits(base=p)) if factored: return(s, out) + X = PolynomialRing(R, name='X').gen() pi = R.ext(X**(p - 1) + p, names='pi').gen() out *= pi**s diff --git a/src/sage/rings/padics/padic_generic_element.pxd b/src/sage/rings/padics/padic_generic_element.pxd index 9166e3fcf2c..fe08b038568 100644 --- a/src/sage/rings/padics/padic_generic_element.pxd +++ b/src/sage/rings/padics/padic_generic_element.pxd @@ -6,6 +6,8 @@ from sage.rings.padics.pow_computer cimport PowComputer_class from sage.rings.integer cimport Integer from sage.rings.rational cimport Rational +cpdef gauss_table(long long p, int f, int prec, bint use_longs) + cdef class pAdicGenericElement(LocalGenericElement): cdef long valuation_c(self) cpdef val_unit(self) @@ -41,3 +43,4 @@ cdef class pAdicGenericElement(LocalGenericElement): cpdef _mod_(self, right) cpdef _floordiv_(self, right) cpdef bint _is_base_elt(self, p) except -1 + diff --git a/src/sage/rings/padics/padic_generic_element.pyx b/src/sage/rings/padics/padic_generic_element.pyx index 11968020ce8..d4b3061f017 100644 --- a/src/sage/rings/padics/padic_generic_element.pyx +++ b/src/sage/rings/padics/padic_generic_element.pyx @@ -42,7 +42,6 @@ from sage.structure.richcmp cimport rich_to_bool cdef long maxordp = (1L << (sizeof(long) * 8 - 2)) - 1 - cdef class pAdicGenericElement(LocalGenericElement): cpdef _richcmp_(left, right, int op): """ @@ -1230,7 +1229,7 @@ cdef class pAdicGenericElement(LocalGenericElement): INPUT: - - ``bd`` -- integer. Is a bound for precision, defaults to 20 + - ``bd`` -- integer. Precision bound, defaults to 20 - ``a`` -- integer. Offset parameter, defaults to 0 OUTPUT: @@ -1265,6 +1264,8 @@ cdef class pAdicGenericElement(LocalGenericElement): 4 + 4*5 + 4*5^2 + 4*5^3 + 2*5^4 + 4*5^5 + 5^7 + 3*5^9 + 4*5^10 + 3*5^11 + 5^13 + 4*5^14 + 2*5^15 + 2*5^16 + 2*5^17 + 3*5^18 + O(5^20) + TESTS: + This test was added in :trac:`24433`:: sage: F = Qp(7) @@ -1274,36 +1275,19 @@ cdef class pAdicGenericElement(LocalGenericElement): 6 + 4*7^19 + O(7^20) """ R = self.parent() - cdef int p = R.prime() - cdef int b = a - cdef int k + p = R.prime() - s = R.zero().add_bigoh(bd) - t = R.one().add_bigoh(bd) + # If p == 2, must work in Qp rather than Zp. + if p == 2 and not R.is_field(): + S = R.fraction_field() + return R(S(self).dwork_expansion(bd, a)) try: v = R.dwork_coeffs + if len(v) < p*bd: + raise AttributeError except AttributeError: - v = None - if v is not None and len(v) < p * bd: - v = None - if v is not None: - for k in range(bd): - s += t * v[p*k+b] - t *= (self + k) - else: - u = [t] - v = [] - for j in range(1, p): - u.append(u[j-1] / j) - for k in range(bd): - v += [x << k for x in u] - s += t * (u[a] << k) - t *= (self + k) - u[0] = ((u[-1] + u[0]) / (k+1)) >> 1 - for j in range(1, p): - u[j] = (u[j-1] + u[j]) / (j + (k+1) * p ) - R.dwork_coeffs = v - return -s + v = dwork_mahler_coeffs(R, bd) + return evaluate_dwork_mahler(v, self, p, bd, a) def gamma(self, algorithm='pari'): r""" @@ -1410,11 +1394,9 @@ cdef class pAdicGenericElement(LocalGenericElement): return parent(self.__pari__().gamma()) elif algorithm == 'sage': p = parent.prime() - bd = -((-n*p)//(p-1)) + bd = -((-n*p) // (p-1)) k = (-self) % p x = (self+k) >> 1 - if p==2 and n>=3: - x = x.lift_to_precision(n) return -x.dwork_expansion(bd, k.lift()) @coerce_binop @@ -4411,3 +4393,170 @@ def _compute_g(p, n, prec, terms): for i in range(n): g[i+1] = -(g[i]/(v-v**2)).integral() return [x.truncate(terms) for x in g] + +cpdef dwork_mahler_coeffs(R, int bd=20): + r""" + Compute Dwork's formula for Mahler coefficients of `p`-adic Gamma. + + This is called internally when one computes Gamma for a `p`-adic + integer. Normally there is no need to call it directly. + + INPUT: + + - ``R`` -- p-adic ring in which to compute + - ``bd`` -- integer. Number of terms in the expansion to use + + OUTPUT: + + A list of `p`-adic integers. + + EXAMPLES:: + + sage: from sage.rings.padics.padic_generic_element import dwork_mahler_coeffs, evaluate_dwork_mahler + sage: R = Zp(3) + sage: v = dwork_mahler_coeffs(R) + sage: x = R(1/7) + sage: evaluate_dwork_mahler(v, x, 3, 20, 1) + 2 + 2*3 + 3^2 + 3^3 + 3^4 + 3^5 + 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^11 + 2*3^12 + 3^13 + 3^14 + 2*3^16 + 3^17 + 3^19 + O(3^20) + sage: x.dwork_expansion(a=1) # Same result + 2 + 2*3 + 3^2 + 3^3 + 3^4 + 3^5 + 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^11 + 2*3^12 + 3^13 + 3^14 + 2*3^16 + 3^17 + 3^19 + O(3^20) + """ + from sage.rings.padics.factory import Qp + cdef int i + cdef long k, p + + v = [R.one()] + p = R.prime() + for k in range(1, p): + v.append(v[-1] / R(k)) + if bd > 1: + R1 = Qp(p, prec=bd) # Need divisions in this calculation + u = [R1(x) for x in v] + for i in range(1, bd): + u[0] = ((u[-1] + u[0]) / i) >> 1 + for j in range(1, p): + u[j] = (u[j-1] + u[j]) / (j + i * p) + for x in u: + v.append(R(x << i)) + return v + +cpdef evaluate_dwork_mahler(v, x, long long p, int bd, long long a): + """ + Evaluate Dwork's Mahler series for `p`-adic Gamma. + + EXAMPLES:: + + sage: from sage.rings.padics.padic_generic_element import dwork_mahler_coeffs, evaluate_dwork_mahler + sage: R = Zp(3) + sage: v = dwork_mahler_coeffs(R) + sage: x = R(1/7) + sage: evaluate_dwork_mahler(v, x, 3, 20, 1) + 2 + 2*3 + 3^2 + 3^3 + 3^4 + 3^5 + 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^11 + 2*3^12 + 3^13 + 3^14 + 2*3^16 + 3^17 + 3^19 + O(3^20) + sage: x.dwork_expansion(a=1) # Same result + 2 + 2*3 + 3^2 + 3^3 + 3^4 + 3^5 + 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^11 + 2*3^12 + 3^13 + 3^14 + 2*3^16 + 3^17 + 3^19 + O(3^20) + """ + cdef int k + bd -= 1 + a1 = a + bd*p + s = v[a1] + u = x + bd + w = x.parent().one() + for k in range(bd): + a1 -= p + u -= w + s = s*u + v[a1] + return -s + +cdef long long evaluate_dwork_mahler_long(v, long long x, long long p, int bd, + long long a, long long q): + cdef int k + cdef long long a1, s, u + bd -= 1 + a1 = a + bd*p + s = v[a1].lift() + u = x + bd + for k in range(bd): + a1 -= p + u -= 1 + s = (s*u + v[a1].lift()) % q + return -s + +cpdef gauss_table(long long p, int f, int prec, bint use_longs): + r""" + Compute a table of Gauss sums using the Gross-Koblitz formula. + + This is used in the computation of L-functions of hypergeometric motives. + The Gross-Koblitz formula is used as in `sage.rings.padics.misc.gauss_sum`, + but further unpacked for efficiency. + + INPUT: + + - `p` - prime + - `f`, `prec` - positive integers + - `use_longs` - boolean; if True, computations are done in C long + integers rather than Sage `p`-adics + + OUTPUT: + + A list of length `q-1=p^f-1`. The entries are `p`-adic units created with + absolute precision `prec`. + + EXAMPLES:: + + sage: from sage.rings.padics.padic_generic_element import gauss_table + sage: gauss_table(2,2,4,False) + [1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3] + sage: gauss_table(3,2,4,False)[3] + 2 + 3 + 2*3^2 + """ + from sage.rings.padics.factory import Zp, Qp + + cdef int i, j, bd + cdef long long q, q1, q3, r, r1, r2, s1, k + + R = Zp(p, prec, 'fixed-mod') + + if (f == 1 and prec == 1): # Shortcut for this key special case + ans = [-R.one()] + for r in range(1, p-1): + ans.append(ans[-1] * R(r)) + return ans + + q = p ** f + q1 = q - 1 + bd = (p*prec+p-2) // (p-1) - 1 + if p == 2: # Dwork expansion has denominators when p = 2 + R1 = Qp(p, prec) + else: + R1 = R + u = R1.one() + ans = [None for r in range(q1)] + ans[0] = -u + d = ~R1(q1) + if use_longs: + q3 = p ** prec + r2 = d.lift() % q3 + v = dwork_mahler_coeffs(R1, bd) + for r in range(1, q1): + if ans[r] is not None: continue + s = u + if use_longs: s1 = 1 + r1 = r + for j in range(1, f+1): + k = r1 % p + r1 = (r1 + k * q1) // p + if use_longs: # Use Dwork expansion to compute p-adic Gamma + s1 *= -evaluate_dwork_mahler_long(v, r1*r2, p, bd, k, q3) + s1 %= q3 + else: + s *= -evaluate_dwork_mahler(v, R1(r1)*d, p, bd, k) + if r1 == r: # End the loop. + if use_longs: s = R1(s1) + if j < f: s **= f // j + break + ans[r] = -s + for i in range(j-1): + r1 = r1 * p % q1 # Initially r1 == r + ans[r1] = ans[r] + if p != 2: return ans + return [R(x) for x in ans] From 848c5153e3ae401051ef77e54bb3660b85d1f668 Mon Sep 17 00:00:00 2001 From: Kiran Kedlaya Date: Tue, 24 Dec 2019 19:05:06 -0800 Subject: [PATCH 013/133] Summary commit of Cythonization of HGMs --- src/module_list.py | 3 + src/sage/modular/hypergeometric_misc.pxd | 4 + src/sage/modular/hypergeometric_misc.pyx | 98 ++++++++ src/sage/modular/hypergeometric_motive.py | 156 +++++++++---- src/sage/rings/padics/misc.py | 1 + .../rings/padics/padic_generic_element.pxd | 3 + .../rings/padics/padic_generic_element.pyx | 211 +++++++++++++++--- 7 files changed, 404 insertions(+), 72 deletions(-) create mode 100644 src/sage/modular/hypergeometric_misc.pxd create mode 100644 src/sage/modular/hypergeometric_misc.pyx diff --git a/src/module_list.py b/src/module_list.py index fc8bb929567..791bcb8a2a2 100644 --- a/src/module_list.py +++ b/src/module_list.py @@ -927,6 +927,9 @@ def uname_specific(name, value, alternative): Extension('sage.modular.arithgroup.arithgroup_element', sources = ['sage/modular/arithgroup/arithgroup_element.pyx']), + Extension('sage.modular.hypergeometric_misc', + sources = ['sage/modular/hypergeometric_misc.pyx']), + Extension('sage.modular.modform.eis_series_cython', sources = ['sage/modular/modform/eis_series_cython.pyx']), diff --git a/src/sage/modular/hypergeometric_misc.pxd b/src/sage/modular/hypergeometric_misc.pxd new file mode 100644 index 00000000000..f3ef421fd11 --- /dev/null +++ b/src/sage/modular/hypergeometric_misc.pxd @@ -0,0 +1,4 @@ +from cpython cimport array + +cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, + gtable, bint use_longs) diff --git a/src/sage/modular/hypergeometric_misc.pyx b/src/sage/modular/hypergeometric_misc.pyx new file mode 100644 index 00000000000..cfb62caf716 --- /dev/null +++ b/src/sage/modular/hypergeometric_misc.pyx @@ -0,0 +1,98 @@ +""" +Some utility routines for the hypergeometric motives package that benefit +significantly from Cythonization. +""" + +from cpython cimport array + +cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, + gtable, bint use_longs): + r""" + Compute coefficients for the hypergeometric trace formula. + + This function is not intended for direct user access. + + TESTS:: + + sage: from sage.modular.hypergeometric_motive import HypergeometricData as Hyp + sage: import array + sage: from sage.modular.hypergeometric_misc import hgm_coeffs + sage: H = Hyp(cyclotomic=([3],[4])) + sage: H.euler_factor(2, 7, cache_p=True) + 7*T^2 - 3*T + 1 + sage: gamma = H.gamma_array() + sage: gtable = H.gauss_table(7, 1, 2) + sage: m = array.array('i', [0]*6) + sage: D = 1 + sage: hgm_coeffs(7, 1, 2, gamma, m, D, gtable, False) + [7, 2*7, 6*7, 7, 6, 4*7] + """ + cdef int gl, j, k, l, v, gv + cdef long long i, q1, w, w1, q2, r, r1 + cdef bint flip + + q1 = p ** f - 1 + gl = len(gamma) + cdef array.array gamma_array1 = array.array('i', gamma.keys()) + cdef array.array gamma_array2 = array.array('i', gamma.values()) + cdef array.array r_array = array.array('i', [0]) * gl + cdef array.array digit_count = array.array('Q', [0]) * q1 + cdef array.array gtab2 + + R = gtable[0].parent() + ans = [] + if use_longs: + q2 = p ** prec + gtab2 = array.array('Q', [0]) * q1 + for r in range(q1): gtab2[r] = gtable[r].lift() % q2 + if f == 1: + for r in range(q1): digit_count[r] = r + else: + for r in range(q1): + r1 = r + digit_count[r] = 0 + for i in range(f): + digit_count[r] += r1 % p + r1 //= p + flip = (f == 1 and prec == 1 and R.precision_cap() == 1) + for r in range(q1): + # First determine whether this term is forced to be zero + # for divisibility reasons. If so, skip the p-adic arithmetic. + i = 0 + for k in range(gl): + v = gamma_array1[k] + gv = gamma_array2[k] + r1 = v * r % q1 + r_array[k] = r1 + i += digit_count[r1] * gv + i //= (p - 1) + l = i + f * (D + m[0] - m[r]) + if l >= prec: + ans.append(R.zero()) + continue + if use_longs: + w = 1 + w1 = 1 + else: + u = R.one() + u1 = R.one() + for k in range(gl): + gv = gamma_array2[k] + r1 = r_array[k] + if (flip): gv = -gv + if use_longs: + if gv > 0: + for j in range(gv): w = w * gtab2[r1] % q2 + else: + for j in range(-gv): w1 = w1 * gtab2[r1] % q2 + else: + if gv > 0: + for j in range(gv): u *= gtable[r1] + else: + for j in range(-gv): u1 *= gtable[r1] + if use_longs: + u = R(w) + u1 = R(w1) + if i % 2: u = -u + ans.append((u / u1) << l) + return ans diff --git a/src/sage/modular/hypergeometric_motive.py b/src/sage/modular/hypergeometric_motive.py index 4234279b41e..c0688319657 100644 --- a/src/sage/modular/hypergeometric_motive.py +++ b/src/sage/modular/hypergeometric_motive.py @@ -62,6 +62,7 @@ from collections import defaultdict from itertools import combinations import array +import sys from sage.arith.misc import divisors, gcd, euler_phi, moebius, is_prime from sage.arith.misc import gauss_sum, kronecker_symbol @@ -72,11 +73,12 @@ from sage.misc.cachefunc import cached_method from sage.misc.functional import cyclotomic_polynomial from sage.misc.misc_c import prod +from sage.modular.hypergeometric_misc import hgm_coeffs from sage.rings.fraction_field import FractionField from sage.rings.finite_rings.integer_mod_ring import IntegerModRing from sage.rings.integer_ring import ZZ -from sage.rings.padics.factory import Qp -from sage.rings.padics.misc import gauss_sum as padic_gauss_sum +from sage.rings.padics.factory import Qp, Zp +from sage.rings.padics.padic_generic_element import gauss_table from sage.rings.polynomial.polynomial_ring import polygen from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.rings.power_series_ring import PowerSeriesRing @@ -85,7 +87,6 @@ from sage.rings.finite_rings.finite_field_constructor import GF from sage.rings.universal_cyclotomic_field import UniversalCyclotomicField - def characteristic_polynomial_from_traces(traces, d, q, i, sign): r""" Given a sequence of traces `t_1, \dots, t_k`, return the @@ -396,6 +397,8 @@ def gamma_list_to_cyclotomic(galist): class HypergeometricData(object): + _gauss_table = {} + def __init__(self, cyclotomic=None, alpha_beta=None, gamma_list=None): r""" Creation of hypergeometric motives. @@ -1063,7 +1066,7 @@ def primitive_data(self): .. SEEALSO:: - :meth:`is_primitive`, :meth:`primitive_index`, + :meth:`is_primitive`, :meth:`primitive_index` EXAMPLES:: @@ -1077,9 +1080,71 @@ def primitive_data(self): d = gcd(g) return HypergeometricData(gamma_list=[x / d for x in g]) +### L-functions + + def gauss_table(self, p, f, prec): + """ + Return (and cache) a table of Gauss sums used in the trace formula. + + .. SEEALSO:: + + :meth:`gauss_table_full` + + EXAMPLES:: + + sage: from sage.modular.hypergeometric_motive import HypergeometricData as Hyp + sage: H = Hyp(cyclotomic=([3],[4])) + sage: H.gauss_table(2, 2, 4) + [1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3] + """ + try: + (prec1, gtab) = self._gauss_table[(p, f)] + if prec1 < prec: raise KeyError + except (AttributeError, KeyError) as err: + if err.__class__ == AttributeError: + self._gauss_table = {} + gtab = gauss_table(p, f, prec, False) + self._gauss_table[(p, f)] = (prec, gtab) + return gtab + + def gauss_table_full(self): + """ + Return a dict of all stored tables of Gauss sums. + + The result is passed by reference, and is an attribute of the class; + consequently, modifying the result has global side effects. Use with + caution. + + .. SEEALSO:: + + :meth:`gauss_table` + + EXAMPLES:: + + sage: from sage.modular.hypergeometric_motive import HypergeometricData as Hyp + sage: H = Hyp(cyclotomic=([3],[4])) + sage: H.euler_factor(2, 7, cache_p=True) + 7*T^2 - 3*T + 1 + sage: H.gauss_table_full()[(7, 1)] + (2, [6 + 6*7, 6 + 2*7, 3 + 3*7, 1, 2, 6 + 3*7]) + + Clearing cached values:: + + sage: H = Hyp(cyclotomic=([3],[4])) + sage: H.euler_factor(2, 7, cache_p=True) + 7*T^2 - 3*T + 1 + sage: d = H.gauss_table_full() + sage: d.clear() # Delete all entries of this dict + sage: H1 = Hyp(cyclotomic=([5],[12])) + sage: d1 = H1.gauss_table_full() + sage: len(d1.keys()) # No cached values + 0 + """ + return self._gauss_table + # --- L-functions --- @cached_method - def padic_H_value(self, p, f, t, prec=None): + def padic_H_value(self, p, f, t, prec=None, cache_p=False): """ Return the `p`-adic trace of Frobenius, computed using the Gross-Koblitz formula. @@ -1087,6 +1152,11 @@ def padic_H_value(self, p, f, t, prec=None): If left unspecified, `prec` is set to the minimum `p`-adic precision needed to recover the Euler factor. + If `cache_p` is True, then the function caches an intermediate + result which depends only on `p` and `f`. This leads to a significant + speedup when iterating over `t`. (When iterating also over the + hypergeometric data, one should also use :meth:`set_gauss_table`.) + INPUT: - `p` -- a prime number @@ -1097,6 +1167,8 @@ def padic_H_value(self, p, f, t, prec=None): - ``prec`` -- precision (optional) + - ``cache_p`` - a boolean + OUTPUT: an integer @@ -1141,48 +1213,41 @@ def padic_H_value(self, p, f, t, prec=None): t = QQ(t) if 0 in alpha: return self._swap.padic_H_value(p, f, ~t, prec) - gamma = self.gamma_array() - q = p**f + q = p ** f + if q * p > 2 ** 64: + return ValueError("p^(f+1) cannot exceed 2^64") - # m = {r: beta.count(QQ((r, q - 1))) for r in range(q - 1)} - m = array.array('i', [0] * (q - 1)) + m = array.array('i', [0]) * int(q - 1) for b in beta: u = b * (q - 1) - if u.is_integer(): - m[u] += 1 + if u.is_integer(): m[u] += 1 M = self.M_value() D = -min(self.zigzag(x, flip_beta=True) for x in alpha + beta) # also: D = (self.weight() + 1 - m[0]) // 2 if prec is None: - prec = (self.weight() * f) // 2 + ceil(log(self.degree(), p)) + 1 - # For some reason, working in Qp instead of Zp is much faster; - # it appears to avoid some costly conversions. - p_ring = Qp(p, prec=prec) - teich = p_ring.teichmuller(M / t) - - gauss_table = [None] * (q - 1) - for r in range(q - 1): - if gauss_table[r] is None: - gauss_table[r] = padic_gauss_sum(r, p, f, prec, factored=True, - algorithm='sage', parent=p_ring) - r1 = (r * p) % (q - 1) - while r1 != r: - gauss_table[r1] = gauss_table[r] - r1 = (r1 * p) % (q - 1) - - sigma = p_ring.zero() - u1 = p_ring.one() - for r in range(q - 1): - i = int(0) - u = u1 - u1 *= teich - for v, gv in gamma.items(): - r1 = (v * r) % (q - 1) - i += gauss_table[r1][0] * gv - u *= gauss_table[r1][1] ** gv - sigma += (-p)**(i // (p - 1)) * u << (f * (D + m[0] - m[r])) - resu = ZZ(-1) ** m[0] / (1 - q) * sigma + prec = ceil((self.weight() * f) / 2 + log(2*self.degree()+1, p)) + use_longs = (p ** prec < 2 ** 31) + + gamma = self._gamma_array + if cache_p: + try: + trcoeffs = self._trace_coeffs[(p, f)] + except (AttributeError, KeyError) as err: + if err.__class__ == AttributeError: + self._trace_coeffs = {} + gtab = self.gauss_table(p, f, prec) + trcoeffs = hgm_coeffs(p, f, prec, gamma, m, D, gtab, use_longs) + self._trace_coeffs[(p,f)] = trcoeffs + else: + gtab = gauss_table(p, f, prec, use_longs) + trcoeffs = hgm_coeffs(p, f, prec, gamma, m, D, gtab, use_longs) + sigma = trcoeffs[q-2] + p_ring = sigma.parent() + teich = p_ring.teichmuller(M/t) + for i in range(q-3, -1, -1): + sigma = sigma * teich + trcoeffs[i] + resu = ZZ(-1) ** m[0] * sigma / (1 - q) return IntegerModRing(p**prec)(resu).lift_centered() @cached_method @@ -1334,7 +1399,7 @@ def sign(self, t, p): return sign @cached_method - def euler_factor(self, t, p): + def euler_factor(self, t, p, cache_p=False): """ Return the Euler factor of the motive `H_t` at prime `p`. @@ -1395,6 +1460,14 @@ def euler_factor(self, t, p): 279841*T^4 - 25392*T^3 + 1242*T^2 - 48*T + 1, 707281*T^4 - 7569*T^3 + 696*T^2 - 9*T + 1] + This is an example of higher degree:: + + sage: H = Hyp(cyclotomic=([11], [7, 12])) + sage: H.euler_factor(2, 13) + 371293*T^10 - 85683*T^9 + 26364*T^8 + 1352*T^7 - 65*T^6 + 394*T^5 - 5*T^4 + 8*T^3 + 12*T^2 - 3*T + 1 + sage: H.euler_factor(2, 19) # long time + 2476099*T^10 - 651605*T^9 + 233206*T^8 - 77254*T^7 + 20349*T^6 - 4611*T^5 + 1071*T^4 - 214*T^3 + 34*T^2 - 5*T + 1 + TESTS:: sage: H1 = Hyp(alpha_beta=([1,1,1],[1/2,1/2,1/2])) @@ -1427,7 +1500,8 @@ def euler_factor(self, t, p): # now p is good d = self.degree() bound = d // 2 - traces = [self.padic_H_value(p, i + 1, t) for i in range(bound)] + traces = [self.padic_H_value(p, i + 1, t, cache_p=cache_p) + for i in range(bound)] w = self.weight() sign = self.sign(t, p) diff --git a/src/sage/rings/padics/misc.py b/src/sage/rings/padics/misc.py index def3b8d177d..b2ffd91f2f8 100644 --- a/src/sage/rings/padics/misc.py +++ b/src/sage/rings/padics/misc.py @@ -139,6 +139,7 @@ def gauss_sum(a, p, f, prec=20, factored=False, algorithm='pari', parent=None): s = sum(a.digits(base=p)) if factored: return(s, out) + X = PolynomialRing(R, name='X').gen() pi = R.ext(X**(p - 1) + p, names='pi').gen() out *= pi**s diff --git a/src/sage/rings/padics/padic_generic_element.pxd b/src/sage/rings/padics/padic_generic_element.pxd index 9166e3fcf2c..fe08b038568 100644 --- a/src/sage/rings/padics/padic_generic_element.pxd +++ b/src/sage/rings/padics/padic_generic_element.pxd @@ -6,6 +6,8 @@ from sage.rings.padics.pow_computer cimport PowComputer_class from sage.rings.integer cimport Integer from sage.rings.rational cimport Rational +cpdef gauss_table(long long p, int f, int prec, bint use_longs) + cdef class pAdicGenericElement(LocalGenericElement): cdef long valuation_c(self) cpdef val_unit(self) @@ -41,3 +43,4 @@ cdef class pAdicGenericElement(LocalGenericElement): cpdef _mod_(self, right) cpdef _floordiv_(self, right) cpdef bint _is_base_elt(self, p) except -1 + diff --git a/src/sage/rings/padics/padic_generic_element.pyx b/src/sage/rings/padics/padic_generic_element.pyx index 11968020ce8..d4b3061f017 100644 --- a/src/sage/rings/padics/padic_generic_element.pyx +++ b/src/sage/rings/padics/padic_generic_element.pyx @@ -42,7 +42,6 @@ from sage.structure.richcmp cimport rich_to_bool cdef long maxordp = (1L << (sizeof(long) * 8 - 2)) - 1 - cdef class pAdicGenericElement(LocalGenericElement): cpdef _richcmp_(left, right, int op): """ @@ -1230,7 +1229,7 @@ cdef class pAdicGenericElement(LocalGenericElement): INPUT: - - ``bd`` -- integer. Is a bound for precision, defaults to 20 + - ``bd`` -- integer. Precision bound, defaults to 20 - ``a`` -- integer. Offset parameter, defaults to 0 OUTPUT: @@ -1265,6 +1264,8 @@ cdef class pAdicGenericElement(LocalGenericElement): 4 + 4*5 + 4*5^2 + 4*5^3 + 2*5^4 + 4*5^5 + 5^7 + 3*5^9 + 4*5^10 + 3*5^11 + 5^13 + 4*5^14 + 2*5^15 + 2*5^16 + 2*5^17 + 3*5^18 + O(5^20) + TESTS: + This test was added in :trac:`24433`:: sage: F = Qp(7) @@ -1274,36 +1275,19 @@ cdef class pAdicGenericElement(LocalGenericElement): 6 + 4*7^19 + O(7^20) """ R = self.parent() - cdef int p = R.prime() - cdef int b = a - cdef int k + p = R.prime() - s = R.zero().add_bigoh(bd) - t = R.one().add_bigoh(bd) + # If p == 2, must work in Qp rather than Zp. + if p == 2 and not R.is_field(): + S = R.fraction_field() + return R(S(self).dwork_expansion(bd, a)) try: v = R.dwork_coeffs + if len(v) < p*bd: + raise AttributeError except AttributeError: - v = None - if v is not None and len(v) < p * bd: - v = None - if v is not None: - for k in range(bd): - s += t * v[p*k+b] - t *= (self + k) - else: - u = [t] - v = [] - for j in range(1, p): - u.append(u[j-1] / j) - for k in range(bd): - v += [x << k for x in u] - s += t * (u[a] << k) - t *= (self + k) - u[0] = ((u[-1] + u[0]) / (k+1)) >> 1 - for j in range(1, p): - u[j] = (u[j-1] + u[j]) / (j + (k+1) * p ) - R.dwork_coeffs = v - return -s + v = dwork_mahler_coeffs(R, bd) + return evaluate_dwork_mahler(v, self, p, bd, a) def gamma(self, algorithm='pari'): r""" @@ -1410,11 +1394,9 @@ cdef class pAdicGenericElement(LocalGenericElement): return parent(self.__pari__().gamma()) elif algorithm == 'sage': p = parent.prime() - bd = -((-n*p)//(p-1)) + bd = -((-n*p) // (p-1)) k = (-self) % p x = (self+k) >> 1 - if p==2 and n>=3: - x = x.lift_to_precision(n) return -x.dwork_expansion(bd, k.lift()) @coerce_binop @@ -4411,3 +4393,170 @@ def _compute_g(p, n, prec, terms): for i in range(n): g[i+1] = -(g[i]/(v-v**2)).integral() return [x.truncate(terms) for x in g] + +cpdef dwork_mahler_coeffs(R, int bd=20): + r""" + Compute Dwork's formula for Mahler coefficients of `p`-adic Gamma. + + This is called internally when one computes Gamma for a `p`-adic + integer. Normally there is no need to call it directly. + + INPUT: + + - ``R`` -- p-adic ring in which to compute + - ``bd`` -- integer. Number of terms in the expansion to use + + OUTPUT: + + A list of `p`-adic integers. + + EXAMPLES:: + + sage: from sage.rings.padics.padic_generic_element import dwork_mahler_coeffs, evaluate_dwork_mahler + sage: R = Zp(3) + sage: v = dwork_mahler_coeffs(R) + sage: x = R(1/7) + sage: evaluate_dwork_mahler(v, x, 3, 20, 1) + 2 + 2*3 + 3^2 + 3^3 + 3^4 + 3^5 + 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^11 + 2*3^12 + 3^13 + 3^14 + 2*3^16 + 3^17 + 3^19 + O(3^20) + sage: x.dwork_expansion(a=1) # Same result + 2 + 2*3 + 3^2 + 3^3 + 3^4 + 3^5 + 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^11 + 2*3^12 + 3^13 + 3^14 + 2*3^16 + 3^17 + 3^19 + O(3^20) + """ + from sage.rings.padics.factory import Qp + cdef int i + cdef long k, p + + v = [R.one()] + p = R.prime() + for k in range(1, p): + v.append(v[-1] / R(k)) + if bd > 1: + R1 = Qp(p, prec=bd) # Need divisions in this calculation + u = [R1(x) for x in v] + for i in range(1, bd): + u[0] = ((u[-1] + u[0]) / i) >> 1 + for j in range(1, p): + u[j] = (u[j-1] + u[j]) / (j + i * p) + for x in u: + v.append(R(x << i)) + return v + +cpdef evaluate_dwork_mahler(v, x, long long p, int bd, long long a): + """ + Evaluate Dwork's Mahler series for `p`-adic Gamma. + + EXAMPLES:: + + sage: from sage.rings.padics.padic_generic_element import dwork_mahler_coeffs, evaluate_dwork_mahler + sage: R = Zp(3) + sage: v = dwork_mahler_coeffs(R) + sage: x = R(1/7) + sage: evaluate_dwork_mahler(v, x, 3, 20, 1) + 2 + 2*3 + 3^2 + 3^3 + 3^4 + 3^5 + 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^11 + 2*3^12 + 3^13 + 3^14 + 2*3^16 + 3^17 + 3^19 + O(3^20) + sage: x.dwork_expansion(a=1) # Same result + 2 + 2*3 + 3^2 + 3^3 + 3^4 + 3^5 + 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^11 + 2*3^12 + 3^13 + 3^14 + 2*3^16 + 3^17 + 3^19 + O(3^20) + """ + cdef int k + bd -= 1 + a1 = a + bd*p + s = v[a1] + u = x + bd + w = x.parent().one() + for k in range(bd): + a1 -= p + u -= w + s = s*u + v[a1] + return -s + +cdef long long evaluate_dwork_mahler_long(v, long long x, long long p, int bd, + long long a, long long q): + cdef int k + cdef long long a1, s, u + bd -= 1 + a1 = a + bd*p + s = v[a1].lift() + u = x + bd + for k in range(bd): + a1 -= p + u -= 1 + s = (s*u + v[a1].lift()) % q + return -s + +cpdef gauss_table(long long p, int f, int prec, bint use_longs): + r""" + Compute a table of Gauss sums using the Gross-Koblitz formula. + + This is used in the computation of L-functions of hypergeometric motives. + The Gross-Koblitz formula is used as in `sage.rings.padics.misc.gauss_sum`, + but further unpacked for efficiency. + + INPUT: + + - `p` - prime + - `f`, `prec` - positive integers + - `use_longs` - boolean; if True, computations are done in C long + integers rather than Sage `p`-adics + + OUTPUT: + + A list of length `q-1=p^f-1`. The entries are `p`-adic units created with + absolute precision `prec`. + + EXAMPLES:: + + sage: from sage.rings.padics.padic_generic_element import gauss_table + sage: gauss_table(2,2,4,False) + [1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3] + sage: gauss_table(3,2,4,False)[3] + 2 + 3 + 2*3^2 + """ + from sage.rings.padics.factory import Zp, Qp + + cdef int i, j, bd + cdef long long q, q1, q3, r, r1, r2, s1, k + + R = Zp(p, prec, 'fixed-mod') + + if (f == 1 and prec == 1): # Shortcut for this key special case + ans = [-R.one()] + for r in range(1, p-1): + ans.append(ans[-1] * R(r)) + return ans + + q = p ** f + q1 = q - 1 + bd = (p*prec+p-2) // (p-1) - 1 + if p == 2: # Dwork expansion has denominators when p = 2 + R1 = Qp(p, prec) + else: + R1 = R + u = R1.one() + ans = [None for r in range(q1)] + ans[0] = -u + d = ~R1(q1) + if use_longs: + q3 = p ** prec + r2 = d.lift() % q3 + v = dwork_mahler_coeffs(R1, bd) + for r in range(1, q1): + if ans[r] is not None: continue + s = u + if use_longs: s1 = 1 + r1 = r + for j in range(1, f+1): + k = r1 % p + r1 = (r1 + k * q1) // p + if use_longs: # Use Dwork expansion to compute p-adic Gamma + s1 *= -evaluate_dwork_mahler_long(v, r1*r2, p, bd, k, q3) + s1 %= q3 + else: + s *= -evaluate_dwork_mahler(v, R1(r1)*d, p, bd, k) + if r1 == r: # End the loop. + if use_longs: s = R1(s1) + if j < f: s **= f // j + break + ans[r] = -s + for i in range(j-1): + r1 = r1 * p % q1 # Initially r1 == r + ans[r1] = ans[r] + if p != 2: return ans + return [R(x) for x in ans] From 65d3cacb324e4d02c82b8d25a00979d697ee1c6e Mon Sep 17 00:00:00 2001 From: Kiran Kedlaya Date: Thu, 26 Dec 2019 18:09:17 -0800 Subject: [PATCH 014/133] Fix pyflakes issues in hypergeometric_motive.py --- src/sage/modular/hypergeometric_motive.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/sage/modular/hypergeometric_motive.py b/src/sage/modular/hypergeometric_motive.py index c0688319657..18ab51cf1f3 100644 --- a/src/sage/modular/hypergeometric_motive.py +++ b/src/sage/modular/hypergeometric_motive.py @@ -62,7 +62,6 @@ from collections import defaultdict from itertools import combinations import array -import sys from sage.arith.misc import divisors, gcd, euler_phi, moebius, is_prime from sage.arith.misc import gauss_sum, kronecker_symbol @@ -77,7 +76,6 @@ from sage.rings.fraction_field import FractionField from sage.rings.finite_rings.integer_mod_ring import IntegerModRing from sage.rings.integer_ring import ZZ -from sage.rings.padics.factory import Qp, Zp from sage.rings.padics.padic_generic_element import gauss_table from sage.rings.polynomial.polynomial_ring import polygen from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing From 4ba780eeb294c0390f3d83f1ffc355802590e018 Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Fri, 27 Dec 2019 20:40:49 +0100 Subject: [PATCH 015/133] Trac 28916: Flexible coercion of mixed forms --- .../differentiable/mixed_form_algebra.py | 76 +++++++++++-------- 1 file changed, 46 insertions(+), 30 deletions(-) diff --git a/src/sage/manifolds/differentiable/mixed_form_algebra.py b/src/sage/manifolds/differentiable/mixed_form_algebra.py index 5aaab8e08c8..173a6596a04 100644 --- a/src/sage/manifolds/differentiable/mixed_form_algebra.py +++ b/src/sage/manifolds/differentiable/mixed_form_algebra.py @@ -197,31 +197,32 @@ def _element_constructor_(self, comp=None, name=None, latex_name=None): return self.zero() elif comp in ZZ and comp == 1: return self.one() - elif isinstance(comp, tuple): - comp_list = list(comp) - if len(comp_list) != self._max_deg + 1: - raise IndexError( "input list must have" - " length {}".format(self._max_deg + 1)) - res[:] = comp_list - elif isinstance(comp, list): + elif isinstance(comp, (tuple, list)): if len(comp) != self._max_deg + 1: - raise IndexError( "input list must have" - " length {}".format(self._max_deg + 1)) - res[:] = comp + raise IndexError( "input list must have " + "length {}".format(self._max_deg + 1)) + if isinstance(com, tuple): + comp = list(comp) + res[:] = comp[:] elif isinstance(comp, self.Element): res[:] = comp[:] else: - ### - # Now, comp seems to be a differential form: + # Has comp a degree method? try: deg = comp.degree() except (AttributeError, NotImplementedError): - # No degree method? Perhaps the degree is zero? - deg = 0 - + # No? Then we must check consecutively: + for d in self.irange(): + dmodule = self._domain.diff_form_module(deg, + dest_map=self._dest_map) + if dmodule.has_coerce_map_from(comp.parent()): + deg = d + break + else: + raise TypeError("cannot convert {} into an element of " + "the {}".format(comp, self)) res[:] = [0] * (self._max_deg + 1) # fill up with zeroes... res[deg] = comp # ...and set comp at deg of res - ### # In case, no other name is given, use name of comp for better # coercion: if name is None: @@ -277,20 +278,36 @@ def _coerce_map_from_(self, S): False """ - if isinstance(S, self.__class__): + if isinstance(S, type(self)): # coercion by domain restriction - return (self._domain.is_subset(S._domain) and - self._ambient_domain.is_subset(S._ambient_domain)) - # Test scalar_field_algebra separately to ensure coercion from SR: - if self._domain.scalar_field_algebra().has_coerce_map_from(S): + if (self._domain.is_subset(S._domain) and + self._ambient_domain.is_subset(S._ambient_domain)): + return True + # Still, there could be a coerce map + if self.irange() != S.irange(): + return False + # Check coercions on each degree: + for deg in self.irange(): + dmodule1 = self._domain.diff_form_module(deg, self._dest_map) + dmodule2 = S._domain.diff_form_module(deg, S._dest_map) + if not dmodule1.has_coerce_map_from(dmodule2): + return False + # Each degree is coercible so there must be a coerce map: return True - # This is tricky, we need to check the degree first: + # If S has a degree method, a coerce map could exist: try: deg = S.degree() - if self._domain.diff_form_module(deg, self._dest_map).has_coerce_map_from(S): + if self._domain.diff_form_module(deg, + self._dest_map).has_coerce_map_from(S): return True except (NotImplementedError, AttributeError, TypeError): pass + # Otherwise let us check the degree consecutively: + for deg in self.irange(): + if self._domain.diff_form_module(deg, + self._dest_map).has_coerce_map_from(S): + return True + # Nothing found... return False @cached_method @@ -369,19 +386,18 @@ def _repr_(self): 3-dimensional differentiable manifold M """ - description = ("Graded algebra " + self._name + - " of mixed differential forms ") + desc = ("Graded algebra " + self._name + " of mixed differential forms ") if self._dest_map is self._domain.identity_map(): - description += "on the {}".format(self._domain) + desc += "on the {}".format(self._domain) else: - description += "along the {} mapped into the {} ".format( - self._domain, self._ambient_domain) + desc += "along the {} mapped into the {} ".format(self._domain, + self._ambient_domain) if self._dest_map._name is None: dm_name = "unnamed map" else: dm_name = self._dest_map._name - description += "via " + dm_name - return description + desc += "via " + dm_name + return desc def _latex_(self): r""" From 3132acc35ea82346bafe2eecc81ca97f6adf5e2b Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Fri, 27 Dec 2019 21:16:16 +0100 Subject: [PATCH 016/133] Trac 28916: Bugs fixed and code cleaned --- .../differentiable/mixed_form_algebra.py | 34 ++++++++----------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/src/sage/manifolds/differentiable/mixed_form_algebra.py b/src/sage/manifolds/differentiable/mixed_form_algebra.py index 173a6596a04..c9cd1017546 100644 --- a/src/sage/manifolds/differentiable/mixed_form_algebra.py +++ b/src/sage/manifolds/differentiable/mixed_form_algebra.py @@ -199,32 +199,26 @@ def _element_constructor_(self, comp=None, name=None, latex_name=None): return self.one() elif isinstance(comp, (tuple, list)): if len(comp) != self._max_deg + 1: - raise IndexError( "input list must have " - "length {}".format(self._max_deg + 1)) - if isinstance(com, tuple): + raise IndexError("input list must have " + "length {}".format(self._max_deg + 1)) + if isinstance(comp, tuple): comp = list(comp) res[:] = comp[:] elif isinstance(comp, self.Element): res[:] = comp[:] else: - # Has comp a degree method? - try: - deg = comp.degree() - except (AttributeError, NotImplementedError): - # No? Then we must check consecutively: - for d in self.irange(): - dmodule = self._domain.diff_form_module(deg, - dest_map=self._dest_map) - if dmodule.has_coerce_map_from(comp.parent()): - deg = d - break - else: - raise TypeError("cannot convert {} into an element of " - "the {}".format(comp, self)) + for d in self.irange(): + dmodule = self._domain.diff_form_module(d, dest_map=self._dest_map) + if dmodule.has_coerce_map_from(comp.parent()): + deg = d + break + else: + raise TypeError("cannot convert {} into an element of " + "the {}".format(comp, self)) res[:] = [0] * (self._max_deg + 1) # fill up with zeroes... - res[deg] = comp # ...and set comp at deg of res - # In case, no other name is given, use name of comp for better - # coercion: + res[deg] = comp # ...and set comp at deg of res; + # the coercion is performed here + # In case, no other name is given, use name of comp: if name is None: if hasattr(comp, '_name'): res._name = comp._name From 6775b86a3a5c4dd10185bc1e7e2eb25136c31041 Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Fri, 27 Dec 2019 21:24:07 +0100 Subject: [PATCH 017/133] Trac 28916: try...except removed --- .../manifolds/differentiable/mixed_form_algebra.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/sage/manifolds/differentiable/mixed_form_algebra.py b/src/sage/manifolds/differentiable/mixed_form_algebra.py index c9cd1017546..ab95c014bab 100644 --- a/src/sage/manifolds/differentiable/mixed_form_algebra.py +++ b/src/sage/manifolds/differentiable/mixed_form_algebra.py @@ -288,15 +288,7 @@ def _coerce_map_from_(self, S): return False # Each degree is coercible so there must be a coerce map: return True - # If S has a degree method, a coerce map could exist: - try: - deg = S.degree() - if self._domain.diff_form_module(deg, - self._dest_map).has_coerce_map_from(S): - return True - except (NotImplementedError, AttributeError, TypeError): - pass - # Otherwise let us check the degree consecutively: + # Let us check for each degree consecutively: for deg in self.irange(): if self._domain.diff_form_module(deg, self._dest_map).has_coerce_map_from(S): From 87425aa9ca3a0fddbce658ee9caba85d9650d2c9 Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Sun, 29 Dec 2019 01:16:30 +0100 Subject: [PATCH 018/133] Trac 28921: Simple checks added for _lmul_ --- src/sage/manifolds/differentiable/mixed_form.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/sage/manifolds/differentiable/mixed_form.py b/src/sage/manifolds/differentiable/mixed_form.py index 3cf6ff50f81..103224d102d 100644 --- a/src/sage/manifolds/differentiable/mixed_form.py +++ b/src/sage/manifolds/differentiable/mixed_form.py @@ -874,7 +874,7 @@ def _lmul_(self, other): INPUT: - - ``num`` -- an element of the symbolic ring + - ``other`` -- an element of the symbolic ring OUTPUT: @@ -896,6 +896,11 @@ def _lmul_(self, other): y/\(x/\F) = [0] + [x^2*y^2 dx] + [0] """ + # Simple checks: + if other.is_trivial_zero(): + return self.parent().zero() + elif other.is_one(): + return self resu = self._new_instance() resu[:] = [other * form for form in self._comp] # Compose name: From 3b3873d77e4ee5c88fea86ad25e8d9649e8a5ccb Mon Sep 17 00:00:00 2001 From: Kiran Kedlaya Date: Mon, 30 Dec 2019 09:54:58 -0800 Subject: [PATCH 019/133] Remove non-ASCII character from docstring --- src/sage/rings/padics/padic_generic_element.pyx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/rings/padics/padic_generic_element.pyx b/src/sage/rings/padics/padic_generic_element.pyx index d4b3061f017..03f737b1e3d 100644 --- a/src/sage/rings/padics/padic_generic_element.pyx +++ b/src/sage/rings/padics/padic_generic_element.pyx @@ -1420,7 +1420,7 @@ cdef class pAdicGenericElement(LocalGenericElement): 0 and 3 in the 3-adic ring `\ZZ_3`. The greatest common divisor of `O(3)` and `O(3)` could be (among others) 3 or 0 which have different valuation. The algorithm implemented here, will - return an element of minimal valuation among the possible greatest + return an element of minimal valuation among the possible greatest common divisors. EXAMPLES: From a14aedb2934c07d38f9997ce4ddaa81ae4ce75fe Mon Sep 17 00:00:00 2001 From: Kiran Kedlaya Date: Tue, 24 Dec 2019 19:05:06 -0800 Subject: [PATCH 020/133] Summary commit of Cythonization of HGMs --- src/module_list.py | 3 + src/sage/modular/hypergeometric_misc.pxd | 4 + src/sage/modular/hypergeometric_misc.pyx | 98 ++++++++ src/sage/modular/hypergeometric_motive.py | 156 +++++++++---- src/sage/rings/padics/misc.py | 1 + .../rings/padics/padic_generic_element.pxd | 3 + .../rings/padics/padic_generic_element.pyx | 211 +++++++++++++++--- 7 files changed, 404 insertions(+), 72 deletions(-) create mode 100644 src/sage/modular/hypergeometric_misc.pxd create mode 100644 src/sage/modular/hypergeometric_misc.pyx diff --git a/src/module_list.py b/src/module_list.py index fc8bb929567..791bcb8a2a2 100644 --- a/src/module_list.py +++ b/src/module_list.py @@ -927,6 +927,9 @@ def uname_specific(name, value, alternative): Extension('sage.modular.arithgroup.arithgroup_element', sources = ['sage/modular/arithgroup/arithgroup_element.pyx']), + Extension('sage.modular.hypergeometric_misc', + sources = ['sage/modular/hypergeometric_misc.pyx']), + Extension('sage.modular.modform.eis_series_cython', sources = ['sage/modular/modform/eis_series_cython.pyx']), diff --git a/src/sage/modular/hypergeometric_misc.pxd b/src/sage/modular/hypergeometric_misc.pxd new file mode 100644 index 00000000000..f3ef421fd11 --- /dev/null +++ b/src/sage/modular/hypergeometric_misc.pxd @@ -0,0 +1,4 @@ +from cpython cimport array + +cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, + gtable, bint use_longs) diff --git a/src/sage/modular/hypergeometric_misc.pyx b/src/sage/modular/hypergeometric_misc.pyx new file mode 100644 index 00000000000..cfb62caf716 --- /dev/null +++ b/src/sage/modular/hypergeometric_misc.pyx @@ -0,0 +1,98 @@ +""" +Some utility routines for the hypergeometric motives package that benefit +significantly from Cythonization. +""" + +from cpython cimport array + +cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, + gtable, bint use_longs): + r""" + Compute coefficients for the hypergeometric trace formula. + + This function is not intended for direct user access. + + TESTS:: + + sage: from sage.modular.hypergeometric_motive import HypergeometricData as Hyp + sage: import array + sage: from sage.modular.hypergeometric_misc import hgm_coeffs + sage: H = Hyp(cyclotomic=([3],[4])) + sage: H.euler_factor(2, 7, cache_p=True) + 7*T^2 - 3*T + 1 + sage: gamma = H.gamma_array() + sage: gtable = H.gauss_table(7, 1, 2) + sage: m = array.array('i', [0]*6) + sage: D = 1 + sage: hgm_coeffs(7, 1, 2, gamma, m, D, gtable, False) + [7, 2*7, 6*7, 7, 6, 4*7] + """ + cdef int gl, j, k, l, v, gv + cdef long long i, q1, w, w1, q2, r, r1 + cdef bint flip + + q1 = p ** f - 1 + gl = len(gamma) + cdef array.array gamma_array1 = array.array('i', gamma.keys()) + cdef array.array gamma_array2 = array.array('i', gamma.values()) + cdef array.array r_array = array.array('i', [0]) * gl + cdef array.array digit_count = array.array('Q', [0]) * q1 + cdef array.array gtab2 + + R = gtable[0].parent() + ans = [] + if use_longs: + q2 = p ** prec + gtab2 = array.array('Q', [0]) * q1 + for r in range(q1): gtab2[r] = gtable[r].lift() % q2 + if f == 1: + for r in range(q1): digit_count[r] = r + else: + for r in range(q1): + r1 = r + digit_count[r] = 0 + for i in range(f): + digit_count[r] += r1 % p + r1 //= p + flip = (f == 1 and prec == 1 and R.precision_cap() == 1) + for r in range(q1): + # First determine whether this term is forced to be zero + # for divisibility reasons. If so, skip the p-adic arithmetic. + i = 0 + for k in range(gl): + v = gamma_array1[k] + gv = gamma_array2[k] + r1 = v * r % q1 + r_array[k] = r1 + i += digit_count[r1] * gv + i //= (p - 1) + l = i + f * (D + m[0] - m[r]) + if l >= prec: + ans.append(R.zero()) + continue + if use_longs: + w = 1 + w1 = 1 + else: + u = R.one() + u1 = R.one() + for k in range(gl): + gv = gamma_array2[k] + r1 = r_array[k] + if (flip): gv = -gv + if use_longs: + if gv > 0: + for j in range(gv): w = w * gtab2[r1] % q2 + else: + for j in range(-gv): w1 = w1 * gtab2[r1] % q2 + else: + if gv > 0: + for j in range(gv): u *= gtable[r1] + else: + for j in range(-gv): u1 *= gtable[r1] + if use_longs: + u = R(w) + u1 = R(w1) + if i % 2: u = -u + ans.append((u / u1) << l) + return ans diff --git a/src/sage/modular/hypergeometric_motive.py b/src/sage/modular/hypergeometric_motive.py index 4234279b41e..c0688319657 100644 --- a/src/sage/modular/hypergeometric_motive.py +++ b/src/sage/modular/hypergeometric_motive.py @@ -62,6 +62,7 @@ from collections import defaultdict from itertools import combinations import array +import sys from sage.arith.misc import divisors, gcd, euler_phi, moebius, is_prime from sage.arith.misc import gauss_sum, kronecker_symbol @@ -72,11 +73,12 @@ from sage.misc.cachefunc import cached_method from sage.misc.functional import cyclotomic_polynomial from sage.misc.misc_c import prod +from sage.modular.hypergeometric_misc import hgm_coeffs from sage.rings.fraction_field import FractionField from sage.rings.finite_rings.integer_mod_ring import IntegerModRing from sage.rings.integer_ring import ZZ -from sage.rings.padics.factory import Qp -from sage.rings.padics.misc import gauss_sum as padic_gauss_sum +from sage.rings.padics.factory import Qp, Zp +from sage.rings.padics.padic_generic_element import gauss_table from sage.rings.polynomial.polynomial_ring import polygen from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.rings.power_series_ring import PowerSeriesRing @@ -85,7 +87,6 @@ from sage.rings.finite_rings.finite_field_constructor import GF from sage.rings.universal_cyclotomic_field import UniversalCyclotomicField - def characteristic_polynomial_from_traces(traces, d, q, i, sign): r""" Given a sequence of traces `t_1, \dots, t_k`, return the @@ -396,6 +397,8 @@ def gamma_list_to_cyclotomic(galist): class HypergeometricData(object): + _gauss_table = {} + def __init__(self, cyclotomic=None, alpha_beta=None, gamma_list=None): r""" Creation of hypergeometric motives. @@ -1063,7 +1066,7 @@ def primitive_data(self): .. SEEALSO:: - :meth:`is_primitive`, :meth:`primitive_index`, + :meth:`is_primitive`, :meth:`primitive_index` EXAMPLES:: @@ -1077,9 +1080,71 @@ def primitive_data(self): d = gcd(g) return HypergeometricData(gamma_list=[x / d for x in g]) +### L-functions + + def gauss_table(self, p, f, prec): + """ + Return (and cache) a table of Gauss sums used in the trace formula. + + .. SEEALSO:: + + :meth:`gauss_table_full` + + EXAMPLES:: + + sage: from sage.modular.hypergeometric_motive import HypergeometricData as Hyp + sage: H = Hyp(cyclotomic=([3],[4])) + sage: H.gauss_table(2, 2, 4) + [1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3] + """ + try: + (prec1, gtab) = self._gauss_table[(p, f)] + if prec1 < prec: raise KeyError + except (AttributeError, KeyError) as err: + if err.__class__ == AttributeError: + self._gauss_table = {} + gtab = gauss_table(p, f, prec, False) + self._gauss_table[(p, f)] = (prec, gtab) + return gtab + + def gauss_table_full(self): + """ + Return a dict of all stored tables of Gauss sums. + + The result is passed by reference, and is an attribute of the class; + consequently, modifying the result has global side effects. Use with + caution. + + .. SEEALSO:: + + :meth:`gauss_table` + + EXAMPLES:: + + sage: from sage.modular.hypergeometric_motive import HypergeometricData as Hyp + sage: H = Hyp(cyclotomic=([3],[4])) + sage: H.euler_factor(2, 7, cache_p=True) + 7*T^2 - 3*T + 1 + sage: H.gauss_table_full()[(7, 1)] + (2, [6 + 6*7, 6 + 2*7, 3 + 3*7, 1, 2, 6 + 3*7]) + + Clearing cached values:: + + sage: H = Hyp(cyclotomic=([3],[4])) + sage: H.euler_factor(2, 7, cache_p=True) + 7*T^2 - 3*T + 1 + sage: d = H.gauss_table_full() + sage: d.clear() # Delete all entries of this dict + sage: H1 = Hyp(cyclotomic=([5],[12])) + sage: d1 = H1.gauss_table_full() + sage: len(d1.keys()) # No cached values + 0 + """ + return self._gauss_table + # --- L-functions --- @cached_method - def padic_H_value(self, p, f, t, prec=None): + def padic_H_value(self, p, f, t, prec=None, cache_p=False): """ Return the `p`-adic trace of Frobenius, computed using the Gross-Koblitz formula. @@ -1087,6 +1152,11 @@ def padic_H_value(self, p, f, t, prec=None): If left unspecified, `prec` is set to the minimum `p`-adic precision needed to recover the Euler factor. + If `cache_p` is True, then the function caches an intermediate + result which depends only on `p` and `f`. This leads to a significant + speedup when iterating over `t`. (When iterating also over the + hypergeometric data, one should also use :meth:`set_gauss_table`.) + INPUT: - `p` -- a prime number @@ -1097,6 +1167,8 @@ def padic_H_value(self, p, f, t, prec=None): - ``prec`` -- precision (optional) + - ``cache_p`` - a boolean + OUTPUT: an integer @@ -1141,48 +1213,41 @@ def padic_H_value(self, p, f, t, prec=None): t = QQ(t) if 0 in alpha: return self._swap.padic_H_value(p, f, ~t, prec) - gamma = self.gamma_array() - q = p**f + q = p ** f + if q * p > 2 ** 64: + return ValueError("p^(f+1) cannot exceed 2^64") - # m = {r: beta.count(QQ((r, q - 1))) for r in range(q - 1)} - m = array.array('i', [0] * (q - 1)) + m = array.array('i', [0]) * int(q - 1) for b in beta: u = b * (q - 1) - if u.is_integer(): - m[u] += 1 + if u.is_integer(): m[u] += 1 M = self.M_value() D = -min(self.zigzag(x, flip_beta=True) for x in alpha + beta) # also: D = (self.weight() + 1 - m[0]) // 2 if prec is None: - prec = (self.weight() * f) // 2 + ceil(log(self.degree(), p)) + 1 - # For some reason, working in Qp instead of Zp is much faster; - # it appears to avoid some costly conversions. - p_ring = Qp(p, prec=prec) - teich = p_ring.teichmuller(M / t) - - gauss_table = [None] * (q - 1) - for r in range(q - 1): - if gauss_table[r] is None: - gauss_table[r] = padic_gauss_sum(r, p, f, prec, factored=True, - algorithm='sage', parent=p_ring) - r1 = (r * p) % (q - 1) - while r1 != r: - gauss_table[r1] = gauss_table[r] - r1 = (r1 * p) % (q - 1) - - sigma = p_ring.zero() - u1 = p_ring.one() - for r in range(q - 1): - i = int(0) - u = u1 - u1 *= teich - for v, gv in gamma.items(): - r1 = (v * r) % (q - 1) - i += gauss_table[r1][0] * gv - u *= gauss_table[r1][1] ** gv - sigma += (-p)**(i // (p - 1)) * u << (f * (D + m[0] - m[r])) - resu = ZZ(-1) ** m[0] / (1 - q) * sigma + prec = ceil((self.weight() * f) / 2 + log(2*self.degree()+1, p)) + use_longs = (p ** prec < 2 ** 31) + + gamma = self._gamma_array + if cache_p: + try: + trcoeffs = self._trace_coeffs[(p, f)] + except (AttributeError, KeyError) as err: + if err.__class__ == AttributeError: + self._trace_coeffs = {} + gtab = self.gauss_table(p, f, prec) + trcoeffs = hgm_coeffs(p, f, prec, gamma, m, D, gtab, use_longs) + self._trace_coeffs[(p,f)] = trcoeffs + else: + gtab = gauss_table(p, f, prec, use_longs) + trcoeffs = hgm_coeffs(p, f, prec, gamma, m, D, gtab, use_longs) + sigma = trcoeffs[q-2] + p_ring = sigma.parent() + teich = p_ring.teichmuller(M/t) + for i in range(q-3, -1, -1): + sigma = sigma * teich + trcoeffs[i] + resu = ZZ(-1) ** m[0] * sigma / (1 - q) return IntegerModRing(p**prec)(resu).lift_centered() @cached_method @@ -1334,7 +1399,7 @@ def sign(self, t, p): return sign @cached_method - def euler_factor(self, t, p): + def euler_factor(self, t, p, cache_p=False): """ Return the Euler factor of the motive `H_t` at prime `p`. @@ -1395,6 +1460,14 @@ def euler_factor(self, t, p): 279841*T^4 - 25392*T^3 + 1242*T^2 - 48*T + 1, 707281*T^4 - 7569*T^3 + 696*T^2 - 9*T + 1] + This is an example of higher degree:: + + sage: H = Hyp(cyclotomic=([11], [7, 12])) + sage: H.euler_factor(2, 13) + 371293*T^10 - 85683*T^9 + 26364*T^8 + 1352*T^7 - 65*T^6 + 394*T^5 - 5*T^4 + 8*T^3 + 12*T^2 - 3*T + 1 + sage: H.euler_factor(2, 19) # long time + 2476099*T^10 - 651605*T^9 + 233206*T^8 - 77254*T^7 + 20349*T^6 - 4611*T^5 + 1071*T^4 - 214*T^3 + 34*T^2 - 5*T + 1 + TESTS:: sage: H1 = Hyp(alpha_beta=([1,1,1],[1/2,1/2,1/2])) @@ -1427,7 +1500,8 @@ def euler_factor(self, t, p): # now p is good d = self.degree() bound = d // 2 - traces = [self.padic_H_value(p, i + 1, t) for i in range(bound)] + traces = [self.padic_H_value(p, i + 1, t, cache_p=cache_p) + for i in range(bound)] w = self.weight() sign = self.sign(t, p) diff --git a/src/sage/rings/padics/misc.py b/src/sage/rings/padics/misc.py index def3b8d177d..b2ffd91f2f8 100644 --- a/src/sage/rings/padics/misc.py +++ b/src/sage/rings/padics/misc.py @@ -139,6 +139,7 @@ def gauss_sum(a, p, f, prec=20, factored=False, algorithm='pari', parent=None): s = sum(a.digits(base=p)) if factored: return(s, out) + X = PolynomialRing(R, name='X').gen() pi = R.ext(X**(p - 1) + p, names='pi').gen() out *= pi**s diff --git a/src/sage/rings/padics/padic_generic_element.pxd b/src/sage/rings/padics/padic_generic_element.pxd index 9166e3fcf2c..fe08b038568 100644 --- a/src/sage/rings/padics/padic_generic_element.pxd +++ b/src/sage/rings/padics/padic_generic_element.pxd @@ -6,6 +6,8 @@ from sage.rings.padics.pow_computer cimport PowComputer_class from sage.rings.integer cimport Integer from sage.rings.rational cimport Rational +cpdef gauss_table(long long p, int f, int prec, bint use_longs) + cdef class pAdicGenericElement(LocalGenericElement): cdef long valuation_c(self) cpdef val_unit(self) @@ -41,3 +43,4 @@ cdef class pAdicGenericElement(LocalGenericElement): cpdef _mod_(self, right) cpdef _floordiv_(self, right) cpdef bint _is_base_elt(self, p) except -1 + diff --git a/src/sage/rings/padics/padic_generic_element.pyx b/src/sage/rings/padics/padic_generic_element.pyx index 11968020ce8..d4b3061f017 100644 --- a/src/sage/rings/padics/padic_generic_element.pyx +++ b/src/sage/rings/padics/padic_generic_element.pyx @@ -42,7 +42,6 @@ from sage.structure.richcmp cimport rich_to_bool cdef long maxordp = (1L << (sizeof(long) * 8 - 2)) - 1 - cdef class pAdicGenericElement(LocalGenericElement): cpdef _richcmp_(left, right, int op): """ @@ -1230,7 +1229,7 @@ cdef class pAdicGenericElement(LocalGenericElement): INPUT: - - ``bd`` -- integer. Is a bound for precision, defaults to 20 + - ``bd`` -- integer. Precision bound, defaults to 20 - ``a`` -- integer. Offset parameter, defaults to 0 OUTPUT: @@ -1265,6 +1264,8 @@ cdef class pAdicGenericElement(LocalGenericElement): 4 + 4*5 + 4*5^2 + 4*5^3 + 2*5^4 + 4*5^5 + 5^7 + 3*5^9 + 4*5^10 + 3*5^11 + 5^13 + 4*5^14 + 2*5^15 + 2*5^16 + 2*5^17 + 3*5^18 + O(5^20) + TESTS: + This test was added in :trac:`24433`:: sage: F = Qp(7) @@ -1274,36 +1275,19 @@ cdef class pAdicGenericElement(LocalGenericElement): 6 + 4*7^19 + O(7^20) """ R = self.parent() - cdef int p = R.prime() - cdef int b = a - cdef int k + p = R.prime() - s = R.zero().add_bigoh(bd) - t = R.one().add_bigoh(bd) + # If p == 2, must work in Qp rather than Zp. + if p == 2 and not R.is_field(): + S = R.fraction_field() + return R(S(self).dwork_expansion(bd, a)) try: v = R.dwork_coeffs + if len(v) < p*bd: + raise AttributeError except AttributeError: - v = None - if v is not None and len(v) < p * bd: - v = None - if v is not None: - for k in range(bd): - s += t * v[p*k+b] - t *= (self + k) - else: - u = [t] - v = [] - for j in range(1, p): - u.append(u[j-1] / j) - for k in range(bd): - v += [x << k for x in u] - s += t * (u[a] << k) - t *= (self + k) - u[0] = ((u[-1] + u[0]) / (k+1)) >> 1 - for j in range(1, p): - u[j] = (u[j-1] + u[j]) / (j + (k+1) * p ) - R.dwork_coeffs = v - return -s + v = dwork_mahler_coeffs(R, bd) + return evaluate_dwork_mahler(v, self, p, bd, a) def gamma(self, algorithm='pari'): r""" @@ -1410,11 +1394,9 @@ cdef class pAdicGenericElement(LocalGenericElement): return parent(self.__pari__().gamma()) elif algorithm == 'sage': p = parent.prime() - bd = -((-n*p)//(p-1)) + bd = -((-n*p) // (p-1)) k = (-self) % p x = (self+k) >> 1 - if p==2 and n>=3: - x = x.lift_to_precision(n) return -x.dwork_expansion(bd, k.lift()) @coerce_binop @@ -4411,3 +4393,170 @@ def _compute_g(p, n, prec, terms): for i in range(n): g[i+1] = -(g[i]/(v-v**2)).integral() return [x.truncate(terms) for x in g] + +cpdef dwork_mahler_coeffs(R, int bd=20): + r""" + Compute Dwork's formula for Mahler coefficients of `p`-adic Gamma. + + This is called internally when one computes Gamma for a `p`-adic + integer. Normally there is no need to call it directly. + + INPUT: + + - ``R`` -- p-adic ring in which to compute + - ``bd`` -- integer. Number of terms in the expansion to use + + OUTPUT: + + A list of `p`-adic integers. + + EXAMPLES:: + + sage: from sage.rings.padics.padic_generic_element import dwork_mahler_coeffs, evaluate_dwork_mahler + sage: R = Zp(3) + sage: v = dwork_mahler_coeffs(R) + sage: x = R(1/7) + sage: evaluate_dwork_mahler(v, x, 3, 20, 1) + 2 + 2*3 + 3^2 + 3^3 + 3^4 + 3^5 + 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^11 + 2*3^12 + 3^13 + 3^14 + 2*3^16 + 3^17 + 3^19 + O(3^20) + sage: x.dwork_expansion(a=1) # Same result + 2 + 2*3 + 3^2 + 3^3 + 3^4 + 3^5 + 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^11 + 2*3^12 + 3^13 + 3^14 + 2*3^16 + 3^17 + 3^19 + O(3^20) + """ + from sage.rings.padics.factory import Qp + cdef int i + cdef long k, p + + v = [R.one()] + p = R.prime() + for k in range(1, p): + v.append(v[-1] / R(k)) + if bd > 1: + R1 = Qp(p, prec=bd) # Need divisions in this calculation + u = [R1(x) for x in v] + for i in range(1, bd): + u[0] = ((u[-1] + u[0]) / i) >> 1 + for j in range(1, p): + u[j] = (u[j-1] + u[j]) / (j + i * p) + for x in u: + v.append(R(x << i)) + return v + +cpdef evaluate_dwork_mahler(v, x, long long p, int bd, long long a): + """ + Evaluate Dwork's Mahler series for `p`-adic Gamma. + + EXAMPLES:: + + sage: from sage.rings.padics.padic_generic_element import dwork_mahler_coeffs, evaluate_dwork_mahler + sage: R = Zp(3) + sage: v = dwork_mahler_coeffs(R) + sage: x = R(1/7) + sage: evaluate_dwork_mahler(v, x, 3, 20, 1) + 2 + 2*3 + 3^2 + 3^3 + 3^4 + 3^5 + 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^11 + 2*3^12 + 3^13 + 3^14 + 2*3^16 + 3^17 + 3^19 + O(3^20) + sage: x.dwork_expansion(a=1) # Same result + 2 + 2*3 + 3^2 + 3^3 + 3^4 + 3^5 + 2*3^6 + 2*3^7 + 2*3^8 + 2*3^9 + 2*3^11 + 2*3^12 + 3^13 + 3^14 + 2*3^16 + 3^17 + 3^19 + O(3^20) + """ + cdef int k + bd -= 1 + a1 = a + bd*p + s = v[a1] + u = x + bd + w = x.parent().one() + for k in range(bd): + a1 -= p + u -= w + s = s*u + v[a1] + return -s + +cdef long long evaluate_dwork_mahler_long(v, long long x, long long p, int bd, + long long a, long long q): + cdef int k + cdef long long a1, s, u + bd -= 1 + a1 = a + bd*p + s = v[a1].lift() + u = x + bd + for k in range(bd): + a1 -= p + u -= 1 + s = (s*u + v[a1].lift()) % q + return -s + +cpdef gauss_table(long long p, int f, int prec, bint use_longs): + r""" + Compute a table of Gauss sums using the Gross-Koblitz formula. + + This is used in the computation of L-functions of hypergeometric motives. + The Gross-Koblitz formula is used as in `sage.rings.padics.misc.gauss_sum`, + but further unpacked for efficiency. + + INPUT: + + - `p` - prime + - `f`, `prec` - positive integers + - `use_longs` - boolean; if True, computations are done in C long + integers rather than Sage `p`-adics + + OUTPUT: + + A list of length `q-1=p^f-1`. The entries are `p`-adic units created with + absolute precision `prec`. + + EXAMPLES:: + + sage: from sage.rings.padics.padic_generic_element import gauss_table + sage: gauss_table(2,2,4,False) + [1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3] + sage: gauss_table(3,2,4,False)[3] + 2 + 3 + 2*3^2 + """ + from sage.rings.padics.factory import Zp, Qp + + cdef int i, j, bd + cdef long long q, q1, q3, r, r1, r2, s1, k + + R = Zp(p, prec, 'fixed-mod') + + if (f == 1 and prec == 1): # Shortcut for this key special case + ans = [-R.one()] + for r in range(1, p-1): + ans.append(ans[-1] * R(r)) + return ans + + q = p ** f + q1 = q - 1 + bd = (p*prec+p-2) // (p-1) - 1 + if p == 2: # Dwork expansion has denominators when p = 2 + R1 = Qp(p, prec) + else: + R1 = R + u = R1.one() + ans = [None for r in range(q1)] + ans[0] = -u + d = ~R1(q1) + if use_longs: + q3 = p ** prec + r2 = d.lift() % q3 + v = dwork_mahler_coeffs(R1, bd) + for r in range(1, q1): + if ans[r] is not None: continue + s = u + if use_longs: s1 = 1 + r1 = r + for j in range(1, f+1): + k = r1 % p + r1 = (r1 + k * q1) // p + if use_longs: # Use Dwork expansion to compute p-adic Gamma + s1 *= -evaluate_dwork_mahler_long(v, r1*r2, p, bd, k, q3) + s1 %= q3 + else: + s *= -evaluate_dwork_mahler(v, R1(r1)*d, p, bd, k) + if r1 == r: # End the loop. + if use_longs: s = R1(s1) + if j < f: s **= f // j + break + ans[r] = -s + for i in range(j-1): + r1 = r1 * p % q1 # Initially r1 == r + ans[r1] = ans[r] + if p != 2: return ans + return [R(x) for x in ans] From 4090795c4312daadcc8a19e13ba8149d6371b340 Mon Sep 17 00:00:00 2001 From: Kiran Kedlaya Date: Thu, 26 Dec 2019 18:09:17 -0800 Subject: [PATCH 021/133] Fix pyflakes issues in hypergeometric_motive.py --- src/sage/modular/hypergeometric_motive.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/sage/modular/hypergeometric_motive.py b/src/sage/modular/hypergeometric_motive.py index c0688319657..18ab51cf1f3 100644 --- a/src/sage/modular/hypergeometric_motive.py +++ b/src/sage/modular/hypergeometric_motive.py @@ -62,7 +62,6 @@ from collections import defaultdict from itertools import combinations import array -import sys from sage.arith.misc import divisors, gcd, euler_phi, moebius, is_prime from sage.arith.misc import gauss_sum, kronecker_symbol @@ -77,7 +76,6 @@ from sage.rings.fraction_field import FractionField from sage.rings.finite_rings.integer_mod_ring import IntegerModRing from sage.rings.integer_ring import ZZ -from sage.rings.padics.factory import Qp, Zp from sage.rings.padics.padic_generic_element import gauss_table from sage.rings.polynomial.polynomial_ring import polygen from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing From a8f085e51829e1d8ab25b62d69a354848d32bfd9 Mon Sep 17 00:00:00 2001 From: Kiran Kedlaya Date: Mon, 30 Dec 2019 09:54:58 -0800 Subject: [PATCH 022/133] Remove non-ASCII character from docstring --- src/sage/rings/padics/padic_generic_element.pyx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/rings/padics/padic_generic_element.pyx b/src/sage/rings/padics/padic_generic_element.pyx index d4b3061f017..03f737b1e3d 100644 --- a/src/sage/rings/padics/padic_generic_element.pyx +++ b/src/sage/rings/padics/padic_generic_element.pyx @@ -1420,7 +1420,7 @@ cdef class pAdicGenericElement(LocalGenericElement): 0 and 3 in the 3-adic ring `\ZZ_3`. The greatest common divisor of `O(3)` and `O(3)` could be (among others) 3 or 0 which have different valuation. The algorithm implemented here, will - return an element of minimal valuation among the possible greatest + return an element of minimal valuation among the possible greatest common divisors. EXAMPLES: From d70c8420027e08f9bf3cd372a42632d8603735c5 Mon Sep 17 00:00:00 2001 From: David Roe Date: Tue, 31 Dec 2019 03:50:27 -0500 Subject: [PATCH 023/133] Minor tweaks and change to long long* for dwork coeffs when using longs --- src/sage/modular/hypergeometric_motive.py | 22 +++--- src/sage/rings/padics/misc.py | 1 - .../rings/padics/padic_generic_element.pxd | 1 - .../rings/padics/padic_generic_element.pyx | 69 +++++++++++-------- 4 files changed, 50 insertions(+), 43 deletions(-) diff --git a/src/sage/modular/hypergeometric_motive.py b/src/sage/modular/hypergeometric_motive.py index 18ab51cf1f3..6c6b7049e44 100644 --- a/src/sage/modular/hypergeometric_motive.py +++ b/src/sage/modular/hypergeometric_motive.py @@ -396,7 +396,7 @@ def gamma_list_to_cyclotomic(galist): class HypergeometricData(object): _gauss_table = {} - + def __init__(self, cyclotomic=None, alpha_beta=None, gamma_list=None): r""" Creation of hypergeometric motives. @@ -468,6 +468,7 @@ def __init__(self, cyclotomic=None, alpha_beta=None, gamma_list=None): self._beta = tuple(beta) self._deg = deg self._gamma_array = cyclotomic_to_gamma(cyclo_up, cyclo_down) + self._trace_coeffs = {} up = QQ.prod(capital_M(d) for d in cyclo_up) down = QQ.prod(capital_M(d) for d in cyclo_down) self._M_value = up / down @@ -1096,13 +1097,11 @@ def gauss_table(self, p, f, prec): [1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3] """ try: - (prec1, gtab) = self._gauss_table[(p, f)] + prec1, gtab = self._gauss_table[p, f] if prec1 < prec: raise KeyError - except (AttributeError, KeyError) as err: - if err.__class__ == AttributeError: - self._gauss_table = {} + except KeyError: gtab = gauss_table(p, f, prec, False) - self._gauss_table[(p, f)] = (prec, gtab) + self._gauss_table[p, f] = (prec, gtab) return gtab def gauss_table_full(self): @@ -1152,8 +1151,7 @@ def padic_H_value(self, p, f, t, prec=None, cache_p=False): If `cache_p` is True, then the function caches an intermediate result which depends only on `p` and `f`. This leads to a significant - speedup when iterating over `t`. (When iterating also over the - hypergeometric data, one should also use :meth:`set_gauss_table`.) + speedup when iterating over `t`. INPUT: @@ -1230,13 +1228,11 @@ def padic_H_value(self, p, f, t, prec=None, cache_p=False): gamma = self._gamma_array if cache_p: try: - trcoeffs = self._trace_coeffs[(p, f)] - except (AttributeError, KeyError) as err: - if err.__class__ == AttributeError: - self._trace_coeffs = {} + trcoeffs = self._trace_coeffs[p, f] + except KeyError: gtab = self.gauss_table(p, f, prec) trcoeffs = hgm_coeffs(p, f, prec, gamma, m, D, gtab, use_longs) - self._trace_coeffs[(p,f)] = trcoeffs + self._trace_coeffs[p, f] = trcoeffs else: gtab = gauss_table(p, f, prec, use_longs) trcoeffs = hgm_coeffs(p, f, prec, gamma, m, D, gtab, use_longs) diff --git a/src/sage/rings/padics/misc.py b/src/sage/rings/padics/misc.py index b2ffd91f2f8..def3b8d177d 100644 --- a/src/sage/rings/padics/misc.py +++ b/src/sage/rings/padics/misc.py @@ -139,7 +139,6 @@ def gauss_sum(a, p, f, prec=20, factored=False, algorithm='pari', parent=None): s = sum(a.digits(base=p)) if factored: return(s, out) - X = PolynomialRing(R, name='X').gen() pi = R.ext(X**(p - 1) + p, names='pi').gen() out *= pi**s diff --git a/src/sage/rings/padics/padic_generic_element.pxd b/src/sage/rings/padics/padic_generic_element.pxd index fe08b038568..e9736dda081 100644 --- a/src/sage/rings/padics/padic_generic_element.pxd +++ b/src/sage/rings/padics/padic_generic_element.pxd @@ -43,4 +43,3 @@ cdef class pAdicGenericElement(LocalGenericElement): cpdef _mod_(self, right) cpdef _floordiv_(self, right) cpdef bint _is_base_elt(self, p) except -1 - diff --git a/src/sage/rings/padics/padic_generic_element.pyx b/src/sage/rings/padics/padic_generic_element.pyx index 03f737b1e3d..977a5bd804a 100644 --- a/src/sage/rings/padics/padic_generic_element.pyx +++ b/src/sage/rings/padics/padic_generic_element.pyx @@ -28,6 +28,7 @@ AUTHORS: #***************************************************************************** from sage.ext.stdsage cimport PY_NEW +from cysignals.memory cimport sig_malloc, sig_free cimport sage.rings.padics.local_generic_element from sage.libs.gmp.mpz cimport mpz_set_si @@ -4460,25 +4461,25 @@ cpdef evaluate_dwork_mahler(v, x, long long p, int bd, long long a): a1 = a + bd*p s = v[a1] u = x + bd - w = x.parent().one() + one = x.parent().one() for k in range(bd): a1 -= p - u -= w + u -= one s = s*u + v[a1] return -s -cdef long long evaluate_dwork_mahler_long(v, long long x, long long p, int bd, +cdef long long evaluate_dwork_mahler_long(long long *v, long long x, long long p, int bd, long long a, long long q): cdef int k cdef long long a1, s, u bd -= 1 a1 = a + bd*p - s = v[a1].lift() + s = v[a1] u = x + bd for k in range(bd): a1 -= p u -= 1 - s = (s*u + v[a1].lift()) % q + s = (s*u + v[a1]) % q return -s cpdef gauss_table(long long p, int f, int prec, bint use_longs): @@ -4493,7 +4494,7 @@ cpdef gauss_table(long long p, int f, int prec, bint use_longs): - `p` - prime - `f`, `prec` - positive integers - - `use_longs` - boolean; if True, computations are done in C long + - `use_longs` - boolean; if True, computations are done in C long integers rather than Sage `p`-adics OUTPUT: @@ -4510,9 +4511,10 @@ cpdef gauss_table(long long p, int f, int prec, bint use_longs): 2 + 3 + 2*3^2 """ from sage.rings.padics.factory import Zp, Qp - + cdef int i, j, bd cdef long long q, q1, q3, r, r1, r2, s1, k + cdef long long *vv R = Zp(p, prec, 'fixed-mod') @@ -4537,26 +4539,37 @@ cpdef gauss_table(long long p, int f, int prec, bint use_longs): q3 = p ** prec r2 = d.lift() % q3 v = dwork_mahler_coeffs(R1, bd) - for r in range(1, q1): - if ans[r] is not None: continue - s = u - if use_longs: s1 = 1 - r1 = r - for j in range(1, f+1): - k = r1 % p - r1 = (r1 + k * q1) // p - if use_longs: # Use Dwork expansion to compute p-adic Gamma - s1 *= -evaluate_dwork_mahler_long(v, r1*r2, p, bd, k, q3) - s1 %= q3 - else: - s *= -evaluate_dwork_mahler(v, R1(r1)*d, p, bd, k) - if r1 == r: # End the loop. - if use_longs: s = R1(s1) - if j < f: s **= f // j - break - ans[r] = -s - for i in range(j-1): - r1 = r1 * p % q1 # Initially r1 == r - ans[r1] = ans[r] + if use_longs: + vv = sig_malloc(sizeof(long long) * len(v)) + for i in range(len(v)): + vv[i] = v[i].lift() + try: + for r in range(1, q1): + if ans[r] is not None: + continue + s = u + if use_longs: s1 = 1 + r1 = r + for j in range(1, f+1): + k = r1 % p + r1 = (r1 + k * q1) // p + if use_longs: # Use Dwork expansion to compute p-adic Gamma + s1 *= -evaluate_dwork_mahler_long(vv, r1*r2, p, bd, k, q3) + s1 %= q3 + else: + s *= -evaluate_dwork_mahler(v, R1(r1)*d, p, bd, k) + if r1 == r: # End the loop. + if use_longs: + s = R1(s1) + if j < f: + s **= f // j + break + ans[r] = -s + for i in range(j-1): + r1 = r1 * p % q1 # Initially r1 == r + ans[r1] = ans[r] + finally: + if use_longs: + sig_free(vv) if p != 2: return ans return [R(x) for x in ans] From 0cb678864d998407a536a9cf04fab1b218aa0375 Mon Sep 17 00:00:00 2001 From: David Roe Date: Tue, 31 Dec 2019 04:24:44 -0500 Subject: [PATCH 024/133] Remove unnecessary import --- src/sage/modular/hypergeometric_misc.pyx | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/sage/modular/hypergeometric_misc.pyx b/src/sage/modular/hypergeometric_misc.pyx index cfb62caf716..35bc11929d9 100644 --- a/src/sage/modular/hypergeometric_misc.pyx +++ b/src/sage/modular/hypergeometric_misc.pyx @@ -3,8 +3,6 @@ Some utility routines for the hypergeometric motives package that benefit significantly from Cythonization. """ -from cpython cimport array - cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, gtable, bint use_longs): r""" From 62f9b7c0886fffaaf581005e1107068c2f159a60 Mon Sep 17 00:00:00 2001 From: Kiran Kedlaya Date: Tue, 31 Dec 2019 14:26:48 -0800 Subject: [PATCH 025/133] Pass arrays of long longs back and forth when possible --- src/sage/modular/hypergeometric_misc.pyx | 31 +++++-- .../rings/padics/padic_generic_element.pxd | 2 + .../rings/padics/padic_generic_element.pyx | 89 ++++++++++--------- 3 files changed, 71 insertions(+), 51 deletions(-) diff --git a/src/sage/modular/hypergeometric_misc.pyx b/src/sage/modular/hypergeometric_misc.pyx index 35bc11929d9..ed8ed18c0fb 100644 --- a/src/sage/modular/hypergeometric_misc.pyx +++ b/src/sage/modular/hypergeometric_misc.pyx @@ -25,6 +25,8 @@ cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, sage: hgm_coeffs(7, 1, 2, gamma, m, D, gtable, False) [7, 2*7, 6*7, 7, 6, 4*7] """ + from sage.rings.padics.factory import Zp + cdef int gl, j, k, l, v, gv cdef long long i, q1, w, w1, q2, r, r1 cdef bint flip @@ -34,17 +36,28 @@ cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, cdef array.array gamma_array1 = array.array('i', gamma.keys()) cdef array.array gamma_array2 = array.array('i', gamma.values()) cdef array.array r_array = array.array('i', [0]) * gl - cdef array.array digit_count = array.array('Q', [0]) * q1 + cdef array.array digit_count = array.array('q', [0]) * q1 cdef array.array gtab2 - R = gtable[0].parent() + try: + R = gtable[0].parent() + except AttributeError: + R = Zp(p, prec, "fixed-mod") + # In certain cases, the reciprocals of the Gauss sums are reported + # for efficiency. + flip = (f == 1 and prec == 1 and R.precision_cap() == 1) ans = [] if use_longs: q2 = p ** prec - gtab2 = array.array('Q', [0]) * q1 - for r in range(q1): gtab2[r] = gtable[r].lift() % q2 + try: + gtab2 = gtable + except TypeError: + gtab2 = array.array('q', [0]) * q1 + for r in range(q1): + gtab2[r] = gtable[r].lift() % q2 if f == 1: - for r in range(q1): digit_count[r] = r + for r in range(q1): + digit_count[r] = r else: for r in range(q1): r1 = r @@ -52,7 +65,7 @@ cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, for i in range(f): digit_count[r] += r1 % p r1 //= p - flip = (f == 1 and prec == 1 and R.precision_cap() == 1) + Rz = R.zero() for r in range(q1): # First determine whether this term is forced to be zero # for divisibility reasons. If so, skip the p-adic arithmetic. @@ -66,8 +79,9 @@ cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, i //= (p - 1) l = i + f * (D + m[0] - m[r]) if l >= prec: - ans.append(R.zero()) + ans.append(Rz) continue + # Keep numerator and denominator separate for efficiency. if use_longs: w = 1 w1 = 1 @@ -77,7 +91,8 @@ cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, for k in range(gl): gv = gamma_array2[k] r1 = r_array[k] - if (flip): gv = -gv + if flip: + gv = -gv if use_longs: if gv > 0: for j in range(gv): w = w * gtab2[r1] % q2 diff --git a/src/sage/rings/padics/padic_generic_element.pxd b/src/sage/rings/padics/padic_generic_element.pxd index e9736dda081..780aa4655bf 100644 --- a/src/sage/rings/padics/padic_generic_element.pxd +++ b/src/sage/rings/padics/padic_generic_element.pxd @@ -1,3 +1,5 @@ +from cpython cimport array + cimport sage.structure.element from sage.libs.gmp.types cimport mpz_t, mpq_t from sage.structure.element cimport Element, RingElement diff --git a/src/sage/rings/padics/padic_generic_element.pyx b/src/sage/rings/padics/padic_generic_element.pyx index 977a5bd804a..b3b31618a0c 100644 --- a/src/sage/rings/padics/padic_generic_element.pyx +++ b/src/sage/rings/padics/padic_generic_element.pyx @@ -4468,7 +4468,7 @@ cpdef evaluate_dwork_mahler(v, x, long long p, int bd, long long a): s = s*u + v[a1] return -s -cdef long long evaluate_dwork_mahler_long(long long *v, long long x, long long p, int bd, +cdef long long evaluate_dwork_mahler_long(array.array v, long long x, long long p, int bd, long long a, long long q): cdef int k cdef long long a1, s, u @@ -4494,8 +4494,9 @@ cpdef gauss_table(long long p, int f, int prec, bint use_longs): - `p` - prime - `f`, `prec` - positive integers - - `use_longs` - boolean; if True, computations are done in C long - integers rather than Sage `p`-adics + - `use_longs` - boolean; if True, computations are done in C long long + integers rather than Sage `p`-adics, and the results are returned + as a Python array rather than a list. OUTPUT: @@ -4510,66 +4511,68 @@ cpdef gauss_table(long long p, int f, int prec, bint use_longs): sage: gauss_table(3,2,4,False)[3] 2 + 3 + 2*3^2 """ + from sage.arith.misc import power_mod from sage.rings.padics.factory import Zp, Qp cdef int i, j, bd cdef long long q, q1, q3, r, r1, r2, s1, k - cdef long long *vv - - R = Zp(p, prec, 'fixed-mod') + cdef array.array vv, ans1 if (f == 1 and prec == 1): # Shortcut for this key special case - ans = [-R.one()] + ans1 = array.array('q', [0]) * p + ans1[0] = p-1 for r in range(1, p-1): - ans.append(ans[-1] * R(r)) - return ans + ans1[r] = ans1[r-1] * r % p + return ans1 q = p ** f q1 = q - 1 bd = (p*prec+p-2) // (p-1) - 1 + R = Zp(p, prec, 'fixed-mod') if p == 2: # Dwork expansion has denominators when p = 2 R1 = Qp(p, prec) else: R1 = R - u = R1.one() - ans = [None for r in range(q1)] - ans[0] = -u d = ~R1(q1) + v = dwork_mahler_coeffs(R1, bd) if use_longs: q3 = p ** prec r2 = d.lift() % q3 - v = dwork_mahler_coeffs(R1, bd) - if use_longs: - vv = sig_malloc(sizeof(long long) * len(v)) - for i in range(len(v)): - vv[i] = v[i].lift() - try: - for r in range(1, q1): - if ans[r] is not None: - continue + vv = array.array('q', [0]) * len(v) + for k in range(len(v)): + vv[k] = v[k].lift() % q3 + ans1 = array.array('q', [0]) * q1 + ans1[0] = -1 + ans = ans1 + else: + u = R1.one() + ans = [0 for r in range(q1)] + ans[0] = -u + for r in range(1, q1): + if ans[r]: continue + if use_longs: + s1 = 1 + else: s = u - if use_longs: s1 = 1 - r1 = r - for j in range(1, f+1): - k = r1 % p - r1 = (r1 + k * q1) // p - if use_longs: # Use Dwork expansion to compute p-adic Gamma - s1 *= -evaluate_dwork_mahler_long(vv, r1*r2, p, bd, k, q3) - s1 %= q3 - else: - s *= -evaluate_dwork_mahler(v, R1(r1)*d, p, bd, k) - if r1 == r: # End the loop. - if use_longs: - s = R1(s1) - if j < f: - s **= f // j - break - ans[r] = -s - for i in range(j-1): - r1 = r1 * p % q1 # Initially r1 == r - ans[r1] = ans[r] - finally: + r1 = r + for j in range(1, f+1): + k = r1 % p + r1 = (r1 + k * q1) // p + if use_longs: # Use Dwork expansion to compute p-adic Gamma + s1 *= -evaluate_dwork_mahler_long(vv, r1*r2, p, bd, k, q3) + s1 %= q3 + else: + s *= -evaluate_dwork_mahler(v, R1(r1)*d, p, bd, k) + if r1 == r: + break if use_longs: - sig_free(vv) + if j < f: s1 = power_mod(s1, f // j, q3) + ans1[r] = -s1 + else: + if j < f: s **= f // j + ans[r] = -s + for i in range(j-1): + r1 = r1 * p % q1 # Initially r1 == r + ans[r1] = ans[r] if p != 2: return ans return [R(x) for x in ans] From bbaa0f7684fcc9f4998d6034e88a45511c24ce73 Mon Sep 17 00:00:00 2001 From: Kiran Kedlaya Date: Tue, 31 Dec 2019 18:02:07 -0800 Subject: [PATCH 026/133] Fix overflow in Gauss sums; use longs when cacheing --- src/sage/modular/hypergeometric_motive.py | 13 +++++++++++-- src/sage/rings/padics/padic_generic_element.pyx | 14 +++++++++----- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/sage/modular/hypergeometric_motive.py b/src/sage/modular/hypergeometric_motive.py index 6c6b7049e44..6a44dcb8571 100644 --- a/src/sage/modular/hypergeometric_motive.py +++ b/src/sage/modular/hypergeometric_motive.py @@ -1100,7 +1100,8 @@ def gauss_table(self, p, f, prec): prec1, gtab = self._gauss_table[p, f] if prec1 < prec: raise KeyError except KeyError: - gtab = gauss_table(p, f, prec, False) + use_longs = (p ** prec < 2 ** 31) + gtab = gauss_table(p, f, prec, use_longs) self._gauss_table[p, f] = (prec, gtab) return gtab @@ -1123,7 +1124,7 @@ def gauss_table_full(self): sage: H.euler_factor(2, 7, cache_p=True) 7*T^2 - 3*T + 1 sage: H.gauss_table_full()[(7, 1)] - (2, [6 + 6*7, 6 + 2*7, 3 + 3*7, 1, 2, 6 + 3*7]) + (2, array('q', [-1, -29, -25, -48, -47, -22])) Clearing cached values:: @@ -1191,6 +1192,8 @@ def padic_H_value(self, p, f, t, prec=None, cache_p=False): sage: H.padic_H_value(13,1,1/t) 0 + TESTS: + Check issue from :trac:`28404`:: sage: H1 = Hyp(cyclotomic=([1,1,1],[6,2])) @@ -1200,6 +1203,12 @@ def padic_H_value(self, p, f, t, prec=None, cache_p=False): sage: [H2.padic_H_value(5,1,i) for i in range(2,5)] [-4, 1, -4] + Check for potential overflow:: + + sage: H = Hyp(cyclotomic=[[10,6],[5,4]]) + sage: H.padic_H_value(101, 2, 2) + -1560629 + REFERENCES: - [MagmaHGM]_ diff --git a/src/sage/rings/padics/padic_generic_element.pyx b/src/sage/rings/padics/padic_generic_element.pyx index b3b31618a0c..41852f9c6bd 100644 --- a/src/sage/rings/padics/padic_generic_element.pyx +++ b/src/sage/rings/padics/padic_generic_element.pyx @@ -4511,11 +4511,10 @@ cpdef gauss_table(long long p, int f, int prec, bint use_longs): sage: gauss_table(3,2,4,False)[3] 2 + 3 + 2*3^2 """ - from sage.arith.misc import power_mod from sage.rings.padics.factory import Zp, Qp cdef int i, j, bd - cdef long long q, q1, q3, r, r1, r2, s1, k + cdef long long q, q1, q3, r, r1, r2, s1, s2, k cdef array.array vv, ans1 if (f == 1 and prec == 1): # Shortcut for this key special case @@ -4531,6 +4530,7 @@ cpdef gauss_table(long long p, int f, int prec, bint use_longs): R = Zp(p, prec, 'fixed-mod') if p == 2: # Dwork expansion has denominators when p = 2 R1 = Qp(p, prec) + use_longs = False else: R1 = R d = ~R1(q1) @@ -4559,17 +4559,21 @@ cpdef gauss_table(long long p, int f, int prec, bint use_longs): k = r1 % p r1 = (r1 + k * q1) // p if use_longs: # Use Dwork expansion to compute p-adic Gamma - s1 *= -evaluate_dwork_mahler_long(vv, r1*r2, p, bd, k, q3) + s1 *= -evaluate_dwork_mahler_long(vv, r1*r2%q3, p, bd, k, q3) s1 %= q3 else: s *= -evaluate_dwork_mahler(v, R1(r1)*d, p, bd, k) if r1 == r: break if use_longs: - if j < f: s1 = power_mod(s1, f // j, q3) + if j < f: + s2 = s1 + for i in range(f//j-1): + s1 = s1 * s2 % q3 ans1[r] = -s1 else: - if j < f: s **= f // j + if j < f: + s **= f // j ans[r] = -s for i in range(j-1): r1 = r1 * p % q1 # Initially r1 == r From c1aa950114146fb0de0648359ea8784d324467de Mon Sep 17 00:00:00 2001 From: Kiran Kedlaya Date: Tue, 31 Dec 2019 19:10:19 -0800 Subject: [PATCH 027/133] Pass table precision manually to hgm_coeffs --- src/sage/modular/hypergeometric_misc.pxd | 2 +- src/sage/modular/hypergeometric_misc.pyx | 6 +++--- src/sage/modular/hypergeometric_motive.py | 20 +++++++++++++++----- 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/sage/modular/hypergeometric_misc.pxd b/src/sage/modular/hypergeometric_misc.pxd index f3ef421fd11..b601a29db24 100644 --- a/src/sage/modular/hypergeometric_misc.pxd +++ b/src/sage/modular/hypergeometric_misc.pxd @@ -1,4 +1,4 @@ from cpython cimport array cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, - gtable, bint use_longs) + gtable, int gtable_prec, bint use_longs) diff --git a/src/sage/modular/hypergeometric_misc.pyx b/src/sage/modular/hypergeometric_misc.pyx index ed8ed18c0fb..d59602dd33d 100644 --- a/src/sage/modular/hypergeometric_misc.pyx +++ b/src/sage/modular/hypergeometric_misc.pyx @@ -4,7 +4,7 @@ significantly from Cythonization. """ cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, - gtable, bint use_longs): + gtable, int gtable_prec, bint use_longs): r""" Compute coefficients for the hypergeometric trace formula. @@ -22,7 +22,7 @@ cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, sage: gtable = H.gauss_table(7, 1, 2) sage: m = array.array('i', [0]*6) sage: D = 1 - sage: hgm_coeffs(7, 1, 2, gamma, m, D, gtable, False) + sage: hgm_coeffs(7, 1, 2, gamma, m, D, gtable, 1, False) [7, 2*7, 6*7, 7, 6, 4*7] """ from sage.rings.padics.factory import Zp @@ -45,7 +45,7 @@ cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, R = Zp(p, prec, "fixed-mod") # In certain cases, the reciprocals of the Gauss sums are reported # for efficiency. - flip = (f == 1 and prec == 1 and R.precision_cap() == 1) + flip = (f == 1 and prec == 1 and gtable_prec == 1) ans = [] if use_longs: q2 = p ** prec diff --git a/src/sage/modular/hypergeometric_motive.py b/src/sage/modular/hypergeometric_motive.py index 6a44dcb8571..0a774041530 100644 --- a/src/sage/modular/hypergeometric_motive.py +++ b/src/sage/modular/hypergeometric_motive.py @@ -1094,7 +1094,7 @@ def gauss_table(self, p, f, prec): sage: from sage.modular.hypergeometric_motive import HypergeometricData as Hyp sage: H = Hyp(cyclotomic=([3],[4])) sage: H.gauss_table(2, 2, 4) - [1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3] + (4, [1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3, 1 + 2 + 2^2 + 2^3]) """ try: prec1, gtab = self._gauss_table[p, f] @@ -1103,7 +1103,8 @@ def gauss_table(self, p, f, prec): use_longs = (p ** prec < 2 ** 31) gtab = gauss_table(p, f, prec, use_longs) self._gauss_table[p, f] = (prec, gtab) - return gtab + prec1 = prec + return prec1, gtab def gauss_table_full(self): """ @@ -1239,12 +1240,12 @@ def padic_H_value(self, p, f, t, prec=None, cache_p=False): try: trcoeffs = self._trace_coeffs[p, f] except KeyError: - gtab = self.gauss_table(p, f, prec) - trcoeffs = hgm_coeffs(p, f, prec, gamma, m, D, gtab, use_longs) + gtab_prec, gtab = self.gauss_table(p, f, prec) + trcoeffs = hgm_coeffs(p, f, prec, gamma, m, D, gtab, gtab_prec, use_longs) self._trace_coeffs[p, f] = trcoeffs else: gtab = gauss_table(p, f, prec, use_longs) - trcoeffs = hgm_coeffs(p, f, prec, gamma, m, D, gtab, use_longs) + trcoeffs = hgm_coeffs(p, f, prec, gamma, m, D, gtab, prec, use_longs) sigma = trcoeffs[q-2] p_ring = sigma.parent() teich = p_ring.teichmuller(M/t) @@ -1483,6 +1484,15 @@ def euler_factor(self, t, p, cache_p=False): sage: H.euler_factor(5,7) 16807*T^5 - 686*T^4 - 105*T^3 - 15*T^2 - 2*T + 1 + Check for precision downsampling:: + + sage: H = Hyp(cyclotomic=[[3],[4]]) + sage: H.euler_factor(2, 11, cache_p=True) + 11*T^2 - 3*T + 1 + sage: H = Hyp(cyclotomic=[[12],[1,2,6]]) + sage: H.euler_factor(2, 11, cache_p=True) + -T^4 + T^3 - T + 1 + REFERENCES: - [Roberts2015]_ From 77273ff4e7ebd8b100c6526046ad60bd40a03925 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Wed, 1 Jan 2020 09:25:23 +0100 Subject: [PATCH 028/133] small cleanup of contour plot file --- src/sage/plot/contour_plot.py | 107 +++++++++++++++++++--------------- 1 file changed, 61 insertions(+), 46 deletions(-) diff --git a/src/sage/plot/contour_plot.py b/src/sage/plot/contour_plot.py index efc1f2b2ee9..a7533fa3d94 100644 --- a/src/sage/plot/contour_plot.py +++ b/src/sage/plot/contour_plot.py @@ -1,8 +1,7 @@ """ Contour Plots """ - -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2006 Alex Clemesha , # William Stein , # 2008 Mike Hansen , @@ -16,19 +15,20 @@ # # The full text of the GPL is available at: # -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** +import operator from sage.plot.primitive import GraphicPrimitive from sage.misc.decorators import options, suboptions from sage.plot.colors import rgbcolor, get_cmap from sage.arith.srange import xsrange -import operator class ContourPlot(GraphicPrimitive): """ - Primitive class for the contour plot graphics type. See - ``contour_plot?`` for help actually doing contour plots. + Primitive class for the contour plot graphics type. + + See ``contour_plot?`` for help actually doing contour plots. INPUT: @@ -63,7 +63,7 @@ class ContourPlot(GraphicPrimitive): """ def __init__(self, xy_data_array, xrange, yrange, options): """ - Initializes base class ContourPlot. + Initialize base class ``ContourPlot``. EXAMPLES:: @@ -84,7 +84,7 @@ def __init__(self, xy_data_array, xrange, yrange, options): def get_minmax_data(self): """ - Returns a dictionary with the bounding box data. + Return a dictionary with the bounding box data. EXAMPLES:: @@ -140,7 +140,8 @@ def _repr_(self): sage: c = C[0]; c ContourPlot defined by a 100 x 100 data grid """ - return "ContourPlot defined by a %s x %s data grid"%(self.xy_array_row, self.xy_array_col) + msg = "ContourPlot defined by a %s x %s data grid" + return msg % (self.xy_array_row, self.xy_array_col) def _render_on_subplot(self, subplot): """ @@ -163,10 +164,11 @@ def _render_on_subplot(self, subplot): cmap = get_cmap('gray') else: if isinstance(contours, (int, Integer)): - cmap = get_cmap([(i,i,i) for i in xsrange(0,1,1/contours)]) + cmap = get_cmap([(i, i, i) + for i in xsrange(0, 1, 1 / contours)]) else: - l = Integer(len(contours)) - cmap = get_cmap([(i,i,i) for i in xsrange(0,1,1/l)]) + step = 1 / Integer(len(contours)) + cmap = get_cmap([(i, i, i) for i in xsrange(0, 1, step)]) x0, x1 = float(self.xrange[0]), float(self.xrange[1]) y0, y1 = float(self.yrange[0]), float(self.yrange[1]) @@ -192,7 +194,8 @@ def _render_on_subplot(self, subplot): from sage.plot.misc import get_matplotlib_linestyle linestyles = options.get('linestyles', None) if isinstance(linestyles, (list, tuple)): - linestyles = [get_matplotlib_linestyle(i, 'long') for i in linestyles] + linestyles = [get_matplotlib_linestyle(i, 'long') + for i in linestyles] else: linestyles = get_matplotlib_linestyle(linestyles, 'long') if contours is None: @@ -827,11 +830,13 @@ def f(x,y): return cos(x) + sin(y) region = options.pop('region') ev = [f] if region is None else [f, region] - F, ranges = setup_for_eval_on_grid(ev, [xrange, yrange], options['plot_points']) + F, ranges = setup_for_eval_on_grid(ev, [xrange, yrange], + options['plot_points']) g = F[0] xrange, yrange = [r[:2] for r in ranges] - xy_data_array = [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] + xy_data_array = [[g(x, y) for x in xsrange(*ranges[0], + include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] if region is not None: @@ -857,10 +862,11 @@ def f(x,y): return cos(x) + sin(y) scale = options.get('scale', None) if isinstance(scale, (list, tuple)): scale = scale[0] - if scale == 'semilogy' or scale == 'semilogx': + if scale in ('semilogy', 'semilogx'): options['aspect_ratio'] = 'automatic' - g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) + g._set_extra_kwds(Graphics._extract_kwds_for_show(options, + ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, options)) return g @@ -949,7 +955,7 @@ def implicit_plot(f, xrange, yrange, **options): g = implicit_plot(x**2 + y**2 - 2, (x,-3,3), (y,-3,3)) sphinx_plot(g) - We can do the same thing, but using a callable function so we don't + We can do the same thing, but using a callable function so we do not need to explicitly define the variables in the ranges. We also fill the inside:: @@ -1179,17 +1185,19 @@ def f(x,y): from sage.symbolic.expression import is_SymbolicEquation if is_SymbolicEquation(f): if f.operator() != operator.eq: - raise ValueError("input to implicit plot must be function or equation") + raise ValueError("input to implicit plot must be function " + "or equation") f = f.lhs() - f.rhs() linewidths = options.pop('linewidth', None) linestyles = options.pop('linestyle', None) if 'color' in options and 'rgbcolor' in options: raise ValueError('only one of color or rgbcolor should be specified') - elif 'color' in options: - options['cmap']=[options.pop('color', None)] + + if 'color' in options: + options['cmap'] = [options.pop('color', None)] elif 'rgbcolor' in options: - options['cmap']=[rgbcolor(options.pop('rgbcolor', None))] + options['cmap'] = [rgbcolor(options.pop('rgbcolor', None))] if options['fill'] is True: options.pop('fill') @@ -1202,11 +1210,10 @@ def f(x,y): borderwidth=linewidths, borderstyle=linestyles, incol=incol, bordercol=bordercol, **options) - else: - return region_plot(f < 0, xrange, yrange, borderwidth=linewidths, - borderstyle=linestyles, - incol=incol, bordercol=bordercol, - **options) + return region_plot(f < 0, xrange, yrange, borderwidth=linewidths, + borderstyle=linestyles, + incol=incol, bordercol=bordercol, + **options) elif options['fill'] is False: options.pop('fillcolor', None) return contour_plot(f, xrange, yrange, linewidths=linewidths, @@ -1349,7 +1356,7 @@ def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, g = region_plot([x**2 + y**2 < 1, x < y], (x,-2,2), (y,-2,2)) sphinx_plot(g) - Since it doesn't look very good, let's increase ``plot_points``:: + Since it does not look very good, let us increase ``plot_points``:: sage: region_plot([x^2 + y^2 < 1, x< y], (x,-2,2), (y,-2,2), plot_points=400) Graphics object consisting of 1 graphics primitive @@ -1486,12 +1493,15 @@ def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, if not isinstance(f, (list, tuple)): f = [f] - feqs = [equify(g) for g in f if is_Expression(g) and g.operator() is operator.eq and not equify(g).is_zero()] - f = [equify(g) for g in f if not (is_Expression(g) and g.operator() is operator.eq)] + feqs = [equify(g) for g in f + if is_Expression(g) and g.operator() is operator.eq + and not equify(g).is_zero()] + f = [equify(g) for g in f + if not (is_Expression(g) and g.operator() is operator.eq)] neqs = len(feqs) if neqs > 1: - warn("There are at least 2 equations; " + - "If the region is degenerated to points, " + + warn("There are at least 2 equations; " + "If the region is degenerated to points, " "plotting might show nothing.") feqs = [sum([fn**2 for fn in feqs])] neqs = 1 @@ -1506,8 +1516,11 @@ def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, plot_points) xrange, yrange = [r[:2] for r in ranges] - xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] - for y in xsrange(*ranges[1], include_endpoint=True)] + xy_data_arrays = numpy.asarray([[[func(x, y) + for x in xsrange(*ranges[0], + include_endpoint=True)] + for y in xsrange(*ranges[1], + include_endpoint=True)] for func in f_all[neqs::]], dtype=float) xy_data_array = numpy.abs(xy_data_arrays.prod(axis=0)) # Now we need to set entries to negative iff all @@ -1534,10 +1547,11 @@ def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, scale = options.get('scale', None) if isinstance(scale, (list, tuple)): scale = scale[0] - if scale == 'semilogy' or scale == 'semilogx': + if scale in ('semilogy', 'semilogx'): options['aspect_ratio'] = 'automatic' - g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) + g._set_extra_kwds(Graphics._extract_kwds_for_show(options, + ignore=['xmin', 'xmax'])) if neqs == 0: g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, @@ -1545,11 +1559,14 @@ def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, cmap=cmap, fill=True, **options))) else: - mask = numpy.asarray([[elt > 0 for elt in rows] for rows in xy_data_array], + mask = numpy.asarray([[elt > 0 for elt in rows] + for rows in xy_data_array], dtype=bool) xy_data_array = numpy.asarray([[f_all[0](x, y) - for x in xsrange(*ranges[0], include_endpoint=True)] - for y in xsrange(*ranges[1], include_endpoint=True)], + for x in xsrange(*ranges[0], + include_endpoint=True)] + for y in xsrange(*ranges[1], + include_endpoint=True)], dtype=float) xy_data_array[mask] = None if bordercol or borderstyle or borderwidth: @@ -1567,8 +1584,8 @@ def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, def equify(f): """ - Returns the equation rewritten as a symbolic function to give - negative values when True, positive when False. + Return the equation rewritten as a symbolic function to give + negative values when ``True``, positive when ``False``. EXAMPLES:: @@ -1583,13 +1600,12 @@ def equify(f): -x*y + 1 sage: equify(y > 0) -y - sage: f=equify(lambda x, y: x > y) + sage: f = equify(lambda x, y: x > y) sage: f(1, 2) 1 sage: f(2, 1) -1 """ - import operator from sage.calculus.all import symbolic_expression from sage.symbolic.expression import is_Expression if not is_Expression(f): @@ -1598,5 +1614,4 @@ def equify(f): op = f.operator() if op is operator.gt or op is operator.ge: return symbolic_expression(f.rhs() - f.lhs()) - else: - return symbolic_expression(f.lhs() - f.rhs()) + return symbolic_expression(f.lhs() - f.rhs()) From b2504856da3fc526892a2231c22304c7cdfd008f Mon Sep 17 00:00:00 2001 From: Markus Wageringel Date: Wed, 1 Jan 2020 12:48:45 +0100 Subject: [PATCH 029/133] 28932: fix QuadraticField when embedding=False --- src/sage/rings/number_field/number_field.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/sage/rings/number_field/number_field.py b/src/sage/rings/number_field/number_field.py index f2996456448..71471c998f0 100644 --- a/src/sage/rings/number_field/number_field.py +++ b/src/sage/rings/number_field/number_field.py @@ -932,6 +932,11 @@ def QuadraticField(D, name='a', check=True, embedding=True, latex_name='sqrt', * False sage: QuadraticField(-11, 'a') is QuadraticField(-11, 'a', latex_name=None) False + + Check quadratic fields without embedding (:trac:`28932`):: + + sage: QuadraticField(3, embedding=False) + Number Field in a with defining polynomial x^2 - 3 """ D = QQ(D) if check: @@ -944,6 +949,8 @@ def QuadraticField(D, name='a', check=True, embedding=True, latex_name='sqrt', * embedding = RLF(D).sqrt() else: embedding = CLF(D).sqrt() + elif embedding is False: + embedding = None if latex_name == 'sqrt': latex_name = r'\sqrt{%s}' % D return NumberField(f, name, check=False, embedding=embedding, latex_name=latex_name, **args) From ee4ef236a0caf93a3068778ceaeaba0fc7fb8931 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Wed, 1 Jan 2020 19:33:36 +0100 Subject: [PATCH 030/133] remove old stuff (about python 2.4) --- build/sage_bootstrap/compat/argparse.py | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/build/sage_bootstrap/compat/argparse.py b/build/sage_bootstrap/compat/argparse.py index 2e537741d09..e3ddc96dc15 100644 --- a/build/sage_bootstrap/compat/argparse.py +++ b/build/sage_bootstrap/compat/argparse.py @@ -96,28 +96,12 @@ from gettext import gettext as _ -try: - set -except NameError: - # for python < 2.4 compatibility (sets module is there since 2.3): - from sets import Set as set try: basestring except NameError: basestring = str -try: - sorted -except NameError: - # for python < 2.4 compatibility: - def sorted(iterable, reverse=False): - result = list(iterable) - result.sort() - if reverse: - result.reverse() - return result - def _callable(obj): return hasattr(obj, '__call__') or hasattr(obj, '__bases__') From de82d2e0390faaf250fc06723e33c60a8ab2a444 Mon Sep 17 00:00:00 2001 From: Kiran Kedlaya Date: Wed, 1 Jan 2020 10:53:57 -0800 Subject: [PATCH 031/133] Fix doctest in hypergeometric_misc --- src/sage/modular/hypergeometric_misc.pyx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/modular/hypergeometric_misc.pyx b/src/sage/modular/hypergeometric_misc.pyx index d59602dd33d..b4129c7b142 100644 --- a/src/sage/modular/hypergeometric_misc.pyx +++ b/src/sage/modular/hypergeometric_misc.pyx @@ -19,10 +19,10 @@ cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, sage: H.euler_factor(2, 7, cache_p=True) 7*T^2 - 3*T + 1 sage: gamma = H.gamma_array() - sage: gtable = H.gauss_table(7, 1, 2) + sage: prec, gtable = H.gauss_table(7, 1, 2) sage: m = array.array('i', [0]*6) sage: D = 1 - sage: hgm_coeffs(7, 1, 2, gamma, m, D, gtable, 1, False) + sage: hgm_coeffs(7, 1, 2, gamma, m, D, gtable, prec, False) [7, 2*7, 6*7, 7, 6, 4*7] """ from sage.rings.padics.factory import Zp From 3197d5dbb60a7e9561a5bbeb5e43114ee4029aaf Mon Sep 17 00:00:00 2001 From: Dave Witte Morris Date: Wed, 1 Jan 2020 15:39:31 -0700 Subject: [PATCH 032/133] minor edits --- src/doc/en/reference/references/index.rst | 1 + src/sage/dynamics/complex_dynamics/mandel_julia.py | 9 ++++----- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/doc/en/reference/references/index.rst b/src/doc/en/reference/references/index.rst index 2e55f4211f1..527c6880299 100644 --- a/src/doc/en/reference/references/index.rst +++ b/src/doc/en/reference/references/index.rst @@ -3534,6 +3534,7 @@ REFERENCES: .. [LS1994] Eike Lau and Dierk Schleicher. *Internal addresses in the Mandelbrot set and irreducibility of polynomials*. Stony Brook Preprint #19 (1994). + https://www.math.stonybrook.edu/theses/thesis94-2/part1.pdf .. [LS2007] Thomas Lam and Mark Shimozono. *Dual graded graphs for Kac-Moody algebras*. Algebra & Number Theory 1.4 (2007) diff --git a/src/sage/dynamics/complex_dynamics/mandel_julia.py b/src/sage/dynamics/complex_dynamics/mandel_julia.py index 26caf88495a..0f68f8c599a 100644 --- a/src/sage/dynamics/complex_dynamics/mandel_julia.py +++ b/src/sage/dynamics/complex_dynamics/mandel_julia.py @@ -436,7 +436,7 @@ def kneading_sequence(theta): r""" Determines the kneading sequence for an angle theta in RR/ZZ which is periodic under doubling. We use the definition for the kneading - sequence given in [LS1994]_. + sequence given in Definition 3.2 of [LS1994]_. INPUT: @@ -469,7 +469,7 @@ def kneading_sequence(theta): sage: kneading_sequence(1.2) '110*' - + Since rationals with even denominator are not periodic under doubling, we have not implemented kneading sequences for such rationals:: sage: kneading_sequence(1/4) @@ -498,7 +498,6 @@ def kneading_sequence(theta): else: not_done = False y = 2*y - floor(2*y) - L = len(KS) KS_str = ''.join(KS) + '*' return KS_str @@ -662,11 +661,11 @@ def julia_plot(f=None, **kwds): max_iteration = kwds.pop("max_iteration", 500) pixel_count = kwds.pop("pixel_count", 500) base_color = kwds.pop("base_color", 'steelblue') - level_sep= kwds.pop("level_sep", 1) + level_sep = kwds.pop("level_sep", 1) number_of_colors = kwds.pop("number_of_colors", 30) interacts = kwds.pop("interact", False) - f_is_default_after_all=None + f_is_default_after_all = None if period: # pick a random c with the specified period R = PolynomialRing(CC, 'c') From 9f9d6aec105e05c40ab26050e7f35bc4ba4baf63 Mon Sep 17 00:00:00 2001 From: Dave Witte Morris Date: Thu, 2 Jan 2020 19:00:36 -0700 Subject: [PATCH 033/133] fixed pyflakes error --- src/sage/dynamics/complex_dynamics/mandel_julia.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/sage/dynamics/complex_dynamics/mandel_julia.py b/src/sage/dynamics/complex_dynamics/mandel_julia.py index 0f68f8c599a..6f730830c90 100644 --- a/src/sage/dynamics/complex_dynamics/mandel_julia.py +++ b/src/sage/dynamics/complex_dynamics/mandel_julia.py @@ -42,7 +42,6 @@ polynomial_mandelbrot, julia_helper) -from sage.dynamics.arithmetic_dynamics.generic_ds import DynamicalSystem from sage.plot.colors import Color from sage.repl.image import Image from sage.functions.log import logb From a7bfd25cbbbc799536da393188fe7094fe6d5d89 Mon Sep 17 00:00:00 2001 From: Kiran Kedlaya Date: Sat, 4 Jan 2020 09:20:48 -0800 Subject: [PATCH 034/133] Use Py2-compatible arrays --- src/sage/modular/hypergeometric_misc.pyx | 14 +++++++------- src/sage/modular/hypergeometric_motive.py | 6 +++--- src/sage/rings/padics/padic_generic_element.pyx | 12 +++++++----- 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/src/sage/modular/hypergeometric_misc.pyx b/src/sage/modular/hypergeometric_misc.pyx index b4129c7b142..df44371d263 100644 --- a/src/sage/modular/hypergeometric_misc.pyx +++ b/src/sage/modular/hypergeometric_misc.pyx @@ -2,7 +2,6 @@ Some utility routines for the hypergeometric motives package that benefit significantly from Cythonization. """ - cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, gtable, int gtable_prec, bint use_longs): r""" @@ -28,7 +27,7 @@ cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, from sage.rings.padics.factory import Zp cdef int gl, j, k, l, v, gv - cdef long long i, q1, w, w1, q2, r, r1 + cdef long long i, q1, w, w1, w2, q2, r, r1 cdef bint flip q1 = p ** f - 1 @@ -36,7 +35,7 @@ cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, cdef array.array gamma_array1 = array.array('i', gamma.keys()) cdef array.array gamma_array2 = array.array('i', gamma.values()) cdef array.array r_array = array.array('i', [0]) * gl - cdef array.array digit_count = array.array('q', [0]) * q1 + cdef array.array digit_count = array.array('i', [0]) * q1 cdef array.array gtab2 try: @@ -52,7 +51,7 @@ cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, try: gtab2 = gtable except TypeError: - gtab2 = array.array('q', [0]) * q1 + gtab2 = array.array('l', [0]) * q1 for r in range(q1): gtab2[r] = gtable[r].lift() % q2 if f == 1: @@ -94,10 +93,11 @@ cpdef hgm_coeffs(long long p, int f, int prec, gamma, array.array m, int D, if flip: gv = -gv if use_longs: - if gv > 0: - for j in range(gv): w = w * gtab2[r1] % q2 + w2 = gtab2[r1] # cast to long long to avoid overflow + if gv > 0: + for j in range(gv): w = w * w2 % q2 else: - for j in range(-gv): w1 = w1 * gtab2[r1] % q2 + for j in range(-gv): w1 = w1 * w2 % q2 else: if gv > 0: for j in range(gv): u *= gtable[r1] diff --git a/src/sage/modular/hypergeometric_motive.py b/src/sage/modular/hypergeometric_motive.py index 0a774041530..645c3a3542e 100644 --- a/src/sage/modular/hypergeometric_motive.py +++ b/src/sage/modular/hypergeometric_motive.py @@ -1125,7 +1125,7 @@ def gauss_table_full(self): sage: H.euler_factor(2, 7, cache_p=True) 7*T^2 - 3*T + 1 sage: H.gauss_table_full()[(7, 1)] - (2, array('q', [-1, -29, -25, -48, -47, -22])) + (2, array('l', [-1, -29, -25, -48, -47, -22])) Clearing cached values:: @@ -1220,8 +1220,8 @@ def padic_H_value(self, p, f, t, prec=None, cache_p=False): if 0 in alpha: return self._swap.padic_H_value(p, f, ~t, prec) q = p ** f - if q * p > 2 ** 64: - return ValueError("p^(f+1) cannot exceed 2^64") + if q > 2 ** 31: + return ValueError("p^f cannot exceed 2^31") m = array.array('i', [0]) * int(q - 1) for b in beta: diff --git a/src/sage/rings/padics/padic_generic_element.pyx b/src/sage/rings/padics/padic_generic_element.pyx index 41852f9c6bd..655c60f5f46 100644 --- a/src/sage/rings/padics/padic_generic_element.pyx +++ b/src/sage/rings/padics/padic_generic_element.pyx @@ -4479,7 +4479,8 @@ cdef long long evaluate_dwork_mahler_long(array.array v, long long x, long long for k in range(bd): a1 -= p u -= 1 - s = (s*u + v[a1]) % q + s = s*u + v[a1] # force cast to long long + s = s % q return -s cpdef gauss_table(long long p, int f, int prec, bint use_longs): @@ -4518,10 +4519,11 @@ cpdef gauss_table(long long p, int f, int prec, bint use_longs): cdef array.array vv, ans1 if (f == 1 and prec == 1): # Shortcut for this key special case - ans1 = array.array('q', [0]) * p + ans1 = array.array('l', [0]) * p ans1[0] = p-1 for r in range(1, p-1): - ans1[r] = ans1[r-1] * r % p + k = ans1[r-1] + ans1[r] = k * r % p return ans1 q = p ** f @@ -4538,10 +4540,10 @@ cpdef gauss_table(long long p, int f, int prec, bint use_longs): if use_longs: q3 = p ** prec r2 = d.lift() % q3 - vv = array.array('q', [0]) * len(v) + vv = array.array('l', [0]) * len(v) for k in range(len(v)): vv[k] = v[k].lift() % q3 - ans1 = array.array('q', [0]) * q1 + ans1 = array.array('l', [0]) * q1 ans1[0] = -1 ans = ans1 else: From 635df5f6b1b5fad7ad57bb66e9b160455dc3cf72 Mon Sep 17 00:00:00 2001 From: Simon Brandhorst Date: Sat, 4 Jan 2020 21:52:14 +0100 Subject: [PATCH 035/133] maximal_overlattices first version --- ...free_quadratic_module_integer_symmetric.py | 115 ++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/src/sage/modules/free_quadratic_module_integer_symmetric.py b/src/sage/modules/free_quadratic_module_integer_symmetric.py index 469d7be6747..ee213c7391c 100644 --- a/src/sage/modules/free_quadratic_module_integer_symmetric.py +++ b/src/sage/modules/free_quadratic_module_integer_symmetric.py @@ -1004,6 +1004,121 @@ def overlattice(self, gens): inner_product_matrix=self.inner_product_matrix(), already_echelonized=False) + def maximal_overlattice(self, p=None): + r""" + Return a maximal even integral overlattice of this lattice. + + The lattice must be even. + + INPUT: + + - ``p`` -- (default:``None``) if given return an overlattice + `M` of this lattice `L` that is maximal at `p` and the + completions `M_q = L_q` are equal for all primes `q \neq p`. + + EXAMPLES:: + + sage: L = IntegralLattice("A4").twist(25*89) + sage: L.maximal_overlattice().determinant() + 5 + sage: L.maximal_overlattice(89).determinant().factor() + 5^9 + sage: L.maximal_overlattice(5).determinant().factor() + 5 * 89^4 + + """ + # this code is somewhat slow but it works + # it might speed up things to use the algorithms given in + # https://arxiv.org/abs/1208.2481 + # and trac:11940 + if not self.is_even(): + raise ValueError("This lattice must be even to admit an even overlattice") + from sage.rings.all import GF + L = self + if p is None: + P = ZZ(self.determinant()).prime_factors() + else: + P = ZZ(p).prime_factors() + # even case + if 2 in P: + # create an isotropic subspace by rescaling + # the generators + D = L.discriminant_group(2) + for b in D.gens(): + e = b.additive_order() + v = e.valuation(2) + delta = (q*e).lift().valuation(2) % 2 + b = 2**((e.valuation(2)/2).ceil() + delta)*b.lift() + isotropic.append(b) + L = L.overlattice(isotropic) + D = L.discriminant_group() + # now L is of exponent at most 4. + if D.cardinality() > 512: + D = D.normal_form(partial=True) + isotropic = [] + # extract an isotropic space spanned by + # a subset of the generators of D + i = 0 + while i < len(D.gens()): + t = D.gens()[i] + if t.q() == 0 and all([t.b(g)==0 for g in isotropic]): + isotropic.append(t) + i += 1 + isotropic = [g.lift() for g in isotropic] + L = L.overlattice(isotropic) + D = L.discriminant_group(2) + # clean up whatever is left by brute force + while D.cardinality().valuation(2) > 1: + for t in D: + if t != 0 and t.q()==0: + break + if t.q()!=0: + # no isotropic vector left + break + L = L.overlattice([t.lift()]) + D = L.discriminant_group(2) + # odd case + for p in P: + if p == 2: + continue + # go squarefree + D = L.discriminant_group(p).normal_form() + isotropic = [p**(-b.q().lift().valuation(p)/2).ceil()*b.lift() for b in D.gens()] + L = L.overlattice(isotropic) + # now the p-discriminant_group is a vector space + while True: + d = L.discriminant_group(p).gram_matrix_bilinear().det() + v = -d.valuation(p) + u = d.numerator() + if v<=1 or (v == 2 and ZZ(-1).kronecker(p) != u.kronecker(p)): + # the lattice is already maximal at p + break + # diagonalize the gram matrix + D = L.discriminant_group(p).normal_form(partial=True) + gen = D.gens() + G = D.gram_matrix_quadratic().diagonal() + k = GF(p) + a = k(G[0].numerator()); b = k(G[1].numerator()); + if (-b/a).is_square(): + # solve: a*x^2 + b *y^2 = 0 + x = (-b/a).sqrt() + y = 1 + t = ZZ(x)*gen[0] + ZZ(y)*gen[1] + else: + # or solve a*x^2 + b*y^2 + c = 0 + # we know the rank is at least 3 + c = k(G[2].numerator()) + # brute force to find a suitable y + # very fast + for y in GF(p): + x = ((-c - b*y**2)/a) + if x.is_square(): + x = x.sqrt() + break + t = ZZ(x)*gen[0] + ZZ(y)*gen[1] + ZZ(1)*gen[2] + L = L.overlattice([t.lift()]) + return L + def orthogonal_group(self, gens=None, is_finite=None): """ Return the orthogonal group of this lattice as a matrix group. From c13d0dfac866432917db43fbf34505defccd42ae Mon Sep 17 00:00:00 2001 From: Simon Brandhorst Date: Sat, 4 Jan 2020 23:55:04 +0100 Subject: [PATCH 036/133] fixes and a test for maximal_overlattice --- .../free_quadratic_module_integer_symmetric.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/sage/modules/free_quadratic_module_integer_symmetric.py b/src/sage/modules/free_quadratic_module_integer_symmetric.py index ee213c7391c..2562a1fee10 100644 --- a/src/sage/modules/free_quadratic_module_integer_symmetric.py +++ b/src/sage/modules/free_quadratic_module_integer_symmetric.py @@ -1008,14 +1008,14 @@ def maximal_overlattice(self, p=None): r""" Return a maximal even integral overlattice of this lattice. - The lattice must be even. - INPUT: - ``p`` -- (default:``None``) if given return an overlattice `M` of this lattice `L` that is maximal at `p` and the completions `M_q = L_q` are equal for all primes `q \neq p`. + If `p` is `2` or ``None``, then the lattice must be even. + EXAMPLES:: sage: L = IntegralLattice("A4").twist(25*89) @@ -1026,12 +1026,18 @@ def maximal_overlattice(self, p=None): sage: L.maximal_overlattice(5).determinant().factor() 5 * 89^4 + TESTS:: + + sage: L = IntegralLattice(matrix.diagonal([2,4,4,8])) + sage: L.maximal_overlattice().is_even() + True + """ # this code is somewhat slow but it works # it might speed up things to use the algorithms given in # https://arxiv.org/abs/1208.2481 # and trac:11940 - if not self.is_even(): + if not self.is_even() and (p is None or p==2): raise ValueError("This lattice must be even to admit an even overlattice") from sage.rings.all import GF L = self @@ -1044,10 +1050,12 @@ def maximal_overlattice(self, p=None): # create an isotropic subspace by rescaling # the generators D = L.discriminant_group(2) + isotropic = [] for b in D.gens(): e = b.additive_order() v = e.valuation(2) - delta = (q*e).lift().valuation(2) % 2 + q = b.q().lift() + delta = (q*e) % 2 b = 2**((e.valuation(2)/2).ceil() + delta)*b.lift() isotropic.append(b) L = L.overlattice(isotropic) From 3226bc5d5a3d917d7d682ec06f4ff08c49cfbb16 Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Sun, 5 Jan 2020 00:02:35 +0100 Subject: [PATCH 037/133] Trac #28921: Trivial one check --- src/sage/manifolds/differentiable/mixed_form.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/manifolds/differentiable/mixed_form.py b/src/sage/manifolds/differentiable/mixed_form.py index 103224d102d..4fabf3111ed 100644 --- a/src/sage/manifolds/differentiable/mixed_form.py +++ b/src/sage/manifolds/differentiable/mixed_form.py @@ -899,7 +899,7 @@ def _lmul_(self, other): # Simple checks: if other.is_trivial_zero(): return self.parent().zero() - elif other.is_one(): + elif (other - 1).is_trivial_zero(): return self resu = self._new_instance() resu[:] = [other * form for form in self._comp] From f78d436a6741bad72e8524f5796e84432a644051 Mon Sep 17 00:00:00 2001 From: Simon Brandhorst Date: Sun, 5 Jan 2020 13:15:55 +0100 Subject: [PATCH 038/133] rational representative first version --- src/sage/quadratic_forms/genera/genus.py | 44 ++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/sage/quadratic_forms/genera/genus.py b/src/sage/quadratic_forms/genera/genus.py index bce8d99640e..98690adf1fe 100644 --- a/src/sage/quadratic_forms/genera/genus.py +++ b/src/sage/quadratic_forms/genera/genus.py @@ -2242,6 +2242,7 @@ def dimension(self): return p + n dim = dimension + rank = dimension def discriminant_form(self): r""" @@ -2276,6 +2277,49 @@ def discriminant_form(self): q = matrix.block_diagonal(qL) return TorsionQuadraticForm(q) + def rational_representative(self): + r""" + Return a representative of the rational + bilinear form defined by this genus. + + OUTPUT: + + A diagonal_matrix. + + EXAMPLES:: + + sage: from sage.quadratic_forms.genera.genus import genera + sage: G = genera((8,0),1)[0] + sage: G + Genus of + None + Signature: (8, 0) + Genus symbol at 2: 1^8 + sage: G.rational_representative() + [1 0 0 0 0 0 0 0] + [0 1 0 0 0 0 0 0] + [0 0 1 0 0 0 0 0] + [0 0 0 1 0 0 0 0] + [0 0 0 0 1 0 0 0] + [0 0 0 0 0 2 0 0] + [0 0 0 0 0 0 1 0] + [0 0 0 0 0 0 0 2] + """ + from sage.quadratic_forms.all import QuadraticForm, quadratic_form_from_invariants + sminus = self.signature_pair_of_matrix()[1] + det = self.determinant() + m = self.rank() + P = [] + for sym in self._local_symbols: + p = sym._prime + # it is important to use the definition of Cassels here! + if QuadraticForm(QQ,2*sym.gram_matrix()).hasse_invariant(p) == -1: + P.append(p) + q = quadratic_form_from_invariants(F=QQ, rk=m, det=det, + P=P, sminus=sminus) + return q.Hessian_matrix()/2 + + def local_symbols(self): r""" Return a copy of the list of local symbols of this symbol. From 6861bce2b5cc1ef32d6a99b8742e02fce165b8a5 Mon Sep 17 00:00:00 2001 From: Simon Brandhorst Date: Sun, 5 Jan 2020 20:22:04 +0100 Subject: [PATCH 039/133] fixed 28955 quadratic_form_from_invariants --- src/sage/quadratic_forms/quadratic_form.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/sage/quadratic_forms/quadratic_form.py b/src/sage/quadratic_forms/quadratic_form.py index 64738e9eea0..1b8544e7c3a 100644 --- a/src/sage/quadratic_forms/quadratic_form.py +++ b/src/sage/quadratic_forms/quadratic_form.py @@ -117,6 +117,16 @@ def quadratic_form_from_invariants(F, rk, det, P, sminus): [ * -3 ] sage: all(q.hasse_invariant(p)==-1 for p in P) True + + TESTS: + + This shows that :trac:`28955` is fixed:: + + sage: quadratic_form_from_invariants(QQ,3,2,[2],2) + Quadratic form in 3 variables over Rational Field with coefficients: + [ -1 0 0 ] + [ * 1 0 ] + [ * * -2 ] """ from sage.arith.misc import hilbert_symbol # normalize input @@ -162,9 +172,9 @@ def quadratic_form_from_invariants(F, rk, det, P, sminus): S += [-1] a = QQ.hilbert_symbol_negative_at_S(S,-d) a = ZZ(a) - P = [p for p in P if hilbert_symbol(a, -d, p) == 1] - P += [p for p in (2*a*d).prime_divisors() - if hilbert_symbol(a, -d, p)==-1 and p not in P] + P = ([p for p in P if hilbert_symbol(a, -d, p) == 1] + +[p for p in (2*a*d).prime_divisors() + if hilbert_symbol(a, -d, p)==-1 and p not in P]) sminus = max(0, sminus-1) rk = rk - 1 d = a*d From d0356c4023aa22d380df624efc5388fbaeea017c Mon Sep 17 00:00:00 2001 From: Simon Brandhorst Date: Sun, 5 Jan 2020 20:29:44 +0100 Subject: [PATCH 040/133] raise the correct error --- src/sage/quadratic_forms/quadratic_form.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/sage/quadratic_forms/quadratic_form.py b/src/sage/quadratic_forms/quadratic_form.py index 1b8544e7c3a..58050ee2e1c 100644 --- a/src/sage/quadratic_forms/quadratic_form.py +++ b/src/sage/quadratic_forms/quadratic_form.py @@ -127,6 +127,11 @@ def quadratic_form_from_invariants(F, rk, det, P, sminus): [ -1 0 0 ] [ * 1 0 ] [ * * -2 ] + + sage: quadratic_form_from_invariants(QQ,4,2,[2],4) + Traceback (most recent call last): + ... + ValueError: invariants do not define a rational quadratic form """ from sage.arith.misc import hilbert_symbol # normalize input @@ -145,7 +150,10 @@ def quadratic_form_from_invariants(F, rk, det, P, sminus): for p in P: if QQ(-d).is_padic_square(p): raise ValueError("invariants do not define a rational quadratic form") - if sminus % 4 in (2, 3) and len(P) % 2 == 0: + f = 0 + if sminus % 4 in (2, 3): + f = 1 + if (f + len(P)) % 2 == 1: raise ValueError("invariants do not define a rational quadratic form") D = [] while rk >= 2: From d58c91ad17254853e2850876e629a962f2325624 Mon Sep 17 00:00:00 2001 From: Simon Brandhorst Date: Sun, 5 Jan 2020 20:59:57 +0100 Subject: [PATCH 041/133] genus representative initial version --- ...free_quadratic_module_integer_symmetric.py | 70 ++++++++++++++ src/sage/quadratic_forms/genera/genus.py | 95 +++++++++++++++++++ 2 files changed, 165 insertions(+) diff --git a/src/sage/modules/free_quadratic_module_integer_symmetric.py b/src/sage/modules/free_quadratic_module_integer_symmetric.py index 2562a1fee10..549bafb2be0 100644 --- a/src/sage/modules/free_quadratic_module_integer_symmetric.py +++ b/src/sage/modules/free_quadratic_module_integer_symmetric.py @@ -1417,3 +1417,73 @@ def twist(self, s, discard_basis=False): inner_product_matrix = s * self.inner_product_matrix() ambient = FreeQuadraticModule(self.base_ring(), n, inner_product_matrix) return FreeQuadraticModule_integer_symmetric(ambient=ambient, basis=self.basis(), inner_product_matrix=inner_product_matrix) + +def local_modification(M, G, p, check=True): + r""" + Return a local modification of `M` that matches `G` at `p`. + + INPUT: + + - ``M`` -- a `\ZZ_p`-maximal lattice + + - ``G`` -- the gram matrix of a lattice + isomorphic to `M` over `\QQ_p` + + - ``p`` -- a prime number + + OUTPUT: + + an integral lattice `M'` in the ambient space of `M` such that `M` and `M'` are locally equal at all + completions except at `p` where `M'` is locally equivalent to the lattice with gram matrix `G` + + EXAMPLES:: + + sage: from sage.modules.free_quadratic_module_integer_symmetric import local_modification + sage: L = IntegralLattice("A3").twist(15) + sage: M = L.maximal_overlattice() + sage: for p in prime_divisors(L.determinant()): + ....: M = local_modification(M, L.gram_matrix(), p) + sage: M.genus() == L.genus() + True + sage: L = IntegralLattice("D4").twist(3*4) + sage: M = L.maximal_overlattice() + sage: local_modification(M, L.gram_matrix(), 2) + Lattice of degree 4 and rank 4 over Integer Ring + Basis matrix: + [1/3 0 1/3 2/3] + [ 0 1/3 1/3 2/3] + [ 0 0 1 0] + [ 0 0 0 1] + Inner product matrix: + [ 24 -12 0 0] + [-12 24 -12 -12] + [ 0 -12 24 0] + [ 0 -12 0 24] + """ + from sage.quadratic_forms.genera.normal_form import p_adic_normal_form + from sage.quadratic_forms.genera.genus import Genus_Symbol_p_adic_ring,p_adic_symbol + + # notation + d = G.inverse().denominator() + n = M.rank() + scale = d.valuation(p) + d = p**scale + + L = IntegralLattice(G) + L_max = L.maximal_overlattice(p=p) + + # invert the gerstein operations + _, U = p_adic_normal_form(L_max.gram_matrix(), p, precision=scale+3) + B = (~L_max.basis_matrix()).change_ring(ZZ)*~U.change_ring(ZZ) + + _, UM = p_adic_normal_form(M.gram_matrix(), p, precision=scale+3) + B = B * UM.change_ring(ZZ) * M.basis_matrix() + + # the local modification + S = M.sublattice(((M.span(B) & M) + d * M).gens()) + # confirm result + if check: + s1 = Genus_Symbol_p_adic_ring(p, p_adic_symbol(S.gram_matrix(), p, scale)) + s2 = Genus_Symbol_p_adic_ring(p, p_adic_symbol(G, p, scale)) + assert s1 == s2, "oops" + return S diff --git a/src/sage/quadratic_forms/genera/genus.py b/src/sage/quadratic_forms/genera/genus.py index 98690adf1fe..69ce8f9dcfa 100644 --- a/src/sage/quadratic_forms/genera/genus.py +++ b/src/sage/quadratic_forms/genera/genus.py @@ -26,6 +26,8 @@ from sage.rings.integer_ring import IntegerRing, ZZ from sage.rings.rational_field import RationalField, QQ from sage.rings.integer import Integer +from sage.interfaces.gp import gp +from sage.libs.pari import pari from sage.rings.finite_rings.finite_field_constructor import FiniteField from copy import copy, deepcopy from sage.misc.misc import verbose @@ -2319,6 +2321,99 @@ def rational_representative(self): P=P, sminus=sminus) return q.Hessian_matrix()/2 + def _compute_representative(self, LLL=True): + r""" + Compute a representative of this genus and cache it. + + INPUT: + + - ``LLL`` -- boolean (default: ``True``); whether or not to LLL reduce the result + + TESTS:: + + sage: from sage.quadratic_forms.genera.genus import genera + sage: for det in range(1,5): + ....: G = genera((3,0), det, even=False) + ....: assert all(g==Genus(g.representative()) for g in G) + sage: for det in range(1,5): + ....: G = genera((1,2), det, even=False) + ....: assert all(g==Genus(g.representative()) for g in G) + sage: for det in range(1,20): # long time (about 40s, 2020) + ....: G = genera((3,0), det, even=False) # long time + ....: assert all(g==Genus(g.representative()) for g in G) # long time + sage: for det in range(1,20): # long time + ....: G = genera((2,2), det, even=False) # long time + ....: assert all(g==Genus(g.representative()) for g in G) # long time + """ + from sage.modules.free_quadratic_module_integer_symmetric import IntegralLattice, local_modification + even = self.is_even() + q = self.rational_representative() + n = q.nrows() + # the associated quadratic form xGx.T/2 should be integral + L = IntegralLattice(4*q).maximal_overlattice() + p = 2 + sym2 = self.local_symbols()[0] + if not self.is_even(): + # the quadratic form of xGx.T/2 must be integral + # for things to work + # solve this by multiplying the basis by 2 + L = local_modification(L, 4*sym2.gram_matrix(), p) + L = L.overlattice(L.basis_matrix()/2) + else: + L = local_modification(L, sym2.gram_matrix(), p) + for sym in self._local_symbols[1:]: + p = sym.prime() + L = local_modification(L, sym.gram_matrix(), p) + L = L.gram_matrix().change_ring(ZZ) + if LLL: + sig = self.signature_pair_of_matrix() + if sig[0]*sig[1] != 0: + from sage.env import SAGE_EXTCODE + m = pari(L) + gp.read(SAGE_EXTCODE + "/pari/simon/qfsolve.gp") + m = gp.eval('qflllgram_indefgoon(%s)'%m) + # convert the output string to sage + L = pari(m).sage()[0] + elif sig[1] != 0: + U = -(-L).LLL_gram() + L = U.T * L * U + else: + U = L.LLL_gram() + L = U.T * L * U + # confirm the computation + assert Genus(L) == self + L.set_immutable() + self._representative = L + + def representative(self): + r""" + Return a representative in this genus. + + EXAMPLES:: + + sage: from sage.quadratic_forms.genera.genus import genera + sage: g = genera([1,3],24)[0] + sage: g + Genus of + None + Signature: (1, 3) + Genus symbol at 2: [1^-1 2^3]_0 + Genus symbol at 3: 1^3 3^1 + + A representative of ``g`` is not known yet. + Let us trigger its computation: + + sage: g.representative() + [ 0 0 0 2] + [ 0 -1 0 0] + [ 0 0 -6 0] + [ 2 0 0 0] + sage: g == Genus(g.representative()) + True + """ + if self._representative is None: + self._compute_representative() + return self._representative def local_symbols(self): r""" From cf3048b1c7b89c7833c4a851107fc3f1651b34fa Mon Sep 17 00:00:00 2001 From: Simon Brandhorst Date: Sun, 5 Jan 2020 21:01:23 +0100 Subject: [PATCH 042/133] author added --- src/sage/quadratic_forms/genera/genus.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/sage/quadratic_forms/genera/genus.py b/src/sage/quadratic_forms/genera/genus.py index 69ce8f9dcfa..660a7dbc6cd 100644 --- a/src/sage/quadratic_forms/genera/genus.py +++ b/src/sage/quadratic_forms/genera/genus.py @@ -7,6 +7,7 @@ - David Kohel & Gabriele Nebe (2007): First created - Simon Brandhorst (2018): various bugfixes and printing - Simon Brandhorst (2018): enumeration of genera +- Simon Brandhorst (2020): genus representative """ # **************************************************************************** # Copyright (C) 2007 David Kohel From 6b64d6823de85fbc44032c8660cce3373e2f00ef Mon Sep 17 00:00:00 2001 From: Dima Pasechnik Date: Mon, 6 Jan 2020 09:09:11 +0100 Subject: [PATCH 043/133] correct AC_CHECK/PATH_PROG call, refactor --- build/pkgs/bzip2/spkg-configure.m4 | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/build/pkgs/bzip2/spkg-configure.m4 b/build/pkgs/bzip2/spkg-configure.m4 index 5a210179a00..29bb93e642a 100644 --- a/build/pkgs/bzip2/spkg-configure.m4 +++ b/build/pkgs/bzip2/spkg-configure.m4 @@ -1,5 +1,7 @@ SAGE_SPKG_CONFIGURE([bzip2], [ - AC_CHECK_HEADER(bzlib.h, [], [sage_spkg_install_bzip2=yes]) - AC_SEARCH_LIBS([BZ2_bzCompress], [bz2], [], [sage_spkg_install_bzip2=yes]) - AC_CHECK_PROG(bzip2, [break], [sage_spkg_install_bzip2=yes]) + AC_CHECK_HEADER(bzlib.h, [ + AC_SEARCH_LIBS([BZ2_bzCompress], [bz2], [ + AC_PATH_PROG([bzip2prog], [bzip2], [sage_spkg_install_bzip2=yes]) + ], [sage_spkg_install_bzip2=yes]) + ], [sage_spkg_install_bzip2=yes]) ]) From dc5b909ab4f9fa2c0e5e7b5fff0747b5d92a0508 Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Mon, 6 Jan 2020 13:02:15 +0100 Subject: [PATCH 044/133] Trac #28916: Any iteration --- src/sage/manifolds/differentiable/mixed_form_algebra.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/sage/manifolds/differentiable/mixed_form_algebra.py b/src/sage/manifolds/differentiable/mixed_form_algebra.py index ab95c014bab..32a31b22432 100644 --- a/src/sage/manifolds/differentiable/mixed_form_algebra.py +++ b/src/sage/manifolds/differentiable/mixed_form_algebra.py @@ -289,12 +289,9 @@ def _coerce_map_from_(self, S): # Each degree is coercible so there must be a coerce map: return True # Let us check for each degree consecutively: - for deg in self.irange(): - if self._domain.diff_form_module(deg, - self._dest_map).has_coerce_map_from(S): - return True - # Nothing found... - return False + return any(self._domain.diff_form_module(deg, + self._dest_map).has_coerce_map_from(S) + for deg in self.irange()) @cached_method def zero(self): From e2e07c4aab94ebb160ed1fd8d3159395ccc51e81 Mon Sep 17 00:00:00 2001 From: Travis Scrimshaw Date: Tue, 7 Jan 2020 03:55:16 +1000 Subject: [PATCH 045/133] Better class hierarchy for classical matrix Lie algebras. --- .../lie_algebras/classical_lie_algebra.py | 66 ++++++------------- src/sage/algebras/lie_algebras/lie_algebra.py | 34 +++++++++- 2 files changed, 52 insertions(+), 48 deletions(-) diff --git a/src/sage/algebras/lie_algebras/classical_lie_algebra.py b/src/sage/algebras/lie_algebras/classical_lie_algebra.py index 10a9e647abb..1f803d2557a 100644 --- a/src/sage/algebras/lie_algebras/classical_lie_algebra.py +++ b/src/sage/algebras/lie_algebras/classical_lie_algebra.py @@ -33,7 +33,7 @@ from sage.categories.lie_algebras import LieAlgebras from sage.categories.triangular_kac_moody_algebras import TriangularKacMoodyAlgebras -from sage.algebras.lie_algebras.lie_algebra import LieAlgebraFromAssociative, FinitelyGeneratedLieAlgebra +from sage.algebras.lie_algebras.lie_algebra import MatrixLieAlgebraFromAssociative, FinitelyGeneratedLieAlgebra from sage.algebras.lie_algebras.structure_coefficients import LieAlgebraWithStructureCoefficients from sage.combinat.root_system.cartan_type import CartanType from sage.combinat.root_system.cartan_matrix import CartanMatrix @@ -43,7 +43,7 @@ from sage.modules.free_module import FreeModule -class ClassicalMatrixLieAlgebra(LieAlgebraFromAssociative): +class ClassicalMatrixLieAlgebra(MatrixLieAlgebraFromAssociative): """ A classical Lie algebra represented using matrices. @@ -122,6 +122,13 @@ def __init__(self, R, ct, e, f, h): sage: sl2 = lie_algebras.sl(QQ, 2, 'matrix') sage: isinstance(sl2.indices(), FiniteEnumeratedSet) True + + Check that elements are hashable (see :trac:`28961`):: + + sage: sl2 = lie_algebras.sl(QQ, 2, 'matrix') + sage: e,f,h = list(sl2.basis()) + sage: len(set([e, e+f])) + 2 """ n = len(e) names = ['e%s'%i for i in range(1, n+1)] @@ -130,11 +137,11 @@ def __init__(self, R, ct, e, f, h): category = LieAlgebras(R).FiniteDimensional().WithBasis() from sage.sets.finite_enumerated_set import FiniteEnumeratedSet index_set = FiniteEnumeratedSet(names) - LieAlgebraFromAssociative.__init__(self, e[0].parent(), - gens=tuple(e + f + h), - names=tuple(names), - index_set=index_set, - category=category) + MatrixLieAlgebraFromAssociative.__init__(self, e[0].parent(), + gens=tuple(e + f + h), + names=tuple(names), + index_set=index_set, + category=category) self._cartan_type = ct gens = tuple(self.gens()) @@ -331,43 +338,8 @@ def affine(self, kac_moody=False): from sage.algebras.lie_algebras.affine_lie_algebra import AffineLieAlgebra return AffineLieAlgebra(self, kac_moody) - class Element(LieAlgebraFromAssociative.Element): - def matrix(self): - r""" - Return ``self`` as element of the underlying matrix algebra. - - OUTPUT: - - An instance of the element class of MatrixSpace. - - EXAMPLES:: - - sage: sl3m = lie_algebras.sl(ZZ, 3, representation='matrix') - sage: e1,e2, f1, f2, h1, h2 = sl3m.gens() - sage: h1m = h1.matrix(); h1m - [ 1 0 0] - [ 0 -1 0] - [ 0 0 0] - sage: h1m.parent() - Full MatrixSpace of 3 by 3 sparse matrices over Integer Ring - sage: matrix(h2) - [ 0 0 0] - [ 0 1 0] - [ 0 0 -1] - sage: L = lie_algebras.so(QQ['z'], 5, representation='matrix') - sage: matrix(L.an_element()) - [ 1 1 0 0 0] - [ 1 1 0 0 2] - [ 0 0 -1 -1 0] - [ 0 0 -1 -1 -1] - [ 0 1 0 -2 0] - """ - return self.value - - _matrix_ = matrix - -class gl(LieAlgebraFromAssociative): +class gl(MatrixLieAlgebraFromAssociative): r""" The matrix Lie algebra `\mathfrak{gl}_n`. @@ -413,10 +385,10 @@ def __init__(self, R, n): category = LieAlgebras(R).FiniteDimensional().WithBasis() from sage.sets.finite_enumerated_set import FiniteEnumeratedSet index_set = FiniteEnumeratedSet(names) - LieAlgebraFromAssociative.__init__(self, MS, tuple(gens), - names=tuple(names), - index_set=index_set, - category=category) + MatrixLieAlgebraFromAssociative.__init__(self, MS, tuple(gens), + names=tuple(names), + index_set=index_set, + category=category) def _repr_(self): """ diff --git a/src/sage/algebras/lie_algebras/lie_algebra.py b/src/sage/algebras/lie_algebras/lie_algebra.py index 641a9dd6118..0d1dfa1c4bf 100644 --- a/src/sage/algebras/lie_algebras/lie_algebra.py +++ b/src/sage/algebras/lie_algebras/lie_algebra.py @@ -1502,5 +1502,37 @@ class MatrixLieAlgebraFromAssociative(LieAlgebraFromAssociative): A Lie algebra constructed from a matrix algebra. """ class Element(LieAlgebraMatrixWrapper, LieAlgebraFromAssociative.Element): - pass + def matrix(self): + r""" + Return ``self`` as element of the underlying matrix algebra. + + OUTPUT: + + An instance of the element class of MatrixSpace. + + EXAMPLES:: + + sage: sl3m = lie_algebras.sl(ZZ, 3, representation='matrix') + sage: e1,e2, f1, f2, h1, h2 = sl3m.gens() + sage: h1m = h1.matrix(); h1m + [ 1 0 0] + [ 0 -1 0] + [ 0 0 0] + sage: h1m.parent() + Full MatrixSpace of 3 by 3 sparse matrices over Integer Ring + sage: matrix(h2) + [ 0 0 0] + [ 0 1 0] + [ 0 0 -1] + sage: L = lie_algebras.so(QQ['z'], 5, representation='matrix') + sage: matrix(L.an_element()) + [ 1 1 0 0 0] + [ 1 1 0 0 2] + [ 0 0 -1 -1 0] + [ 0 0 -1 -1 -1] + [ 0 1 0 -2 0] + """ + return self.value + + _matrix_ = matrix From d90c2286fdcf02c88bdb4b8e2e5154d332036ae4 Mon Sep 17 00:00:00 2001 From: Vincent Delecroix <20100.delecroix@gmail.com> Date: Tue, 7 Jan 2020 11:42:24 +0100 Subject: [PATCH 046/133] fix libgap conversion of ElementLibGAP --- src/sage/groups/libgap_wrapper.pyx | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/sage/groups/libgap_wrapper.pyx b/src/sage/groups/libgap_wrapper.pyx index 33ce1d2a813..64e7c7e4199 100644 --- a/src/sage/groups/libgap_wrapper.pyx +++ b/src/sage/groups/libgap_wrapper.pyx @@ -59,6 +59,7 @@ AUTHORS: # https://www.gnu.org/licenses/ ############################################################################## +from sage.libs.gap.libgap import libgap from sage.libs.gap.element cimport GapElement from sage.rings.integer import Integer from sage.rings.integer_ring import IntegerRing @@ -517,10 +518,36 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): a*b*a^-1*b^-1 sage: type(xg) + + TESTS:: + + sage: libgap(FreeGroup('a, b').an_element()) + a*b + sage: type(libgap(FreeGroup('a, b').an_element())) + """ return self._libgap - _gap_ = gap + _libgap_ = _gap_ = gap + + def _test_libgap_conversion(self, **options): + r""" + TESTS:: + + sage: FreeGroup(2).an_element()._test_libgap_conversion() + """ + tester = self._tester(**options) + tester.assertTrue(libgap(self) is self.gap()) + + def _test_libgap_reconstruction(self, **options): + r""" + TESTS:: + + sage: FreeGroup(2).an_element()._test_libgap_reconstruction() + """ + tester = self._tester(**options) + P = self.parent() + tester.assertEqual(self, P.element_class(P, libgap(self))) def is_one(self): """ From d25f23945738d1ad2be1894c12221c2b138ea64d Mon Sep 17 00:00:00 2001 From: Vincent Delecroix <20100.delecroix@gmail.com> Date: Tue, 7 Jan 2020 11:44:07 +0100 Subject: [PATCH 047/133] allow raag elements to be constructed from libgap object --- src/sage/groups/raag.py | 54 +++++++++++++++++++++++++++++++++++------ 1 file changed, 46 insertions(+), 8 deletions(-) diff --git a/src/sage/groups/raag.py b/src/sage/groups/raag.py index dbe06b18494..76c093475cf 100644 --- a/src/sage/groups/raag.py +++ b/src/sage/groups/raag.py @@ -26,6 +26,8 @@ from __future__ import division, absolute_import, print_function import six +from sage.libs.gap.element import GapElement + from sage.misc.cachefunc import cached_method from sage.structure.richcmp import richcmp from sage.groups.finitely_presented import FinitelyPresentedGroup, FinitelyPresentedGroupElement @@ -387,15 +389,51 @@ def __init__(self, parent, lst): sage: G = RightAngledArtinGroup(Gamma) sage: elt = G.prod(G.gens()) sage: TestSuite(elt).run() + + sage: g = G([[0,-3], [2,2], [3,-1], [2,4]]) + sage: h = G.element_class(G, g.gap()) + sage: assert g.gap() == h.gap() + sage: assert g._data == h._data + + sage: g = G.one() + sage: h = G.element_class(G, g.gap()) + sage: assert g.gap() == h.gap() + sage: assert g._data == h._data """ - self._data = lst - elt = [] - for i, p in lst: - if p > 0: - elt.extend([i + 1] * p) - elif p < 0: - elt.extend([-i - 1] * -p) - FinitelyPresentedGroupElement.__init__(self, parent, elt) + if isinstance(lst, GapElement): + # e.g. direct call from GroupLibGAP + FinitelyPresentedGroupElement.__init__(self, parent, lst) + data = [] + j = None + mult = 0 + for i in self.Tietze(): + if j is None: + j = i + mult = 1 + elif j == i: + mult += 1 + else: + if j < 0: + data.append([-j-1, -mult]) + else: + data.append([j-1, mult]) + j = i + mult = 1 + if j is not None: + if j < 0: + data.append([-j-1, -mult]) + else: + data.append([j-1, mult]) + self._data = tuple(data) + else: + self._data = lst + elt = [] + for i, p in lst: + if p > 0: + elt.extend([i + 1] * p) + elif p < 0: + elt.extend([-i - 1] * -p) + FinitelyPresentedGroupElement.__init__(self, parent, elt) def __reduce__(self): """ From 03dca2b456e444cd3bd8baae16f38e5eccdaefa2 Mon Sep 17 00:00:00 2001 From: Vincent Delecroix <20100.delecroix@gmail.com> Date: Tue, 7 Jan 2020 11:45:09 +0100 Subject: [PATCH 048/133] rework gens of ParentLibGAP --- src/sage/groups/free_group.py | 4 +- src/sage/groups/libgap_wrapper.pyx | 79 +++++++++++------------------- 2 files changed, 31 insertions(+), 52 deletions(-) diff --git a/src/sage/groups/free_group.py b/src/sage/groups/free_group.py index 9bc5ff4e7d3..a056ad4c455 100644 --- a/src/sage/groups/free_group.py +++ b/src/sage/groups/free_group.py @@ -228,7 +228,7 @@ def __init__(self, parent, x): else: i=i+1 AbstractWordTietzeWord = libgap.eval('AbstractWordTietzeWord') - x = AbstractWordTietzeWord(l, parent._gap_gens()) + x = AbstractWordTietzeWord(l, parent.gap().GeneratorsOfGroup()) ElementLibGAP.__init__(self, parent, x) def __hash__(self): @@ -840,7 +840,7 @@ def _element_constructor_(self, *args, **kwds): sage: G([1, 2, -2, 1, 1, -2]) # indirect doctest a^3*b^-1 - sage: G( G._gap_gens()[0] ) + sage: G( a.gap() ) a sage: type(_) diff --git a/src/sage/groups/libgap_wrapper.pyx b/src/sage/groups/libgap_wrapper.pyx index 64e7c7e4199..05d9f83adcc 100644 --- a/src/sage/groups/libgap_wrapper.pyx +++ b/src/sage/groups/libgap_wrapper.pyx @@ -300,26 +300,6 @@ class ParentLibGAP(SageObject): _libgap_ = _gap_ = gap - @cached_method - def _gap_gens(self): - """ - Return the generators as a LibGAP object - - OUTPUT: - - A :class:`~sage.libs.gap.element.GapElement` - - EXAMPLES:: - - sage: G = FreeGroup(2) - sage: G._gap_gens() - [ x0, x1 ] - sage: type(_) - - """ - return self._libgap.GeneratorsOfGroup() - - @cached_method def ngens(self): """ Return the number of generators of self. @@ -339,7 +319,7 @@ class ParentLibGAP(SageObject): sage: type(G.ngens()) """ - return self._gap_gens().Length().sage() + return Integer(len(self.gens())) def _repr_(self): """ @@ -358,6 +338,33 @@ class ParentLibGAP(SageObject): """ return self._libgap._repr_() + @cached_method + def gens(self): + """ + Returns the generators of the group. + + EXAMPLES:: + + sage: G = FreeGroup(2) + sage: G.gens() + (x0, x1) + sage: H = FreeGroup('a, b, c') + sage: H.gens() + (a, b, c) + + :meth:`generators` is an alias for :meth:`gens` :: + + sage: G = FreeGroup('a, b') + sage: G.generators() + (a, b) + sage: H = FreeGroup(3, 'x') + sage: H.generators() + (x0, x1, x2) + """ + return tuple(self.element_class(self, g) for g in self._libgap.GeneratorsOfGroup()) + + generators = gens + def gen(self, i): """ Return the `i`-th generator of self. @@ -386,35 +393,7 @@ class ParentLibGAP(SageObject): """ if not (0 <= i < self.ngens()): raise ValueError('i must be in range(ngens)') - gap = self._gap_gens()[i] - return self.element_class(self, gap) - - @cached_method - def gens(self): - """ - Returns the generators of the group. - - EXAMPLES:: - - sage: G = FreeGroup(2) - sage: G.gens() - (x0, x1) - sage: H = FreeGroup('a, b, c') - sage: H.gens() - (a, b, c) - - :meth:`generators` is an alias for :meth:`gens` :: - - sage: G = FreeGroup('a, b') - sage: G.generators() - (a, b) - sage: H = FreeGroup(3, 'x') - sage: H.generators() - (x0, x1, x2) - """ - return tuple( self.gen(i) for i in range(self.ngens()) ) - - generators = gens + return self.gens()[i] @cached_method def one(self): From 2044eb2863d641ba2a01a1acc2a66a3e333b5edc Mon Sep 17 00:00:00 2001 From: Vincent Delecroix <20100.delecroix@gmail.com> Date: Tue, 7 Jan 2020 11:45:37 +0100 Subject: [PATCH 049/133] less indirection in group operations for ElementLibGAP --- src/sage/groups/libgap_wrapper.pyx | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/sage/groups/libgap_wrapper.pyx b/src/sage/groups/libgap_wrapper.pyx index 05d9f83adcc..f586f544f9d 100644 --- a/src/sage/groups/libgap_wrapper.pyx +++ b/src/sage/groups/libgap_wrapper.pyx @@ -618,8 +618,9 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): sage: y*x == y._mul_(x) True """ - P = left.parent() - return P.element_class(P, left.gap() * right.gap()) + P = ( left)._parent + return P.element_class(P, ( left)._libgap * \ + ( right)._libgap) cpdef _richcmp_(left, right, int op): """ @@ -659,8 +660,9 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): sage: x/y == y.__truediv__(x) False """ - P = left.parent() - return P.element_class(P, left.gap() / right.gap()) + P = ( left)._parent + return P.element_class(P, ( left)._libgap / \ + ( right)._libgap) def __pow__(self, n, dummy): """ @@ -680,8 +682,8 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): """ if n not in IntegerRing(): raise TypeError("exponent must be an integer") - P = self.parent() - return P.element_class(P, self.gap() ** n) + P = ( self)._parent + return P.element_class(P, ( self)._libgap ** n) def __invert__(self): """ @@ -701,8 +703,8 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): sage: x.inverse() b*a*b^-1*a^-1 """ - P = self.parent() - return P.element_class(P, self.gap().Inverse()) + P = ( self)._parent + return P.element_class(P, ( self)._libgap.Inverse()) inverse = __invert__ From 95c76cbf079b0c79edf8f5d75eba45b06d413650 Mon Sep 17 00:00:00 2001 From: Vincent Delecroix <20100.delecroix@gmail.com> Date: Tue, 7 Jan 2020 11:46:10 +0100 Subject: [PATCH 050/133] clean import --- src/sage/groups/libgap_wrapper.pxd | 2 +- src/sage/matrix/matrix_gap.pxd | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/sage/groups/libgap_wrapper.pxd b/src/sage/groups/libgap_wrapper.pxd index a7c689e201f..0c43b098140 100644 --- a/src/sage/groups/libgap_wrapper.pxd +++ b/src/sage/groups/libgap_wrapper.pxd @@ -1,4 +1,4 @@ -from sage.structure.element cimport MultiplicativeGroupElement, MonoidElement +from sage.structure.element cimport MultiplicativeGroupElement from sage.libs.gap.element cimport GapElement diff --git a/src/sage/matrix/matrix_gap.pxd b/src/sage/matrix/matrix_gap.pxd index d61f6918f7e..0667c158df8 100644 --- a/src/sage/matrix/matrix_gap.pxd +++ b/src/sage/matrix/matrix_gap.pxd @@ -1,6 +1,5 @@ from .matrix_dense cimport Matrix_dense from sage.libs.gap.element cimport GapElement -from sage.groups.libgap_wrapper cimport ElementLibGAP cdef class Matrix_gap(Matrix_dense): cdef GapElement _libgap From 81e7ecf158613727e2fafec293f134a3dfb7a98f Mon Sep 17 00:00:00 2001 From: Vincent Delecroix <20100.delecroix@gmail.com> Date: Tue, 7 Jan 2020 11:46:28 +0100 Subject: [PATCH 051/133] more capable libgap mixin and libgap group --- src/sage/groups/libgap_group.py | 6 +- src/sage/groups/libgap_mixin.py | 147 +++++++++++++++++---- src/sage/groups/matrix_gps/matrix_group.py | 12 +- 3 files changed, 131 insertions(+), 34 deletions(-) diff --git a/src/sage/groups/libgap_group.py b/src/sage/groups/libgap_group.py index cf3d39056e4..25783d73d6e 100644 --- a/src/sage/groups/libgap_group.py +++ b/src/sage/groups/libgap_group.py @@ -34,8 +34,9 @@ from sage.groups.group import Group from sage.groups.libgap_wrapper import ParentLibGAP, ElementLibGAP +from sage.groups.libgap_mixin import GroupMixinLibGAP -class GroupLibGAP(Group, ParentLibGAP): +class GroupLibGAP(GroupMixinLibGAP, Group, ParentLibGAP): Element = ElementLibGAP @@ -62,6 +63,3 @@ def __init__(self, *args, **kwds): ParentLibGAP.__init__(self, *args, **kwds) Group.__init__(self) - - - diff --git a/src/sage/groups/libgap_mixin.py b/src/sage/groups/libgap_mixin.py index f125a6d2182..f33bd24ea87 100644 --- a/src/sage/groups/libgap_mixin.py +++ b/src/sage/groups/libgap_mixin.py @@ -18,7 +18,6 @@ class GroupMixinLibGAP(object): - @cached_method def is_abelian(self): r""" Test whether the group is Abelian. @@ -29,6 +28,12 @@ def is_abelian(self): EXAMPLES:: + sage: from sage.groups.libgap_group import GroupLibGAP + sage: GroupLibGAP(libgap.CyclicGroup(12)).is_abelian() + True + sage: GroupLibGAP(libgap.SymmetricGroup(12)).is_abelian() + False + sage: SL(1, 17).is_abelian() True sage: SL(2, 17).is_abelian() @@ -36,7 +41,110 @@ def is_abelian(self): """ return self.gap().IsAbelian().sage() - @cached_method + def is_nilpotent(self): + r""" + Return whether this group is nilpotent. + + EXAMPLES:: + + sage: from sage.groups.libgap_group import GroupLibGAP + sage: GroupLibGAP(libgap.AlternatingGroup(3)).is_nilpotent() + True + sage: GroupLibGAP(libgap.SymmetricGroup(3)).is_nilpotent() + False + """ + return self.gap().IsNilpotentGroup().sage() + + def is_solvable(self): + r""" + Return whether this group is nilpotent. + + EXAMPLES:: + + sage: from sage.groups.libgap_group import GroupLibGAP + sage: GroupLibGAP(libgap.SymmetricGroup(4)).is_solvable() + True + sage: GroupLibGAP(libgap.SymmetricGroup(5)).is_solvable() + False + """ + return self.gap().IsSolvableGroup().sage() + + def is_super_solvable(self): + r""" + Return whether this group is super solvable. + + EXAMPLES:: + + sage: from sage.groups.libgap_group import GroupLibGAP + sage: GroupLibGAP(libgap.SymmetricGroup(3)).is_super_solvable() + True + sage: GroupLibGAP(libgap.SymmetricGroup(4)).is_super_solvable() + False + """ + return self.gap().IsSupersolvableGroup().sage() + + def is_polycyclic(self): + r""" + Return whether this group is polycyclic. + + EXAMPLES:: + + sage: from sage.groups.libgap_group import GroupLibGAP + sage: GroupLibGAP(libgap.AlternatingGroup(4)).is_polycyclic() + True + sage: GroupLibGAP(libgap.AlternatingGroup(5)).is_solvable() + False + """ + return self.gap().IsPolycyclicGroup().sage() + + def is_perfect(self): + r""" + Return whether this group is perfect. + + EXAMPLES:: + + sage: from sage.groups.libgap_group import GroupLibGAP + sage: GroupLibGAP(libgap.SymmetricGroup(5)).is_perfect() + False + sage: GroupLibGAP(libgap.AlternatingGroup(5)).is_perfect() + True + + sage: SL(3,3).is_perfect() + True + """ + return self.gap().IsPerfectGroup().sage() + + def is_p_group(self): + r""" + Return whether this group is a p-group. + + EXAMPLES:: + + sage: from sage.groups.libgap_group import GroupLibGAP + sage: GroupLibGAP(libgap.CyclicGroup(9)).is_p_group() + True + sage: GroupLibGAP(libgap.CyclicGroup(10)).is_p_group() + False + """ + return self.gap().IsPGroup().sage() + + def is_simple(self): + r""" + Return whether this group is simple. + + EXAMPLES:: + + sage: from sage.groups.libgap_group import GroupLibGAP + sage: GroupLibGAP(libgap.SL(2,3)).is_simple() + False + sage: GroupLibGAP(libgap.SL(3,3)).is_simple() + True + + sage: SL(3,3).is_simple() + True + """ + return self.gap().IsSimpleGroup().sage() + def is_finite(self): """ Test whether the matrix group is finite. @@ -98,8 +206,6 @@ def cardinality(self): +Infinity """ return self.gap().Size().sage() - from sage.rings.infinity import Infinity - return Infinity order = cardinality @@ -504,9 +610,10 @@ def __len__(self): ... NotImplementedError: group must be finite """ - if not self.is_finite(): - raise NotImplementedError('group must be finite') - return int(self.cardinality()) + size = self.gap().Size() + if size.IsInfinity(): + raise NotImplementedError("group must be finite") + return int(size) @cached_method def list(self): @@ -530,9 +637,10 @@ def list(self): 24 sage: v[:5] ( - [0 1] [0 1] [0 1] [0 2] [0 2] - [2 0], [2 1], [2 2], [1 0], [1 1] + [1 0] [2 0] [0 1] [0 2] [1 2] + [0 1], [0 2], [2 0], [1 0], [2 2] ) + sage: all(g in G for g in G.list()) True @@ -544,12 +652,12 @@ def list(self): sage: MG = MatrixGroup([M1, M2, M3]) sage: MG.list() ( - [-1 0] [-1 0] [ 1 0] [1 0] - [ 0 -1], [ 0 1], [ 0 -1], [0 1] + [1 0] [ 1 0] [-1 0] [-1 0] + [0 1], [ 0 -1], [ 0 1], [ 0 -1] ) sage: MG.list()[1] - [-1 0] - [ 0 1] + [ 1 0] + [ 0 -1] sage: MG.list()[1].parent() Matrix group over Integer Ring with 3 generators ( [-1 0] [ 1 0] [-1 0] @@ -579,8 +687,7 @@ def list(self): """ if not self.is_finite(): raise NotImplementedError('group must be finite') - elements = self.gap().Elements() - return tuple(self(x, check=False) for x in elements) + return tuple(self.element_class(self, g) for g in self.gap().AsList()) def is_isomorphic(self, H): """ @@ -610,12 +717,4 @@ def is_isomorphic(self, H): sage: F==G, G==H, F==H (False, False, False) """ - iso = self.gap().IsomorphismGroups(H.gap()) - if iso.is_bool(): # fail means not isomorphic - try: - iso.sage() - assert False - except ValueError: - pass - return False - return True + return self.gap().IsomorphismGroups(H.gap()) != libgap.fail diff --git a/src/sage/groups/matrix_gps/matrix_group.py b/src/sage/groups/matrix_gps/matrix_group.py index 3413c2a6358..90249e2adcf 100644 --- a/src/sage/groups/matrix_gps/matrix_group.py +++ b/src/sage/groups/matrix_gps/matrix_group.py @@ -574,8 +574,8 @@ def __init__(self, degree, base_ring, libgap_group, ambient=None, category=None) 24 sage: v[:5] ( - [0 1] [0 1] [0 1] [0 2] [0 2] - [2 0], [2 1], [2 2], [1 0], [1 1] + [1 0] [2 0] [0 1] [0 2] [1 2] + [0 1], [0 2], [2 0], [1 0], [2 2] ) sage: all(g in G for g in G.list()) True @@ -588,12 +588,12 @@ def __init__(self, degree, base_ring, libgap_group, ambient=None, category=None) sage: MG = MatrixGroup([M1, M2, M3]) sage: MG.list() ( - [-1 0] [-1 0] [ 1 0] [1 0] - [ 0 -1], [ 0 1], [ 0 -1], [0 1] + [1 0] [ 1 0] [-1 0] [-1 0] + [0 1], [ 0 -1], [ 0 1], [ 0 -1] ) sage: MG.list()[1] - [-1 0] - [ 0 1] + [ 1 0] + [ 0 -1] sage: MG.list()[1].parent() Matrix group over Integer Ring with 3 generators ( [-1 0] [ 1 0] [-1 0] From 03ded4b7dfe4eaa5091aee8b10a27519ef3a0cb0 Mon Sep 17 00:00:00 2001 From: Dima Pasechnik Date: Tue, 7 Jan 2020 11:53:19 +0000 Subject: [PATCH 052/133] add forgotten test (arrgh!) --- build/pkgs/bzip2/spkg-configure.m4 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build/pkgs/bzip2/spkg-configure.m4 b/build/pkgs/bzip2/spkg-configure.m4 index 29bb93e642a..40b8fe79220 100644 --- a/build/pkgs/bzip2/spkg-configure.m4 +++ b/build/pkgs/bzip2/spkg-configure.m4 @@ -1,7 +1,8 @@ SAGE_SPKG_CONFIGURE([bzip2], [ AC_CHECK_HEADER(bzlib.h, [ AC_SEARCH_LIBS([BZ2_bzCompress], [bz2], [ - AC_PATH_PROG([bzip2prog], [bzip2], [sage_spkg_install_bzip2=yes]) + AC_PATH_PROG([bzip2_prog], [bzip2]) + AS_IF([test x$bzip2_prog = x], [sage_spkg_install_bzip2=yes]) ], [sage_spkg_install_bzip2=yes]) ], [sage_spkg_install_bzip2=yes]) ]) From 2a2a77ecd6c091be1c26efc2b7b87096bf1bb5df Mon Sep 17 00:00:00 2001 From: Simon Brandhorst Date: Tue, 7 Jan 2020 12:58:18 +0100 Subject: [PATCH 053/133] PEP8 and avoid list comprehension --- .../free_quadratic_module_integer_symmetric.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/sage/modules/free_quadratic_module_integer_symmetric.py b/src/sage/modules/free_quadratic_module_integer_symmetric.py index 2562a1fee10..5652b33c848 100644 --- a/src/sage/modules/free_quadratic_module_integer_symmetric.py +++ b/src/sage/modules/free_quadratic_module_integer_symmetric.py @@ -1069,7 +1069,7 @@ def maximal_overlattice(self, p=None): i = 0 while i < len(D.gens()): t = D.gens()[i] - if t.q() == 0 and all([t.b(g)==0 for g in isotropic]): + if t.q() == 0 and all(t.b(g) == 0 for g in isotropic): isotropic.append(t) i += 1 isotropic = [g.lift() for g in isotropic] @@ -1078,9 +1078,9 @@ def maximal_overlattice(self, p=None): # clean up whatever is left by brute force while D.cardinality().valuation(2) > 1: for t in D: - if t != 0 and t.q()==0: + if t != 0 and t.q() == 0: break - if t.q()!=0: + if t.q()!=0 : # no isotropic vector left break L = L.overlattice([t.lift()]) @@ -1098,7 +1098,7 @@ def maximal_overlattice(self, p=None): d = L.discriminant_group(p).gram_matrix_bilinear().det() v = -d.valuation(p) u = d.numerator() - if v<=1 or (v == 2 and ZZ(-1).kronecker(p) != u.kronecker(p)): + if v <= 1 or (v == 2 and ZZ(-1).kronecker(p) != u.kronecker(p)): # the lattice is already maximal at p break # diagonalize the gram matrix @@ -1106,7 +1106,8 @@ def maximal_overlattice(self, p=None): gen = D.gens() G = D.gram_matrix_quadratic().diagonal() k = GF(p) - a = k(G[0].numerator()); b = k(G[1].numerator()); + a = k(G[0].numerator()) + b = k(G[1].numerator()) if (-b/a).is_square(): # solve: a*x^2 + b *y^2 = 0 x = (-b/a).sqrt() @@ -1119,7 +1120,7 @@ def maximal_overlattice(self, p=None): # brute force to find a suitable y # very fast for y in GF(p): - x = ((-c - b*y**2)/a) + x = (-c - b*y**2)/a if x.is_square(): x = x.sqrt() break From ce8e3ac097e369cceebebe498c2a20a076bc10db Mon Sep 17 00:00:00 2001 From: Vincent Delecroix <20100.delecroix@gmail.com> Date: Tue, 7 Jan 2020 21:17:42 +0100 Subject: [PATCH 054/133] further improvements to GroupLibGAP --- src/sage/groups/libgap_mixin.py | 36 ++++++++++++++++++++++++++++-- src/sage/groups/libgap_wrapper.pyx | 22 ++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/src/sage/groups/libgap_mixin.py b/src/sage/groups/libgap_mixin.py index f33bd24ea87..e9db528730b 100644 --- a/src/sage/groups/libgap_mixin.py +++ b/src/sage/groups/libgap_mixin.py @@ -11,12 +11,44 @@ just raise ``NotImplementedError``. """ -from sage.libs.all import libgap +from sage.libs.gap.libgap import libgap +from sage.libs.gap.element import GapElement +from sage.structure.element import parent from sage.misc.cachefunc import cached_method from sage.groups.class_function import ClassFunction_libgap - +from sage.groups.libgap_wrapper import ElementLibGAP class GroupMixinLibGAP(object): + def __contains__(self, elt): + r""" + TESTS:: + + sage: from sage.groups.libgap_group import GroupLibGAP + sage: G = GroupLibGAP(libgap.SL(2,3)) + sage: libgap([[1,0],[0,1]]) in G + False + sage: o = Mod(1, 3) + sage: z = Mod(0, 3) + sage: libgap([[o,z],[z,o]]) in G + True + + sage: G.an_element() in GroupLibGAP(libgap.GL(2,3)) + True + sage: G.an_element() in GroupLibGAP(libgap.GL(2,5)) + False + """ + if parent(elt) is self: + return True + elif isinstance(elt, GapElement): + return elt in self.gap() + elif isinstance(elt, ElementLibGAP): + return elt.gap() in self.gap() + else: + try: + elt2 = self(elt) + except Exception: + return False + return elt == elt2 def is_abelian(self): r""" diff --git a/src/sage/groups/libgap_wrapper.pyx b/src/sage/groups/libgap_wrapper.pyx index f586f544f9d..e4421df722d 100644 --- a/src/sage/groups/libgap_wrapper.pyx +++ b/src/sage/groups/libgap_wrapper.pyx @@ -708,3 +708,25 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): inverse = __invert__ + def order(self): + r""" + Return the multiplicative order. + + EXAMPLES:: + + sage: from sage.groups.libgap_group import GroupLibGAP + sage: G = GroupLibGAP(libgap.GL(2, 3)) + sage: a,b = G.gens() + sage: print(a.order(), b.order()) + 2 3 + sage: print(a.multiplicative_order(), b.multiplicative_order()) + 2 3 + + sage: z = Mod(0, 3) + sage: o = Mod(1, 3) + sage: G(libgap([[o,o],[z,o]])).order() + 3 + """ + return self._libgap.Order().sage() + + multiplicative_order = order From 139c8d2a71f849e1ccdd10a8dbd9d67cc193d4b8 Mon Sep 17 00:00:00 2001 From: Dave Witte Morris Date: Tue, 7 Jan 2020 13:31:00 -0700 Subject: [PATCH 055/133] implement basic functionality --- src/sage/structure/element.pyx | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/src/sage/structure/element.pyx b/src/sage/structure/element.pyx index fe7b8fdec93..beb641973c6 100644 --- a/src/sage/structure/element.pyx +++ b/src/sage/structure/element.pyx @@ -2713,7 +2713,7 @@ cdef class RingElement(ModuleElement): sage: Mod(-15, 37).abs() Traceback (most recent call last): ... - ArithmeticError: absolute valued not defined on integers modulo n. + ArithmeticError: absolute value not defined on integers modulo n. """ return abs(self) @@ -2794,12 +2794,36 @@ cdef class CommutativeRingElement(RingElement): """ Base class for elements of commutative rings. """ + def inverse_mod(self, I): r""" Return an inverse of ``self`` modulo the ideal `I`, if defined, i.e., if `I` and ``self`` together generate the unit ideal. - """ - raise NotImplementedError + + EXAMPLES:: + + sage: F = GF(25) + sage: x = F.gen() + sage: z = F.zero() + sage: x.inverse_mod(F.ideal(z)) + 2*z2 + 3 + sage: x.inverse_mod(F.ideal(1)) + 1 + sage: z.inverse_mod(F.ideal(1)) + 1 + sage: z.inverse_mod(F.ideal(z)) + Traceback (most recent call last): + ... + ValueError: 0 is in the proper ideal Principal ideal (0) of Finite Field in z2 of size 5^2 and therefore does not have an inverse + """ + if I.is_one(): + return self.parent().one() + elif self.is_unit(): + return self.inverse_of_unit() + elif self in I: + raise ValueError("%s is in the proper ideal %s and therefore does not have an inverse"%(self,I)) + else: + raise NotImplementedError def divides(self, x): """ From a817901535dea364c31c9d33259b307e948fbd77 Mon Sep 17 00:00:00 2001 From: Dave Witte Morris Date: Tue, 7 Jan 2020 15:13:47 -0700 Subject: [PATCH 056/133] fix typo in error message --- src/sage/rings/finite_rings/integer_mod.pyx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/rings/finite_rings/integer_mod.pyx b/src/sage/rings/finite_rings/integer_mod.pyx index 76f0d3ed655..c03ab39e179 100644 --- a/src/sage/rings/finite_rings/integer_mod.pyx +++ b/src/sage/rings/finite_rings/integer_mod.pyx @@ -428,9 +428,9 @@ cdef class IntegerMod_abstract(FiniteRingElement): sage: abs(Mod(2,3)) Traceback (most recent call last): ... - ArithmeticError: absolute valued not defined on integers modulo n. + ArithmeticError: absolute value not defined on integers modulo n. """ - raise ArithmeticError("absolute valued not defined on integers modulo n.") + raise ArithmeticError("absolute value not defined on integers modulo n.") def __reduce__(IntegerMod_abstract self): """ From 587652c9de0bae096c3e0206c74197039978720b Mon Sep 17 00:00:00 2001 From: Dave Witte Morris Date: Tue, 7 Jan 2020 15:18:09 -0700 Subject: [PATCH 057/133] also correct file element.pyx --- src/sage/structure/element.pyx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/structure/element.pyx b/src/sage/structure/element.pyx index fe7b8fdec93..35a2afa913e 100644 --- a/src/sage/structure/element.pyx +++ b/src/sage/structure/element.pyx @@ -2713,7 +2713,7 @@ cdef class RingElement(ModuleElement): sage: Mod(-15, 37).abs() Traceback (most recent call last): ... - ArithmeticError: absolute valued not defined on integers modulo n. + ArithmeticError: absolute value not defined on integers modulo n. """ return abs(self) From 46e1047b4ffa282de479d1691e074c62e7d00513 Mon Sep 17 00:00:00 2001 From: Dave Witte Morris Date: Tue, 7 Jan 2020 17:12:56 -0700 Subject: [PATCH 058/133] better handling of is_unit --- src/sage/structure/element.pyx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sage/structure/element.pyx b/src/sage/structure/element.pyx index beb641973c6..11169932e69 100644 --- a/src/sage/structure/element.pyx +++ b/src/sage/structure/element.pyx @@ -2814,14 +2814,14 @@ cdef class CommutativeRingElement(RingElement): sage: z.inverse_mod(F.ideal(z)) Traceback (most recent call last): ... - ValueError: 0 is in the proper ideal Principal ideal (0) of Finite Field in z2 of size 5^2 and therefore does not have an inverse + ValueError: Impossible inverse modulo """ if I.is_one(): return self.parent().one() - elif self.is_unit(): - return self.inverse_of_unit() elif self in I: - raise ValueError("%s is in the proper ideal %s and therefore does not have an inverse"%(self,I)) + raise ValueError("Impossible inverse modulo") + elif hasattr(self, "is_unit") and self.is_unit(): + return self.inverse_of_unit() else: raise NotImplementedError From ca2b83e736aea3a580051616bed172ce36c820d4 Mon Sep 17 00:00:00 2001 From: Simon Brandhorst Date: Wed, 8 Jan 2020 07:47:24 +0100 Subject: [PATCH 059/133] pep 8 --- src/sage/modules/free_quadratic_module_integer_symmetric.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/modules/free_quadratic_module_integer_symmetric.py b/src/sage/modules/free_quadratic_module_integer_symmetric.py index 5652b33c848..d2eeec0bd01 100644 --- a/src/sage/modules/free_quadratic_module_integer_symmetric.py +++ b/src/sage/modules/free_quadratic_module_integer_symmetric.py @@ -1080,7 +1080,7 @@ def maximal_overlattice(self, p=None): for t in D: if t != 0 and t.q() == 0: break - if t.q()!=0 : + if t.q() != 0 : # no isotropic vector left break L = L.overlattice([t.lift()]) From 96dad18223aad6e4c446978738aaa2444acc5f2f Mon Sep 17 00:00:00 2001 From: Jonathan Kliem Date: Wed, 8 Jan 2020 08:52:48 +0100 Subject: [PATCH 060/133] add doctests that cdd can handle empty polyhedron now --- src/sage/geometry/polyhedron/backend_cdd.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/sage/geometry/polyhedron/backend_cdd.py b/src/sage/geometry/polyhedron/backend_cdd.py index 6585dfbbf40..02b20ff2ec7 100644 --- a/src/sage/geometry/polyhedron/backend_cdd.py +++ b/src/sage/geometry/polyhedron/backend_cdd.py @@ -367,6 +367,17 @@ class Polyhedron_QQ_cdd(Polyhedron_cdd, Polyhedron_QQ): sage: from sage.geometry.polyhedron.backend_cdd import Polyhedron_QQ_cdd sage: Polyhedron_QQ_cdd(parent, [ [(1,0),(0,1),(0,0)], [], []], None, verbose=False) A 2-dimensional polyhedron in QQ^2 defined as the convex hull of 3 vertices + + TESTS: + + Check that :trac:`19803` is fixed:: + + sage: from sage.geometry.polyhedron.parent import Polyhedra + sage: P_cdd = Polyhedra(QQ, 3, 'cdd') + sage: P_cdd([[],[],[]], None) + The empty polyhedron in QQ^3 + sage: Polyhedron(vertices=[], backend='cdd', base_ring=QQ) + The empty polyhedron in QQ^0 """ _cdd_type = 'rational' @@ -439,6 +450,15 @@ class Polyhedron_RDF_cdd(Polyhedron_cdd, Polyhedron_RDF): 10 sage: P.n_facets() 10 + + Check that :trac:`19803` is fixed:: + + sage: from sage.geometry.polyhedron.parent import Polyhedra + sage: P_cdd = Polyhedra(RDF, 3, 'cdd') + sage: P_cdd([[],[],[]], None) + The empty polyhedron in RDF^3 + sage: Polyhedron(vertices=[], backend='cdd', base_ring=RDF) + The empty polyhedron in RDF^0 """ _cdd_type = 'real' From b6833f76d36f665bf26343415c8f5f955b1bb46c Mon Sep 17 00:00:00 2001 From: "E. Madison Bray" Date: Wed, 8 Jan 2020 15:14:07 +0100 Subject: [PATCH 061/133] Trac #28695: Make mismatch between compiler and AS/LD a fatal error. This is a subtle problem that's easy to miss otherwise, and results in Sage trying to build GCC unwantedly. --- build/pkgs/gcc/spkg-configure.m4 | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/build/pkgs/gcc/spkg-configure.m4 b/build/pkgs/gcc/spkg-configure.m4 index 76647d9cb65..19c55b08aad 100644 --- a/build/pkgs/gcc/spkg-configure.m4 +++ b/build/pkgs/gcc/spkg-configure.m4 @@ -159,9 +159,9 @@ SAGE_SPKG_CONFIGURE_BASE([gcc], [ cmd_AS=`command -v $AS` if ! (test "$CXX_as" = "" -o "$CXX_as" -ef "$cmd_AS"); then - SAGE_SHOULD_INSTALL_GCC([there is a mismatch of assemblers]) - AC_MSG_NOTICE([ $CXX uses $CXX_as]) - AC_MSG_NOTICE([ \$AS equal to $AS]) + AC_MSG_NOTICE([ $CXX uses $CXX_as]) + AC_MSG_NOTICE([ \$AS equal to $AS]) + AC_MSG_ERROR([unset \$AS or set it to match your compiler's assembler]) fi fi if test -n "$LD"; then @@ -169,9 +169,9 @@ SAGE_SPKG_CONFIGURE_BASE([gcc], [ CXX_ld=`command -v $CXX_ld 2>/dev/null` cmd_LD=`command -v $LD` if ! (test "$CXX_ld" = "" -o "$CXX_ld" -ef "$cmd_LD"); then - SAGE_SHOULD_INSTALL_GCC([there is a mismatch of linkers]) - AC_MSG_NOTICE([ $CXX uses $CXX_ld]) - AC_MSG_NOTICE([ \$LD equal to $LD]) + AC_MSG_NOTICE([ $CXX uses $CXX_ld]) + AC_MSG_NOTICE([ \$LD equal to $LD]) + AC_MSG_ERROR([unset \$LD or set it to match your compiler's linker]) fi fi From ca7013b61464c3516db1554534f6f01f2b6514ad Mon Sep 17 00:00:00 2001 From: "E. Madison Bray" Date: Wed, 8 Jan 2020 15:20:50 +0100 Subject: [PATCH 062/133] Trac #28695: These settings (if they are even needed at all) should use -print-prog-name, which on current gcc versions will provide the full path to the program. --- src/bin/sage-env | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/bin/sage-env b/src/bin/sage-env index 49f29942df0..c9623effc87 100644 --- a/src/bin/sage-env +++ b/src/bin/sage-env @@ -500,7 +500,7 @@ fi # Set AS to assembler used by $CC ("as" by default) if [ "$AS" = "" ]; then - CC_as=`$CC -print-file-name=as 2>/dev/null` + CC_as=`$CC -print-prog-name=as 2>/dev/null` if command -v $CC_as >/dev/null 2>/dev/null; then AS="$CC_as" fi @@ -512,7 +512,7 @@ export AS # Set LD to linker used by $CC ("ld" by default) if [ "$LD" = "" ]; then - CC_ld=`$CC -print-file-name=ld 2>/dev/null` + CC_ld=`$CC -print-prog-name=ld 2>/dev/null` if command -v $CC_ld >/dev/null 2>/dev/null; then LD="$CC_ld" fi From 5e1a8725534c39f4f37021b922abe27bb24a9145 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Wed, 8 Jan 2020 20:03:50 +0100 Subject: [PATCH 063/133] fix some details in dynamics and rings (return is not a function) --- .../arithmetic_dynamics/projective_ds.py | 45 ++++++++++--------- src/sage/rings/function_field/place.py | 4 +- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/src/sage/dynamics/arithmetic_dynamics/projective_ds.py b/src/sage/dynamics/arithmetic_dynamics/projective_ds.py index 65c8841a1ad..448b1eacdb6 100644 --- a/src/sage/dynamics/arithmetic_dynamics/projective_ds.py +++ b/src/sage/dynamics/arithmetic_dynamics/projective_ds.py @@ -487,7 +487,7 @@ def _number_field_from_algebraics(self): r""" Return a dynamical system defined over the number field of its coefficients. - OTUPUT: dynamical system. + OUTPUT: dynamical system. EXAMPLES:: @@ -1322,7 +1322,7 @@ def orbit(self, P, N, **kwds): if N[0] < 0 or N[1] < 0: raise TypeError("orbit bounds must be non-negative") if N[0] > N[1]: - return([]) + return [] R = self.domain()(P) if R in self.domain(): #Check whether R is a zero-dimensional point @@ -1343,7 +1343,7 @@ def orbit(self, P, N, **kwds): if normalize: Q.normalize_coordinates() orb.append(Q) - return(orb) + return orb def resultant(self, normalize=False): r""" @@ -1416,7 +1416,7 @@ def resultant(self, normalize=False): try: res = (f.lc() ** (d - g.degree()) * g.lc() ** (d - f.degree()) * f.__pari__().polresultant(g, x)) - return(self.domain().base_ring()(res)) + return self.domain().base_ring()(res) except (TypeError, PariError): pass #Otherwise, use Macaulay @@ -1542,7 +1542,7 @@ def primes_of_bad_reduction(self, check=True): badprimes.pop(index) else: index += 1 - return(badprimes) + return badprimes else: raise TypeError("base ring must be number field or number field ring") @@ -2166,7 +2166,7 @@ def height_difference_bound(self, prec=None): maxh = max(maxh, val[1]) L = abs(R(gcdRes).log() - R((N + 1) * binomial(N + D - d, D - d)).log() - maxh) C = max(U, L) #height difference dh(P) - L <= h(f(P)) <= dh(P) +U - return(C / (d - 1)) + return C / (d - 1) def multiplier(self, P, n, check=True): r""" @@ -2331,7 +2331,7 @@ def _multipliermod(self, P, n, p, k): F = self.dehomogenize((indexlist[i],indexlist[i+1])) l = (F.jacobian()(tuple(Q.dehomogenize(indexlist[i])))*l) % (p ** k) Q = R - return(l) + return l def _nth_preimage_tree_helper(self, Q, n, m, **kwds): r""" @@ -2679,7 +2679,7 @@ def _preperiodic_points_to_cyclegraph(self, preper): E.append([Q]) from sage.graphs.digraph import DiGraph g = DiGraph(dict(zip(V, E)), loops=True) - return(g) + return g def is_PGL_minimal(self, prime_list=None): r""" @@ -3171,11 +3171,11 @@ def automorphism_group(self, **kwds): from .endPN_automorphism_group import automorphism_group_QQ_CRT, automorphism_group_QQ_fixedpoints if alg is None: if self.degree() <= 12: - return(automorphism_group_QQ_fixedpoints(F, return_functions, iso_type)) - return(automorphism_group_QQ_CRT(F, p, return_functions, iso_type)) + return automorphism_group_QQ_fixedpoints(F, return_functions, iso_type) + return automorphism_group_QQ_CRT(F, p, return_functions, iso_type) elif alg == 'CRT': - return(automorphism_group_QQ_CRT(F, p, return_functions, iso_type)) - return(automorphism_group_QQ_fixedpoints(F, return_functions, iso_type)) + return automorphism_group_QQ_CRT(F, p, return_functions, iso_type) + return automorphism_group_QQ_fixedpoints(F, return_functions, iso_type) def critical_subscheme(self): r""" @@ -3390,7 +3390,7 @@ def is_postcritically_finite(self, err=0.01, use_algebraic_closure=True): if crit_points[i].is_preperiodic(F, err) == False: pcf = False i += 1 - return(pcf) + return pcf def critical_point_portrait(self, check=True, use_algebraic_closure=True): r""" @@ -3503,7 +3503,7 @@ def critical_point_portrait(self, check=True, use_algebraic_closure=True): else: crit_points.append(Q) Q = F(Q) - return(F._preperiodic_points_to_cyclegraph(crit_points)) + return F._preperiodic_points_to_cyclegraph(crit_points) def critical_height(self, **kwds): r""" @@ -3795,8 +3795,8 @@ def preperiodic_points(self, m, n, **kwds): points = [dom(Q) for Q in X.rational_points()] good_points = [] for Q in points: - #check if point is in indeterminacy - if not all([F(list(Q)) == 0 for F in f]): + # check if point is in indeterminacy + if not all(F(list(Q)) == 0 for F in f): good_points.append(Q) points = good_points if not minimal: @@ -3810,7 +3810,7 @@ def preperiodic_points(self, m, n, **kwds): orbit = [P] Q = f(P) n_plus_m = 1 - while not Q in orbit: + while Q not in orbit: orbit.append(Q) Q = f(Q) n_plus_m += 1 @@ -4027,7 +4027,7 @@ def periodic_points(self, n, minimal=True, R=None, algorithm='variety', else: if n % m == 0: points = points + cycle[:-1] - return(points) + return points else: raise TypeError("ring must be finite to generate cyclegraph") elif algorithm == 'variety': @@ -4952,7 +4952,7 @@ def _is_preperiodic(self, P, err=0.1, return_period=False): if H <= B: #it must have been in the cycle if return_period: m = orbit.index(Q) - return((m, n-m)) + return (m, n - m) else: return True if return_period: @@ -4960,6 +4960,7 @@ def _is_preperiodic(self, P, err=0.1, return_period=False): else: return False + class DynamicalSystem_projective_field(DynamicalSystem_projective, SchemeMorphism_polynomial_projective_space_field): @@ -5164,7 +5165,7 @@ def lift_to_rational_periodic(self, points_modp, B=None): done = True k += 1 - return(good_points) + return good_points def all_periodic_points(self, **kwds): r""" @@ -5818,7 +5819,7 @@ def all_preperiodic_points(self, **kwds): periods = DS.possible_periods(prime_bound=primebound, bad_primes=badprimes, ncpus=num_cpus) if periods == []: - return([]) #no rational preperiodic points + return [] #no rational preperiodic points else: p = kwds.pop("lifting_prime", 23) #find the rational preperiodic points @@ -7232,7 +7233,7 @@ def automorphism_group(self, absolute=False, iso_type=False, return_functions=Fa else: F = f[0].numerator().polynomial(z) from .endPN_automorphism_group import automorphism_group_FF - return(automorphism_group_FF(F, absolute, iso_type, return_functions)) + return automorphism_group_FF(F, absolute, iso_type, return_functions) def all_periodic_points(self, **kwds): r""" diff --git a/src/sage/rings/function_field/place.py b/src/sage/rings/function_field/place.py index 476273171f7..a856a25ec8c 100644 --- a/src/sage/rings/function_field/place.py +++ b/src/sage/rings/function_field/place.py @@ -865,8 +865,8 @@ def _residue_field(self, name=None): To: Number Field in s with defining polynomial x^2 - 2*x + 2)] sage: for p in L.places_above(I.place()): ....: k, fr_k, to_k = p.residue_field() - ....: assert all([fr_k(k(e)) == e for e in range(10)]) - ....: assert all([to_k(fr_k(e)) == e for e in [k.random_element() for i in [1..10]]]) + ....: assert all(fr_k(k(e)) == e for e in range(10)) + ....: assert all(to_k(fr_k(e)) == e for e in [k.random_element() for i in [1..10]]) :: From 37863dffe422080bacb83e930ad22b7c92f92749 Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Thu, 9 Jan 2020 00:03:28 +0100 Subject: [PATCH 064/133] Trac #28916: Doctest for coerce map added --- src/sage/manifolds/differentiable/mixed_form_algebra.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/sage/manifolds/differentiable/mixed_form_algebra.py b/src/sage/manifolds/differentiable/mixed_form_algebra.py index 32a31b22432..f8e5a524781 100644 --- a/src/sage/manifolds/differentiable/mixed_form_algebra.py +++ b/src/sage/manifolds/differentiable/mixed_form_algebra.py @@ -264,6 +264,8 @@ def _coerce_map_from_(self, S): True sage: A._coerce_map_from_(M.diff_form_module(3)) True + sage: A._coerce_map_from_(M.tensor_field_module((0,1))) + True sage: U = M.open_subset('U') sage: AU = U.mixed_form_algebra() sage: AU._coerce_map_from_(A) From c02dcdcd0a4d04087c432afcfe51cab054d41d35 Mon Sep 17 00:00:00 2001 From: Vincent Delecroix <20100.delecroix@gmail.com> Date: Thu, 9 Jan 2020 01:15:48 +0100 Subject: [PATCH 065/133] fix group iteration --- src/sage/groups/libgap_mixin.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/sage/groups/libgap_mixin.py b/src/sage/groups/libgap_mixin.py index e9db528730b..12edc2dca32 100644 --- a/src/sage/groups/libgap_mixin.py +++ b/src/sage/groups/libgap_mixin.py @@ -614,6 +614,11 @@ def __iter__(self): sage: next(iter(G)) [1 0] [0 1] + + sage: from sage.groups.libgap_group import GroupLibGAP + sage: G = GroupLibGAP(libgap.AlternatingGroup(5)) + sage: sum(1 for g in G) + 60 """ if self.list.cache is not None: for g in self.list(): @@ -621,7 +626,7 @@ def __iter__(self): return iterator = self.gap().Iterator() while not iterator.IsDoneIterator().sage(): - yield self(iterator.NextIterator(), check=False) + yield self.element_class(self, iterator.NextIterator()) def __len__(self): """ From 94972c7b5312ddfae5ae4db51f2d3394eab82794 Mon Sep 17 00:00:00 2001 From: Vincent Delecroix <20100.delecroix@gmail.com> Date: Thu, 9 Jan 2020 01:17:05 +0100 Subject: [PATCH 066/133] is_conjugate/normalizer/nth_roots for elements --- src/sage/groups/libgap_wrapper.pyx | 57 ++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/src/sage/groups/libgap_wrapper.pyx b/src/sage/groups/libgap_wrapper.pyx index e4421df722d..6d4fbec9e8a 100644 --- a/src/sage/groups/libgap_wrapper.pyx +++ b/src/sage/groups/libgap_wrapper.pyx @@ -730,3 +730,60 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): return self._libgap.Order().sage() multiplicative_order = order + + def is_conjugate(self, other): + r""" + Return whether the elements ``self`` and ``other`` are conjugate. + + EXAMPLES:: + + sage: from sage.groups.libgap_group import GroupLibGAP + sage: G = GroupLibGAP(libgap.GL(2, 3)) + sage: a,b = G.gens() + sage: a.is_conjugate(b) + False + sage: a.is_conjugate((a*b^2) * a * ~(a*b^2)) + True + """ + return libgap.IsConjugate(self.parent(), self, other).sage() + + def normalizer(self): + r""" + Return the normalizer of the cyclic group generated by this element. + + EXAMPLES:: + + sage: from sage.groups.libgap_group import GroupLibGAP + sage: G = GroupLibGAP(libgap.GL(3,3)) + sage: a,b = G.gens() + sage: H = a.normalizer() + sage: H + + sage: H.cardinality() + 96 + sage: all(g*a == a*g for g in H) + True + """ + from sage.groups.libgap_group import GroupLibGAP + P = self.parent() + return GroupLibGAP(libgap.Normalizer(P, self), ambient=P) + + def nth_roots(self, n): + r""" + Return the set of ``n``-th roots of this group element. + + EXAMPLES:: + + sage: from sage.groups.libgap_group import GroupLibGAP + sage: G = GroupLibGAP(libgap.GL(3,3)) + sage: a,b = G.gens() + sage: g = a*b**2*a*~b + sage: r = g.nth_roots(4) + sage: r + [[ [ Z(3), Z(3), Z(3)^0 ], [ Z(3)^0, Z(3)^0, 0*Z(3) ], [ 0*Z(3), Z(3), 0*Z(3) ] ], + [ [ Z(3)^0, Z(3)^0, Z(3) ], [ Z(3), Z(3), 0*Z(3) ], [ 0*Z(3), Z(3)^0, 0*Z(3) ] ]] + sage: r[0]**4 == r[1]**4 == g + True + """ + P = self.parent() + return [P.element_class(P, g) for g in libgap.NthRootsInGroup(P.gap(), self._libgap, n)] From 8b9ac9a24a29930ae84cac2e575ce821171bd4bb Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Thu, 9 Jan 2020 13:18:56 +0100 Subject: [PATCH 067/133] Trac #28973: Brackets around element before inverse --- .../differentiable/automorphismfield.py | 22 +++++++++---------- .../differentiable/automorphismfield_group.py | 4 ++-- .../modules/free_module_automorphism.py | 16 +++++++------- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/sage/manifolds/differentiable/automorphismfield.py b/src/sage/manifolds/differentiable/automorphismfield.py index 157ccd421f0..041dd206ee0 100644 --- a/src/sage/manifolds/differentiable/automorphismfield.py +++ b/src/sage/manifolds/differentiable/automorphismfield.py @@ -120,12 +120,12 @@ class AutomorphismField(TensorField): In particular, we may ask for its inverse on the whole manifold `M`:: sage: ia = a.inverse() ; ia - Field of tangent-space automorphisms a^(-1) on the 2-dimensional + Field of tangent-space automorphisms (a)^(-1) on the 2-dimensional differentiable manifold M sage: ia.display(eU) - a^(-1) = d/dx*dx - 1/2*x d/dx*dy + 1/2 d/dy*dy + (a)^(-1) = d/dx*dx - 1/2*x d/dx*dy + 1/2 d/dy*dy sage: ia.display(eV) - a^(-1) = (-1/8*u - 1/8*v + 3/4) d/du*du + (1/8*u + 1/8*v + 1/4) d/du*dv + (a)^(-1) = (-1/8*u - 1/8*v + 3/4) d/du*du + (1/8*u + 1/8*v + 1/4) d/du*dv + (-1/8*u - 1/8*v + 1/4) d/dv*du + (1/8*u + 1/8*v + 3/4) d/dv*dv Equivalently, one can use the power minus one to get the inverse:: @@ -550,7 +550,7 @@ def __invert__(self): sage: a = M.automorphism_field({eU: [[1,x], [0,2]]}, name='a') sage: a.add_comp_by_continuation(eV, W, c_uv) sage: ia = a.inverse() ; ia - Field of tangent-space automorphisms a^(-1) on the 2-dimensional + Field of tangent-space automorphisms (a)^(-1) on the 2-dimensional differentiable manifold M sage: a[eU,:], ia[eU,:] ( @@ -603,11 +603,11 @@ def __invert__(self): if self._name is None: inv_name = None else: - inv_name = self._name + '^(-1)' + inv_name = '(' + self._name + ')^(-1)' if self._latex_name is None: inv_latex_name = None else: - inv_latex_name = self._latex_name + r'^{-1}' + inv_latex_name = r'\left(' + self._latex_name + r'\right)^{-1}' self._inverse = self._vmodule.automorphism(name=inv_name, latex_name=inv_latex_name) for dom, rst in self._restrictions.items(): @@ -938,10 +938,10 @@ class AutomorphismFieldParal(FreeModuleAutomorphism, TensorFieldParal): The inverse automorphism is obtained via the method :meth:`inverse`:: sage: inv = rot.inverse() ; inv - Field of tangent-space automorphisms R^(-1) on the 2-dimensional + Field of tangent-space automorphisms (R)^(-1) on the 2-dimensional differentiable manifold R^2 sage: latex(inv) - R^{-1} + \left(R\right)^{-1} sage: inv[:] [1/2*sqrt(3) 1/2] [ -1/2 1/2*sqrt(3)] @@ -1122,7 +1122,7 @@ def __invert__(self): sage: X. = M.chart() sage: a = M.automorphism_field([[0, 2], [-1, 0]], name='a') sage: b = a.inverse(); b - Field of tangent-space automorphisms a^(-1) on the 2-dimensional + Field of tangent-space automorphisms (a)^(-1) on the 2-dimensional differentiable manifold M sage: b[:] [ 0 -1] @@ -1157,11 +1157,11 @@ def __invert__(self): if self._name is None: inv_name = None else: - inv_name = self._name + '^(-1)' + inv_name = '(' + self._name + ')^(-1)' if self._latex_name is None: inv_latex_name = None else: - inv_latex_name = self._latex_name + r'^{-1}' + inv_latex_name = r'\left(' + self._latex_name + r'\right)^{-1}' fmodule = self._fmodule si = fmodule._sindex ; nsi = fmodule._rank + si self._inverse = fmodule.automorphism(name=inv_name, diff --git a/src/sage/manifolds/differentiable/automorphismfield_group.py b/src/sage/manifolds/differentiable/automorphismfield_group.py index 4cc248e67dd..e3204e80f36 100644 --- a/src/sage/manifolds/differentiable/automorphismfield_group.py +++ b/src/sage/manifolds/differentiable/automorphismfield_group.py @@ -537,10 +537,10 @@ class AutomorphismFieldParalGroup(FreeModuleLinearGroup): sage: t1.display() t = (e^y + 1) d/dx*dx + x*y d/dx*dy + (x^2 + 1) d/dy*dy sage: t1^(-1) - Field of tangent-space automorphisms t^(-1) on the 2-dimensional + Field of tangent-space automorphisms (t)^(-1) on the 2-dimensional differentiable manifold M sage: (t1^(-1)).display() - t^(-1) = 1/(e^y + 1) d/dx*dx - x*y/(x^2 + (x^2 + 1)*e^y + 1) d/dx*dy + (t)^(-1) = 1/(e^y + 1) d/dx*dx - x*y/(x^2 + (x^2 + 1)*e^y + 1) d/dx*dy + 1/(x^2 + 1) d/dy*dy Since any automorphism field can be considered as a tensor field of diff --git a/src/sage/tensor/modules/free_module_automorphism.py b/src/sage/tensor/modules/free_module_automorphism.py index c526e24129c..1364e5153f0 100644 --- a/src/sage/tensor/modules/free_module_automorphism.py +++ b/src/sage/tensor/modules/free_module_automorphism.py @@ -193,7 +193,7 @@ class FreeModuleAutomorphism(FreeModuleTensor, MultiplicativeGroupElement): or the operator ~, or the exponent -1:: sage: a.inverse() - Automorphism a^(-1) of the Rank-2 free module M over the Integer Ring + Automorphism (a)^(-1) of the Rank-2 free module M over the Integer Ring sage: a.inverse() is ~a True sage: a.inverse() is a^(-1) @@ -357,7 +357,7 @@ def _del_derived(self): sage: a[e,:] = [[1,0,-1], [0,3,0], [0,0,2]] sage: b = a.inverse() sage: a._inverse - Automorphism a^(-1) of the 3-dimensional vector space M over the + Automorphism (a)^(-1) of the 3-dimensional vector space M over the Rational Field sage: a._del_derived() sage: a._inverse # has been reset to None @@ -683,7 +683,7 @@ def __invert__(self): sage: a = M.automorphism(name='a') sage: a[e,:] = [[1,0,0],[0,-1,2],[0,1,-3]] sage: a.inverse() - Automorphism a^(-1) of the Rank-3 free module M over the Integer + Automorphism (a)^(-1) of the Rank-3 free module M over the Integer Ring sage: a.inverse().parent() General linear group of the Rank-3 free module M over the Integer @@ -729,7 +729,7 @@ def __invert__(self): sage: ~a is a.inverse() True - sage: a^(-1) is a.inverse() + sage: (a)^(-1) is a.inverse() True The inverse of the identity map is of course itself:: @@ -740,9 +740,9 @@ def __invert__(self): and we have:: - sage: a*a^(-1) == id + sage: a*(a)^(-1) == id True - sage: a^(-1)*a == id + sage: (a)^(-1)*a == id True """ from .comp import Components @@ -752,11 +752,11 @@ def __invert__(self): if self._name is None: inv_name = None else: - inv_name = self._name + '^(-1)' + inv_name = '(' + self._name + ')^(-1)' if self._latex_name is None: inv_latex_name = None else: - inv_latex_name = self._latex_name + r'^{-1}' + inv_latex_name = r'\left(' + self._latex_name + r'\right)^{-1}' fmodule = self._fmodule si = fmodule._sindex nsi = fmodule._rank + si From 15067c152449793de4e1ca567313ed10b06de245 Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Thu, 9 Jan 2020 15:06:00 +0100 Subject: [PATCH 068/133] Trac #28973: is_atomic adapted and used --- .../differentiable/automorphismfield.py | 16 +++-- src/sage/tensor/modules/format_utilities.py | 62 +++++++++---------- .../modules/free_module_automorphism.py | 28 +++++++-- 3 files changed, 64 insertions(+), 42 deletions(-) diff --git a/src/sage/manifolds/differentiable/automorphismfield.py b/src/sage/manifolds/differentiable/automorphismfield.py index 041dd206ee0..965fe1fef4c 100644 --- a/src/sage/manifolds/differentiable/automorphismfield.py +++ b/src/sage/manifolds/differentiable/automorphismfield.py @@ -120,7 +120,7 @@ class AutomorphismField(TensorField): In particular, we may ask for its inverse on the whole manifold `M`:: sage: ia = a.inverse() ; ia - Field of tangent-space automorphisms (a)^(-1) on the 2-dimensional + Field of tangent-space automorphisms a^(-1) on the 2-dimensional differentiable manifold M sage: ia.display(eU) (a)^(-1) = d/dx*dx - 1/2*x d/dx*dy + 1/2 d/dy*dy @@ -550,7 +550,7 @@ def __invert__(self): sage: a = M.automorphism_field({eU: [[1,x], [0,2]]}, name='a') sage: a.add_comp_by_continuation(eV, W, c_uv) sage: ia = a.inverse() ; ia - Field of tangent-space automorphisms (a)^(-1) on the 2-dimensional + Field of tangent-space automorphisms a^(-1) on the 2-dimensional differentiable manifold M sage: a[eU,:], ia[eU,:] ( @@ -600,14 +600,22 @@ def __invert__(self): if self._is_identity: return self if self._inverse is None: + from sage.tensor.modules.format_utilities import is_atomic if self._name is None: inv_name = None else: - inv_name = '(' + self._name + ')^(-1)' + if is_atomic(self._name, ['*']): + inv_name = self._name + '^(-1)' + else: + inv_name = '(' + self._name + ')^(-1)' if self._latex_name is None: inv_latex_name = None else: - inv_latex_name = r'\left(' + self._latex_name + r'\right)^{-1}' + if is_atomic(self._latex_name, ['\\circ', '\\otimes']): + inv_latex_name = self._latex_name + r'^{-1}' + else: + inv_latex_name = r'\left(' + self._latex_name + \ + r'\right)^{-1}' self._inverse = self._vmodule.automorphism(name=inv_name, latex_name=inv_latex_name) for dom, rst in self._restrictions.items(): diff --git a/src/sage/tensor/modules/format_utilities.py b/src/sage/tensor/modules/format_utilities.py index f09c79c2626..a98aa455184 100644 --- a/src/sage/tensor/modules/format_utilities.py +++ b/src/sage/tensor/modules/format_utilities.py @@ -7,6 +7,7 @@ - Eric Gourgoulhon, Michal Bejger (2014-2015): initial version - Joris Vankerschaver (2010): for the function :func:`is_atomic()` +- Michael Jung (2020): extended usage of :func:`is_atomic()` """ @@ -23,7 +24,7 @@ import six from sage.structure.sage_object import SageObject -def is_atomic(expression): +def is_atomic(expr, sep=['+', '-']): r""" Helper function to check whether some LaTeX expression is atomic. @@ -31,15 +32,17 @@ def is_atomic(expression): :meth:`~sage.tensor.differential_form_element.DifferentialFormFormatter._is_atomic` of class :class:`~sage.tensor.differential_form_element.DifferentialFormFormatter` - written by Joris Vankerschaver (2010). + written by Joris Vankerschaver (2010) and modified by Michael Jung (2020). INPUT: - - ``expression`` -- string representing the expression (e.g. LaTeX string) + - ``expr`` -- string representing the expression (e.g. LaTeX string) + - ``sep`` -- (default: ``['+', '-']``) a list of strings representing the + operations (e.g. LaTeX strings) OUTPUT: - - ``True`` if additive operations are enclosed in parentheses and + - ``True`` if the operations are enclosed in parentheses and ``False`` otherwise. EXAMPLES:: @@ -52,16 +55,31 @@ def is_atomic(expression): sage: is_atomic("(2+x)") True + Moreover the separator can be changed:: + + sage: is_atomic("a*b", sep=['*']) + False + sage: is_atomic("(a*b)", sep=['*']) + True + sage: is_atomic("a<>b", sep=['<>']) + False + sage: is_atomic("(a<>b)", sep=['<>']) + True + """ - if not isinstance(expression, six.string_types): + if not isinstance(expr, six.string_types): raise TypeError("The argument must be a string") + if not isinstance(sep, list): + raise TypeError("the argument 'sep' must be a list") + elif any(not isinstance(s, six.string_types) for s in sep): + raise TypeError("the argument 'sep' must consist of strings") level = 0 - for n, c in enumerate(expression): + for n, c in enumerate(expr): if c == '(': level += 1 elif c == ')': level -= 1 - if c == '+' or c == '-': + if any(expr[n:n + len(s)] == s for s in sep): if level == 0 and n > 0: return False return True @@ -76,7 +94,7 @@ def is_atomic_wedge_txt(expression): :meth:`~sage.tensor.differential_form_element.DifferentialFormFormatter._is_atomic` of class :class:`~sage.tensor.differential_form_element.DifferentialFormFormatter` - written by Joris Vankerschaver (2010). + written by Joris Vankerschaver (2010) and modified by Michael Jung (2020). INPUT: @@ -102,18 +120,7 @@ def is_atomic_wedge_txt(expression): True """ - if not isinstance(expression, six.string_types): - raise TypeError("The argument must be a string.") - level = 0 - for n, c in enumerate(expression): - if c == '(': - level += 1 - elif c == ')': - level -= 1 - if c == '/' and expression[n+1:n+2] == '\\': - if level == 0 and n > 0: - return False - return True + return is_atomic(expression, sep=['/\\']) def is_atomic_wedge_latex(expression): @@ -125,7 +132,7 @@ def is_atomic_wedge_latex(expression): :meth:`~sage.tensor.differential_form_element.DifferentialFormFormatter._is_atomic` of class :class:`~sage.tensor.differential_form_element.DifferentialFormFormatter` - written by Joris Vankerschaver (2010). + written by Joris Vankerschaver (2010) and modified by Michael Jung (2020). INPUT: @@ -159,18 +166,7 @@ def is_atomic_wedge_latex(expression): False """ - if not isinstance(expression, six.string_types): - raise TypeError("The argument must be a string.") - level = 0 - for n, c in enumerate(expression): - if c == '(': - level += 1 - elif c == ')': - level -= 1 - if c == '\\' and expression[n+1:n+6] == 'wedge': - if level == 0 and n > 0: - return False - return True + return is_atomic(expression, sep=['\\wedge']) def format_mul_txt(name1, operator, name2): diff --git a/src/sage/tensor/modules/free_module_automorphism.py b/src/sage/tensor/modules/free_module_automorphism.py index 1364e5153f0..73de99ffbc0 100644 --- a/src/sage/tensor/modules/free_module_automorphism.py +++ b/src/sage/tensor/modules/free_module_automorphism.py @@ -193,7 +193,7 @@ class FreeModuleAutomorphism(FreeModuleTensor, MultiplicativeGroupElement): or the operator ~, or the exponent -1:: sage: a.inverse() - Automorphism (a)^(-1) of the Rank-2 free module M over the Integer Ring + Automorphism a^(-1) of the Rank-2 free module M over the Integer Ring sage: a.inverse() is ~a True sage: a.inverse() is a^(-1) @@ -357,7 +357,7 @@ def _del_derived(self): sage: a[e,:] = [[1,0,-1], [0,3,0], [0,0,2]] sage: b = a.inverse() sage: a._inverse - Automorphism (a)^(-1) of the 3-dimensional vector space M over the + Automorphism a^(-1) of the 3-dimensional vector space M over the Rational Field sage: a._del_derived() sage: a._inverse # has been reset to None @@ -683,7 +683,7 @@ def __invert__(self): sage: a = M.automorphism(name='a') sage: a[e,:] = [[1,0,0],[0,-1,2],[0,1,-3]] sage: a.inverse() - Automorphism (a)^(-1) of the Rank-3 free module M over the Integer + Automorphism a^(-1) of the Rank-3 free module M over the Integer Ring sage: a.inverse().parent() General linear group of the Rank-3 free module M over the Integer @@ -744,19 +744,37 @@ def __invert__(self): True sage: (a)^(-1)*a == id True + + If the name could cause some confusion, a bracket is added around the + element before taking the inverse:: + + sage: c = M.automorphism(name='a^(-1)*b') + sage: c[e,:] = [[1,0,0],[0,-1,1],[0,2,-1]] + sage: c.inverse() + Automorphism (a^(-1)*b)^(-1) of the Rank-3 free module M over the + Integer Ring + """ from .comp import Components if self._is_identity: return self if self._inverse is None: + from sage.tensor.modules.format_utilities import is_atomic if self._name is None: inv_name = None else: - inv_name = '(' + self._name + ')^(-1)' + if is_atomic(self._name, ['*']): + inv_name = self._name + '^(-1)' + else: + inv_name = '(' + self._name + ')^(-1)' if self._latex_name is None: inv_latex_name = None else: - inv_latex_name = r'\left(' + self._latex_name + r'\right)^{-1}' + if is_atomic(self._latex_name, ['\\circ', '\\otimes']): + inv_latex_name = self._latex_name + r'^{-1}' + else: + inv_latex_name = r'\left(' + self._latex_name + \ + r'\right)^{-1}' fmodule = self._fmodule si = fmodule._sindex nsi = fmodule._rank + si From c7fbb72cab8da51db5c461b0b51b2c686a232d75 Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Thu, 9 Jan 2020 17:30:44 +0100 Subject: [PATCH 069/133] Trac #28973: Small improvement of is_atomic and Python3 compatibility in doctest --- src/sage/tensor/modules/format_utilities.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sage/tensor/modules/format_utilities.py b/src/sage/tensor/modules/format_utilities.py index a98aa455184..d2a3a924b4a 100644 --- a/src/sage/tensor/modules/format_utilities.py +++ b/src/sage/tensor/modules/format_utilities.py @@ -61,9 +61,9 @@ def is_atomic(expr, sep=['+', '-']): False sage: is_atomic("(a*b)", sep=['*']) True - sage: is_atomic("a<>b", sep=['<>']) + sage: is_atomic(r"a<>b", sep=[r'<>']) False - sage: is_atomic("(a<>b)", sep=['<>']) + sage: is_atomic(r"(a<>b)", sep=[r'<>']) True """ @@ -76,9 +76,9 @@ def is_atomic(expr, sep=['+', '-']): level = 0 for n, c in enumerate(expr): if c == '(': - level += 1 + level += 1; continue elif c == ')': - level -= 1 + level -= 1; continue if any(expr[n:n + len(s)] == s for s in sep): if level == 0 and n > 0: return False From 69ee5289141605e9aa6a1c3683d76b59efa50a7d Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Thu, 9 Jan 2020 17:40:28 +0100 Subject: [PATCH 070/133] Trac #28973: No raw string needed --- src/sage/tensor/modules/format_utilities.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/tensor/modules/format_utilities.py b/src/sage/tensor/modules/format_utilities.py index d2a3a924b4a..768a1e7b6a1 100644 --- a/src/sage/tensor/modules/format_utilities.py +++ b/src/sage/tensor/modules/format_utilities.py @@ -61,9 +61,9 @@ def is_atomic(expr, sep=['+', '-']): False sage: is_atomic("(a*b)", sep=['*']) True - sage: is_atomic(r"a<>b", sep=[r'<>']) + sage: is_atomic("a<>b", sep=['<>']) False - sage: is_atomic(r"(a<>b)", sep=[r'<>']) + sage: is_atomic("(a<>b)", sep=['<>']) True """ From 48d84fe66ffa84b4976faf6141813aa27f8aaf80 Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Thu, 9 Jan 2020 17:50:04 +0100 Subject: [PATCH 071/133] Trac #28973: Automorphism fields adapted to new code --- .../differentiable/automorphismfield.py | 22 +++++++++++++------ .../differentiable/automorphismfield_group.py | 4 ++-- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/src/sage/manifolds/differentiable/automorphismfield.py b/src/sage/manifolds/differentiable/automorphismfield.py index 965fe1fef4c..9ef53c66739 100644 --- a/src/sage/manifolds/differentiable/automorphismfield.py +++ b/src/sage/manifolds/differentiable/automorphismfield.py @@ -123,9 +123,9 @@ class AutomorphismField(TensorField): Field of tangent-space automorphisms a^(-1) on the 2-dimensional differentiable manifold M sage: ia.display(eU) - (a)^(-1) = d/dx*dx - 1/2*x d/dx*dy + 1/2 d/dy*dy + a^(-1) = d/dx*dx - 1/2*x d/dx*dy + 1/2 d/dy*dy sage: ia.display(eV) - (a)^(-1) = (-1/8*u - 1/8*v + 3/4) d/du*du + (1/8*u + 1/8*v + 1/4) d/du*dv + a^(-1) = (-1/8*u - 1/8*v + 3/4) d/du*du + (1/8*u + 1/8*v + 1/4) d/du*dv + (-1/8*u - 1/8*v + 1/4) d/dv*du + (1/8*u + 1/8*v + 3/4) d/dv*dv Equivalently, one can use the power minus one to get the inverse:: @@ -946,10 +946,10 @@ class AutomorphismFieldParal(FreeModuleAutomorphism, TensorFieldParal): The inverse automorphism is obtained via the method :meth:`inverse`:: sage: inv = rot.inverse() ; inv - Field of tangent-space automorphisms (R)^(-1) on the 2-dimensional + Field of tangent-space automorphisms R^(-1) on the 2-dimensional differentiable manifold R^2 sage: latex(inv) - \left(R\right)^{-1} + R sage: inv[:] [1/2*sqrt(3) 1/2] [ -1/2 1/2*sqrt(3)] @@ -1130,7 +1130,7 @@ def __invert__(self): sage: X. = M.chart() sage: a = M.automorphism_field([[0, 2], [-1, 0]], name='a') sage: b = a.inverse(); b - Field of tangent-space automorphisms (a)^(-1) on the 2-dimensional + Field of tangent-space automorphisms a^(-1) on the 2-dimensional differentiable manifold M sage: b[:] [ 0 -1] @@ -1162,14 +1162,22 @@ def __invert__(self): if self._is_identity: return self if self._inverse is None: + from sage.tensor.modules.format_utilities import is_atomic if self._name is None: inv_name = None else: - inv_name = '(' + self._name + ')^(-1)' + if is_atomic(self._name, ['*']): + inv_name = self._name + '^(-1)' + else: + inv_name = '(' + self._name + ')^(-1)' if self._latex_name is None: inv_latex_name = None else: - inv_latex_name = r'\left(' + self._latex_name + r'\right)^{-1}' + if is_atomic(self._latex_name, ['\\circ', '\\otimes']): + inv_latex_name = self._latex_name + r'^{-1}' + else: + inv_latex_name = r'\left(' + self._latex_name + \ + r'\right)^{-1}' fmodule = self._fmodule si = fmodule._sindex ; nsi = fmodule._rank + si self._inverse = fmodule.automorphism(name=inv_name, diff --git a/src/sage/manifolds/differentiable/automorphismfield_group.py b/src/sage/manifolds/differentiable/automorphismfield_group.py index e3204e80f36..4cc248e67dd 100644 --- a/src/sage/manifolds/differentiable/automorphismfield_group.py +++ b/src/sage/manifolds/differentiable/automorphismfield_group.py @@ -537,10 +537,10 @@ class AutomorphismFieldParalGroup(FreeModuleLinearGroup): sage: t1.display() t = (e^y + 1) d/dx*dx + x*y d/dx*dy + (x^2 + 1) d/dy*dy sage: t1^(-1) - Field of tangent-space automorphisms (t)^(-1) on the 2-dimensional + Field of tangent-space automorphisms t^(-1) on the 2-dimensional differentiable manifold M sage: (t1^(-1)).display() - (t)^(-1) = 1/(e^y + 1) d/dx*dx - x*y/(x^2 + (x^2 + 1)*e^y + 1) d/dx*dy + t^(-1) = 1/(e^y + 1) d/dx*dx - x*y/(x^2 + (x^2 + 1)*e^y + 1) d/dx*dy + 1/(x^2 + 1) d/dy*dy Since any automorphism field can be considered as a tensor field of From 8dfc58ca566b16b68eba5a174d714ec7bba32add Mon Sep 17 00:00:00 2001 From: "Martin R. Albrecht" Date: Thu, 9 Jan 2020 20:23:43 +0000 Subject: [PATCH 072/133] update to fplll 5.3.2 --- build/pkgs/fplll/checksums.ini | 6 +++--- build/pkgs/fplll/package-version.txt | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/build/pkgs/fplll/checksums.ini b/build/pkgs/fplll/checksums.ini index dd08acd0fa1..371a327766d 100644 --- a/build/pkgs/fplll/checksums.ini +++ b/build/pkgs/fplll/checksums.ini @@ -1,4 +1,4 @@ tarball=fplll-VERSION.tar.gz -sha1=4169d6094f8722df73bdbe43c0ccc54d38bbd1f1 -md5=9da76b18f8cc551d42e70192c9582d03 -cksum=3051787648 +sha1=67b70f4dcbb835025abce879b9acb4500e2f1d2c +md5=e72082af9084c5b2d427977c9b79a602 +cksum=65319984 diff --git a/build/pkgs/fplll/package-version.txt b/build/pkgs/fplll/package-version.txt index c7cb1311a64..84197c89467 100644 --- a/build/pkgs/fplll/package-version.txt +++ b/build/pkgs/fplll/package-version.txt @@ -1 +1 @@ -5.3.1 +5.3.2 From 1e9cb8148150e2110e159166649aacf39f8ef5e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Thu, 9 Jan 2020 21:28:24 +0100 Subject: [PATCH 073/133] return is not a function --- src/sage/calculus/desolvers.py | 12 +++++----- src/sage/categories/magmas.py | 2 +- src/sage/combinat/alternating_sign_matrix.py | 4 ++-- .../cluster_algebra_quiver/cluster_seed.py | 4 ++-- src/sage/combinat/finite_state_machine.py | 7 +++--- src/sage/graphs/strongly_regular_db.pyx | 3 ++- src/sage/quadratic_forms/genera/genus.py | 5 ++-- src/sage/quadratic_forms/ternary.pyx | 5 ++-- src/sage/repl/display/fancy_repr.py | 2 +- src/sage/rings/padics/misc.py | 2 +- .../rings/polynomial/polynomial_element.pyx | 24 +++++++++++-------- src/sage/rings/qqbar.py | 2 +- src/sage/schemes/affine/affine_morphism.py | 4 ++-- src/sage/schemes/affine/affine_point.py | 13 +++++----- src/sage/schemes/affine/affine_space.py | 6 ++--- src/sage/schemes/affine/affine_subscheme.py | 8 +++---- src/sage/schemes/curves/curve.py | 2 +- src/sage/schemes/generic/morphism.py | 8 +++---- src/sage/schemes/generic/scheme.py | 2 +- .../schemes/product_projective/morphism.py | 10 ++++---- .../schemes/projective/projective_morphism.py | 10 ++++---- .../schemes/projective/projective_point.py | 12 +++++----- .../schemes/projective/projective_space.py | 5 ++-- .../projective/projective_subscheme.py | 8 +++---- src/sage/structure/element.pyx | 6 ++--- src/sage/symbolic/relation.py | 11 ++++----- 26 files changed, 92 insertions(+), 85 deletions(-) diff --git a/src/sage/calculus/desolvers.py b/src/sage/calculus/desolvers.py index 43a81bd4a8d..c945229ba9f 100644 --- a/src/sage/calculus/desolvers.py +++ b/src/sage/calculus/desolvers.py @@ -1243,13 +1243,13 @@ def desolve_rk4_determine_bounds(ics,end_points=None): """ if end_points is None: - return((ics[0],ics[0]+10)) - if not isinstance(end_points,list): - end_points=[end_points] - if len(end_points)==1: - return (min(ics[0],end_points[0]),max(ics[0],end_points[0])) + return (ics[0], ics[0] + 10) + if not isinstance(end_points, list): + end_points = [end_points] + if len(end_points) == 1: + return (min(ics[0], end_points[0]), max(ics[0], end_points[0])) else: - return (min(ics[0],end_points[0]),max(ics[0],end_points[1])) + return (min(ics[0], end_points[0]), max(ics[0], end_points[1])) def desolve_rk4(de, dvar, ics=None, ivar=None, end_points=None, step=0.1, output='list', **kwds): diff --git a/src/sage/categories/magmas.py b/src/sage/categories/magmas.py index ed71a2c1e9d..5efcf5b3973 100644 --- a/src/sage/categories/magmas.py +++ b/src/sage/categories/magmas.py @@ -758,7 +758,7 @@ def one(self): sage: PvW0.one() 1 """ - return(self(self.realization_of().a_realization().one())) + return self(self.realization_of().a_realization().one()) class ParentMethods: diff --git a/src/sage/combinat/alternating_sign_matrix.py b/src/sage/combinat/alternating_sign_matrix.py index 571bad916a9..9ff0b58199e 100644 --- a/src/sage/combinat/alternating_sign_matrix.py +++ b/src/sage/combinat/alternating_sign_matrix.py @@ -752,7 +752,7 @@ def ASM_compatible_bigger(self): for k in range(len(output)): output[k] = M.from_height_function(output[k]/2) - return(output) + return output def ASM_compatible_smaller(self): r""" @@ -809,7 +809,7 @@ def ASM_compatible_smaller(self): output.append(d) for k in range(len(output)): output[k] = M.from_height_function((output[k]-matrix.ones(n,n))/2) - return(output) + return output @combinatorial_map(name='to Dyck word') def to_dyck_word(self, algorithm): diff --git a/src/sage/combinat/cluster_algebra_quiver/cluster_seed.py b/src/sage/combinat/cluster_algebra_quiver/cluster_seed.py index 79f582b0f6f..fcb53e3ac3e 100644 --- a/src/sage/combinat/cluster_algebra_quiver/cluster_seed.py +++ b/src/sage/combinat/cluster_algebra_quiver/cluster_seed.py @@ -4122,7 +4122,7 @@ def greedy(self, a1, a2, algorithm='by_recursion'): for q in range(max(a1, 0)+1): if p != 0 or q != 0: ans += self._R(coeff_recurs(p, q, a1, a2, b, c))*self.x(0)**(b*p-a1)*self.x(1)**(c*q-a2) - return(ans) + return ans elif algorithm == 'by_combinatorics': if b == 0: S = ClusterSeed([['A', 1], ['A', 1]]) @@ -4153,7 +4153,7 @@ def greedy(self, a1, a2, algorithm='by_recursion'): for q in range(max(a1, 0)+1): if p != 0 or q != 0: ans += coeff_recurs(p, q, a1, a2, b, c) - return(ans) + return ans else: raise ValueError("The third input should be 'by_recursion', " "'by_combinatorics', or 'just_numbers'.") diff --git a/src/sage/combinat/finite_state_machine.py b/src/sage/combinat/finite_state_machine.py index 0f932830332..0d74e8a6531 100644 --- a/src/sage/combinat/finite_state_machine.py +++ b/src/sage/combinat/finite_state_machine.py @@ -6907,7 +6907,7 @@ def add_from_transition_function(self, function, initial_states=None, ....: final_states=[1], ....: input_alphabet=[0]) sage: def transition_function(state, letter): - ....: return(1-state, []) + ....: return (1 - state, []) sage: F.add_from_transition_function(transition_function) sage: F.transitions() [Transition from 0 to 1: 0|-, @@ -6921,7 +6921,7 @@ def add_from_transition_function(self, function, initial_states=None, ....: final_states=[1], ....: input_alphabet=[0]) sage: def transition_function(state, letter): - ....: return(1-state, []) + ....: return (1 - state, []) sage: F.add_from_transition_function(transition_function, ....: explore_existing_states=False) sage: F.transitions() @@ -10031,8 +10031,7 @@ def predecessors(self, state, valid_input=None): open.extend(candidates) unhandeled_direct_predecessors[s] = None done.append(s) - return(done) - + return done def number_of_words(self, variable=var('n'), base_ring=None): diff --git a/src/sage/graphs/strongly_regular_db.pyx b/src/sage/graphs/strongly_regular_db.pyx index 3d890a3602e..df555342b74 100644 --- a/src/sage/graphs/strongly_regular_db.pyx +++ b/src/sage/graphs/strongly_regular_db.pyx @@ -1488,9 +1488,10 @@ def is_twograph_descendant_of_srg(int v, int k0, int l, int mu): g = strongly_regular_graph(vv, k, l - 2*mu + k) return twograph_descendant(g, next(g.vertex_iterator()), name=True) - return(la, v + 1) + return (la, v + 1) return + @cached_function def is_taylor_twograph_srg(int v,int k,int l,int mu): r""" diff --git a/src/sage/quadratic_forms/genera/genus.py b/src/sage/quadratic_forms/genera/genus.py index bce8d99640e..f7e24930a75 100644 --- a/src/sage/quadratic_forms/genera/genus.py +++ b/src/sage/quadratic_forms/genera/genus.py @@ -111,7 +111,8 @@ def genera(sig_pair, determinant, max_scale=None, even=False): genera.append(G) # render the output deterministic for testing genera.sort(key=lambda x: [s.symbol_tuple_list() for s in x.local_symbols()]) - return(genera) + return genera + def _local_genera(p, rank, det_val, max_scale, even): r""" @@ -210,7 +211,7 @@ def _local_genera(p, rank, det_val, max_scale, even): # each equivalence class if not g1 in symbols: symbols.append(g1) - return(symbols) + return symbols def _blocks(b, even_only=False): diff --git a/src/sage/quadratic_forms/ternary.pyx b/src/sage/quadratic_forms/ternary.pyx index ec7a00e0919..b4344fa67ea 100644 --- a/src/sage/quadratic_forms/ternary.pyx +++ b/src/sage/quadratic_forms/ternary.pyx @@ -248,7 +248,8 @@ def _reduced_ternary_form_eisenstein_with_matrix(a1, a2, a3, a23, a13, a12): M*=matrix(ZZ,3,[0,-1,0,-1,0,0,0,0,-1]) [a13,a23]=[a23,a13] - return((a1,a2,a3,a23,a13,a12),M) + return ((a1, a2, a3, a23, a13, a12), M) + def _reduced_ternary_form_eisenstein_without_matrix(a1, a2, a3, a23, a13, a12): """ @@ -416,7 +417,7 @@ def _reduced_ternary_form_eisenstein_without_matrix(a1, a2, a3, a23, a13, a12): if a1 == a2 and abs(a23) > abs(a13): [a13,a23]=[a23,a13] - return((a1,a2,a3,a23,a13,a12)) + return ((a1, a2, a3, a23, a13, a12)) def primitivize(long long v0, long long v1, long long v2, p): diff --git a/src/sage/repl/display/fancy_repr.py b/src/sage/repl/display/fancy_repr.py index 818498fbaec..b33a3064ed9 100644 --- a/src/sage/repl/display/fancy_repr.py +++ b/src/sage/repl/display/fancy_repr.py @@ -43,7 +43,7 @@ def __repr__(self): sage: ObjectReprABC() ObjectReprABC pretty printer """ - return('{0} pretty printer'.format(self.__class__.__name__)) + return '{0} pretty printer'.format(self.__class__.__name__) def __call__(self, obj, p, cycle): r""" diff --git a/src/sage/rings/padics/misc.py b/src/sage/rings/padics/misc.py index def3b8d177d..3a6fba87e5e 100644 --- a/src/sage/rings/padics/misc.py +++ b/src/sage/rings/padics/misc.py @@ -138,7 +138,7 @@ def gauss_sum(a, p, f, prec=20, factored=False, algorithm='pari', parent=None): a = (a*p) % (q-1) s = sum(a.digits(base=p)) if factored: - return(s, out) + return (s, out) X = PolynomialRing(R, name='X').gen() pi = R.ext(X**(p - 1) + p, names='pi').gen() out *= pi**s diff --git a/src/sage/rings/polynomial/polynomial_element.pyx b/src/sage/rings/polynomial/polynomial_element.pyx index a5a6f2bdfae..1368e8a97e7 100644 --- a/src/sage/rings/polynomial/polynomial_element.pyx +++ b/src/sage/rings/polynomial/polynomial_element.pyx @@ -7988,10 +7988,12 @@ cdef class Polynomial(CommutativeAlgebraElement): [a,b], counted without multiplicity. The endpoints a, b default to -Infinity, Infinity (which are also valid input values). - Calls the PARI routine polsturm. Note that as of version 2.8, PARI - includes the left endpoint of the interval (and no longer uses - Sturm's algorithm on exact inputs). polsturm requires a polynomial - with real coefficients; in case PARI returns an error, we try again + Calls the PARI routine :pari:`polsturm`. + + Note that as of version 2.8, PARI includes the left endpoint + of the interval (and no longer uses Sturm's algorithm on exact + inputs). polsturm requires a polynomial with real + coefficients; in case PARI returns an error, we try again after taking the GCD of `self` with its complex conjugate. EXAMPLES:: @@ -8030,7 +8032,7 @@ cdef class Polynomial(CommutativeAlgebraElement): 3 """ - pol = self // self.gcd(self.derivative()) #squarefree part + pol = self // self.gcd(self.derivative()) # squarefree part if a is None: a1 = -infinity.infinity else: @@ -8040,12 +8042,12 @@ cdef class Polynomial(CommutativeAlgebraElement): else: b1 = b try: - return(pari(pol).polsturm([a1,b1])) + return pari(pol).polsturm([a1, b1]) except PariError: # Take GCD with the conjugate, to extract the maximum factor # with real coefficients. pol2 = pol.gcd(pol.map_coefficients(lambda z: z.conjugate())) - return(pari(pol2).polsturm([a1,b1])) + return pari(pol2).polsturm([a1, b1]) def number_of_real_roots(self): r""" @@ -8092,7 +8094,7 @@ cdef class Polynomial(CommutativeAlgebraElement): True """ pol = self // self.gcd(self.derivative()) - return(pol.number_of_roots_in_interval(a,b) == pol.degree()) + return pol.number_of_roots_in_interval(a, b) == pol.degree() def is_real_rooted(self): r""" @@ -9663,9 +9665,11 @@ cdef class Polynomial(CommutativeAlgebraElement): # stable under squaring. This factor is constant if and only if # the original polynomial has no cyclotomic factor. while True: - if pol1.is_constant(): return(False) + if pol1.is_constant(): + return False pol2 = pol1.gcd(polRing((pol1*pol1(-x)).list()[::2])) - if pol1.degree() == pol2.degree(): return(True) + if pol1.degree() == pol2.degree(): + return True pol1 = pol2 def homogenize(self, var='h'): diff --git a/src/sage/rings/qqbar.py b/src/sage/rings/qqbar.py index 9c6ec027d09..14a9bcf0b97 100644 --- a/src/sage/rings/qqbar.py +++ b/src/sage/rings/qqbar.py @@ -1604,7 +1604,7 @@ def gens(self): sage: QQbar.gens() (I,) """ - return(QQbar_I, ) + return (QQbar_I,) def gen(self, n=0): r""" diff --git a/src/sage/schemes/affine/affine_morphism.py b/src/sage/schemes/affine/affine_morphism.py index 79e7f08c995..a3b8232866a 100644 --- a/src/sage/schemes/affine/affine_morphism.py +++ b/src/sage/schemes/affine/affine_morphism.py @@ -564,7 +564,7 @@ def homogenize(self, n): pass d = max([F[i].degree() for i in range(M+1)]) F = [F[i].homogenize(str(newvar))*newvar**(d-F[i].degree()) for i in range(M+1)] - return(H(F)) + return H(F) def as_dynamical_system(self): """ @@ -872,7 +872,7 @@ def weil_restriction(self): result = R.ideal(self._polys).weil_restriction().gens() H = Hom(DS.weil_restriction(), self.codomain().weil_restriction()) - return(H(result)) + return H(result) def reduce_base_field(self): """ diff --git a/src/sage/schemes/affine/affine_point.py b/src/sage/schemes/affine/affine_point.py index 080509beb78..64d98fe0974 100644 --- a/src/sage/schemes/affine/affine_point.py +++ b/src/sage/schemes/affine/affine_point.py @@ -210,9 +210,9 @@ def global_height(self, prec=None): else: R = RealField(prec) H = max([self[i].abs() for i in range(self.codomain().ambient_space().dimension_relative())]) - return(R(max(H,1)).log()) + return R(max(H,1)).log() if self.domain().base_ring() in _NumberFields or is_NumberFieldOrder(self.domain().base_ring()): - return(max([self[i].global_height(prec) for i in range(self.codomain().ambient_space().dimension_relative())])) + return max([self[i].global_height(prec) for i in range(self.codomain().ambient_space().dimension_relative())]) else: raise NotImplementedError("must be over a number field or a number field Order") @@ -244,7 +244,8 @@ def homogenize(self, n): True """ phi = self.codomain().projective_embedding(n) - return(phi(self)) + return phi(self) + class SchemeMorphism_point_affine_field(SchemeMorphism_point_affine): @@ -318,7 +319,7 @@ def weil_restriction(self): if L.is_finite(): d = L.degree() if d == 1: - return(self) + return self newP = [] for t in self: c = t.polynomial().coefficients(sparse=False) @@ -327,7 +328,7 @@ def weil_restriction(self): else: d = L.relative_degree() if d == 1: - return(self) + return self #create a CoordinateFunction that gets the relative coordinates in terms of powers from sage.rings.number_field.number_field_element import CoordinateFunction v = L.gen() @@ -343,7 +344,7 @@ def weil_restriction(self): newP = [] for t in self: newP += p(t) - return(WR(newP)) + return WR(newP) def intersection_multiplicity(self, X): r""" diff --git a/src/sage/schemes/affine/affine_space.py b/src/sage/schemes/affine/affine_space.py index 8d23562a7d1..9a836781ab4 100644 --- a/src/sage/schemes/affine/affine_space.py +++ b/src/sage/schemes/affine/affine_space.py @@ -2,13 +2,13 @@ Affine `n` space over a ring """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2006 William Stein # # Distributed under the terms of the GNU General Public License (GPL) # # https://www.gnu.org/licenses/ -#***************************************************************************** +# **************************************************************************** from __future__ import print_function from six import integer_types @@ -760,7 +760,7 @@ def projective_embedding(self, i=None, PP=None): #assume that if you've passed in a new codomain you want to override #the existing embedding if PP is None or phi.codomain() == PP: - return(phi) + return phi except AttributeError: self.__projective_embedding = {} except KeyError: diff --git a/src/sage/schemes/affine/affine_subscheme.py b/src/sage/schemes/affine/affine_subscheme.py index 820b4a0ecd2..5957ab489a3 100644 --- a/src/sage/schemes/affine/affine_subscheme.py +++ b/src/sage/schemes/affine/affine_subscheme.py @@ -7,15 +7,15 @@ - Ben Hutz (2013): affine subschemes """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2005 William Stein # Copyright (C) 2013 Ben Hutz # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** from sage.categories.fields import Fields from sage.interfaces.all import singular @@ -231,7 +231,7 @@ def projective_embedding(self, i=None, PP=None): #assume that if you've passed in a new ambient projective space #you want to override the existing embedding if PP is None or phi.codomain().ambient_space() == PP: - return(phi) + return phi except AttributeError: self.__projective_embedding = {} except KeyError: diff --git a/src/sage/schemes/curves/curve.py b/src/sage/schemes/curves/curve.py index fcd9b2e6f1d..1cb012aa3f8 100644 --- a/src/sage/schemes/curves/curve.py +++ b/src/sage/schemes/curves/curve.py @@ -466,4 +466,4 @@ def change_ring(self, R): """ new_AS = self.ambient_space().change_ring(R) I = [f.change_ring(R) for f in self.defining_polynomials()] - return(new_AS.curve(I)) + return new_AS.curve(I) diff --git a/src/sage/schemes/generic/morphism.py b/src/sage/schemes/generic/morphism.py index cda5e68d735..722dc71cab0 100644 --- a/src/sage/schemes/generic/morphism.py +++ b/src/sage/schemes/generic/morphism.py @@ -1229,7 +1229,7 @@ def base_ring(self): sage: f.base_ring() Multivariate Polynomial Ring in t over Integer Ring """ - return(self.domain().base_ring()) + return self.domain().base_ring() def coordinate_ring(self): r""" @@ -1258,7 +1258,7 @@ def coordinate_ring(self): Multivariate Polynomial Ring in x, y over Multivariate Polynomial Ring in t over Integer Ring """ - return(self._polys[0].parent()) + return self._polys[0].parent() def change_ring(self, R, check=True): r""" @@ -1935,7 +1935,7 @@ def change_ring(self, R, check=True): """ S = self.codomain().change_ring(R) Q = [R(t) for t in self] - return(S.point(Q, check=check)) + return S.point(Q, check=check) def __copy__(self): r""" @@ -1955,7 +1955,7 @@ def __copy__(self): sage: Q2 == Q True """ - return(self._codomain.point(self._coords, check=False)) + return self._codomain.point(self._coords, check=False) def specialization(self, D=None, phi=None, ambient=None): r""" diff --git a/src/sage/schemes/generic/scheme.py b/src/sage/schemes/generic/scheme.py index a50d866cdc2..cca2f261d73 100644 --- a/src/sage/schemes/generic/scheme.py +++ b/src/sage/schemes/generic/scheme.py @@ -693,7 +693,7 @@ def count_points(self, n): F1, psi = F.extension(i, map=True) S1 = self.change_ring(psi) a.append(len(S1.rational_points())) - return(a) + return a def zeta_function(self): r""" diff --git a/src/sage/schemes/product_projective/morphism.py b/src/sage/schemes/product_projective/morphism.py index 88d5ee84466..61908d9b363 100644 --- a/src/sage/schemes/product_projective/morphism.py +++ b/src/sage/schemes/product_projective/morphism.py @@ -12,14 +12,14 @@ Defn: Defined by sending (x : y , u : v) to (x^2*u : y^2*v , x*v^2 : y*u^2). """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2014 Ben Hutz # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** from sage.schemes.generic.morphism import SchemeMorphism_polynomial from sage.categories.fields import Fields from sage.categories.number_fields import NumberFields @@ -144,7 +144,7 @@ def __getitem__(self, i): sage: F[2] z^2*u """ - return(self._polys[i]) + return self._polys[i] def _repr_defn(self): r""" @@ -234,7 +234,7 @@ def __call__(self, P, check=True): A = self.codomain() Q = list(P) newP = [f(Q) for f in self.defining_polynomials()] - return(A.point(newP, check)) + return A.point(newP, check) def __eq__(self, right): """ diff --git a/src/sage/schemes/projective/projective_morphism.py b/src/sage/schemes/projective/projective_morphism.py index e5af0f495f9..1c94e986f3e 100644 --- a/src/sage/schemes/projective/projective_morphism.py +++ b/src/sage/schemes/projective/projective_morphism.py @@ -965,7 +965,7 @@ def degree(self): sage: f.degree() 2 """ - return(self._polys[0].degree()) + return self._polys[0].degree() def dehomogenize(self, n): r""" @@ -1241,7 +1241,7 @@ def global_height(self, prec=None): C = f[i].coefficients() h = max([c.global_height(prec) for c in C]) H = max(H, h) - return(H) + return H def local_height(self, v, prec=None): r""" @@ -1372,7 +1372,7 @@ def wronskian_ideal(self): N = dom.dimension_relative()+1 R = dom.coordinate_ring() J = jacobian(self.defining_polynomials(),dom.gens()) - return(R.ideal(J.minors(N))) + return R.ideal(J.minors(N)) class SchemeMorphism_polynomial_projective_space_field(SchemeMorphism_polynomial_projective_space): @@ -1505,11 +1505,11 @@ def rational_preimages(self, Q, k=1): """ k = ZZ(k) if k <= 0: - raise ValueError("k (=%s) must be a positive integer"%(k)) + raise ValueError("k (=%s) must be a positive integer" % k) #first check if subscheme from sage.schemes.projective.projective_subscheme import AlgebraicScheme_subscheme_projective if isinstance(Q, AlgebraicScheme_subscheme_projective): - return(Q.preimage(self, k)) + return Q.preimage(self, k) #else assume a point BR = self.base_ring() diff --git a/src/sage/schemes/projective/projective_point.py b/src/sage/schemes/projective/projective_point.py index 2d0ae5b9f39..399e995a045 100644 --- a/src/sage/schemes/projective/projective_point.py +++ b/src/sage/schemes/projective/projective_point.py @@ -660,10 +660,10 @@ def dehomogenize(self,n): PS = self.codomain() A = PS.affine_patch(n) Q = [] - for i in range(0,PS.ambient_space().dimension_relative()+1): - if i !=n: - Q.append(self[i]/self[n]) - return(A.point(Q)) + for i in range(PS.ambient_space().dimension_relative() + 1): + if i != n: + Q.append(self[i] / self[n]) + return A.point(Q) def global_height(self, prec=None): r""" @@ -723,7 +723,7 @@ def global_height(self, prec=None): P = self._number_field_from_algebraics() except TypeError: raise TypeError("must be defined over an algebraic field") - return(max([P[i].global_height(prec=prec) for i in range(self.codomain().ambient_space().dimension_relative()+1)])) + return max([P[i].global_height(prec=prec) for i in range(self.codomain().ambient_space().dimension_relative()+1)]) def local_height(self, v, prec=None): r""" @@ -1185,7 +1185,7 @@ def _number_field_from_algebraics(self): P = [ psi(p) for p in P ] # The elements of P were elements of K_pre from sage.schemes.projective.projective_space import ProjectiveSpace PS = ProjectiveSpace(K,self.codomain().dimension_relative(),'z') - return(PS(P)) + return PS(P) def clear_denominators(self): r""" diff --git a/src/sage/schemes/projective/projective_space.py b/src/sage/schemes/projective/projective_space.py index ca8407020f6..1a0d1c2e3bd 100644 --- a/src/sage/schemes/projective/projective_space.py +++ b/src/sage/schemes/projective/projective_space.py @@ -1018,7 +1018,7 @@ def affine_patch(self, i, AA=None): #assume that if you've passed in a new affine space you want to override #the existing patch if AA is None or A == AA: - return(A) + return A except AttributeError: self.__affine_patches = {} except KeyError: @@ -1851,7 +1851,8 @@ def rational_points_dictionary(self): P[j] = zero j += 1 i -= 1 - return(D) + return D + class ProjectiveSpace_rational_field(ProjectiveSpace_field): def rational_points(self, bound=0): diff --git a/src/sage/schemes/projective/projective_subscheme.py b/src/sage/schemes/projective/projective_subscheme.py index 126e471739c..7a22576d870 100644 --- a/src/sage/schemes/projective/projective_subscheme.py +++ b/src/sage/schemes/projective/projective_subscheme.py @@ -521,7 +521,7 @@ def orbit(self, f, N): if N[0] < 0 or N[1] < 0: raise TypeError("orbit bounds must be non-negative") if N[0] > N[1]: - return([]) + return [] Q = self for i in range(1, N[0]+1): @@ -531,7 +531,7 @@ def orbit(self, f, N): for i in range(N[0]+1, N[1]+1): Q = f(Q) Orb.append(Q) - return(Orb) + return Orb def nth_iterate(self, f, n): r""" @@ -781,7 +781,7 @@ def _forward_image(self, f, check = True): v = G[i].variables() if all(Rvars[j] not in v for j in range(n)): newL.append(psi(G[i])) - return(codom.subscheme(newL)) + return codom.subscheme(newL) def preimage(self, f, k=1, check=True): r""" @@ -903,7 +903,7 @@ def preimage(self, f, k=1, check=True): else: F = f dict = {R.gen(i): F[i] for i in range(codom.dimension_relative()+1)} - return(dom.subscheme([t.subs(dict) for t in self.defining_polynomials()])) + return dom.subscheme([t.subs(dict) for t in self.defining_polynomials()]) def dual(self): r""" diff --git a/src/sage/structure/element.pyx b/src/sage/structure/element.pyx index fe7b8fdec93..e453277b6ed 100644 --- a/src/sage/structure/element.pyx +++ b/src/sage/structure/element.pyx @@ -1038,15 +1038,15 @@ cdef class Element(SageObject): def _cache_key(self): """ - Provide a hashable key for an element if it is not hashable + Provide a hashable key for an element if it is not hashable. EXAMPLES:: - sage: a=sage.structure.element.Element(ZZ) + sage: a = sage.structure.element.Element(ZZ) sage: a._cache_key() (Integer Ring, 'Generic element of a structure') """ - return(self.parent(),str(self)) + return (self.parent(), str(self)) #################################################################### # In a Cython or a Python class, you must define either _cmp_ diff --git a/src/sage/symbolic/relation.py b/src/sage/symbolic/relation.py index d7938e515b4..0121570ee7b 100644 --- a/src/sage/symbolic/relation.py +++ b/src/sage/symbolic/relation.py @@ -1242,11 +1242,11 @@ def _solve_expression(f, x, explicit_solutions, multiplicities, return sympy_set_to_list(ret, sympy_vars) else: try: - return(solve_ineq(f)) # trying solve_ineq_univar + return solve_ineq(f) # trying solve_ineq_univar except Exception: pass try: - return(solve_ineq([f])) # trying solve_ineq_fourier + return solve_ineq([f]) # trying solve_ineq_fourier except Exception: raise NotImplementedError("solving only implemented for equalities and few special inequalities, see solve_ineq") ex = f @@ -1809,7 +1809,6 @@ def solve_ineq(ineq, vars=None): - Robert Marik (01-2010) """ - if isinstance(ineq,list): - return(solve_ineq_fourier(ineq, vars)) - else: - return(solve_ineq_univar(ineq)) + if isinstance(ineq, list): + return solve_ineq_fourier(ineq, vars) + return solve_ineq_univar(ineq) From 012fa27eaf29452a878688630933875378dadfd4 Mon Sep 17 00:00:00 2001 From: Vincent Delecroix <20100.delecroix@gmail.com> Date: Thu, 9 Jan 2020 22:49:18 +0100 Subject: [PATCH 074/133] some fix in documentation --- src/sage/groups/libgap_mixin.py | 2 +- src/sage/groups/libgap_wrapper.pyx | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/sage/groups/libgap_mixin.py b/src/sage/groups/libgap_mixin.py index 12edc2dca32..0770a2bb29d 100644 --- a/src/sage/groups/libgap_mixin.py +++ b/src/sage/groups/libgap_mixin.py @@ -89,7 +89,7 @@ def is_nilpotent(self): def is_solvable(self): r""" - Return whether this group is nilpotent. + Return whether this group is solvable. EXAMPLES:: diff --git a/src/sage/groups/libgap_wrapper.pyx b/src/sage/groups/libgap_wrapper.pyx index 6d4fbec9e8a..7082a755996 100644 --- a/src/sage/groups/libgap_wrapper.pyx +++ b/src/sage/groups/libgap_wrapper.pyx @@ -717,10 +717,10 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): sage: from sage.groups.libgap_group import GroupLibGAP sage: G = GroupLibGAP(libgap.GL(2, 3)) sage: a,b = G.gens() - sage: print(a.order(), b.order()) - 2 3 - sage: print(a.multiplicative_order(), b.multiplicative_order()) - 2 3 + sage: print(a.order()) + 2 + sage: print(a.multiplicative_order()) + 2 sage: z = Mod(0, 3) sage: o = Mod(1, 3) From 0bbdcdf6ff51ee22a6d52aba8369282c851182bc Mon Sep 17 00:00:00 2001 From: "John H. Palmieri" Date: Thu, 9 Jan 2020 16:44:34 -0800 Subject: [PATCH 075/133] trac 28979: change "high mem" to "memlimit" --- src/bin/sage-runtests | 4 ++-- src/sage/doctest/reporting.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/bin/sage-runtests b/src/bin/sage-runtests index f23c185f22a..4f8eb29ebcc 100755 --- a/src/bin/sage-runtests +++ b/src/bin/sage-runtests @@ -46,8 +46,8 @@ if __name__ == "__main__": parser.add_option("-m", "--memlimit", type=int, default=3300, help='maximum virtual memory to allow each test ' 'process, in megabytes; no limit if zero or less, ' - 'but tests tagged "high mem" are skipped if no limit ' - 'is set (default: 3300 MB)') + 'but tests tagged "optional - memlimit" are ' + 'skipped if no limit is set (default: 3300 MB)') parser.add_option("-a", "--all", action="store_true", default=False, help="test all files in the Sage library") parser.add_option("--logfile", metavar="FILE", help="log all output to FILE") parser.add_option("--sagenb", action="store_true", default=False, help="test all files from the Sage notebook sources") diff --git a/src/sage/doctest/reporting.py b/src/sage/doctest/reporting.py index 5518953f9c9..60571e9044e 100644 --- a/src/sage/doctest/reporting.py +++ b/src/sage/doctest/reporting.py @@ -483,10 +483,10 @@ def report(self, source, timeout, return_code, results, output, pid=None): if not self.controller.options.long: if self.controller.options.show_skipped: log(" %s not run"%(count_noun(nskipped, "long test"))) - elif tag == "high_mem": + elif tag == "memlimit": if self.controller.options.memlimit <= 0: seen_other = True - log(" %s not run"%(count_noun(nskipped, "high mem"))) + log(" %s not run"%(count_noun(nskipped, "memlimit"))) elif tag == "not tested": if self.controller.options.show_skipped: log(" %s not run"%(count_noun(nskipped, "not tested test"))) From cbce48b86ad3934fcddf1e2a590234087b73ece5 Mon Sep 17 00:00:00 2001 From: Vincent Delecroix <20100.delecroix@gmail.com> Date: Fri, 10 Jan 2020 14:22:37 +0100 Subject: [PATCH 076/133] super solvable -> supersolvable --- src/sage/groups/libgap_mixin.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sage/groups/libgap_mixin.py b/src/sage/groups/libgap_mixin.py index 0770a2bb29d..2f26f83d39e 100644 --- a/src/sage/groups/libgap_mixin.py +++ b/src/sage/groups/libgap_mixin.py @@ -101,16 +101,16 @@ def is_solvable(self): """ return self.gap().IsSolvableGroup().sage() - def is_super_solvable(self): + def is_supersolvable(self): r""" - Return whether this group is super solvable. + Return whether this group is supersolvable. EXAMPLES:: sage: from sage.groups.libgap_group import GroupLibGAP - sage: GroupLibGAP(libgap.SymmetricGroup(3)).is_super_solvable() + sage: GroupLibGAP(libgap.SymmetricGroup(3)).is_supersolvable() True - sage: GroupLibGAP(libgap.SymmetricGroup(4)).is_super_solvable() + sage: GroupLibGAP(libgap.SymmetricGroup(4)).is_supersolvable() False """ return self.gap().IsSupersolvableGroup().sage() From 387130d1b28722a6c795fa65a7993b22e4ce6caa Mon Sep 17 00:00:00 2001 From: Vincent Delecroix <20100.delecroix@gmail.com> Date: Fri, 10 Jan 2020 14:22:43 +0100 Subject: [PATCH 077/133] documentation --- src/sage/groups/libgap_mixin.py | 11 ++++++----- src/sage/groups/libgap_wrapper.pyx | 12 ++++++------ 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/sage/groups/libgap_mixin.py b/src/sage/groups/libgap_mixin.py index 2f26f83d39e..16417aea5e0 100644 --- a/src/sage/groups/libgap_mixin.py +++ b/src/sage/groups/libgap_mixin.py @@ -52,11 +52,12 @@ def __contains__(self, elt): def is_abelian(self): r""" - Test whether the group is Abelian. + Return whether the group is Abelian. OUTPUT: - Boolean. ``True`` if this group is an Abelian group. + Boolean. ``True`` if this group is an Abelian group and ``False`` + otherwise. EXAMPLES:: @@ -473,7 +474,7 @@ def irreducible_characters(self): def character(self, values): r""" - Returns a group character from ``values``, where ``values`` is + Return a group character from ``values``, where ``values`` is a list of the values of the character evaluated on the conjugacy classes. @@ -503,7 +504,7 @@ def character(self, values): def trivial_character(self): r""" - Returns the trivial character of this group. + Return the trivial character of this group. OUTPUT: a group character @@ -526,7 +527,7 @@ def trivial_character(self): def character_table(self): r""" - Returns the matrix of values of the irreducible characters of this + Return the matrix of values of the irreducible characters of this group `G` at its conjugacy classes. The columns represent the conjugacy classes of diff --git a/src/sage/groups/libgap_wrapper.pyx b/src/sage/groups/libgap_wrapper.pyx index 7082a755996..a259eecf0ab 100644 --- a/src/sage/groups/libgap_wrapper.pyx +++ b/src/sage/groups/libgap_wrapper.pyx @@ -262,7 +262,7 @@ class ParentLibGAP(SageObject): def gap(self): """ - Returns the gap representation of self + Return the gap representation of self. OUTPUT: @@ -323,7 +323,7 @@ class ParentLibGAP(SageObject): def _repr_(self): """ - Return a string representation + Return a string representation. OUTPUT: @@ -341,7 +341,7 @@ class ParentLibGAP(SageObject): @cached_method def gens(self): """ - Returns the generators of the group. + Return the generators of the group. EXAMPLES:: @@ -398,7 +398,7 @@ class ParentLibGAP(SageObject): @cached_method def one(self): """ - Returns the identity element of self + Return the identity element of self. EXAMPLES:: @@ -414,7 +414,7 @@ class ParentLibGAP(SageObject): def _an_element_(self): """ - Returns an element of self. + Return an element of self. EXAMPLES:: @@ -480,7 +480,7 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): cpdef GapElement gap(self): """ - Returns a LibGAP representation of the element + Return a LibGAP representation of the element. OUTPUT: From dfa32fcecc9366ced8015da239812f9f7b4555fb Mon Sep 17 00:00:00 2001 From: Jonathan Kliem Date: Mon, 28 Oct 2019 11:57:36 +0100 Subject: [PATCH 078/133] added simplicity and simpliciality to CombinatorialPolyhedron --- .../combinatorial_polyhedron/base.pxd | 2 + .../combinatorial_polyhedron/base.pyx | 141 ++++++++++++++++++ 2 files changed, 143 insertions(+) diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd index 57ff89c2499..c795e9196ac 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd @@ -8,6 +8,8 @@ from .polyhedron_face_lattice cimport PolyhedronFaceLattice @cython.final cdef class CombinatorialPolyhedron(SageObject): + cdef public dict __cached_methods + # Do not assume any of those attributes to be initialized, use the corresponding methods instead. cdef tuple _Vrep # the names of VRep, if they exist cdef tuple _facet_names # the names of HRep without equalities, if they exist diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx index 9971320c8cf..0e3a3b3f701 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx @@ -97,6 +97,7 @@ from .conversions \ incidence_matrix_to_bit_repr_of_Vrepr, \ facets_tuple_to_bit_repr_of_facets, \ facets_tuple_to_bit_repr_of_Vrepr +from sage.misc.cachefunc import cached_method from sage.rings.integer cimport smallInteger from cysignals.signals cimport sig_check, sig_block, sig_unblock @@ -1241,6 +1242,146 @@ cdef class CombinatorialPolyhedron(SageObject): f_vector.set_immutable() return f_vector + @cached_method + def simpliciality(self): + r""" + Return the largest `k` such that the polytope is `k`-simplicial. + + Return the dimension in case of a simplex. + + A polytope is `k`-simplicial, if every `k`-face is a simplex. + + EXAMPLES:: + + sage: cyclic = polytopes.cyclic_polytope(10,4) + sage: CombinatorialPolyhedron(cyclic).simpliciality() + 3 + + sage: hypersimplex = polytopes.hypersimplex(5,2) + sage: CombinatorialPolyhedron(hypersimplex).simpliciality() + 2 + + sage: cross = polytopes.cross_polytope(4) + sage: P = cross.join(cross) + sage: CombinatorialPolyhedron(P).simpliciality() + 3 + + sage: P = polytopes.simplex(3) + sage: CombinatorialPolyhedron(P).simpliciality() + 3 + + sage: P = polytopes.simplex(1) + sage: CombinatorialPolyhedron(P).simpliciality() + 1 + + TESTS:: + + sage: P = polytopes.cube() + sage: C = CombinatorialPolyhedron(P) + sage: C.simpliciality is C.simpliciality + True + """ + if not self.is_bounded(): + raise NotImplementedError("must be bounded") + cdef FaceIterator face_iter = self._face_iter(False, -2) + cdef int d + cdef int dim = self.dimension() + + if self.n_facets() == self.dimension() + 1: + # A simplex. + return self.dimension() + + cdef simpliciality = dim - 1 + + # For each face in the iterator, check if its a simplex. + face_iter.lowest_dimension = 2 # every 1-face is a simplex + d = face_iter.next_dimension() + while (d < dim): + sig_check() + if face_iter.length_atom_repr() == d + 1: + # The current face is a simplex. + face_iter.ignore_subfaces() + else: + # Current face is not a simplex. + if simpliciality > d - 1: + simpliciality = d - 1 + d = face_iter.next_dimension() + if simpliciality == 1: + # Every polytope is 1-simplicial. + d = dim + return smallInteger(simpliciality) + + @cached_method + def simplicity(self): + r""" + Return the largest `k` such that the polytope is `k`-simple. + + Return the dimension in case of a simplex. + + A polytope `P` is `k`-simple, if for every face `F` + of codimension `k` the polytope `P/F` is simple. + + Equivalently it is `k`-simple if the polar/dual polytope is `k`-simplicial. + + EXAMPLES:: + + sage: hyper4 = polytopes.hypersimplex(4,2) + sage: CombinatorialPolyhedron(hyper4).simplicity() + 1 + + sage: hyper5 = polytopes.hypersimplex(5,2) + sage: CombinatorialPolyhedron(hyper5).simplicity() + 2 + + sage: hyper6 = polytopes.hypersimplex(6,2) + sage: CombinatorialPolyhedron(hyper6).simplicity() + 3 + + sage: P = polytopes.simplex(3) + sage: CombinatorialPolyhedron(P).simplicity() + 3 + + sage: P = polytopes.simplex(1) + sage: CombinatorialPolyhedron(P).simplicity() + 1 + + TESTS:: + + sage: P = polytopes.cube() + sage: C = CombinatorialPolyhedron(P) + sage: C.simplicity is C.simplicity + True + """ + if not self.is_bounded(): + raise NotImplementedError("must be bounded") + cdef FaceIterator face_iter = self._face_iter(True, -2) + cdef int d + cdef int dim = self.dimension() + + if self.n_facets() == self.dimension() + 1: + # A simplex. + return self.dimension() + + cdef simplicity = dim - 1 + + # For each coface in the iterator, check if its a simplex. + face_iter.lowest_dimension = 2 # every coface of dimension 1 is a simplex + d = face_iter.next_dimension() + while (d < dim): + sig_check() + if face_iter.length_atom_repr() == d + 1: + # The current face is a simplex. + face_iter.ignore_supfaces() + else: + # Current coface is not a simplex. + if simplicity > d - 1: + simplicity = d - 1 + d = face_iter.next_dimension() + if simplicity == 1: + # Every polytope is 1-simple. + d = dim + return smallInteger(simplicity) + def face_iter(self, dimension=None, dual=None): r""" Iterator over all proper faces of specified dimension. From e47a1440dd18e8498992f97e0baaf9db9488f295 Mon Sep 17 00:00:00 2001 From: Jonathan Kliem Date: Fri, 13 Dec 2019 13:59:25 +0100 Subject: [PATCH 079/133] took into account the changes from #28614 --- .../geometry/polyhedron/combinatorial_polyhedron/base.pyx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx index 0e3a3b3f701..513fe5340b3 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx @@ -1298,7 +1298,7 @@ cdef class CombinatorialPolyhedron(SageObject): d = face_iter.next_dimension() while (d < dim): sig_check() - if face_iter.length_atom_repr() == d + 1: + if face_iter.n_atom_rep() == d + 1: # The current face is a simplex. face_iter.ignore_subfaces() else: @@ -1369,7 +1369,7 @@ cdef class CombinatorialPolyhedron(SageObject): d = face_iter.next_dimension() while (d < dim): sig_check() - if face_iter.length_atom_repr() == d + 1: + if face_iter.n_atom_rep() == d + 1: # The current face is a simplex. face_iter.ignore_supfaces() else: From a19efd6f63db32799d27aa6af2b7b20c08fbf022 Mon Sep 17 00:00:00 2001 From: Jonathan Kliem Date: Fri, 10 Jan 2020 14:50:22 +0100 Subject: [PATCH 080/133] small changes improving readibilty of code --- .../combinatorial_polyhedron/base.pyx | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx index 513fe5340b3..ca8ccba5b2a 100644 --- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx +++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pyx @@ -1318,8 +1318,8 @@ cdef class CombinatorialPolyhedron(SageObject): Return the dimension in case of a simplex. - A polytope `P` is `k`-simple, if for every face `F` - of codimension `k` the polytope `P/F` is simple. + A polytope `P` is `k`-simple, if every `(d-1-k)`-face + is contained in exactly `k+1` facets of `P` for `1 <= k <= d-1`. Equivalently it is `k`-simple if the polar/dual polytope is `k`-simplicial. @@ -1354,7 +1354,7 @@ cdef class CombinatorialPolyhedron(SageObject): """ if not self.is_bounded(): raise NotImplementedError("must be bounded") - cdef FaceIterator face_iter = self._face_iter(True, -2) + cdef FaceIterator coface_iter = self._face_iter(True, -2) cdef int d cdef int dim = self.dimension() @@ -1365,18 +1365,18 @@ cdef class CombinatorialPolyhedron(SageObject): cdef simplicity = dim - 1 # For each coface in the iterator, check if its a simplex. - face_iter.lowest_dimension = 2 # every coface of dimension 1 is a simplex - d = face_iter.next_dimension() + coface_iter.lowest_dimension = 2 # every coface of dimension 1 is a simplex + d = coface_iter.next_dimension() while (d < dim): sig_check() - if face_iter.n_atom_rep() == d + 1: - # The current face is a simplex. - face_iter.ignore_supfaces() + if coface_iter.n_atom_rep() == d + 1: + # The current coface is a simplex. + coface_iter.ignore_supfaces() else: # Current coface is not a simplex. if simplicity > d - 1: simplicity = d - 1 - d = face_iter.next_dimension() + d = coface_iter.next_dimension() if simplicity == 1: # Every polytope is 1-simple. d = dim From 6ec12145efe1c98087737497075fc54dd978a66e Mon Sep 17 00:00:00 2001 From: Matthias Koeppe Date: Fri, 10 Jan 2020 22:20:52 -0500 Subject: [PATCH 081/133] build/pkgs/gfan/spkg-configure.m4: New --- build/pkgs/gfan/spkg-configure.m4 | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 build/pkgs/gfan/spkg-configure.m4 diff --git a/build/pkgs/gfan/spkg-configure.m4 b/build/pkgs/gfan/spkg-configure.m4 new file mode 100644 index 00000000000..aec11130f67 --- /dev/null +++ b/build/pkgs/gfan/spkg-configure.m4 @@ -0,0 +1,14 @@ +SAGE_SPKG_CONFIGURE( + [gfan], [ + AC_CACHE_CHECK([for gfan >= 0.6.2], [ac_cv_path_GFAN], [ + AC_PATH_PROGS_FEATURE_CHECK([GFAN_VERSION], [gfan_version], [ + gfan_version=`$ac_path_GFAN_VERSION | $SED -n '/^gfan/s/gfan//p'` + AS_IF([test -n "$gfan_version"], [ + AX_COMPARE_VERSION([$gfan_version], [ge], [0.6.2], [ + ac_cv_path_GFAN_VERSION="$ac_path_GFAN_VERSION" + ]) + ]) + ]) + ]) + AS_IF([test -z "$ac_cv_path_GFAN_VERSION"], [sage_spkg_install_gfan=yes]) +]) From cb85af7dd50a847760d865ed55aeb6f2989daa52 Mon Sep 17 00:00:00 2001 From: Matthias Koeppe Date: Wed, 25 Dec 2019 11:49:52 -0500 Subject: [PATCH 082/133] build/pkgs/cbc/spkg-configure.m4: New --- build/pkgs/cbc/spkg-configure.m4 | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 build/pkgs/cbc/spkg-configure.m4 diff --git a/build/pkgs/cbc/spkg-configure.m4 b/build/pkgs/cbc/spkg-configure.m4 new file mode 100644 index 00000000000..f2956cdd00f --- /dev/null +++ b/build/pkgs/cbc/spkg-configure.m4 @@ -0,0 +1,4 @@ +SAGE_SPKG_CONFIGURE([cbc], [ + dnl checking with pkg-config + PKG_CHECK_MODULES([CBC], [cbc >= 2.9.4], [], [sage_spkg_install_cbc=yes]) +]) From 2b07cf5ba64c9557c6e6f3f008168886da7e69ad Mon Sep 17 00:00:00 2001 From: Matthias Koeppe Date: Fri, 10 Jan 2020 23:11:26 -0500 Subject: [PATCH 083/133] build/pkgs/cbc/spkg-configure.m4: Add SAGE_SPKG_DEPCHECK --- build/pkgs/cbc/spkg-configure.m4 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/build/pkgs/cbc/spkg-configure.m4 b/build/pkgs/cbc/spkg-configure.m4 index f2956cdd00f..999d4b7497b 100644 --- a/build/pkgs/cbc/spkg-configure.m4 +++ b/build/pkgs/cbc/spkg-configure.m4 @@ -1,4 +1,6 @@ SAGE_SPKG_CONFIGURE([cbc], [ - dnl checking with pkg-config - PKG_CHECK_MODULES([CBC], [cbc >= 2.9.4], [], [sage_spkg_install_cbc=yes]) + SAGE_SPKG_DEPCHECK([atlas openblas zlib bzip2], [ + dnl checking with pkg-config + PKG_CHECK_MODULES([CBC], [cbc >= 2.9.4], [], [sage_spkg_install_cbc=yes]) + ]) ]) From 3518586c9a0f2bdba6ca088942752ed82a2073d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Sat, 11 Jan 2020 08:29:14 +0100 Subject: [PATCH 084/133] trac 28975 reviewer suggestion --- src/sage/calculus/desolvers.py | 6 +++--- src/sage/combinat/finite_state_machine.py | 4 ++-- src/sage/graphs/strongly_regular_db.pyx | 2 +- src/sage/quadratic_forms/ternary.pyx | 4 ++-- src/sage/rings/padics/misc.py | 2 +- src/sage/structure/element.pyx | 2 +- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/sage/calculus/desolvers.py b/src/sage/calculus/desolvers.py index c945229ba9f..6bd78d2524a 100644 --- a/src/sage/calculus/desolvers.py +++ b/src/sage/calculus/desolvers.py @@ -1243,13 +1243,13 @@ def desolve_rk4_determine_bounds(ics,end_points=None): """ if end_points is None: - return (ics[0], ics[0] + 10) + return ics[0], ics[0] + 10 if not isinstance(end_points, list): end_points = [end_points] if len(end_points) == 1: - return (min(ics[0], end_points[0]), max(ics[0], end_points[0])) + return min(ics[0], end_points[0]), max(ics[0], end_points[0]) else: - return (min(ics[0], end_points[0]), max(ics[0], end_points[1])) + return min(ics[0], end_points[0]), max(ics[0], end_points[1]) def desolve_rk4(de, dvar, ics=None, ivar=None, end_points=None, step=0.1, output='list', **kwds): diff --git a/src/sage/combinat/finite_state_machine.py b/src/sage/combinat/finite_state_machine.py index 0d74e8a6531..796571fec00 100644 --- a/src/sage/combinat/finite_state_machine.py +++ b/src/sage/combinat/finite_state_machine.py @@ -6907,7 +6907,7 @@ def add_from_transition_function(self, function, initial_states=None, ....: final_states=[1], ....: input_alphabet=[0]) sage: def transition_function(state, letter): - ....: return (1 - state, []) + ....: return 1 - state, [] sage: F.add_from_transition_function(transition_function) sage: F.transitions() [Transition from 0 to 1: 0|-, @@ -6921,7 +6921,7 @@ def add_from_transition_function(self, function, initial_states=None, ....: final_states=[1], ....: input_alphabet=[0]) sage: def transition_function(state, letter): - ....: return (1 - state, []) + ....: return 1 - state, [] sage: F.add_from_transition_function(transition_function, ....: explore_existing_states=False) sage: F.transitions() diff --git a/src/sage/graphs/strongly_regular_db.pyx b/src/sage/graphs/strongly_regular_db.pyx index df555342b74..7a3d0761e1e 100644 --- a/src/sage/graphs/strongly_regular_db.pyx +++ b/src/sage/graphs/strongly_regular_db.pyx @@ -1488,7 +1488,7 @@ def is_twograph_descendant_of_srg(int v, int k0, int l, int mu): g = strongly_regular_graph(vv, k, l - 2*mu + k) return twograph_descendant(g, next(g.vertex_iterator()), name=True) - return (la, v + 1) + return la, v + 1 return diff --git a/src/sage/quadratic_forms/ternary.pyx b/src/sage/quadratic_forms/ternary.pyx index b4344fa67ea..63b59b82525 100644 --- a/src/sage/quadratic_forms/ternary.pyx +++ b/src/sage/quadratic_forms/ternary.pyx @@ -248,7 +248,7 @@ def _reduced_ternary_form_eisenstein_with_matrix(a1, a2, a3, a23, a13, a12): M*=matrix(ZZ,3,[0,-1,0,-1,0,0,0,0,-1]) [a13,a23]=[a23,a13] - return ((a1, a2, a3, a23, a13, a12), M) + return (a1, a2, a3, a23, a13, a12), M def _reduced_ternary_form_eisenstein_without_matrix(a1, a2, a3, a23, a13, a12): @@ -417,7 +417,7 @@ def _reduced_ternary_form_eisenstein_without_matrix(a1, a2, a3, a23, a13, a12): if a1 == a2 and abs(a23) > abs(a13): [a13,a23]=[a23,a13] - return ((a1, a2, a3, a23, a13, a12)) + return a1, a2, a3, a23, a13, a12 def primitivize(long long v0, long long v1, long long v2, p): diff --git a/src/sage/rings/padics/misc.py b/src/sage/rings/padics/misc.py index 3a6fba87e5e..3bedd534e69 100644 --- a/src/sage/rings/padics/misc.py +++ b/src/sage/rings/padics/misc.py @@ -138,7 +138,7 @@ def gauss_sum(a, p, f, prec=20, factored=False, algorithm='pari', parent=None): a = (a*p) % (q-1) s = sum(a.digits(base=p)) if factored: - return (s, out) + return s, out X = PolynomialRing(R, name='X').gen() pi = R.ext(X**(p - 1) + p, names='pi').gen() out *= pi**s diff --git a/src/sage/structure/element.pyx b/src/sage/structure/element.pyx index e453277b6ed..fbc2c716771 100644 --- a/src/sage/structure/element.pyx +++ b/src/sage/structure/element.pyx @@ -1046,7 +1046,7 @@ cdef class Element(SageObject): sage: a._cache_key() (Integer Ring, 'Generic element of a structure') """ - return (self.parent(), str(self)) + return self.parent(), str(self) #################################################################### # In a Cython or a Python class, you must define either _cmp_ From 6e67c65ba7b81f60f491262335b1d039662f6c90 Mon Sep 17 00:00:00 2001 From: Antonio Rojas Date: Sat, 11 Jan 2020 09:09:55 +0100 Subject: [PATCH 085/133] Support both rpy 2.x and 3.x --- src/sage/interfaces/r.py | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/sage/interfaces/r.py b/src/sage/interfaces/r.py index 6b38a22a58a..2939d46644b 100644 --- a/src/sage/interfaces/r.py +++ b/src/sage/interfaces/r.py @@ -372,8 +372,14 @@ def _setup_r_to_sage_converter(): # expect interface) cv = Converter('r to sage converter') + # support rpy version 2 and 3 + try: + rpy2py = cv.rpy2py + except AttributeError: + rpy2py = cv.ri2py + # fallback - cv.ri2py.register(object, lambda obj: obj) + rpy2py.register(object, lambda obj: obj) def float_to_int_if_possible(f): # First, round the float to at most 15 significant places. @@ -383,7 +389,7 @@ def float_to_int_if_possible(f): # Preserve the behaviour of the old r parser, e.g. return 1 instead of 1.0 float_or_int = int(f) if isinstance(f, int) or f.is_integer() else f return float_or_int - cv.ri2py.register(float, float_to_int_if_possible) + rpy2py.register(float, float_to_int_if_possible) def list_to_singleton_if_possible(l): if len(l) == 1: @@ -395,11 +401,11 @@ def _vector(vec): attrs = vec.list_attrs() # Recursive calls have to be made explicitly # https://bitbucket.org/rpy2/rpy2/issues/363/custom-converters-are-not-applied - data = list_to_singleton_if_possible([ cv.ri2py(val) for val in vec ]) + data = list_to_singleton_if_possible([ rpy2py(val) for val in vec ]) rclass = list(vec.do_slot('class')) if 'class' in attrs else vec.rclass if 'names' in attrs: - # separate names and values, call ri2py recursively to convert elements + # separate names and values, call rpy2py recursively to convert elements names = list_to_singleton_if_possible(list(vec.do_slot('names'))) return { 'DATA': data, @@ -409,7 +415,7 @@ def _vector(vec): else: # if no names are present, convert to a normal list or a single value return data - cv.ri2py.register(SexpVector, _vector) + rpy2py.register(SexpVector, _vector) def _matrix(mat): if 'dim' in mat.list_attrs(): @@ -421,28 +427,28 @@ def _matrix(mat): (nrow, ncol) = dimensions # Since R does it the other way round, we assign transposed and # then transpose the matrix :) - m = matrix(ncol, nrow, [cv.ri2py(i) for i in mat]) + m = matrix(ncol, nrow, [rpy2py(i) for i in mat]) return m.transpose() except TypeError: pass else: return _vector(mat) - cv.ri2py.register(FloatSexpVector, _matrix) + rpy2py.register(FloatSexpVector, _matrix) def _list_vector(vec): # we have a R list (vector of arbitrary elements) attrs = vec.list_attrs() names = vec.do_slot('names') - values = [ cv.ri2py(val) for val in vec ] + values = [ rpy2py(val) for val in vec ] rclass = list(vec.do_slot('class')) if 'class' in attrs else vec.rclass data = zip(names, values) return { 'DATA': dict(data), - '_Names': cv.ri2py(names), + '_Names': rpy2py(names), # We don't give the rclass here because the old expect interface # didn't do that either and we want to maintain compatibility. }; - cv.ri2py.register(ListSexpVector, _list_vector) + rpy2py.register(ListSexpVector, _list_vector) return cv From 05a962dca8867f60dc024fc3e24ba36e06064b34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Sat, 11 Jan 2020 14:14:18 +0100 Subject: [PATCH 086/133] some lgtm fixes in sage_bootstrap and mac-app --- build/sage_bootstrap/app.py | 9 +++------ build/sage_bootstrap/cksum.py | 2 -- build/sage_bootstrap/cmdline.py | 8 +++----- build/sage_bootstrap/compat/__init__.py | 2 +- build/sage_bootstrap/config.py | 9 +++------ build/sage_bootstrap/logger.py | 7 +++---- build/sage_bootstrap/package.py | 6 +++--- build/sage_bootstrap/stdio.py | 9 +++------ build/sage_bootstrap/updater.py | 9 +++------ src/mac-app/tools/createDSStore/mac_alias/alias.py | 4 +--- src/mac-app/tools/createDSStore/mac_alias/bookmark.py | 3 +-- src/mac-app/tools/createDSStore/mac_alias/osx.py | 3 +-- 12 files changed, 25 insertions(+), 46 deletions(-) diff --git a/build/sage_bootstrap/app.py b/build/sage_bootstrap/app.py index 495c7b7e61d..20f5043d201 100644 --- a/build/sage_bootstrap/app.py +++ b/build/sage_bootstrap/app.py @@ -4,29 +4,26 @@ """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2016 Volker Braun # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** import os -import sys import logging log = logging.getLogger() -from sage_bootstrap.env import SAGE_DISTFILES from sage_bootstrap.package import Package from sage_bootstrap.tarball import Tarball from sage_bootstrap.updater import ChecksumUpdater, PackageUpdater from sage_bootstrap.creator import PackageCreator - class Application(object): def config(self): diff --git a/build/sage_bootstrap/cksum.py b/build/sage_bootstrap/cksum.py index eaba1e87619..e44e8241bac 100644 --- a/build/sage_bootstrap/cksum.py +++ b/build/sage_bootstrap/cksum.py @@ -4,8 +4,6 @@ This is a weak checksum, only included for legacy reasons. """ -import sys - # Fun table, e.g. http://www.nco.ncep.noaa.gov/pmb/codes/nwprod/util/sorc/wgrib2.cd/grib2/wgrib2/crc32.c crctab = [ diff --git a/build/sage_bootstrap/cmdline.py b/build/sage_bootstrap/cmdline.py index 9515c61c54c..07925fdec11 100644 --- a/build/sage_bootstrap/cmdline.py +++ b/build/sage_bootstrap/cmdline.py @@ -6,18 +6,16 @@ is also exposed as "sage --package". """ - -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2016 Volker Braun # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** -import os import sys import logging log = logging.getLogger() diff --git a/build/sage_bootstrap/compat/__init__.py b/build/sage_bootstrap/compat/__init__.py index e5c485a1bd7..7fb303e4edc 100644 --- a/build/sage_bootstrap/compat/__init__.py +++ b/build/sage_bootstrap/compat/__init__.py @@ -11,7 +11,7 @@ # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. -# http://www.gnu.org/licenses/ +# https://www.gnu.org/licenses/ #***************************************************************************** diff --git a/build/sage_bootstrap/config.py b/build/sage_bootstrap/config.py index 666411e28ff..b96948d5d33 100644 --- a/build/sage_bootstrap/config.py +++ b/build/sage_bootstrap/config.py @@ -18,20 +18,19 @@ """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2015 Volker Braun # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** import sys import os -import logging LOG_LEVELS = ( @@ -43,8 +42,6 @@ ) - - class Configuration(object): _initialized = False diff --git a/build/sage_bootstrap/logger.py b/build/sage_bootstrap/logger.py index 894aecefd8c..88c19fc4800 100644 --- a/build/sage_bootstrap/logger.py +++ b/build/sage_bootstrap/logger.py @@ -8,18 +8,17 @@ """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2015 Volker Braun # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** import sys -import os import logging logger = logging.getLogger() diff --git a/build/sage_bootstrap/package.py b/build/sage_bootstrap/package.py index aff921299cc..08ed0b4d550 100644 --- a/build/sage_bootstrap/package.py +++ b/build/sage_bootstrap/package.py @@ -3,7 +3,7 @@ Sage Packages """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2015 Volker Braun # # This program is free software: you can redistribute it and/or modify @@ -11,13 +11,13 @@ # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # http://www.gnu.org/licenses/ -#***************************************************************************** +# **************************************************************************** import re import os import logging -from sage_bootstrap.env import SAGE_ROOT, SAGE_DISTFILES +from sage_bootstrap.env import SAGE_ROOT log = logging.getLogger() diff --git a/build/sage_bootstrap/stdio.py b/build/sage_bootstrap/stdio.py index e3984595aba..d4df3f05b84 100644 --- a/build/sage_bootstrap/stdio.py +++ b/build/sage_bootstrap/stdio.py @@ -6,19 +6,16 @@ the terminal. """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2015 Volker Braun # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** - - +# https://www.gnu.org/licenses/ +# **************************************************************************** import sys -import os class UnbufferedStream(object): diff --git a/build/sage_bootstrap/updater.py b/build/sage_bootstrap/updater.py index a24fffa9261..496b579cd37 100644 --- a/build/sage_bootstrap/updater.py +++ b/build/sage_bootstrap/updater.py @@ -3,28 +3,25 @@ Package Updater """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2015 Volker Braun # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** -import re import os import logging log = logging.getLogger() -from sage_bootstrap.env import SAGE_ROOT from sage_bootstrap.package import Package from sage_bootstrap.download import Download - class ChecksumUpdater(object): def __init__(self, package_name): diff --git a/src/mac-app/tools/createDSStore/mac_alias/alias.py b/src/mac-app/tools/createDSStore/mac_alias/alias.py index 512d2221bcb..b984598f1f9 100644 --- a/src/mac-app/tools/createDSStore/mac_alias/alias.py +++ b/src/mac-app/tools/createDSStore/mac_alias/alias.py @@ -5,10 +5,8 @@ import struct import datetime import io -import re import os import os.path -import stat import sys if sys.platform == 'darwin': @@ -19,7 +17,7 @@ except NameError: long = int -from .utils import * +from .utils import mac_epoch ALIAS_KIND_FILE = 0 ALIAS_KIND_FOLDER = 1 diff --git a/src/mac-app/tools/createDSStore/mac_alias/bookmark.py b/src/mac-app/tools/createDSStore/mac_alias/bookmark.py index 0de6b9404b6..37b8f946edc 100644 --- a/src/mac-app/tools/createDSStore/mac_alias/bookmark.py +++ b/src/mac-app/tools/createDSStore/mac_alias/bookmark.py @@ -11,7 +11,6 @@ import datetime import os import sys -import pprint try: from urlparse import urljoin @@ -223,12 +222,12 @@ def absolute(self): if self.base is None: return self.relative else: - base_abs = self.base.absolute return urljoin(self.base.absolute, self.relative) def __repr__(self): return 'URL(%r)' % self.absolute + class Bookmark (object): def __init__(self, tocs=None): if tocs is None: diff --git a/src/mac-app/tools/createDSStore/mac_alias/osx.py b/src/mac-app/tools/createDSStore/mac_alias/osx.py index d4af65d756c..29c2e7a916e 100644 --- a/src/mac-app/tools/createDSStore/mac_alias/osx.py +++ b/src/mac-app/tools/createDSStore/mac_alias/osx.py @@ -2,12 +2,11 @@ from __future__ import unicode_literals from ctypes import * -import struct import os import datetime import uuid -from .utils import * +from .utils import unix_epoch libc = cdll.LoadLibrary('/usr/lib/libc.dylib') From e86ec713a996be9f58eb81d32c21293ac37e1b7b Mon Sep 17 00:00:00 2001 From: Michael Orlitzky Date: Fri, 10 Jan 2020 21:08:01 -0500 Subject: [PATCH 087/133] Trac #28045: spkg-configure.m4 for libatomic_ops. Implement a simple check for libatomic_ops >= 7.6.2 using pkg-config. This suffices to detect all versions of the library available in Gentoo linux. --- build/pkgs/libatomic_ops/spkg-configure.m4 | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 build/pkgs/libatomic_ops/spkg-configure.m4 diff --git a/build/pkgs/libatomic_ops/spkg-configure.m4 b/build/pkgs/libatomic_ops/spkg-configure.m4 new file mode 100644 index 00000000000..e796277cc1e --- /dev/null +++ b/build/pkgs/libatomic_ops/spkg-configure.m4 @@ -0,0 +1,6 @@ +SAGE_SPKG_CONFIGURE([libatomic_ops], [ + PKG_CHECK_MODULES([LIBATOMIC_OPS], + [atomic_ops >= 7.6.2], + [], + [sage_spkg_install_libatomic_ops=yes]) +]) From 74d7935b3f347cc64fa5e0f2037b14f8a233a111 Mon Sep 17 00:00:00 2001 From: Vincent Delecroix <20100.delecroix@gmail.com> Date: Sat, 11 Jan 2020 20:32:40 +0100 Subject: [PATCH 088/133] doctest compatibility with Python 2 --- src/sage/groups/libgap_wrapper.pyx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/groups/libgap_wrapper.pyx b/src/sage/groups/libgap_wrapper.pyx index f586f544f9d..64ecb830e92 100644 --- a/src/sage/groups/libgap_wrapper.pyx +++ b/src/sage/groups/libgap_wrapper.pyx @@ -503,7 +503,7 @@ cdef class ElementLibGAP(MultiplicativeGroupElement): sage: libgap(FreeGroup('a, b').an_element()) a*b sage: type(libgap(FreeGroup('a, b').an_element())) - + """ return self._libgap From 9a3554134e426243c12a6aec7cac9ea71fb1ed97 Mon Sep 17 00:00:00 2001 From: Sebastian Oehms Date: Sun, 12 Jan 2020 08:43:04 +0100 Subject: [PATCH 089/133] 28239: initial version --- .../rings/laurent_series_ring_element.pyx | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/sage/rings/laurent_series_ring_element.pyx b/src/sage/rings/laurent_series_ring_element.pyx index 6c3f176a133..432ccb8bf2e 100644 --- a/src/sage/rings/laurent_series_ring_element.pyx +++ b/src/sage/rings/laurent_series_ring_element.pyx @@ -740,6 +740,14 @@ cdef class LaurentSeries(AlgebraElement): def add_bigoh(self, prec): """ + Return the truncated series at chosen precision ``prec``. + + See also :meth:`O`. + + INPUT: + + - ``prec`` -- the precision of the series as an integer. + EXAMPLES:: sage: R. = LaurentSeriesRing(QQ) @@ -747,11 +755,20 @@ cdef class LaurentSeries(AlgebraElement): t^2 + t^3 + O(t^10) sage: f.add_bigoh(5) t^2 + t^3 + O(t^5) + + TESTS: + + Check that :trac:`28239` is fixed:: + + sage: (t^(-2)).add_bigoh(-1) + t^-2 + O(t^-1) + sage: (t^(-2)).add_bigoh(-3) + O(t^-3) """ if prec == infinity or prec >= self.prec(): return self P = self._parent - if not self: + if not self or prec < self.__n: return type(self)(P, P._power_series_ring(0, prec=0), prec) u = self.__u.add_bigoh(prec - self.__n) return type(self)(P, u, self.__n) @@ -766,6 +783,8 @@ cdef class LaurentSeries(AlgebraElement): the precision of ``self`` and ``prec``. The term `O(q^\text{prec})` is the zero series with precision ``prec``. + See also :meth:`add_bigoh`. + EXAMPLES:: sage: R. = LaurentSeriesRing(QQ) From 5715b690ba1b10c2e68839c42af8c76861ce258c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Sun, 12 Jan 2020 10:06:10 +0100 Subject: [PATCH 090/133] cleaning (from pyflakes) in categories --- src/sage/categories/commutative_rings.py | 5 ++--- src/sage/categories/examples/cw_complexes.py | 11 ++++------- src/sage/categories/examples/graphs.py | 10 ++++------ src/sage/categories/examples/manifolds.py | 10 ++++------ src/sage/categories/pushout.py | 11 +++++------ src/sage/categories/unital_algebras.py | 9 ++++----- src/sage/categories/weyl_groups.py | 1 + 7 files changed, 24 insertions(+), 33 deletions(-) diff --git a/src/sage/categories/commutative_rings.py b/src/sage/categories/commutative_rings.py index 5af5785d7c7..2a1f5a0f7a4 100644 --- a/src/sage/categories/commutative_rings.py +++ b/src/sage/categories/commutative_rings.py @@ -77,10 +77,9 @@ def _test_divides(self, **options): return # 3. divisibility of some elements - S = tester.some_elements() - for a,b in tester.some_elements(repeat=2): + for a, b in tester.some_elements(repeat=2): try: - test = a.divides(a*b) + test = a.divides(a * b) except NotImplementedError: pass else: diff --git a/src/sage/categories/examples/cw_complexes.py b/src/sage/categories/examples/cw_complexes.py index ba59be17bd2..8422fc0a418 100644 --- a/src/sage/categories/examples/cw_complexes.py +++ b/src/sage/categories/examples/cw_complexes.py @@ -1,21 +1,19 @@ """ Examples of CW complexes """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2015 Travis Scrimshaw # # Distributed under the terms of the GNU General Public License (GPL) -# http://www.gnu.org/licenses/ -#****************************************************************************** - +# https://www.gnu.org/licenses/ +# ***************************************************************************** from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.structure.element import Element from sage.categories.cw_complexes import CWComplexes -from sage.rings.integer import Integer -from sage.rings.all import QQ from sage.sets.family import Family + class Surface(UniqueRepresentation, Parent): r""" An example of a CW complex: a (2-dimensional) surface. @@ -161,4 +159,3 @@ def dimension(self): return self._dim Example = Surface - diff --git a/src/sage/categories/examples/graphs.py b/src/sage/categories/examples/graphs.py index 9c1e1eddb7e..21c2d2a150a 100644 --- a/src/sage/categories/examples/graphs.py +++ b/src/sage/categories/examples/graphs.py @@ -1,18 +1,17 @@ """ Examples of graphs """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2015 Travis Scrimshaw # # Distributed under the terms of the GNU General Public License (GPL) -# http://www.gnu.org/licenses/ -#****************************************************************************** - +# https://www.gnu.org/licenses/ +# ***************************************************************************** from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.structure.element_wrapper import ElementWrapper from sage.categories.graphs import Graphs -from sage.rings.all import QQ + class Cycle(UniqueRepresentation, Parent): r""" @@ -119,4 +118,3 @@ def dimension(self): return 1 Example = Cycle - diff --git a/src/sage/categories/examples/manifolds.py b/src/sage/categories/examples/manifolds.py index a71b7cf30e3..e1d7c851202 100644 --- a/src/sage/categories/examples/manifolds.py +++ b/src/sage/categories/examples/manifolds.py @@ -1,18 +1,17 @@ """ Examples of manifolds """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2015 Travis Scrimshaw # # Distributed under the terms of the GNU General Public License (GPL) -# http://www.gnu.org/licenses/ -#****************************************************************************** - +# https://www.gnu.org/licenses/ +# ***************************************************************************** from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.structure.element_wrapper import ElementWrapper from sage.categories.manifolds import Manifolds -from sage.rings.all import QQ + class Plane(UniqueRepresentation, Parent): r""" @@ -91,4 +90,3 @@ def an_element(self): Element = ElementWrapper Example = Plane - diff --git a/src/sage/categories/pushout.py b/src/sage/categories/pushout.py index 0fe756e5259..27e436c6360 100644 --- a/src/sage/categories/pushout.py +++ b/src/sage/categories/pushout.py @@ -1390,10 +1390,11 @@ def __mul__(self, other): othervars = other.vars else: othervars = [other.var] - OverlappingGens = [] ## Generator names of variable names of the MultiPolynomialFunctor - ## that can be interpreted as variables in self - OverlappingVars = [] ## The variable names of the MultiPolynomialFunctor - ## that can be interpreted as variables in self + + OverlappingVars = [] + # The variable names of the MultiPolynomialFunctor + # that can be interpreted as variables in self + RemainingVars = [x for x in othervars] IsOverlap = False BadOverlap = False @@ -1741,7 +1742,6 @@ def _apply_functor(self, R): if self.multi_variate and is_LaurentPolynomialRing(R): return LaurentPolynomialRing(R.base_ring(), (list(R.variable_names()) + [self.var])) else: - from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing return LaurentPolynomialRing(R, self.var) def __eq__(self, other): @@ -2746,7 +2746,6 @@ def _apply_functor(self, R): Quotient of Rational Field by the ideal (1) """ I = self.I - from sage.all import QQ if not I.is_zero(): from sage.categories.fields import Fields if R in Fields(): diff --git a/src/sage/categories/unital_algebras.py b/src/sage/categories/unital_algebras.py index bc2bd4bf03b..ec757ade1e7 100644 --- a/src/sage/categories/unital_algebras.py +++ b/src/sage/categories/unital_algebras.py @@ -1,13 +1,12 @@ r""" Unital algebras """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2011 Nicolas M. Thiery # # Distributed under the terms of the GNU General Public License (GPL) -# http://www.gnu.org/licenses/ -#****************************************************************************** - +# https://www.gnu.org/licenses/ +# ***************************************************************************** from sage.misc.abstract_method import abstract_method from sage.misc.cachefunc import cached_method from sage.misc.lazy_attribute import lazy_attribute @@ -18,9 +17,9 @@ from sage.categories.morphism import SetMorphism from sage.categories.homset import Hom from sage.categories.rings import Rings -from sage.categories.magmas import Magmas from sage.categories.magmatic_algebras import MagmaticAlgebras + class UnitalAlgebras(CategoryWithAxiom_over_base_ring): """ The category of non-associative algebras over a given base ring. diff --git a/src/sage/categories/weyl_groups.py b/src/sage/categories/weyl_groups.py index ec858f557d8..6ea5cf878ea 100644 --- a/src/sage/categories/weyl_groups.py +++ b/src/sage/categories/weyl_groups.py @@ -147,6 +147,7 @@ def pieri_factors(self, *args, **keywords): # Do not remove this line which makes sure the pieri factor # code is properly inserted inside the Cartan Types import sage.combinat.root_system.pieri_factors + assert sage.combinat.root_system.pieri_factors ct = self.cartan_type() if hasattr(ct, "PieriFactors"): return ct.PieriFactors(self, *args, **keywords) From 0a281d4c681540deed490451cd156989b59e894d Mon Sep 17 00:00:00 2001 From: Dima Pasechnik Date: Tue, 7 Jan 2020 18:54:57 +0000 Subject: [PATCH 091/133] spkg-configure for nauty find nauty's programs, with or without "nauty-"-prefix --- build/pkgs/nauty/spkg-configure.m4 | 19 +++++++++++++++++++ src/bin/sage-env-config.in | 2 ++ src/sage/env.py | 1 + 3 files changed, 22 insertions(+) create mode 100644 build/pkgs/nauty/spkg-configure.m4 diff --git a/build/pkgs/nauty/spkg-configure.m4 b/build/pkgs/nauty/spkg-configure.m4 new file mode 100644 index 00000000000..6648afd0876 --- /dev/null +++ b/build/pkgs/nauty/spkg-configure.m4 @@ -0,0 +1,19 @@ +AC_DEFUN([SAGE_TEST_NAUTY_PROGS], [ + m4_foreach([nautyprog], [directg, gentourng, geng, genbg], [ + AC_PATH_PROG([$2]nautyprog, [[$1]nautyprog]) + AS_IF([test x$[$2]nautyprog = x], [sage_spkg_install_nauty=yes]) + ]) + AC_SUBST(SAGE_NAUTY_BINS_PREFIX, ['$1']) +]) +SAGE_SPKG_CONFIGURE([nauty], [ + AC_PATH_PROG([GENGCHECK],[geng]) + AS_IF([test x$GENGCHECK = x], [ + AC_PATH_PROG([GENGnautyCHECK],[nauty-geng]) + AS_IF([test x$GENGnautyCHECK = x], [sage_spkg_install_nauty=yes], + [SAGE_TEST_NAUTY_PROGS(nauty-,nau)]) + ], [SAGE_TEST_NAUTY_PROGS(,foo)]) + ], [], [], [ + AS_IF([test x$sage_spkg_install_nauty = xyes], [ + AC_SUBST(SAGE_NAUTY_BINS_PREFIX, ['']) + ]) +]) diff --git a/src/bin/sage-env-config.in b/src/bin/sage-env-config.in index 487f2c97b0c..4e177c53395 100644 --- a/src/bin/sage-env-config.in +++ b/src/bin/sage-env-config.in @@ -109,3 +109,5 @@ if [ -n "$SAGE_PKG_CONFIG_PATH" ]; then # (Sage's pkgconf spkg takes care of this, if installed) export PKG_CONFIG_PATH="$SAGE_PKG_CONFIG_PATH${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}" fi + +export SAGE_NAUTY_BINS_PREFIX="@SAGE_NAUTY_BINS_PREFIX@" diff --git a/src/sage/env.py b/src/sage/env.py index d8609ad6c99..48fe9616c60 100644 --- a/src/sage/env.py +++ b/src/sage/env.py @@ -187,6 +187,7 @@ def var(key, *fallbacks, **kwds): var('SINGULARPATH', join(SAGE_SHARE, 'singular')) var('PPLPY_DOCS', join(SAGE_SHARE, 'doc', 'pplpy')) var('MAXIMA_FAS') +var('SAGE_NAUTY_BINS_PREFIX') # misc var('SAGE_BANNER', '') From 6c240a75f9cc1967a8340a4f7f1ec957c9181b72 Mon Sep 17 00:00:00 2001 From: Dima Pasechnik Date: Tue, 7 Jan 2020 21:28:26 +0000 Subject: [PATCH 092/133] prefixes for calls to nauty routines, adjust tests --- src/sage/graphs/digraph_generators.py | 5 +++-- src/sage/graphs/graph_generators.py | 9 +++++---- src/sage/graphs/hypergraph_generators.py | 3 ++- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/sage/graphs/digraph_generators.py b/src/sage/graphs/digraph_generators.py index b1f2efdc846..89492161f5b 100644 --- a/src/sage/graphs/digraph_generators.py +++ b/src/sage/graphs/digraph_generators.py @@ -65,6 +65,7 @@ from six.moves import range from six import PY2 from sage.cpython.string import bytes_to_str +from sage.env import SAGE_NAUTY_BINS_PREFIX as nautyprefix import sys from sage.misc.randstate import current_randstate @@ -528,7 +529,7 @@ def tournaments_nauty(self, n, nauty_input += " " + str(n) + " " - sp = subprocess.Popen("gentourng {0}".format(nauty_input), shell=True, + sp = subprocess.Popen(nautyprefix+"gentourng {0}".format(nauty_input), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) @@ -642,7 +643,7 @@ def nauty_directg(self, graphs, options="", debug=False): # Build directg input (graphs6 format) input = ''.join(g.graph6_string()+'\n' for g in graphs) - sub = subprocess.Popen('directg {0}'.format(options), + sub = subprocess.Popen(nautyprefix+'directg {0}'.format(options), shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, diff --git a/src/sage/graphs/graph_generators.py b/src/sage/graphs/graph_generators.py index 14721c7ac6a..a5794c1a6c0 100644 --- a/src/sage/graphs/graph_generators.py +++ b/src/sage/graphs/graph_generators.py @@ -18,6 +18,7 @@ from __future__ import print_function, absolute_import, division from six.moves import range from six import PY2 +from sage.env import SAGE_NAUTY_BINS_PREFIX as nautyprefix import subprocess @@ -899,7 +900,7 @@ def nauty_geng(self, options="", debug=False): sage: gen = graphs.nauty_geng("4", debug=True) sage: print(next(gen)) - >A geng -d0D3 n=4 e=0-6 + >A ...geng -d0D3 n=4 e=0-6 sage: gen = graphs.nauty_geng("4 -q", debug=True) sage: next(gen) '' @@ -913,16 +914,16 @@ def nauty_geng(self, options="", debug=False): ... ValueError: wrong format of parameter option sage: list(graphs.nauty_geng("-c3", debug=True)) - ['>E Usage: geng [-cCmtfbd#D#] [-uygsnh] [-lvq] \n'] + ['>E Usage: ...geng [-cCmtfbd#D#] [-uygsnh] [-lvq] ... sage: list(graphs.nauty_geng("-c 3", debug=True)) - ['>A geng -cd1D2 n=3 e=2-3\n', Graph on 3 vertices, Graph on 3 vertices] + ['>A ...geng -cd1D2 n=3 e=2-3\n', Graph on 3 vertices, Graph on 3 vertices] """ if PY2: enc_kwargs = {} else: enc_kwargs = {'encoding': 'latin-1'} - sp = subprocess.Popen("geng {0}".format(options), shell=True, + sp = subprocess.Popen(nautyprefix+"geng {0}".format(options), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, **enc_kwargs) diff --git a/src/sage/graphs/hypergraph_generators.py b/src/sage/graphs/hypergraph_generators.py index ef36b7294e8..aa3d5e39885 100644 --- a/src/sage/graphs/hypergraph_generators.py +++ b/src/sage/graphs/hypergraph_generators.py @@ -31,6 +31,7 @@ --------------------- """ from __future__ import print_function +from sage.env import SAGE_NAUTY_BINS_PREFIX as nautyprefix class HypergraphGenerators(): r""" @@ -161,7 +162,7 @@ def nauty(self, number_of_sets, number_of_vertices, nauty_input += " " + str(number_of_vertices) + " " + str(number_of_sets) + " " - sp = subprocess.Popen("genbg {0}".format(nauty_input), shell=True, + sp = subprocess.Popen(nautyprefix+"genbg {0}".format(nauty_input), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) From 0c17402e3a28298137b03ed61e129ac512ebfb45 Mon Sep 17 00:00:00 2001 From: Dima Pasechnik Date: Sun, 12 Jan 2020 09:13:19 +0000 Subject: [PATCH 093/133] allow undefined SAGE_NAUTY_BINS_PREFIX --- src/sage/env.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/env.py b/src/sage/env.py index 48fe9616c60..d692e329045 100644 --- a/src/sage/env.py +++ b/src/sage/env.py @@ -187,7 +187,7 @@ def var(key, *fallbacks, **kwds): var('SINGULARPATH', join(SAGE_SHARE, 'singular')) var('PPLPY_DOCS', join(SAGE_SHARE, 'doc', 'pplpy')) var('MAXIMA_FAS') -var('SAGE_NAUTY_BINS_PREFIX') +var('SAGE_NAUTY_BINS_PREFIX', '') # misc var('SAGE_BANNER', '') From 87cd023005a814a14e5fb1785bdd5cc6c267dfda Mon Sep 17 00:00:00 2001 From: Sebastian Oehms Date: Sun, 12 Jan 2020 11:17:23 +0100 Subject: [PATCH 094/133] 28993: initial version --- src/sage/rings/laurent_series_ring.py | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/sage/rings/laurent_series_ring.py b/src/sage/rings/laurent_series_ring.py index 186959eb8dc..0e47af25b00 100644 --- a/src/sage/rings/laurent_series_ring.py +++ b/src/sage/rings/laurent_series_ring.py @@ -34,6 +34,7 @@ from __future__ import print_function, absolute_import from sage.categories.rings import Rings +from sage.rings.infinity import infinity from sage.categories.integral_domains import IntegralDomains from sage.categories.fields import Fields from sage.categories.complete_discrete_valuation import CompleteDiscreteValuationFields @@ -369,7 +370,7 @@ def _repr_(self): s = 'Sparse ' + s return s - def _element_constructor_(self, x, n=0): + def _element_constructor_(self, x, n=0, prec=infinity): r""" Construct a Laurent series from `x`. @@ -379,12 +380,18 @@ def _element_constructor_(self, x, n=0): - ``n`` -- (default: 0) multiply the result by `t^n` + - ``prec`` -- (default: ``infinity``) the precision of the series + as an integer. + + EXAMPLES:: sage: R. = LaurentSeriesRing(Qp(5, 10)) sage: S. = LaurentSeriesRing(RationalField()) sage: R(t + t^2 + O(t^3)) (1 + O(5^10))*u + (1 + O(5^10))*u^2 + O(u^3) + sage: R(t + t^2 + O(t^3), prec=2) + (1 + O(5^10))*u + O(u^2) Note that coercing an element into its own parent just produces that element again (since Laurent series are immutable):: @@ -412,6 +419,12 @@ def _element_constructor_(self, x, n=0): TESTS: + Check that :trac:`28993` is fixed:: + + sage: from sage.modular.etaproducts import qexp_eta + sage: qexp_eta(S, prec=30) + 1 - t - t^2 + t^5 + t^7 - t^12 - t^15 + t^22 + t^26 + O(t^30) + When converting from `R((z))` to `R((z))((w))`, the variable `z` is sent to `z` rather than to `w` (see :trac:`7085`):: @@ -452,7 +465,7 @@ def _element_constructor_(self, x, n=0): P = parent(x) if isinstance(x, self.element_class) and n == 0 and P is self: - return x # ok, since Laurent series are immutable (no need to make a copy) + return x.add_bigoh(prec) # ok, since Laurent series are immutable (no need to make a copy) elif P is self.base_ring(): # Convert x into a power series; if P is itself a Laurent # series ring A((t)), this prevents the implementation of @@ -469,20 +482,20 @@ def _element_constructor_(self, x, n=0): if t == "t_RFRAC": # Rational function x = self(self.polynomial_ring()(x.numerator())) / \ self(self.polynomial_ring()(x.denominator())) - return (x << n) + return (x << n).add_bigoh(prec) elif t == "t_SER": # Laurent series n += x._valp() bigoh = n + x.length() x = self(self.polynomial_ring()(x.Vec())) return (x << n).add_bigoh(bigoh) else: # General case, pretend to be a polynomial - return self(self.polynomial_ring()(x)) << n + return (self(self.polynomial_ring()(x)) << n).add_bigoh(prec) elif (is_FractionFieldElement(x) and (x.base_ring() is self.base_ring() or x.base_ring() == self.base_ring()) and (is_Polynomial(x.numerator()) or is_MPolynomial(x.numerator())) ): x = self(x.numerator()) / self(x.denominator()) - return (x << n) - return self.element_class(self, x, n) + return (x << n).add_bigoh(prec) + return self.element_class(self, x, n).add_bigoh(prec) def construction(self): r""" From dce291f782c440be0536f644ee13a59d9444a37e Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Sun, 12 Jan 2020 17:11:55 +0100 Subject: [PATCH 095/133] Trac #28973: Python3 compatibility and doctest --- src/sage/manifolds/differentiable/automorphismfield.py | 2 +- src/sage/tensor/modules/format_utilities.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/sage/manifolds/differentiable/automorphismfield.py b/src/sage/manifolds/differentiable/automorphismfield.py index 9ef53c66739..0ee55d75c8c 100644 --- a/src/sage/manifolds/differentiable/automorphismfield.py +++ b/src/sage/manifolds/differentiable/automorphismfield.py @@ -949,7 +949,7 @@ class AutomorphismFieldParal(FreeModuleAutomorphism, TensorFieldParal): Field of tangent-space automorphisms R^(-1) on the 2-dimensional differentiable manifold R^2 sage: latex(inv) - R + R^{-1} sage: inv[:] [1/2*sqrt(3) 1/2] [ -1/2 1/2*sqrt(3)] diff --git a/src/sage/tensor/modules/format_utilities.py b/src/sage/tensor/modules/format_utilities.py index 768a1e7b6a1..d2a3a924b4a 100644 --- a/src/sage/tensor/modules/format_utilities.py +++ b/src/sage/tensor/modules/format_utilities.py @@ -61,9 +61,9 @@ def is_atomic(expr, sep=['+', '-']): False sage: is_atomic("(a*b)", sep=['*']) True - sage: is_atomic("a<>b", sep=['<>']) + sage: is_atomic(r"a<>b", sep=[r'<>']) False - sage: is_atomic("(a<>b)", sep=['<>']) + sage: is_atomic(r"(a<>b)", sep=[r'<>']) True """ From 018aea21a235670fc11fedcc714e6167be577897 Mon Sep 17 00:00:00 2001 From: Matthias Koeppe Date: Sun, 12 Jan 2020 12:39:07 -0500 Subject: [PATCH 096/133] Update sage-numerical-backends-gurobi to 9.0.0 --- build/pkgs/sage_numerical_backends_gurobi/checksums.ini | 6 +++--- .../pkgs/sage_numerical_backends_gurobi/package-version.txt | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/build/pkgs/sage_numerical_backends_gurobi/checksums.ini b/build/pkgs/sage_numerical_backends_gurobi/checksums.ini index 5f14b7f8f73..44dbf4cee30 100644 --- a/build/pkgs/sage_numerical_backends_gurobi/checksums.ini +++ b/build/pkgs/sage_numerical_backends_gurobi/checksums.ini @@ -1,4 +1,4 @@ tarball=sage_numerical_backends_gurobi-VERSION.tar.gz -sha1=1a3ea79350cb6bffaff0c785bdb310f4c21475f4 -md5=31e4da1d0538422c370a0149b4da809d -cksum=2128488628 +sha1=64253f735ee6779b6ded809643b455061a105dc4 +md5=3df7d18fe53af89e0a796974a2d788b5 +cksum=3824076545 diff --git a/build/pkgs/sage_numerical_backends_gurobi/package-version.txt b/build/pkgs/sage_numerical_backends_gurobi/package-version.txt index 1700f7be00d..f7ee06693c1 100644 --- a/build/pkgs/sage_numerical_backends_gurobi/package-version.txt +++ b/build/pkgs/sage_numerical_backends_gurobi/package-version.txt @@ -1 +1 @@ -9.0b12 +9.0.0 From 14878d5c2b583966e842214f0b0438921d21516b Mon Sep 17 00:00:00 2001 From: Sebastian Oehms Date: Sun, 12 Jan 2020 19:29:35 +0100 Subject: [PATCH 097/133] 28239: fix according to review --- src/sage/rings/laurent_series_ring_element.pyx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/sage/rings/laurent_series_ring_element.pyx b/src/sage/rings/laurent_series_ring_element.pyx index 432ccb8bf2e..bb6f15703c0 100644 --- a/src/sage/rings/laurent_series_ring_element.pyx +++ b/src/sage/rings/laurent_series_ring_element.pyx @@ -746,7 +746,7 @@ cdef class LaurentSeries(AlgebraElement): INPUT: - - ``prec`` -- the precision of the series as an integer. + - ``prec`` -- the precision of the series as an integer EXAMPLES:: @@ -762,6 +762,8 @@ cdef class LaurentSeries(AlgebraElement): sage: (t^(-2)).add_bigoh(-1) t^-2 + O(t^-1) + sage: (t^(-2)).add_bigoh(-2) + O(t^-2) sage: (t^(-2)).add_bigoh(-3) O(t^-3) """ From 967c51041eeafed08222c0db360ee660e92c1244 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Sun, 12 Jan 2020 10:26:38 +0100 Subject: [PATCH 098/133] little tweak to lgtm yaml config file --- .lgtm.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.lgtm.yml b/.lgtm.yml index 52e5d90b9f0..b0978fd288d 100644 --- a/.lgtm.yml +++ b/.lgtm.yml @@ -2,6 +2,10 @@ queries: - exclude: py/call/wrong-named-class-argument - exclude: py/call/wrong-number-class-arguments - exclude: py/unsafe-cyclic-import +path_classifiers: + imports_only: + - "**/all.py" + - "**/*catalog*.py" extraction: python: python_setup: From 840304928e17abefa37418de9d702090850e06fd Mon Sep 17 00:00:00 2001 From: Michael Jung Date: Sun, 12 Jan 2020 23:06:06 +0100 Subject: [PATCH 099/133] Trac #28973: Doctest improved --- src/sage/tensor/modules/format_utilities.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/tensor/modules/format_utilities.py b/src/sage/tensor/modules/format_utilities.py index d2a3a924b4a..0012b375731 100644 --- a/src/sage/tensor/modules/format_utilities.py +++ b/src/sage/tensor/modules/format_utilities.py @@ -61,9 +61,9 @@ def is_atomic(expr, sep=['+', '-']): False sage: is_atomic("(a*b)", sep=['*']) True - sage: is_atomic(r"a<>b", sep=[r'<>']) + sage: is_atomic("a mod b", sep=['mod']) False - sage: is_atomic(r"(a<>b)", sep=[r'<>']) + sage: is_atomic("(a mod b)", sep=['mod']) True """ From 16a0a75c66a2e05187e174f3336edd525c65bb41 Mon Sep 17 00:00:00 2001 From: "Erik M. Bray" Date: Mon, 13 Jan 2020 13:48:34 +0000 Subject: [PATCH 100/133] Trac #29001: Add workaround for older version of pkg-config that do not include the PKG_CHECK_VAR macro --- m4/sage_spkg_collect.m4 | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/m4/sage_spkg_collect.m4 b/m4/sage_spkg_collect.m4 index 304d1988b15..e6a507b349f 100644 --- a/m4/sage_spkg_collect.m4 +++ b/m4/sage_spkg_collect.m4 @@ -52,6 +52,22 @@ # type which are installed by running a custom script, which may # download additional source files. # + +dnl ========================================================================== +dnl define PKG_CHECK_VAR for old pkg-config < 0.28; see Trac #29001 +m4_ifndef([PKG_CHECK_VAR], [ +AC_DEFUN([PKG_CHECK_VAR], +[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl +AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl + +_PKG_CONFIG([$1], [variable="][$3]["], [$2]) +AS_VAR_COPY([$1], [pkg_cv_][$1]) + +AS_VAR_IF([$1], [""], [$5], [$4])dnl +])dnl PKG_CHECK_VAR +]) +dnl ========================================================================== + AC_DEFUN_ONCE([SAGE_SPKG_COLLECT], [ # Configure all spkgs with configure-time checks m4_include([m4/sage_spkg_configures.m4]) From 854c8990d99a88aac87b06bf385943d4382d0c2f Mon Sep 17 00:00:00 2001 From: "Erik M. Bray" Date: Mon, 13 Jan 2020 15:23:05 +0000 Subject: [PATCH 101/133] Trac #29003: Create generated .pc files in the source tree and install them later instead of creating them directly in SAGE_LOCAL --- build/make/Makefile.in | 5 +++++ build/make/deps | 8 +++++++- build/make/install | 1 + build/pkgs/numpy/dependencies | 2 +- build/pkgs/openblas/spkg-configure.m4 | 6 +++--- src/bin/sage-env | 1 + src/lib/pkgconfig/.gitignore | 4 ++++ 7 files changed, 22 insertions(+), 5 deletions(-) create mode 100644 src/lib/pkgconfig/.gitignore diff --git a/build/make/Makefile.in b/build/make/Makefile.in index eea7ceb7dce..8dbbdb2ece7 100644 --- a/build/make/Makefile.in +++ b/build/make/Makefile.in @@ -35,6 +35,11 @@ PYTHON = python@SAGE_PYTHON_VERSION@ MP_LIBRARY = @SAGE_MP_LIBRARY@ BLAS = @SAGE_BLAS@ +# Because some .pc files are generated at configure time we can't write their +# names explicitly the Makefile, so we use the wildcard function here at make +# runtime +PCFILES = $(subst $(SAGE_SRC),$(SAGE_LOCAL),$(wildcard $(SAGE_SRC)/lib/pkgconfig/*.pc)) + # Files to track installation of packages BUILT_PACKAGES = @SAGE_BUILT_PACKAGES@ DUMMY_PACKAGES = @SAGE_DUMMY_PACKAGES@ diff --git a/build/make/deps b/build/make/deps index f9bc4711ad4..4206edaa524 100644 --- a/build/make/deps +++ b/build/make/deps @@ -174,7 +174,8 @@ sagelib: \ $(inst_six) \ $(inst_symmetrica) \ $(inst_zn_poly) \ - $(EXTCODE) + $(EXTCODE) \ + $(PCFILES) $(AM_V_at)if [ -z "$$SAGE_INSTALL_FETCH_ONLY" ]; then \ cd $(SAGE_SRC) && source bin/sage-env && \ sage-logger -p 'time $(MAKE) sage' '$(SAGE_LOGS)/sagelib-$(SAGE_VERSION).log'; \ @@ -197,6 +198,11 @@ $(SAGE_EXTCODE)/%: $(SAGE_SRC)/ext/% @mkdir -p "$(@D)" $(AM_V_at)cp $< $@ +# Install sage-specific generated .pc files +$(SAGE_PKGCONFIG)/%.pc: $(SAGE_SRC)/lib/pkgconfig/%.pc + @mkdir -p "$(@D)" + $(AM_V_at)cp -P $< $@ + ############################################################################### # Building the documentation diff --git a/build/make/install b/build/make/install index 46267c4278f..70459c0138f 100755 --- a/build/make/install +++ b/build/make/install @@ -17,6 +17,7 @@ fi export SAGE_SHARE="$SAGE_LOCAL/share" export SAGE_EXTCODE="$SAGE_SHARE/sage/ext" +export SAGE_PKGCONFIG="$SAGE_LOCAL/lib/pkgconfig" export SAGE_LOGS="$SAGE_ROOT/logs/pkgs" export SAGE_SPKG_INST="$SAGE_LOCAL/var/lib/sage/installed" . "$SAGE_SRC"/bin/sage-version.sh diff --git a/build/pkgs/numpy/dependencies b/build/pkgs/numpy/dependencies index 62d58ce643a..a9b073c9b51 100644 --- a/build/pkgs/numpy/dependencies +++ b/build/pkgs/numpy/dependencies @@ -1,4 +1,4 @@ -$(PYTHON) $(BLAS) gfortran | setuptools pip pkgconfig cython +$(PYTHON) $(BLAS) $(PCFILES) gfortran | setuptools pip pkgconfig cython ---------- All lines of this file are ignored except the first. diff --git a/build/pkgs/openblas/spkg-configure.m4 b/build/pkgs/openblas/spkg-configure.m4 index d25ace4ea59..dd529fdc32f 100644 --- a/build/pkgs/openblas/spkg-configure.m4 +++ b/build/pkgs/openblas/spkg-configure.m4 @@ -2,9 +2,9 @@ SAGE_SPKG_CONFIGURE([openblas], [ PKG_CHECK_MODULES([OPENBLAS], [openblas >= 0.2.20], [ PKG_CHECK_VAR([OPENBLASPCDIR], [openblas], [pcfiledir], [ AC_CONFIG_LINKS([ - $SAGE_LOCAL/lib/pkgconfig/blas.pc:$OPENBLASPCDIR/openblas.pc - $SAGE_LOCAL/lib/pkgconfig/cblas.pc:$OPENBLASPCDIR/openblas.pc - $SAGE_LOCAL/lib/pkgconfig/lapack.pc:$OPENBLASPCDIR/openblas.pc]) + $SAGE_SRC/lib/pkgconfig/blas.pc:$OPENBLASPCDIR/openblas.pc + $SAGE_SRC/lib/pkgconfig/cblas.pc:$OPENBLASPCDIR/openblas.pc + $SAGE_SRC/lib/pkgconfig/lapack.pc:$OPENBLASPCDIR/openblas.pc]) ], [ AC_MSG_WARN([Unable to locate the directory of openblas.pc. This should not happen!]) sage_spkg_install_openblas=yes diff --git a/src/bin/sage-env b/src/bin/sage-env index 49f29942df0..2a36d09a797 100644 --- a/src/bin/sage-env +++ b/src/bin/sage-env @@ -284,6 +284,7 @@ fi export SAGE_ETC="$SAGE_LOCAL/etc" export SAGE_SHARE="$SAGE_LOCAL/share" export SAGE_EXTCODE="$SAGE_SHARE/sage/ext" +export SAGE_PKGCONFIG="$SAGE_LOCAL/lib/pkgconfig" export SAGE_SPKG_INST="$SAGE_LOCAL/var/lib/sage/installed" export SAGE_SPKG_SCRIPTS="$SAGE_LOCAL/var/lib/sage/scripts" export SAGE_LOGS="$SAGE_ROOT/logs/pkgs" diff --git a/src/lib/pkgconfig/.gitignore b/src/lib/pkgconfig/.gitignore new file mode 100644 index 00000000000..065f153aa9a --- /dev/null +++ b/src/lib/pkgconfig/.gitignore @@ -0,0 +1,4 @@ +# .pc files created at configure time +blas.pc +cblas.pc +lapack.pc From 63179e906d7838772e464a94fb4d44b7de97c77b Mon Sep 17 00:00:00 2001 From: Travis Scrimshaw Date: Tue, 14 Jan 2020 04:41:53 +1000 Subject: [PATCH 102/133] Fixing broken doc link. --- src/sage/algebras/hall_algebra.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/algebras/hall_algebra.py b/src/sage/algebras/hall_algebra.py index 707a90abc12..cbfc5494f1b 100644 --- a/src/sage/algebras/hall_algebra.py +++ b/src/sage/algebras/hall_algebra.py @@ -97,7 +97,7 @@ class HallAlgebra(CombinatorialFreeModule): I_\mu \cdot I_\lambda = \sum_\nu P^{\nu}_{\mu, \lambda}(q) I_\nu, where `P^{\nu}_{\mu, \lambda}` is a Hall polynomial (see - :meth:`~sage.combinat.hall_polynomial.hall_polynomial`). The + :func:`~sage.combinat.hall_polynomial.hall_polynomial`). The unity of this algebra is `I_{\emptyset}`. The (classical) Hall algebra is also known as the Hall-Steinitz From 83b09a76fa78fac7d2f35c4fcd7405e6ad1ecc50 Mon Sep 17 00:00:00 2001 From: Darij Grinberg Date: Mon, 13 Jan 2020 20:06:29 +0100 Subject: [PATCH 103/133] move Element class of gln to a more appropriate superclass --- src/sage/algebras/lie_algebras/classical_lie_algebra.py | 7 +++++-- src/sage/algebras/lie_algebras/lie_algebra.py | 8 ++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/sage/algebras/lie_algebras/classical_lie_algebra.py b/src/sage/algebras/lie_algebras/classical_lie_algebra.py index 1f803d2557a..30e5176fdde 100644 --- a/src/sage/algebras/lie_algebras/classical_lie_algebra.py +++ b/src/sage/algebras/lie_algebras/classical_lie_algebra.py @@ -47,6 +47,9 @@ class ClassicalMatrixLieAlgebra(MatrixLieAlgebraFromAssociative): """ A classical Lie algebra represented using matrices. + This means a classical Lie algebra given as a Lie + algebra of matrices, with commutator as Lie bracket. + INPUT: - ``R`` -- the base ring @@ -166,7 +169,7 @@ def e(self, i): def f(self, i): r""" - Return the generator `f_i`.- + Return the generator `f_i`. EXAMPLES:: @@ -466,7 +469,7 @@ def monomial(self, i): return self.basis()['E_{}_{}'.format(*i)] return self.basis()[i] - class Element(ClassicalMatrixLieAlgebra.Element): + class Element(MatrixLieAlgebraFromAssociative.Element): def monomial_coefficients(self, copy=True): r""" Return the monomial coefficients of ``self``. diff --git a/src/sage/algebras/lie_algebras/lie_algebra.py b/src/sage/algebras/lie_algebras/lie_algebra.py index 0d1dfa1c4bf..a75ab2c3dec 100644 --- a/src/sage/algebras/lie_algebras/lie_algebra.py +++ b/src/sage/algebras/lie_algebras/lie_algebra.py @@ -1500,6 +1500,9 @@ def section(self): class MatrixLieAlgebraFromAssociative(LieAlgebraFromAssociative): """ A Lie algebra constructed from a matrix algebra. + + This means a Lie algebra consisting of matrices, + with commutator as Lie bracket. """ class Element(LieAlgebraMatrixWrapper, LieAlgebraFromAssociative.Element): def matrix(self): @@ -1531,6 +1534,11 @@ def matrix(self): [ 0 0 -1 -1 0] [ 0 0 -1 -1 -1] [ 0 1 0 -2 0] + + sage: gl2 = lie_algebras.gl(QQ, 2) + sage: matrix(gl2.an_element()) + [1 1] + [1 1] """ return self.value From 4a6a94b5fd0812cb3571eaffaf499dc7f39ca1d6 Mon Sep 17 00:00:00 2001 From: Peter Bruin Date: Fri, 10 Jan 2020 18:02:21 +0100 Subject: [PATCH 104/133] Trac 29008: move sage.rings.homset to the new coercion model --- src/sage/categories/modules_with_basis.py | 2 +- src/sage/rings/homset.py | 148 ++++++++-------------- src/sage/rings/morphism.pyx | 6 +- 3 files changed, 59 insertions(+), 97 deletions(-) diff --git a/src/sage/categories/modules_with_basis.py b/src/sage/categories/modules_with_basis.py index 14790bf4b54..7b43e95ad7d 100644 --- a/src/sage/categories/modules_with_basis.py +++ b/src/sage/categories/modules_with_basis.py @@ -1350,7 +1350,7 @@ def coefficient(self, m): Test that ``coefficient`` also works for those parents that do not have an ``element_class``:: - sage: H = End(ZZ) + sage: H = pAdicWeightSpace(3) sage: F = CombinatorialFreeModule(QQ, H) sage: hasattr(H, "element_class") False diff --git a/src/sage/rings/homset.py b/src/sage/rings/homset.py index 6a20fb5217c..93cc41b3661 100644 --- a/src/sage/rings/homset.py +++ b/src/sage/rings/homset.py @@ -65,6 +65,9 @@ class RingHomset_generic(HomsetWithBase): sage: QQ.Hom(ZZ) Set of Homomorphisms from Rational Field to Integer Ring """ + + Element = morphism.RingHomomorphism_im_gens + def __init__(self, R, S, category = None): """ Initialize ``self``. @@ -105,66 +108,23 @@ def has_coerce_map_from(self, x): """ return (x.domain() == self.domain() and x.codomain() == self.codomain()) - def _coerce_impl(self, x): + def _element_constructor_(self, x, check=True, base_map=None): """ - Check to see if we can coerce ``x`` into a homomorphism with the - correct rings. + Construct an element of ``self`` from ``x``. EXAMPLES:: sage: H = Hom(ZZ, QQ) - sage: phi = H([1]) - sage: H2 = Hom(QQ, QQ) - sage: phi2 = H2(phi); phi2 # indirect doctest - Ring endomorphism of Rational Field - Defn: 1 |--> 1 - sage: H(phi2) # indirect doctest + sage: phi = H([1]); phi Ring morphism: From: Integer Ring To: Rational Field Defn: 1 |--> 1 - """ - from sage.categories.map import Map - if not (isinstance(x, Map) and x.category_for().is_subcategory(Rings())): - raise TypeError - if x.parent() is self: - return x - # Case 1: the parent fits - if x.parent() == self: - if isinstance(x, morphism.RingHomomorphism_im_gens): - return morphism.RingHomomorphism_im_gens(self, x.im_gens()) - elif isinstance(x, morphism.RingHomomorphism_cover): - return morphism.RingHomomorphism_cover(self) - elif isinstance(x, morphism.RingHomomorphism_from_base): - return morphism.RingHomomorphism_from_base(self, x.underlying_map()) - # Case 2: unique extension via fraction field - try: - if isinstance(x, morphism.RingHomomorphism_im_gens) and x.domain().fraction_field().has_coerce_map_from(self.domain()): - return morphism.RingHomomorphism_im_gens(self, x.im_gens()) - except Exception: - pass - # Case 3: the homomorphism can be extended by coercion - try: - return x.extend_codomain(self.codomain()).extend_domain(self.domain()) - except Exception: - pass - # Last resort, case 4: the homomorphism is induced from the base ring - if self.domain()==self.domain().base() or self.codomain()==self.codomain().base(): - raise TypeError - try: - x = self.domain().base().Hom(self.codomain().base())(x) - return morphism.RingHomomorphism_from_base(self, x) - except Exception: - raise TypeError - - def __call__(self, im_gens, check=True, base_map=None): - """ - Create a homomorphism. - - EXAMPLES:: - - sage: H = Hom(ZZ, QQ) - sage: H([1]) + sage: H2 = Hom(QQ, QQ) + sage: phi2 = H2(phi); phi2 + Ring endomorphism of Rational Field + Defn: 1 |--> 1 + sage: H(phi2) Ring morphism: From: Integer Ring To: Rational Field @@ -200,12 +160,37 @@ def __call__(self, im_gens, check=True, base_map=None): True """ from sage.categories.map import Map - if isinstance(im_gens, Map): - if base_map is not None: - raise ValueError("Cannot specify base_map when providing a map") - return self._coerce_impl(im_gens) - else: - return morphism.RingHomomorphism_im_gens(self, im_gens, base_map=base_map, check=check) + # Case 0: the homomorphism is given by images of generators + if not (isinstance(x, Map) and x.category_for().is_subcategory(Rings())): + return self.element_class(self, x, base_map=base_map, check=check) + if base_map is not None: + raise ValueError("cannot specify base_map when providing a map") + # Case 1: the parent fits + if x.parent() == self: + if isinstance(x, morphism.RingHomomorphism_im_gens): + return self.element_class(self, x.im_gens()) + elif isinstance(x, morphism.RingHomomorphism_cover): + return morphism.RingHomomorphism_cover(self) + elif isinstance(x, morphism.RingHomomorphism_from_base): + return morphism.RingHomomorphism_from_base(self, x.underlying_map()) + # Case 2: unique extension via fraction field + try: + if (isinstance(x, morphism.RingHomomorphism_im_gens) + and x.domain().fraction_field().has_coerce_map_from(self.domain())): + return self.element_class(self, x.im_gens()) + except (TypeError, ValueError): + pass + # Case 3: the homomorphism can be extended by coercion + try: + return x.extend_codomain(self.codomain()).extend_domain(self.domain()) + except (TypeError, ValueError): + pass + # Case 4: the homomorphism is induced from the base ring + if (self.domain() != self.domain().base() + or self.codomain() != self.codomain().base()): + x = self.domain().base().Hom(self.codomain().base())(x) + return morphism.RingHomomorphism_from_base(self, x) + raise ValueError('cannot convert {} to an element of {}'.format(x, self)) def natural_map(self): """ @@ -289,49 +274,27 @@ class RingHomset_quo_ring(RingHomset_generic): sage: phi == loads(dumps(phi)) True """ - def __call__(self, im_gens, base_map=None, check=True): + + Element = morphism.RingHomomorphism_from_quotient + + def _element_constructor_(self, x, base_map=None, check=True): """ - Create a homomorphism. + Construct an element of ``self`` from ``x``. EXAMPLES:: sage: R. = PolynomialRing(QQ, 2) sage: S. = R.quotient(x^2 + y^2) sage: H = S.Hom(R) - sage: phi = H([b,a]); phi + sage: phi = H([b, a]); phi Ring morphism: From: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2) To: Multivariate Polynomial Ring in x, y over Rational Field Defn: a |--> b b |--> a - - """ - if isinstance(im_gens, morphism.RingHomomorphism_from_quotient): - return morphism.RingHomomorphism_from_quotient(self, im_gens._phi()) - try: - pi = self.domain().cover() - phi = pi.domain().hom(im_gens, base_map=base_map, check=check) - return morphism.RingHomomorphism_from_quotient(self, phi) - except (NotImplementedError, ValueError): - try: - return self._coerce_impl(im_gens) - except TypeError: - raise TypeError("images do not define a valid homomorphism") - - def _coerce_impl(self, x): - """ - Check to see if we can coerce ``x`` into a homomorphism with the - correct rings. - - EXAMPLES:: - - sage: R. = PolynomialRing(QQ, 2) - sage: S. = R.quotient(x^2 + y^2) - sage: H = S.Hom(R) - sage: phi = H([b,a]) sage: R2. = PolynomialRing(ZZ, 2) sage: H2 = Hom(R2, S) - sage: H2(phi) # indirect doctest + sage: H2(phi) Composite map: From: Multivariate Polynomial Ring in x, y over Integer Ring To: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2) @@ -350,10 +313,9 @@ def _coerce_impl(self, x): To: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2) """ - if not isinstance(x, morphism.RingHomomorphism_from_quotient): - raise TypeError - if x.parent() is self: - return x - if x.parent() == self: - return morphism.RingHomomorphism_from_quotient(self, x._phi()) - raise TypeError + if isinstance(x, morphism.RingHomomorphism_from_quotient): + phi = x._phi() + else: + pi = self.domain().cover() + phi = pi.domain().hom(x, base_map=base_map, check=check) + return self.element_class(self, phi) diff --git a/src/sage/rings/morphism.pyx b/src/sage/rings/morphism.pyx index eed78a5015e..66cec959e9d 100644 --- a/src/sage/rings/morphism.pyx +++ b/src/sage/rings/morphism.pyx @@ -1086,7 +1086,7 @@ cdef class RingHomomorphism_im_gens(RingHomomorphism): sage: phi = S.hom([xx+1,xx-1]) Traceback (most recent call last): ... - TypeError: images do not define a valid homomorphism + ValueError: relations do not all (canonically) map to 0 under map determined by images of generators You can give a map of the base ring:: @@ -1119,7 +1119,7 @@ cdef class RingHomomorphism_im_gens(RingHomomorphism): sage: phi = S.hom([xx+1,xx-1], check=False) Traceback (most recent call last): ... - TypeError: images do not define a valid homomorphism + ValueError: relations do not all (canonically) map to 0 under map determined by images of generators """ RingHomomorphism.__init__(self, parent) if not isinstance(im_gens, sage.structure.sequence.Sequence_generic): @@ -1836,7 +1836,7 @@ cdef class RingHomomorphism_from_quotient(RingHomomorphism): sage: S.hom([b^2, c^2, a^2]) Traceback (most recent call last): ... - TypeError: images do not define a valid homomorphism + ValueError: relations do not all (canonically) map to 0 under map determined by images of generators """ def __init__(self, parent, phi): """ From 90e81ad9858910a0ad67727a6cb0fa9f75536ec8 Mon Sep 17 00:00:00 2001 From: "E. Madison Bray" Date: Mon, 13 Jan 2020 16:54:06 +0000 Subject: [PATCH 105/133] Trac #29003: Also output generated gsl.pc to SAGE_SRC --- build/pkgs/gsl/dependencies | 2 +- build/pkgs/gsl/spkg-configure.m4 | 2 +- src/lib/pkgconfig/.gitignore | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/build/pkgs/gsl/dependencies b/build/pkgs/gsl/dependencies index 052eb4373db..a9bcae9fc7f 100644 --- a/build/pkgs/gsl/dependencies +++ b/build/pkgs/gsl/dependencies @@ -1,4 +1,4 @@ -$(BLAS) +$(BLAS) | $(PCFILES) ---------- All lines of this file are ignored except the first. diff --git a/build/pkgs/gsl/spkg-configure.m4 b/build/pkgs/gsl/spkg-configure.m4 index 97d4e44330b..486fd67e867 100644 --- a/build/pkgs/gsl/spkg-configure.m4 +++ b/build/pkgs/gsl/spkg-configure.m4 @@ -6,7 +6,7 @@ SAGE_SPKG_CONFIGURE([gsl], [ AC_CONFIG_COMMANDS([GSLPCPROCESS], [ $SED -e 's/\${GSL_CBLAS_LIB}\ //' \ -e 's/GSL_CBLAS_LIB.*/Requires: cblas/' $GSL_PC \ - > "$SAGE_LOCAL"/lib/pkgconfig/gsl.pc + > "$SAGE_SRC"/lib/pkgconfig/gsl.pc ], [ SED=$ac_cv_path_SED GSL_PC="$GSLPCDIR"/gsl.pc diff --git a/src/lib/pkgconfig/.gitignore b/src/lib/pkgconfig/.gitignore index 065f153aa9a..1b806dad94b 100644 --- a/src/lib/pkgconfig/.gitignore +++ b/src/lib/pkgconfig/.gitignore @@ -1,4 +1,5 @@ # .pc files created at configure time blas.pc cblas.pc +gsl.pc lapack.pc From c7fbc6582240c5b960e56a7d2af0e2bfb8ad3c25 Mon Sep 17 00:00:00 2001 From: "E. Madison Bray" Date: Mon, 13 Jan 2020 17:02:59 +0000 Subject: [PATCH 106/133] Trac #29003: Instead of making individual packages responsible for .pc files being installed, just include them as part of the standard 'toolchain' --- build/make/deps | 2 +- build/pkgs/gsl/dependencies | 2 +- build/pkgs/numpy/dependencies | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/build/make/deps b/build/make/deps index 4206edaa524..d12ae30da24 100644 --- a/build/make/deps +++ b/build/make/deps @@ -64,7 +64,7 @@ download-for-sdist: # TOOLCHAIN consists of dependencies determined by configure. # These are built after the "base" target but before anything else. -toolchain: $(foreach pkgname,$(TOOLCHAIN),$(inst_$(pkgname))) +toolchain: $(foreach pkgname,$(TOOLCHAIN),$(inst_$(pkgname))) $(PCFILES) # Build all packages that GCC links against serially, otherwise this # leads to race conditions where some library which is used by GCC gets diff --git a/build/pkgs/gsl/dependencies b/build/pkgs/gsl/dependencies index a9bcae9fc7f..052eb4373db 100644 --- a/build/pkgs/gsl/dependencies +++ b/build/pkgs/gsl/dependencies @@ -1,4 +1,4 @@ -$(BLAS) | $(PCFILES) +$(BLAS) ---------- All lines of this file are ignored except the first. diff --git a/build/pkgs/numpy/dependencies b/build/pkgs/numpy/dependencies index a9b073c9b51..62d58ce643a 100644 --- a/build/pkgs/numpy/dependencies +++ b/build/pkgs/numpy/dependencies @@ -1,4 +1,4 @@ -$(PYTHON) $(BLAS) $(PCFILES) gfortran | setuptools pip pkgconfig cython +$(PYTHON) $(BLAS) gfortran | setuptools pip pkgconfig cython ---------- All lines of this file are ignored except the first. From 1a66fedd32a9e9a4cb9ecc31c5626087608ce44c Mon Sep 17 00:00:00 2001 From: Peter Bruin Date: Tue, 14 Jan 2020 14:26:44 +0100 Subject: [PATCH 107/133] Trac 29010: split off sage.rings.number_field.homset from sage.rings.number_field.morphism --- src/doc/en/reference/number_fields/index.rst | 1 + src/sage/categories/rings.py | 2 +- src/sage/rings/number_field/homset.py | 580 ++++++++++++++++++ src/sage/rings/number_field/morphism.py | 565 +---------------- src/sage/rings/number_field/number_field.py | 8 +- .../rings/number_field/number_field_rel.py | 4 +- 6 files changed, 598 insertions(+), 562 deletions(-) create mode 100644 src/sage/rings/number_field/homset.py diff --git a/src/doc/en/reference/number_fields/index.rst b/src/doc/en/reference/number_fields/index.rst index 50d71420349..0fecfe43518 100644 --- a/src/doc/en/reference/number_fields/index.rst +++ b/src/doc/en/reference/number_fields/index.rst @@ -24,6 +24,7 @@ Morphisms :maxdepth: 1 sage/rings/number_field/morphism + sage/rings/number_field/homset sage/rings/number_field/number_field_morphisms sage/rings/number_field/maps sage/rings/number_field/structure diff --git a/src/sage/categories/rings.py b/src/sage/categories/rings.py index e8036869add..a8f648277f5 100644 --- a/src/sage/categories/rings.py +++ b/src/sage/categories/rings.py @@ -348,7 +348,7 @@ def _Hom_(self, Y, category): sage: Hom(CyclotomicField(3), QQ, category = Rings()).__class__ - + sage: TestSuite(Hom(QQ, QQ, category = Rings())).run() # indirect doctest diff --git a/src/sage/rings/number_field/homset.py b/src/sage/rings/number_field/homset.py new file mode 100644 index 00000000000..6a42e7b88e4 --- /dev/null +++ b/src/sage/rings/number_field/homset.py @@ -0,0 +1,580 @@ +""" +Sets of homomorphisms between number fields +""" + +#***************************************************************************** +# Copyright (C) 2007 William Stein +# Copyright (C) 2020 Peter Bruin +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# http://www.gnu.org/licenses/ +#***************************************************************************** + +from sage.misc.cachefunc import cached_method +from sage.misc.superseded import deprecation + +from sage.rings.homset import RingHomset_generic +from sage.rings.number_field.morphism import (NumberFieldHomomorphism_im_gens, + RelativeNumberFieldHomomorphism_from_abs, + CyclotomicFieldHomomorphism_im_gens) +from sage.rings.integer import Integer +from sage.rings.finite_rings.integer_mod_ring import Zmod +from sage.structure.sequence import Sequence + + +class NumberFieldHomset(RingHomset_generic): + """ + Set of homomorphisms with domain a given number field. + + TESTS:: + + sage: H = Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'b')) + sage: TestSuite(H).run() + Failure in _test_category: + ... + The following tests failed: _test_elements + """ + def __init__(self, R, S, category=None): + """ + TESTS: + + Check that :trac:`23647` is fixed:: + + sage: K. = NumberField([x^2 - 2, x^2 - 3]) + sage: e, u, v, w = End(K) + sage: e.abs_hom().parent().category() + Category of homsets of number fields + sage: (v*v).abs_hom().parent().category() + Category of homsets of number fields + """ + if category is None: + from sage.categories.all import Fields, NumberFields + if S in NumberFields: + category = NumberFields() + elif S in Fields: + category = Fields() + RingHomset_generic.__init__(self, R, S, category) + + def __call__(self, im_gens, check=True): + """ + Create the homomorphism sending the generators to ``im_gens``. + + EXAMPLES:: + + sage: H = Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'b')) + sage: phi = H([H.domain().gen()]); phi # indirect doctest + Ring morphism: + From: Number Field in a with defining polynomial x^2 + 1 with a = 1*I + To: Number Field in b with defining polynomial x^2 + 1 with b = 1*I + Defn: a |--> b + """ + if isinstance(im_gens, NumberFieldHomomorphism_im_gens): + return self._coerce_impl(im_gens) + try: + return NumberFieldHomomorphism_im_gens(self, im_gens, check=check) + except (NotImplementedError, ValueError): + try: + return self._coerce_impl(im_gens) + except TypeError: + raise TypeError("images do not define a valid homomorphism") + + def _coerce_impl(self, x): + r""" + Canonical coercion of ``x`` into this homset. The only things that + coerce canonically into self are elements of self and of homsets equal + to self. + + EXAMPLES:: + + sage: H1 = End(QuadraticField(-1, 'a')) + sage: H1.coerce(loads(dumps(H1[1]))) # indirect doctest + Ring endomorphism of Number Field in a with defining polynomial x^2 + 1 with a = 1*I + Defn: a |--> -a + + TESTS: + + We can move morphisms between categories:: + + sage: f = H1.an_element() + sage: g = End(H1.domain(), category=Rings())(f) + sage: f == End(H1.domain(), category=NumberFields())(g) + True + """ + if not isinstance(x, NumberFieldHomomorphism_im_gens): + raise TypeError + if x.parent() is self: + return x + from sage.categories.all import NumberFields, Rings + if (x.parent() == self or + (x.domain() == self.domain() and x.codomain() == self.codomain() and + # This would be the better check, however it returns False currently: + # self.homset_category().is_full_subcategory(x.category_for()) + # So we check instead that this is a morphism anywhere between + # Rings and NumberFields where the hom spaces do not change. + NumberFields().is_subcategory(self.homset_category()) and + self.homset_category().is_subcategory(Rings()) and + NumberFields().is_subcategory(x.category_for()) and + x.category_for().is_subcategory(Rings()))): + return NumberFieldHomomorphism_im_gens(self, x.im_gens(), check=False) + raise TypeError + + def _an_element_(self): + r""" + Return an element of this set of embeddings. + + EXAMPLES:: + + sage: H = Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'b')) + sage: H.an_element() # indirect doctest + Ring morphism: + From: Number Field in a with defining polynomial x^2 + 1 with a = 1*I + To: Number Field in b with defining polynomial x^2 + 1 with b = 1*I + Defn: a |--> b + + sage: H = Hom(QuadraticField(-1, 'a'), QuadraticField(-2, 'b')) + sage: H.an_element() + Traceback (most recent call last): + ... + EmptySetError: There is no morphism from Number Field in a with defining polynomial x^2 + 1 with a = 1*I to Number Field in b with defining polynomial x^2 + 2 with b = 1.414213562373095?*I + """ + L = self.list() + if len(L) != 0: + return L[0] + else: + from sage.categories.sets_cat import EmptySetError + raise EmptySetError("There is no morphism from {} to {}".format( + self.domain(), self.codomain())) + + def _repr_(self): + r""" + String representation of this homset. + + EXAMPLES:: + + sage: repr(Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'b'))) # indirect doctest + 'Set of field embeddings from Number Field in a with defining polynomial x^2 + 1 with a = 1*I to Number Field in b with defining polynomial x^2 + 1 with b = 1*I' + sage: repr(Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'a'))) # indirect doctest + 'Automorphism group of Number Field in a with defining polynomial x^2 + 1 with a = 1*I' + """ + D = self.domain() + C = self.codomain() + if C == D: + return "Automorphism group of {}".format(D) + else: + return "Set of field embeddings from {} to {}".format(D, C) + + def order(self): + """ + Return the order of this set of field homomorphism. + + EXAMPLES:: + + sage: k. = NumberField(x^2 + 1) + sage: End(k) + Automorphism group of Number Field in a with defining polynomial x^2 + 1 + sage: End(k).order() + 2 + sage: k. = NumberField(x^3 + 2) + sage: End(k).order() + 1 + + sage: K. = NumberField( [x^3 + 2, x^2 + x + 1] ) + sage: End(K).order() + 6 + """ + return Integer(len(self.list())) + + cardinality = order + + @cached_method + def list(self): + """ + Return a list of all the elements of self. + + EXAMPLES:: + + sage: K. = NumberField(x^3 - 3*x + 1) + sage: End(K).list() + [ + Ring endomorphism of Number Field in a with defining polynomial x^3 - 3*x + 1 + Defn: a |--> a, + Ring endomorphism of Number Field in a with defining polynomial x^3 - 3*x + 1 + Defn: a |--> a^2 - 2, + Ring endomorphism of Number Field in a with defining polynomial x^3 - 3*x + 1 + Defn: a |--> -a^2 - a + 2 + ] + sage: Hom(K, CyclotomicField(9))[0] # indirect doctest + Ring morphism: + From: Number Field in a with defining polynomial x^3 - 3*x + 1 + To: Cyclotomic Field of order 9 and degree 6 + Defn: a |--> -zeta9^4 + zeta9^2 - zeta9 + + An example where the codomain is a relative extension:: + + sage: K. = NumberField(x^3 - 2) + sage: L. = K.extension(x^2 + 3) + sage: Hom(K, L).list() + [ + Ring morphism: + From: Number Field in a with defining polynomial x^3 - 2 + To: Number Field in b with defining polynomial x^2 + 3 over its base field + Defn: a |--> a, + Ring morphism: + From: Number Field in a with defining polynomial x^3 - 2 + To: Number Field in b with defining polynomial x^2 + 3 over its base field + Defn: a |--> -1/2*a*b - 1/2*a, + Ring morphism: + From: Number Field in a with defining polynomial x^3 - 2 + To: Number Field in b with defining polynomial x^2 + 3 over its base field + Defn: a |--> 1/2*a*b - 1/2*a + ] + """ + D = self.domain() + C = self.codomain() + if D.degree().divides(C.absolute_degree()): + roots = D.polynomial().roots(ring=C, multiplicities=False) + v = [D.hom([r], codomain=C, check=False) for r in roots] + else: + v = [] + return Sequence(v, universe=self, check=False, immutable=True, cr=v!=[]) + + def __getitem__(self, n): + r""" + Return the ``n``th element of ``self.list()``. + + EXAMPLES:: + + sage: End(CyclotomicField(37))[3] # indirect doctest + Ring endomorphism of Cyclotomic Field of order 37 and degree 36 + Defn: zeta37 |--> zeta37^4 + """ + return self.list()[n] + + +class RelativeNumberFieldHomset(NumberFieldHomset): + """ + Set of homomorphisms with domain a given relative number field. + + EXAMPLES: + + We construct a homomorphism from a relative field by giving + the image of a generator:: + + sage: L. = CyclotomicField(3).extension(x^3 - 2) + sage: phi = L.hom([cuberoot2 * zeta3]); phi + Relative number field endomorphism of Number Field in cuberoot2 with defining polynomial x^3 - 2 over its base field + Defn: cuberoot2 |--> zeta3*cuberoot2 + zeta3 |--> zeta3 + sage: phi(cuberoot2 + zeta3) + zeta3*cuberoot2 + zeta3 + + In fact, this phi is a generator for the Kummer Galois group of this + cyclic extension:: + + sage: phi(phi(cuberoot2 + zeta3)) + (-zeta3 - 1)*cuberoot2 + zeta3 + sage: phi(phi(phi(cuberoot2 + zeta3))) + cuberoot2 + zeta3 + """ + def __call__(self, im_gen, base_map=None, base_hom=None, check=True): + r""" + Create a homomorphism in this homset from the given data, which can be: + + - A homomorphism from this number field. + - A homomorphism from the absolute number field corresponding to this + relative number field. + - An element (specifying the image of the generator) of a ring into + which the base ring coerces. + - A pair consisting of an element of a ring R and a homomorphism from + the base ring to R. + + EXAMPLES:: + + sage: K. = NumberField(x^2 + 1) + sage: L. = K.extension(x^4 - 2) + sage: E = End(L) + sage: E(E[0]) # indirect doctest + Relative number field endomorphism of Number Field in b with defining polynomial x^4 - 2 over its base field + Defn: b |--> b + a |--> a + sage: E(L.absolute_field('c').hom(b+a, L)) # indirect doctest + Relative number field endomorphism of Number Field in b with defining polynomial x^4 - 2 over its base field + Defn: b |--> b + a |--> -a + sage: E(-b*a) # indirect doctest + Relative number field endomorphism of Number Field in b with defining polynomial x^4 - 2 over its base field + Defn: b |--> -a*b + a |--> a + sage: E(-a*b, K.hom([-a])) # indirect doctest + Relative number field endomorphism of Number Field in b with defining polynomial x^4 - 2 over its base field + Defn: b |--> -a*b + a |--> -a + + You can specify a map on the base field:: + + sage: R. = ZZ[] + sage: K. = NumberField(x^2 + 1) + sage: L. = K.extension(x^2-17) + sage: cc = K.hom([-i]) + sage: phi = L.hom([-b],base_map=cc); phi + Relative number field endomorphism of Number Field in b with defining polynomial x^2 - 17 over its base field + Defn: b |--> -b + i |--> -i + + Using check=False, it is possible to construct homomorphisms into fields such as CC + where calculations are only approximate. + + sage: K. = QuadraticField(-7) + sage: f = K.hom([CC(sqrt(-7))], check=False) + sage: x = polygen(K) + sage: L. = K.extension(x^2 - a - 5) + sage: L.Hom(CC)(f(a + 5).sqrt(), f, check=False) + Relative number field morphism: + From: Number Field in b with defining polynomial x^2 - a - 5 over its base field + To: Complex Field with 53 bits of precision + Defn: b |--> 2.30833860703888 + 0.573085617291335*I + a |--> -8.88178419700125e-16 + 2.64575131106459*I + """ + if base_hom is not None: + deprecation(26105, "Use base_map rather than base_hom") + base_map = base_hom + if isinstance(im_gen, NumberFieldHomomorphism_im_gens): + # Then it must be a homomorphism from the corresponding + # absolute number field + abs_hom = im_gen + K = abs_hom.domain() + if K != self.domain().absolute_field(K.variable_name()): + raise TypeError("domain of morphism must be absolute field of domain.") + from_K, to_K = K.structure() + if abs_hom.domain() != K: + raise ValueError("domain of absolute homomorphism must be absolute field of domain.") + if abs_hom.codomain() != self.codomain(): + raise ValueError("codomain of absolute homomorphism must be codomain of this homset.") + return RelativeNumberFieldHomomorphism_from_abs(self, abs_hom) + if isinstance(im_gen, RelativeNumberFieldHomomorphism_from_abs): + return self._coerce_impl(im_gen) + if base_map is None: + base_map = self.default_base_hom() + if isinstance(im_gen, (list, tuple)) and len(im_gen) == 1: + im_gen = im_gen[0] + if check: + im_gen = self.codomain()(im_gen) + return self._from_im(im_gen, base_map=base_map, check=check) + + def _coerce_impl(self, x): + r""" + Canonically coerce ``x`` into this homset. This will only work if ``x`` + is already in the homset. + + EXAMPLES:: + + sage: L. = NumberField([x^3 - x + 1, x^2 + 23]) + sage: E = End(L) + sage: E.coerce(loads(dumps(E[0]))) # indirect doctest + Relative number field endomorphism of Number Field in a with defining polynomial x^3 - x + 1 over its base field + Defn: a |--> a + b |--> b + """ + if not isinstance(x, RelativeNumberFieldHomomorphism_from_abs): + raise TypeError + if x.parent() is self: + return x + if x.parent() == self: + return RelativeNumberFieldHomomorphism_from_abs(self, x.abs_hom()) + raise TypeError + + def _from_im(self, im_gen, base_map, check=True): + """ + Return the homomorphism that acts on the base as given and + sends the generator of the domain to im_gen. + + EXAMPLES:: + + sage: K. = NumberField(x^2 + 23) + sage: L. = K.extension(x^3 - x + 1) + sage: End(L)._from_im( -3/23*a*b^2 + (-9/46*a - 1/2)*b + 2/23*a, K.hom([-a], K)) + Relative number field endomorphism of Number Field in b with defining polynomial x^3 - x + 1 over its base field + Defn: b |--> -3/23*a*b^2 + (-9/46*a - 1/2)*b + 2/23*a + a |--> -a + """ + K = self.domain().absolute_field('a') + from_K, to_K = K.structure() + a = from_K(K.gen()) + # We just have to figure out where a goes to + # under the morphism defined by im_gen and base_map. + L = self.codomain() + R = L['x'] + f = R([base_map(x) for x in a.list()]) + b = f(im_gen) + abs_hom = K.hom([b], check=check) + return RelativeNumberFieldHomomorphism_from_abs(self, abs_hom) + + @cached_method + def default_base_hom(self): + r""" + Pick an embedding of the base field of self into the codomain of this + homset. This is done in an essentially arbitrary way. + + EXAMPLES:: + + sage: L. = NumberField([x^3 - x + 1, x^2 + 23]) + sage: M. = NumberField(x^4 + 80*x^2 + 36) + sage: Hom(L, M).default_base_hom() + Ring morphism: + From: Number Field in b with defining polynomial x^2 + 23 + To: Number Field in c with defining polynomial x^4 + 80*x^2 + 36 + Defn: b |--> 1/12*c^3 + 43/6*c + """ + v = self.domain().base_field().embeddings(self.codomain()) + if len(v) == 0: + raise ValueError("no way to map base field to codomain.") + return v[0] + + @cached_method + def list(self): + """ + Return a list of all the elements of self (for which the domain + is a relative number field). + + EXAMPLES:: + + sage: K. = NumberField([x^2 + x + 1, x^3 + 2]) + sage: End(K).list() + [ + Relative number field endomorphism of Number Field in a with defining polynomial x^2 + x + 1 over its base field + Defn: a |--> a + b |--> b, + ... + Relative number field endomorphism of Number Field in a with defining polynomial x^2 + x + 1 over its base field + Defn: a |--> a + b |--> -b*a - b + ] + + An example with an absolute codomain:: + + sage: K. = NumberField([x^2 - 3, x^2 + 2]) + sage: Hom(K, CyclotomicField(24, 'z')).list() + [ + Relative number field morphism: + From: Number Field in a with defining polynomial x^2 - 3 over its base field + To: Cyclotomic Field of order 24 and degree 8 + Defn: a |--> z^6 - 2*z^2 + b |--> -z^5 - z^3 + z, + ... + Relative number field morphism: + From: Number Field in a with defining polynomial x^2 - 3 over its base field + To: Cyclotomic Field of order 24 and degree 8 + Defn: a |--> -z^6 + 2*z^2 + b |--> z^5 + z^3 - z + ] + """ + D = self.domain() + C = self.codomain() + D_abs = D.absolute_field('a') + v = [self(f, check=False) for f in D_abs.Hom(C).list()] + return Sequence(v, universe=self, check=False, immutable=True, cr=v!=[]) + + +class CyclotomicFieldHomset(NumberFieldHomset): + """ + Set of homomorphisms with domain a given cyclotomic field. + + EXAMPLES:: + + sage: End(CyclotomicField(16)) + Automorphism group of Cyclotomic Field of order 16 and degree 8 + """ + def __call__(self, im_gens, check=True): + """ + Create an element of this homset. + + EXAMPLES:: + + sage: K. = CyclotomicField(16) + sage: E = End(K) + sage: E(E[0]) # indirect doctest + Ring endomorphism of Cyclotomic Field of order 16 and degree 8 + Defn: z |--> z + sage: E(z^5) # indirect doctest + Ring endomorphism of Cyclotomic Field of order 16 and degree 8 + Defn: z |--> z^5 + sage: E(z^6) # indirect doctest + Traceback (most recent call last): + ... + TypeError: images do not define a valid homomorphism + """ + if isinstance(im_gens, CyclotomicFieldHomomorphism_im_gens): + return self._coerce_impl(im_gens) + try: + return CyclotomicFieldHomomorphism_im_gens(self, im_gens, check=check) + except (NotImplementedError, ValueError): + try: + return self._coerce_impl(im_gens) + except TypeError: + raise TypeError("images do not define a valid homomorphism") + + def _coerce_impl(self, x): + r""" + Coerce ``x`` into self. This will only work if ``x`` is already in self. + + EXAMPLES:: + + sage: E = End(CyclotomicField(16)) + sage: E.coerce(E[0]) # indirect doctest + Ring endomorphism of Cyclotomic Field of order 16 and degree 8 + Defn: zeta16 |--> zeta16 + sage: E.coerce(17) # indirect doctest + Traceback (most recent call last): + ... + TypeError: no canonical coercion from Integer Ring to Automorphism group of Cyclotomic Field of order 16 and degree 8 + """ + if not isinstance(x, CyclotomicFieldHomomorphism_im_gens): + raise TypeError + if x.parent() is self: + return x + if x.parent() == self: + return CyclotomicFieldHomomorphism_im_gens(self, x.im_gens()) + raise TypeError + + @cached_method + def list(self): + """ + Return a list of all the elements of self (for which the domain + is a cyclotomic field). + + EXAMPLES:: + + sage: K. = CyclotomicField(12) + sage: G = End(K); G + Automorphism group of Cyclotomic Field of order 12 and degree 4 + sage: [g(z) for g in G] + [z, z^3 - z, -z, -z^3 + z] + sage: L. = NumberField([x^2 + x + 1, x^4 + 1]) + sage: L + Number Field in a with defining polynomial x^2 + x + 1 over its base field + sage: Hom(CyclotomicField(12), L)[3] + Ring morphism: + From: Cyclotomic Field of order 12 and degree 4 + To: Number Field in a with defining polynomial x^2 + x + 1 over its base field + Defn: zeta12 |--> -b^2*a + sage: list(Hom(CyclotomicField(5), K)) + [] + sage: Hom(CyclotomicField(11), L).list() + [] + """ + D = self.domain() + C = self.codomain() + z = D.gen() + n = z.multiplicative_order() + if not n.divides(C.zeta_order()): + v =[] + else: + if D == C: + w = z + else: + w = C.zeta(n) + v = [self([w**k], check=False) for k in Zmod(n) if k.is_unit()] + return Sequence(v, universe=self, check=False, immutable=True, cr=v!=[]) diff --git a/src/sage/rings/number_field/morphism.py b/src/sage/rings/number_field/morphism.py index b740969ba91..a2a13de527e 100644 --- a/src/sage/rings/number_field/morphism.py +++ b/src/sage/rings/number_field/morphism.py @@ -5,245 +5,23 @@ fields (i.e. field embeddings). """ +#***************************************************************************** +# Copyright (C) 2007 William Stein +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# http://www.gnu.org/licenses/ +#***************************************************************************** + from sage.misc.cachefunc import cached_method -from sage.misc.superseded import deprecation -from sage.rings.homset import RingHomset_generic from sage.rings.morphism import RingHomomorphism_im_gens, RingHomomorphism -from sage.rings.integer import Integer -from sage.rings.finite_rings.integer_mod_ring import Zmod from sage.structure.sequence import Sequence from sage.structure.richcmp import richcmp -class NumberFieldHomset(RingHomset_generic): - """ - Set of homomorphisms with domain a given number field. - - TESTS:: - - sage: H = Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'b')) - sage: TestSuite(H).run() - Failure in _test_category: - ... - The following tests failed: _test_elements - """ - def __init__(self, R, S, category=None): - """ - TESTS: - - Check that :trac:`23647` is fixed:: - - sage: K. = NumberField([x^2 - 2, x^2 - 3]) - sage: e, u, v, w = End(K) - sage: e.abs_hom().parent().category() - Category of homsets of number fields - sage: (v*v).abs_hom().parent().category() - Category of homsets of number fields - """ - if category is None: - from sage.categories.all import Fields, NumberFields - if S in NumberFields: - category = NumberFields() - elif S in Fields: - category = Fields() - RingHomset_generic.__init__(self, R, S, category) - - def __call__(self, im_gens, check=True): - """ - Create the homomorphism sending the generators to ``im_gens``. - - EXAMPLES:: - - sage: H = Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'b')) - sage: phi = H([H.domain().gen()]); phi # indirect doctest - Ring morphism: - From: Number Field in a with defining polynomial x^2 + 1 with a = 1*I - To: Number Field in b with defining polynomial x^2 + 1 with b = 1*I - Defn: a |--> b - """ - if isinstance(im_gens, NumberFieldHomomorphism_im_gens): - return self._coerce_impl(im_gens) - try: - return NumberFieldHomomorphism_im_gens(self, im_gens, check=check) - except (NotImplementedError, ValueError): - try: - return self._coerce_impl(im_gens) - except TypeError: - raise TypeError("images do not define a valid homomorphism") - - def _coerce_impl(self, x): - r""" - Canonical coercion of ``x`` into this homset. The only things that - coerce canonically into self are elements of self and of homsets equal - to self. - - EXAMPLES:: - - sage: H1 = End(QuadraticField(-1, 'a')) - sage: H1.coerce(loads(dumps(H1[1]))) # indirect doctest - Ring endomorphism of Number Field in a with defining polynomial x^2 + 1 with a = 1*I - Defn: a |--> -a - - TESTS: - - We can move morphisms between categories:: - - sage: f = H1.an_element() - sage: g = End(H1.domain(), category=Rings())(f) - sage: f == End(H1.domain(), category=NumberFields())(g) - True - """ - if not isinstance(x, NumberFieldHomomorphism_im_gens): - raise TypeError - if x.parent() is self: - return x - from sage.categories.all import NumberFields, Rings - if (x.parent() == self or - (x.domain() == self.domain() and x.codomain() == self.codomain() and - # This would be the better check, however it returns False currently: - # self.homset_category().is_full_subcategory(x.category_for()) - # So we check instead that this is a morphism anywhere between - # Rings and NumberFields where the hom spaces do not change. - NumberFields().is_subcategory(self.homset_category()) and - self.homset_category().is_subcategory(Rings()) and - NumberFields().is_subcategory(x.category_for()) and - x.category_for().is_subcategory(Rings()))): - return NumberFieldHomomorphism_im_gens(self, x.im_gens(), check=False) - raise TypeError - - def _an_element_(self): - r""" - Return an element of this set of embeddings. - - EXAMPLES:: - - sage: H = Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'b')) - sage: H.an_element() # indirect doctest - Ring morphism: - From: Number Field in a with defining polynomial x^2 + 1 with a = 1*I - To: Number Field in b with defining polynomial x^2 + 1 with b = 1*I - Defn: a |--> b - - sage: H = Hom(QuadraticField(-1, 'a'), QuadraticField(-2, 'b')) - sage: H.an_element() - Traceback (most recent call last): - ... - EmptySetError: There is no morphism from Number Field in a with defining polynomial x^2 + 1 with a = 1*I to Number Field in b with defining polynomial x^2 + 2 with b = 1.414213562373095?*I - """ - L = self.list() - if len(L) != 0: - return L[0] - else: - from sage.categories.sets_cat import EmptySetError - raise EmptySetError("There is no morphism from {} to {}".format( - self.domain(), self.codomain())) - - def _repr_(self): - r""" - String representation of this homset. - - EXAMPLES:: - - sage: repr(Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'b'))) # indirect doctest - 'Set of field embeddings from Number Field in a with defining polynomial x^2 + 1 with a = 1*I to Number Field in b with defining polynomial x^2 + 1 with b = 1*I' - sage: repr(Hom(QuadraticField(-1, 'a'), QuadraticField(-1, 'a'))) # indirect doctest - 'Automorphism group of Number Field in a with defining polynomial x^2 + 1 with a = 1*I' - """ - D = self.domain() - C = self.codomain() - if C == D: - return "Automorphism group of {}".format(D) - else: - return "Set of field embeddings from {} to {}".format(D, C) - - def order(self): - """ - Return the order of this set of field homomorphism. - - EXAMPLES:: - - sage: k. = NumberField(x^2 + 1) - sage: End(k) - Automorphism group of Number Field in a with defining polynomial x^2 + 1 - sage: End(k).order() - 2 - sage: k. = NumberField(x^3 + 2) - sage: End(k).order() - 1 - - sage: K. = NumberField( [x^3 + 2, x^2 + x + 1] ) - sage: End(K).order() - 6 - """ - return Integer(len(self.list())) - - cardinality = order - - @cached_method - def list(self): - """ - Return a list of all the elements of self. - - EXAMPLES:: - - sage: K. = NumberField(x^3 - 3*x + 1) - sage: End(K).list() - [ - Ring endomorphism of Number Field in a with defining polynomial x^3 - 3*x + 1 - Defn: a |--> a, - Ring endomorphism of Number Field in a with defining polynomial x^3 - 3*x + 1 - Defn: a |--> a^2 - 2, - Ring endomorphism of Number Field in a with defining polynomial x^3 - 3*x + 1 - Defn: a |--> -a^2 - a + 2 - ] - sage: Hom(K, CyclotomicField(9))[0] # indirect doctest - Ring morphism: - From: Number Field in a with defining polynomial x^3 - 3*x + 1 - To: Cyclotomic Field of order 9 and degree 6 - Defn: a |--> -zeta9^4 + zeta9^2 - zeta9 - - An example where the codomain is a relative extension:: - - sage: K. = NumberField(x^3 - 2) - sage: L. = K.extension(x^2 + 3) - sage: Hom(K, L).list() - [ - Ring morphism: - From: Number Field in a with defining polynomial x^3 - 2 - To: Number Field in b with defining polynomial x^2 + 3 over its base field - Defn: a |--> a, - Ring morphism: - From: Number Field in a with defining polynomial x^3 - 2 - To: Number Field in b with defining polynomial x^2 + 3 over its base field - Defn: a |--> -1/2*a*b - 1/2*a, - Ring morphism: - From: Number Field in a with defining polynomial x^3 - 2 - To: Number Field in b with defining polynomial x^2 + 3 over its base field - Defn: a |--> 1/2*a*b - 1/2*a - ] - """ - D = self.domain() - C = self.codomain() - if D.degree().divides(C.absolute_degree()): - roots = D.polynomial().roots(ring=C, multiplicities=False) - v = [D.hom([r], codomain=C, check=False) for r in roots] - else: - v = [] - return Sequence(v, universe=self, check=False, immutable=True, cr=v!=[]) - - def __getitem__(self, n): - r""" - Return the ``n``th element of ``self.list()``. - - EXAMPLES:: - - sage: End(CyclotomicField(37))[3] # indirect doctest - Ring endomorphism of Cyclotomic Field of order 37 and degree 36 - Defn: zeta37 |--> zeta37^4 - """ - return self.list()[n] - class NumberFieldHomomorphism_im_gens(RingHomomorphism_im_gens): def __invert__(self): r""" @@ -363,228 +141,6 @@ def preimage(self, y): raise ValueError("Element '{}' is not in the image of this homomorphism.".format(y)) return VtoK(xvec) # pass from the vector space representation of K back to a point in K -class RelativeNumberFieldHomset(NumberFieldHomset): - """ - Set of homomorphisms with domain a given relative number field. - - EXAMPLES: - - We construct a homomorphism from a relative field by giving - the image of a generator:: - - sage: L. = CyclotomicField(3).extension(x^3 - 2) - sage: phi = L.hom([cuberoot2 * zeta3]); phi - Relative number field endomorphism of Number Field in cuberoot2 with defining polynomial x^3 - 2 over its base field - Defn: cuberoot2 |--> zeta3*cuberoot2 - zeta3 |--> zeta3 - sage: phi(cuberoot2 + zeta3) - zeta3*cuberoot2 + zeta3 - - In fact, this phi is a generator for the Kummer Galois group of this - cyclic extension:: - - sage: phi(phi(cuberoot2 + zeta3)) - (-zeta3 - 1)*cuberoot2 + zeta3 - sage: phi(phi(phi(cuberoot2 + zeta3))) - cuberoot2 + zeta3 - """ - def __call__(self, im_gen, base_map=None, base_hom=None, check=True): - r""" - Create a homomorphism in this homset from the given data, which can be: - - - A homomorphism from this number field. - - A homomorphism from the absolute number field corresponding to this - relative number field. - - An element (specifying the image of the generator) of a ring into - which the base ring coerces. - - A pair consisting of an element of a ring R and a homomorphism from - the base ring to R. - - EXAMPLES:: - - sage: K. = NumberField(x^2 + 1) - sage: L. = K.extension(x^4 - 2) - sage: E = End(L) - sage: E(E[0]) # indirect doctest - Relative number field endomorphism of Number Field in b with defining polynomial x^4 - 2 over its base field - Defn: b |--> b - a |--> a - sage: E(L.absolute_field('c').hom(b+a, L)) # indirect doctest - Relative number field endomorphism of Number Field in b with defining polynomial x^4 - 2 over its base field - Defn: b |--> b - a |--> -a - sage: E(-b*a) # indirect doctest - Relative number field endomorphism of Number Field in b with defining polynomial x^4 - 2 over its base field - Defn: b |--> -a*b - a |--> a - sage: E(-a*b, K.hom([-a])) # indirect doctest - Relative number field endomorphism of Number Field in b with defining polynomial x^4 - 2 over its base field - Defn: b |--> -a*b - a |--> -a - - You can specify a map on the base field:: - - sage: R. = ZZ[] - sage: K. = NumberField(x^2 + 1) - sage: L. = K.extension(x^2-17) - sage: cc = K.hom([-i]) - sage: phi = L.hom([-b],base_map=cc); phi - Relative number field endomorphism of Number Field in b with defining polynomial x^2 - 17 over its base field - Defn: b |--> -b - i |--> -i - - Using check=False, it is possible to construct homomorphisms into fields such as CC - where calculations are only approximate. - - sage: K. = QuadraticField(-7) - sage: f = K.hom([CC(sqrt(-7))], check=False) - sage: x = polygen(K) - sage: L. = K.extension(x^2 - a - 5) - sage: L.Hom(CC)(f(a + 5).sqrt(), f, check=False) - Relative number field morphism: - From: Number Field in b with defining polynomial x^2 - a - 5 over its base field - To: Complex Field with 53 bits of precision - Defn: b |--> 2.30833860703888 + 0.573085617291335*I - a |--> -8.88178419700125e-16 + 2.64575131106459*I - """ - if base_hom is not None: - deprecation(26105, "Use base_map rather than base_hom") - base_map = base_hom - if isinstance(im_gen, NumberFieldHomomorphism_im_gens): - # Then it must be a homomorphism from the corresponding - # absolute number field - abs_hom = im_gen - K = abs_hom.domain() - if K != self.domain().absolute_field(K.variable_name()): - raise TypeError("domain of morphism must be absolute field of domain.") - from_K, to_K = K.structure() - if abs_hom.domain() != K: - raise ValueError("domain of absolute homomorphism must be absolute field of domain.") - if abs_hom.codomain() != self.codomain(): - raise ValueError("codomain of absolute homomorphism must be codomain of this homset.") - return RelativeNumberFieldHomomorphism_from_abs(self, abs_hom) - if isinstance(im_gen, RelativeNumberFieldHomomorphism_from_abs): - return self._coerce_impl(im_gen) - if base_map is None: - base_map = self.default_base_hom() - if isinstance(im_gen, (list, tuple)) and len(im_gen) == 1: - im_gen = im_gen[0] - if check: - im_gen = self.codomain()(im_gen) - return self._from_im(im_gen, base_map=base_map, check=check) - - def _coerce_impl(self, x): - r""" - Canonically coerce ``x`` into this homset. This will only work if ``x`` - is already in the homset. - - EXAMPLES:: - - sage: L. = NumberField([x^3 - x + 1, x^2 + 23]) - sage: E = End(L) - sage: E.coerce(loads(dumps(E[0]))) # indirect doctest - Relative number field endomorphism of Number Field in a with defining polynomial x^3 - x + 1 over its base field - Defn: a |--> a - b |--> b - """ - if not isinstance(x, RelativeNumberFieldHomomorphism_from_abs): - raise TypeError - if x.parent() is self: - return x - if x.parent() == self: - return RelativeNumberFieldHomomorphism_from_abs(self, x.abs_hom()) - raise TypeError - - def _from_im(self, im_gen, base_map, check=True): - """ - Return the homomorphism that acts on the base as given and - sends the generator of the domain to im_gen. - - EXAMPLES:: - - sage: K. = NumberField(x^2 + 23) - sage: L. = K.extension(x^3 - x + 1) - sage: End(L)._from_im( -3/23*a*b^2 + (-9/46*a - 1/2)*b + 2/23*a, K.hom([-a], K)) - Relative number field endomorphism of Number Field in b with defining polynomial x^3 - x + 1 over its base field - Defn: b |--> -3/23*a*b^2 + (-9/46*a - 1/2)*b + 2/23*a - a |--> -a - """ - K = self.domain().absolute_field('a') - from_K, to_K = K.structure() - a = from_K(K.gen()) - # We just have to figure out where a goes to - # under the morphism defined by im_gen and base_map. - L = self.codomain() - R = L['x'] - f = R([base_map(x) for x in a.list()]) - b = f(im_gen) - abs_hom = K.hom([b], check=check) - return RelativeNumberFieldHomomorphism_from_abs(self, abs_hom) - - @cached_method - def default_base_hom(self): - r""" - Pick an embedding of the base field of self into the codomain of this - homset. This is done in an essentially arbitrary way. - - EXAMPLES:: - - sage: L. = NumberField([x^3 - x + 1, x^2 + 23]) - sage: M. = NumberField(x^4 + 80*x^2 + 36) - sage: Hom(L, M).default_base_hom() - Ring morphism: - From: Number Field in b with defining polynomial x^2 + 23 - To: Number Field in c with defining polynomial x^4 + 80*x^2 + 36 - Defn: b |--> 1/12*c^3 + 43/6*c - """ - v = self.domain().base_field().embeddings(self.codomain()) - if len(v) == 0: - raise ValueError("no way to map base field to codomain.") - return v[0] - - @cached_method - def list(self): - """ - Return a list of all the elements of self (for which the domain - is a relative number field). - - EXAMPLES:: - - sage: K. = NumberField([x^2 + x + 1, x^3 + 2]) - sage: End(K).list() - [ - Relative number field endomorphism of Number Field in a with defining polynomial x^2 + x + 1 over its base field - Defn: a |--> a - b |--> b, - ... - Relative number field endomorphism of Number Field in a with defining polynomial x^2 + x + 1 over its base field - Defn: a |--> a - b |--> -b*a - b - ] - - An example with an absolute codomain:: - - sage: K. = NumberField([x^2 - 3, x^2 + 2]) - sage: Hom(K, CyclotomicField(24, 'z')).list() - [ - Relative number field morphism: - From: Number Field in a with defining polynomial x^2 - 3 over its base field - To: Cyclotomic Field of order 24 and degree 8 - Defn: a |--> z^6 - 2*z^2 - b |--> -z^5 - z^3 + z, - ... - Relative number field morphism: - From: Number Field in a with defining polynomial x^2 - 3 over its base field - To: Cyclotomic Field of order 24 and degree 8 - Defn: a |--> -z^6 + 2*z^2 - b |--> z^5 + z^3 - z - ] - """ - D = self.domain() - C = self.codomain() - D_abs = D.absolute_field('a') - v = [self(f, check=False) for f in D_abs.Hom(C).list()] - return Sequence(v, universe=self, check=False, immutable=True, cr=v!=[]) class RelativeNumberFieldHomomorphism_from_abs(RingHomomorphism): r""" @@ -698,106 +254,5 @@ def _call_(self, x): return self._abs_hom(self._to_K(x)) -class CyclotomicFieldHomset(NumberFieldHomset): - """ - Set of homomorphisms with domain a given cyclotomic field. - - EXAMPLES:: - - sage: End(CyclotomicField(16)) - Automorphism group of Cyclotomic Field of order 16 and degree 8 - """ - def __call__(self, im_gens, check=True): - """ - Create an element of this homset. - - EXAMPLES:: - - sage: K. = CyclotomicField(16) - sage: E = End(K) - sage: E(E[0]) # indirect doctest - Ring endomorphism of Cyclotomic Field of order 16 and degree 8 - Defn: z |--> z - sage: E(z^5) # indirect doctest - Ring endomorphism of Cyclotomic Field of order 16 and degree 8 - Defn: z |--> z^5 - sage: E(z^6) # indirect doctest - Traceback (most recent call last): - ... - TypeError: images do not define a valid homomorphism - """ - if isinstance(im_gens, CyclotomicFieldHomomorphism_im_gens): - return self._coerce_impl(im_gens) - try: - return CyclotomicFieldHomomorphism_im_gens(self, im_gens, check=check) - except (NotImplementedError, ValueError): - try: - return self._coerce_impl(im_gens) - except TypeError: - raise TypeError("images do not define a valid homomorphism") - - def _coerce_impl(self, x): - r""" - Coerce ``x`` into self. This will only work if ``x`` is already in self. - - EXAMPLES:: - - sage: E = End(CyclotomicField(16)) - sage: E.coerce(E[0]) # indirect doctest - Ring endomorphism of Cyclotomic Field of order 16 and degree 8 - Defn: zeta16 |--> zeta16 - sage: E.coerce(17) # indirect doctest - Traceback (most recent call last): - ... - TypeError: no canonical coercion from Integer Ring to Automorphism group of Cyclotomic Field of order 16 and degree 8 - """ - if not isinstance(x, CyclotomicFieldHomomorphism_im_gens): - raise TypeError - if x.parent() is self: - return x - if x.parent() == self: - return CyclotomicFieldHomomorphism_im_gens(self, x.im_gens()) - raise TypeError - - @cached_method - def list(self): - """ - Return a list of all the elements of self (for which the domain - is a cyclotomic field). - - EXAMPLES:: - - sage: K. = CyclotomicField(12) - sage: G = End(K); G - Automorphism group of Cyclotomic Field of order 12 and degree 4 - sage: [g(z) for g in G] - [z, z^3 - z, -z, -z^3 + z] - sage: L. = NumberField([x^2 + x + 1, x^4 + 1]) - sage: L - Number Field in a with defining polynomial x^2 + x + 1 over its base field - sage: Hom(CyclotomicField(12), L)[3] - Ring morphism: - From: Cyclotomic Field of order 12 and degree 4 - To: Number Field in a with defining polynomial x^2 + x + 1 over its base field - Defn: zeta12 |--> -b^2*a - sage: list(Hom(CyclotomicField(5), K)) - [] - sage: Hom(CyclotomicField(11), L).list() - [] - """ - D = self.domain() - C = self.codomain() - z = D.gen() - n = z.multiplicative_order() - if not n.divides(C.zeta_order()): - v =[] - else: - if D == C: - w = z - else: - w = C.zeta(n) - v = [self([w**k], check=False) for k in Zmod(n) if k.is_unit()] - return Sequence(v, universe=self, check=False, immutable=True, cr=v!=[]) - class CyclotomicFieldHomomorphism_im_gens(NumberFieldHomomorphism_im_gens): pass diff --git a/src/sage/rings/number_field/number_field.py b/src/sage/rings/number_field/number_field.py index f2996456448..552b479c0ab 100644 --- a/src/sage/rings/number_field/number_field.py +++ b/src/sage/rings/number_field/number_field.py @@ -153,7 +153,7 @@ def is_NumberFieldHomsetCodomain(codomain): Returns whether ``codomain`` is a valid codomain for a number field homset. This is used by NumberField._Hom_ to determine whether the created homsets should be a - :class:`sage.rings.number_field.morphism.NumberFieldHomset`. + :class:`sage.rings.number_field.homset.NumberFieldHomset`. EXAMPLES: @@ -1917,7 +1917,7 @@ def _Hom_(self, codomain, category=None): # Using LazyFormat fixes #28036 - infinite loop from sage.misc.lazy_format import LazyFormat raise TypeError(LazyFormat("%s is not suitable as codomain for homomorphisms from %s") % (codomain, self)) - from .morphism import NumberFieldHomset + from sage.rings.number_field.homset import NumberFieldHomset return NumberFieldHomset(self, codomain, category) @cached_method @@ -10561,8 +10561,8 @@ def _Hom_(self, codomain, cat=None): Automorphism group of Cyclotomic Field of order 21 and degree 12 """ if is_NumberFieldHomsetCodomain(codomain): - from . import morphism - return morphism.CyclotomicFieldHomset(self, codomain) + from sage.rings.number_field.homset import CyclotomicFieldHomset + return CyclotomicFieldHomset(self, codomain) else: raise TypeError diff --git a/src/sage/rings/number_field/number_field_rel.py b/src/sage/rings/number_field/number_field_rel.py index 49d1e377d75..ca4ab7294e3 100644 --- a/src/sage/rings/number_field/number_field_rel.py +++ b/src/sage/rings/number_field/number_field_rel.py @@ -765,7 +765,7 @@ def _Hom_(self, codomain, category=None): sage: K.Hom(K) # indirect doctest Automorphism group of Number Field in a with defining polynomial x^3 - 2 over its base field sage: type(K.Hom(K)) - + TESTS:: @@ -776,7 +776,7 @@ def _Hom_(self, codomain, category=None): if not is_NumberFieldHomsetCodomain(codomain): raise TypeError("{} is not suitable as codomain for homomorphisms from {}".format(codomain, self)) - from .morphism import RelativeNumberFieldHomset + from sage.rings.number_field.homset import RelativeNumberFieldHomset return RelativeNumberFieldHomset(self, codomain, category) def _latex_(self): From 5ef3e20cd688a4ed66815576166a3e373e784fd3 Mon Sep 17 00:00:00 2001 From: Simon Brandhorst Date: Tue, 14 Jan 2020 21:38:39 +0100 Subject: [PATCH 108/133] shorter test --- src/sage/quadratic_forms/genera/genus.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/sage/quadratic_forms/genera/genus.py b/src/sage/quadratic_forms/genera/genus.py index 660a7dbc6cd..07fd6b6ca9c 100644 --- a/src/sage/quadratic_forms/genera/genus.py +++ b/src/sage/quadratic_forms/genera/genus.py @@ -2334,15 +2334,12 @@ def _compute_representative(self, LLL=True): sage: from sage.quadratic_forms.genera.genus import genera sage: for det in range(1,5): - ....: G = genera((3,0), det, even=False) + ....: G = genera((4,0), det, even=False) ....: assert all(g==Genus(g.representative()) for g in G) sage: for det in range(1,5): ....: G = genera((1,2), det, even=False) ....: assert all(g==Genus(g.representative()) for g in G) - sage: for det in range(1,20): # long time (about 40s, 2020) - ....: G = genera((3,0), det, even=False) # long time - ....: assert all(g==Genus(g.representative()) for g in G) # long time - sage: for det in range(1,20): # long time + sage: for det in range(1,9): # long time (8s, 2020) ....: G = genera((2,2), det, even=False) # long time ....: assert all(g==Genus(g.representative()) for g in G) # long time """ From a9d73a3d3e598f1ca7d406b0d02391477bc1f677 Mon Sep 17 00:00:00 2001 From: Markus Wageringel Date: Tue, 14 Jan 2020 23:30:55 +0100 Subject: [PATCH 109/133] 29014: use pkg-config for blas and gsl variables of cvxopt --- build/pkgs/cvxopt/spkg-install | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/build/pkgs/cvxopt/spkg-install b/build/pkgs/cvxopt/spkg-install index 47a2d68a103..e5cfab9e1b6 100644 --- a/build/pkgs/cvxopt/spkg-install +++ b/build/pkgs/cvxopt/spkg-install @@ -18,7 +18,7 @@ pkg_libs() { # Note that *_INC_DIR variables have to be non-empty. # Compilers don't like "-I ". export CVXOPT_BLAS_LIB="$(pkg_libs blas)" -export CVXOPT_BLAS_LIB_DIR="${SAGE_LOCAL}" +export CVXOPT_BLAS_LIB_DIR="$(pkg-config --variable=libdir blas)" export CVXOPT_LAPACK_LIB="$(pkg_libs lapack)" export CVXOPT_SUITESPARSE_LIB_DIR="${SAGE_LOCAL}" @@ -29,8 +29,8 @@ export CVXOPT_GLPK_LIB_DIR="${SAGE_LOCAL}" export CVXOPT_GLPK_INC_DIR="${SAGE_LOCAL}/include" export CVXOPT_BUILD_GSL=1 -export CVXOPT_GSL_LIB_DIR="${SAGE_LOCAL}" -export CVXOPT_GSL_INC_DIR="${SAGE_LOCAL}/include" +export CVXOPT_GSL_LIB_DIR="$(pkg-config --variable=libdir gsl)" +export CVXOPT_GSL_INC_DIR="$(pkg-config --variable=includedir gsl)" sdh_pip_install . From e2a84fab1a646c82539f559323e2603219c227ef Mon Sep 17 00:00:00 2001 From: Dave Witte Morris Date: Tue, 14 Jan 2020 19:17:31 -0700 Subject: [PATCH 110/133] change error message --- src/sage/structure/element.pyx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/structure/element.pyx b/src/sage/structure/element.pyx index 11169932e69..50665e5c58a 100644 --- a/src/sage/structure/element.pyx +++ b/src/sage/structure/element.pyx @@ -2814,12 +2814,12 @@ cdef class CommutativeRingElement(RingElement): sage: z.inverse_mod(F.ideal(z)) Traceback (most recent call last): ... - ValueError: Impossible inverse modulo + ValueError: An element of a proper ideal does not have an inverse modulo that ideal """ if I.is_one(): return self.parent().one() elif self in I: - raise ValueError("Impossible inverse modulo") + raise ValueError("An element of a proper ideal does not have an inverse modulo that ideal") elif hasattr(self, "is_unit") and self.is_unit(): return self.inverse_of_unit() else: From 4db45698a8a3e554a7eadf95aab3951309eab5da Mon Sep 17 00:00:00 2001 From: Dave Witte Morris Date: Tue, 14 Jan 2020 20:48:39 -0700 Subject: [PATCH 111/133] error message should be lowercase --- src/sage/structure/element.pyx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/structure/element.pyx b/src/sage/structure/element.pyx index 50665e5c58a..de7efad7718 100644 --- a/src/sage/structure/element.pyx +++ b/src/sage/structure/element.pyx @@ -2814,12 +2814,12 @@ cdef class CommutativeRingElement(RingElement): sage: z.inverse_mod(F.ideal(z)) Traceback (most recent call last): ... - ValueError: An element of a proper ideal does not have an inverse modulo that ideal + ValueError: an element of a proper ideal does not have an inverse modulo that ideal """ if I.is_one(): return self.parent().one() elif self in I: - raise ValueError("An element of a proper ideal does not have an inverse modulo that ideal") + raise ValueError("an element of a proper ideal does not have an inverse modulo that ideal") elif hasattr(self, "is_unit") and self.is_unit(): return self.inverse_of_unit() else: From 686fc32129f0573a300c262d643166f4f616c71d Mon Sep 17 00:00:00 2001 From: Simon Brandhorst Date: Wed, 15 Jan 2020 09:36:18 +0100 Subject: [PATCH 112/133] replace ceil with integer division --- src/sage/modules/free_quadratic_module_integer_symmetric.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/modules/free_quadratic_module_integer_symmetric.py b/src/sage/modules/free_quadratic_module_integer_symmetric.py index 309404efb64..94a55520b3f 100644 --- a/src/sage/modules/free_quadratic_module_integer_symmetric.py +++ b/src/sage/modules/free_quadratic_module_integer_symmetric.py @@ -1056,7 +1056,7 @@ def maximal_overlattice(self, p=None): v = e.valuation(2) q = b.q().lift() delta = (q*e) % 2 - b = 2**((e.valuation(2)/2).ceil() + delta)*b.lift() + b = 2**(((e.valuation(2)+1)//2) + delta) * b.lift() isotropic.append(b) L = L.overlattice(isotropic) D = L.discriminant_group() @@ -1091,7 +1091,7 @@ def maximal_overlattice(self, p=None): continue # go squarefree D = L.discriminant_group(p).normal_form() - isotropic = [p**(-b.q().lift().valuation(p)/2).ceil()*b.lift() for b in D.gens()] + isotropic = [p**((-b.q().lift().valuation(p)+1)//2) * b.lift() for b in D.gens()] L = L.overlattice(isotropic) # now the p-discriminant_group is a vector space while True: From fa2a465eeb91e5176f0aa960f8e17f590ef2084d Mon Sep 17 00:00:00 2001 From: Peter Bruin Date: Wed, 15 Jan 2020 11:40:54 +0100 Subject: [PATCH 113/133] Trac 29010: add lazy import with deprecation warning for moved classes --- src/sage/rings/number_field/morphism.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/sage/rings/number_field/morphism.py b/src/sage/rings/number_field/morphism.py index a2a13de527e..885431c4436 100644 --- a/src/sage/rings/number_field/morphism.py +++ b/src/sage/rings/number_field/morphism.py @@ -16,6 +16,7 @@ #***************************************************************************** from sage.misc.cachefunc import cached_method +from sage.misc.lazy_import import lazy_import from sage.rings.morphism import RingHomomorphism_im_gens, RingHomomorphism from sage.structure.sequence import Sequence @@ -256,3 +257,8 @@ def _call_(self, x): class CyclotomicFieldHomomorphism_im_gens(NumberFieldHomomorphism_im_gens): pass + + +lazy_import('sage.rings.number_field.homset', + ('NumberFieldHomset', 'RelativeNumberFieldHomset', 'CyclotomicFieldHomset'), + deprecation=29010) From ae7b61b638e9547761dc209fd8bb8633b11fe314 Mon Sep 17 00:00:00 2001 From: Dima Pasechnik Date: Wed, 15 Jan 2020 10:49:08 +0000 Subject: [PATCH 114/133] allow for proper uninstall of R --- build/pkgs/r/spkg-legacy-uninstall | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 build/pkgs/r/spkg-legacy-uninstall diff --git a/build/pkgs/r/spkg-legacy-uninstall b/build/pkgs/r/spkg-legacy-uninstall new file mode 100644 index 00000000000..234d37746fa --- /dev/null +++ b/build/pkgs/r/spkg-legacy-uninstall @@ -0,0 +1,6 @@ +# Remove old install +rm -rf "$SAGE_LOCAL"/lib/r +rm -rf "$SAGE_LOCAL"/lib/R +rm -rf "$SAGE_LOCAL"/lib/R.old +rm -rf "$SAGE_LOCAL"/lib/libRblas.* "$SAGE_LOCAL"/lib/libRlapack.* "$SAGE_LOCAL"/lib/libR.* +rm -f "$SAGE_LOCAL"/bin/R* From 681b55b1f6ba613e1a1e8e60cf32162ba8e92ab1 Mon Sep 17 00:00:00 2001 From: Peter Bruin Date: Wed, 15 Jan 2020 13:50:31 +0100 Subject: [PATCH 115/133] Trac 29008: make RingHomset_generic._element_constructor_() always return an instance of RingHomset_generic.element_class --- src/sage/rings/homset.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sage/rings/homset.py b/src/sage/rings/homset.py index 93cc41b3661..86ac99e1852 100644 --- a/src/sage/rings/homset.py +++ b/src/sage/rings/homset.py @@ -66,7 +66,7 @@ class RingHomset_generic(HomsetWithBase): Set of Homomorphisms from Rational Field to Integer Ring """ - Element = morphism.RingHomomorphism_im_gens + Element = morphism.RingHomomorphism def __init__(self, R, S, category = None): """ @@ -162,13 +162,13 @@ def _element_constructor_(self, x, check=True, base_map=None): from sage.categories.map import Map # Case 0: the homomorphism is given by images of generators if not (isinstance(x, Map) and x.category_for().is_subcategory(Rings())): - return self.element_class(self, x, base_map=base_map, check=check) + return morphism.RingHomomorphism_im_gens(self, x, base_map=base_map, check=check) if base_map is not None: raise ValueError("cannot specify base_map when providing a map") # Case 1: the parent fits if x.parent() == self: if isinstance(x, morphism.RingHomomorphism_im_gens): - return self.element_class(self, x.im_gens()) + return morphism.RingHomomorphism_im_gens(self, x.im_gens()) elif isinstance(x, morphism.RingHomomorphism_cover): return morphism.RingHomomorphism_cover(self) elif isinstance(x, morphism.RingHomomorphism_from_base): @@ -177,7 +177,7 @@ def _element_constructor_(self, x, check=True, base_map=None): try: if (isinstance(x, morphism.RingHomomorphism_im_gens) and x.domain().fraction_field().has_coerce_map_from(self.domain())): - return self.element_class(self, x.im_gens()) + return morphism.RingHomomorphism_im_gens(self, x.im_gens()) except (TypeError, ValueError): pass # Case 3: the homomorphism can be extended by coercion From 049297054b9d8d434b6fe967bacba907a185adc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Wed, 15 Jan 2020 20:56:20 +0100 Subject: [PATCH 116/133] remove some deprecated stuff in modular --- src/sage/modular/all.py | 3 -- .../modular/pollack_stevens/padic_lseries.py | 42 +++++++------------ 2 files changed, 16 insertions(+), 29 deletions(-) diff --git a/src/sage/modular/all.py b/src/sage/modular/all.py index dd2ead1d705..5dfa44415a7 100644 --- a/src/sage/modular/all.py +++ b/src/sage/modular/all.py @@ -41,9 +41,6 @@ from .etaproducts import (EtaGroup, EtaProduct, EtaGroupElement, AllCusps, CuspFamily) -lazy_import("sage.modular.etaproducts", ['num_cusps_of_width', 'qexp_eta', - 'eta_poly_relations'], - deprecation=26196) from .overconvergent.all import * diff --git a/src/sage/modular/pollack_stevens/padic_lseries.py b/src/sage/modular/pollack_stevens/padic_lseries.py index 02a21602c03..b477ff659d8 100644 --- a/src/sage/modular/pollack_stevens/padic_lseries.py +++ b/src/sage/modular/pollack_stevens/padic_lseries.py @@ -3,9 +3,10 @@ `p`-adic `L`-series attached to overconvergent eigensymbols An overconvergent eigensymbol gives rise to a `p`-adic `L`-series, -which is essentially defined as the evaluation of the eigensymbol at the -path `0 \rightarrow \infty`. The resulting distribution on `\ZZ_p` can be restricted -to `\ZZ_p^\times`, thus giving the measure attached to the sought `p`-adic `L`-series. +which is essentially defined as the evaluation of the eigensymbol at +the path `0 \rightarrow \infty`. The resulting distribution on `\ZZ_p` +can be restricted to `\ZZ_p^\times`, thus giving the measure attached +to the sought `p`-adic `L`-series. All this is carefully explained in [PS2011]_. @@ -26,7 +27,6 @@ from sage.arith.all import binomial, kronecker from sage.rings.padics.precision_error import PrecisionError from sage.structure.sage_object import SageObject -from sage.misc.superseded import deprecation class pAdicLseries(SageObject): @@ -36,10 +36,12 @@ class pAdicLseries(SageObject): INPUT: - ``symb`` -- an overconvergent eigensymbol - - ``gamma`` -- topological generator of `1 + p\ZZ_p` (default: `1+p` or 5 if `p=2`) + - ``gamma`` -- topological generator of `1 + p\ZZ_p` + (default: `1+p` or 5 if `p=2`) - ``quadratic_twist`` -- conductor of quadratic twist `\chi` (default: 1) - - ``precision`` -- if ``None`` (default) is specified, the correct precision bound is - computed and the answer is returned modulo that accuracy + - ``precision`` -- if ``None`` (default) is specified, + the correct precision bound is computed and the answer + is returned modulo that accuracy EXAMPLES:: @@ -132,8 +134,7 @@ def __getitem__(self, n): O(7^5) sage: L[1] # long time 5 + 5*7 + 2*7^2 + 2*7^3 + O(7^4) - """ - + """ if n in self._coefficients: return self._coefficients[n] else: @@ -208,7 +209,8 @@ def symbol(self): sage: Phi = phi.p_stabilize_and_lift(2,5) # long time sage: L = pAdicLseries(Phi) # long time sage: L.symbol() # long time - Modular symbol of level 42 with values in Space of 2-adic distributions with k=0 action and precision cap 15 + Modular symbol of level 42 with values in Space of 2-adic + distributions with k=0 action and precision cap 15 sage: L.symbol() is Phi # long time True """ @@ -252,7 +254,8 @@ def _repr_(self): sage: E = EllipticCurve('14a2') sage: L = E.padic_lseries(3, implementation="pollackstevens", precision=4) # long time sage: L._repr_() # long time - '3-adic L-series of Modular symbol of level 42 with values in Space of 3-adic distributions with k=0 action and precision cap 8' + '3-adic L-series of Modular symbol of level 42 with values in + Space of 3-adic distributions with k=0 action and precision cap 8' """ return "%s-adic L-series of %s" % (self.prime(), self.symbol()) @@ -375,7 +378,7 @@ def _basic_integral(self, a, j): symb_twisted.moment(r) for r in range(j + 1)) / ap -def log_gamma_binomial(p, gamma, n, M, old=None): +def log_gamma_binomial(p, gamma, n, M): r""" Return the list of coefficients in the power series expansion (up to precision `M`) of `\binom{\log_p(z)/\log_p(\gamma)}{n}` @@ -399,22 +402,9 @@ def log_gamma_binomial(p, gamma, n, M, old=None): [0, -3/205, 651/84050, -223/42025] sage: log_gamma_binomial(5,1+5,3,4) [0, 2/205, -223/42025, 95228/25845375] - - TESTS:: - - sage: z = polygen(QQ, 'z') - sage: log_gamma_binomial(5,1+5,z,2,4) - doctest:...: DeprecationWarning: the parameter z is ignored and deprecated - See https://trac.sagemath.org/26096 for details. - [0, -3/205, 651/84050, -223/42025] """ - if old is not None: - deprecation(26096, 'the parameter z is ignored and deprecated') - # old deprecated order for the parameters - _, n, M = n, M, old - S = PowerSeriesRing(QQ, 'z') - L = S([0] + [ZZ(-1) ** j / j for j in range(1, M)]) # log_p(1+z) + L = S([0] + [ZZ(-1)**j / j for j in range(1, M)]) # log_p(1+z) loggam = L.O(M) / L(gamma - 1) # log_{gamma}(1+z)= log_p(1+z)/log_p(gamma) return binomial(loggam, n).list() From 258d1124b7b0739c306caaf8a6f9d08bb88eafdc Mon Sep 17 00:00:00 2001 From: Matthias Koeppe Date: Wed, 15 Jan 2020 14:57:11 -0500 Subject: [PATCH 117/133] build/pkgs/pillow/patches/setup.py.patch: Don't fail if Py_MACOS_SYSROOT sysconfig variable does not exist --- build/pkgs/pillow/patches/setup.py.patch | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/build/pkgs/pillow/patches/setup.py.patch b/build/pkgs/pillow/patches/setup.py.patch index 67d8ef46883..e620b00d0a4 100644 --- a/build/pkgs/pillow/patches/setup.py.patch +++ b/build/pkgs/pillow/patches/setup.py.patch @@ -10,13 +10,15 @@ index 15d81e4..5893d3d 100755 import warnings from distutils import ccompiler, sysconfig from distutils.command.build_ext import build_ext -@@ -311,6 +312,9 @@ class pil_build_ext(build_ext): +@@ -311,6 +312,11 @@ class pil_build_ext(build_ext): # darwin ports installation directories _add_directory(library_dirs, "/opt/local/lib") _add_directory(include_dirs, "/opt/local/include") ++ # Check variable introduced in #27631. + sysroot = sysconfig.get_config_var('Py_MACOS_SYSROOT') -+ _add_directory(library_dirs, sysroot+"/usr/lib") -+ _add_directory(include_dirs, sysroot+"/usr/include") ++ if sysroot is not None: ++ _add_directory(library_dirs, sysroot+"/usr/lib") ++ _add_directory(include_dirs, sysroot+"/usr/include") # if Homebrew is installed, use its lib and include directories try: From 56b16181df532469e5c680345166ea116a3e6f15 Mon Sep 17 00:00:00 2001 From: Matthias Koeppe Date: Wed, 15 Jan 2020 15:33:46 -0500 Subject: [PATCH 118/133] build/pkgs/pillow/spkg-install: Help setup.py find zlib.h on macOS; show more build output --- build/pkgs/pillow/spkg-install | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/build/pkgs/pillow/spkg-install b/build/pkgs/pillow/spkg-install index c3a809c3912..18bc8c730df 100644 --- a/build/pkgs/pillow/spkg-install +++ b/build/pkgs/pillow/spkg-install @@ -6,10 +6,18 @@ rm -rf \ "$SAGE_LOCAL"/lib/python*/site-packages/PIL-*.egg* \ "$SAGE_LOCAL"/lib/python*/site-packages/Pillow-*.egg* +if [ "$UNAME" = "Darwin" ] ; then + # #29019 + # https://github.com/python-pillow/Pillow/issues/3438#issuecomment-555019284 + # https://apple.stackexchange.com/questions/372032/usr-include-missing-on-macos-catalina-with-xcode-11/372600#372600 + export CPATH="$CPATH:`xcrun --show-sdk-path`/usr/include" +fi + # Note: Avoid shared libraries inside egg files, Trac #19467 sage-python23 setup.py \ --no-user-cfg \ build_ext \ + --debug \ --disable-jpeg \ install \ --single-version-externally-managed \ From f993d721e5724d2c4db3894c532c24d21bf38510 Mon Sep 17 00:00:00 2001 From: Eric Gourgoulhon Date: Wed, 15 Jan 2020 22:23:58 +0100 Subject: [PATCH 119/133] #29021: fix bug in set_calculus_method --- src/sage/manifolds/manifold.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/sage/manifolds/manifold.py b/src/sage/manifolds/manifold.py index 09bf880522b..81cf6b8c230 100644 --- a/src/sage/manifolds/manifold.py +++ b/src/sage/manifolds/manifold.py @@ -2260,6 +2260,7 @@ def set_calculus_method(self, method): control of the calculus method chart by chart """ + self._calculus_method = method for chart in self._atlas: chart.calculus_method().set(method) From 02f0418649826f05be7f704e963c6f275f81eb80 Mon Sep 17 00:00:00 2001 From: Eric Gourgoulhon Date: Wed, 15 Jan 2020 22:43:26 +0100 Subject: [PATCH 120/133] #29021: add a doctest --- src/sage/manifolds/manifold.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/sage/manifolds/manifold.py b/src/sage/manifolds/manifold.py index 81cf6b8c230..c33a3eace7f 100644 --- a/src/sage/manifolds/manifold.py +++ b/src/sage/manifolds/manifold.py @@ -2254,6 +2254,16 @@ def set_calculus_method(self, method): F: M --> R (x, y) |--> x^2 + cos(y)*sin(x) + The calculus method chosen via ``set_calculus_method()`` applies to any + chart defined subsequently on the manifold:: + + sage: M.set_calculus_method('sympy') + sage: Y. = M.chart() # a new chart + sage: Y.calculus_method() + Available calculus methods (* = current): + - SR (default) + - sympy (*) + .. SEEALSO:: :meth:`~sage.manifolds.chart.Chart.calculus_method` for a From 896d628d5e3de70e01afac79f484c2fc22687b0e Mon Sep 17 00:00:00 2001 From: Kwankyu Lee Date: Thu, 16 Jan 2020 11:54:20 +0900 Subject: [PATCH 121/133] Use p_LDeg for degree --- src/sage/libs/singular/polynomial.pyx | 13 +- .../multi_polynomial_libsingular.pyx | 163 +++++++++--------- 2 files changed, 88 insertions(+), 88 deletions(-) diff --git a/src/sage/libs/singular/polynomial.pyx b/src/sage/libs/singular/polynomial.pyx index 3f625387ff8..3bcf52f4094 100644 --- a/src/sage/libs/singular/polynomial.pyx +++ b/src/sage/libs/singular/polynomial.pyx @@ -29,7 +29,7 @@ from sage.cpython.string cimport bytes_to_str, str_to_bytes from sage.libs.singular.decl cimport number, ideal from sage.libs.singular.decl cimport currRing, rChangeCurrRing from sage.libs.singular.decl cimport p_Copy, p_Add_q, p_Neg, pp_Mult_nn, p_GetCoeff, p_IsConstant, p_Cmp, pNext -from sage.libs.singular.decl cimport p_GetMaxExp, pp_Mult_qq, pPower, p_String, p_GetExp, p_Deg, p_Totaldegree, p_WTotaldegree, p_WDegree +from sage.libs.singular.decl cimport p_GetMaxExp, pp_Mult_qq, pPower, p_String, p_GetExp, p_Deg, p_LDeg, p_Totaldegree, p_WTotaldegree, p_WDegree from sage.libs.singular.decl cimport n_Delete, idInit, fast_map_common_subexp, id_Delete from sage.libs.singular.decl cimport omAlloc0, omStrDup, omFree from sage.libs.singular.decl cimport p_GetComp, p_SetComp @@ -551,21 +551,16 @@ cdef object singular_polynomial_str_with_changed_varnames(poly *p, ring *r, obje cdef long singular_polynomial_deg(poly *p, poly *x, ring *r): cdef long _deg, deg + cdef int dummy deg = -1 - _deg = -1 + _deg = -1 if p == NULL: return -1 if r != currRing: rChangeCurrRing(r) if x == NULL: - while p: - _deg = p_WDegree(p,r) - - if _deg > deg: - deg = _deg - p = pNext(p) - return deg + return p_LDeg(p, &dummy, r) cdef int i = 0 for i in range(1,r.N+1): diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx index 74f964c9845..14a3d8ca527 100644 --- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx @@ -16,32 +16,6 @@ supported by this implementation: - and absolute number fields `\QQ(a)`. -AUTHORS: - -The libSINGULAR interface was implemented by - -- Martin Albrecht (2007-01): initial implementation - -- Joel Mohler (2008-01): misc improvements, polishing - -- Martin Albrecht (2008-08): added `\QQ(a)` and `\ZZ` support - -- Simon King (2009-04): improved coercion - -- Martin Albrecht (2009-05): added `\ZZ/n\ZZ` support, refactoring - -- Martin Albrecht (2009-06): refactored the code to allow better - re-use - -- Simon King (2011-03): Use a faster way of conversion from the base - ring. - -- Volker Braun (2011-06): Major cleanup, refcount singular rings, bugfixes. - -.. TODO:: - - Implement Real, Complex coefficient rings via libSINGULAR - EXAMPLES: We show how to construct various multivariate polynomial rings:: @@ -150,6 +124,31 @@ Check if :trac:`6160` is fixed:: sage: R. = K[] sage: b-j*c b - 1728*c + +.. TODO:: + + Implement Real, Complex coefficient rings via libSINGULAR + +AUTHORS: + +- Martin Albrecht (2007-01): initial implementation + +- Joel Mohler (2008-01): misc improvements, polishing + +- Martin Albrecht (2008-08): added `\QQ(a)` and `\ZZ` support + +- Simon King (2009-04): improved coercion + +- Martin Albrecht (2009-05): added `\ZZ/n\ZZ` support, refactoring + +- Martin Albrecht (2009-06): refactored the code to allow better + re-use + +- Simon King (2011-03): use a faster way of conversion from the base + ring. + +- Volker Braun (2011-06): major cleanup, refcount singular rings, bugfixes. + """ #***************************************************************************** @@ -825,7 +824,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base): p_SetExp(mon, pos+1, m[pos], _ring) p_Setm(mon, _ring) #we can use "_m" because we're merging a monomial and - #"Merge" because this monomial is different from the rest + #"Merge" because this monomial is different from the rest sBucket_Merge_m(bucket, mon) e=0 #we can use "Merge" because the monomials are distinct @@ -2590,22 +2589,20 @@ cdef class MPolynomial_libsingular(MPolynomial): def degree(self, MPolynomial_libsingular x=None, int std_grading=False): """ - Return the maximal degree of this polynomial in ``x``, where - ``x`` must be one of the generators for the parent of this - polynomial. + Return the degree of this polynomial. INPUT: - - ``x`` - (default: ``None``) a multivariate polynomial which is (or - coerces to) a generator of the parent of self. If ``x`` is ``None``, - return the total degree, which is the maximum degree of any monomial. - Note that a matrix term ordering alters the grading of the generators - of the ring; see the tests below. To avoid this behavior, use either - ``exponents()`` for the exponents themselves, or the optional - argument ``std_grading=False``. + - ``x`` -- (default: ``None``) a generator of the parent ring OUTPUT: - integer + + If ``x`` is not given, return the maximum degree of the monomials of + the polynomial. Note that the degree of a monomial is affected by the + gradings given to the generators of the parent ring. If ``x`` is given, + it is (or coercible to) a generator of the parent ring and the output + is the maximum degree in ``x``. This is not affected by the gradings of + the generators. EXAMPLES:: @@ -2620,6 +2617,26 @@ cdef class MPolynomial_libsingular(MPolynomial): sage: (y^10*x - 7*x^2*y^5 + 5*x^3).degree(y) 10 + A matrix term ordering determines the grading of the generators by the + first row of the matrix. :: + + sage: m = matrix(3, [3,2,1,1,1,0,1,0,0]) + sage: m + [3 2 1] + [1 1 0] + [1 0 0] + sage: R. = PolynomialRing(QQ, order=TermOrder(m)) + sage: x.degree(), y.degree(), z.degree() + (3, 2, 1) + sage: f = x^3*y + x*z^4 + sage: f.degree() + 11 + + To get the degree with the standard grading, use ``std_grading=True``. :: + + sage: f.degree(std_grading=True) + 5 + TESTS:: sage: P. = QQ[] @@ -2628,25 +2645,10 @@ cdef class MPolynomial_libsingular(MPolynomial): sage: P(1).degree(x) 0 - With a matrix term ordering, the grading of the generators is - determined by the first row of the matrix. This affects the behavior - of ``degree()`` when no variable is specified. - To evaluate the degree with a standard grading, use the optional - argument ``std_grading=True``. - - sage: tord = TermOrder(matrix([3,0,1,1,1,0,1,0,0])) - sage: R. = PolynomialRing(QQ,3,order=tord) - sage: (x^3*y+x*z^4).degree() - 9 - sage: (x^3*y+x*z^4).degree(std_grading=True) - 5 - sage: x.degree(x), y.degree(y), z.degree(z) - (1, 1, 1) - The following example is inspired by :trac:`11652`:: sage: R. = ZZ[] - sage: poly = p+q^2+t^3 + sage: poly = p + q^2 + t^3 sage: poly = poly.polynomial(t)[0] sage: poly q^2 + p @@ -2692,18 +2694,17 @@ cdef class MPolynomial_libsingular(MPolynomial): cdef ring *r = self._parent_ring cdef poly *p = self._poly if not x: - if not std_grading: - return singular_polynomial_deg(p,NULL,r) - else: + if std_grading: return self.total_degree(std_grading=True) + return singular_polynomial_deg(p, NULL, r) if not x.parent() is self.parent(): try: x = self.parent().coerce(x) except TypeError: - raise TypeError("argument must canonically coerce to parent") + raise TypeError("argument is not coercible to the parent") if not x.is_generator(): - raise TypeError("argument must be a generator") + raise TypeError("argument is not a generator") return singular_polynomial_deg(p, x._poly, r) @@ -2715,25 +2716,41 @@ cdef class MPolynomial_libsingular(MPolynomial): EXAMPLES:: sage: R. = QQ[] - sage: f=2*x*y^3*z^2 + sage: f = 2*x*y^3*z^2 sage: f.total_degree() 6 - sage: f=4*x^2*y^2*z^3 + sage: f = 4*x^2*y^2*z^3 sage: f.total_degree() 7 - sage: f=99*x^6*y^3*z^9 + sage: f = 99*x^6*y^3*z^9 sage: f.total_degree() 18 - sage: f=x*y^3*z^6+3*x^2 + sage: f = x*y^3*z^6+3*x^2 sage: f.total_degree() 10 - sage: f=z^3+8*x^4*y^5*z + sage: f = z^3+8*x^4*y^5*z sage: f.total_degree() 10 - sage: f=z^9+10*x^4+y^8*x^2 + sage: f = z^9+10*x^4+y^8*x^2 sage: f.total_degree() 10 + A matrix term ordering changes the grading. To get the total degree + using the standard grading, use ``std_grading=True``:: + + sage: tord = TermOrder(matrix(3, [3,2,1,1,1,0,1,0,0])) + sage: tord + Matrix term order with matrix + [3 2 1] + [1 1 0] + [1 0 0] + sage: R. = PolynomialRing(QQ, order=tord) + sage: f = x^2*y + sage: f.total_degree() + 8 + sage: f.total_degree(std_grading=True) + 3 + TESTS:: sage: R. = QQ[] @@ -2741,30 +2758,18 @@ cdef class MPolynomial_libsingular(MPolynomial): -1 sage: R(1).total_degree() 0 - - With a matrix term ordering, the grading changes. - To evaluate the total degree using the standard grading, - use the optional argument``std_grading=True``:: - - sage: tord=TermOrder(matrix([3,0,1,1,1,0,1,0,0])) - sage: R. = PolynomialRing(QQ,3,order=tord) - sage: (x^2*y).total_degree() - 6 - sage: (x^2*y).total_degree(std_grading=True) - 3 """ cdef int i, result cdef poly *p = self._poly cdef ring *r = self._parent_ring - if not std_grading: - return singular_polynomial_deg(p,NULL,r) - else: + if std_grading: result = 0 while p: result = max(result, sum([p_GetExp(p,i,r) for i in xrange(1,r.N+1)])) p = pNext(p) return result + return singular_polynomial_deg(p, NULL, r) def degrees(self): """ From 85147f9a7bb3741646693b913bbb96fff1e11432 Mon Sep 17 00:00:00 2001 From: Matthias Koeppe Date: Wed, 15 Jan 2020 22:02:11 -0500 Subject: [PATCH 122/133] build/pkgs/numpy/lapack_conf.py: Add a [DEFAULT] section to site.cfg --- build/pkgs/numpy/lapack_conf.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/build/pkgs/numpy/lapack_conf.py b/build/pkgs/numpy/lapack_conf.py index d127d08def8..9ded057c3c2 100644 --- a/build/pkgs/numpy/lapack_conf.py +++ b/build/pkgs/numpy/lapack_conf.py @@ -8,6 +8,11 @@ conf_file.write('library_dirs = '+ os.environ['SAGE_LOCAL']+ '/lib\n') conf_file.write('include_dirs = '+ os.environ['SAGE_LOCAL']+ '/include\n') +conf_file.write('[DEFAULT]\n') +conf_file.write('library_dirs = '+ os.environ['SAGE_LOCAL']+ '/lib\n') +conf_file.write('include_dirs = '+ os.environ['SAGE_LOCAL']+ '/include\n') + + pc_blas = pkgconfig.parse('cblas blas') pc_lapack = pkgconfig.parse('lapack') From 06c2c54e251d6dc69dbb01f36c18990881e8c808 Mon Sep 17 00:00:00 2001 From: Kwankyu Lee Date: Thu, 16 Jan 2020 12:11:48 +0900 Subject: [PATCH 123/133] Doctest fixes --- src/sage/rings/polynomial/multi_polynomial_libsingular.pyx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx index 14a3d8ca527..aeb4f91fd34 100644 --- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx @@ -2659,7 +2659,7 @@ cdef class MPolynomial_libsingular(MPolynomial): sage: poly.degree(q) Traceback (most recent call last): ... - TypeError: argument must canonically coerce to parent + TypeError: argument is not coercible to the parent Using a non-canonical coercion does work, but we require this to be done explicitly, since it can lead to confusing results @@ -2681,7 +2681,7 @@ cdef class MPolynomial_libsingular(MPolynomial): sage: poly.degree(pp+1) Traceback (most recent call last): ... - TypeError: argument must be a generator + TypeError: argument is not a generator Canonical coercions are used:: From f8e34e1f798daf33d7a0dafa72c381e996eff411 Mon Sep 17 00:00:00 2001 From: Travis Scrimshaw Date: Thu, 16 Jan 2020 14:52:40 +1000 Subject: [PATCH 124/133] Making polynomial quotient rings category parameterization be a category. --- src/sage/categories/fields.py | 4 ++-- .../polynomial/polynomial_quotient_ring.py | 20 ++++++++++++++----- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/sage/categories/fields.py b/src/sage/categories/fields.py index af9f1b29122..686c5eb369a 100644 --- a/src/sage/categories/fields.py +++ b/src/sage/categories/fields.py @@ -141,8 +141,8 @@ def _contains_helper(cls): sage: P. = QQ[] sage: Q = P.quotient(x^2+2) sage: Q.category() - Category of commutative no zero divisors quotients - of algebras over Rational Field + Category of commutative no zero divisors quotients of algebras + over (number fields and quotient fields and metric spaces) sage: F = Fields() sage: F._contains_helper(Q) False diff --git a/src/sage/rings/polynomial/polynomial_quotient_ring.py b/src/sage/rings/polynomial/polynomial_quotient_ring.py index 14cc009a7b0..397e92d0fdc 100644 --- a/src/sage/rings/polynomial/polynomial_quotient_ring.py +++ b/src/sage/rings/polynomial/polynomial_quotient_ring.py @@ -311,7 +311,8 @@ class of the quotient ring and its newly created elements. sage: P. = QQ[] sage: Q = P.quotient(x^2+2) sage: Q.category() - Category of commutative no zero divisors quotients of algebras over Rational Field + Category of commutative no zero divisors quotients of algebras over + (number fields and quotient fields and metric spaces) We verify that the elements belong to the correct element class. Also, we list the attributes that are provided by the element @@ -330,8 +331,8 @@ class of the category, and store the current class of the quotient sage: Q in Fields() True sage: Q.category() - Category of commutative division no zero divisors - quotients of algebras over Rational Field + Category of commutative division no zero divisors quotients of algebras + over (number fields and quotient fields and metric spaces) sage: first_class == Q.__class__ False sage: [s for s in dir(Q.category().element_class) if not s.startswith('_')] @@ -399,7 +400,7 @@ def __init__(self, ring, polynomial, name=None, category=None): self.__ring = ring self.__polynomial = polynomial - category = CommutativeAlgebras(ring.base_ring()).Quotients().or_subcategory(category) + category = CommutativeAlgebras(ring.base_ring().category()).Quotients().or_subcategory(category) CommutativeRing.__init__(self, ring, names=name, category=category) def _element_constructor_(self, x): @@ -2057,8 +2058,17 @@ def __init__(self, ring, polynomial, name=None, category=None): sage: S in IntegralDomains() True + + Check that :trac:`29017` is fixed:: + + sage: R. = ZZ[] + sage: Q = R.quo(x-1) + sage: H = R.Hom(Q) + sage: h = R.hom(Q) + sage: h.parent() is H + True """ - category = CommutativeAlgebras(ring.base_ring()).Quotients().NoZeroDivisors().or_subcategory(category) + category = CommutativeAlgebras(ring.base_ring().category()).Quotients().NoZeroDivisors().or_subcategory(category) PolynomialQuotientRing_generic.__init__(self, ring, polynomial, name, category) def field_extension(self, names): From 57063585de32842eee101e7ad11d0b467d1351bd Mon Sep 17 00:00:00 2001 From: Dima Pasechnik Date: Thu, 16 Jan 2020 13:47:57 +0000 Subject: [PATCH 125/133] add missing # long time tags --- src/sage/coding/linear_code.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/coding/linear_code.py b/src/sage/coding/linear_code.py index 47e3d7d80b0..e1064980632 100644 --- a/src/sage/coding/linear_code.py +++ b/src/sage/coding/linear_code.py @@ -3711,9 +3711,9 @@ class LinearCodeSyndromeDecoder(Decoder): is bigger than both the covering radius and half the minimum distance:: sage: D = C.decoder("Syndrome", maximum_error_weight = 5) # long time - sage: D.decoder_type() + sage: D.decoder_type() # long time {'complete', 'hard-decision', 'might-error'} - sage: D.decoding_radius() + sage: D.decoding_radius() # long time 4 In that case, the decoder might still return an unexpected codeword, but From 1c894f8aa62238065d7f199b1020d6f5d5aff754 Mon Sep 17 00:00:00 2001 From: dcoudert Date: Thu, 16 Jan 2020 17:20:51 +0100 Subject: [PATCH 126/133] trac #28473: include review comments --- src/sage/graphs/graph.py | 5 +- .../clique_separators.pyx | 46 +++++++++++-------- src/sage/graphs/traversals.pyx | 6 ++- 3 files changed, 33 insertions(+), 24 deletions(-) diff --git a/src/sage/graphs/graph.py b/src/sage/graphs/graph.py index 7a72ee05b8c..6450e9574ef 100644 --- a/src/sage/graphs/graph.py +++ b/src/sage/graphs/graph.py @@ -8627,9 +8627,8 @@ def most_common_neighbors(self, nonedgesonly=True): from sage.graphs.domination import is_redundant from sage.graphs.domination import private_neighbors from sage.graphs.domination import minimal_dominating_sets - from sage.graphs.traversals import lex_M - from sage.graphs.traversals import maximum_cardinality_search - from sage.graphs.traversals import maximum_cardinality_search_M + from sage.graphs.traversals import (lex_M, maximum_cardinality_search, + maximum_cardinality_search_M) _additional_categories = { "is_long_hole_free" : "Graph properties", diff --git a/src/sage/graphs/graph_decompositions/clique_separators.pyx b/src/sage/graphs/graph_decompositions/clique_separators.pyx index bae829985f6..3df6224d839 100644 --- a/src/sage/graphs/graph_decompositions/clique_separators.pyx +++ b/src/sage/graphs/graph_decompositions/clique_separators.pyx @@ -141,6 +141,21 @@ def make_labelled_rooted_tree(atoms, cliques): return to_tree(0, len(cliques)) +cdef inline bint is_clique(short_digraph sd, vector[int] Hx): + """ + Check if the subgraph sd[Hx] is a clique. + + This is a helper function of ``atoms_and_clique_separators``. + """ + cdef size_t Hx_size = Hx.size() + cdef size_t i, j + cdef int u + for i in range(Hx_size -1): + u = Hx[i] + for j in range(i + 1, Hx_size): + if not has_edge(sd, u, Hx[j]): + return False + return True def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=False): r""" @@ -422,7 +437,10 @@ def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=Fal Sh.extend(res[1]) if not first: Sc.append(Set()) - Sc.extend(res[2 if separators else 1]) + if separators: + Sc.extend(res[2]) + else: + Sc.extend(res[1]) first = False # Format and return the result @@ -503,6 +521,7 @@ def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=Fal cdef frozenset Sint cdef vector[int] Sint_min cdef vector[int] Cint + cdef vector[int] Hx cdef size_t ui, vi cdef bint stop @@ -510,26 +529,15 @@ def atoms_and_clique_separators(G, tree=False, rooted_tree=False, separators=Fal sig_check() x = alpha[i] if X[x] and not H[x].empty(): + Hx = H[x] if separators: - Sh.append(Set(int_to_vertex[u] for u in H[x])) - - # Check if the subgraph of G[H[x]] is a clique - stop = False - for ui in range(H[x].size() -1): - u = H[x][ui] - for vi in range(ui + 1, H[x].size()): - if not has_edge(sd, u, H[x][vi]): - stop = True - break - if stop: - break - - # Weird Python syntax which is useful once in a lifetime : if break - # was never called in the loop above, G[H[x]] = G[S] is a clique - else: - # Extract the connected component of Gp - S containing x - Sint = frozenset(H[x]) + Sh.append(Set(int_to_vertex[u] for u in Hx)) + + if is_clique(sd, Hx): + # The subgraph G[H[x]] = G[S] is a clique. + # We extract the connected component of Gp - S containing x + Sint = frozenset(Hx) Sint_min.clear() Cint.clear() Cint.push_back(x) diff --git a/src/sage/graphs/traversals.pyx b/src/sage/graphs/traversals.pyx index 1cebe2cca8d..5116f71f75b 100644 --- a/src/sage/graphs/traversals.pyx +++ b/src/sage/graphs/traversals.pyx @@ -1366,7 +1366,9 @@ def maximum_cardinality_search(G, reverse=False, tree=False, initial_vertex=None - ``initial_vertex`` -- (default: ``None``); the first vertex to consider - OUPUT: by default, return the ordering `\alpha` as a list. When ``tree`` is + OUTPUT: + + By default, return the ordering `\alpha` as a list. When ``tree`` is ``True``, the method returns a tuple `(\alpha, T)`, where `T` is a directed tree with the same set of vertices as `G`and a directed edge from `u` to `v` if `u` was the first vertex to saw `v`. @@ -1446,7 +1448,7 @@ def maximum_cardinality_search(G, reverse=False, tree=False, initial_vertex=None cdef int* pred = mem.allocarray(N, sizeof(int)) cdef int i, u, v - for i in range(G.order()): + for i in range(N): weight[i] = 0 seen[i] = False pred[i] = i From aa3b1db81f29f717fccfa61761281d1a7f254225 Mon Sep 17 00:00:00 2001 From: Dima Pasechnik Date: Thu, 16 Jan 2020 16:33:32 +0000 Subject: [PATCH 127/133] removed unneeded rm's in spkg-install this is handled by spkg-legacy-uninstall now --- build/pkgs/r/spkg-install | 6 ------ 1 file changed, 6 deletions(-) diff --git a/build/pkgs/r/spkg-install b/build/pkgs/r/spkg-install index 3f85e847deb..e83ca680cda 100644 --- a/build/pkgs/r/spkg-install +++ b/build/pkgs/r/spkg-install @@ -160,12 +160,6 @@ if [ $? -ne 0 ]; then exit 1 fi -# Remove old install -rm -rf "$SAGE_LOCAL"/lib/r -rm -rf "$SAGE_LOCAL"/lib/R -rm -rf "$SAGE_LOCAL"/lib/R.old -rm -rf "$SAGE_LOCAL"/lib/libRblas.* "$SAGE_LOCAL"/lib/libRlapack.* "$SAGE_LOCAL"/lib/libR.* - # Install new version $MAKE install if [ $? -ne 0 ]; then From 63c84e49b49fa6eb15cdb317ae4c798c7aa168c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Thu, 16 Jan 2020 21:16:47 +0100 Subject: [PATCH 128/133] some cleanup in power series pyx files --- src/sage/rings/power_series_pari.pyx | 8 +-- src/sage/rings/power_series_poly.pyx | 87 ++++++++++++++-------------- 2 files changed, 46 insertions(+), 49 deletions(-) diff --git a/src/sage/rings/power_series_pari.pyx b/src/sage/rings/power_series_pari.pyx index 65c3ec23643..b4d32da0b98 100644 --- a/src/sage/rings/power_series_pari.pyx +++ b/src/sage/rings/power_series_pari.pyx @@ -59,23 +59,21 @@ AUTHORS: """ -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2013-2017 Peter Bruin # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** from cypari2.gen cimport Gen as pari_gen from cypari2.pari_instance cimport get_var from cypari2.paridecl cimport gel, typ, lg, valp, varn, t_POL, t_SER, t_RFRAC, t_VEC from sage.libs.pari.all import pari -from sage.misc.superseded import deprecated_function_alias - from sage.rings.polynomial.polynomial_element cimport Polynomial from sage.rings.power_series_ring_element cimport PowerSeries from sage.structure.element cimport Element, RingElement diff --git a/src/sage/rings/power_series_poly.pyx b/src/sage/rings/power_series_poly.pyx index f411b46b3ae..bc386db4a7a 100644 --- a/src/sage/rings/power_series_poly.pyx +++ b/src/sage/rings/power_series_poly.pyx @@ -9,7 +9,6 @@ from .power_series_ring_element cimport PowerSeries from sage.structure.element cimport Element, ModuleElement, RingElement from .infinity import infinity, is_Infinite from sage.libs.all import pari_gen, PariError -from sage.misc.superseded import deprecated_function_alias cdef class PowerSeries_poly(PowerSeries): @@ -103,7 +102,7 @@ cdef class PowerSeries_poly(PowerSeries): def polynomial(self): """ - Return the underlying polynomial of self. + Return the underlying polynomial of ``self``. EXAMPLES:: @@ -116,7 +115,7 @@ cdef class PowerSeries_poly(PowerSeries): def valuation(self): """ - Return the valuation of self. + Return the valuation of ``self``. EXAMPLES:: @@ -137,10 +136,11 @@ cdef class PowerSeries_poly(PowerSeries): def degree(self): """ - Return the degree of the underlying polynomial of self. That - is, if self is of the form f(x) + O(x^n), we return the degree - of f(x). Note that if f(x) is 0, we return -1, just as with - polynomials. + Return the degree of the underlying polynomial of ``self``. + + That is, if ``self`` is of the form f(x) + O(x^n), we return + the degree of f(x). Note that if f(x) is 0, we return -1, just + as with polynomials. EXAMPLES:: @@ -156,7 +156,7 @@ cdef class PowerSeries_poly(PowerSeries): def __nonzero__(self): """ - Return True if self is nonzero, and False otherwise. + Return ``True`` if ``self`` is nonzero, and ``False`` otherwise. EXAMPLES:: @@ -179,14 +179,14 @@ cdef class PowerSeries_poly(PowerSeries): - ``x``: - a tuple of elements the first of which can be meaningfully - substituted in self, with the remainder used for substitution - in the coefficients of self. + substituted in ``self``, with the remainder used for substitution + in the coefficients of ``self``. - a dictionary for kwds:value pairs. If the variable name of self is a keyword it is substituted for. Other keywords are used for substitution in the coefficients of self. - OUTPUT: the value of self after substitution. + OUTPUT: the value of ``self`` after substitution. EXAMPLES:: @@ -404,13 +404,13 @@ cdef class PowerSeries_poly(PowerSeries): def __getitem__(self, n): """ - Return the nth coefficient of self. + Return the ``n``-th coefficient of ``self``. - If n is a slice object, this will return a power series of the - same precision, whose coefficients are the same as self for + If ``n`` is a slice object, this will return a power series of the + same precision, whose coefficients are the same as ``self`` for those indices in the slice, and 0 otherwise. - Returns 0 for negative coefficients. Raises an IndexError if + Returns 0 for negative coefficients. Raises an ``IndexError`` if try to access beyond known coefficients. EXAMPLES:: @@ -545,7 +545,7 @@ cdef class PowerSeries_poly(PowerSeries): cpdef _rmul_(self, Element c): """ - Multiply self on the right by a scalar. + Multiply ``self`` on the right by a scalar. EXAMPLES:: @@ -558,7 +558,7 @@ cdef class PowerSeries_poly(PowerSeries): cpdef _lmul_(self, Element c): """ - Multiply self on the left by a scalar. + Multiply ``self`` on the left by a scalar. EXAMPLES:: @@ -571,7 +571,7 @@ cdef class PowerSeries_poly(PowerSeries): def __lshift__(PowerSeries_poly self, n): """ - Shift self to the left by n, i.e. multiply by x^n. + Shift ``self`` to the left by ``n``, i.e. multiply by `x^n`. EXAMPLES:: @@ -587,7 +587,7 @@ cdef class PowerSeries_poly(PowerSeries): def __rshift__(PowerSeries_poly self, n): """ - Shift self to the right by n, i.e. multiply by x^-n and + Shift ``self`` to the right by ``n``, i.e. multiply by `x^-n` and remove any terms of negative exponent. EXAMPLES:: @@ -720,9 +720,9 @@ cdef class PowerSeries_poly(PowerSeries): cdef _inplace_truncate(self, long prec): """ - Truncate self to precision ``prec`` in place. + Truncate ``self`` to precision ``prec`` in place. - NOTE:: + .. NOTE:: This is very unsafe, since power series are supposed to be immutable in Sage. Use at your own risk! @@ -749,9 +749,11 @@ cdef class PowerSeries_poly(PowerSeries): def list(self): """ - Return the list of known coefficients for self. This is just - the list of coefficients of the underlying polynomial, so in - particular, need not have length equal to self.prec(). + Return the list of known coefficients for ``self``. + + This is just the list of coefficients of the underlying + polynomial, so in particular, need not have length equal to + ``self.prec()``. EXAMPLES:: @@ -764,9 +766,11 @@ cdef class PowerSeries_poly(PowerSeries): def dict(self): """ - Return a dictionary of coefficients for self. This is simply a - dict for the underlying polynomial, so need not have keys - corresponding to every number smaller than self.prec(). + Return a dictionary of coefficients for ``self``. + + This is simply a dict for the underlying polynomial, so need + not have keys corresponding to every number smaller than + ``self.prec()``. EXAMPLES:: @@ -780,17 +784,17 @@ cdef class PowerSeries_poly(PowerSeries): def _derivative(self, var=None): """ Return the derivative of this power series with respect - to the variable var. + to the variable ``var``. - If var is None or is the generator of this ring, we take the derivative - with respect to the generator. + If ``var`` is ``None`` or is the generator of this ring, we + take the derivative with respect to the generator. - Otherwise, we call _derivative(var) on each coefficient of + Otherwise, we call ``_derivative(var)`` on each coefficient of the series. - SEEALSO:: + .. SEEALSO:: - self.derivative() + ``self.derivative()`` EXAMPLES:: @@ -836,7 +840,7 @@ cdef class PowerSeries_poly(PowerSeries): def integral(self,var=None): """ - The integral of this power series + Return the integral of this power series. By default, the integration variable is the variable of the power series. @@ -880,6 +884,7 @@ cdef class PowerSeries_poly(PowerSeries): def reverse(self, precision=None): """ Return the reverse of f, i.e., the series g such that g(f(x)) = x. + Given an optional argument ``precision``, return the reverse with given precision (note that the reverse can have precision at most ``f.prec()``). If ``f`` has infinite precision, and the argument @@ -991,7 +996,6 @@ cdef class PowerSeries_poly(PowerSeries): sage: (x - x^2).reverse(precision=3) x + x^2 + O(x^3) - TESTS:: sage: R. = PowerSeriesRing(QQ) @@ -1000,9 +1004,6 @@ cdef class PowerSeries_poly(PowerSeries): Traceback (most recent call last): ... ValueError: Series must have valuation one for reversion. - - - """ if self.valuation() != 1: raise ValueError("Series must have valuation one for reversion.") @@ -1038,8 +1039,7 @@ cdef class PowerSeries_poly(PowerSeries): from sage.misc.all import verbose verbose("passing to pari failed; trying Lagrange inversion") - - if f.parent().characteristic() > 0: + if f.parent().characteristic(): # over a ring of positive characteristic, attempt lifting to # characteristic zero ring verbose("parent ring has positive characteristic; attempting lift to characteristic zero") @@ -1064,7 +1064,7 @@ cdef class PowerSeries_poly(PowerSeries): def pade(self, m, n): r""" - Returns the Padé approximant of ``self`` of index `(m, n)`. + Return the Padé approximant of ``self`` of index `(m, n)`. The Padé approximant of index `(m, n)` of a formal power series `f` is the quotient `Q/P` of two polynomials `Q` and `P` @@ -1149,7 +1149,6 @@ cdef class PowerSeries_poly(PowerSeries): u, v = c.rational_reconstruct(z**(n + m + 1), m, n); return u/v - def _symbolic_(self, ring): """ Conversion to symbolic series. @@ -1188,9 +1187,9 @@ cdef class PowerSeries_poly(PowerSeries): return pex.series(var, self.prec()) -def make_powerseries_poly_v0(parent, f, prec, is_gen): +def make_powerseries_poly_v0(parent, f, prec, is_gen): """ - Return the power series specified by f, prec, and is_gen. + Return the power series specified by ``f``, ``prec``, and ``is_gen``. This function exists for the purposes of pickling. Do not delete this function -- if you change the internal representation, From 7ee37044da6afc985a34d292c5d41836b24edecb Mon Sep 17 00:00:00 2001 From: Antonio Rojas Date: Thu, 16 Jan 2020 22:36:28 +0100 Subject: [PATCH 129/133] Import importlib first to avoid deprecation warnings --- src/sage/parallel/use_fork.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/parallel/use_fork.py b/src/sage/parallel/use_fork.py index 77842ec794a..2c1689bd256 100644 --- a/src/sage/parallel/use_fork.py +++ b/src/sage/parallel/use_fork.py @@ -281,9 +281,9 @@ def _subprocess(self, f, dir, args, kwds={}): """ import os, sys try: - from imp import reload - except ImportError: from importlib import reload + except ImportError: + from imp import reload from sage.misc.persist import save # Make it so all stdout is sent to a file so it can From 0100ac05053ca466fadabc168577971d11e2e97d Mon Sep 17 00:00:00 2001 From: Kwankyu Lee Date: Fri, 17 Jan 2020 11:44:52 +0900 Subject: [PATCH 130/133] Fixes for reviewer comments --- src/sage/libs/singular/polynomial.pyx | 2 +- .../multi_polynomial_libsingular.pyx | 25 ++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/sage/libs/singular/polynomial.pyx b/src/sage/libs/singular/polynomial.pyx index 3bcf52f4094..7687de8f2d8 100644 --- a/src/sage/libs/singular/polynomial.pyx +++ b/src/sage/libs/singular/polynomial.pyx @@ -29,7 +29,7 @@ from sage.cpython.string cimport bytes_to_str, str_to_bytes from sage.libs.singular.decl cimport number, ideal from sage.libs.singular.decl cimport currRing, rChangeCurrRing from sage.libs.singular.decl cimport p_Copy, p_Add_q, p_Neg, pp_Mult_nn, p_GetCoeff, p_IsConstant, p_Cmp, pNext -from sage.libs.singular.decl cimport p_GetMaxExp, pp_Mult_qq, pPower, p_String, p_GetExp, p_Deg, p_LDeg, p_Totaldegree, p_WTotaldegree, p_WDegree +from sage.libs.singular.decl cimport p_GetMaxExp, pp_Mult_qq, pPower, p_String, p_GetExp, p_LDeg from sage.libs.singular.decl cimport n_Delete, idInit, fast_map_common_subexp, id_Delete from sage.libs.singular.decl cimport omAlloc0, omStrDup, omFree from sage.libs.singular.decl cimport p_GetComp, p_SetComp diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx index aeb4f91fd34..caaf1650e9b 100644 --- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx @@ -2617,6 +2617,14 @@ cdef class MPolynomial_libsingular(MPolynomial): sage: (y^10*x - 7*x^2*y^5 + 5*x^3).degree(y) 10 + The term ordering of the parent ring determines the grading of the + generators. :: + + sage: T = TermOrder('wdegrevlex', (1,2,3,4)) + sage: R = PolynomialRing(QQ, 'x', 12, order=T+T+T) + sage: [x.degree() for x in R.gens()] + [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4] + A matrix term ordering determines the grading of the generators by the first row of the matrix. :: @@ -2632,7 +2640,22 @@ cdef class MPolynomial_libsingular(MPolynomial): sage: f.degree() 11 - To get the degree with the standard grading, use ``std_grading=True``. :: + If the first row contains zero, the grading becomes the standard one. :: + + sage: m = matrix(3, [3,0,1,1,1,0,1,0,0]) + sage: m + [3 0 1] + [1 1 0] + [1 0 0] + sage: R. = PolynomialRing(QQ, order=TermOrder(m)) + sage: x.degree(), y.degree(), z.degree() + (1, 1, 1) + sage: f = x^3*y + x*z^4 + sage: f.degree() + 5 + + To get the degree with the standard grading regardless of the term + ordering of the parent ring, use ``std_grading=True``. :: sage: f.degree(std_grading=True) 5 From 59fa95c53dd4baffaf97beff9ac228693c7b4250 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Fri, 17 Jan 2020 08:32:34 +0100 Subject: [PATCH 131/133] fix returns plugin --- src/sage/rings/power_series_poly.pyx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sage/rings/power_series_poly.pyx b/src/sage/rings/power_series_poly.pyx index bc386db4a7a..16a87b48bba 100644 --- a/src/sage/rings/power_series_poly.pyx +++ b/src/sage/rings/power_series_poly.pyx @@ -410,8 +410,8 @@ cdef class PowerSeries_poly(PowerSeries): same precision, whose coefficients are the same as ``self`` for those indices in the slice, and 0 otherwise. - Returns 0 for negative coefficients. Raises an ``IndexError`` if - try to access beyond known coefficients. + This returns 0 for negative coefficients and raises an + ``IndexError`` if trying to access beyond known coefficients. EXAMPLES:: From da67634e796cb1ec9a259b1f6ddcb31b8736e418 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Fri, 17 Jan 2020 21:01:22 +0100 Subject: [PATCH 132/133] trac 29029 fix details --- src/sage/rings/power_series_poly.pyx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sage/rings/power_series_poly.pyx b/src/sage/rings/power_series_poly.pyx index 16a87b48bba..6baccef4138 100644 --- a/src/sage/rings/power_series_poly.pyx +++ b/src/sage/rings/power_series_poly.pyx @@ -138,9 +138,9 @@ cdef class PowerSeries_poly(PowerSeries): """ Return the degree of the underlying polynomial of ``self``. - That is, if ``self`` is of the form f(x) + O(x^n), we return - the degree of f(x). Note that if f(x) is 0, we return -1, just - as with polynomials. + That is, if ``self`` is of the form `f(x) + O(x^n)`, we return + the degree of `f(x)`. Note that if `f(x)` is `0`, we return `-1`, + just as with polynomials. EXAMPLES:: @@ -587,7 +587,7 @@ cdef class PowerSeries_poly(PowerSeries): def __rshift__(PowerSeries_poly self, n): """ - Shift ``self`` to the right by ``n``, i.e. multiply by `x^-n` and + Shift ``self`` to the right by ``n``, i.e. multiply by `x^{-n}` and remove any terms of negative exponent. EXAMPLES:: From dde78cbd22ea84dda7f3e985e6d50ff0d8a8f193 Mon Sep 17 00:00:00 2001 From: Release Manager Date: Tue, 21 Jan 2020 22:56:07 +0100 Subject: [PATCH 133/133] Updated SageMath version to 9.1.beta1 --- VERSION.txt | 2 +- build/pkgs/configure/checksums.ini | 6 +++--- build/pkgs/configure/package-version.txt | 2 +- src/bin/sage-version.sh | 6 +++--- src/sage/version.py | 6 +++--- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/VERSION.txt b/VERSION.txt index 0c5f5563dc4..d44f31ea138 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -1 +1 @@ -SageMath version 9.1.beta0, Release Date: 2020-01-10 +SageMath version 9.1.beta1, Release Date: 2020-01-21 diff --git a/build/pkgs/configure/checksums.ini b/build/pkgs/configure/checksums.ini index 33c48ea3df6..1537fb00361 100644 --- a/build/pkgs/configure/checksums.ini +++ b/build/pkgs/configure/checksums.ini @@ -1,4 +1,4 @@ tarball=configure-VERSION.tar.gz -sha1=3506adf8c82496e255cfdbbdcf29834dfe304972 -md5=5025184149d48727710a67a8cff91387 -cksum=914476400 +sha1=029fe778cefcb82231353c0dab72a75769ffdcf9 +md5=b4231b3e4ce67fc656ba9532b123485a +cksum=3808756319 diff --git a/build/pkgs/configure/package-version.txt b/build/pkgs/configure/package-version.txt index 172262e9837..ce2624fb22f 100644 --- a/build/pkgs/configure/package-version.txt +++ b/build/pkgs/configure/package-version.txt @@ -1 +1 @@ -c17110f970d3b0d8b0857cd02edd96b8f03430ef +4fd5d56ecea2c81d58e9e43bd5f07b05e863bc7c diff --git a/src/bin/sage-version.sh b/src/bin/sage-version.sh index 57f8fb95cc0..dc09574db4e 100644 --- a/src/bin/sage-version.sh +++ b/src/bin/sage-version.sh @@ -1,5 +1,5 @@ # Sage version information for shell scripts # This file is auto-generated by the sage-update-version script, do not edit! -SAGE_VERSION='9.1.beta0' -SAGE_RELEASE_DATE='2020-01-10' -SAGE_VERSION_BANNER='SageMath version 9.1.beta0, Release Date: 2020-01-10' +SAGE_VERSION='9.1.beta1' +SAGE_RELEASE_DATE='2020-01-21' +SAGE_VERSION_BANNER='SageMath version 9.1.beta1, Release Date: 2020-01-21' diff --git a/src/sage/version.py b/src/sage/version.py index dafb2c7d3f4..48c223a1d1d 100644 --- a/src/sage/version.py +++ b/src/sage/version.py @@ -1,5 +1,5 @@ # Sage version information for Python scripts # This file is auto-generated by the sage-update-version script, do not edit! -version = '9.1.beta0' -date = '2020-01-10' -banner = 'SageMath version 9.1.beta0, Release Date: 2020-01-10' +version = '9.1.beta1' +date = '2020-01-21' +banner = 'SageMath version 9.1.beta1, Release Date: 2020-01-21'