diff --git a/.gitattributes b/.gitattributes index fa760c652c847a013baae67cf81c2d0d045753ae..aa51198f8806bc6802c2872ccd4ccf98707a8978 100644 --- a/.gitattributes +++ b/.gitattributes @@ -574,3 +574,8 @@ moondream/lib/python3.10/site-packages/narwhals/__pycache__/series.cpython-310.p moondream/lib/python3.10/site-packages/narwhals/__pycache__/expr.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text moondream/lib/python3.10/site-packages/narwhals/__pycache__/dataframe.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text mantis_evalkit/lib/python3.10/site-packages/pyarrow/libarrow_flight.so.1900 filter=lfs diff=lfs merge=lfs -text +mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/_csparsetools.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_base.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +moondream/lib/python3.10/site-packages/numpy/random/mtrand.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +moondream/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +moondream/lib/python3.10/site-packages/onnx/onnx_cpp2py_export.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/_csparsetools.cpython-310-x86_64-linux-gnu.so b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/_csparsetools.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..68d103053c500825dbc878247b60a020f8983731 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/_csparsetools.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbc4aa657a759ee9130cc8babb9c626a2e554ae582a34ae90a35564312269ab3 +size 839504 diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/__init__.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..00ab19af4748147d748fccb51a3710d5c711f4b4 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/__init__.py @@ -0,0 +1,210 @@ +r""" +Compressed sparse graph routines (:mod:`scipy.sparse.csgraph`) +============================================================== + +.. currentmodule:: scipy.sparse.csgraph + +Fast graph algorithms based on sparse matrix representations. + +Contents +-------- + +.. autosummary:: + :toctree: generated/ + + connected_components -- determine connected components of a graph + laplacian -- compute the laplacian of a graph + shortest_path -- compute the shortest path between points on a positive graph + dijkstra -- use Dijkstra's algorithm for shortest path + floyd_warshall -- use the Floyd-Warshall algorithm for shortest path + bellman_ford -- use the Bellman-Ford algorithm for shortest path + johnson -- use Johnson's algorithm for shortest path + yen -- use Yen's algorithm for K-shortest paths between to nodes. + breadth_first_order -- compute a breadth-first order of nodes + depth_first_order -- compute a depth-first order of nodes + breadth_first_tree -- construct the breadth-first tree from a given node + depth_first_tree -- construct a depth-first tree from a given node + minimum_spanning_tree -- construct the minimum spanning tree of a graph + reverse_cuthill_mckee -- compute permutation for reverse Cuthill-McKee ordering + maximum_flow -- solve the maximum flow problem for a graph + maximum_bipartite_matching -- compute a maximum matching of a bipartite graph + min_weight_full_bipartite_matching - compute a minimum weight full matching of a bipartite graph + structural_rank -- compute the structural rank of a graph + NegativeCycleError + +.. autosummary:: + :toctree: generated/ + + construct_dist_matrix + csgraph_from_dense + csgraph_from_masked + csgraph_masked_from_dense + csgraph_to_dense + csgraph_to_masked + reconstruct_path + +Graph Representations +--------------------- +This module uses graphs which are stored in a matrix format. A +graph with N nodes can be represented by an (N x N) adjacency matrix G. +If there is a connection from node i to node j, then G[i, j] = w, where +w is the weight of the connection. For nodes i and j which are +not connected, the value depends on the representation: + +- for dense array representations, non-edges are represented by + G[i, j] = 0, infinity, or NaN. + +- for dense masked representations (of type np.ma.MaskedArray), non-edges + are represented by masked values. This can be useful when graphs with + zero-weight edges are desired. + +- for sparse array representations, non-edges are represented by + non-entries in the matrix. This sort of sparse representation also + allows for edges with zero weights. + +As a concrete example, imagine that you would like to represent the following +undirected graph:: + + G + + (0) + / \ + 1 2 + / \ + (2) (1) + +This graph has three nodes, where node 0 and 1 are connected by an edge of +weight 2, and nodes 0 and 2 are connected by an edge of weight 1. +We can construct the dense, masked, and sparse representations as follows, +keeping in mind that an undirected graph is represented by a symmetric matrix:: + + >>> import numpy as np + >>> G_dense = np.array([[0, 2, 1], + ... [2, 0, 0], + ... [1, 0, 0]]) + >>> G_masked = np.ma.masked_values(G_dense, 0) + >>> from scipy.sparse import csr_array + >>> G_sparse = csr_array(G_dense) + +This becomes more difficult when zero edges are significant. For example, +consider the situation when we slightly modify the above graph:: + + G2 + + (0) + / \ + 0 2 + / \ + (2) (1) + +This is identical to the previous graph, except nodes 0 and 2 are connected +by an edge of zero weight. In this case, the dense representation above +leads to ambiguities: how can non-edges be represented if zero is a meaningful +value? In this case, either a masked or sparse representation must be used +to eliminate the ambiguity:: + + >>> import numpy as np + >>> G2_data = np.array([[np.inf, 2, 0 ], + ... [2, np.inf, np.inf], + ... [0, np.inf, np.inf]]) + >>> G2_masked = np.ma.masked_invalid(G2_data) + >>> from scipy.sparse.csgraph import csgraph_from_dense + >>> # G2_sparse = csr_array(G2_data) would give the wrong result + >>> G2_sparse = csgraph_from_dense(G2_data, null_value=np.inf) + >>> G2_sparse.data + array([ 2., 0., 2., 0.]) + +Here we have used a utility routine from the csgraph submodule in order to +convert the dense representation to a sparse representation which can be +understood by the algorithms in submodule. By viewing the data array, we +can see that the zero values are explicitly encoded in the graph. + +Directed vs. undirected +^^^^^^^^^^^^^^^^^^^^^^^ +Matrices may represent either directed or undirected graphs. This is +specified throughout the csgraph module by a boolean keyword. Graphs are +assumed to be directed by default. In a directed graph, traversal from node +i to node j can be accomplished over the edge G[i, j], but not the edge +G[j, i]. Consider the following dense graph:: + + >>> import numpy as np + >>> G_dense = np.array([[0, 1, 0], + ... [2, 0, 3], + ... [0, 4, 0]]) + +When ``directed=True`` we get the graph:: + + ---1--> ---3--> + (0) (1) (2) + <--2--- <--4--- + +In a non-directed graph, traversal from node i to node j can be +accomplished over either G[i, j] or G[j, i]. If both edges are not null, +and the two have unequal weights, then the smaller of the two is used. + +So for the same graph, when ``directed=False`` we get the graph:: + + (0)--1--(1)--3--(2) + +Note that a symmetric matrix will represent an undirected graph, regardless +of whether the 'directed' keyword is set to True or False. In this case, +using ``directed=True`` generally leads to more efficient computation. + +The routines in this module accept as input either scipy.sparse representations +(csr, csc, or lil format), masked representations, or dense representations +with non-edges indicated by zeros, infinities, and NaN entries. +""" # noqa: E501 + +__docformat__ = "restructuredtext en" + +__all__ = ['connected_components', + 'laplacian', + 'shortest_path', + 'floyd_warshall', + 'dijkstra', + 'bellman_ford', + 'johnson', + 'yen', + 'breadth_first_order', + 'depth_first_order', + 'breadth_first_tree', + 'depth_first_tree', + 'minimum_spanning_tree', + 'reverse_cuthill_mckee', + 'maximum_flow', + 'maximum_bipartite_matching', + 'min_weight_full_bipartite_matching', + 'structural_rank', + 'construct_dist_matrix', + 'reconstruct_path', + 'csgraph_masked_from_dense', + 'csgraph_from_dense', + 'csgraph_from_masked', + 'csgraph_to_dense', + 'csgraph_to_masked', + 'NegativeCycleError'] + +from ._laplacian import laplacian +from ._shortest_path import ( + shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson, yen, + NegativeCycleError +) +from ._traversal import ( + breadth_first_order, depth_first_order, breadth_first_tree, + depth_first_tree, connected_components +) +from ._min_spanning_tree import minimum_spanning_tree +from ._flow import maximum_flow +from ._matching import ( + maximum_bipartite_matching, min_weight_full_bipartite_matching +) +from ._reordering import reverse_cuthill_mckee, structural_rank +from ._tools import ( + construct_dist_matrix, reconstruct_path, csgraph_from_dense, + csgraph_to_dense, csgraph_masked_from_dense, csgraph_from_masked, + csgraph_to_masked +) + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_laplacian.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_laplacian.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fdaa6137fbdba462c82345f88d0a2014cbc603e Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_laplacian.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_validation.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_validation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b743010b408ec49f8aead5b90c3e1f622374f02 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_validation.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py new file mode 100644 index 0000000000000000000000000000000000000000..e5529a0662a3f9db006bc5411664908f10d8fe23 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py @@ -0,0 +1,563 @@ +""" +Laplacian of a compressed-sparse graph +""" + +import numpy as np +from scipy.sparse import issparse +from scipy.sparse.linalg import LinearOperator +from scipy.sparse._sputils import convert_pydata_sparse_to_scipy, is_pydata_spmatrix + + +############################################################################### +# Graph laplacian +def laplacian( + csgraph, + normed=False, + return_diag=False, + use_out_degree=False, + *, + copy=True, + form="array", + dtype=None, + symmetrized=False, +): + """ + Return the Laplacian of a directed graph. + + Parameters + ---------- + csgraph : array_like or sparse array or matrix, 2 dimensions + compressed-sparse graph, with shape (N, N). + normed : bool, optional + If True, then compute symmetrically normalized Laplacian. + Default: False. + return_diag : bool, optional + If True, then also return an array related to vertex degrees. + Default: False. + use_out_degree : bool, optional + If True, then use out-degree instead of in-degree. + This distinction matters only if the graph is asymmetric. + Default: False. + copy: bool, optional + If False, then change `csgraph` in place if possible, + avoiding doubling the memory use. + Default: True, for backward compatibility. + form: 'array', or 'function', or 'lo' + Determines the format of the output Laplacian: + + * 'array' is a numpy array; + * 'function' is a pointer to evaluating the Laplacian-vector + or Laplacian-matrix product; + * 'lo' results in the format of the `LinearOperator`. + + Choosing 'function' or 'lo' always avoids doubling + the memory use, ignoring `copy` value. + Default: 'array', for backward compatibility. + dtype: None or one of numeric numpy dtypes, optional + The dtype of the output. If ``dtype=None``, the dtype of the + output matches the dtype of the input csgraph, except for + the case ``normed=True`` and integer-like csgraph, where + the output dtype is 'float' allowing accurate normalization, + but dramatically increasing the memory use. + Default: None, for backward compatibility. + symmetrized: bool, optional + If True, then the output Laplacian is symmetric/Hermitian. + The symmetrization is done by ``csgraph + csgraph.T.conj`` + without dividing by 2 to preserve integer dtypes if possible + prior to the construction of the Laplacian. + The symmetrization will increase the memory footprint of + sparse matrices unless the sparsity pattern is symmetric or + `form` is 'function' or 'lo'. + Default: False, for backward compatibility. + + Returns + ------- + lap : ndarray, or sparse array or matrix, or `LinearOperator` + The N x N Laplacian of csgraph. It will be a NumPy array (dense) + if the input was dense, or a sparse array otherwise, or + the format of a function or `LinearOperator` if + `form` equals 'function' or 'lo', respectively. + diag : ndarray, optional + The length-N main diagonal of the Laplacian matrix. + For the normalized Laplacian, this is the array of square roots + of vertex degrees or 1 if the degree is zero. + + Notes + ----- + The Laplacian matrix of a graph is sometimes referred to as the + "Kirchhoff matrix" or just the "Laplacian", and is useful in many + parts of spectral graph theory. + In particular, the eigen-decomposition of the Laplacian can give + insight into many properties of the graph, e.g., + is commonly used for spectral data embedding and clustering. + + The constructed Laplacian doubles the memory use if ``copy=True`` and + ``form="array"`` which is the default. + Choosing ``copy=False`` has no effect unless ``form="array"`` + or the matrix is sparse in the ``coo`` format, or dense array, except + for the integer input with ``normed=True`` that forces the float output. + + Sparse input is reformatted into ``coo`` if ``form="array"``, + which is the default. + + If the input adjacency matrix is not symmetric, the Laplacian is + also non-symmetric unless ``symmetrized=True`` is used. + + Diagonal entries of the input adjacency matrix are ignored and + replaced with zeros for the purpose of normalization where ``normed=True``. + The normalization uses the inverse square roots of row-sums of the input + adjacency matrix, and thus may fail if the row-sums contain + negative or complex with a non-zero imaginary part values. + + The normalization is symmetric, making the normalized Laplacian also + symmetric if the input csgraph was symmetric. + + References + ---------- + .. [1] Laplacian matrix. https://en.wikipedia.org/wiki/Laplacian_matrix + + Examples + -------- + >>> import numpy as np + >>> from scipy.sparse import csgraph + + Our first illustration is the symmetric graph + + >>> G = np.arange(4) * np.arange(4)[:, np.newaxis] + >>> G + array([[0, 0, 0, 0], + [0, 1, 2, 3], + [0, 2, 4, 6], + [0, 3, 6, 9]]) + + and its symmetric Laplacian matrix + + >>> csgraph.laplacian(G) + array([[ 0, 0, 0, 0], + [ 0, 5, -2, -3], + [ 0, -2, 8, -6], + [ 0, -3, -6, 9]]) + + The non-symmetric graph + + >>> G = np.arange(9).reshape(3, 3) + >>> G + array([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + + has different row- and column sums, resulting in two varieties + of the Laplacian matrix, using an in-degree, which is the default + + >>> L_in_degree = csgraph.laplacian(G) + >>> L_in_degree + array([[ 9, -1, -2], + [-3, 8, -5], + [-6, -7, 7]]) + + or alternatively an out-degree + + >>> L_out_degree = csgraph.laplacian(G, use_out_degree=True) + >>> L_out_degree + array([[ 3, -1, -2], + [-3, 8, -5], + [-6, -7, 13]]) + + Constructing a symmetric Laplacian matrix, one can add the two as + + >>> L_in_degree + L_out_degree.T + array([[ 12, -4, -8], + [ -4, 16, -12], + [ -8, -12, 20]]) + + or use the ``symmetrized=True`` option + + >>> csgraph.laplacian(G, symmetrized=True) + array([[ 12, -4, -8], + [ -4, 16, -12], + [ -8, -12, 20]]) + + that is equivalent to symmetrizing the original graph + + >>> csgraph.laplacian(G + G.T) + array([[ 12, -4, -8], + [ -4, 16, -12], + [ -8, -12, 20]]) + + The goal of normalization is to make the non-zero diagonal entries + of the Laplacian matrix to be all unit, also scaling off-diagonal + entries correspondingly. The normalization can be done manually, e.g., + + >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) + >>> L, d = csgraph.laplacian(G, return_diag=True) + >>> L + array([[ 2, -1, -1], + [-1, 2, -1], + [-1, -1, 2]]) + >>> d + array([2, 2, 2]) + >>> scaling = np.sqrt(d) + >>> scaling + array([1.41421356, 1.41421356, 1.41421356]) + >>> (1/scaling)*L*(1/scaling) + array([[ 1. , -0.5, -0.5], + [-0.5, 1. , -0.5], + [-0.5, -0.5, 1. ]]) + + Or using ``normed=True`` option + + >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True) + >>> L + array([[ 1. , -0.5, -0.5], + [-0.5, 1. , -0.5], + [-0.5, -0.5, 1. ]]) + + which now instead of the diagonal returns the scaling coefficients + + >>> d + array([1.41421356, 1.41421356, 1.41421356]) + + Zero scaling coefficients are substituted with 1s, where scaling + has thus no effect, e.g., + + >>> G = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0]]) + >>> G + array([[0, 0, 0], + [0, 0, 1], + [0, 1, 0]]) + >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True) + >>> L + array([[ 0., -0., -0.], + [-0., 1., -1.], + [-0., -1., 1.]]) + >>> d + array([1., 1., 1.]) + + Only the symmetric normalization is implemented, resulting + in a symmetric Laplacian matrix if and only if its graph is symmetric + and has all non-negative degrees, like in the examples above. + + The output Laplacian matrix is by default a dense array or a sparse + array or matrix inferring its class, shape, format, and dtype from + the input graph matrix: + + >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]).astype(np.float32) + >>> G + array([[0., 1., 1.], + [1., 0., 1.], + [1., 1., 0.]], dtype=float32) + >>> csgraph.laplacian(G) + array([[ 2., -1., -1.], + [-1., 2., -1.], + [-1., -1., 2.]], dtype=float32) + + but can alternatively be generated matrix-free as a LinearOperator: + + >>> L = csgraph.laplacian(G, form="lo") + >>> L + <3x3 _CustomLinearOperator with dtype=float32> + >>> L(np.eye(3)) + array([[ 2., -1., -1.], + [-1., 2., -1.], + [-1., -1., 2.]]) + + or as a lambda-function: + + >>> L = csgraph.laplacian(G, form="function") + >>> L + . at 0x0000012AE6F5A598> + >>> L(np.eye(3)) + array([[ 2., -1., -1.], + [-1., 2., -1.], + [-1., -1., 2.]]) + + The Laplacian matrix is used for + spectral data clustering and embedding + as well as for spectral graph partitioning. + Our final example illustrates the latter + for a noisy directed linear graph. + + >>> from scipy.sparse import diags_array, random_array + >>> from scipy.sparse.linalg import lobpcg + + Create a directed linear graph with ``N=35`` vertices + using a sparse adjacency matrix ``G``: + + >>> N = 35 + >>> G = diags_array(np.ones(N - 1), offsets=1, format="csr") + + Fix a random seed ``rng`` and add a random sparse noise to the graph ``G``: + + >>> rng = np.random.default_rng() + >>> G += 1e-2 * random_array((N, N), density=0.1, rng=rng) + + Set initial approximations for eigenvectors: + + >>> X = rng.random((N, 2)) + + The constant vector of ones is always a trivial eigenvector + of the non-normalized Laplacian to be filtered out: + + >>> Y = np.ones((N, 1)) + + Alternating (1) the sign of the graph weights allows determining + labels for spectral max- and min- cuts in a single loop. + Since the graph is undirected, the option ``symmetrized=True`` + must be used in the construction of the Laplacian. + The option ``normed=True`` cannot be used in (2) for the negative weights + here as the symmetric normalization evaluates square roots. + The option ``form="lo"`` in (2) is matrix-free, i.e., guarantees + a fixed memory footprint and read-only access to the graph. + Calling the eigenvalue solver ``lobpcg`` (3) computes the Fiedler vector + that determines the labels as the signs of its components in (5). + Since the sign in an eigenvector is not deterministic and can flip, + we fix the sign of the first component to be always +1 in (4). + + >>> for cut in ["max", "min"]: + ... G = -G # 1. + ... L = csgraph.laplacian(G, symmetrized=True, form="lo") # 2. + ... _, eves = lobpcg(L, X, Y=Y, largest=False, tol=1e-2) # 3. + ... eves *= np.sign(eves[0, 0]) # 4. + ... print(cut + "-cut labels:\\n", 1 * (eves[:, 0]>0)) # 5. + max-cut labels: + [1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1] + min-cut labels: + [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] + + As anticipated for a (slightly noisy) linear graph, + the max-cut strips all the edges of the graph coloring all + odd vertices into one color and all even vertices into another one, + while the balanced min-cut partitions the graph + in the middle by deleting a single edge. + Both determined partitions are optimal. + """ + is_pydata_sparse = is_pydata_spmatrix(csgraph) + if is_pydata_sparse: + pydata_sparse_cls = csgraph.__class__ + csgraph = convert_pydata_sparse_to_scipy(csgraph) + if csgraph.ndim != 2 or csgraph.shape[0] != csgraph.shape[1]: + raise ValueError('csgraph must be a square matrix or array') + + if normed and ( + np.issubdtype(csgraph.dtype, np.signedinteger) + or np.issubdtype(csgraph.dtype, np.uint) + ): + csgraph = csgraph.astype(np.float64) + + if form == "array": + create_lap = ( + _laplacian_sparse if issparse(csgraph) else _laplacian_dense + ) + else: + create_lap = ( + _laplacian_sparse_flo + if issparse(csgraph) + else _laplacian_dense_flo + ) + + degree_axis = 1 if use_out_degree else 0 + + lap, d = create_lap( + csgraph, + normed=normed, + axis=degree_axis, + copy=copy, + form=form, + dtype=dtype, + symmetrized=symmetrized, + ) + if is_pydata_sparse: + lap = pydata_sparse_cls.from_scipy_sparse(lap) + if return_diag: + return lap, d + return lap + + +def _setdiag_dense(m, d): + step = len(d) + 1 + m.flat[::step] = d + + +def _laplace(m, d): + return lambda v: v * d[:, np.newaxis] - m @ v + + +def _laplace_normed(m, d, nd): + laplace = _laplace(m, d) + return lambda v: nd[:, np.newaxis] * laplace(v * nd[:, np.newaxis]) + + +def _laplace_sym(m, d): + return ( + lambda v: v * d[:, np.newaxis] + - m @ v + - np.transpose(np.conjugate(np.transpose(np.conjugate(v)) @ m)) + ) + + +def _laplace_normed_sym(m, d, nd): + laplace_sym = _laplace_sym(m, d) + return lambda v: nd[:, np.newaxis] * laplace_sym(v * nd[:, np.newaxis]) + + +def _linearoperator(mv, shape, dtype): + return LinearOperator(matvec=mv, matmat=mv, shape=shape, dtype=dtype) + + +def _laplacian_sparse_flo(graph, normed, axis, copy, form, dtype, symmetrized): + # The keyword argument `copy` is unused and has no effect here. + del copy + + if dtype is None: + dtype = graph.dtype + + graph_sum = np.asarray(graph.sum(axis=axis)).ravel() + graph_diagonal = graph.diagonal() + diag = graph_sum - graph_diagonal + if symmetrized: + graph_sum += np.asarray(graph.sum(axis=1 - axis)).ravel() + diag = graph_sum - graph_diagonal - graph_diagonal + + if normed: + isolated_node_mask = diag == 0 + w = np.where(isolated_node_mask, 1, np.sqrt(diag)) + if symmetrized: + md = _laplace_normed_sym(graph, graph_sum, 1.0 / w) + else: + md = _laplace_normed(graph, graph_sum, 1.0 / w) + if form == "function": + return md, w.astype(dtype, copy=False) + elif form == "lo": + m = _linearoperator(md, shape=graph.shape, dtype=dtype) + return m, w.astype(dtype, copy=False) + else: + raise ValueError(f"Invalid form: {form!r}") + else: + if symmetrized: + md = _laplace_sym(graph, graph_sum) + else: + md = _laplace(graph, graph_sum) + if form == "function": + return md, diag.astype(dtype, copy=False) + elif form == "lo": + m = _linearoperator(md, shape=graph.shape, dtype=dtype) + return m, diag.astype(dtype, copy=False) + else: + raise ValueError(f"Invalid form: {form!r}") + + +def _laplacian_sparse(graph, normed, axis, copy, form, dtype, symmetrized): + # The keyword argument `form` is unused and has no effect here. + del form + + if dtype is None: + dtype = graph.dtype + + needs_copy = False + if graph.format in ('lil', 'dok'): + m = graph.tocoo() + else: + m = graph + if copy: + needs_copy = True + + if symmetrized: + m += m.T.conj() + + w = np.asarray(m.sum(axis=axis)).ravel() - m.diagonal() + if normed: + m = m.tocoo(copy=needs_copy) + isolated_node_mask = (w == 0) + w = np.where(isolated_node_mask, 1, np.sqrt(w)) + m.data /= w[m.row] + m.data /= w[m.col] + m.data *= -1 + m.setdiag(1 - isolated_node_mask) + else: + if m.format == 'dia': + m = m.copy() + else: + m = m.tocoo(copy=needs_copy) + m.data *= -1 + m.setdiag(w) + + return m.astype(dtype, copy=False), w.astype(dtype) + + +def _laplacian_dense_flo(graph, normed, axis, copy, form, dtype, symmetrized): + + if copy: + m = np.array(graph) + else: + m = np.asarray(graph) + + if dtype is None: + dtype = m.dtype + + graph_sum = m.sum(axis=axis) + graph_diagonal = m.diagonal() + diag = graph_sum - graph_diagonal + if symmetrized: + graph_sum += m.sum(axis=1 - axis) + diag = graph_sum - graph_diagonal - graph_diagonal + + if normed: + isolated_node_mask = diag == 0 + w = np.where(isolated_node_mask, 1, np.sqrt(diag)) + if symmetrized: + md = _laplace_normed_sym(m, graph_sum, 1.0 / w) + else: + md = _laplace_normed(m, graph_sum, 1.0 / w) + if form == "function": + return md, w.astype(dtype, copy=False) + elif form == "lo": + m = _linearoperator(md, shape=graph.shape, dtype=dtype) + return m, w.astype(dtype, copy=False) + else: + raise ValueError(f"Invalid form: {form!r}") + else: + if symmetrized: + md = _laplace_sym(m, graph_sum) + else: + md = _laplace(m, graph_sum) + if form == "function": + return md, diag.astype(dtype, copy=False) + elif form == "lo": + m = _linearoperator(md, shape=graph.shape, dtype=dtype) + return m, diag.astype(dtype, copy=False) + else: + raise ValueError(f"Invalid form: {form!r}") + + +def _laplacian_dense(graph, normed, axis, copy, form, dtype, symmetrized): + + if form != "array": + raise ValueError(f'{form!r} must be "array"') + + if dtype is None: + dtype = graph.dtype + + if copy: + m = np.array(graph) + else: + m = np.asarray(graph) + + if dtype is None: + dtype = m.dtype + + if symmetrized: + m += m.T.conj() + np.fill_diagonal(m, 0) + w = m.sum(axis=axis) + if normed: + isolated_node_mask = (w == 0) + w = np.where(isolated_node_mask, 1, np.sqrt(w)) + m /= w + m /= w[:, np.newaxis] + m *= -1 + _setdiag_dense(m, 1 - isolated_node_mask) + else: + m *= -1 + _setdiag_dense(m, w) + + return m.astype(dtype, copy=False), w.astype(dtype, copy=False) diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/_validation.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..6eb9ce811b73e751ebb1cd6b226b73f7bcfe7ceb --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/_validation.py @@ -0,0 +1,66 @@ +import numpy as np +from scipy.sparse import issparse +from scipy.sparse._sputils import convert_pydata_sparse_to_scipy +from scipy.sparse.csgraph._tools import ( + csgraph_to_dense, csgraph_from_dense, + csgraph_masked_from_dense, csgraph_from_masked +) + +DTYPE = np.float64 + + +def validate_graph(csgraph, directed, dtype=DTYPE, + csr_output=True, dense_output=True, + copy_if_dense=False, copy_if_sparse=False, + null_value_in=0, null_value_out=np.inf, + infinity_null=True, nan_null=True): + """Routine for validation and conversion of csgraph inputs""" + if not (csr_output or dense_output): + raise ValueError("Internal: dense or csr output must be true") + + accept_fv = [null_value_in] + if infinity_null: + accept_fv.append(np.inf) + if nan_null: + accept_fv.append(np.nan) + csgraph = convert_pydata_sparse_to_scipy(csgraph, accept_fv=accept_fv) + + # if undirected and csc storage, then transposing in-place + # is quicker than later converting to csr. + if (not directed) and issparse(csgraph) and csgraph.format == "csc": + csgraph = csgraph.T + + if issparse(csgraph): + if csr_output: + csgraph = csgraph.tocsr(copy=copy_if_sparse).astype(DTYPE, copy=False) + else: + csgraph = csgraph_to_dense(csgraph, null_value=null_value_out) + elif np.ma.isMaskedArray(csgraph): + if dense_output: + mask = csgraph.mask + csgraph = np.array(csgraph.data, dtype=DTYPE, copy=copy_if_dense) + csgraph[mask] = null_value_out + else: + csgraph = csgraph_from_masked(csgraph) + else: + if dense_output: + csgraph = csgraph_masked_from_dense(csgraph, + copy=copy_if_dense, + null_value=null_value_in, + nan_null=nan_null, + infinity_null=infinity_null) + mask = csgraph.mask + csgraph = np.asarray(csgraph.data, dtype=DTYPE) + csgraph[mask] = null_value_out + else: + csgraph = csgraph_from_dense(csgraph, null_value=null_value_in, + infinity_null=infinity_null, + nan_null=nan_null) + + if csgraph.ndim != 2: + raise ValueError("compressed-sparse graph must be 2-D") + + if csgraph.shape[0] != csgraph.shape[1]: + raise ValueError("compressed-sparse graph must be shape (N, N)") + + return csgraph diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__init__.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/__init__.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..182b9ec8d5a98bbd537ccfb23f6fa7c67e9e4ccb Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_connected_components.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_connected_components.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bb98ee25aebacc3e3d99124b5e1110bae0c6513 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_connected_components.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_conversions.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_conversions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23156f4e77de25ff5a78cef40ce297b7cf587b62 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_conversions.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_flow.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_flow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..824549b4869e334ec3a0e0468a98fffb20c23c65 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_flow.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_graph_laplacian.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_graph_laplacian.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de17f3b16cfe7422b55622ca8b7eb05ebe7c4a38 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_graph_laplacian.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_matching.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_matching.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88a29e497ea3bc32c3992d2b7946cc07f898533a Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_matching.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_pydata_sparse.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_pydata_sparse.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19af07071b3d1d5016cab4108602b75251dce4e1 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_pydata_sparse.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_reordering.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_reordering.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c9c4e1d21f833b25621c7b4399af0f84b5c5418 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_reordering.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_shortest_path.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_shortest_path.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b9d5c972b4811a5cf575748d3862b88ae799a79 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_shortest_path.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_spanning_tree.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_spanning_tree.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..468365d69ad85ac0b8487d7150e4e1ec9907055b Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_spanning_tree.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_traversal.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_traversal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aced61292a3683fc9d518e0be0704aa32e5d13cc Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__pycache__/test_traversal.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py new file mode 100644 index 0000000000000000000000000000000000000000..0b190a24deb9f2818893a120f8ea376fbfb8d6fe --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py @@ -0,0 +1,119 @@ +import numpy as np +from numpy.testing import assert_equal, assert_array_almost_equal +from scipy.sparse import csgraph, csr_array + + +def test_weak_connections(): + Xde = np.array([[0, 1, 0], + [0, 0, 0], + [0, 0, 0]]) + + Xsp = csgraph.csgraph_from_dense(Xde, null_value=0) + + for X in Xsp, Xde: + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='weak') + + assert_equal(n_components, 2) + assert_array_almost_equal(labels, [0, 0, 1]) + + +def test_strong_connections(): + X1de = np.array([[0, 1, 0], + [0, 0, 0], + [0, 0, 0]]) + X2de = X1de + X1de.T + + X1sp = csgraph.csgraph_from_dense(X1de, null_value=0) + X2sp = csgraph.csgraph_from_dense(X2de, null_value=0) + + for X in X1sp, X1de: + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='strong') + + assert_equal(n_components, 3) + labels.sort() + assert_array_almost_equal(labels, [0, 1, 2]) + + for X in X2sp, X2de: + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='strong') + + assert_equal(n_components, 2) + labels.sort() + assert_array_almost_equal(labels, [0, 0, 1]) + + +def test_strong_connections2(): + X = np.array([[0, 0, 0, 0, 0, 0], + [1, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0]]) + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='strong') + assert_equal(n_components, 5) + labels.sort() + assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) + + +def test_weak_connections2(): + X = np.array([[0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0]]) + n_components, labels =\ + csgraph.connected_components(X, directed=True, + connection='weak') + assert_equal(n_components, 2) + labels.sort() + assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1]) + + +def test_ticket1876(): + # Regression test: this failed in the original implementation + # There should be two strongly-connected components; previously gave one + g = np.array([[0, 1, 1, 0], + [1, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 1, 0]]) + n_components, labels = csgraph.connected_components(g, connection='strong') + + assert_equal(n_components, 2) + assert_equal(labels[0], labels[1]) + assert_equal(labels[2], labels[3]) + + +def test_fully_connected_graph(): + # Fully connected dense matrices raised an exception. + # https://github.com/scipy/scipy/issues/3818 + g = np.ones((4, 4)) + n_components, labels = csgraph.connected_components(g) + assert_equal(n_components, 1) + + +def test_int64_indices_undirected(): + # See https://github.com/scipy/scipy/issues/18716 + g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2)) + assert g.indices.dtype == np.int64 + n, labels = csgraph.connected_components(g, directed=False) + assert n == 1 + assert_array_almost_equal(labels, [0, 0]) + + +def test_int64_indices_directed(): + # See https://github.com/scipy/scipy/issues/18716 + g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2)) + assert g.indices.dtype == np.int64 + n, labels = csgraph.connected_components(g, directed=True, + connection='strong') + assert n == 2 + assert_array_almost_equal(labels, [1, 0]) + diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py new file mode 100644 index 0000000000000000000000000000000000000000..65f141e5b371367018a6e9985f8325850d8972da --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py @@ -0,0 +1,61 @@ +import numpy as np +from numpy.testing import assert_array_almost_equal +from scipy.sparse import csr_array +from scipy.sparse.csgraph import csgraph_from_dense, csgraph_to_dense + + +def test_csgraph_from_dense(): + np.random.seed(1234) + G = np.random.random((10, 10)) + some_nulls = (G < 0.4) + all_nulls = (G < 0.8) + + for null_value in [0, np.nan, np.inf]: + G[all_nulls] = null_value + with np.errstate(invalid="ignore"): + G_csr = csgraph_from_dense(G, null_value=0) + + G[all_nulls] = 0 + assert_array_almost_equal(G, G_csr.toarray()) + + for null_value in [np.nan, np.inf]: + G[all_nulls] = 0 + G[some_nulls] = null_value + with np.errstate(invalid="ignore"): + G_csr = csgraph_from_dense(G, null_value=0) + + G[all_nulls] = 0 + assert_array_almost_equal(G, G_csr.toarray()) + + +def test_csgraph_to_dense(): + np.random.seed(1234) + G = np.random.random((10, 10)) + nulls = (G < 0.8) + G[nulls] = np.inf + + G_csr = csgraph_from_dense(G) + + for null_value in [0, 10, -np.inf, np.inf]: + G[nulls] = null_value + assert_array_almost_equal(G, csgraph_to_dense(G_csr, null_value)) + + +def test_multiple_edges(): + # create a random square matrix with an even number of elements + np.random.seed(1234) + X = np.random.random((10, 10)) + Xcsr = csr_array(X) + + # now double-up every other column + Xcsr.indices[::2] = Xcsr.indices[1::2] + + # normal sparse toarray() will sum the duplicated edges + Xdense = Xcsr.toarray() + assert_array_almost_equal(Xdense[:, 1::2], + X[:, ::2] + X[:, 1::2]) + + # csgraph_to_dense chooses the minimum of each duplicated edge + Xdense = csgraph_to_dense(Xcsr) + assert_array_almost_equal(Xdense[:, 1::2], + np.minimum(X[:, ::2], X[:, 1::2])) diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..c92eb985a1145c4b7c1777f0449bb423402f6d66 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py @@ -0,0 +1,209 @@ +import numpy as np +from numpy.testing import assert_array_equal +import pytest + +from scipy.sparse import csr_array, csc_array, csr_matrix +from scipy.sparse.csgraph import maximum_flow +from scipy.sparse.csgraph._flow import ( + _add_reverse_edges, _make_edge_pointers, _make_tails +) + +methods = ['edmonds_karp', 'dinic'] + +def test_raises_on_dense_input(): + with pytest.raises(TypeError): + graph = np.array([[0, 1], [0, 0]]) + maximum_flow(graph, 0, 1) + maximum_flow(graph, 0, 1, method='edmonds_karp') + + +def test_raises_on_csc_input(): + with pytest.raises(TypeError): + graph = csc_array([[0, 1], [0, 0]]) + maximum_flow(graph, 0, 1) + maximum_flow(graph, 0, 1, method='edmonds_karp') + + +def test_raises_on_floating_point_input(): + with pytest.raises(ValueError): + graph = csr_array([[0, 1.5], [0, 0]], dtype=np.float64) + maximum_flow(graph, 0, 1) + maximum_flow(graph, 0, 1, method='edmonds_karp') + + +def test_raises_on_non_square_input(): + with pytest.raises(ValueError): + graph = csr_array([[0, 1, 2], [2, 1, 0]]) + maximum_flow(graph, 0, 1) + + +def test_raises_when_source_is_sink(): + with pytest.raises(ValueError): + graph = csr_array([[0, 1], [0, 0]]) + maximum_flow(graph, 0, 0) + maximum_flow(graph, 0, 0, method='edmonds_karp') + + +@pytest.mark.parametrize('method', methods) +@pytest.mark.parametrize('source', [-1, 2, 3]) +def test_raises_when_source_is_out_of_bounds(source, method): + with pytest.raises(ValueError): + graph = csr_array([[0, 1], [0, 0]]) + maximum_flow(graph, source, 1, method=method) + + +@pytest.mark.parametrize('method', methods) +@pytest.mark.parametrize('sink', [-1, 2, 3]) +def test_raises_when_sink_is_out_of_bounds(sink, method): + with pytest.raises(ValueError): + graph = csr_array([[0, 1], [0, 0]]) + maximum_flow(graph, 0, sink, method=method) + + +@pytest.mark.parametrize('method', methods) +def test_simple_graph(method): + # This graph looks as follows: + # (0) --5--> (1) + graph = csr_array([[0, 5], [0, 0]]) + res = maximum_flow(graph, 0, 1, method=method) + assert res.flow_value == 5 + expected_flow = np.array([[0, 5], [-5, 0]]) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_return_type(method): + graph = csr_array([[0, 5], [0, 0]]) + assert isinstance(maximum_flow(graph, 0, 1, method=method).flow, csr_array) + graph = csr_matrix([[0, 5], [0, 0]]) + assert isinstance(maximum_flow(graph, 0, 1, method=method).flow, csr_matrix) + + +@pytest.mark.parametrize('method', methods) +def test_bottle_neck_graph(method): + # This graph cannot use the full capacity between 0 and 1: + # (0) --5--> (1) --3--> (2) + graph = csr_array([[0, 5, 0], [0, 0, 3], [0, 0, 0]]) + res = maximum_flow(graph, 0, 2, method=method) + assert res.flow_value == 3 + expected_flow = np.array([[0, 3, 0], [-3, 0, 3], [0, -3, 0]]) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_backwards_flow(method): + # This example causes backwards flow between vertices 3 and 4, + # and so this test ensures that we handle that accordingly. See + # https://stackoverflow.com/q/38843963/5085211 + # for more information. + graph = csr_array([[0, 10, 0, 0, 10, 0, 0, 0], + [0, 0, 10, 0, 0, 0, 0, 0], + [0, 0, 0, 10, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 10], + [0, 0, 0, 10, 0, 10, 0, 0], + [0, 0, 0, 0, 0, 0, 10, 0], + [0, 0, 0, 0, 0, 0, 0, 10], + [0, 0, 0, 0, 0, 0, 0, 0]]) + res = maximum_flow(graph, 0, 7, method=method) + assert res.flow_value == 20 + expected_flow = np.array([[0, 10, 0, 0, 10, 0, 0, 0], + [-10, 0, 10, 0, 0, 0, 0, 0], + [0, -10, 0, 10, 0, 0, 0, 0], + [0, 0, -10, 0, 0, 0, 0, 10], + [-10, 0, 0, 0, 0, 10, 0, 0], + [0, 0, 0, 0, -10, 0, 10, 0], + [0, 0, 0, 0, 0, -10, 0, 10], + [0, 0, 0, -10, 0, 0, -10, 0]]) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_example_from_clrs_chapter_26_1(method): + # See page 659 in CLRS second edition, but note that the maximum flow + # we find is slightly different than the one in CLRS; we push a flow of + # 12 to v_1 instead of v_2. + graph = csr_array([[0, 16, 13, 0, 0, 0], + [0, 0, 10, 12, 0, 0], + [0, 4, 0, 0, 14, 0], + [0, 0, 9, 0, 0, 20], + [0, 0, 0, 7, 0, 4], + [0, 0, 0, 0, 0, 0]]) + res = maximum_flow(graph, 0, 5, method=method) + assert res.flow_value == 23 + expected_flow = np.array([[0, 12, 11, 0, 0, 0], + [-12, 0, 0, 12, 0, 0], + [-11, 0, 0, 0, 11, 0], + [0, -12, 0, 0, -7, 19], + [0, 0, -11, 7, 0, 4], + [0, 0, 0, -19, -4, 0]]) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_disconnected_graph(method): + # This tests the following disconnected graph: + # (0) --5--> (1) (2) --3--> (3) + graph = csr_array([[0, 5, 0, 0], + [0, 0, 0, 0], + [0, 0, 9, 3], + [0, 0, 0, 0]]) + res = maximum_flow(graph, 0, 3, method=method) + assert res.flow_value == 0 + expected_flow = np.zeros((4, 4), dtype=np.int32) + assert_array_equal(res.flow.toarray(), expected_flow) + + +@pytest.mark.parametrize('method', methods) +def test_add_reverse_edges_large_graph(method): + # Regression test for https://github.com/scipy/scipy/issues/14385 + n = 100_000 + indices = np.arange(1, n) + indptr = np.array(list(range(n)) + [n - 1]) + data = np.ones(n - 1, dtype=np.int32) + graph = csr_array((data, indices, indptr), shape=(n, n)) + res = maximum_flow(graph, 0, n - 1, method=method) + assert res.flow_value == 1 + expected_flow = graph - graph.transpose() + assert_array_equal(res.flow.data, expected_flow.data) + assert_array_equal(res.flow.indices, expected_flow.indices) + assert_array_equal(res.flow.indptr, expected_flow.indptr) + + +@pytest.mark.parametrize("a,b_data_expected", [ + ([[]], []), + ([[0], [0]], []), + ([[1, 0, 2], [0, 0, 0], [0, 3, 0]], [1, 2, 0, 0, 3]), + ([[9, 8, 7], [4, 5, 6], [0, 0, 0]], [9, 8, 7, 4, 5, 6, 0, 0])]) +def test_add_reverse_edges(a, b_data_expected): + """Test that the reversal of the edges of the input graph works + as expected. + """ + a = csr_array(a, dtype=np.int32, shape=(len(a), len(a))) + b = _add_reverse_edges(a) + assert_array_equal(b.data, b_data_expected) + + +@pytest.mark.parametrize("a,expected", [ + ([[]], []), + ([[0]], []), + ([[1]], [0]), + ([[0, 1], [10, 0]], [1, 0]), + ([[1, 0, 2], [0, 0, 3], [4, 5, 0]], [0, 3, 4, 1, 2]) +]) +def test_make_edge_pointers(a, expected): + a = csr_array(a, dtype=np.int32) + rev_edge_ptr = _make_edge_pointers(a) + assert_array_equal(rev_edge_ptr, expected) + + +@pytest.mark.parametrize("a,expected", [ + ([[]], []), + ([[0]], []), + ([[1]], [0]), + ([[0, 1], [10, 0]], [0, 1]), + ([[1, 0, 2], [0, 0, 3], [4, 5, 0]], [0, 0, 1, 2, 2]) +]) +def test_make_tails(a, expected): + a = csr_array(a, dtype=np.int32) + tails = _make_tails(a) + assert_array_equal(tails, expected) diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed5e2edf92ef0cacc819fcbd06bc6d4e195cb44 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py @@ -0,0 +1,368 @@ +import pytest +import numpy as np +from numpy.testing import assert_allclose +from pytest import raises as assert_raises +from scipy import sparse + +from scipy.sparse import csgraph +from scipy._lib._util import np_long, np_ulong + + +def check_int_type(mat): + return np.issubdtype(mat.dtype, np.signedinteger) or np.issubdtype( + mat.dtype, np_ulong + ) + + +def test_laplacian_value_error(): + for t in int, float, complex: + for m in ([1, 1], + [[[1]]], + [[1, 2, 3], [4, 5, 6]], + [[1, 2], [3, 4], [5, 5]]): + A = np.array(m, dtype=t) + assert_raises(ValueError, csgraph.laplacian, A) + + +def _explicit_laplacian(x, normed=False): + if sparse.issparse(x): + x = x.toarray() + x = np.asarray(x) + y = -1.0 * x + for j in range(y.shape[0]): + y[j,j] = x[j,j+1:].sum() + x[j,:j].sum() + if normed: + d = np.diag(y).copy() + d[d == 0] = 1.0 + y /= d[:,None]**.5 + y /= d[None,:]**.5 + return y + + +def _check_symmetric_graph_laplacian(mat, normed, copy=True): + if not hasattr(mat, 'shape'): + mat = eval(mat, dict(np=np, sparse=sparse)) + + if sparse.issparse(mat): + sp_mat = mat + mat = sp_mat.toarray() + else: + sp_mat = sparse.csr_array(mat) + + mat_copy = np.copy(mat) + sp_mat_copy = sparse.csr_array(sp_mat, copy=True) + + n_nodes = mat.shape[0] + explicit_laplacian = _explicit_laplacian(mat, normed=normed) + laplacian = csgraph.laplacian(mat, normed=normed, copy=copy) + sp_laplacian = csgraph.laplacian(sp_mat, normed=normed, + copy=copy) + + if copy: + assert_allclose(mat, mat_copy) + _assert_allclose_sparse(sp_mat, sp_mat_copy) + else: + if not (normed and check_int_type(mat)): + assert_allclose(laplacian, mat) + if sp_mat.format == 'coo': + _assert_allclose_sparse(sp_laplacian, sp_mat) + + assert_allclose(laplacian, sp_laplacian.toarray()) + + for tested in [laplacian, sp_laplacian.toarray()]: + if not normed: + assert_allclose(tested.sum(axis=0), np.zeros(n_nodes)) + assert_allclose(tested.T, tested) + assert_allclose(tested, explicit_laplacian) + + +def test_symmetric_graph_laplacian(): + symmetric_mats = ( + 'np.arange(10) * np.arange(10)[:, np.newaxis]', + 'np.ones((7, 7))', + 'np.eye(19)', + 'sparse.diags([1, 1], [-1, 1], shape=(4, 4))', + 'sparse.diags([1, 1], [-1, 1], shape=(4, 4)).toarray()', + 'sparse.diags([1, 1], [-1, 1], shape=(4, 4)).todense()', + 'np.vander(np.arange(4)) + np.vander(np.arange(4)).T' + ) + for mat in symmetric_mats: + for normed in True, False: + for copy in True, False: + _check_symmetric_graph_laplacian(mat, normed, copy) + + +def _assert_allclose_sparse(a, b, **kwargs): + # helper function that can deal with sparse matrices + if sparse.issparse(a): + a = a.toarray() + if sparse.issparse(b): + b = b.toarray() + assert_allclose(a, b, **kwargs) + + +def _check_laplacian_dtype_none( + A, desired_L, desired_d, normed, use_out_degree, copy, dtype, arr_type +): + mat = arr_type(A, dtype=dtype) + L, d = csgraph.laplacian( + mat, + normed=normed, + return_diag=True, + use_out_degree=use_out_degree, + copy=copy, + dtype=None, + ) + if normed and check_int_type(mat): + assert L.dtype == np.float64 + assert d.dtype == np.float64 + _assert_allclose_sparse(L, desired_L, atol=1e-12) + _assert_allclose_sparse(d, desired_d, atol=1e-12) + else: + assert L.dtype == dtype + assert d.dtype == dtype + desired_L = np.asarray(desired_L).astype(dtype) + desired_d = np.asarray(desired_d).astype(dtype) + _assert_allclose_sparse(L, desired_L, atol=1e-12) + _assert_allclose_sparse(d, desired_d, atol=1e-12) + + if not copy: + if not (normed and check_int_type(mat)): + if type(mat) is np.ndarray: + assert_allclose(L, mat) + elif mat.format == "coo": + _assert_allclose_sparse(L, mat) + + +def _check_laplacian_dtype( + A, desired_L, desired_d, normed, use_out_degree, copy, dtype, arr_type +): + mat = arr_type(A, dtype=dtype) + L, d = csgraph.laplacian( + mat, + normed=normed, + return_diag=True, + use_out_degree=use_out_degree, + copy=copy, + dtype=dtype, + ) + assert L.dtype == dtype + assert d.dtype == dtype + desired_L = np.asarray(desired_L).astype(dtype) + desired_d = np.asarray(desired_d).astype(dtype) + _assert_allclose_sparse(L, desired_L, atol=1e-12) + _assert_allclose_sparse(d, desired_d, atol=1e-12) + + if not copy: + if not (normed and check_int_type(mat)): + if type(mat) is np.ndarray: + assert_allclose(L, mat) + elif mat.format == 'coo': + _assert_allclose_sparse(L, mat) + + +INT_DTYPES = (np.intc, np_long, np.longlong) +REAL_DTYPES = (np.float32, np.float64, np.longdouble) +COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble) +DTYPES = INT_DTYPES + REAL_DTYPES + COMPLEX_DTYPES + + +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("arr_type", [np.array, + sparse.csr_matrix, + sparse.coo_matrix, + sparse.csr_array, + sparse.coo_array]) +@pytest.mark.parametrize("copy", [True, False]) +@pytest.mark.parametrize("normed", [True, False]) +@pytest.mark.parametrize("use_out_degree", [True, False]) +def test_asymmetric_laplacian(use_out_degree, normed, + copy, dtype, arr_type): + # adjacency matrix + A = [[0, 1, 0], + [4, 2, 0], + [0, 0, 0]] + A = arr_type(np.array(A), dtype=dtype) + A_copy = A.copy() + + if not normed and use_out_degree: + # Laplacian matrix using out-degree + L = [[1, -1, 0], + [-4, 4, 0], + [0, 0, 0]] + d = [1, 4, 0] + + if normed and use_out_degree: + # normalized Laplacian matrix using out-degree + L = [[1, -0.5, 0], + [-2, 1, 0], + [0, 0, 0]] + d = [1, 2, 1] + + if not normed and not use_out_degree: + # Laplacian matrix using in-degree + L = [[4, -1, 0], + [-4, 1, 0], + [0, 0, 0]] + d = [4, 1, 0] + + if normed and not use_out_degree: + # normalized Laplacian matrix using in-degree + L = [[1, -0.5, 0], + [-2, 1, 0], + [0, 0, 0]] + d = [2, 1, 1] + + _check_laplacian_dtype_none( + A, + L, + d, + normed=normed, + use_out_degree=use_out_degree, + copy=copy, + dtype=dtype, + arr_type=arr_type, + ) + + _check_laplacian_dtype( + A_copy, + L, + d, + normed=normed, + use_out_degree=use_out_degree, + copy=copy, + dtype=dtype, + arr_type=arr_type, + ) + + +@pytest.mark.parametrize("fmt", ['csr', 'csc', 'coo', 'lil', + 'dok', 'dia', 'bsr']) +@pytest.mark.parametrize("normed", [True, False]) +@pytest.mark.parametrize("copy", [True, False]) +def test_sparse_formats(fmt, normed, copy): + mat = sparse.diags_array([1, 1], offsets=[-1, 1], shape=(4, 4), format=fmt) + _check_symmetric_graph_laplacian(mat, normed, copy) + + +@pytest.mark.parametrize( + "arr_type", [np.asarray, + sparse.csr_matrix, + sparse.coo_matrix, + sparse.csr_array, + sparse.coo_array] +) +@pytest.mark.parametrize("form", ["array", "function", "lo"]) +def test_laplacian_symmetrized(arr_type, form): + # adjacency matrix + n = 3 + mat = arr_type(np.arange(n * n).reshape(n, n)) + L_in, d_in = csgraph.laplacian( + mat, + return_diag=True, + form=form, + ) + L_out, d_out = csgraph.laplacian( + mat, + return_diag=True, + use_out_degree=True, + form=form, + ) + Ls, ds = csgraph.laplacian( + mat, + return_diag=True, + symmetrized=True, + form=form, + ) + Ls_normed, ds_normed = csgraph.laplacian( + mat, + return_diag=True, + symmetrized=True, + normed=True, + form=form, + ) + mat += mat.T + Lss, dss = csgraph.laplacian(mat, return_diag=True, form=form) + Lss_normed, dss_normed = csgraph.laplacian( + mat, + return_diag=True, + normed=True, + form=form, + ) + + assert_allclose(ds, d_in + d_out) + assert_allclose(ds, dss) + assert_allclose(ds_normed, dss_normed) + + d = {} + for L in ["L_in", "L_out", "Ls", "Ls_normed", "Lss", "Lss_normed"]: + if form == "array": + d[L] = eval(L) + else: + d[L] = eval(L)(np.eye(n, dtype=mat.dtype)) + + _assert_allclose_sparse(d["Ls"], d["L_in"] + d["L_out"].T) + _assert_allclose_sparse(d["Ls"], d["Lss"]) + _assert_allclose_sparse(d["Ls_normed"], d["Lss_normed"]) + + +@pytest.mark.parametrize( + "arr_type", [np.asarray, + sparse.csr_matrix, + sparse.coo_matrix, + sparse.csr_array, + sparse.coo_array] +) +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("normed", [True, False]) +@pytest.mark.parametrize("symmetrized", [True, False]) +@pytest.mark.parametrize("use_out_degree", [True, False]) +@pytest.mark.parametrize("form", ["function", "lo"]) +def test_format(dtype, arr_type, normed, symmetrized, use_out_degree, form): + n = 3 + mat = [[0, 1, 0], [4, 2, 0], [0, 0, 0]] + mat = arr_type(np.array(mat), dtype=dtype) + Lo, do = csgraph.laplacian( + mat, + return_diag=True, + normed=normed, + symmetrized=symmetrized, + use_out_degree=use_out_degree, + dtype=dtype, + ) + La, da = csgraph.laplacian( + mat, + return_diag=True, + normed=normed, + symmetrized=symmetrized, + use_out_degree=use_out_degree, + dtype=dtype, + form="array", + ) + assert_allclose(do, da) + _assert_allclose_sparse(Lo, La) + + L, d = csgraph.laplacian( + mat, + return_diag=True, + normed=normed, + symmetrized=symmetrized, + use_out_degree=use_out_degree, + dtype=dtype, + form=form, + ) + assert_allclose(d, do) + assert d.dtype == dtype + Lm = L(np.eye(n, dtype=mat.dtype)).astype(dtype) + _assert_allclose_sparse(Lm, Lo, rtol=2e-7, atol=2e-7) + x = np.arange(6).reshape(3, 2) + if not (normed and dtype in INT_DTYPES): + assert_allclose(L(x), Lo @ x) + else: + # Normalized Lo is casted to integer, but L() is not + pass + + +def test_format_error_message(): + with pytest.raises(ValueError, match="Invalid form: 'toto'"): + _ = csgraph.laplacian(np.eye(1), form='toto') diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..8477861d3e563c43379c615ec0913f47a4349abd --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py @@ -0,0 +1,295 @@ +from itertools import product + +import numpy as np +from numpy.testing import assert_array_equal, assert_equal +import pytest + +from scipy.sparse import csr_array, diags_array +from scipy.sparse.csgraph import ( + maximum_bipartite_matching, min_weight_full_bipartite_matching +) + + +def test_maximum_bipartite_matching_raises_on_dense_input(): + with pytest.raises(TypeError): + graph = np.array([[0, 1], [0, 0]]) + maximum_bipartite_matching(graph) + + +def test_maximum_bipartite_matching_empty_graph(): + graph = csr_array((0, 0)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + expected_matching = np.array([]) + assert_array_equal(expected_matching, x) + assert_array_equal(expected_matching, y) + + +def test_maximum_bipartite_matching_empty_left_partition(): + graph = csr_array((2, 0)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + assert_array_equal(np.array([]), x) + assert_array_equal(np.array([-1, -1]), y) + + +def test_maximum_bipartite_matching_empty_right_partition(): + graph = csr_array((0, 3)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + assert_array_equal(np.array([-1, -1, -1]), x) + assert_array_equal(np.array([]), y) + + +def test_maximum_bipartite_matching_graph_with_no_edges(): + graph = csr_array((2, 2)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + assert_array_equal(np.array([-1, -1]), x) + assert_array_equal(np.array([-1, -1]), y) + + +def test_maximum_bipartite_matching_graph_that_causes_augmentation(): + # In this graph, column 1 is initially assigned to row 1, but it should be + # reassigned to make room for row 2. + graph = csr_array([[1, 1], [1, 0]]) + x = maximum_bipartite_matching(graph, perm_type='column') + y = maximum_bipartite_matching(graph, perm_type='row') + expected_matching = np.array([1, 0]) + assert_array_equal(expected_matching, x) + assert_array_equal(expected_matching, y) + + +def test_maximum_bipartite_matching_graph_with_more_rows_than_columns(): + graph = csr_array([[1, 1], [1, 0], [0, 1]]) + x = maximum_bipartite_matching(graph, perm_type='column') + y = maximum_bipartite_matching(graph, perm_type='row') + assert_array_equal(np.array([0, -1, 1]), x) + assert_array_equal(np.array([0, 2]), y) + + +def test_maximum_bipartite_matching_graph_with_more_columns_than_rows(): + graph = csr_array([[1, 1, 0], [0, 0, 1]]) + x = maximum_bipartite_matching(graph, perm_type='column') + y = maximum_bipartite_matching(graph, perm_type='row') + assert_array_equal(np.array([0, 2]), x) + assert_array_equal(np.array([0, -1, 1]), y) + + +def test_maximum_bipartite_matching_explicit_zeros_count_as_edges(): + data = [0, 0] + indices = [1, 0] + indptr = [0, 1, 2] + graph = csr_array((data, indices, indptr), shape=(2, 2)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + expected_matching = np.array([1, 0]) + assert_array_equal(expected_matching, x) + assert_array_equal(expected_matching, y) + + +def test_maximum_bipartite_matching_feasibility_of_result(): + # This is a regression test for GitHub issue #11458 + data = np.ones(50, dtype=int) + indices = [11, 12, 19, 22, 23, 5, 22, 3, 8, 10, 5, 6, 11, 12, 13, 5, 13, + 14, 20, 22, 3, 15, 3, 13, 14, 11, 12, 19, 22, 23, 5, 22, 3, 8, + 10, 5, 6, 11, 12, 13, 5, 13, 14, 20, 22, 3, 15, 3, 13, 14] + indptr = [0, 5, 7, 10, 10, 15, 20, 22, 22, 23, 25, 30, 32, 35, 35, 40, 45, + 47, 47, 48, 50] + graph = csr_array((data, indices, indptr), shape=(20, 25)) + x = maximum_bipartite_matching(graph, perm_type='row') + y = maximum_bipartite_matching(graph, perm_type='column') + assert (x != -1).sum() == 13 + assert (y != -1).sum() == 13 + # Ensure that each element of the matching is in fact an edge in the graph. + for u, v in zip(range(graph.shape[0]), y): + if v != -1: + assert graph[u, v] + for u, v in zip(x, range(graph.shape[1])): + if u != -1: + assert graph[u, v] + + +def test_matching_large_random_graph_with_one_edge_incident_to_each_vertex(): + np.random.seed(42) + A = diags_array(np.ones(25), offsets=0, format='csr') + rand_perm = np.random.permutation(25) + rand_perm2 = np.random.permutation(25) + + Rrow = np.arange(25) + Rcol = rand_perm + Rdata = np.ones(25, dtype=int) + Rmat = csr_array((Rdata, (Rrow, Rcol))) + + Crow = rand_perm2 + Ccol = np.arange(25) + Cdata = np.ones(25, dtype=int) + Cmat = csr_array((Cdata, (Crow, Ccol))) + # Randomly permute identity matrix + B = Rmat @ A @ Cmat + + # Row permute + perm = maximum_bipartite_matching(B, perm_type='row') + Rrow = np.arange(25) + Rcol = perm + Rdata = np.ones(25, dtype=int) + Rmat = csr_array((Rdata, (Rrow, Rcol))) + C1 = Rmat @ B + + # Column permute + perm2 = maximum_bipartite_matching(B, perm_type='column') + Crow = perm2 + Ccol = np.arange(25) + Cdata = np.ones(25, dtype=int) + Cmat = csr_array((Cdata, (Crow, Ccol))) + C2 = B @ Cmat + + # Should get identity matrix back + assert_equal(any(C1.diagonal() == 0), False) + assert_equal(any(C2.diagonal() == 0), False) + + +@pytest.mark.parametrize('num_rows,num_cols', [(0, 0), (2, 0), (0, 3)]) +def test_min_weight_full_matching_trivial_graph(num_rows, num_cols): + biadjacency = csr_array((num_cols, num_rows)) + row_ind, col_ind = min_weight_full_bipartite_matching(biadjacency) + assert len(row_ind) == 0 + assert len(col_ind) == 0 + + +@pytest.mark.parametrize('biadjacency', + [ + [[1, 1, 1], [1, 0, 0], [1, 0, 0]], + [[1, 1, 1], [0, 0, 1], [0, 0, 1]], + [[1, 0, 0, 1], [1, 1, 0, 1], [0, 0, 0, 0]], + [[1, 0, 0], [2, 0, 0]], + [[0, 1, 0], [0, 2, 0]], + [[1, 0], [2, 0], [5, 0]] + ]) +def test_min_weight_full_matching_infeasible_problems(biadjacency): + with pytest.raises(ValueError): + min_weight_full_bipartite_matching(csr_array(biadjacency)) + + +def test_min_weight_full_matching_large_infeasible(): + # Regression test for GitHub issue #17269 + a = np.asarray([ + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001], + [0.0, 0.11687445, 0.0, 0.0, 0.01319788, 0.07509257, 0.0, + 0.0, 0.0, 0.74228317, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.81087935, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.8408466, 0.0, 0.0, 0.0, 0.0, 0.01194389, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.82994211, 0.0, 0.0, 0.0, 0.11468516, 0.0, 0.0, 0.0, + 0.11173505, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0], + [0.18796507, 0.0, 0.04002318, 0.0, 0.0, 0.0, 0.0, 0.0, 0.75883335, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.71545464, 0.0, 0.0, 0.0, 0.0, 0.0, 0.02748488, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.78470564, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.14829198, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.10870609, 0.0, 0.0, 0.0, 0.8918677, 0.0, 0.0, 0.0, 0.06306644, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.63844085, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.7442354, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.09850549, 0.0, 0.0, 0.18638258, + 0.2769244, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.73182464, 0.0, 0.0, 0.46443561, + 0.38589284, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.29510278, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.09666032, 0.0, + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + ]) + with pytest.raises(ValueError, match='no full matching exists'): + min_weight_full_bipartite_matching(csr_array(a)) + + +@pytest.mark.thread_unsafe +def test_explicit_zero_causes_warning(): + with pytest.warns(UserWarning): + biadjacency = csr_array(((2, 0, 3), (0, 1, 1), (0, 2, 3))) + min_weight_full_bipartite_matching(biadjacency) + + +# General test for linear sum assignment solvers to make it possible to rely +# on the same tests for scipy.optimize.linear_sum_assignment. +def linear_sum_assignment_assertions( + solver, array_type, sign, test_case +): + cost_matrix, expected_cost = test_case + maximize = sign == -1 + cost_matrix = sign * array_type(cost_matrix) + expected_cost = sign * np.array(expected_cost) + + row_ind, col_ind = solver(cost_matrix, maximize=maximize) + assert_array_equal(row_ind, np.sort(row_ind)) + assert_array_equal(expected_cost, + np.array(cost_matrix[row_ind, col_ind]).flatten()) + + cost_matrix = cost_matrix.T + row_ind, col_ind = solver(cost_matrix, maximize=maximize) + assert_array_equal(row_ind, np.sort(row_ind)) + assert_array_equal(np.sort(expected_cost), + np.sort(np.array( + cost_matrix[row_ind, col_ind])).flatten()) + + +linear_sum_assignment_test_cases = product( + [-1, 1], + [ + # Square + ([[400, 150, 400], + [400, 450, 600], + [300, 225, 300]], + [150, 400, 300]), + + # Rectangular variant + ([[400, 150, 400, 1], + [400, 450, 600, 2], + [300, 225, 300, 3]], + [150, 2, 300]), + + ([[10, 10, 8], + [9, 8, 1], + [9, 7, 4]], + [10, 1, 7]), + + # Square + ([[10, 10, 8, 11], + [9, 8, 1, 1], + [9, 7, 4, 10]], + [10, 1, 4]), + + # Rectangular variant + ([[10, float("inf"), float("inf")], + [float("inf"), float("inf"), 1], + [float("inf"), 7, float("inf")]], + [10, 1, 7]) + ]) + + +@pytest.mark.parametrize('sign,test_case', linear_sum_assignment_test_cases) +def test_min_weight_full_matching_small_inputs(sign, test_case): + linear_sum_assignment_assertions( + min_weight_full_bipartite_matching, csr_array, sign, test_case) diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..1476c29a3ba97869c6c38be4d717641a494c1183 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py @@ -0,0 +1,194 @@ +import pytest + +import numpy as np +import scipy.sparse as sp +import scipy.sparse.csgraph as spgraph +from scipy._lib import _pep440 + +from numpy.testing import assert_equal + +try: + import sparse +except Exception: + sparse = None + +pytestmark = pytest.mark.skipif(sparse is None, + reason="pydata/sparse not installed") + + +msg = "pydata/sparse (0.15.1) does not implement necessary operations" + + +sparse_params = (pytest.param("COO"), + pytest.param("DOK", marks=[pytest.mark.xfail(reason=msg)])) + + +def check_sparse_version(min_ver): + if sparse is None: + return pytest.mark.skip(reason="sparse is not installed") + return pytest.mark.skipif( + _pep440.parse(sparse.__version__) < _pep440.Version(min_ver), + reason=f"sparse version >= {min_ver} required" + ) + + +@pytest.fixture(params=sparse_params) +def sparse_cls(request): + return getattr(sparse, request.param) + + +@pytest.fixture +def graphs(sparse_cls): + graph = [ + [0, 1, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 1], + [0, 0, 0, 0, 0], + ] + A_dense = np.array(graph) + A_sparse = sparse_cls(A_dense) + return A_dense, A_sparse + + +@pytest.mark.parametrize( + "func", + [ + spgraph.shortest_path, + spgraph.dijkstra, + spgraph.floyd_warshall, + spgraph.bellman_ford, + spgraph.johnson, + spgraph.reverse_cuthill_mckee, + spgraph.maximum_bipartite_matching, + spgraph.structural_rank, + ] +) +def test_csgraph_equiv(func, graphs): + A_dense, A_sparse = graphs + actual = func(A_sparse) + desired = func(sp.csc_array(A_dense)) + assert_equal(actual, desired) + + +def test_connected_components(graphs): + A_dense, A_sparse = graphs + func = spgraph.connected_components + + actual_comp, actual_labels = func(A_sparse) + desired_comp, desired_labels, = func(sp.csc_array(A_dense)) + + assert actual_comp == desired_comp + assert_equal(actual_labels, desired_labels) + + +def test_laplacian(graphs): + A_dense, A_sparse = graphs + sparse_cls = type(A_sparse) + func = spgraph.laplacian + + actual = func(A_sparse) + desired = func(sp.csc_array(A_dense)) + + assert isinstance(actual, sparse_cls) + + assert_equal(actual.todense(), desired.todense()) + + +@pytest.mark.parametrize( + "func", [spgraph.breadth_first_order, spgraph.depth_first_order] +) +def test_order_search(graphs, func): + A_dense, A_sparse = graphs + + actual = func(A_sparse, 0) + desired = func(sp.csc_array(A_dense), 0) + + assert_equal(actual, desired) + + +@pytest.mark.parametrize( + "func", [spgraph.breadth_first_tree, spgraph.depth_first_tree] +) +def test_tree_search(graphs, func): + A_dense, A_sparse = graphs + sparse_cls = type(A_sparse) + + actual = func(A_sparse, 0) + desired = func(sp.csc_array(A_dense), 0) + + assert isinstance(actual, sparse_cls) + + assert_equal(actual.todense(), desired.todense()) + + +def test_minimum_spanning_tree(graphs): + A_dense, A_sparse = graphs + sparse_cls = type(A_sparse) + func = spgraph.minimum_spanning_tree + + actual = func(A_sparse) + desired = func(sp.csc_array(A_dense)) + + assert isinstance(actual, sparse_cls) + + assert_equal(actual.todense(), desired.todense()) + + +def test_maximum_flow(graphs): + A_dense, A_sparse = graphs + sparse_cls = type(A_sparse) + func = spgraph.maximum_flow + + actual = func(A_sparse, 0, 2) + desired = func(sp.csr_array(A_dense), 0, 2) + + assert actual.flow_value == desired.flow_value + assert isinstance(actual.flow, sparse_cls) + + assert_equal(actual.flow.todense(), desired.flow.todense()) + + +def test_min_weight_full_bipartite_matching(graphs): + A_dense, A_sparse = graphs + func = spgraph.min_weight_full_bipartite_matching + + actual = func(A_sparse[0:2, 1:3]) + desired = func(sp.csc_array(A_dense)[0:2, 1:3]) + + assert_equal(actual, desired) + + +@check_sparse_version("0.15.4") +@pytest.mark.parametrize( + "func", + [ + spgraph.shortest_path, + spgraph.dijkstra, + spgraph.floyd_warshall, + spgraph.bellman_ford, + spgraph.johnson, + spgraph.minimum_spanning_tree, + ] +) +@pytest.mark.parametrize( + "fill_value, comp_func", + [(np.inf, np.isposinf), (np.nan, np.isnan)], +) +def test_nonzero_fill_value(graphs, func, fill_value, comp_func): + A_dense, A_sparse = graphs + A_sparse = A_sparse.astype(float) + A_sparse.fill_value = fill_value + sparse_cls = type(A_sparse) + + actual = func(A_sparse) + desired = func(sp.csc_array(A_dense)) + + if func == spgraph.minimum_spanning_tree: + assert isinstance(actual, sparse_cls) + assert comp_func(actual.fill_value) + actual = actual.todense() + actual[comp_func(actual)] = 0.0 + assert_equal(actual, desired.todense()) + else: + assert_equal(actual, desired) diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py new file mode 100644 index 0000000000000000000000000000000000000000..add76cdc29c39c079f386a6ca73075bb90b0a6e8 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py @@ -0,0 +1,70 @@ +import numpy as np +from numpy.testing import assert_equal +from scipy.sparse.csgraph import reverse_cuthill_mckee, structural_rank +from scipy.sparse import csc_array, csr_array, coo_array + + +def test_graph_reverse_cuthill_mckee(): + A = np.array([[1, 0, 0, 0, 1, 0, 0, 0], + [0, 1, 1, 0, 0, 1, 0, 1], + [0, 1, 1, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 1, 0], + [1, 0, 1, 0, 1, 0, 0, 0], + [0, 1, 0, 0, 0, 1, 0, 1], + [0, 0, 0, 1, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0, 1]], dtype=int) + + graph = csr_array(A) + perm = reverse_cuthill_mckee(graph) + correct_perm = np.array([6, 3, 7, 5, 1, 2, 4, 0]) + assert_equal(perm, correct_perm) + + # Test int64 indices input + graph.indices = graph.indices.astype('int64') + graph.indptr = graph.indptr.astype('int64') + perm = reverse_cuthill_mckee(graph, True) + assert_equal(perm, correct_perm) + + +def test_graph_reverse_cuthill_mckee_ordering(): + data = np.ones(63,dtype=int) + rows = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, + 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, + 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, + 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, + 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, + 14, 15, 15, 15, 15, 15]) + cols = np.array([0, 2, 5, 8, 10, 1, 3, 9, 11, 0, 2, + 7, 10, 1, 3, 11, 4, 6, 12, 14, 0, 7, 13, + 15, 4, 6, 14, 2, 5, 7, 15, 0, 8, 10, 13, + 1, 9, 11, 0, 2, 8, 10, 15, 1, 3, 9, 11, + 4, 12, 14, 5, 8, 13, 15, 4, 6, 12, 14, + 5, 7, 10, 13, 15]) + graph = csr_array((data, (rows,cols))) + perm = reverse_cuthill_mckee(graph) + correct_perm = np.array([12, 14, 4, 6, 10, 8, 2, 15, + 0, 13, 7, 5, 9, 11, 1, 3]) + assert_equal(perm, correct_perm) + + +def test_graph_structural_rank(): + # Test square matrix #1 + A = csc_array([[1, 1, 0], + [1, 0, 1], + [0, 1, 0]]) + assert_equal(structural_rank(A), 3) + + # Test square matrix #2 + rows = np.array([0,0,0,0,0,1,1,2,2,3,3,3,3,3,3,4,4,5,5,6,6,7,7]) + cols = np.array([0,1,2,3,4,2,5,2,6,0,1,3,5,6,7,4,5,5,6,2,6,2,4]) + data = np.ones_like(rows) + B = coo_array((data,(rows,cols)), shape=(8,8)) + assert_equal(structural_rank(B), 6) + + #Test non-square matrix + C = csc_array([[1, 0, 2, 0], + [2, 0, 4, 0]]) + assert_equal(structural_rank(C), 2) + + #Test tall matrix + assert_equal(structural_rank(C.T), 2) diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py new file mode 100644 index 0000000000000000000000000000000000000000..ba50f760e750ce1dbdec3624c2ab985fca1af7d1 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py @@ -0,0 +1,484 @@ +from io import StringIO +import warnings +import numpy as np +from numpy.testing import assert_array_almost_equal, assert_array_equal, assert_allclose +from pytest import raises as assert_raises +from scipy.sparse.csgraph import (shortest_path, dijkstra, johnson, + bellman_ford, construct_dist_matrix, yen, + NegativeCycleError) +import scipy.sparse +from scipy.io import mmread +import pytest + +directed_G = np.array([[0, 3, 3, 0, 0], + [0, 0, 0, 2, 4], + [0, 0, 0, 0, 0], + [1, 0, 0, 0, 0], + [2, 0, 0, 2, 0]], dtype=float) + +undirected_G = np.array([[0, 3, 3, 1, 2], + [3, 0, 0, 2, 4], + [3, 0, 0, 0, 0], + [1, 2, 0, 0, 2], + [2, 4, 0, 2, 0]], dtype=float) + +unweighted_G = (directed_G > 0).astype(float) + +directed_SP = [[0, 3, 3, 5, 7], + [3, 0, 6, 2, 4], + [np.inf, np.inf, 0, np.inf, np.inf], + [1, 4, 4, 0, 8], + [2, 5, 5, 2, 0]] + +directed_2SP_0_to_3 = [[-9999, 0, -9999, 1, -9999], + [-9999, 0, -9999, 4, 1]] + +directed_sparse_zero_G = scipy.sparse.csr_array( + ( + [0, 1, 2, 3, 1], + ([0, 1, 2, 3, 4], [1, 2, 0, 4, 3]), + ), + shape=(5, 5), +) + +directed_sparse_zero_SP = [[0, 0, 1, np.inf, np.inf], + [3, 0, 1, np.inf, np.inf], + [2, 2, 0, np.inf, np.inf], + [np.inf, np.inf, np.inf, 0, 3], + [np.inf, np.inf, np.inf, 1, 0]] + +undirected_sparse_zero_G = scipy.sparse.csr_array( + ( + [0, 0, 1, 1, 2, 2, 1, 1], + ([0, 1, 1, 2, 2, 0, 3, 4], [1, 0, 2, 1, 0, 2, 4, 3]) + ), + shape=(5, 5), +) + +undirected_sparse_zero_SP = [[0, 0, 1, np.inf, np.inf], + [0, 0, 1, np.inf, np.inf], + [1, 1, 0, np.inf, np.inf], + [np.inf, np.inf, np.inf, 0, 1], + [np.inf, np.inf, np.inf, 1, 0]] + +directed_pred = np.array([[-9999, 0, 0, 1, 1], + [3, -9999, 0, 1, 1], + [-9999, -9999, -9999, -9999, -9999], + [3, 0, 0, -9999, 1], + [4, 0, 0, 4, -9999]], dtype=float) + +undirected_SP = np.array([[0, 3, 3, 1, 2], + [3, 0, 6, 2, 4], + [3, 6, 0, 4, 5], + [1, 2, 4, 0, 2], + [2, 4, 5, 2, 0]], dtype=float) + +undirected_SP_limit_2 = np.array([[0, np.inf, np.inf, 1, 2], + [np.inf, 0, np.inf, 2, np.inf], + [np.inf, np.inf, 0, np.inf, np.inf], + [1, 2, np.inf, 0, 2], + [2, np.inf, np.inf, 2, 0]], dtype=float) + +undirected_SP_limit_0 = np.ones((5, 5), dtype=float) - np.eye(5) +undirected_SP_limit_0[undirected_SP_limit_0 > 0] = np.inf + +undirected_pred = np.array([[-9999, 0, 0, 0, 0], + [1, -9999, 0, 1, 1], + [2, 0, -9999, 0, 0], + [3, 3, 0, -9999, 3], + [4, 4, 0, 4, -9999]], dtype=float) + +directed_negative_weighted_G = np.array([[0, 0, 0], + [-1, 0, 0], + [0, -1, 0]], dtype=float) + +directed_negative_weighted_SP = np.array([[0, np.inf, np.inf], + [-1, 0, np.inf], + [-2, -1, 0]], dtype=float) + +methods = ['auto', 'FW', 'D', 'BF', 'J'] + + +def test_dijkstra_limit(): + limits = [0, 2, np.inf] + results = [undirected_SP_limit_0, + undirected_SP_limit_2, + undirected_SP] + + def check(limit, result): + SP = dijkstra(undirected_G, directed=False, limit=limit) + assert_array_almost_equal(SP, result) + + for limit, result in zip(limits, results): + check(limit, result) + + +def test_directed(): + def check(method): + SP = shortest_path(directed_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP, directed_SP) + + for method in methods: + check(method) + + +def test_undirected(): + def check(method, directed_in): + if directed_in: + SP1 = shortest_path(directed_G, method=method, directed=False, + overwrite=False) + assert_array_almost_equal(SP1, undirected_SP) + else: + SP2 = shortest_path(undirected_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP2, undirected_SP) + + for method in methods: + for directed_in in (True, False): + check(method, directed_in) + + +def test_directed_sparse_zero(): + # test directed sparse graph with zero-weight edge and two connected components + def check(method): + SP = shortest_path(directed_sparse_zero_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP, directed_sparse_zero_SP) + + for method in methods: + check(method) + + +def test_undirected_sparse_zero(): + def check(method, directed_in): + if directed_in: + SP1 = shortest_path(directed_sparse_zero_G, method=method, directed=False, + overwrite=False) + assert_array_almost_equal(SP1, undirected_sparse_zero_SP) + else: + SP2 = shortest_path(undirected_sparse_zero_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP2, undirected_sparse_zero_SP) + + for method in methods: + for directed_in in (True, False): + check(method, directed_in) + + +@pytest.mark.parametrize('directed, SP_ans', + ((True, directed_SP), + (False, undirected_SP))) +@pytest.mark.parametrize('indices', ([0, 2, 4], [0, 4], [3, 4], [0, 0])) +def test_dijkstra_indices_min_only(directed, SP_ans, indices): + SP_ans = np.array(SP_ans) + indices = np.array(indices, dtype=np.int64) + min_ind_ans = indices[np.argmin(SP_ans[indices, :], axis=0)] + min_d_ans = np.zeros(SP_ans.shape[0], SP_ans.dtype) + for k in range(SP_ans.shape[0]): + min_d_ans[k] = SP_ans[min_ind_ans[k], k] + min_ind_ans[np.isinf(min_d_ans)] = -9999 + + SP, pred, sources = dijkstra(directed_G, + directed=directed, + indices=indices, + min_only=True, + return_predecessors=True) + assert_array_almost_equal(SP, min_d_ans) + assert_array_equal(min_ind_ans, sources) + SP = dijkstra(directed_G, + directed=directed, + indices=indices, + min_only=True, + return_predecessors=False) + assert_array_almost_equal(SP, min_d_ans) + + +@pytest.mark.parametrize('n', (10, 100, 1000)) +def test_dijkstra_min_only_random(n): + rng = np.random.default_rng(7345782358920239234) + data = scipy.sparse.random_array((n, n), density=0.5, format='lil', + rng=rng, dtype=np.float64) + data.setdiag(np.zeros(n, dtype=np.bool_)) + # choose some random vertices + v = np.arange(n) + rng.shuffle(v) + indices = v[:int(n*.1)] + ds, pred, sources = dijkstra(data, + directed=True, + indices=indices, + min_only=True, + return_predecessors=True) + for k in range(n): + p = pred[k] + s = sources[k] + while p != -9999: + assert sources[p] == s + p = pred[p] + + +def test_dijkstra_random(): + # reproduces the hang observed in gh-17782 + n = 10 + indices = [0, 4, 4, 5, 7, 9, 0, 6, 2, 3, 7, 9, 1, 2, 9, 2, 5, 6] + indptr = [0, 0, 2, 5, 6, 7, 8, 12, 15, 18, 18] + data = [0.33629, 0.40458, 0.47493, 0.42757, 0.11497, 0.91653, 0.69084, + 0.64979, 0.62555, 0.743, 0.01724, 0.99945, 0.31095, 0.15557, + 0.02439, 0.65814, 0.23478, 0.24072] + graph = scipy.sparse.csr_array((data, indices, indptr), shape=(n, n)) + dijkstra(graph, directed=True, return_predecessors=True) + + +def test_gh_17782_segfault(): + text = """%%MatrixMarket matrix coordinate real general + 84 84 22 + 2 1 4.699999809265137e+00 + 6 14 1.199999973177910e-01 + 9 6 1.199999973177910e-01 + 10 16 2.012000083923340e+01 + 11 10 1.422000026702881e+01 + 12 1 9.645999908447266e+01 + 13 18 2.012000083923340e+01 + 14 13 4.679999828338623e+00 + 15 11 1.199999973177910e-01 + 16 12 1.199999973177910e-01 + 18 15 1.199999973177910e-01 + 32 2 2.299999952316284e+00 + 33 20 6.000000000000000e+00 + 33 32 5.000000000000000e+00 + 36 9 3.720000028610229e+00 + 36 37 3.720000028610229e+00 + 36 38 3.720000028610229e+00 + 37 44 8.159999847412109e+00 + 38 32 7.903999328613281e+01 + 43 20 2.400000000000000e+01 + 43 33 4.000000000000000e+00 + 44 43 6.028000259399414e+01 + """ + data = mmread(StringIO(text), spmatrix=False) + dijkstra(data, directed=True, return_predecessors=True) + + +def test_shortest_path_indices(): + indices = np.arange(4) + + def check(func, indshape): + outshape = indshape + (5,) + SP = func(directed_G, directed=False, + indices=indices.reshape(indshape)) + assert_array_almost_equal(SP, undirected_SP[indices].reshape(outshape)) + + for indshape in [(4,), (4, 1), (2, 2)]: + for func in (dijkstra, bellman_ford, johnson, shortest_path): + check(func, indshape) + + assert_raises(ValueError, shortest_path, directed_G, method='FW', + indices=indices) + + +def test_predecessors(): + SP_res = {True: directed_SP, + False: undirected_SP} + pred_res = {True: directed_pred, + False: undirected_pred} + + def check(method, directed): + SP, pred = shortest_path(directed_G, method, directed=directed, + overwrite=False, + return_predecessors=True) + assert_array_almost_equal(SP, SP_res[directed]) + assert_array_almost_equal(pred, pred_res[directed]) + + for method in methods: + for directed in (True, False): + check(method, directed) + + +def test_construct_shortest_path(): + def check(method, directed): + SP1, pred = shortest_path(directed_G, + directed=directed, + overwrite=False, + return_predecessors=True) + SP2 = construct_dist_matrix(directed_G, pred, directed=directed) + assert_array_almost_equal(SP1, SP2) + + for method in methods: + for directed in (True, False): + check(method, directed) + + +def test_unweighted_path(): + def check(method, directed): + SP1 = shortest_path(directed_G, + directed=directed, + overwrite=False, + unweighted=True) + SP2 = shortest_path(unweighted_G, + directed=directed, + overwrite=False, + unweighted=False) + assert_array_almost_equal(SP1, SP2) + + for method in methods: + for directed in (True, False): + check(method, directed) + + +def test_negative_cycles(): + # create a small graph with a negative cycle + graph = np.ones([5, 5]) + graph.flat[::6] = 0 + graph[1, 2] = -2 + + def check(method, directed): + assert_raises(NegativeCycleError, shortest_path, graph, method, + directed) + + for directed in (True, False): + for method in ['FW', 'J', 'BF']: + check(method, directed) + + assert_raises(NegativeCycleError, yen, graph, 0, 1, 1, + directed=directed) + + +@pytest.mark.parametrize("method", ['FW', 'J', 'BF']) +def test_negative_weights(method): + SP = shortest_path(directed_negative_weighted_G, method, directed=True) + assert_allclose(SP, directed_negative_weighted_SP, atol=1e-10) + + +def test_masked_input(): + np.ma.masked_equal(directed_G, 0) + + def check(method): + SP = shortest_path(directed_G, method=method, directed=True, + overwrite=False) + assert_array_almost_equal(SP, directed_SP) + + for method in methods: + check(method) + + +def test_overwrite(): + G = np.array([[0, 3, 3, 1, 2], + [3, 0, 0, 2, 4], + [3, 0, 0, 0, 0], + [1, 2, 0, 0, 2], + [2, 4, 0, 2, 0]], dtype=float) + foo = G.copy() + shortest_path(foo, overwrite=False) + assert_array_equal(foo, G) + + +@pytest.mark.parametrize('method', methods) +def test_buffer(method): + # Smoke test that sparse matrices with read-only buffers (e.g., those from + # joblib workers) do not cause:: + # + # ValueError: buffer source array is read-only + # + G = scipy.sparse.csr_array([[1.]]) + G.data.flags['WRITEABLE'] = False + shortest_path(G, method=method) + + +def test_NaN_warnings(): + with warnings.catch_warnings(record=True) as record: + shortest_path(np.array([[0, 1], [np.nan, 0]])) + for r in record: + assert r.category is not RuntimeWarning + + +def test_sparse_matrices(): + # Test that using lil,csr and csc sparse matrix do not cause error + G_dense = np.array([[0, 3, 0, 0, 0], + [0, 0, -1, 0, 0], + [0, 0, 0, 2, 0], + [0, 0, 0, 0, 4], + [0, 0, 0, 0, 0]], dtype=float) + SP = shortest_path(G_dense) + G_csr = scipy.sparse.csr_array(G_dense) + G_csc = scipy.sparse.csc_array(G_dense) + G_lil = scipy.sparse.lil_array(G_dense) + assert_array_almost_equal(SP, shortest_path(G_csr)) + assert_array_almost_equal(SP, shortest_path(G_csc)) + assert_array_almost_equal(SP, shortest_path(G_lil)) + + +def test_yen_directed(): + distances, predecessors = yen( + directed_G, + source=0, + sink=3, + K=2, + return_predecessors=True + ) + assert_allclose(distances, [5., 9.]) + assert_allclose(predecessors, directed_2SP_0_to_3) + + +def test_yen_undirected(): + distances = yen( + undirected_G, + source=0, + sink=3, + K=4, + ) + assert_allclose(distances, [1., 4., 5., 8.]) + +def test_yen_unweighted(): + # Ask for more paths than there are, verify only the available paths are returned + distances, predecessors = yen( + directed_G, + source=0, + sink=3, + K=4, + unweighted=True, + return_predecessors=True, + ) + assert_allclose(distances, [2., 3.]) + assert_allclose(predecessors, directed_2SP_0_to_3) + +def test_yen_no_paths(): + distances = yen( + directed_G, + source=2, + sink=3, + K=1, + ) + assert distances.size == 0 + +def test_yen_negative_weights(): + distances = yen( + directed_negative_weighted_G, + source=2, + sink=0, + K=1, + ) + assert_allclose(distances, [-2.]) + + +@pytest.mark.parametrize("min_only", (True, False)) +@pytest.mark.parametrize("directed", (True, False)) +@pytest.mark.parametrize("return_predecessors", (True, False)) +@pytest.mark.parametrize("index_dtype", (np.int32, np.int64)) +@pytest.mark.parametrize("indices", (None, [1])) +def test_20904(min_only, directed, return_predecessors, index_dtype, indices): + """Test two failures from gh-20904: int32 and indices-as-None.""" + adj_mat = scipy.sparse.eye_array(4, format="csr") + adj_mat = scipy.sparse.csr_array( + ( + adj_mat.data, + adj_mat.indices.astype(index_dtype), + adj_mat.indptr.astype(index_dtype), + ), + ) + dijkstra( + adj_mat, + directed, + indices=indices, + min_only=min_only, + return_predecessors=return_predecessors, + ) diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..3237a14584d42022184a54f174b809a2b06d16ed --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py @@ -0,0 +1,66 @@ +"""Test the minimum spanning tree function""" +import numpy as np +from numpy.testing import assert_ +import numpy.testing as npt +from scipy.sparse import csr_array +from scipy.sparse.csgraph import minimum_spanning_tree + + +def test_minimum_spanning_tree(): + + # Create a graph with two connected components. + graph = [[0,1,0,0,0], + [1,0,0,0,0], + [0,0,0,8,5], + [0,0,8,0,1], + [0,0,5,1,0]] + graph = np.asarray(graph) + + # Create the expected spanning tree. + expected = [[0,1,0,0,0], + [0,0,0,0,0], + [0,0,0,0,5], + [0,0,0,0,1], + [0,0,0,0,0]] + expected = np.asarray(expected) + + # Ensure minimum spanning tree code gives this expected output. + csgraph = csr_array(graph) + mintree = minimum_spanning_tree(csgraph) + mintree_array = mintree.toarray() + npt.assert_array_equal(mintree_array, expected, + 'Incorrect spanning tree found.') + + # Ensure that the original graph was not modified. + npt.assert_array_equal(csgraph.toarray(), graph, + 'Original graph was modified.') + + # Now let the algorithm modify the csgraph in place. + mintree = minimum_spanning_tree(csgraph, overwrite=True) + npt.assert_array_equal(mintree.toarray(), expected, + 'Graph was not properly modified to contain MST.') + + np.random.seed(1234) + for N in (5, 10, 15, 20): + + # Create a random graph. + graph = 3 + np.random.random((N, N)) + csgraph = csr_array(graph) + + # The spanning tree has at most N - 1 edges. + mintree = minimum_spanning_tree(csgraph) + assert_(mintree.nnz < N) + + # Set the sub diagonal to 1 to create a known spanning tree. + idx = np.arange(N-1) + graph[idx,idx+1] = 1 + csgraph = csr_array(graph) + mintree = minimum_spanning_tree(csgraph) + + # We expect to see this pattern in the spanning tree and otherwise + # have this zero. + expected = np.zeros((N, N)) + expected[idx, idx+1] = 1 + + npt.assert_array_equal(mintree.toarray(), expected, + 'Incorrect spanning tree found.') diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py new file mode 100644 index 0000000000000000000000000000000000000000..aef6def21b61ff6b8d8bfb990a3a69136349d7c5 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py @@ -0,0 +1,148 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_almost_equal +from scipy.sparse import csr_array, csr_matrix, coo_array, coo_matrix +from scipy.sparse.csgraph import (breadth_first_tree, depth_first_tree, + csgraph_to_dense, csgraph_from_dense, csgraph_masked_from_dense) + + +def test_graph_breadth_first(): + csgraph = np.array([[0, 1, 2, 0, 0], + [1, 0, 0, 0, 3], + [2, 0, 0, 7, 0], + [0, 0, 7, 0, 1], + [0, 3, 0, 1, 0]]) + csgraph = csgraph_from_dense(csgraph, null_value=0) + + bfirst = np.array([[0, 1, 2, 0, 0], + [0, 0, 0, 0, 3], + [0, 0, 0, 7, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]]) + + for directed in [True, False]: + bfirst_test = breadth_first_tree(csgraph, 0, directed) + assert_array_almost_equal(csgraph_to_dense(bfirst_test), + bfirst) + + +def test_graph_depth_first(): + csgraph = np.array([[0, 1, 2, 0, 0], + [1, 0, 0, 0, 3], + [2, 0, 0, 7, 0], + [0, 0, 7, 0, 1], + [0, 3, 0, 1, 0]]) + csgraph = csgraph_from_dense(csgraph, null_value=0) + + dfirst = np.array([[0, 1, 0, 0, 0], + [0, 0, 0, 0, 3], + [0, 0, 0, 0, 0], + [0, 0, 7, 0, 0], + [0, 0, 0, 1, 0]]) + + for directed in [True, False]: + dfirst_test = depth_first_tree(csgraph, 0, directed) + assert_array_almost_equal(csgraph_to_dense(dfirst_test), dfirst) + + +def test_return_type(): + from .._laplacian import laplacian + from .._min_spanning_tree import minimum_spanning_tree + + np_csgraph = np.array([[0, 1, 2, 0, 0], + [1, 0, 0, 0, 3], + [2, 0, 0, 7, 0], + [0, 0, 7, 0, 1], + [0, 3, 0, 1, 0]]) + csgraph = csr_array(np_csgraph) + assert isinstance(laplacian(csgraph), coo_array) + assert isinstance(minimum_spanning_tree(csgraph), csr_array) + for directed in [True, False]: + assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array) + assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array) + + csgraph = csgraph_from_dense(np_csgraph, null_value=0) + assert isinstance(csgraph, csr_array) + assert isinstance(laplacian(csgraph), coo_array) + assert isinstance(minimum_spanning_tree(csgraph), csr_array) + for directed in [True, False]: + assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array) + assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array) + + csgraph = csgraph_masked_from_dense(np_csgraph, null_value=0) + assert isinstance(csgraph, np.ma.MaskedArray) + assert csgraph._baseclass is np.ndarray + # laplacian doesnt work with masked arrays so not here + assert isinstance(minimum_spanning_tree(csgraph), csr_array) + for directed in [True, False]: + assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array) + assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array) + + # start of testing with matrix/spmatrix types + with np.testing.suppress_warnings() as sup: + sup.filter(DeprecationWarning, "the matrix subclass.*") + sup.filter(PendingDeprecationWarning, "the matrix subclass.*") + + nm_csgraph = np.matrix([[0, 1, 2, 0, 0], + [1, 0, 0, 0, 3], + [2, 0, 0, 7, 0], + [0, 0, 7, 0, 1], + [0, 3, 0, 1, 0]]) + + csgraph = csr_matrix(nm_csgraph) + assert isinstance(laplacian(csgraph), coo_matrix) + assert isinstance(minimum_spanning_tree(csgraph), csr_matrix) + for directed in [True, False]: + assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix) + assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix) + + csgraph = csgraph_from_dense(nm_csgraph, null_value=0) + assert isinstance(csgraph, csr_matrix) + assert isinstance(laplacian(csgraph), coo_matrix) + assert isinstance(minimum_spanning_tree(csgraph), csr_matrix) + for directed in [True, False]: + assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix) + assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix) + + mm_csgraph = csgraph_masked_from_dense(nm_csgraph, null_value=0) + assert isinstance(mm_csgraph, np.ma.MaskedArray) + # laplacian doesnt work with masked arrays so not here + assert isinstance(minimum_spanning_tree(csgraph), csr_matrix) + for directed in [True, False]: + assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix) + assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix) + # end of testing with matrix/spmatrix types + + +def test_graph_breadth_first_trivial_graph(): + csgraph = np.array([[0]]) + csgraph = csgraph_from_dense(csgraph, null_value=0) + + bfirst = np.array([[0]]) + + for directed in [True, False]: + bfirst_test = breadth_first_tree(csgraph, 0, directed) + assert_array_almost_equal(csgraph_to_dense(bfirst_test), bfirst) + + +def test_graph_depth_first_trivial_graph(): + csgraph = np.array([[0]]) + csgraph = csgraph_from_dense(csgraph, null_value=0) + + bfirst = np.array([[0]]) + + for directed in [True, False]: + bfirst_test = depth_first_tree(csgraph, 0, directed) + assert_array_almost_equal(csgraph_to_dense(bfirst_test), + bfirst) + + +@pytest.mark.parametrize('directed', [True, False]) +@pytest.mark.parametrize('tree_func', [breadth_first_tree, depth_first_tree]) +def test_int64_indices(tree_func, directed): + # See https://github.com/scipy/scipy/issues/18716 + g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2)) + assert g.indices.dtype == np.int64 + tree = tree_func(g, 0, directed=directed) + assert_array_almost_equal(csgraph_to_dense(tree), [[0, 1], [0, 0]]) + diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lsmr.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lsmr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..568fd5d3bc9e765f716b82d632a1b766fa7d96e7 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lsmr.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_gcrotmk.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_gcrotmk.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5bae2697be680738b2f13da62e7ed25783890c4 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_gcrotmk.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_iterative.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_iterative.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03be1e225c45718f0de9959bfe6d2ebf7819d86e Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_iterative.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_lsmr.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_lsmr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7013c43022619e29ec41910e3010fdc74b6e7632 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_lsmr.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_lsqr.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_lsqr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d85b077d07dc4464f5fe310e3e127445755ed52d Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_lsqr.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_minres.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_minres.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47dd4f41a2c0a11c2b13ea1168b64b0e6d1998e7 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_minres.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_utils.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..720fba6e3794d740f8da4c3a2f0fe601ab44d26d Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__pycache__/test_utils.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py new file mode 100644 index 0000000000000000000000000000000000000000..6523f0b344e86bdcb1e520a61cbaed0a28e77e70 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python +"""Tests for the linalg._isolve.gcrotmk module +""" + +import threading +from numpy.testing import (assert_, assert_allclose, assert_equal, + suppress_warnings) + +import numpy as np +from numpy import zeros, array, allclose +from scipy.linalg import norm +from scipy.sparse import csr_array, eye_array, random_array + +from scipy.sparse.linalg._interface import LinearOperator +from scipy.sparse.linalg import splu +from scipy.sparse.linalg._isolve import gcrotmk, gmres + + +Am = csr_array(array([[-2,1,0,0,0,9], + [1,-2,1,0,5,0], + [0,1,-2,1,0,0], + [0,0,1,-2,1,0], + [0,3,0,1,-2,1], + [1,0,0,0,1,-2]])) +b = array([1,2,3,4,5,6]) +count = threading.local() # [0] +niter = threading.local() # [0] + + +def matvec(v): + if not hasattr(count, 'c'): + count.c = [0] + count.c[0] += 1 + return Am@v + + +def cb(v): + if not hasattr(niter, 'n'): + niter.n = [0] + niter.n[0] += 1 + + +A = LinearOperator(matvec=matvec, shape=Am.shape, dtype=Am.dtype) + + +def do_solve(**kw): + if not hasattr(niter, 'n'): + niter.n = [0] + + if not hasattr(count, 'c'): + count.c = [0] + + count.c[0] = 0 + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + x0, flag = gcrotmk(A, b, x0=zeros(A.shape[0]), rtol=1e-14, **kw) + count_0 = count.c[0] + assert_(allclose(A@x0, b, rtol=1e-12, atol=1e-12), norm(A@x0-b)) + return x0, count_0 + + +class TestGCROTMK: + def test_preconditioner(self): + # Check that preconditioning works + pc = splu(Am.tocsc()) + M = LinearOperator(matvec=pc.solve, shape=A.shape, dtype=A.dtype) + + x0, count_0 = do_solve() + niter.n[0] = 0 + x1, count_1 = do_solve(M=M, callback=cb) + + assert_equal(count_1, 3) + assert count_1 < count_0/2 + assert allclose(x1, x0, rtol=1e-14) + assert niter.n[0] < 3 + + def test_arnoldi(self): + rng = np.random.default_rng(1) + + A = eye_array(2000) + random_array((2000, 2000), density=5e-4, rng=rng) + b = rng.random(2000) + + # The inner arnoldi should be equivalent to gmres + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + x0, flag0 = gcrotmk(A, b, x0=zeros(A.shape[0]), m=10, k=0, maxiter=1) + x1, flag1 = gmres(A, b, x0=zeros(A.shape[0]), restart=10, maxiter=1) + + assert_equal(flag0, 1) + assert_equal(flag1, 1) + assert np.linalg.norm(A.dot(x0) - b) > 1e-4 + + assert_allclose(x0, x1) + + def test_cornercase(self): + np.random.seed(1234) + + # Rounding error may prevent convergence with tol=0 --- ensure + # that the return values in this case are correct, and no + # exceptions are raised + + for n in [3, 5, 10, 100]: + A = 2*eye_array(n) + + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + b = np.ones(n) + x, info = gcrotmk(A, b, maxiter=10) + assert_equal(info, 0) + assert_allclose(A.dot(x) - b, 0, atol=1e-14) + + x, info = gcrotmk(A, b, rtol=0, maxiter=10) + if info == 0: + assert_allclose(A.dot(x) - b, 0, atol=1e-14) + + b = np.random.rand(n) + x, info = gcrotmk(A, b, maxiter=10) + assert_equal(info, 0) + assert_allclose(A.dot(x) - b, 0, atol=1e-14) + + x, info = gcrotmk(A, b, rtol=0, maxiter=10) + if info == 0: + assert_allclose(A.dot(x) - b, 0, atol=1e-14) + + def test_nans(self): + A = eye_array(3, format='lil') + A[1,1] = np.nan + b = np.ones(3) + + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + x, info = gcrotmk(A, b, rtol=0, maxiter=10) + assert_equal(info, 1) + + def test_truncate(self): + np.random.seed(1234) + A = np.random.rand(30, 30) + np.eye(30) + b = np.random.rand(30) + + for truncate in ['oldest', 'smallest']: + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + x, info = gcrotmk(A, b, m=10, k=10, truncate=truncate, + rtol=1e-4, maxiter=200) + assert_equal(info, 0) + assert_allclose(A.dot(x) - b, 0, atol=1e-3) + + def test_CU(self): + for discard_C in (True, False): + # Check that C,U behave as expected + CU = [] + x0, count_0 = do_solve(CU=CU, discard_C=discard_C) + assert_(len(CU) > 0) + assert_(len(CU) <= 6) + + if discard_C: + for c, u in CU: + assert_(c is None) + + # should converge immediately + x1, count_1 = do_solve(CU=CU, discard_C=discard_C) + if discard_C: + assert_equal(count_1, 2 + len(CU)) + else: + assert_equal(count_1, 3) + assert_(count_1 <= count_0/2) + assert_allclose(x1, x0, atol=1e-14) + + def test_denormals(self): + # Check that no warnings are emitted if the matrix contains + # numbers for which 1/x has no float representation, and that + # the solver behaves properly. + A = np.array([[1, 2], [3, 4]], dtype=float) + A *= 100 * np.nextafter(0, 1) + + b = np.array([1, 1]) + + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, ".*called without specifying.*") + xp, info = gcrotmk(A, b) + + if info == 0: + assert_allclose(A.dot(xp), b) diff --git a/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_base.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..820f6c5697c9cdfbb17233c40cb94ff43e361c9c --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/scipy/sparse/tests/__pycache__/test_base.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:513e26cfb85855a7a0835f7faa0e0687257d1ac95aa0c31c3989fe1296da3d4f +size 160622 diff --git a/moondream/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER b/moondream/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/moondream/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/METADATA b/moondream/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..fa2550faeadd4cce0f28323321c2c212032f4481 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/METADATA @@ -0,0 +1,93 @@ +Metadata-Version: 2.1 +Name: contourpy +Version: 1.3.1 +Summary: Python library for calculating contours of 2D quadrilateral grids +Author-Email: Ian Thomas +License: BSD 3-Clause License + + Copyright (c) 2021-2024, ContourPy Developers. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: C++ +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Scientific/Engineering :: Information Analysis +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Visualization +Project-URL: Homepage, https://github.com/contourpy/contourpy +Project-URL: Changelog, https://contourpy.readthedocs.io/en/latest/changelog.html +Project-URL: Documentation, https://contourpy.readthedocs.io +Project-URL: Repository, https://github.com/contourpy/contourpy +Requires-Python: >=3.10 +Requires-Dist: numpy>=1.23 +Provides-Extra: docs +Requires-Dist: furo; extra == "docs" +Requires-Dist: sphinx>=7.2; extra == "docs" +Requires-Dist: sphinx-copybutton; extra == "docs" +Provides-Extra: bokeh +Requires-Dist: bokeh; extra == "bokeh" +Requires-Dist: selenium; extra == "bokeh" +Provides-Extra: mypy +Requires-Dist: contourpy[bokeh,docs]; extra == "mypy" +Requires-Dist: docutils-stubs; extra == "mypy" +Requires-Dist: mypy==1.11.1; extra == "mypy" +Requires-Dist: types-Pillow; extra == "mypy" +Provides-Extra: test +Requires-Dist: contourpy[test-no-images]; extra == "test" +Requires-Dist: matplotlib; extra == "test" +Requires-Dist: Pillow; extra == "test" +Provides-Extra: test-no-images +Requires-Dist: pytest; extra == "test-no-images" +Requires-Dist: pytest-cov; extra == "test-no-images" +Requires-Dist: pytest-rerunfailures; extra == "test-no-images" +Requires-Dist: pytest-xdist; extra == "test-no-images" +Requires-Dist: wurlitzer; extra == "test-no-images" +Description-Content-Type: text/markdown + +ContourPy + +ContourPy is a Python library for calculating contours of 2D quadrilateral grids. It is written in C++11 and wrapped using pybind11. + +It contains the 2005 and 2014 algorithms used in Matplotlib as well as a newer algorithm that includes more features and is available in both serial and multithreaded versions. It provides an easy way for Python libraries to use contouring algorithms without having to include Matplotlib as a dependency. + + * **Documentation**: https://contourpy.readthedocs.io + * **Source code**: https://github.com/contourpy/contourpy + +| | | +| --- | --- | +| Latest release | [![PyPI version](https://img.shields.io/pypi/v/contourpy.svg?label=pypi&color=fdae61)](https://pypi.python.org/pypi/contourpy) [![conda-forge version](https://img.shields.io/conda/v/conda-forge/contourpy.svg?label=conda-forge&color=a6d96a)](https://anaconda.org/conda-forge/contourpy) | +| Downloads | [![PyPi downloads](https://img.shields.io/pypi/dm/contourpy?label=pypi&style=flat&color=fdae61)](https://pepy.tech/project/contourpy) | +| Python version | [![Platforms](https://img.shields.io/pypi/pyversions/contourpy?color=fdae61)](https://pypi.org/project/contourpy/) | +| Coverage | [![Codecov](https://img.shields.io/codecov/c/gh/contourpy/contourpy?color=fdae61&label=codecov)](https://app.codecov.io/gh/contourpy/contourpy) | diff --git a/moondream/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/RECORD b/moondream/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f4bc9005ba1d6f860f270a9cf25a1bdee9513d7e --- /dev/null +++ b/moondream/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/RECORD @@ -0,0 +1,43 @@ +contourpy-1.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +contourpy-1.3.1.dist-info/LICENSE,sha256=x9ChU7_6oQQERGPrxjN5PUUXIu_TE4tf_SUntA8VBaI,1534 +contourpy-1.3.1.dist-info/METADATA,sha256=LQNae4q9MVNwpfb0FlnTCTe2tkw22GiKEJjpks9n7jk,5423 +contourpy-1.3.1.dist-info/RECORD,, +contourpy-1.3.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +contourpy-1.3.1.dist-info/WHEEL,sha256=sZM_NeUMz2G4fDenMf11eikcCxcLaQWiYRmjwQBavQs,137 +contourpy/__init__.py,sha256=Vi2YbtUhM9VxYPY3PBvxfu0xZYr6fBysl5gQPJEo88k,11831 +contourpy/__pycache__/__init__.cpython-310.pyc,, +contourpy/__pycache__/_version.cpython-310.pyc,, +contourpy/__pycache__/array.cpython-310.pyc,, +contourpy/__pycache__/chunk.cpython-310.pyc,, +contourpy/__pycache__/convert.cpython-310.pyc,, +contourpy/__pycache__/dechunk.cpython-310.pyc,, +contourpy/__pycache__/enum_util.cpython-310.pyc,, +contourpy/__pycache__/typecheck.cpython-310.pyc,, +contourpy/__pycache__/types.cpython-310.pyc,, +contourpy/_contourpy.cpython-310-x86_64-linux-gnu.so,sha256=H8GWcYv0tePHkvGU0HhmBO_d_Chj3Bs_6QYgLRKjIMI,854312 +contourpy/_contourpy.pyi,sha256=fvtccxkiZwGb6qYag7Fp4E8bsFmAIjAmobf8LNxqfgc,7122 +contourpy/_version.py,sha256=-ypEJktJToAL9by62JJKWEzDo_KPCQtmE5kwFgX24z4,22 +contourpy/array.py,sha256=4WwLuiZe30rizn_raymmY13OzE6hlCsDOO8kuVFOP18,8979 +contourpy/chunk.py,sha256=8njDQqlpuD22RjaaCyA75FXQsSQDY5hZGJSrxFpvGGU,3279 +contourpy/convert.py,sha256=mhyn7prEoWCnf0igaH-VqDwlk-CegFsZ4qOy2LL-hpU,26154 +contourpy/dechunk.py,sha256=EgFL6hw5H54ccuof4tJ2ehdnktT7trgZjiZqppsH8QI,7756 +contourpy/enum_util.py,sha256=o8MItJRs08oqzwPP3IwC75BBAY9Qq95saIzjkXBXwqA,1519 +contourpy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +contourpy/typecheck.py,sha256=t1nvvCuKMYva1Zx4fc30EpdKFcO0Enz3n_UFfXBsq9o,10747 +contourpy/types.py,sha256=2K4T5tJpMIjYrkkg1Lqh3C2ZKlnOhnMtYmtwz92l_y8,247 +contourpy/util/__init__.py,sha256=eVhJ_crOHL7nkG4Kb0dOo7NL4WHMy_Px665aAN_3d-8,118 +contourpy/util/__pycache__/__init__.cpython-310.pyc,, +contourpy/util/__pycache__/_build_config.cpython-310.pyc,, +contourpy/util/__pycache__/bokeh_renderer.cpython-310.pyc,, +contourpy/util/__pycache__/bokeh_util.cpython-310.pyc,, +contourpy/util/__pycache__/data.cpython-310.pyc,, +contourpy/util/__pycache__/mpl_renderer.cpython-310.pyc,, +contourpy/util/__pycache__/mpl_util.cpython-310.pyc,, +contourpy/util/__pycache__/renderer.cpython-310.pyc,, +contourpy/util/_build_config.py,sha256=jzJKkuBQpyjnX1U_eltbhIAN_i6fbzTAQXMAP1YTlG0,1848 +contourpy/util/bokeh_renderer.py,sha256=wNGBghEVA4x11wrSerb3dBbdRxX6E8kuoqlaKPoHTQ8,13769 +contourpy/util/bokeh_util.py,sha256=wc-S3ewBUYWyIkEv9jkhFySIergjLQl4Z0UEVnE0HhA,2804 +contourpy/util/data.py,sha256=-7SSGMLX_gN-1H2JzpNSEB_EcEF_uMtYdOo_ePRIcg8,2586 +contourpy/util/mpl_renderer.py,sha256=avUxO7_MQRDQM84X5PZ9GbNtGxG0EXPSVQYV00xQMvQ,20089 +contourpy/util/mpl_util.py,sha256=0Jz5f-aA9XMWlpO2pDnHbkVgxIiw4SY_ysxf_gACWEo,3452 +contourpy/util/renderer.py,sha256=8CBHzPmVsFPfqsWxqrxGBhqFpJhVeFHFeDzVXAgT8Fc,5118 diff --git a/moondream/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/REQUESTED b/moondream/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/moondream/lib/python3.10/site-packages/matplotlib/_cm_multivar.py b/moondream/lib/python3.10/site-packages/matplotlib/_cm_multivar.py new file mode 100644 index 0000000000000000000000000000000000000000..610d7c40935b0999fe7de38515f316ce816023f7 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/_cm_multivar.py @@ -0,0 +1,166 @@ +# auto-generated by https://github.com/trygvrad/multivariate_colormaps +# date: 2024-05-28 + +from .colors import LinearSegmentedColormap, MultivarColormap +import matplotlib as mpl +_LUTSIZE = mpl.rcParams['image.lut'] + +_2VarAddA0_data = [[0.000, 0.000, 0.000], + [0.020, 0.026, 0.031], + [0.049, 0.068, 0.085], + [0.075, 0.107, 0.135], + [0.097, 0.144, 0.183], + [0.116, 0.178, 0.231], + [0.133, 0.212, 0.279], + [0.148, 0.244, 0.326], + [0.161, 0.276, 0.374], + [0.173, 0.308, 0.422], + [0.182, 0.339, 0.471], + [0.190, 0.370, 0.521], + [0.197, 0.400, 0.572], + [0.201, 0.431, 0.623], + [0.204, 0.461, 0.675], + [0.204, 0.491, 0.728], + [0.202, 0.520, 0.783], + [0.197, 0.549, 0.838], + [0.187, 0.577, 0.895]] + +_2VarAddA1_data = [[0.000, 0.000, 0.000], + [0.030, 0.023, 0.018], + [0.079, 0.060, 0.043], + [0.125, 0.093, 0.065], + [0.170, 0.123, 0.083], + [0.213, 0.151, 0.098], + [0.255, 0.177, 0.110], + [0.298, 0.202, 0.120], + [0.341, 0.226, 0.128], + [0.384, 0.249, 0.134], + [0.427, 0.271, 0.138], + [0.472, 0.292, 0.141], + [0.517, 0.313, 0.142], + [0.563, 0.333, 0.141], + [0.610, 0.353, 0.139], + [0.658, 0.372, 0.134], + [0.708, 0.390, 0.127], + [0.759, 0.407, 0.118], + [0.813, 0.423, 0.105]] + +_2VarSubA0_data = [[1.000, 1.000, 1.000], + [0.959, 0.973, 0.986], + [0.916, 0.948, 0.974], + [0.874, 0.923, 0.965], + [0.832, 0.899, 0.956], + [0.790, 0.875, 0.948], + [0.748, 0.852, 0.940], + [0.707, 0.829, 0.934], + [0.665, 0.806, 0.927], + [0.624, 0.784, 0.921], + [0.583, 0.762, 0.916], + [0.541, 0.740, 0.910], + [0.500, 0.718, 0.905], + [0.457, 0.697, 0.901], + [0.414, 0.675, 0.896], + [0.369, 0.652, 0.892], + [0.320, 0.629, 0.888], + [0.266, 0.604, 0.884], + [0.199, 0.574, 0.881]] + +_2VarSubA1_data = [[1.000, 1.000, 1.000], + [0.982, 0.967, 0.955], + [0.966, 0.935, 0.908], + [0.951, 0.902, 0.860], + [0.937, 0.870, 0.813], + [0.923, 0.838, 0.765], + [0.910, 0.807, 0.718], + [0.898, 0.776, 0.671], + [0.886, 0.745, 0.624], + [0.874, 0.714, 0.577], + [0.862, 0.683, 0.530], + [0.851, 0.653, 0.483], + [0.841, 0.622, 0.435], + [0.831, 0.592, 0.388], + [0.822, 0.561, 0.340], + [0.813, 0.530, 0.290], + [0.806, 0.498, 0.239], + [0.802, 0.464, 0.184], + [0.801, 0.426, 0.119]] + +_3VarAddA0_data = [[0.000, 0.000, 0.000], + [0.018, 0.023, 0.028], + [0.040, 0.056, 0.071], + [0.059, 0.087, 0.110], + [0.074, 0.114, 0.147], + [0.086, 0.139, 0.183], + [0.095, 0.163, 0.219], + [0.101, 0.187, 0.255], + [0.105, 0.209, 0.290], + [0.107, 0.230, 0.326], + [0.105, 0.251, 0.362], + [0.101, 0.271, 0.398], + [0.091, 0.291, 0.434], + [0.075, 0.309, 0.471], + [0.046, 0.325, 0.507], + [0.021, 0.341, 0.546], + [0.021, 0.363, 0.584], + [0.022, 0.385, 0.622], + [0.023, 0.408, 0.661]] + +_3VarAddA1_data = [[0.000, 0.000, 0.000], + [0.020, 0.024, 0.016], + [0.047, 0.058, 0.034], + [0.072, 0.088, 0.048], + [0.093, 0.116, 0.059], + [0.113, 0.142, 0.067], + [0.131, 0.167, 0.071], + [0.149, 0.190, 0.074], + [0.166, 0.213, 0.074], + [0.182, 0.235, 0.072], + [0.198, 0.256, 0.068], + [0.215, 0.276, 0.061], + [0.232, 0.296, 0.051], + [0.249, 0.314, 0.037], + [0.270, 0.330, 0.018], + [0.288, 0.347, 0.000], + [0.302, 0.369, 0.000], + [0.315, 0.391, 0.000], + [0.328, 0.414, 0.000]] + +_3VarAddA2_data = [[0.000, 0.000, 0.000], + [0.029, 0.020, 0.023], + [0.072, 0.045, 0.055], + [0.111, 0.067, 0.084], + [0.148, 0.085, 0.109], + [0.184, 0.101, 0.133], + [0.219, 0.115, 0.155], + [0.254, 0.127, 0.176], + [0.289, 0.138, 0.195], + [0.323, 0.147, 0.214], + [0.358, 0.155, 0.232], + [0.393, 0.161, 0.250], + [0.429, 0.166, 0.267], + [0.467, 0.169, 0.283], + [0.507, 0.168, 0.298], + [0.546, 0.168, 0.313], + [0.580, 0.172, 0.328], + [0.615, 0.175, 0.341], + [0.649, 0.178, 0.355]] + +cmaps = { + name: LinearSegmentedColormap.from_list(name, data, _LUTSIZE) for name, data in [ + ('2VarAddA0', _2VarAddA0_data), + ('2VarAddA1', _2VarAddA1_data), + ('2VarSubA0', _2VarSubA0_data), + ('2VarSubA1', _2VarSubA1_data), + ('3VarAddA0', _3VarAddA0_data), + ('3VarAddA1', _3VarAddA1_data), + ('3VarAddA2', _3VarAddA2_data), + ]} + +cmap_families = { + '2VarAddA': MultivarColormap([cmaps[f'2VarAddA{i}'] for i in range(2)], + 'sRGB_add', name='2VarAddA'), + '2VarSubA': MultivarColormap([cmaps[f'2VarSubA{i}'] for i in range(2)], + 'sRGB_sub', name='2VarSubA'), + '3VarAddA': MultivarColormap([cmaps[f'3VarAddA{i}'] for i in range(3)], + 'sRGB_add', name='3VarAddA'), +} diff --git a/moondream/lib/python3.10/site-packages/matplotlib/_internal_utils.py b/moondream/lib/python3.10/site-packages/matplotlib/_internal_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0223aa593bb2cb20b58f2b9e41bdc0dfa5ceed35 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/_internal_utils.py @@ -0,0 +1,64 @@ +""" +Internal debugging utilities, that are not expected to be used in the rest of +the codebase. + +WARNING: Code in this module may change without prior notice! +""" + +from io import StringIO +from pathlib import Path +import subprocess + +from matplotlib.transforms import TransformNode + + +def graphviz_dump_transform(transform, dest, *, highlight=None): + """ + Generate a graphical representation of the transform tree for *transform* + using the :program:`dot` program (which this function depends on). The + output format (png, dot, etc.) is determined from the suffix of *dest*. + + Parameters + ---------- + transform : `~matplotlib.transform.Transform` + The represented transform. + dest : str + Output filename. The extension must be one of the formats supported + by :program:`dot`, e.g. png, svg, dot, ... + (see https://www.graphviz.org/doc/info/output.html). + highlight : list of `~matplotlib.transform.Transform` or None + The transforms in the tree to be drawn in bold. + If *None*, *transform* is highlighted. + """ + + if highlight is None: + highlight = [transform] + seen = set() + + def recurse(root, buf): + if id(root) in seen: + return + seen.add(id(root)) + props = {} + label = type(root).__name__ + if root._invalid: + label = f'[{label}]' + if root in highlight: + props['style'] = 'bold' + props['shape'] = 'box' + props['label'] = '"%s"' % label + props = ' '.join(map('{0[0]}={0[1]}'.format, props.items())) + buf.write(f'{id(root)} [{props}];\n') + for key, val in vars(root).items(): + if isinstance(val, TransformNode) and id(root) in val._parents: + buf.write(f'"{id(root)}" -> "{id(val)}" ' + f'[label="{key}", fontsize=10];\n') + recurse(val, buf) + + buf = StringIO() + buf.write('digraph G {\n') + recurse(transform, buf) + buf.write('}\n') + subprocess.run( + ['dot', '-T', Path(dest).suffix[1:], '-o', dest], + input=buf.getvalue().encode('utf-8'), check=True) diff --git a/moondream/lib/python3.10/site-packages/matplotlib/_layoutgrid.py b/moondream/lib/python3.10/site-packages/matplotlib/_layoutgrid.py new file mode 100644 index 0000000000000000000000000000000000000000..8f81b14765b68fa1f7480c3d34ba74245e39b84f --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/_layoutgrid.py @@ -0,0 +1,547 @@ +""" +A layoutgrid is a nrows by ncols set of boxes, meant to be used by +`._constrained_layout`, each box is analogous to a subplotspec element of +a gridspec. + +Each box is defined by left[ncols], right[ncols], bottom[nrows] and top[nrows], +and by two editable margins for each side. The main margin gets its value +set by the size of ticklabels, titles, etc on each Axes that is in the figure. +The outer margin is the padding around the Axes, and space for any +colorbars. + +The "inner" widths and heights of these boxes are then constrained to be the +same (relative the values of `width_ratios[ncols]` and `height_ratios[nrows]`). + +The layoutgrid is then constrained to be contained within a parent layoutgrid, +its column(s) and row(s) specified when it is created. +""" + +import itertools +import kiwisolver as kiwi +import logging +import numpy as np + +import matplotlib as mpl +import matplotlib.patches as mpatches +from matplotlib.transforms import Bbox + +_log = logging.getLogger(__name__) + + +class LayoutGrid: + """ + Analogous to a gridspec, and contained in another LayoutGrid. + """ + + def __init__(self, parent=None, parent_pos=(0, 0), + parent_inner=False, name='', ncols=1, nrows=1, + h_pad=None, w_pad=None, width_ratios=None, + height_ratios=None): + Variable = kiwi.Variable + self.parent_pos = parent_pos + self.parent_inner = parent_inner + self.name = name + seq_id() + if isinstance(parent, LayoutGrid): + self.name = f'{parent.name}.{self.name}' + self.nrows = nrows + self.ncols = ncols + self.height_ratios = np.atleast_1d(height_ratios) + if height_ratios is None: + self.height_ratios = np.ones(nrows) + self.width_ratios = np.atleast_1d(width_ratios) + if width_ratios is None: + self.width_ratios = np.ones(ncols) + + sn = self.name + '_' + if not isinstance(parent, LayoutGrid): + # parent can be a rect if not a LayoutGrid + # allows specifying a rectangle to contain the layout. + self.solver = kiwi.Solver() + else: + parent.add_child(self, *parent_pos) + self.solver = parent.solver + # keep track of artist associated w/ this layout. Can be none + self.artists = np.empty((nrows, ncols), dtype=object) + self.children = np.empty((nrows, ncols), dtype=object) + + self.margins = {} + self.margin_vals = {} + # all the boxes in each column share the same left/right margins: + for todo in ['left', 'right', 'leftcb', 'rightcb']: + # track the value so we can change only if a margin is larger + # than the current value + self.margin_vals[todo] = np.zeros(ncols) + + sol = self.solver + + self.lefts = [Variable(f'{sn}lefts[{i}]') for i in range(ncols)] + self.rights = [Variable(f'{sn}rights[{i}]') for i in range(ncols)] + for todo in ['left', 'right', 'leftcb', 'rightcb']: + self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]') + for i in range(ncols)] + for i in range(ncols): + sol.addEditVariable(self.margins[todo][i], 'strong') + + for todo in ['bottom', 'top', 'bottomcb', 'topcb']: + self.margins[todo] = np.empty((nrows), dtype=object) + self.margin_vals[todo] = np.zeros(nrows) + + self.bottoms = [Variable(f'{sn}bottoms[{i}]') for i in range(nrows)] + self.tops = [Variable(f'{sn}tops[{i}]') for i in range(nrows)] + for todo in ['bottom', 'top', 'bottomcb', 'topcb']: + self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]') + for i in range(nrows)] + for i in range(nrows): + sol.addEditVariable(self.margins[todo][i], 'strong') + + # set these margins to zero by default. They will be edited as + # children are filled. + self.reset_margins() + self.add_constraints(parent) + + self.h_pad = h_pad + self.w_pad = w_pad + + def __repr__(self): + str = f'LayoutBox: {self.name:25s} {self.nrows}x{self.ncols},\n' + for i in range(self.nrows): + for j in range(self.ncols): + str += f'{i}, {j}: '\ + f'L{self.lefts[j].value():1.3f}, ' \ + f'B{self.bottoms[i].value():1.3f}, ' \ + f'R{self.rights[j].value():1.3f}, ' \ + f'T{self.tops[i].value():1.3f}, ' \ + f'ML{self.margins["left"][j].value():1.3f}, ' \ + f'MR{self.margins["right"][j].value():1.3f}, ' \ + f'MB{self.margins["bottom"][i].value():1.3f}, ' \ + f'MT{self.margins["top"][i].value():1.3f}, \n' + return str + + def reset_margins(self): + """ + Reset all the margins to zero. Must do this after changing + figure size, for instance, because the relative size of the + axes labels etc changes. + """ + for todo in ['left', 'right', 'bottom', 'top', + 'leftcb', 'rightcb', 'bottomcb', 'topcb']: + self.edit_margins(todo, 0.0) + + def add_constraints(self, parent): + # define self-consistent constraints + self.hard_constraints() + # define relationship with parent layoutgrid: + self.parent_constraints(parent) + # define relative widths of the grid cells to each other + # and stack horizontally and vertically. + self.grid_constraints() + + def hard_constraints(self): + """ + These are the redundant constraints, plus ones that make the + rest of the code easier. + """ + for i in range(self.ncols): + hc = [self.rights[i] >= self.lefts[i], + (self.rights[i] - self.margins['right'][i] - + self.margins['rightcb'][i] >= + self.lefts[i] - self.margins['left'][i] - + self.margins['leftcb'][i]) + ] + for c in hc: + self.solver.addConstraint(c | 'required') + + for i in range(self.nrows): + hc = [self.tops[i] >= self.bottoms[i], + (self.tops[i] - self.margins['top'][i] - + self.margins['topcb'][i] >= + self.bottoms[i] - self.margins['bottom'][i] - + self.margins['bottomcb'][i]) + ] + for c in hc: + self.solver.addConstraint(c | 'required') + + def add_child(self, child, i=0, j=0): + # np.ix_ returns the cross product of i and j indices + self.children[np.ix_(np.atleast_1d(i), np.atleast_1d(j))] = child + + def parent_constraints(self, parent): + # constraints that are due to the parent... + # i.e. the first column's left is equal to the + # parent's left, the last column right equal to the + # parent's right... + if not isinstance(parent, LayoutGrid): + # specify a rectangle in figure coordinates + hc = [self.lefts[0] == parent[0], + self.rights[-1] == parent[0] + parent[2], + # top and bottom reversed order... + self.tops[0] == parent[1] + parent[3], + self.bottoms[-1] == parent[1]] + else: + rows, cols = self.parent_pos + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + left = parent.lefts[cols[0]] + right = parent.rights[cols[-1]] + top = parent.tops[rows[0]] + bottom = parent.bottoms[rows[-1]] + if self.parent_inner: + # the layout grid is contained inside the inner + # grid of the parent. + left += parent.margins['left'][cols[0]] + left += parent.margins['leftcb'][cols[0]] + right -= parent.margins['right'][cols[-1]] + right -= parent.margins['rightcb'][cols[-1]] + top -= parent.margins['top'][rows[0]] + top -= parent.margins['topcb'][rows[0]] + bottom += parent.margins['bottom'][rows[-1]] + bottom += parent.margins['bottomcb'][rows[-1]] + hc = [self.lefts[0] == left, + self.rights[-1] == right, + # from top to bottom + self.tops[0] == top, + self.bottoms[-1] == bottom] + for c in hc: + self.solver.addConstraint(c | 'required') + + def grid_constraints(self): + # constrain the ratio of the inner part of the grids + # to be the same (relative to width_ratios) + + # constrain widths: + w = (self.rights[0] - self.margins['right'][0] - + self.margins['rightcb'][0]) + w = (w - self.lefts[0] - self.margins['left'][0] - + self.margins['leftcb'][0]) + w0 = w / self.width_ratios[0] + # from left to right + for i in range(1, self.ncols): + w = (self.rights[i] - self.margins['right'][i] - + self.margins['rightcb'][i]) + w = (w - self.lefts[i] - self.margins['left'][i] - + self.margins['leftcb'][i]) + c = (w == w0 * self.width_ratios[i]) + self.solver.addConstraint(c | 'strong') + # constrain the grid cells to be directly next to each other. + c = (self.rights[i - 1] == self.lefts[i]) + self.solver.addConstraint(c | 'strong') + + # constrain heights: + h = self.tops[0] - self.margins['top'][0] - self.margins['topcb'][0] + h = (h - self.bottoms[0] - self.margins['bottom'][0] - + self.margins['bottomcb'][0]) + h0 = h / self.height_ratios[0] + # from top to bottom: + for i in range(1, self.nrows): + h = (self.tops[i] - self.margins['top'][i] - + self.margins['topcb'][i]) + h = (h - self.bottoms[i] - self.margins['bottom'][i] - + self.margins['bottomcb'][i]) + c = (h == h0 * self.height_ratios[i]) + self.solver.addConstraint(c | 'strong') + # constrain the grid cells to be directly above each other. + c = (self.bottoms[i - 1] == self.tops[i]) + self.solver.addConstraint(c | 'strong') + + # Margin editing: The margins are variable and meant to + # contain things of a fixed size like axes labels, tick labels, titles + # etc + def edit_margin(self, todo, size, cell): + """ + Change the size of the margin for one cell. + + Parameters + ---------- + todo : string (one of 'left', 'right', 'bottom', 'top') + margin to alter. + + size : float + Size of the margin. If it is larger than the existing minimum it + updates the margin size. Fraction of figure size. + + cell : int + Cell column or row to edit. + """ + self.solver.suggestValue(self.margins[todo][cell], size) + self.margin_vals[todo][cell] = size + + def edit_margin_min(self, todo, size, cell=0): + """ + Change the minimum size of the margin for one cell. + + Parameters + ---------- + todo : string (one of 'left', 'right', 'bottom', 'top') + margin to alter. + + size : float + Minimum size of the margin . If it is larger than the + existing minimum it updates the margin size. Fraction of + figure size. + + cell : int + Cell column or row to edit. + """ + + if size > self.margin_vals[todo][cell]: + self.edit_margin(todo, size, cell) + + def edit_margins(self, todo, size): + """ + Change the size of all the margin of all the cells in the layout grid. + + Parameters + ---------- + todo : string (one of 'left', 'right', 'bottom', 'top') + margin to alter. + + size : float + Size to set the margins. Fraction of figure size. + """ + + for i in range(len(self.margin_vals[todo])): + self.edit_margin(todo, size, i) + + def edit_all_margins_min(self, todo, size): + """ + Change the minimum size of all the margin of all + the cells in the layout grid. + + Parameters + ---------- + todo : {'left', 'right', 'bottom', 'top'} + The margin to alter. + + size : float + Minimum size of the margin. If it is larger than the + existing minimum it updates the margin size. Fraction of + figure size. + """ + + for i in range(len(self.margin_vals[todo])): + self.edit_margin_min(todo, size, i) + + def edit_outer_margin_mins(self, margin, ss): + """ + Edit all four margin minimums in one statement. + + Parameters + ---------- + margin : dict + size of margins in a dict with keys 'left', 'right', 'bottom', + 'top' + + ss : SubplotSpec + defines the subplotspec these margins should be applied to + """ + + self.edit_margin_min('left', margin['left'], ss.colspan.start) + self.edit_margin_min('leftcb', margin['leftcb'], ss.colspan.start) + self.edit_margin_min('right', margin['right'], ss.colspan.stop - 1) + self.edit_margin_min('rightcb', margin['rightcb'], ss.colspan.stop - 1) + # rows are from the top down: + self.edit_margin_min('top', margin['top'], ss.rowspan.start) + self.edit_margin_min('topcb', margin['topcb'], ss.rowspan.start) + self.edit_margin_min('bottom', margin['bottom'], ss.rowspan.stop - 1) + self.edit_margin_min('bottomcb', margin['bottomcb'], + ss.rowspan.stop - 1) + + def get_margins(self, todo, col): + """Return the margin at this position""" + return self.margin_vals[todo][col] + + def get_outer_bbox(self, rows=0, cols=0): + """ + Return the outer bounding box of the subplot specs + given by rows and cols. rows and cols can be spans. + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + self.lefts[cols[0]].value(), + self.bottoms[rows[-1]].value(), + self.rights[cols[-1]].value(), + self.tops[rows[0]].value()) + return bbox + + def get_inner_bbox(self, rows=0, cols=0): + """ + Return the inner bounding box of the subplot specs + given by rows and cols. rows and cols can be spans. + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + (self.lefts[cols[0]].value() + + self.margins['left'][cols[0]].value() + + self.margins['leftcb'][cols[0]].value()), + (self.bottoms[rows[-1]].value() + + self.margins['bottom'][rows[-1]].value() + + self.margins['bottomcb'][rows[-1]].value()), + (self.rights[cols[-1]].value() - + self.margins['right'][cols[-1]].value() - + self.margins['rightcb'][cols[-1]].value()), + (self.tops[rows[0]].value() - + self.margins['top'][rows[0]].value() - + self.margins['topcb'][rows[0]].value()) + ) + return bbox + + def get_bbox_for_cb(self, rows=0, cols=0): + """ + Return the bounding box that includes the + decorations but, *not* the colorbar... + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + (self.lefts[cols[0]].value() + + self.margins['leftcb'][cols[0]].value()), + (self.bottoms[rows[-1]].value() + + self.margins['bottomcb'][rows[-1]].value()), + (self.rights[cols[-1]].value() - + self.margins['rightcb'][cols[-1]].value()), + (self.tops[rows[0]].value() - + self.margins['topcb'][rows[0]].value()) + ) + return bbox + + def get_left_margin_bbox(self, rows=0, cols=0): + """ + Return the left margin bounding box of the subplot specs + given by rows and cols. rows and cols can be spans. + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + (self.lefts[cols[0]].value() + + self.margins['leftcb'][cols[0]].value()), + (self.bottoms[rows[-1]].value()), + (self.lefts[cols[0]].value() + + self.margins['leftcb'][cols[0]].value() + + self.margins['left'][cols[0]].value()), + (self.tops[rows[0]].value())) + return bbox + + def get_bottom_margin_bbox(self, rows=0, cols=0): + """ + Return the left margin bounding box of the subplot specs + given by rows and cols. rows and cols can be spans. + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + (self.lefts[cols[0]].value()), + (self.bottoms[rows[-1]].value() + + self.margins['bottomcb'][rows[-1]].value()), + (self.rights[cols[-1]].value()), + (self.bottoms[rows[-1]].value() + + self.margins['bottom'][rows[-1]].value() + + self.margins['bottomcb'][rows[-1]].value() + )) + return bbox + + def get_right_margin_bbox(self, rows=0, cols=0): + """ + Return the left margin bounding box of the subplot specs + given by rows and cols. rows and cols can be spans. + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + (self.rights[cols[-1]].value() - + self.margins['right'][cols[-1]].value() - + self.margins['rightcb'][cols[-1]].value()), + (self.bottoms[rows[-1]].value()), + (self.rights[cols[-1]].value() - + self.margins['rightcb'][cols[-1]].value()), + (self.tops[rows[0]].value())) + return bbox + + def get_top_margin_bbox(self, rows=0, cols=0): + """ + Return the left margin bounding box of the subplot specs + given by rows and cols. rows and cols can be spans. + """ + rows = np.atleast_1d(rows) + cols = np.atleast_1d(cols) + + bbox = Bbox.from_extents( + (self.lefts[cols[0]].value()), + (self.tops[rows[0]].value() - + self.margins['topcb'][rows[0]].value()), + (self.rights[cols[-1]].value()), + (self.tops[rows[0]].value() - + self.margins['topcb'][rows[0]].value() - + self.margins['top'][rows[0]].value())) + return bbox + + def update_variables(self): + """ + Update the variables for the solver attached to this layoutgrid. + """ + self.solver.updateVariables() + +_layoutboxobjnum = itertools.count() + + +def seq_id(): + """Generate a short sequential id for layoutbox objects.""" + return '%06d' % next(_layoutboxobjnum) + + +def plot_children(fig, lg=None, level=0): + """Simple plotting to show where boxes are.""" + if lg is None: + _layoutgrids = fig.get_layout_engine().execute(fig) + lg = _layoutgrids[fig] + colors = mpl.rcParams["axes.prop_cycle"].by_key()["color"] + col = colors[level] + for i in range(lg.nrows): + for j in range(lg.ncols): + bb = lg.get_outer_bbox(rows=i, cols=j) + fig.add_artist( + mpatches.Rectangle(bb.p0, bb.width, bb.height, linewidth=1, + edgecolor='0.7', facecolor='0.7', + alpha=0.2, transform=fig.transFigure, + zorder=-3)) + bbi = lg.get_inner_bbox(rows=i, cols=j) + fig.add_artist( + mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=2, + edgecolor=col, facecolor='none', + transform=fig.transFigure, zorder=-2)) + + bbi = lg.get_left_margin_bbox(rows=i, cols=j) + fig.add_artist( + mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0, + edgecolor='none', alpha=0.2, + facecolor=[0.5, 0.7, 0.5], + transform=fig.transFigure, zorder=-2)) + bbi = lg.get_right_margin_bbox(rows=i, cols=j) + fig.add_artist( + mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0, + edgecolor='none', alpha=0.2, + facecolor=[0.7, 0.5, 0.5], + transform=fig.transFigure, zorder=-2)) + bbi = lg.get_bottom_margin_bbox(rows=i, cols=j) + fig.add_artist( + mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0, + edgecolor='none', alpha=0.2, + facecolor=[0.5, 0.5, 0.7], + transform=fig.transFigure, zorder=-2)) + bbi = lg.get_top_margin_bbox(rows=i, cols=j) + fig.add_artist( + mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0, + edgecolor='none', alpha=0.2, + facecolor=[0.7, 0.2, 0.7], + transform=fig.transFigure, zorder=-2)) + for ch in lg.children.flat: + if ch is not None: + plot_children(fig, ch, level=level+1) diff --git a/moondream/lib/python3.10/site-packages/matplotlib/_text_helpers.py b/moondream/lib/python3.10/site-packages/matplotlib/_text_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..b9603b114bc245ecf32da926573ddb4157210c7a --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/_text_helpers.py @@ -0,0 +1,82 @@ +""" +Low-level text helper utilities. +""" + +from __future__ import annotations + +import dataclasses + +from . import _api +from .ft2font import FT2Font, Kerning, LoadFlags + + +@dataclasses.dataclass(frozen=True) +class LayoutItem: + ft_object: FT2Font + char: str + glyph_idx: int + x: float + prev_kern: float + + +def warn_on_missing_glyph(codepoint, fontnames): + _api.warn_external( + f"Glyph {codepoint} " + f"({chr(codepoint).encode('ascii', 'namereplace').decode('ascii')}) " + f"missing from font(s) {fontnames}.") + + block = ("Hebrew" if 0x0590 <= codepoint <= 0x05ff else + "Arabic" if 0x0600 <= codepoint <= 0x06ff else + "Devanagari" if 0x0900 <= codepoint <= 0x097f else + "Bengali" if 0x0980 <= codepoint <= 0x09ff else + "Gurmukhi" if 0x0a00 <= codepoint <= 0x0a7f else + "Gujarati" if 0x0a80 <= codepoint <= 0x0aff else + "Oriya" if 0x0b00 <= codepoint <= 0x0b7f else + "Tamil" if 0x0b80 <= codepoint <= 0x0bff else + "Telugu" if 0x0c00 <= codepoint <= 0x0c7f else + "Kannada" if 0x0c80 <= codepoint <= 0x0cff else + "Malayalam" if 0x0d00 <= codepoint <= 0x0d7f else + "Sinhala" if 0x0d80 <= codepoint <= 0x0dff else + None) + if block: + _api.warn_external( + f"Matplotlib currently does not support {block} natively.") + + +def layout(string, font, *, kern_mode=Kerning.DEFAULT): + """ + Render *string* with *font*. + + For each character in *string*, yield a LayoutItem instance. When such an instance + is yielded, the font's glyph is set to the corresponding character. + + Parameters + ---------- + string : str + The string to be rendered. + font : FT2Font + The font. + kern_mode : Kerning + A FreeType kerning mode. + + Yields + ------ + LayoutItem + """ + x = 0 + prev_glyph_idx = None + char_to_font = font._get_fontmap(string) + base_font = font + for char in string: + # This has done the fallback logic + font = char_to_font.get(char, base_font) + glyph_idx = font.get_char_index(ord(char)) + kern = ( + base_font.get_kerning(prev_glyph_idx, glyph_idx, kern_mode) / 64 + if prev_glyph_idx is not None else 0. + ) + x += kern + glyph = font.load_glyph(glyph_idx, flags=LoadFlags.NO_HINTING) + yield LayoutItem(font, char, glyph_idx, x, kern) + x += glyph.linearHoriAdvance / 65536 + prev_glyph_idx = glyph_idx diff --git a/moondream/lib/python3.10/site-packages/matplotlib/artist.pyi b/moondream/lib/python3.10/site-packages/matplotlib/artist.pyi new file mode 100644 index 0000000000000000000000000000000000000000..be23f69d44a6df19fef57131eadede93bf4875bc --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/artist.pyi @@ -0,0 +1,199 @@ +from .axes._base import _AxesBase +from .backend_bases import RendererBase, MouseEvent +from .figure import Figure, SubFigure +from .path import Path +from .patches import Patch +from .patheffects import AbstractPathEffect +from .transforms import ( + BboxBase, + Bbox, + Transform, + TransformedPatchPath, + TransformedPath, +) + +import numpy as np + +from collections.abc import Callable, Iterable +from typing import Any, Literal, NamedTuple, TextIO, overload, TypeVar +from numpy.typing import ArrayLike + +_T_Artist = TypeVar("_T_Artist", bound=Artist) + +def allow_rasterization(draw): ... + +class _XYPair(NamedTuple): + x: ArrayLike + y: ArrayLike + +class _Unset: ... + +class Artist: + zorder: float + stale_callback: Callable[[Artist, bool], None] | None + @property + def figure(self) -> Figure | SubFigure: ... + clipbox: BboxBase | None + def __init__(self) -> None: ... + def remove(self) -> None: ... + def have_units(self) -> bool: ... + # TODO units + def convert_xunits(self, x): ... + def convert_yunits(self, y): ... + @property + def axes(self) -> _AxesBase | None: ... + @axes.setter + def axes(self, new_axes: _AxesBase | None) -> None: ... + @property + def stale(self) -> bool: ... + @stale.setter + def stale(self, val: bool) -> None: ... + def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ... + def get_tightbbox(self, renderer: RendererBase | None = ...) -> Bbox | None: ... + def add_callback(self, func: Callable[[Artist], Any]) -> int: ... + def remove_callback(self, oid: int) -> None: ... + def pchanged(self) -> None: ... + def is_transform_set(self) -> bool: ... + def set_transform(self, t: Transform | None) -> None: ... + def get_transform(self) -> Transform: ... + def get_children(self) -> list[Artist]: ... + # TODO can these dicts be type narrowed? e.g. str keys + def contains(self, mouseevent: MouseEvent) -> tuple[bool, dict[Any, Any]]: ... + def pickable(self) -> bool: ... + def pick(self, mouseevent: MouseEvent) -> None: ... + def set_picker( + self, + picker: None + | bool + | float + | Callable[[Artist, MouseEvent], tuple[bool, dict[Any, Any]]], + ) -> None: ... + def get_picker( + self, + ) -> None | bool | float | Callable[ + [Artist, MouseEvent], tuple[bool, dict[Any, Any]] + ]: ... + def get_url(self) -> str | None: ... + def set_url(self, url: str | None) -> None: ... + def get_gid(self) -> str | None: ... + def set_gid(self, gid: str | None) -> None: ... + def get_snap(self) -> bool | None: ... + def set_snap(self, snap: bool | None) -> None: ... + def get_sketch_params(self) -> tuple[float, float, float] | None: ... + def set_sketch_params( + self, + scale: float | None = ..., + length: float | None = ..., + randomness: float | None = ..., + ) -> None: ... + def set_path_effects(self, path_effects: list[AbstractPathEffect]) -> None: ... + def get_path_effects(self) -> list[AbstractPathEffect]: ... + @overload + def get_figure(self, root: Literal[True]) -> Figure | None: ... + @overload + def get_figure(self, root: Literal[False]) -> Figure | SubFigure | None: ... + @overload + def get_figure(self, root: bool = ...) -> Figure | SubFigure | None: ... + def set_figure(self, fig: Figure | SubFigure) -> None: ... + def set_clip_box(self, clipbox: BboxBase | None) -> None: ... + def set_clip_path( + self, + path: Patch | Path | TransformedPath | TransformedPatchPath | None, + transform: Transform | None = ..., + ) -> None: ... + def get_alpha(self) -> float | None: ... + def get_visible(self) -> bool: ... + def get_animated(self) -> bool: ... + def get_in_layout(self) -> bool: ... + def get_clip_on(self) -> bool: ... + def get_clip_box(self) -> Bbox | None: ... + def get_clip_path( + self, + ) -> Patch | Path | TransformedPath | TransformedPatchPath | None: ... + def get_transformed_clip_path_and_affine( + self, + ) -> tuple[None, None] | tuple[Path, Transform]: ... + def set_clip_on(self, b: bool) -> None: ... + def get_rasterized(self) -> bool: ... + def set_rasterized(self, rasterized: bool) -> None: ... + def get_agg_filter(self) -> Callable[[ArrayLike, float], tuple[np.ndarray, float, float]] | None: ... + def set_agg_filter( + self, filter_func: Callable[[ArrayLike, float], tuple[np.ndarray, float, float]] | None + ) -> None: ... + def draw(self, renderer: RendererBase) -> None: ... + def set_alpha(self, alpha: float | None) -> None: ... + def set_visible(self, b: bool) -> None: ... + def set_animated(self, b: bool) -> None: ... + def set_in_layout(self, in_layout: bool) -> None: ... + def get_label(self) -> object: ... + def set_label(self, s: object) -> None: ... + def get_zorder(self) -> float: ... + def set_zorder(self, level: float) -> None: ... + @property + def sticky_edges(self) -> _XYPair: ... + def update_from(self, other: Artist) -> None: ... + def properties(self) -> dict[str, Any]: ... + def update(self, props: dict[str, Any]) -> list[Any]: ... + def _internal_update(self, kwargs: Any) -> list[Any]: ... + def set(self, **kwargs: Any) -> list[Any]: ... + + @overload + def findobj( + self, + match: None | Callable[[Artist], bool] = ..., + include_self: bool = ..., + ) -> list[Artist]: ... + + @overload + def findobj( + self, + match: type[_T_Artist], + include_self: bool = ..., + ) -> list[_T_Artist]: ... + + def get_cursor_data(self, event: MouseEvent) -> Any: ... + def format_cursor_data(self, data: Any) -> str: ... + def get_mouseover(self) -> bool: ... + def set_mouseover(self, mouseover: bool) -> None: ... + @property + def mouseover(self) -> bool: ... + @mouseover.setter + def mouseover(self, mouseover: bool) -> None: ... + +class ArtistInspector: + oorig: Artist | type[Artist] + o: type[Artist] + aliasd: dict[str, set[str]] + def __init__( + self, o: Artist | type[Artist] | Iterable[Artist | type[Artist]] + ) -> None: ... + def get_aliases(self) -> dict[str, set[str]]: ... + def get_valid_values(self, attr: str) -> str | None: ... + def get_setters(self) -> list[str]: ... + @staticmethod + def number_of_parameters(func: Callable) -> int: ... + @staticmethod + def is_alias(method: Callable) -> bool: ... + def aliased_name(self, s: str) -> str: ... + def aliased_name_rest(self, s: str, target: str) -> str: ... + @overload + def pprint_setters( + self, prop: None = ..., leadingspace: int = ... + ) -> list[str]: ... + @overload + def pprint_setters(self, prop: str, leadingspace: int = ...) -> str: ... + @overload + def pprint_setters_rest( + self, prop: None = ..., leadingspace: int = ... + ) -> list[str]: ... + @overload + def pprint_setters_rest(self, prop: str, leadingspace: int = ...) -> str: ... + def properties(self) -> dict[str, Any]: ... + def pprint_getters(self) -> list[str]: ... + +def getp(obj: Artist, property: str | None = ...) -> Any: ... + +get = getp + +def setp(obj: Artist, *args, file: TextIO | None = ..., **kwargs) -> list[Any] | None: ... +def kwdoc(artist: Artist | type[Artist] | Iterable[Artist | type[Artist]]) -> str: ... diff --git a/moondream/lib/python3.10/site-packages/matplotlib/axis.py b/moondream/lib/python3.10/site-packages/matplotlib/axis.py new file mode 100644 index 0000000000000000000000000000000000000000..56eeb0e4169b2c48a0e37fd1470d7e9e00539196 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/axis.py @@ -0,0 +1,2830 @@ +""" +Classes for the ticks and x- and y-axis. +""" + +import datetime +import functools +import logging +from numbers import Real +import warnings + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook +import matplotlib.artist as martist +import matplotlib.colors as mcolors +import matplotlib.lines as mlines +import matplotlib.scale as mscale +import matplotlib.text as mtext +import matplotlib.ticker as mticker +import matplotlib.transforms as mtransforms +import matplotlib.units as munits + +_log = logging.getLogger(__name__) + +GRIDLINE_INTERPOLATION_STEPS = 180 + +# This list is being used for compatibility with Axes.grid, which +# allows all Line2D kwargs. +_line_inspector = martist.ArtistInspector(mlines.Line2D) +_line_param_names = _line_inspector.get_setters() +_line_param_aliases = [next(iter(d)) for d in _line_inspector.aliasd.values()] +_gridline_param_names = ['grid_' + name + for name in _line_param_names + _line_param_aliases] + + +class Tick(martist.Artist): + """ + Abstract base class for the axis ticks, grid lines and labels. + + Ticks mark a position on an Axis. They contain two lines as markers and + two labels; one each for the bottom and top positions (in case of an + `.XAxis`) or for the left and right positions (in case of a `.YAxis`). + + Attributes + ---------- + tick1line : `~matplotlib.lines.Line2D` + The left/bottom tick marker. + tick2line : `~matplotlib.lines.Line2D` + The right/top tick marker. + gridline : `~matplotlib.lines.Line2D` + The grid line associated with the label position. + label1 : `~matplotlib.text.Text` + The left/bottom tick label. + label2 : `~matplotlib.text.Text` + The right/top tick label. + + """ + def __init__( + self, axes, loc, *, + size=None, # points + width=None, + color=None, + tickdir=None, + pad=None, + labelsize=None, + labelcolor=None, + labelfontfamily=None, + zorder=None, + gridOn=None, # defaults to axes.grid depending on axes.grid.which + tick1On=True, + tick2On=True, + label1On=True, + label2On=False, + major=True, + labelrotation=0, + grid_color=None, + grid_linestyle=None, + grid_linewidth=None, + grid_alpha=None, + **kwargs, # Other Line2D kwargs applied to gridlines. + ): + """ + bbox is the Bound2D bounding box in display coords of the Axes + loc is the tick location in data coords + size is the tick size in points + """ + super().__init__() + + if gridOn is None: + which = mpl.rcParams['axes.grid.which'] + if major and (which in ('both', 'major')): + gridOn = mpl.rcParams['axes.grid'] + elif (not major) and (which in ('both', 'minor')): + gridOn = mpl.rcParams['axes.grid'] + else: + gridOn = False + + self.set_figure(axes.get_figure(root=False)) + self.axes = axes + + self._loc = loc + self._major = major + + name = self.__name__ + major_minor = "major" if major else "minor" + + if size is None: + size = mpl.rcParams[f"{name}.{major_minor}.size"] + self._size = size + + if width is None: + width = mpl.rcParams[f"{name}.{major_minor}.width"] + self._width = width + + if color is None: + color = mpl.rcParams[f"{name}.color"] + + if pad is None: + pad = mpl.rcParams[f"{name}.{major_minor}.pad"] + self._base_pad = pad + + if labelcolor is None: + labelcolor = mpl.rcParams[f"{name}.labelcolor"] + + if cbook._str_equal(labelcolor, 'inherit'): + # inherit from tick color + labelcolor = mpl.rcParams[f"{name}.color"] + + if labelsize is None: + labelsize = mpl.rcParams[f"{name}.labelsize"] + + self._set_labelrotation(labelrotation) + + if zorder is None: + if major: + zorder = mlines.Line2D.zorder + 0.01 + else: + zorder = mlines.Line2D.zorder + self._zorder = zorder + + grid_color = mpl._val_or_rc(grid_color, "grid.color") + grid_linestyle = mpl._val_or_rc(grid_linestyle, "grid.linestyle") + grid_linewidth = mpl._val_or_rc(grid_linewidth, "grid.linewidth") + if grid_alpha is None and not mcolors._has_alpha_channel(grid_color): + # alpha precedence: kwarg > color alpha > rcParams['grid.alpha'] + # Note: only resolve to rcParams if the color does not have alpha + # otherwise `grid(color=(1, 1, 1, 0.5))` would work like + # grid(color=(1, 1, 1, 0.5), alpha=rcParams['grid.alpha']) + # so the that the rcParams default would override color alpha. + grid_alpha = mpl.rcParams["grid.alpha"] + grid_kw = {k[5:]: v for k, v in kwargs.items()} + + self.tick1line = mlines.Line2D( + [], [], + color=color, linestyle="none", zorder=zorder, visible=tick1On, + markeredgecolor=color, markersize=size, markeredgewidth=width, + ) + self.tick2line = mlines.Line2D( + [], [], + color=color, linestyle="none", zorder=zorder, visible=tick2On, + markeredgecolor=color, markersize=size, markeredgewidth=width, + ) + self.gridline = mlines.Line2D( + [], [], + color=grid_color, alpha=grid_alpha, visible=gridOn, + linestyle=grid_linestyle, linewidth=grid_linewidth, marker="", + **grid_kw, + ) + self.gridline.get_path()._interpolation_steps = \ + GRIDLINE_INTERPOLATION_STEPS + self.label1 = mtext.Text( + np.nan, np.nan, + fontsize=labelsize, color=labelcolor, visible=label1On, + fontfamily=labelfontfamily, rotation=self._labelrotation[1]) + self.label2 = mtext.Text( + np.nan, np.nan, + fontsize=labelsize, color=labelcolor, visible=label2On, + fontfamily=labelfontfamily, rotation=self._labelrotation[1]) + + self._apply_tickdir(tickdir) + + for artist in [self.tick1line, self.tick2line, self.gridline, + self.label1, self.label2]: + self._set_artist_props(artist) + + self.update_position(loc) + + def _set_labelrotation(self, labelrotation): + if isinstance(labelrotation, str): + mode = labelrotation + angle = 0 + elif isinstance(labelrotation, (tuple, list)): + mode, angle = labelrotation + else: + mode = 'default' + angle = labelrotation + _api.check_in_list(['auto', 'default'], labelrotation=mode) + self._labelrotation = (mode, angle) + + @property + def _pad(self): + return self._base_pad + self.get_tick_padding() + + def _apply_tickdir(self, tickdir): + """Set tick direction. Valid values are 'out', 'in', 'inout'.""" + # This method is responsible for verifying input and, in subclasses, for setting + # the tick{1,2}line markers. From the user perspective this should always be + # called through _apply_params, which further updates ticklabel positions using + # the new pads. + if tickdir is None: + tickdir = mpl.rcParams[f'{self.__name__}.direction'] + else: + _api.check_in_list(['in', 'out', 'inout'], tickdir=tickdir) + self._tickdir = tickdir + + def get_tickdir(self): + return self._tickdir + + def get_tick_padding(self): + """Get the length of the tick outside of the Axes.""" + padding = { + 'in': 0.0, + 'inout': 0.5, + 'out': 1.0 + } + return self._size * padding[self._tickdir] + + def get_children(self): + children = [self.tick1line, self.tick2line, + self.gridline, self.label1, self.label2] + return children + + def set_clip_path(self, path, transform=None): + # docstring inherited + super().set_clip_path(path, transform) + self.gridline.set_clip_path(path, transform) + self.stale = True + + def contains(self, mouseevent): + """ + Test whether the mouse event occurred in the Tick marks. + + This function always returns false. It is more useful to test if the + axis as a whole contains the mouse rather than the set of tick marks. + """ + return False, {} + + def set_pad(self, val): + """ + Set the tick label pad in points + + Parameters + ---------- + val : float + """ + self._apply_params(pad=val) + self.stale = True + + def get_pad(self): + """Get the value of the tick label pad in points.""" + return self._base_pad + + def get_loc(self): + """Return the tick location (data coords) as a scalar.""" + return self._loc + + @martist.allow_rasterization + def draw(self, renderer): + if not self.get_visible(): + self.stale = False + return + renderer.open_group(self.__name__, gid=self.get_gid()) + for artist in [self.gridline, self.tick1line, self.tick2line, + self.label1, self.label2]: + artist.draw(renderer) + renderer.close_group(self.__name__) + self.stale = False + + def set_url(self, url): + """ + Set the url of label1 and label2. + + Parameters + ---------- + url : str + """ + super().set_url(url) + self.label1.set_url(url) + self.label2.set_url(url) + self.stale = True + + def _set_artist_props(self, a): + a.set_figure(self.get_figure(root=False)) + + def get_view_interval(self): + """ + Return the view limits ``(min, max)`` of the axis the tick belongs to. + """ + raise NotImplementedError('Derived must override') + + def _apply_params(self, **kwargs): + for name, target in [("gridOn", self.gridline), + ("tick1On", self.tick1line), + ("tick2On", self.tick2line), + ("label1On", self.label1), + ("label2On", self.label2)]: + if name in kwargs: + target.set_visible(kwargs.pop(name)) + if any(k in kwargs for k in ['size', 'width', 'pad', 'tickdir']): + self._size = kwargs.pop('size', self._size) + # Width could be handled outside this block, but it is + # convenient to leave it here. + self._width = kwargs.pop('width', self._width) + self._base_pad = kwargs.pop('pad', self._base_pad) + # _apply_tickdir uses _size and _base_pad to make _pad, and also + # sets the ticklines markers. + self._apply_tickdir(kwargs.pop('tickdir', self._tickdir)) + for line in (self.tick1line, self.tick2line): + line.set_markersize(self._size) + line.set_markeredgewidth(self._width) + # _get_text1_transform uses _pad from _apply_tickdir. + trans = self._get_text1_transform()[0] + self.label1.set_transform(trans) + trans = self._get_text2_transform()[0] + self.label2.set_transform(trans) + tick_kw = {k: v for k, v in kwargs.items() if k in ['color', 'zorder']} + if 'color' in kwargs: + tick_kw['markeredgecolor'] = kwargs['color'] + self.tick1line.set(**tick_kw) + self.tick2line.set(**tick_kw) + for k, v in tick_kw.items(): + setattr(self, '_' + k, v) + + if 'labelrotation' in kwargs: + self._set_labelrotation(kwargs.pop('labelrotation')) + self.label1.set(rotation=self._labelrotation[1]) + self.label2.set(rotation=self._labelrotation[1]) + + label_kw = {k[5:]: v for k, v in kwargs.items() + if k in ['labelsize', 'labelcolor', 'labelfontfamily']} + self.label1.set(**label_kw) + self.label2.set(**label_kw) + + grid_kw = {k[5:]: v for k, v in kwargs.items() + if k in _gridline_param_names} + self.gridline.set(**grid_kw) + + def update_position(self, loc): + """Set the location of tick in data coords with scalar *loc*.""" + raise NotImplementedError('Derived must override') + + def _get_text1_transform(self): + raise NotImplementedError('Derived must override') + + def _get_text2_transform(self): + raise NotImplementedError('Derived must override') + + +class XTick(Tick): + """ + Contains all the Artists needed to make an x tick - the tick line, + the label text and the grid line + """ + __name__ = 'xtick' + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # x in data coords, y in axes coords + ax = self.axes + self.tick1line.set( + data=([0], [0]), transform=ax.get_xaxis_transform("tick1")) + self.tick2line.set( + data=([0], [1]), transform=ax.get_xaxis_transform("tick2")) + self.gridline.set( + data=([0, 0], [0, 1]), transform=ax.get_xaxis_transform("grid")) + # the y loc is 3 points below the min of y axis + trans, va, ha = self._get_text1_transform() + self.label1.set( + x=0, y=0, + verticalalignment=va, horizontalalignment=ha, transform=trans, + ) + trans, va, ha = self._get_text2_transform() + self.label2.set( + x=0, y=1, + verticalalignment=va, horizontalalignment=ha, transform=trans, + ) + + def _get_text1_transform(self): + return self.axes.get_xaxis_text1_transform(self._pad) + + def _get_text2_transform(self): + return self.axes.get_xaxis_text2_transform(self._pad) + + def _apply_tickdir(self, tickdir): + # docstring inherited + super()._apply_tickdir(tickdir) + mark1, mark2 = { + 'out': (mlines.TICKDOWN, mlines.TICKUP), + 'in': (mlines.TICKUP, mlines.TICKDOWN), + 'inout': ('|', '|'), + }[self._tickdir] + self.tick1line.set_marker(mark1) + self.tick2line.set_marker(mark2) + + def update_position(self, loc): + """Set the location of tick in data coords with scalar *loc*.""" + self.tick1line.set_xdata((loc,)) + self.tick2line.set_xdata((loc,)) + self.gridline.set_xdata((loc,)) + self.label1.set_x(loc) + self.label2.set_x(loc) + self._loc = loc + self.stale = True + + def get_view_interval(self): + # docstring inherited + return self.axes.viewLim.intervalx + + +class YTick(Tick): + """ + Contains all the Artists needed to make a Y tick - the tick line, + the label text and the grid line + """ + __name__ = 'ytick' + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # x in axes coords, y in data coords + ax = self.axes + self.tick1line.set( + data=([0], [0]), transform=ax.get_yaxis_transform("tick1")) + self.tick2line.set( + data=([1], [0]), transform=ax.get_yaxis_transform("tick2")) + self.gridline.set( + data=([0, 1], [0, 0]), transform=ax.get_yaxis_transform("grid")) + # the y loc is 3 points below the min of y axis + trans, va, ha = self._get_text1_transform() + self.label1.set( + x=0, y=0, + verticalalignment=va, horizontalalignment=ha, transform=trans, + ) + trans, va, ha = self._get_text2_transform() + self.label2.set( + x=1, y=0, + verticalalignment=va, horizontalalignment=ha, transform=trans, + ) + + def _get_text1_transform(self): + return self.axes.get_yaxis_text1_transform(self._pad) + + def _get_text2_transform(self): + return self.axes.get_yaxis_text2_transform(self._pad) + + def _apply_tickdir(self, tickdir): + # docstring inherited + super()._apply_tickdir(tickdir) + mark1, mark2 = { + 'out': (mlines.TICKLEFT, mlines.TICKRIGHT), + 'in': (mlines.TICKRIGHT, mlines.TICKLEFT), + 'inout': ('_', '_'), + }[self._tickdir] + self.tick1line.set_marker(mark1) + self.tick2line.set_marker(mark2) + + def update_position(self, loc): + """Set the location of tick in data coords with scalar *loc*.""" + self.tick1line.set_ydata((loc,)) + self.tick2line.set_ydata((loc,)) + self.gridline.set_ydata((loc,)) + self.label1.set_y(loc) + self.label2.set_y(loc) + self._loc = loc + self.stale = True + + def get_view_interval(self): + # docstring inherited + return self.axes.viewLim.intervaly + + +class Ticker: + """ + A container for the objects defining tick position and format. + + Attributes + ---------- + locator : `~matplotlib.ticker.Locator` subclass + Determines the positions of the ticks. + formatter : `~matplotlib.ticker.Formatter` subclass + Determines the format of the tick labels. + """ + + def __init__(self): + self._locator = None + self._formatter = None + self._locator_is_default = True + self._formatter_is_default = True + + @property + def locator(self): + return self._locator + + @locator.setter + def locator(self, locator): + if not isinstance(locator, mticker.Locator): + raise TypeError('locator must be a subclass of ' + 'matplotlib.ticker.Locator') + self._locator = locator + + @property + def formatter(self): + return self._formatter + + @formatter.setter + def formatter(self, formatter): + if not isinstance(formatter, mticker.Formatter): + raise TypeError('formatter must be a subclass of ' + 'matplotlib.ticker.Formatter') + self._formatter = formatter + + +class _LazyTickList: + """ + A descriptor for lazy instantiation of tick lists. + + See comment above definition of the ``majorTicks`` and ``minorTicks`` + attributes. + """ + + def __init__(self, major): + self._major = major + + def __get__(self, instance, owner): + if instance is None: + return self + else: + # instance._get_tick() can itself try to access the majorTicks + # attribute (e.g. in certain projection classes which override + # e.g. get_xaxis_text1_transform). In order to avoid infinite + # recursion, first set the majorTicks on the instance temporarily + # to an empty lis. Then create the tick; note that _get_tick() + # may call reset_ticks(). Therefore, the final tick list is + # created and assigned afterwards. + if self._major: + instance.majorTicks = [] + tick = instance._get_tick(major=True) + instance.majorTicks = [tick] + return instance.majorTicks + else: + instance.minorTicks = [] + tick = instance._get_tick(major=False) + instance.minorTicks = [tick] + return instance.minorTicks + + +class Axis(martist.Artist): + """ + Base class for `.XAxis` and `.YAxis`. + + Attributes + ---------- + isDefault_label : bool + + axes : `~matplotlib.axes.Axes` + The `~.axes.Axes` to which the Axis belongs. + major : `~matplotlib.axis.Ticker` + Determines the major tick positions and their label format. + minor : `~matplotlib.axis.Ticker` + Determines the minor tick positions and their label format. + callbacks : `~matplotlib.cbook.CallbackRegistry` + + label : `~matplotlib.text.Text` + The axis label. + labelpad : float + The distance between the axis label and the tick labels. + Defaults to :rc:`axes.labelpad`. + offsetText : `~matplotlib.text.Text` + A `.Text` object containing the data offset of the ticks (if any). + pickradius : float + The acceptance radius for containment tests. See also `.Axis.contains`. + majorTicks : list of `.Tick` + The major ticks. + + .. warning:: + + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that changes to individual ticks will not + survive if you work on the figure further (including also + panning/zooming on a displayed figure). + + Working on the individual ticks is a method of last resort. + Use `.set_tick_params` instead if possible. + + minorTicks : list of `.Tick` + The minor ticks. + """ + OFFSETTEXTPAD = 3 + # The class used in _get_tick() to create tick instances. Must either be + # overwritten in subclasses, or subclasses must reimplement _get_tick(). + _tick_class = None + converter = _api.deprecate_privatize_attribute( + "3.10", + alternative="get_converter and set_converter methods" + ) + + def __str__(self): + return "{}({},{})".format( + type(self).__name__, *self.axes.transAxes.transform((0, 0))) + + def __init__(self, axes, *, pickradius=15, clear=True): + """ + Parameters + ---------- + axes : `~matplotlib.axes.Axes` + The `~.axes.Axes` to which the created Axis belongs. + pickradius : float + The acceptance radius for containment tests. See also + `.Axis.contains`. + clear : bool, default: True + Whether to clear the Axis on creation. This is not required, e.g., when + creating an Axis as part of an Axes, as ``Axes.clear`` will call + ``Axis.clear``. + .. versionadded:: 3.8 + """ + super().__init__() + self._remove_overlapping_locs = True + + self.set_figure(axes.get_figure(root=False)) + + self.isDefault_label = True + + self.axes = axes + self.major = Ticker() + self.minor = Ticker() + self.callbacks = cbook.CallbackRegistry(signals=["units"]) + + self._autolabelpos = True + + self.label = mtext.Text( + np.nan, np.nan, + fontsize=mpl.rcParams['axes.labelsize'], + fontweight=mpl.rcParams['axes.labelweight'], + color=mpl.rcParams['axes.labelcolor'], + ) #: The `.Text` object of the axis label. + + self._set_artist_props(self.label) + self.offsetText = mtext.Text(np.nan, np.nan) + self._set_artist_props(self.offsetText) + + self.labelpad = mpl.rcParams['axes.labelpad'] + + self.pickradius = pickradius + + # Initialize here for testing; later add API + self._major_tick_kw = dict() + self._minor_tick_kw = dict() + + if clear: + self.clear() + else: + self._converter = None + self._converter_is_explicit = False + self.units = None + + self._autoscale_on = True + + @property + def isDefault_majloc(self): + return self.major._locator_is_default + + @isDefault_majloc.setter + def isDefault_majloc(self, value): + self.major._locator_is_default = value + + @property + def isDefault_majfmt(self): + return self.major._formatter_is_default + + @isDefault_majfmt.setter + def isDefault_majfmt(self, value): + self.major._formatter_is_default = value + + @property + def isDefault_minloc(self): + return self.minor._locator_is_default + + @isDefault_minloc.setter + def isDefault_minloc(self, value): + self.minor._locator_is_default = value + + @property + def isDefault_minfmt(self): + return self.minor._formatter_is_default + + @isDefault_minfmt.setter + def isDefault_minfmt(self, value): + self.minor._formatter_is_default = value + + def _get_shared_axes(self): + """Return Grouper of shared Axes for current axis.""" + return self.axes._shared_axes[ + self._get_axis_name()].get_siblings(self.axes) + + def _get_shared_axis(self): + """Return list of shared axis for current axis.""" + name = self._get_axis_name() + return [ax._axis_map[name] for ax in self._get_shared_axes()] + + def _get_axis_name(self): + """Return the axis name.""" + return next(name for name, axis in self.axes._axis_map.items() + if axis is self) + + # During initialization, Axis objects often create ticks that are later + # unused; this turns out to be a very slow step. Instead, use a custom + # descriptor to make the tick lists lazy and instantiate them as needed. + majorTicks = _LazyTickList(major=True) + minorTicks = _LazyTickList(major=False) + + def get_remove_overlapping_locs(self): + return self._remove_overlapping_locs + + def set_remove_overlapping_locs(self, val): + self._remove_overlapping_locs = bool(val) + + remove_overlapping_locs = property( + get_remove_overlapping_locs, set_remove_overlapping_locs, + doc=('If minor ticker locations that overlap with major ' + 'ticker locations should be trimmed.')) + + def set_label_coords(self, x, y, transform=None): + """ + Set the coordinates of the label. + + By default, the x coordinate of the y label and the y coordinate of the + x label are determined by the tick label bounding boxes, but this can + lead to poor alignment of multiple labels if there are multiple Axes. + + You can also specify the coordinate system of the label with the + transform. If None, the default coordinate system will be the axes + coordinate system: (0, 0) is bottom left, (0.5, 0.5) is center, etc. + """ + self._autolabelpos = False + if transform is None: + transform = self.axes.transAxes + + self.label.set_transform(transform) + self.label.set_position((x, y)) + self.stale = True + + def get_transform(self): + """Return the transform used in the Axis' scale""" + return self._scale.get_transform() + + def get_scale(self): + """Return this Axis' scale (as a str).""" + return self._scale.name + + def _set_scale(self, value, **kwargs): + if not isinstance(value, mscale.ScaleBase): + self._scale = mscale.scale_factory(value, self, **kwargs) + else: + self._scale = value + self._scale.set_default_locators_and_formatters(self) + + self.isDefault_majloc = True + self.isDefault_minloc = True + self.isDefault_majfmt = True + self.isDefault_minfmt = True + + # This method is directly wrapped by Axes.set_{x,y}scale. + def _set_axes_scale(self, value, **kwargs): + """ + Set this Axis' scale. + + Parameters + ---------- + value : {"linear", "log", "symlog", "logit", ...} or `.ScaleBase` + The axis scale type to apply. + + **kwargs + Different keyword arguments are accepted, depending on the scale. + See the respective class keyword arguments: + + - `matplotlib.scale.LinearScale` + - `matplotlib.scale.LogScale` + - `matplotlib.scale.SymmetricalLogScale` + - `matplotlib.scale.LogitScale` + - `matplotlib.scale.FuncScale` + - `matplotlib.scale.AsinhScale` + + Notes + ----- + By default, Matplotlib supports the above-mentioned scales. + Additionally, custom scales may be registered using + `matplotlib.scale.register_scale`. These scales can then also + be used here. + """ + name = self._get_axis_name() + old_default_lims = (self.get_major_locator() + .nonsingular(-np.inf, np.inf)) + for ax in self._get_shared_axes(): + ax._axis_map[name]._set_scale(value, **kwargs) + ax._update_transScale() + ax.stale = True + new_default_lims = (self.get_major_locator() + .nonsingular(-np.inf, np.inf)) + if old_default_lims != new_default_lims: + # Force autoscaling now, to take advantage of the scale locator's + # nonsingular() before it possibly gets swapped out by the user. + self.axes.autoscale_view( + **{f"scale{k}": k == name for k in self.axes._axis_names}) + + def limit_range_for_scale(self, vmin, vmax): + """ + Return the range *vmin*, *vmax*, restricted to the domain supported by the + current scale. + """ + return self._scale.limit_range_for_scale(vmin, vmax, self.get_minpos()) + + def _get_autoscale_on(self): + """Return whether this Axis is autoscaled.""" + return self._autoscale_on + + def _set_autoscale_on(self, b): + """ + Set whether this Axis is autoscaled when drawing or by `.Axes.autoscale_view`. + + If b is None, then the value is not changed. + + Parameters + ---------- + b : bool + """ + if b is not None: + self._autoscale_on = b + + def get_children(self): + return [self.label, self.offsetText, + *self.get_major_ticks(), *self.get_minor_ticks()] + + def _reset_major_tick_kw(self): + self._major_tick_kw.clear() + self._major_tick_kw['gridOn'] = ( + mpl.rcParams['axes.grid'] and + mpl.rcParams['axes.grid.which'] in ('both', 'major')) + + def _reset_minor_tick_kw(self): + self._minor_tick_kw.clear() + self._minor_tick_kw['gridOn'] = ( + mpl.rcParams['axes.grid'] and + mpl.rcParams['axes.grid.which'] in ('both', 'minor')) + + def clear(self): + """ + Clear the axis. + + This resets axis properties to their default values: + + - the label + - the scale + - locators, formatters and ticks + - major and minor grid + - units + - registered callbacks + """ + self.label._reset_visual_defaults() + # The above resets the label formatting using text rcParams, + # so we then update the formatting using axes rcParams + self.label.set_color(mpl.rcParams['axes.labelcolor']) + self.label.set_fontsize(mpl.rcParams['axes.labelsize']) + self.label.set_fontweight(mpl.rcParams['axes.labelweight']) + self.offsetText._reset_visual_defaults() + self.labelpad = mpl.rcParams['axes.labelpad'] + + self._init() + + self._set_scale('linear') + + # Clear the callback registry for this axis, or it may "leak" + self.callbacks = cbook.CallbackRegistry(signals=["units"]) + + # whether the grids are on + self._major_tick_kw['gridOn'] = ( + mpl.rcParams['axes.grid'] and + mpl.rcParams['axes.grid.which'] in ('both', 'major')) + self._minor_tick_kw['gridOn'] = ( + mpl.rcParams['axes.grid'] and + mpl.rcParams['axes.grid.which'] in ('both', 'minor')) + self.reset_ticks() + + self._converter = None + self._converter_is_explicit = False + self.units = None + self.stale = True + + def reset_ticks(self): + """ + Re-initialize the major and minor Tick lists. + + Each list starts with a single fresh Tick. + """ + # Restore the lazy tick lists. + try: + del self.majorTicks + except AttributeError: + pass + try: + del self.minorTicks + except AttributeError: + pass + try: + self.set_clip_path(self.axes.patch) + except AttributeError: + pass + + def minorticks_on(self): + """ + Display default minor ticks on the Axis, depending on the scale + (`~.axis.Axis.get_scale`). + + Scales use specific minor locators: + + - log: `~.LogLocator` + - symlog: `~.SymmetricalLogLocator` + - asinh: `~.AsinhLocator` + - logit: `~.LogitLocator` + - default: `~.AutoMinorLocator` + + Displaying minor ticks may reduce performance; you may turn them off + using `minorticks_off()` if drawing speed is a problem. + """ + scale = self.get_scale() + if scale == 'log': + s = self._scale + self.set_minor_locator(mticker.LogLocator(s.base, s.subs)) + elif scale == 'symlog': + s = self._scale + self.set_minor_locator( + mticker.SymmetricalLogLocator(s._transform, s.subs)) + elif scale == 'asinh': + s = self._scale + self.set_minor_locator( + mticker.AsinhLocator(s.linear_width, base=s._base, + subs=s._subs)) + elif scale == 'logit': + self.set_minor_locator(mticker.LogitLocator(minor=True)) + else: + self.set_minor_locator(mticker.AutoMinorLocator()) + + def minorticks_off(self): + """Remove minor ticks from the Axis.""" + self.set_minor_locator(mticker.NullLocator()) + + def set_tick_params(self, which='major', reset=False, **kwargs): + """ + Set appearance parameters for ticks, ticklabels, and gridlines. + + For documentation of keyword arguments, see + :meth:`matplotlib.axes.Axes.tick_params`. + + See Also + -------- + .Axis.get_tick_params + View the current style settings for ticks, ticklabels, and + gridlines. + """ + _api.check_in_list(['major', 'minor', 'both'], which=which) + kwtrans = self._translate_tick_params(kwargs) + + # the kwargs are stored in self._major/minor_tick_kw so that any + # future new ticks will automatically get them + if reset: + if which in ['major', 'both']: + self._reset_major_tick_kw() + self._major_tick_kw.update(kwtrans) + if which in ['minor', 'both']: + self._reset_minor_tick_kw() + self._minor_tick_kw.update(kwtrans) + self.reset_ticks() + else: + if which in ['major', 'both']: + self._major_tick_kw.update(kwtrans) + for tick in self.majorTicks: + tick._apply_params(**kwtrans) + if which in ['minor', 'both']: + self._minor_tick_kw.update(kwtrans) + for tick in self.minorTicks: + tick._apply_params(**kwtrans) + # labelOn and labelcolor also apply to the offset text. + if 'label1On' in kwtrans or 'label2On' in kwtrans: + self.offsetText.set_visible( + self._major_tick_kw.get('label1On', False) + or self._major_tick_kw.get('label2On', False)) + if 'labelcolor' in kwtrans: + self.offsetText.set_color(kwtrans['labelcolor']) + + self.stale = True + + def get_tick_params(self, which='major'): + """ + Get appearance parameters for ticks, ticklabels, and gridlines. + + .. versionadded:: 3.7 + + Parameters + ---------- + which : {'major', 'minor'}, default: 'major' + The group of ticks for which the parameters are retrieved. + + Returns + ------- + dict + Properties for styling tick elements added to the axis. + + Notes + ----- + This method returns the appearance parameters for styling *new* + elements added to this axis and may be different from the values + on current elements if they were modified directly by the user + (e.g., via ``set_*`` methods on individual tick objects). + + Examples + -------- + :: + + >>> ax.yaxis.set_tick_params(labelsize=30, labelcolor='red', + ... direction='out', which='major') + >>> ax.yaxis.get_tick_params(which='major') + {'direction': 'out', + 'left': True, + 'right': False, + 'labelleft': True, + 'labelright': False, + 'gridOn': False, + 'labelsize': 30, + 'labelcolor': 'red'} + >>> ax.yaxis.get_tick_params(which='minor') + {'left': True, + 'right': False, + 'labelleft': True, + 'labelright': False, + 'gridOn': False} + + + """ + _api.check_in_list(['major', 'minor'], which=which) + if which == 'major': + return self._translate_tick_params( + self._major_tick_kw, reverse=True + ) + return self._translate_tick_params(self._minor_tick_kw, reverse=True) + + @classmethod + def _translate_tick_params(cls, kw, reverse=False): + """ + Translate the kwargs supported by `.Axis.set_tick_params` to kwargs + supported by `.Tick._apply_params`. + + In particular, this maps axis specific names like 'top', 'left' + to the generic tick1, tick2 logic of the axis. Additionally, there + are some other name translations. + + Returns a new dict of translated kwargs. + + Note: Use reverse=True to translate from those supported by + `.Tick._apply_params` back to those supported by + `.Axis.set_tick_params`. + """ + kw_ = {**kw} + + # The following lists may be moved to a more accessible location. + allowed_keys = [ + 'size', 'width', 'color', 'tickdir', 'pad', + 'labelsize', 'labelcolor', 'labelfontfamily', 'zorder', 'gridOn', + 'tick1On', 'tick2On', 'label1On', 'label2On', + 'length', 'direction', 'left', 'bottom', 'right', 'top', + 'labelleft', 'labelbottom', 'labelright', 'labeltop', + 'labelrotation', + *_gridline_param_names] + + keymap = { + # tick_params key -> axis key + 'length': 'size', + 'direction': 'tickdir', + 'rotation': 'labelrotation', + 'left': 'tick1On', + 'bottom': 'tick1On', + 'right': 'tick2On', + 'top': 'tick2On', + 'labelleft': 'label1On', + 'labelbottom': 'label1On', + 'labelright': 'label2On', + 'labeltop': 'label2On', + } + if reverse: + kwtrans = {} + is_x_axis = cls.axis_name == 'x' + y_axis_keys = ['left', 'right', 'labelleft', 'labelright'] + for oldkey, newkey in keymap.items(): + if newkey in kw_: + if is_x_axis and oldkey in y_axis_keys: + continue + else: + kwtrans[oldkey] = kw_.pop(newkey) + else: + kwtrans = { + newkey: kw_.pop(oldkey) + for oldkey, newkey in keymap.items() if oldkey in kw_ + } + if 'colors' in kw_: + c = kw_.pop('colors') + kwtrans['color'] = c + kwtrans['labelcolor'] = c + # Maybe move the checking up to the caller of this method. + for key in kw_: + if key not in allowed_keys: + raise ValueError( + "keyword %s is not recognized; valid keywords are %s" + % (key, allowed_keys)) + kwtrans.update(kw_) + return kwtrans + + def set_clip_path(self, path, transform=None): + super().set_clip_path(path, transform) + for child in self.majorTicks + self.minorTicks: + child.set_clip_path(path, transform) + self.stale = True + + def get_view_interval(self): + """Return the ``(min, max)`` view limits of this axis.""" + raise NotImplementedError('Derived must override') + + def set_view_interval(self, vmin, vmax, ignore=False): + """ + Set the axis view limits. This method is for internal use; Matplotlib + users should typically use e.g. `~.Axes.set_xlim` or `~.Axes.set_ylim`. + + If *ignore* is False (the default), this method will never reduce the + preexisting view limits, only expand them if *vmin* or *vmax* are not + within them. Moreover, the order of *vmin* and *vmax* does not matter; + the orientation of the axis will not change. + + If *ignore* is True, the view limits will be set exactly to ``(vmin, + vmax)`` in that order. + """ + raise NotImplementedError('Derived must override') + + def get_data_interval(self): + """Return the ``(min, max)`` data limits of this axis.""" + raise NotImplementedError('Derived must override') + + def set_data_interval(self, vmin, vmax, ignore=False): + """ + Set the axis data limits. This method is for internal use. + + If *ignore* is False (the default), this method will never reduce the + preexisting data limits, only expand them if *vmin* or *vmax* are not + within them. Moreover, the order of *vmin* and *vmax* does not matter; + the orientation of the axis will not change. + + If *ignore* is True, the data limits will be set exactly to ``(vmin, + vmax)`` in that order. + """ + raise NotImplementedError('Derived must override') + + def get_inverted(self): + """ + Return whether this Axis is oriented in the "inverse" direction. + + The "normal" direction is increasing to the right for the x-axis and to + the top for the y-axis; the "inverse" direction is increasing to the + left for the x-axis and to the bottom for the y-axis. + """ + low, high = self.get_view_interval() + return high < low + + def set_inverted(self, inverted): + """ + Set whether this Axis is oriented in the "inverse" direction. + + The "normal" direction is increasing to the right for the x-axis and to + the top for the y-axis; the "inverse" direction is increasing to the + left for the x-axis and to the bottom for the y-axis. + """ + a, b = self.get_view_interval() + # cast to bool to avoid bad interaction between python 3.8 and np.bool_ + self._set_lim(*sorted((a, b), reverse=bool(inverted)), auto=None) + + def set_default_intervals(self): + """ + Set the default limits for the axis data and view interval if they + have not been not mutated yet. + """ + # this is mainly in support of custom object plotting. For + # example, if someone passes in a datetime object, we do not + # know automagically how to set the default min/max of the + # data and view limits. The unit conversion AxisInfo + # interface provides a hook for custom types to register + # default limits through the AxisInfo.default_limits + # attribute, and the derived code below will check for that + # and use it if it's available (else just use 0..1) + + def _set_lim(self, v0, v1, *, emit=True, auto): + """ + Set view limits. + + This method is a helper for the Axes ``set_xlim``, ``set_ylim``, and + ``set_zlim`` methods. + + Parameters + ---------- + v0, v1 : float + The view limits. (Passing *v0* as a (low, high) pair is not + supported; normalization must occur in the Axes setters.) + emit : bool, default: True + Whether to notify observers of limit change. + auto : bool or None, default: False + Whether to turn on autoscaling of the x-axis. True turns on, False + turns off, None leaves unchanged. + """ + name = self._get_axis_name() + + self.axes._process_unit_info([(name, (v0, v1))], convert=False) + v0 = self.axes._validate_converted_limits(v0, self.convert_units) + v1 = self.axes._validate_converted_limits(v1, self.convert_units) + + if v0 is None or v1 is None: + # Axes init calls set_xlim(0, 1) before get_xlim() can be called, + # so only grab the limits if we really need them. + old0, old1 = self.get_view_interval() + if v0 is None: + v0 = old0 + if v1 is None: + v1 = old1 + + if self.get_scale() == 'log' and (v0 <= 0 or v1 <= 0): + # Axes init calls set_xlim(0, 1) before get_xlim() can be called, + # so only grab the limits if we really need them. + old0, old1 = self.get_view_interval() + if v0 <= 0: + _api.warn_external(f"Attempt to set non-positive {name}lim on " + f"a log-scaled axis will be ignored.") + v0 = old0 + if v1 <= 0: + _api.warn_external(f"Attempt to set non-positive {name}lim on " + f"a log-scaled axis will be ignored.") + v1 = old1 + if v0 == v1: + _api.warn_external( + f"Attempting to set identical low and high {name}lims " + f"makes transformation singular; automatically expanding.") + reverse = bool(v0 > v1) # explicit cast needed for python3.8+np.bool_. + v0, v1 = self.get_major_locator().nonsingular(v0, v1) + v0, v1 = self.limit_range_for_scale(v0, v1) + v0, v1 = sorted([v0, v1], reverse=bool(reverse)) + + self.set_view_interval(v0, v1, ignore=True) + # Mark viewlims as no longer stale without triggering an autoscale. + for ax in self._get_shared_axes(): + ax._stale_viewlims[name] = False + self._set_autoscale_on(auto) + + if emit: + self.axes.callbacks.process(f"{name}lim_changed", self.axes) + # Call all of the other Axes that are shared with this one + for other in self._get_shared_axes(): + if other is self.axes: + continue + other._axis_map[name]._set_lim(v0, v1, emit=False, auto=auto) + if emit: + other.callbacks.process(f"{name}lim_changed", other) + if ((other_fig := other.get_figure(root=False)) != + self.get_figure(root=False)): + other_fig.canvas.draw_idle() + + self.stale = True + return v0, v1 + + def _set_artist_props(self, a): + if a is None: + return + a.set_figure(self.get_figure(root=False)) + + def _update_ticks(self): + """ + Update ticks (position and labels) using the current data interval of + the axes. Return the list of ticks that will be drawn. + """ + major_locs = self.get_majorticklocs() + major_labels = self.major.formatter.format_ticks(major_locs) + major_ticks = self.get_major_ticks(len(major_locs)) + for tick, loc, label in zip(major_ticks, major_locs, major_labels): + tick.update_position(loc) + tick.label1.set_text(label) + tick.label2.set_text(label) + minor_locs = self.get_minorticklocs() + minor_labels = self.minor.formatter.format_ticks(minor_locs) + minor_ticks = self.get_minor_ticks(len(minor_locs)) + for tick, loc, label in zip(minor_ticks, minor_locs, minor_labels): + tick.update_position(loc) + tick.label1.set_text(label) + tick.label2.set_text(label) + ticks = [*major_ticks, *minor_ticks] + + view_low, view_high = self.get_view_interval() + if view_low > view_high: + view_low, view_high = view_high, view_low + + if (hasattr(self, "axes") and self.axes.name == '3d' + and mpl.rcParams['axes3d.automargin']): + # In mpl3.8, the margin was 1/48. Due to the change in automargin + # behavior in mpl3.9, we need to adjust this to compensate for a + # zoom factor of 2/48, giving us a 23/24 modifier. So the new + # margin is 0.019965277777777776 = 1/48*23/24. + margin = 0.019965277777777776 + delta = view_high - view_low + view_high = view_high - delta * margin + view_low = view_low + delta * margin + + interval_t = self.get_transform().transform([view_low, view_high]) + + ticks_to_draw = [] + for tick in ticks: + try: + loc_t = self.get_transform().transform(tick.get_loc()) + except AssertionError: + # transforms.transform doesn't allow masked values but + # some scales might make them, so we need this try/except. + pass + else: + if mtransforms._interval_contains_close(interval_t, loc_t): + ticks_to_draw.append(tick) + + return ticks_to_draw + + def _get_ticklabel_bboxes(self, ticks, renderer=None): + """Return lists of bboxes for ticks' label1's and label2's.""" + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + return ([tick.label1.get_window_extent(renderer) + for tick in ticks if tick.label1.get_visible()], + [tick.label2.get_window_extent(renderer) + for tick in ticks if tick.label2.get_visible()]) + + def get_tightbbox(self, renderer=None, *, for_layout_only=False): + """ + Return a bounding box that encloses the axis. It only accounts + tick labels, axis label, and offsetText. + + If *for_layout_only* is True, then the width of the label (if this + is an x-axis) or the height of the label (if this is a y-axis) is + collapsed to near zero. This allows tight/constrained_layout to ignore + too-long labels when doing their layout. + """ + if not self.get_visible() or for_layout_only and not self.get_in_layout(): + return + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + ticks_to_draw = self._update_ticks() + + self._update_label_position(renderer) + + # go back to just this axis's tick labels + tlb1, tlb2 = self._get_ticklabel_bboxes(ticks_to_draw, renderer) + + self._update_offset_text_position(tlb1, tlb2) + self.offsetText.set_text(self.major.formatter.get_offset()) + + bboxes = [ + *(a.get_window_extent(renderer) + for a in [self.offsetText] + if a.get_visible()), + *tlb1, *tlb2, + ] + # take care of label + if self.label.get_visible(): + bb = self.label.get_window_extent(renderer) + # for constrained/tight_layout, we want to ignore the label's + # width/height because the adjustments they make can't be improved. + # this code collapses the relevant direction + if for_layout_only: + if self.axis_name == "x" and bb.width > 0: + bb.x0 = (bb.x0 + bb.x1) / 2 - 0.5 + bb.x1 = bb.x0 + 1.0 + if self.axis_name == "y" and bb.height > 0: + bb.y0 = (bb.y0 + bb.y1) / 2 - 0.5 + bb.y1 = bb.y0 + 1.0 + bboxes.append(bb) + bboxes = [b for b in bboxes + if 0 < b.width < np.inf and 0 < b.height < np.inf] + if bboxes: + return mtransforms.Bbox.union(bboxes) + else: + return None + + def get_tick_padding(self): + values = [] + if len(self.majorTicks): + values.append(self.majorTicks[0].get_tick_padding()) + if len(self.minorTicks): + values.append(self.minorTicks[0].get_tick_padding()) + return max(values, default=0) + + @martist.allow_rasterization + def draw(self, renderer): + # docstring inherited + + if not self.get_visible(): + return + renderer.open_group(__name__, gid=self.get_gid()) + + ticks_to_draw = self._update_ticks() + tlb1, tlb2 = self._get_ticklabel_bboxes(ticks_to_draw, renderer) + + for tick in ticks_to_draw: + tick.draw(renderer) + + # Shift label away from axes to avoid overlapping ticklabels. + self._update_label_position(renderer) + self.label.draw(renderer) + + self._update_offset_text_position(tlb1, tlb2) + self.offsetText.set_text(self.major.formatter.get_offset()) + self.offsetText.draw(renderer) + + renderer.close_group(__name__) + self.stale = False + + def get_gridlines(self): + r"""Return this Axis' grid lines as a list of `.Line2D`\s.""" + ticks = self.get_major_ticks() + return cbook.silent_list('Line2D gridline', + [tick.gridline for tick in ticks]) + + def set_label(self, s): + """Assigning legend labels is not supported. Raises RuntimeError.""" + raise RuntimeError( + "A legend label cannot be assigned to an Axis. Did you mean to " + "set the axis label via set_label_text()?") + + def get_label(self): + """ + Return the axis label as a Text instance. + + .. admonition:: Discouraged + + This overrides `.Artist.get_label`, which is for legend labels, with a new + semantic. It is recommended to use the attribute ``Axis.label`` instead. + """ + return self.label + + def get_offset_text(self): + """Return the axis offsetText as a Text instance.""" + return self.offsetText + + def get_pickradius(self): + """Return the depth of the axis used by the picker.""" + return self._pickradius + + def get_majorticklabels(self): + """Return this Axis' major tick labels, as a list of `~.text.Text`.""" + self._update_ticks() + ticks = self.get_major_ticks() + labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()] + labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()] + return labels1 + labels2 + + def get_minorticklabels(self): + """Return this Axis' minor tick labels, as a list of `~.text.Text`.""" + self._update_ticks() + ticks = self.get_minor_ticks() + labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()] + labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()] + return labels1 + labels2 + + def get_ticklabels(self, minor=False, which=None): + """ + Get this Axis' tick labels. + + Parameters + ---------- + minor : bool + Whether to return the minor or the major ticklabels. + + which : None, ('minor', 'major', 'both') + Overrides *minor*. + + Selects which ticklabels to return + + Returns + ------- + list of `~matplotlib.text.Text` + """ + if which is not None: + if which == 'minor': + return self.get_minorticklabels() + elif which == 'major': + return self.get_majorticklabels() + elif which == 'both': + return self.get_majorticklabels() + self.get_minorticklabels() + else: + _api.check_in_list(['major', 'minor', 'both'], which=which) + if minor: + return self.get_minorticklabels() + return self.get_majorticklabels() + + def get_majorticklines(self): + r"""Return this Axis' major tick lines as a list of `.Line2D`\s.""" + lines = [] + ticks = self.get_major_ticks() + for tick in ticks: + lines.append(tick.tick1line) + lines.append(tick.tick2line) + return cbook.silent_list('Line2D ticklines', lines) + + def get_minorticklines(self): + r"""Return this Axis' minor tick lines as a list of `.Line2D`\s.""" + lines = [] + ticks = self.get_minor_ticks() + for tick in ticks: + lines.append(tick.tick1line) + lines.append(tick.tick2line) + return cbook.silent_list('Line2D ticklines', lines) + + def get_ticklines(self, minor=False): + r"""Return this Axis' tick lines as a list of `.Line2D`\s.""" + if minor: + return self.get_minorticklines() + return self.get_majorticklines() + + def get_majorticklocs(self): + """Return this Axis' major tick locations in data coordinates.""" + return self.major.locator() + + def get_minorticklocs(self): + """Return this Axis' minor tick locations in data coordinates.""" + # Remove minor ticks duplicating major ticks. + minor_locs = np.asarray(self.minor.locator()) + if self.remove_overlapping_locs: + major_locs = self.major.locator() + transform = self._scale.get_transform() + tr_minor_locs = transform.transform(minor_locs) + tr_major_locs = transform.transform(major_locs) + lo, hi = sorted(transform.transform(self.get_view_interval())) + # Use the transformed view limits as scale. 1e-5 is the default + # rtol for np.isclose. + tol = (hi - lo) * 1e-5 + mask = np.isclose(tr_minor_locs[:, None], tr_major_locs[None, :], + atol=tol, rtol=0).any(axis=1) + minor_locs = minor_locs[~mask] + return minor_locs + + def get_ticklocs(self, *, minor=False): + """ + Return this Axis' tick locations in data coordinates. + + The locations are not clipped to the current axis limits and hence + may contain locations that are not visible in the output. + + Parameters + ---------- + minor : bool, default: False + True to return the minor tick directions, + False to return the major tick directions. + + Returns + ------- + array of tick locations + """ + return self.get_minorticklocs() if minor else self.get_majorticklocs() + + def get_ticks_direction(self, minor=False): + """ + Return an array of this Axis' tick directions. + + Parameters + ---------- + minor : bool, default: False + True to return the minor tick directions, + False to return the major tick directions. + + Returns + ------- + array of tick directions + """ + if minor: + return np.array( + [tick._tickdir for tick in self.get_minor_ticks()]) + else: + return np.array( + [tick._tickdir for tick in self.get_major_ticks()]) + + def _get_tick(self, major): + """Return the default tick instance.""" + if self._tick_class is None: + raise NotImplementedError( + f"The Axis subclass {self.__class__.__name__} must define " + "_tick_class or reimplement _get_tick()") + tick_kw = self._major_tick_kw if major else self._minor_tick_kw + return self._tick_class(self.axes, 0, major=major, **tick_kw) + + def _get_tick_label_size(self, axis_name): + """ + Return the text size of tick labels for this Axis. + + This is a convenience function to avoid having to create a `Tick` in + `.get_tick_space`, since it is expensive. + """ + tick_kw = self._major_tick_kw + size = tick_kw.get('labelsize', + mpl.rcParams[f'{axis_name}tick.labelsize']) + return mtext.FontProperties(size=size).get_size_in_points() + + def _copy_tick_props(self, src, dest): + """Copy the properties from *src* tick to *dest* tick.""" + if src is None or dest is None: + return + dest.label1.update_from(src.label1) + dest.label2.update_from(src.label2) + dest.tick1line.update_from(src.tick1line) + dest.tick2line.update_from(src.tick2line) + dest.gridline.update_from(src.gridline) + dest.update_from(src) + dest._loc = src._loc + dest._size = src._size + dest._width = src._width + dest._base_pad = src._base_pad + dest._labelrotation = src._labelrotation + dest._zorder = src._zorder + dest._tickdir = src._tickdir + + def get_label_text(self): + """Get the text of the label.""" + return self.label.get_text() + + def get_major_locator(self): + """Get the locator of the major ticker.""" + return self.major.locator + + def get_minor_locator(self): + """Get the locator of the minor ticker.""" + return self.minor.locator + + def get_major_formatter(self): + """Get the formatter of the major ticker.""" + return self.major.formatter + + def get_minor_formatter(self): + """Get the formatter of the minor ticker.""" + return self.minor.formatter + + def get_major_ticks(self, numticks=None): + r""" + Return the list of major `.Tick`\s. + + .. warning:: + + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that changes to individual ticks will not + survive if you work on the figure further (including also + panning/zooming on a displayed figure). + + Working on the individual ticks is a method of last resort. + Use `.set_tick_params` instead if possible. + """ + if numticks is None: + numticks = len(self.get_majorticklocs()) + + while len(self.majorTicks) < numticks: + # Update the new tick label properties from the old. + tick = self._get_tick(major=True) + self.majorTicks.append(tick) + self._copy_tick_props(self.majorTicks[0], tick) + + return self.majorTicks[:numticks] + + def get_minor_ticks(self, numticks=None): + r""" + Return the list of minor `.Tick`\s. + + .. warning:: + + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that changes to individual ticks will not + survive if you work on the figure further (including also + panning/zooming on a displayed figure). + + Working on the individual ticks is a method of last resort. + Use `.set_tick_params` instead if possible. + """ + if numticks is None: + numticks = len(self.get_minorticklocs()) + + while len(self.minorTicks) < numticks: + # Update the new tick label properties from the old. + tick = self._get_tick(major=False) + self.minorTicks.append(tick) + self._copy_tick_props(self.minorTicks[0], tick) + + return self.minorTicks[:numticks] + + def grid(self, visible=None, which='major', **kwargs): + """ + Configure the grid lines. + + Parameters + ---------- + visible : bool or None + Whether to show the grid lines. If any *kwargs* are supplied, it + is assumed you want the grid on and *visible* will be set to True. + + If *visible* is *None* and there are no *kwargs*, this toggles the + visibility of the lines. + + which : {'major', 'minor', 'both'} + The grid lines to apply the changes on. + + **kwargs : `~matplotlib.lines.Line2D` properties + Define the line properties of the grid, e.g.:: + + grid(color='r', linestyle='-', linewidth=2) + """ + if kwargs: + if visible is None: + visible = True + elif not visible: # something false-like but not None + _api.warn_external('First parameter to grid() is false, ' + 'but line properties are supplied. The ' + 'grid will be enabled.') + visible = True + which = which.lower() + _api.check_in_list(['major', 'minor', 'both'], which=which) + gridkw = {f'grid_{name}': value for name, value in kwargs.items()} + if which in ['minor', 'both']: + gridkw['gridOn'] = (not self._minor_tick_kw['gridOn'] + if visible is None else visible) + self.set_tick_params(which='minor', **gridkw) + if which in ['major', 'both']: + gridkw['gridOn'] = (not self._major_tick_kw['gridOn'] + if visible is None else visible) + self.set_tick_params(which='major', **gridkw) + self.stale = True + + def update_units(self, data): + """ + Introspect *data* for units converter and update the + ``axis.get_converter`` instance if necessary. Return *True* + if *data* is registered for unit conversion. + """ + if not self._converter_is_explicit: + converter = munits.registry.get_converter(data) + else: + converter = self._converter + + if converter is None: + return False + + neednew = self._converter != converter + self._set_converter(converter) + default = self._converter.default_units(data, self) + if default is not None and self.units is None: + self.set_units(default) + + elif neednew: + self._update_axisinfo() + self.stale = True + return True + + def _update_axisinfo(self): + """ + Check the axis converter for the stored units to see if the + axis info needs to be updated. + """ + if self._converter is None: + return + + info = self._converter.axisinfo(self.units, self) + + if info is None: + return + if info.majloc is not None and \ + self.major.locator != info.majloc and self.isDefault_majloc: + self.set_major_locator(info.majloc) + self.isDefault_majloc = True + if info.minloc is not None and \ + self.minor.locator != info.minloc and self.isDefault_minloc: + self.set_minor_locator(info.minloc) + self.isDefault_minloc = True + if info.majfmt is not None and \ + self.major.formatter != info.majfmt and self.isDefault_majfmt: + self.set_major_formatter(info.majfmt) + self.isDefault_majfmt = True + if info.minfmt is not None and \ + self.minor.formatter != info.minfmt and self.isDefault_minfmt: + self.set_minor_formatter(info.minfmt) + self.isDefault_minfmt = True + if info.label is not None and self.isDefault_label: + self.set_label_text(info.label) + self.isDefault_label = True + + self.set_default_intervals() + + def have_units(self): + return self._converter is not None or self.units is not None + + def convert_units(self, x): + # If x is natively supported by Matplotlib, doesn't need converting + if munits._is_natively_supported(x): + return x + + if self._converter is None: + self._set_converter(munits.registry.get_converter(x)) + + if self._converter is None: + return x + try: + ret = self._converter.convert(x, self.units, self) + except Exception as e: + raise munits.ConversionError('Failed to convert value(s) to axis ' + f'units: {x!r}') from e + return ret + + def get_converter(self): + """ + Get the unit converter for axis. + + Returns + ------- + `~matplotlib.units.ConversionInterface` or None + """ + return self._converter + + def set_converter(self, converter): + """ + Set the unit converter for axis. + + Parameters + ---------- + converter : `~matplotlib.units.ConversionInterface` + """ + self._set_converter(converter) + self._converter_is_explicit = True + + def _set_converter(self, converter): + if self._converter is converter or self._converter == converter: + return + if self._converter_is_explicit: + raise RuntimeError("Axis already has an explicit converter set") + elif ( + self._converter is not None and + not isinstance(converter, type(self._converter)) and + not isinstance(self._converter, type(converter)) + ): + _api.warn_external( + "This axis already has a converter set and " + "is updating to a potentially incompatible converter" + ) + self._converter = converter + + def set_units(self, u): + """ + Set the units for axis. + + Parameters + ---------- + u : units tag + + Notes + ----- + The units of any shared axis will also be updated. + """ + if u == self.units: + return + for axis in self._get_shared_axis(): + axis.units = u + axis._update_axisinfo() + axis.callbacks.process('units') + axis.stale = True + + def get_units(self): + """Return the units for axis.""" + return self.units + + def set_label_text(self, label, fontdict=None, **kwargs): + """ + Set the text value of the axis label. + + Parameters + ---------- + label : str + Text string. + fontdict : dict + Text properties. + + .. admonition:: Discouraged + + The use of *fontdict* is discouraged. Parameters should be passed as + individual keyword arguments or using dictionary-unpacking + ``set_label_text(..., **fontdict)``. + + **kwargs + Merged into fontdict. + """ + self.isDefault_label = False + self.label.set_text(label) + if fontdict is not None: + self.label.update(fontdict) + self.label.update(kwargs) + self.stale = True + return self.label + + def set_major_formatter(self, formatter): + """ + Set the formatter of the major ticker. + + In addition to a `~matplotlib.ticker.Formatter` instance, + this also accepts a ``str`` or function. + + For a ``str`` a `~matplotlib.ticker.StrMethodFormatter` is used. + The field used for the value must be labeled ``'x'`` and the field used + for the position must be labeled ``'pos'``. + See the `~matplotlib.ticker.StrMethodFormatter` documentation for + more information. + + For a function, a `~matplotlib.ticker.FuncFormatter` is used. + The function must take two inputs (a tick value ``x`` and a + position ``pos``), and return a string containing the corresponding + tick label. + See the `~matplotlib.ticker.FuncFormatter` documentation for + more information. + + Parameters + ---------- + formatter : `~matplotlib.ticker.Formatter`, ``str``, or function + """ + self._set_formatter(formatter, self.major) + + def set_minor_formatter(self, formatter): + """ + Set the formatter of the minor ticker. + + In addition to a `~matplotlib.ticker.Formatter` instance, + this also accepts a ``str`` or function. + See `.Axis.set_major_formatter` for more information. + + Parameters + ---------- + formatter : `~matplotlib.ticker.Formatter`, ``str``, or function + """ + self._set_formatter(formatter, self.minor) + + def _set_formatter(self, formatter, level): + if isinstance(formatter, str): + formatter = mticker.StrMethodFormatter(formatter) + # Don't allow any other TickHelper to avoid easy-to-make errors, + # like using a Locator instead of a Formatter. + elif (callable(formatter) and + not isinstance(formatter, mticker.TickHelper)): + formatter = mticker.FuncFormatter(formatter) + else: + _api.check_isinstance(mticker.Formatter, formatter=formatter) + + if (isinstance(formatter, mticker.FixedFormatter) + and len(formatter.seq) > 0 + and not isinstance(level.locator, mticker.FixedLocator)): + _api.warn_external('FixedFormatter should only be used together ' + 'with FixedLocator') + + if level == self.major: + self.isDefault_majfmt = False + else: + self.isDefault_minfmt = False + + level.formatter = formatter + formatter.set_axis(self) + self.stale = True + + def set_major_locator(self, locator): + """ + Set the locator of the major ticker. + + Parameters + ---------- + locator : `~matplotlib.ticker.Locator` + """ + _api.check_isinstance(mticker.Locator, locator=locator) + self.isDefault_majloc = False + self.major.locator = locator + if self.major.formatter: + self.major.formatter._set_locator(locator) + locator.set_axis(self) + self.stale = True + + def set_minor_locator(self, locator): + """ + Set the locator of the minor ticker. + + Parameters + ---------- + locator : `~matplotlib.ticker.Locator` + """ + _api.check_isinstance(mticker.Locator, locator=locator) + self.isDefault_minloc = False + self.minor.locator = locator + if self.minor.formatter: + self.minor.formatter._set_locator(locator) + locator.set_axis(self) + self.stale = True + + def set_pickradius(self, pickradius): + """ + Set the depth of the axis used by the picker. + + Parameters + ---------- + pickradius : float + The acceptance radius for containment tests. + See also `.Axis.contains`. + """ + if not isinstance(pickradius, Real) or pickradius < 0: + raise ValueError("pick radius should be a distance") + self._pickradius = pickradius + + pickradius = property( + get_pickradius, set_pickradius, doc="The acceptance radius for " + "containment tests. See also `.Axis.contains`.") + + # Helper for set_ticklabels. Defining it here makes it picklable. + @staticmethod + def _format_with_dict(tickd, x, pos): + return tickd.get(x, "") + + def set_ticklabels(self, labels, *, minor=False, fontdict=None, **kwargs): + r""" + [*Discouraged*] Set this Axis' tick labels with list of string labels. + + .. admonition:: Discouraged + + The use of this method is discouraged, because of the dependency on + tick positions. In most cases, you'll want to use + ``Axes.set_[x/y/z]ticks(positions, labels)`` or ``Axis.set_ticks`` + instead. + + If you are using this method, you should always fix the tick + positions before, e.g. by using `.Axis.set_ticks` or by explicitly + setting a `~.ticker.FixedLocator`. Otherwise, ticks are free to + move and the labels may end up in unexpected positions. + + Parameters + ---------- + labels : sequence of str or of `.Text`\s + Texts for labeling each tick location in the sequence set by + `.Axis.set_ticks`; the number of labels must match the number of locations. + The labels are used as is, via a `.FixedFormatter` (without further + formatting). + + minor : bool + If True, set minor ticks instead of major ticks. + + fontdict : dict, optional + + .. admonition:: Discouraged + + The use of *fontdict* is discouraged. Parameters should be passed as + individual keyword arguments or using dictionary-unpacking + ``set_ticklabels(..., **fontdict)``. + + A dictionary controlling the appearance of the ticklabels. + The default *fontdict* is:: + + {'fontsize': rcParams['axes.titlesize'], + 'fontweight': rcParams['axes.titleweight'], + 'verticalalignment': 'baseline', + 'horizontalalignment': loc} + + **kwargs + Text properties. + + .. warning:: + + This only sets the properties of the current ticks, which is + only sufficient for static plots. + + Ticks are not guaranteed to be persistent. Various operations + can create, delete and modify the Tick instances. There is an + imminent risk that these settings can get lost if you work on + the figure further (including also panning/zooming on a + displayed figure). + + Use `.set_tick_params` instead if possible. + + Returns + ------- + list of `.Text`\s + For each tick, includes ``tick.label1`` if it is visible, then + ``tick.label2`` if it is visible, in that order. + """ + try: + labels = [t.get_text() if hasattr(t, 'get_text') else t + for t in labels] + except TypeError: + raise TypeError(f"{labels:=} must be a sequence") from None + locator = (self.get_minor_locator() if minor + else self.get_major_locator()) + if not labels: + # eg labels=[]: + formatter = mticker.NullFormatter() + elif isinstance(locator, mticker.FixedLocator): + # Passing [] as a list of labels is often used as a way to + # remove all tick labels, so only error for > 0 labels + if len(locator.locs) != len(labels) and len(labels) != 0: + raise ValueError( + "The number of FixedLocator locations" + f" ({len(locator.locs)}), usually from a call to" + " set_ticks, does not match" + f" the number of labels ({len(labels)}).") + tickd = {loc: lab for loc, lab in zip(locator.locs, labels)} + func = functools.partial(self._format_with_dict, tickd) + formatter = mticker.FuncFormatter(func) + else: + _api.warn_external( + "set_ticklabels() should only be used with a fixed number of " + "ticks, i.e. after set_ticks() or using a FixedLocator.") + formatter = mticker.FixedFormatter(labels) + + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message="FixedFormatter should only be used together with FixedLocator") + if minor: + self.set_minor_formatter(formatter) + locs = self.get_minorticklocs() + ticks = self.get_minor_ticks(len(locs)) + else: + self.set_major_formatter(formatter) + locs = self.get_majorticklocs() + ticks = self.get_major_ticks(len(locs)) + + ret = [] + if fontdict is not None: + kwargs.update(fontdict) + for pos, (loc, tick) in enumerate(zip(locs, ticks)): + tick.update_position(loc) + tick_label = formatter(loc, pos) + # deal with label1 + tick.label1.set_text(tick_label) + tick.label1._internal_update(kwargs) + # deal with label2 + tick.label2.set_text(tick_label) + tick.label2._internal_update(kwargs) + # only return visible tick labels + if tick.label1.get_visible(): + ret.append(tick.label1) + if tick.label2.get_visible(): + ret.append(tick.label2) + + self.stale = True + return ret + + def _set_tick_locations(self, ticks, *, minor=False): + # see docstring of set_ticks + + # XXX if the user changes units, the information will be lost here + ticks = self.convert_units(ticks) + locator = mticker.FixedLocator(ticks) # validate ticks early. + if len(ticks): + for axis in self._get_shared_axis(): + # set_view_interval maintains any preexisting inversion. + axis.set_view_interval(min(ticks), max(ticks)) + self.axes.stale = True + if minor: + self.set_minor_locator(locator) + return self.get_minor_ticks(len(ticks)) + else: + self.set_major_locator(locator) + return self.get_major_ticks(len(ticks)) + + def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs): + """ + Set this Axis' tick locations and optionally tick labels. + + If necessary, the view limits of the Axis are expanded so that all + given ticks are visible. + + Parameters + ---------- + ticks : 1D array-like + Array of tick locations (either floats or in axis units). The axis + `.Locator` is replaced by a `~.ticker.FixedLocator`. + + Pass an empty list (``set_ticks([])``) to remove all ticks. + + Some tick formatters will not label arbitrary tick positions; + e.g. log formatters only label decade ticks by default. In + such a case you can set a formatter explicitly on the axis + using `.Axis.set_major_formatter` or provide formatted + *labels* yourself. + + labels : list of str, optional + Tick labels for each location in *ticks*; must have the same length as + *ticks*. If set, the labels are used as is, via a `.FixedFormatter`. + If not set, the labels are generated using the axis tick `.Formatter`. + + minor : bool, default: False + If ``False``, set only the major ticks; if ``True``, only the minor ticks. + + **kwargs + `.Text` properties for the labels. Using these is only allowed if + you pass *labels*. In other cases, please use `~.Axes.tick_params`. + + Notes + ----- + The mandatory expansion of the view limits is an intentional design + choice to prevent the surprise of a non-visible tick. If you need + other limits, you should set the limits explicitly after setting the + ticks. + """ + if labels is None and kwargs: + first_key = next(iter(kwargs)) + raise ValueError( + f"Incorrect use of keyword argument {first_key!r}. Keyword arguments " + "other than 'minor' modify the text labels and can only be used if " + "'labels' are passed as well.") + result = self._set_tick_locations(ticks, minor=minor) + if labels is not None: + self.set_ticklabels(labels, minor=minor, **kwargs) + return result + + def _get_tick_boxes_siblings(self, renderer): + """ + Get the bounding boxes for this `.axis` and its siblings + as set by `.Figure.align_xlabels` or `.Figure.align_ylabels`. + + By default, it just gets bboxes for *self*. + """ + # Get the Grouper keeping track of x or y label groups for this figure. + name = self._get_axis_name() + if name not in self.get_figure(root=False)._align_label_groups: + return [], [] + grouper = self.get_figure(root=False)._align_label_groups[name] + bboxes = [] + bboxes2 = [] + # If we want to align labels from other Axes: + for ax in grouper.get_siblings(self.axes): + axis = ax._axis_map[name] + ticks_to_draw = axis._update_ticks() + tlb, tlb2 = axis._get_ticklabel_bboxes(ticks_to_draw, renderer) + bboxes.extend(tlb) + bboxes2.extend(tlb2) + return bboxes, bboxes2 + + def _update_label_position(self, renderer): + """ + Update the label position based on the bounding box enclosing + all the ticklabels and axis spine. + """ + raise NotImplementedError('Derived must override') + + def _update_offset_text_position(self, bboxes, bboxes2): + """ + Update the offset text position based on the sequence of bounding + boxes of all the ticklabels. + """ + raise NotImplementedError('Derived must override') + + def axis_date(self, tz=None): + """ + Set up axis ticks and labels to treat data along this Axis as dates. + + Parameters + ---------- + tz : str or `datetime.tzinfo`, default: :rc:`timezone` + The timezone used to create date labels. + """ + # By providing a sample datetime instance with the desired timezone, + # the registered converter can be selected, and the "units" attribute, + # which is the timezone, can be set. + if isinstance(tz, str): + import dateutil.tz + tz = dateutil.tz.gettz(tz) + self.update_units(datetime.datetime(2009, 1, 1, 0, 0, 0, 0, tz)) + + def get_tick_space(self): + """Return the estimated number of ticks that can fit on the axis.""" + # Must be overridden in the subclass + raise NotImplementedError() + + def _get_ticks_position(self): + """ + Helper for `XAxis.get_ticks_position` and `YAxis.get_ticks_position`. + + Check the visibility of tick1line, label1, tick2line, and label2 on + the first major and the first minor ticks, and return + + - 1 if only tick1line and label1 are visible (which corresponds to + "bottom" for the x-axis and "left" for the y-axis); + - 2 if only tick2line and label2 are visible (which corresponds to + "top" for the x-axis and "right" for the y-axis); + - "default" if only tick1line, tick2line and label1 are visible; + - "unknown" otherwise. + """ + major = self.majorTicks[0] + minor = self.minorTicks[0] + if all(tick.tick1line.get_visible() + and not tick.tick2line.get_visible() + and tick.label1.get_visible() + and not tick.label2.get_visible() + for tick in [major, minor]): + return 1 + elif all(tick.tick2line.get_visible() + and not tick.tick1line.get_visible() + and tick.label2.get_visible() + and not tick.label1.get_visible() + for tick in [major, minor]): + return 2 + elif all(tick.tick1line.get_visible() + and tick.tick2line.get_visible() + and tick.label1.get_visible() + and not tick.label2.get_visible() + for tick in [major, minor]): + return "default" + else: + return "unknown" + + def get_label_position(self): + """ + Return the label position (top or bottom) + """ + return self.label_position + + def set_label_position(self, position): + """ + Set the label position (top or bottom) + + Parameters + ---------- + position : {'top', 'bottom'} + """ + raise NotImplementedError() + + def get_minpos(self): + raise NotImplementedError() + + +def _make_getset_interval(method_name, lim_name, attr_name): + """ + Helper to generate ``get_{data,view}_interval`` and + ``set_{data,view}_interval`` implementations. + """ + + def getter(self): + # docstring inherited. + return getattr(getattr(self.axes, lim_name), attr_name) + + def setter(self, vmin, vmax, ignore=False): + # docstring inherited. + if ignore: + setattr(getattr(self.axes, lim_name), attr_name, (vmin, vmax)) + else: + oldmin, oldmax = getter(self) + if oldmin < oldmax: + setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax), + ignore=True) + else: + setter(self, max(vmin, vmax, oldmin), min(vmin, vmax, oldmax), + ignore=True) + self.stale = True + + getter.__name__ = f"get_{method_name}_interval" + setter.__name__ = f"set_{method_name}_interval" + + return getter, setter + + +class XAxis(Axis): + __name__ = 'xaxis' + axis_name = 'x' #: Read-only name identifying the axis. + _tick_class = XTick + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._init() + + def _init(self): + """ + Initialize the label and offsetText instance values and + `label_position` / `offset_text_position`. + """ + # x in axes coords, y in display coords (to be updated at draw time by + # _update_label_positions and _update_offset_text_position). + self.label.set( + x=0.5, y=0, + verticalalignment='top', horizontalalignment='center', + transform=mtransforms.blended_transform_factory( + self.axes.transAxes, mtransforms.IdentityTransform()), + ) + self.label_position = 'bottom' + + if mpl.rcParams['xtick.labelcolor'] == 'inherit': + tick_color = mpl.rcParams['xtick.color'] + else: + tick_color = mpl.rcParams['xtick.labelcolor'] + + self.offsetText.set( + x=1, y=0, + verticalalignment='top', horizontalalignment='right', + transform=mtransforms.blended_transform_factory( + self.axes.transAxes, mtransforms.IdentityTransform()), + fontsize=mpl.rcParams['xtick.labelsize'], + color=tick_color + ) + self.offset_text_position = 'bottom' + + def contains(self, mouseevent): + """Test whether the mouse event occurred in the x-axis.""" + if self._different_canvas(mouseevent): + return False, {} + x, y = mouseevent.x, mouseevent.y + try: + trans = self.axes.transAxes.inverted() + xaxes, yaxes = trans.transform((x, y)) + except ValueError: + return False, {} + (l, b), (r, t) = self.axes.transAxes.transform([(0, 0), (1, 1)]) + inaxis = 0 <= xaxes <= 1 and ( + b - self._pickradius < y < b or + t < y < t + self._pickradius) + return inaxis, {} + + def set_label_position(self, position): + """ + Set the label position (top or bottom) + + Parameters + ---------- + position : {'top', 'bottom'} + """ + self.label.set_verticalalignment(_api.check_getitem({ + 'top': 'baseline', 'bottom': 'top', + }, position=position)) + self.label_position = position + self.stale = True + + def _update_label_position(self, renderer): + """ + Update the label position based on the bounding box enclosing + all the ticklabels and axis spine + """ + if not self._autolabelpos: + return + + # get bounding boxes for this axis and any siblings + # that have been set by `fig.align_xlabels()` + bboxes, bboxes2 = self._get_tick_boxes_siblings(renderer=renderer) + x, y = self.label.get_position() + + if self.label_position == 'bottom': + # Union with extents of the bottom spine if present, of the axes otherwise. + bbox = mtransforms.Bbox.union([ + *bboxes, self.axes.spines.get("bottom", self.axes).get_window_extent()]) + self.label.set_position( + (x, bbox.y0 - self.labelpad * self.get_figure(root=True).dpi / 72)) + else: + # Union with extents of the top spine if present, of the axes otherwise. + bbox = mtransforms.Bbox.union([ + *bboxes2, self.axes.spines.get("top", self.axes).get_window_extent()]) + self.label.set_position( + (x, bbox.y1 + self.labelpad * self.get_figure(root=True).dpi / 72)) + + def _update_offset_text_position(self, bboxes, bboxes2): + """ + Update the offset_text position based on the sequence of bounding + boxes of all the ticklabels + """ + x, y = self.offsetText.get_position() + if not hasattr(self, '_tick_position'): + self._tick_position = 'bottom' + if self._tick_position == 'bottom': + if not len(bboxes): + bottom = self.axes.bbox.ymin + else: + bbox = mtransforms.Bbox.union(bboxes) + bottom = bbox.y0 + y = bottom - self.OFFSETTEXTPAD * self.get_figure(root=True).dpi / 72 + else: + if not len(bboxes2): + top = self.axes.bbox.ymax + else: + bbox = mtransforms.Bbox.union(bboxes2) + top = bbox.y1 + y = top + self.OFFSETTEXTPAD * self.get_figure(root=True).dpi / 72 + self.offsetText.set_position((x, y)) + + def set_ticks_position(self, position): + """ + Set the ticks position. + + Parameters + ---------- + position : {'top', 'bottom', 'both', 'default', 'none'} + 'both' sets the ticks to appear on both positions, but does not + change the tick labels. 'default' resets the tick positions to + the default: ticks on both positions, labels at bottom. 'none' + can be used if you don't want any ticks. 'none' and 'both' + affect only the ticks, not the labels. + """ + if position == 'top': + self.set_tick_params(which='both', top=True, labeltop=True, + bottom=False, labelbottom=False) + self._tick_position = 'top' + self.offsetText.set_verticalalignment('bottom') + elif position == 'bottom': + self.set_tick_params(which='both', top=False, labeltop=False, + bottom=True, labelbottom=True) + self._tick_position = 'bottom' + self.offsetText.set_verticalalignment('top') + elif position == 'both': + self.set_tick_params(which='both', top=True, + bottom=True) + elif position == 'none': + self.set_tick_params(which='both', top=False, + bottom=False) + elif position == 'default': + self.set_tick_params(which='both', top=True, labeltop=False, + bottom=True, labelbottom=True) + self._tick_position = 'bottom' + self.offsetText.set_verticalalignment('top') + else: + _api.check_in_list(['top', 'bottom', 'both', 'default', 'none'], + position=position) + self.stale = True + + def tick_top(self): + """ + Move ticks and ticklabels (if present) to the top of the Axes. + """ + label = True + if 'label1On' in self._major_tick_kw: + label = (self._major_tick_kw['label1On'] + or self._major_tick_kw['label2On']) + self.set_ticks_position('top') + # If labels were turned off before this was called, leave them off. + self.set_tick_params(which='both', labeltop=label) + + def tick_bottom(self): + """ + Move ticks and ticklabels (if present) to the bottom of the Axes. + """ + label = True + if 'label1On' in self._major_tick_kw: + label = (self._major_tick_kw['label1On'] + or self._major_tick_kw['label2On']) + self.set_ticks_position('bottom') + # If labels were turned off before this was called, leave them off. + self.set_tick_params(which='both', labelbottom=label) + + def get_ticks_position(self): + """ + Return the ticks position ("top", "bottom", "default", or "unknown"). + """ + return {1: "bottom", 2: "top", + "default": "default", "unknown": "unknown"}[ + self._get_ticks_position()] + + get_view_interval, set_view_interval = _make_getset_interval( + "view", "viewLim", "intervalx") + get_data_interval, set_data_interval = _make_getset_interval( + "data", "dataLim", "intervalx") + + def get_minpos(self): + return self.axes.dataLim.minposx + + def set_default_intervals(self): + # docstring inherited + # only change view if dataLim has not changed and user has + # not changed the view: + if (not self.axes.dataLim.mutatedx() and + not self.axes.viewLim.mutatedx()): + if self._converter is not None: + info = self._converter.axisinfo(self.units, self) + if info.default_limits is not None: + xmin, xmax = self.convert_units(info.default_limits) + self.axes.viewLim.intervalx = xmin, xmax + self.stale = True + + def get_tick_space(self): + ends = mtransforms.Bbox.unit().transformed( + self.axes.transAxes - self.get_figure(root=False).dpi_scale_trans) + length = ends.width * 72 + # There is a heuristic here that the aspect ratio of tick text + # is no more than 3:1 + size = self._get_tick_label_size('x') * 3 + if size > 0: + return int(np.floor(length / size)) + else: + return 2**31 - 1 + + +class YAxis(Axis): + __name__ = 'yaxis' + axis_name = 'y' #: Read-only name identifying the axis. + _tick_class = YTick + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._init() + + def _init(self): + """ + Initialize the label and offsetText instance values and + `label_position` / `offset_text_position`. + """ + # x in display coords, y in axes coords (to be updated at draw time by + # _update_label_positions and _update_offset_text_position). + self.label.set( + x=0, y=0.5, + verticalalignment='bottom', horizontalalignment='center', + rotation='vertical', rotation_mode='anchor', + transform=mtransforms.blended_transform_factory( + mtransforms.IdentityTransform(), self.axes.transAxes), + ) + self.label_position = 'left' + + if mpl.rcParams['ytick.labelcolor'] == 'inherit': + tick_color = mpl.rcParams['ytick.color'] + else: + tick_color = mpl.rcParams['ytick.labelcolor'] + + # x in axes coords, y in display coords(!). + self.offsetText.set( + x=0, y=0.5, + verticalalignment='baseline', horizontalalignment='left', + transform=mtransforms.blended_transform_factory( + self.axes.transAxes, mtransforms.IdentityTransform()), + fontsize=mpl.rcParams['ytick.labelsize'], + color=tick_color + ) + self.offset_text_position = 'left' + + def contains(self, mouseevent): + # docstring inherited + if self._different_canvas(mouseevent): + return False, {} + x, y = mouseevent.x, mouseevent.y + try: + trans = self.axes.transAxes.inverted() + xaxes, yaxes = trans.transform((x, y)) + except ValueError: + return False, {} + (l, b), (r, t) = self.axes.transAxes.transform([(0, 0), (1, 1)]) + inaxis = 0 <= yaxes <= 1 and ( + l - self._pickradius < x < l or + r < x < r + self._pickradius) + return inaxis, {} + + def set_label_position(self, position): + """ + Set the label position (left or right) + + Parameters + ---------- + position : {'left', 'right'} + """ + self.label.set_rotation_mode('anchor') + self.label.set_verticalalignment(_api.check_getitem({ + 'left': 'bottom', 'right': 'top', + }, position=position)) + self.label_position = position + self.stale = True + + def _update_label_position(self, renderer): + """ + Update the label position based on the bounding box enclosing + all the ticklabels and axis spine + """ + if not self._autolabelpos: + return + + # get bounding boxes for this axis and any siblings + # that have been set by `fig.align_ylabels()` + bboxes, bboxes2 = self._get_tick_boxes_siblings(renderer=renderer) + x, y = self.label.get_position() + + if self.label_position == 'left': + # Union with extents of the left spine if present, of the axes otherwise. + bbox = mtransforms.Bbox.union([ + *bboxes, self.axes.spines.get("left", self.axes).get_window_extent()]) + self.label.set_position( + (bbox.x0 - self.labelpad * self.get_figure(root=True).dpi / 72, y)) + else: + # Union with extents of the right spine if present, of the axes otherwise. + bbox = mtransforms.Bbox.union([ + *bboxes2, self.axes.spines.get("right", self.axes).get_window_extent()]) + self.label.set_position( + (bbox.x1 + self.labelpad * self.get_figure(root=True).dpi / 72, y)) + + def _update_offset_text_position(self, bboxes, bboxes2): + """ + Update the offset_text position based on the sequence of bounding + boxes of all the ticklabels + """ + x, _ = self.offsetText.get_position() + if 'outline' in self.axes.spines: + # Special case for colorbars: + bbox = self.axes.spines['outline'].get_window_extent() + else: + bbox = self.axes.bbox + top = bbox.ymax + self.offsetText.set_position( + (x, top + self.OFFSETTEXTPAD * self.get_figure(root=True).dpi / 72) + ) + + def set_offset_position(self, position): + """ + Parameters + ---------- + position : {'left', 'right'} + """ + x, y = self.offsetText.get_position() + x = _api.check_getitem({'left': 0, 'right': 1}, position=position) + + self.offsetText.set_ha(position) + self.offsetText.set_position((x, y)) + self.stale = True + + def set_ticks_position(self, position): + """ + Set the ticks position. + + Parameters + ---------- + position : {'left', 'right', 'both', 'default', 'none'} + 'both' sets the ticks to appear on both positions, but does not + change the tick labels. 'default' resets the tick positions to + the default: ticks on both positions, labels at left. 'none' + can be used if you don't want any ticks. 'none' and 'both' + affect only the ticks, not the labels. + """ + if position == 'right': + self.set_tick_params(which='both', right=True, labelright=True, + left=False, labelleft=False) + self.set_offset_position(position) + elif position == 'left': + self.set_tick_params(which='both', right=False, labelright=False, + left=True, labelleft=True) + self.set_offset_position(position) + elif position == 'both': + self.set_tick_params(which='both', right=True, + left=True) + elif position == 'none': + self.set_tick_params(which='both', right=False, + left=False) + elif position == 'default': + self.set_tick_params(which='both', right=True, labelright=False, + left=True, labelleft=True) + else: + _api.check_in_list(['left', 'right', 'both', 'default', 'none'], + position=position) + self.stale = True + + def tick_right(self): + """ + Move ticks and ticklabels (if present) to the right of the Axes. + """ + label = True + if 'label1On' in self._major_tick_kw: + label = (self._major_tick_kw['label1On'] + or self._major_tick_kw['label2On']) + self.set_ticks_position('right') + # if labels were turned off before this was called + # leave them off + self.set_tick_params(which='both', labelright=label) + + def tick_left(self): + """ + Move ticks and ticklabels (if present) to the left of the Axes. + """ + label = True + if 'label1On' in self._major_tick_kw: + label = (self._major_tick_kw['label1On'] + or self._major_tick_kw['label2On']) + self.set_ticks_position('left') + # if labels were turned off before this was called + # leave them off + self.set_tick_params(which='both', labelleft=label) + + def get_ticks_position(self): + """ + Return the ticks position ("left", "right", "default", or "unknown"). + """ + return {1: "left", 2: "right", + "default": "default", "unknown": "unknown"}[ + self._get_ticks_position()] + + get_view_interval, set_view_interval = _make_getset_interval( + "view", "viewLim", "intervaly") + get_data_interval, set_data_interval = _make_getset_interval( + "data", "dataLim", "intervaly") + + def get_minpos(self): + return self.axes.dataLim.minposy + + def set_default_intervals(self): + # docstring inherited + # only change view if dataLim has not changed and user has + # not changed the view: + if (not self.axes.dataLim.mutatedy() and + not self.axes.viewLim.mutatedy()): + if self._converter is not None: + info = self._converter.axisinfo(self.units, self) + if info.default_limits is not None: + ymin, ymax = self.convert_units(info.default_limits) + self.axes.viewLim.intervaly = ymin, ymax + self.stale = True + + def get_tick_space(self): + ends = mtransforms.Bbox.unit().transformed( + self.axes.transAxes - self.get_figure(root=False).dpi_scale_trans) + length = ends.height * 72 + # Having a spacing of at least 2 just looks good. + size = self._get_tick_label_size('y') * 2 + if size > 0: + return int(np.floor(length / size)) + else: + return 2**31 - 1 diff --git a/moondream/lib/python3.10/site-packages/matplotlib/backend_tools.py b/moondream/lib/python3.10/site-packages/matplotlib/backend_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..87ed794022a0eee732da01ac9627b84020c83013 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/backend_tools.py @@ -0,0 +1,998 @@ +""" +Abstract base classes define the primitives for Tools. +These tools are used by `matplotlib.backend_managers.ToolManager` + +:class:`ToolBase` + Simple stateless tool + +:class:`ToolToggleBase` + Tool that has two states, only one Toggle tool can be + active at any given time for the same + `matplotlib.backend_managers.ToolManager` +""" + +import enum +import functools +import re +import time +from types import SimpleNamespace +import uuid +from weakref import WeakKeyDictionary + +import numpy as np + +import matplotlib as mpl +from matplotlib._pylab_helpers import Gcf +from matplotlib import _api, cbook + + +class Cursors(enum.IntEnum): # Must subclass int for the macOS backend. + """Backend-independent cursor types.""" + POINTER = enum.auto() + HAND = enum.auto() + SELECT_REGION = enum.auto() + MOVE = enum.auto() + WAIT = enum.auto() + RESIZE_HORIZONTAL = enum.auto() + RESIZE_VERTICAL = enum.auto() +cursors = Cursors # Backcompat. + + +# _tool_registry, _register_tool_class, and _find_tool_class implement a +# mechanism through which ToolManager.add_tool can determine whether a subclass +# of the requested tool class has been registered (either for the current +# canvas class or for a parent class), in which case that tool subclass will be +# instantiated instead. This is the mechanism used e.g. to allow different +# GUI backends to implement different specializations for ConfigureSubplots. + + +_tool_registry = set() + + +def _register_tool_class(canvas_cls, tool_cls=None): + """Decorator registering *tool_cls* as a tool class for *canvas_cls*.""" + if tool_cls is None: + return functools.partial(_register_tool_class, canvas_cls) + _tool_registry.add((canvas_cls, tool_cls)) + return tool_cls + + +def _find_tool_class(canvas_cls, tool_cls): + """Find a subclass of *tool_cls* registered for *canvas_cls*.""" + for canvas_parent in canvas_cls.__mro__: + for tool_child in _api.recursive_subclasses(tool_cls): + if (canvas_parent, tool_child) in _tool_registry: + return tool_child + return tool_cls + + +# Views positions tool +_views_positions = 'viewpos' + + +class ToolBase: + """ + Base tool class. + + A base tool, only implements `trigger` method or no method at all. + The tool is instantiated by `matplotlib.backend_managers.ToolManager`. + """ + + default_keymap = None + """ + Keymap to associate with this tool. + + ``list[str]``: List of keys that will trigger this tool when a keypress + event is emitted on ``self.figure.canvas``. Note that this attribute is + looked up on the instance, and can therefore be a property (this is used + e.g. by the built-in tools to load the rcParams at instantiation time). + """ + + description = None + """ + Description of the Tool. + + `str`: Tooltip used if the Tool is included in a Toolbar. + """ + + image = None + """ + Icon filename. + + ``str | None``: Filename of the Toolbar icon; either absolute, or relative to the + directory containing the Python source file where the ``Tool.image`` class attribute + is defined (in the latter case, this cannot be defined as an instance attribute). + In either case, the extension is optional; leaving it off lets individual backends + select the icon format they prefer. If None, the *name* is used as a label in the + toolbar button. + """ + + def __init__(self, toolmanager, name): + self._name = name + self._toolmanager = toolmanager + self._figure = None + + name = property( + lambda self: self._name, + doc="The tool id (str, must be unique among tools of a tool manager).") + toolmanager = property( + lambda self: self._toolmanager, + doc="The `.ToolManager` that controls this tool.") + canvas = property( + lambda self: self._figure.canvas if self._figure is not None else None, + doc="The canvas of the figure affected by this tool, or None.") + + def set_figure(self, figure): + self._figure = figure + + figure = property( + lambda self: self._figure, + # The setter must explicitly call self.set_figure so that subclasses can + # meaningfully override it. + lambda self, figure: self.set_figure(figure), + doc="The Figure affected by this tool, or None.") + + def _make_classic_style_pseudo_toolbar(self): + """ + Return a placeholder object with a single `canvas` attribute. + + This is useful to reuse the implementations of tools already provided + by the classic Toolbars. + """ + return SimpleNamespace(canvas=self.canvas) + + def trigger(self, sender, event, data=None): + """ + Called when this tool gets used. + + This method is called by `.ToolManager.trigger_tool`. + + Parameters + ---------- + event : `.Event` + The canvas event that caused this tool to be called. + sender : object + Object that requested the tool to be triggered. + data : object + Extra data. + """ + pass + + +class ToolToggleBase(ToolBase): + """ + Toggleable tool. + + Every time it is triggered, it switches between enable and disable. + + Parameters + ---------- + ``*args`` + Variable length argument to be used by the Tool. + ``**kwargs`` + `toggled` if present and True, sets the initial state of the Tool + Arbitrary keyword arguments to be consumed by the Tool + """ + + radio_group = None + """ + Attribute to group 'radio' like tools (mutually exclusive). + + `str` that identifies the group or **None** if not belonging to a group. + """ + + cursor = None + """Cursor to use when the tool is active.""" + + default_toggled = False + """Default of toggled state.""" + + def __init__(self, *args, **kwargs): + self._toggled = kwargs.pop('toggled', self.default_toggled) + super().__init__(*args, **kwargs) + + def trigger(self, sender, event, data=None): + """Calls `enable` or `disable` based on `toggled` value.""" + if self._toggled: + self.disable(event) + else: + self.enable(event) + self._toggled = not self._toggled + + def enable(self, event=None): + """ + Enable the toggle tool. + + `trigger` calls this method when `toggled` is False. + """ + pass + + def disable(self, event=None): + """ + Disable the toggle tool. + + `trigger` call this method when `toggled` is True. + + This can happen in different circumstances. + + * Click on the toolbar tool button. + * Call to `matplotlib.backend_managers.ToolManager.trigger_tool`. + * Another `ToolToggleBase` derived tool is triggered + (from the same `.ToolManager`). + """ + pass + + @property + def toggled(self): + """State of the toggled tool.""" + return self._toggled + + def set_figure(self, figure): + toggled = self.toggled + if toggled: + if self.figure: + self.trigger(self, None) + else: + # if no figure the internal state is not changed + # we change it here so next call to trigger will change it back + self._toggled = False + super().set_figure(figure) + if toggled: + if figure: + self.trigger(self, None) + else: + # if there is no figure, trigger won't change the internal + # state we change it back + self._toggled = True + + +class ToolSetCursor(ToolBase): + """ + Change to the current cursor while inaxes. + + This tool, keeps track of all `ToolToggleBase` derived tools, and updates + the cursor when a tool gets triggered. + """ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._id_drag = None + self._current_tool = None + self._default_cursor = cursors.POINTER + self._last_cursor = self._default_cursor + self.toolmanager.toolmanager_connect('tool_added_event', + self._add_tool_cbk) + for tool in self.toolmanager.tools.values(): # process current tools + self._add_tool_cbk(mpl.backend_managers.ToolEvent( + 'tool_added_event', self.toolmanager, tool)) + + def set_figure(self, figure): + if self._id_drag: + self.canvas.mpl_disconnect(self._id_drag) + super().set_figure(figure) + if figure: + self._id_drag = self.canvas.mpl_connect( + 'motion_notify_event', self._set_cursor_cbk) + + def _add_tool_cbk(self, event): + """Process every newly added tool.""" + if getattr(event.tool, 'cursor', None) is not None: + self.toolmanager.toolmanager_connect( + f'tool_trigger_{event.tool.name}', self._tool_trigger_cbk) + + def _tool_trigger_cbk(self, event): + self._current_tool = event.tool if event.tool.toggled else None + self._set_cursor_cbk(event.canvasevent) + + def _set_cursor_cbk(self, event): + if not event or not self.canvas: + return + if (self._current_tool and getattr(event, "inaxes", None) + and event.inaxes.get_navigate()): + if self._last_cursor != self._current_tool.cursor: + self.canvas.set_cursor(self._current_tool.cursor) + self._last_cursor = self._current_tool.cursor + elif self._last_cursor != self._default_cursor: + self.canvas.set_cursor(self._default_cursor) + self._last_cursor = self._default_cursor + + +class ToolCursorPosition(ToolBase): + """ + Send message with the current pointer position. + + This tool runs in the background reporting the position of the cursor. + """ + def __init__(self, *args, **kwargs): + self._id_drag = None + super().__init__(*args, **kwargs) + + def set_figure(self, figure): + if self._id_drag: + self.canvas.mpl_disconnect(self._id_drag) + super().set_figure(figure) + if figure: + self._id_drag = self.canvas.mpl_connect( + 'motion_notify_event', self.send_message) + + def send_message(self, event): + """Call `matplotlib.backend_managers.ToolManager.message_event`.""" + if self.toolmanager.messagelock.locked(): + return + + from matplotlib.backend_bases import NavigationToolbar2 + message = NavigationToolbar2._mouse_event_to_message(event) + self.toolmanager.message_event(message, self) + + +class RubberbandBase(ToolBase): + """Draw and remove a rubberband.""" + def trigger(self, sender, event, data=None): + """Call `draw_rubberband` or `remove_rubberband` based on data.""" + if not self.figure.canvas.widgetlock.available(sender): + return + if data is not None: + self.draw_rubberband(*data) + else: + self.remove_rubberband() + + def draw_rubberband(self, *data): + """ + Draw rubberband. + + This method must get implemented per backend. + """ + raise NotImplementedError + + def remove_rubberband(self): + """ + Remove rubberband. + + This method should get implemented per backend. + """ + pass + + +class ToolQuit(ToolBase): + """Tool to call the figure manager destroy method.""" + + description = 'Quit the figure' + default_keymap = property(lambda self: mpl.rcParams['keymap.quit']) + + def trigger(self, sender, event, data=None): + Gcf.destroy_fig(self.figure) + + +class ToolQuitAll(ToolBase): + """Tool to call the figure manager destroy method.""" + + description = 'Quit all figures' + default_keymap = property(lambda self: mpl.rcParams['keymap.quit_all']) + + def trigger(self, sender, event, data=None): + Gcf.destroy_all() + + +class ToolGrid(ToolBase): + """Tool to toggle the major grids of the figure.""" + + description = 'Toggle major grids' + default_keymap = property(lambda self: mpl.rcParams['keymap.grid']) + + def trigger(self, sender, event, data=None): + sentinel = str(uuid.uuid4()) + # Trigger grid switching by temporarily setting :rc:`keymap.grid` + # to a unique key and sending an appropriate event. + with (cbook._setattr_cm(event, key=sentinel), + mpl.rc_context({'keymap.grid': sentinel})): + mpl.backend_bases.key_press_handler(event, self.figure.canvas) + + +class ToolMinorGrid(ToolBase): + """Tool to toggle the major and minor grids of the figure.""" + + description = 'Toggle major and minor grids' + default_keymap = property(lambda self: mpl.rcParams['keymap.grid_minor']) + + def trigger(self, sender, event, data=None): + sentinel = str(uuid.uuid4()) + # Trigger grid switching by temporarily setting :rc:`keymap.grid_minor` + # to a unique key and sending an appropriate event. + with (cbook._setattr_cm(event, key=sentinel), + mpl.rc_context({'keymap.grid_minor': sentinel})): + mpl.backend_bases.key_press_handler(event, self.figure.canvas) + + +class ToolFullScreen(ToolBase): + """Tool to toggle full screen.""" + + description = 'Toggle fullscreen mode' + default_keymap = property(lambda self: mpl.rcParams['keymap.fullscreen']) + + def trigger(self, sender, event, data=None): + self.figure.canvas.manager.full_screen_toggle() + + +class AxisScaleBase(ToolToggleBase): + """Base Tool to toggle between linear and logarithmic.""" + + def trigger(self, sender, event, data=None): + if event.inaxes is None: + return + super().trigger(sender, event, data) + + def enable(self, event=None): + self.set_scale(event.inaxes, 'log') + self.figure.canvas.draw_idle() + + def disable(self, event=None): + self.set_scale(event.inaxes, 'linear') + self.figure.canvas.draw_idle() + + +class ToolYScale(AxisScaleBase): + """Tool to toggle between linear and logarithmic scales on the Y axis.""" + + description = 'Toggle scale Y axis' + default_keymap = property(lambda self: mpl.rcParams['keymap.yscale']) + + def set_scale(self, ax, scale): + ax.set_yscale(scale) + + +class ToolXScale(AxisScaleBase): + """Tool to toggle between linear and logarithmic scales on the X axis.""" + + description = 'Toggle scale X axis' + default_keymap = property(lambda self: mpl.rcParams['keymap.xscale']) + + def set_scale(self, ax, scale): + ax.set_xscale(scale) + + +class ToolViewsPositions(ToolBase): + """ + Auxiliary Tool to handle changes in views and positions. + + Runs in the background and should get used by all the tools that + need to access the figure's history of views and positions, e.g. + + * `ToolZoom` + * `ToolPan` + * `ToolHome` + * `ToolBack` + * `ToolForward` + """ + + def __init__(self, *args, **kwargs): + self.views = WeakKeyDictionary() + self.positions = WeakKeyDictionary() + self.home_views = WeakKeyDictionary() + super().__init__(*args, **kwargs) + + def add_figure(self, figure): + """Add the current figure to the stack of views and positions.""" + + if figure not in self.views: + self.views[figure] = cbook._Stack() + self.positions[figure] = cbook._Stack() + self.home_views[figure] = WeakKeyDictionary() + # Define Home + self.push_current(figure) + # Make sure we add a home view for new Axes as they're added + figure.add_axobserver(lambda fig: self.update_home_views(fig)) + + def clear(self, figure): + """Reset the Axes stack.""" + if figure in self.views: + self.views[figure].clear() + self.positions[figure].clear() + self.home_views[figure].clear() + self.update_home_views() + + def update_view(self): + """ + Update the view limits and position for each Axes from the current + stack position. If any Axes are present in the figure that aren't in + the current stack position, use the home view limits for those Axes and + don't update *any* positions. + """ + + views = self.views[self.figure]() + if views is None: + return + pos = self.positions[self.figure]() + if pos is None: + return + home_views = self.home_views[self.figure] + all_axes = self.figure.get_axes() + for a in all_axes: + if a in views: + cur_view = views[a] + else: + cur_view = home_views[a] + a._set_view(cur_view) + + if set(all_axes).issubset(pos): + for a in all_axes: + # Restore both the original and modified positions + a._set_position(pos[a][0], 'original') + a._set_position(pos[a][1], 'active') + + self.figure.canvas.draw_idle() + + def push_current(self, figure=None): + """ + Push the current view limits and position onto their respective stacks. + """ + if not figure: + figure = self.figure + views = WeakKeyDictionary() + pos = WeakKeyDictionary() + for a in figure.get_axes(): + views[a] = a._get_view() + pos[a] = self._axes_pos(a) + self.views[figure].push(views) + self.positions[figure].push(pos) + + def _axes_pos(self, ax): + """ + Return the original and modified positions for the specified Axes. + + Parameters + ---------- + ax : matplotlib.axes.Axes + The `.Axes` to get the positions for. + + Returns + ------- + original_position, modified_position + A tuple of the original and modified positions. + """ + + return (ax.get_position(True).frozen(), + ax.get_position().frozen()) + + def update_home_views(self, figure=None): + """ + Make sure that ``self.home_views`` has an entry for all Axes present + in the figure. + """ + + if not figure: + figure = self.figure + for a in figure.get_axes(): + if a not in self.home_views[figure]: + self.home_views[figure][a] = a._get_view() + + def home(self): + """Recall the first view and position from the stack.""" + self.views[self.figure].home() + self.positions[self.figure].home() + + def back(self): + """Back one step in the stack of views and positions.""" + self.views[self.figure].back() + self.positions[self.figure].back() + + def forward(self): + """Forward one step in the stack of views and positions.""" + self.views[self.figure].forward() + self.positions[self.figure].forward() + + +class ViewsPositionsBase(ToolBase): + """Base class for `ToolHome`, `ToolBack` and `ToolForward`.""" + + _on_trigger = None + + def trigger(self, sender, event, data=None): + self.toolmanager.get_tool(_views_positions).add_figure(self.figure) + getattr(self.toolmanager.get_tool(_views_positions), + self._on_trigger)() + self.toolmanager.get_tool(_views_positions).update_view() + + +class ToolHome(ViewsPositionsBase): + """Restore the original view limits.""" + + description = 'Reset original view' + image = 'mpl-data/images/home' + default_keymap = property(lambda self: mpl.rcParams['keymap.home']) + _on_trigger = 'home' + + +class ToolBack(ViewsPositionsBase): + """Move back up the view limits stack.""" + + description = 'Back to previous view' + image = 'mpl-data/images/back' + default_keymap = property(lambda self: mpl.rcParams['keymap.back']) + _on_trigger = 'back' + + +class ToolForward(ViewsPositionsBase): + """Move forward in the view lim stack.""" + + description = 'Forward to next view' + image = 'mpl-data/images/forward' + default_keymap = property(lambda self: mpl.rcParams['keymap.forward']) + _on_trigger = 'forward' + + +class ConfigureSubplotsBase(ToolBase): + """Base tool for the configuration of subplots.""" + + description = 'Configure subplots' + image = 'mpl-data/images/subplots' + + +class SaveFigureBase(ToolBase): + """Base tool for figure saving.""" + + description = 'Save the figure' + image = 'mpl-data/images/filesave' + default_keymap = property(lambda self: mpl.rcParams['keymap.save']) + + +class ZoomPanBase(ToolToggleBase): + """Base class for `ToolZoom` and `ToolPan`.""" + def __init__(self, *args): + super().__init__(*args) + self._button_pressed = None + self._xypress = None + self._idPress = None + self._idRelease = None + self._idScroll = None + self.base_scale = 2. + self.scrollthresh = .5 # .5 second scroll threshold + self.lastscroll = time.time()-self.scrollthresh + + def enable(self, event=None): + """Connect press/release events and lock the canvas.""" + self.figure.canvas.widgetlock(self) + self._idPress = self.figure.canvas.mpl_connect( + 'button_press_event', self._press) + self._idRelease = self.figure.canvas.mpl_connect( + 'button_release_event', self._release) + self._idScroll = self.figure.canvas.mpl_connect( + 'scroll_event', self.scroll_zoom) + + def disable(self, event=None): + """Release the canvas and disconnect press/release events.""" + self._cancel_action() + self.figure.canvas.widgetlock.release(self) + self.figure.canvas.mpl_disconnect(self._idPress) + self.figure.canvas.mpl_disconnect(self._idRelease) + self.figure.canvas.mpl_disconnect(self._idScroll) + + def trigger(self, sender, event, data=None): + self.toolmanager.get_tool(_views_positions).add_figure(self.figure) + super().trigger(sender, event, data) + new_navigate_mode = self.name.upper() if self.toggled else None + for ax in self.figure.axes: + ax.set_navigate_mode(new_navigate_mode) + + def scroll_zoom(self, event): + # https://gist.github.com/tacaswell/3144287 + if event.inaxes is None: + return + + if event.button == 'up': + # deal with zoom in + scl = self.base_scale + elif event.button == 'down': + # deal with zoom out + scl = 1/self.base_scale + else: + # deal with something that should never happen + scl = 1 + + ax = event.inaxes + ax._set_view_from_bbox([event.x, event.y, scl]) + + # If last scroll was done within the timing threshold, delete the + # previous view + if (time.time()-self.lastscroll) < self.scrollthresh: + self.toolmanager.get_tool(_views_positions).back() + + self.figure.canvas.draw_idle() # force re-draw + + self.lastscroll = time.time() + self.toolmanager.get_tool(_views_positions).push_current() + + +class ToolZoom(ZoomPanBase): + """A Tool for zooming using a rectangle selector.""" + + description = 'Zoom to rectangle' + image = 'mpl-data/images/zoom_to_rect' + default_keymap = property(lambda self: mpl.rcParams['keymap.zoom']) + cursor = cursors.SELECT_REGION + radio_group = 'default' + + def __init__(self, *args): + super().__init__(*args) + self._ids_zoom = [] + + def _cancel_action(self): + for zoom_id in self._ids_zoom: + self.figure.canvas.mpl_disconnect(zoom_id) + self.toolmanager.trigger_tool('rubberband', self) + self.figure.canvas.draw_idle() + self._xypress = None + self._button_pressed = None + self._ids_zoom = [] + return + + def _press(self, event): + """Callback for mouse button presses in zoom-to-rectangle mode.""" + + # If we're already in the middle of a zoom, pressing another + # button works to "cancel" + if self._ids_zoom: + self._cancel_action() + + if event.button == 1: + self._button_pressed = 1 + elif event.button == 3: + self._button_pressed = 3 + else: + self._cancel_action() + return + + x, y = event.x, event.y + + self._xypress = [] + for i, a in enumerate(self.figure.get_axes()): + if (x is not None and y is not None and a.in_axes(event) and + a.get_navigate() and a.can_zoom()): + self._xypress.append((x, y, a, i, a._get_view())) + + id1 = self.figure.canvas.mpl_connect( + 'motion_notify_event', self._mouse_move) + id2 = self.figure.canvas.mpl_connect( + 'key_press_event', self._switch_on_zoom_mode) + id3 = self.figure.canvas.mpl_connect( + 'key_release_event', self._switch_off_zoom_mode) + + self._ids_zoom = id1, id2, id3 + self._zoom_mode = event.key + + def _switch_on_zoom_mode(self, event): + self._zoom_mode = event.key + self._mouse_move(event) + + def _switch_off_zoom_mode(self, event): + self._zoom_mode = None + self._mouse_move(event) + + def _mouse_move(self, event): + """Callback for mouse moves in zoom-to-rectangle mode.""" + + if self._xypress: + x, y = event.x, event.y + lastx, lasty, a, ind, view = self._xypress[0] + (x1, y1), (x2, y2) = np.clip( + [[lastx, lasty], [x, y]], a.bbox.min, a.bbox.max) + if self._zoom_mode == "x": + y1, y2 = a.bbox.intervaly + elif self._zoom_mode == "y": + x1, x2 = a.bbox.intervalx + self.toolmanager.trigger_tool( + 'rubberband', self, data=(x1, y1, x2, y2)) + + def _release(self, event): + """Callback for mouse button releases in zoom-to-rectangle mode.""" + + for zoom_id in self._ids_zoom: + self.figure.canvas.mpl_disconnect(zoom_id) + self._ids_zoom = [] + + if not self._xypress: + self._cancel_action() + return + + done_ax = [] + + for cur_xypress in self._xypress: + x, y = event.x, event.y + lastx, lasty, a, _ind, view = cur_xypress + # ignore singular clicks - 5 pixels is a threshold + if abs(x - lastx) < 5 or abs(y - lasty) < 5: + self._cancel_action() + return + + # detect twinx, twiny Axes and avoid double zooming + twinx = any(a.get_shared_x_axes().joined(a, a1) for a1 in done_ax) + twiny = any(a.get_shared_y_axes().joined(a, a1) for a1 in done_ax) + done_ax.append(a) + + if self._button_pressed == 1: + direction = 'in' + elif self._button_pressed == 3: + direction = 'out' + else: + continue + + a._set_view_from_bbox((lastx, lasty, x, y), direction, + self._zoom_mode, twinx, twiny) + + self._zoom_mode = None + self.toolmanager.get_tool(_views_positions).push_current() + self._cancel_action() + + +class ToolPan(ZoomPanBase): + """Pan Axes with left mouse, zoom with right.""" + + default_keymap = property(lambda self: mpl.rcParams['keymap.pan']) + description = 'Pan axes with left mouse, zoom with right' + image = 'mpl-data/images/move' + cursor = cursors.MOVE + radio_group = 'default' + + def __init__(self, *args): + super().__init__(*args) + self._id_drag = None + + def _cancel_action(self): + self._button_pressed = None + self._xypress = [] + self.figure.canvas.mpl_disconnect(self._id_drag) + self.toolmanager.messagelock.release(self) + self.figure.canvas.draw_idle() + + def _press(self, event): + if event.button == 1: + self._button_pressed = 1 + elif event.button == 3: + self._button_pressed = 3 + else: + self._cancel_action() + return + + x, y = event.x, event.y + + self._xypress = [] + for i, a in enumerate(self.figure.get_axes()): + if (x is not None and y is not None and a.in_axes(event) and + a.get_navigate() and a.can_pan()): + a.start_pan(x, y, event.button) + self._xypress.append((a, i)) + self.toolmanager.messagelock(self) + self._id_drag = self.figure.canvas.mpl_connect( + 'motion_notify_event', self._mouse_move) + + def _release(self, event): + if self._button_pressed is None: + self._cancel_action() + return + + self.figure.canvas.mpl_disconnect(self._id_drag) + self.toolmanager.messagelock.release(self) + + for a, _ind in self._xypress: + a.end_pan() + if not self._xypress: + self._cancel_action() + return + + self.toolmanager.get_tool(_views_positions).push_current() + self._cancel_action() + + def _mouse_move(self, event): + for a, _ind in self._xypress: + # safer to use the recorded button at the _press than current + # button: # multiple button can get pressed during motion... + a.drag_pan(self._button_pressed, event.key, event.x, event.y) + self.toolmanager.canvas.draw_idle() + + +class ToolHelpBase(ToolBase): + description = 'Print tool list, shortcuts and description' + default_keymap = property(lambda self: mpl.rcParams['keymap.help']) + image = 'mpl-data/images/help' + + @staticmethod + def format_shortcut(key_sequence): + """ + Convert a shortcut string from the notation used in rc config to the + standard notation for displaying shortcuts, e.g. 'ctrl+a' -> 'Ctrl+A'. + """ + return (key_sequence if len(key_sequence) == 1 else + re.sub(r"\+[A-Z]", r"+Shift\g<0>", key_sequence).title()) + + def _format_tool_keymap(self, name): + keymaps = self.toolmanager.get_tool_keymap(name) + return ", ".join(self.format_shortcut(keymap) for keymap in keymaps) + + def _get_help_entries(self): + return [(name, self._format_tool_keymap(name), tool.description) + for name, tool in sorted(self.toolmanager.tools.items()) + if tool.description] + + def _get_help_text(self): + entries = self._get_help_entries() + entries = ["{}: {}\n\t{}".format(*entry) for entry in entries] + return "\n".join(entries) + + def _get_help_html(self): + fmt = "{}{}{}" + rows = [fmt.format( + "Action", "Shortcuts", "Description")] + rows += [fmt.format(*row) for row in self._get_help_entries()] + return ("" + "" + rows[0] + "" + "".join(rows[1:]) + "
") + + +class ToolCopyToClipboardBase(ToolBase): + """Tool to copy the figure to the clipboard.""" + + description = 'Copy the canvas figure to clipboard' + default_keymap = property(lambda self: mpl.rcParams['keymap.copy']) + + def trigger(self, *args, **kwargs): + message = "Copy tool is not available" + self.toolmanager.message_event(message, self) + + +default_tools = {'home': ToolHome, 'back': ToolBack, 'forward': ToolForward, + 'zoom': ToolZoom, 'pan': ToolPan, + 'subplots': ConfigureSubplotsBase, + 'save': SaveFigureBase, + 'grid': ToolGrid, + 'grid_minor': ToolMinorGrid, + 'fullscreen': ToolFullScreen, + 'quit': ToolQuit, + 'quit_all': ToolQuitAll, + 'xscale': ToolXScale, + 'yscale': ToolYScale, + 'position': ToolCursorPosition, + _views_positions: ToolViewsPositions, + 'cursor': ToolSetCursor, + 'rubberband': RubberbandBase, + 'help': ToolHelpBase, + 'copy': ToolCopyToClipboardBase, + } + +default_toolbar_tools = [['navigation', ['home', 'back', 'forward']], + ['zoompan', ['pan', 'zoom', 'subplots']], + ['io', ['save', 'help']]] + + +def add_tools_to_manager(toolmanager, tools=default_tools): + """ + Add multiple tools to a `.ToolManager`. + + Parameters + ---------- + toolmanager : `.backend_managers.ToolManager` + Manager to which the tools are added. + tools : {str: class_like}, optional + The tools to add in a {name: tool} dict, see + `.backend_managers.ToolManager.add_tool` for more info. + """ + + for name, tool in tools.items(): + toolmanager.add_tool(name, tool) + + +def add_tools_to_container(container, tools=default_toolbar_tools): + """ + Add multiple tools to the container. + + Parameters + ---------- + container : Container + `.backend_bases.ToolContainerBase` object that will get the tools + added. + tools : list, optional + List in the form ``[[group1, [tool1, tool2 ...]], [group2, [...]]]`` + where the tools ``[tool1, tool2, ...]`` will display in group1. + See `.backend_bases.ToolContainerBase.add_tool` for details. + """ + + for group, grouptools in tools: + for position, tool in enumerate(grouptools): + container.add_tool(tool, group, position) diff --git a/moondream/lib/python3.10/site-packages/matplotlib/bezier.py b/moondream/lib/python3.10/site-packages/matplotlib/bezier.py new file mode 100644 index 0000000000000000000000000000000000000000..42a6b478d729f3b2837e11e6767b84ac5972654d --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/bezier.py @@ -0,0 +1,602 @@ +""" +A module providing some utility functions regarding Bézier path manipulation. +""" + +from functools import lru_cache +import math +import warnings + +import numpy as np + +from matplotlib import _api + + +# same algorithm as 3.8's math.comb +@np.vectorize +@lru_cache(maxsize=128) +def _comb(n, k): + if k > n: + return 0 + k = min(k, n - k) + i = np.arange(1, k + 1) + return np.prod((n + 1 - i)/i).astype(int) + + +class NonIntersectingPathException(ValueError): + pass + + +# some functions + + +def get_intersection(cx1, cy1, cos_t1, sin_t1, + cx2, cy2, cos_t2, sin_t2): + """ + Return the intersection between the line through (*cx1*, *cy1*) at angle + *t1* and the line through (*cx2*, *cy2*) at angle *t2*. + """ + + # line1 => sin_t1 * (x - cx1) - cos_t1 * (y - cy1) = 0. + # line1 => sin_t1 * x + cos_t1 * y = sin_t1*cx1 - cos_t1*cy1 + + line1_rhs = sin_t1 * cx1 - cos_t1 * cy1 + line2_rhs = sin_t2 * cx2 - cos_t2 * cy2 + + # rhs matrix + a, b = sin_t1, -cos_t1 + c, d = sin_t2, -cos_t2 + + ad_bc = a * d - b * c + if abs(ad_bc) < 1e-12: + raise ValueError("Given lines do not intersect. Please verify that " + "the angles are not equal or differ by 180 degrees.") + + # rhs_inverse + a_, b_ = d, -b + c_, d_ = -c, a + a_, b_, c_, d_ = (k / ad_bc for k in [a_, b_, c_, d_]) + + x = a_ * line1_rhs + b_ * line2_rhs + y = c_ * line1_rhs + d_ * line2_rhs + + return x, y + + +def get_normal_points(cx, cy, cos_t, sin_t, length): + """ + For a line passing through (*cx*, *cy*) and having an angle *t*, return + locations of the two points located along its perpendicular line at the + distance of *length*. + """ + + if length == 0.: + return cx, cy, cx, cy + + cos_t1, sin_t1 = sin_t, -cos_t + cos_t2, sin_t2 = -sin_t, cos_t + + x1, y1 = length * cos_t1 + cx, length * sin_t1 + cy + x2, y2 = length * cos_t2 + cx, length * sin_t2 + cy + + return x1, y1, x2, y2 + + +# BEZIER routines + +# subdividing bezier curve +# http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-sub.html + + +def _de_casteljau1(beta, t): + next_beta = beta[:-1] * (1 - t) + beta[1:] * t + return next_beta + + +def split_de_casteljau(beta, t): + """ + Split a Bézier segment defined by its control points *beta* into two + separate segments divided at *t* and return their control points. + """ + beta = np.asarray(beta) + beta_list = [beta] + while True: + beta = _de_casteljau1(beta, t) + beta_list.append(beta) + if len(beta) == 1: + break + left_beta = [beta[0] for beta in beta_list] + right_beta = [beta[-1] for beta in reversed(beta_list)] + + return left_beta, right_beta + + +def find_bezier_t_intersecting_with_closedpath( + bezier_point_at_t, inside_closedpath, t0=0., t1=1., tolerance=0.01): + """ + Find the intersection of the Bézier curve with a closed path. + + The intersection point *t* is approximated by two parameters *t0*, *t1* + such that *t0* <= *t* <= *t1*. + + Search starts from *t0* and *t1* and uses a simple bisecting algorithm + therefore one of the end points must be inside the path while the other + doesn't. The search stops when the distance of the points parametrized by + *t0* and *t1* gets smaller than the given *tolerance*. + + Parameters + ---------- + bezier_point_at_t : callable + A function returning x, y coordinates of the Bézier at parameter *t*. + It must have the signature:: + + bezier_point_at_t(t: float) -> tuple[float, float] + + inside_closedpath : callable + A function returning True if a given point (x, y) is inside the + closed path. It must have the signature:: + + inside_closedpath(point: tuple[float, float]) -> bool + + t0, t1 : float + Start parameters for the search. + + tolerance : float + Maximal allowed distance between the final points. + + Returns + ------- + t0, t1 : float + The Bézier path parameters. + """ + start = bezier_point_at_t(t0) + end = bezier_point_at_t(t1) + + start_inside = inside_closedpath(start) + end_inside = inside_closedpath(end) + + if start_inside == end_inside and start != end: + raise NonIntersectingPathException( + "Both points are on the same side of the closed path") + + while True: + + # return if the distance is smaller than the tolerance + if np.hypot(start[0] - end[0], start[1] - end[1]) < tolerance: + return t0, t1 + + # calculate the middle point + middle_t = 0.5 * (t0 + t1) + middle = bezier_point_at_t(middle_t) + middle_inside = inside_closedpath(middle) + + if start_inside ^ middle_inside: + t1 = middle_t + if end == middle: + # Edge case where infinite loop is possible + # Caused by large numbers relative to tolerance + return t0, t1 + end = middle + else: + t0 = middle_t + if start == middle: + # Edge case where infinite loop is possible + # Caused by large numbers relative to tolerance + return t0, t1 + start = middle + start_inside = middle_inside + + +class BezierSegment: + """ + A d-dimensional Bézier segment. + + Parameters + ---------- + control_points : (N, d) array + Location of the *N* control points. + """ + + def __init__(self, control_points): + self._cpoints = np.asarray(control_points) + self._N, self._d = self._cpoints.shape + self._orders = np.arange(self._N) + coeff = [math.factorial(self._N - 1) + // (math.factorial(i) * math.factorial(self._N - 1 - i)) + for i in range(self._N)] + self._px = (self._cpoints.T * coeff).T + + def __call__(self, t): + """ + Evaluate the Bézier curve at point(s) *t* in [0, 1]. + + Parameters + ---------- + t : (k,) array-like + Points at which to evaluate the curve. + + Returns + ------- + (k, d) array + Value of the curve for each point in *t*. + """ + t = np.asarray(t) + return (np.power.outer(1 - t, self._orders[::-1]) + * np.power.outer(t, self._orders)) @ self._px + + def point_at_t(self, t): + """ + Evaluate the curve at a single point, returning a tuple of *d* floats. + """ + return tuple(self(t)) + + @property + def control_points(self): + """The control points of the curve.""" + return self._cpoints + + @property + def dimension(self): + """The dimension of the curve.""" + return self._d + + @property + def degree(self): + """Degree of the polynomial. One less the number of control points.""" + return self._N - 1 + + @property + def polynomial_coefficients(self): + r""" + The polynomial coefficients of the Bézier curve. + + .. warning:: Follows opposite convention from `numpy.polyval`. + + Returns + ------- + (n+1, d) array + Coefficients after expanding in polynomial basis, where :math:`n` + is the degree of the Bézier curve and :math:`d` its dimension. + These are the numbers (:math:`C_j`) such that the curve can be + written :math:`\sum_{j=0}^n C_j t^j`. + + Notes + ----- + The coefficients are calculated as + + .. math:: + + {n \choose j} \sum_{i=0}^j (-1)^{i+j} {j \choose i} P_i + + where :math:`P_i` are the control points of the curve. + """ + n = self.degree + # matplotlib uses n <= 4. overflow plausible starting around n = 15. + if n > 10: + warnings.warn("Polynomial coefficients formula unstable for high " + "order Bezier curves!", RuntimeWarning) + P = self.control_points + j = np.arange(n+1)[:, None] + i = np.arange(n+1)[None, :] # _comb is non-zero for i <= j + prefactor = (-1)**(i + j) * _comb(j, i) # j on axis 0, i on axis 1 + return _comb(n, j) * prefactor @ P # j on axis 0, self.dimension on 1 + + def axis_aligned_extrema(self): + """ + Return the dimension and location of the curve's interior extrema. + + The extrema are the points along the curve where one of its partial + derivatives is zero. + + Returns + ------- + dims : array of int + Index :math:`i` of the partial derivative which is zero at each + interior extrema. + dzeros : array of float + Of same size as dims. The :math:`t` such that :math:`d/dx_i B(t) = + 0` + """ + n = self.degree + if n <= 1: + return np.array([]), np.array([]) + Cj = self.polynomial_coefficients + dCj = np.arange(1, n+1)[:, None] * Cj[1:] + dims = [] + roots = [] + for i, pi in enumerate(dCj.T): + r = np.roots(pi[::-1]) + roots.append(r) + dims.append(np.full_like(r, i)) + roots = np.concatenate(roots) + dims = np.concatenate(dims) + in_range = np.isreal(roots) & (roots >= 0) & (roots <= 1) + return dims[in_range], np.real(roots)[in_range] + + +def split_bezier_intersecting_with_closedpath( + bezier, inside_closedpath, tolerance=0.01): + """ + Split a Bézier curve into two at the intersection with a closed path. + + Parameters + ---------- + bezier : (N, 2) array-like + Control points of the Bézier segment. See `.BezierSegment`. + inside_closedpath : callable + A function returning True if a given point (x, y) is inside the + closed path. See also `.find_bezier_t_intersecting_with_closedpath`. + tolerance : float + The tolerance for the intersection. See also + `.find_bezier_t_intersecting_with_closedpath`. + + Returns + ------- + left, right + Lists of control points for the two Bézier segments. + """ + + bz = BezierSegment(bezier) + bezier_point_at_t = bz.point_at_t + + t0, t1 = find_bezier_t_intersecting_with_closedpath( + bezier_point_at_t, inside_closedpath, tolerance=tolerance) + + _left, _right = split_de_casteljau(bezier, (t0 + t1) / 2.) + return _left, _right + + +# matplotlib specific + + +def split_path_inout(path, inside, tolerance=0.01, reorder_inout=False): + """ + Divide a path into two segments at the point where ``inside(x, y)`` becomes + False. + """ + from .path import Path + path_iter = path.iter_segments() + + ctl_points, command = next(path_iter) + begin_inside = inside(ctl_points[-2:]) # true if begin point is inside + + ctl_points_old = ctl_points + + iold = 0 + i = 1 + + for ctl_points, command in path_iter: + iold = i + i += len(ctl_points) // 2 + if inside(ctl_points[-2:]) != begin_inside: + bezier_path = np.concatenate([ctl_points_old[-2:], ctl_points]) + break + ctl_points_old = ctl_points + else: + raise ValueError("The path does not intersect with the patch") + + bp = bezier_path.reshape((-1, 2)) + left, right = split_bezier_intersecting_with_closedpath( + bp, inside, tolerance) + if len(left) == 2: + codes_left = [Path.LINETO] + codes_right = [Path.MOVETO, Path.LINETO] + elif len(left) == 3: + codes_left = [Path.CURVE3, Path.CURVE3] + codes_right = [Path.MOVETO, Path.CURVE3, Path.CURVE3] + elif len(left) == 4: + codes_left = [Path.CURVE4, Path.CURVE4, Path.CURVE4] + codes_right = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4] + else: + raise AssertionError("This should never be reached") + + verts_left = left[1:] + verts_right = right[:] + + if path.codes is None: + path_in = Path(np.concatenate([path.vertices[:i], verts_left])) + path_out = Path(np.concatenate([verts_right, path.vertices[i:]])) + + else: + path_in = Path(np.concatenate([path.vertices[:iold], verts_left]), + np.concatenate([path.codes[:iold], codes_left])) + + path_out = Path(np.concatenate([verts_right, path.vertices[i:]]), + np.concatenate([codes_right, path.codes[i:]])) + + if reorder_inout and not begin_inside: + path_in, path_out = path_out, path_in + + return path_in, path_out + + +def inside_circle(cx, cy, r): + """ + Return a function that checks whether a point is in a circle with center + (*cx*, *cy*) and radius *r*. + + The returned function has the signature:: + + f(xy: tuple[float, float]) -> bool + """ + r2 = r ** 2 + + def _f(xy): + x, y = xy + return (x - cx) ** 2 + (y - cy) ** 2 < r2 + return _f + + +# quadratic Bezier lines + +def get_cos_sin(x0, y0, x1, y1): + dx, dy = x1 - x0, y1 - y0 + d = (dx * dx + dy * dy) ** .5 + # Account for divide by zero + if d == 0: + return 0.0, 0.0 + return dx / d, dy / d + + +def check_if_parallel(dx1, dy1, dx2, dy2, tolerance=1.e-5): + """ + Check if two lines are parallel. + + Parameters + ---------- + dx1, dy1, dx2, dy2 : float + The gradients *dy*/*dx* of the two lines. + tolerance : float + The angular tolerance in radians up to which the lines are considered + parallel. + + Returns + ------- + is_parallel + - 1 if two lines are parallel in same direction. + - -1 if two lines are parallel in opposite direction. + - False otherwise. + """ + theta1 = np.arctan2(dx1, dy1) + theta2 = np.arctan2(dx2, dy2) + dtheta = abs(theta1 - theta2) + if dtheta < tolerance: + return 1 + elif abs(dtheta - np.pi) < tolerance: + return -1 + else: + return False + + +def get_parallels(bezier2, width): + """ + Given the quadratic Bézier control points *bezier2*, returns + control points of quadratic Bézier lines roughly parallel to given + one separated by *width*. + """ + + # The parallel Bezier lines are constructed by following ways. + # c1 and c2 are control points representing the start and end of the + # Bezier line. + # cm is the middle point + + c1x, c1y = bezier2[0] + cmx, cmy = bezier2[1] + c2x, c2y = bezier2[2] + + parallel_test = check_if_parallel(c1x - cmx, c1y - cmy, + cmx - c2x, cmy - c2y) + + if parallel_test == -1: + _api.warn_external( + "Lines do not intersect. A straight line is used instead.") + cos_t1, sin_t1 = get_cos_sin(c1x, c1y, c2x, c2y) + cos_t2, sin_t2 = cos_t1, sin_t1 + else: + # t1 and t2 is the angle between c1 and cm, cm, c2. They are + # also an angle of the tangential line of the path at c1 and c2 + cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy) + cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c2x, c2y) + + # find c1_left, c1_right which are located along the lines + # through c1 and perpendicular to the tangential lines of the + # Bezier path at a distance of width. Same thing for c2_left and + # c2_right with respect to c2. + c1x_left, c1y_left, c1x_right, c1y_right = ( + get_normal_points(c1x, c1y, cos_t1, sin_t1, width) + ) + c2x_left, c2y_left, c2x_right, c2y_right = ( + get_normal_points(c2x, c2y, cos_t2, sin_t2, width) + ) + + # find cm_left which is the intersecting point of a line through + # c1_left with angle t1 and a line through c2_left with angle + # t2. Same with cm_right. + try: + cmx_left, cmy_left = get_intersection(c1x_left, c1y_left, cos_t1, + sin_t1, c2x_left, c2y_left, + cos_t2, sin_t2) + cmx_right, cmy_right = get_intersection(c1x_right, c1y_right, cos_t1, + sin_t1, c2x_right, c2y_right, + cos_t2, sin_t2) + except ValueError: + # Special case straight lines, i.e., angle between two lines is + # less than the threshold used by get_intersection (we don't use + # check_if_parallel as the threshold is not the same). + cmx_left, cmy_left = ( + 0.5 * (c1x_left + c2x_left), 0.5 * (c1y_left + c2y_left) + ) + cmx_right, cmy_right = ( + 0.5 * (c1x_right + c2x_right), 0.5 * (c1y_right + c2y_right) + ) + + # the parallel Bezier lines are created with control points of + # [c1_left, cm_left, c2_left] and [c1_right, cm_right, c2_right] + path_left = [(c1x_left, c1y_left), + (cmx_left, cmy_left), + (c2x_left, c2y_left)] + path_right = [(c1x_right, c1y_right), + (cmx_right, cmy_right), + (c2x_right, c2y_right)] + + return path_left, path_right + + +def find_control_points(c1x, c1y, mmx, mmy, c2x, c2y): + """ + Find control points of the Bézier curve passing through (*c1x*, *c1y*), + (*mmx*, *mmy*), and (*c2x*, *c2y*), at parametric values 0, 0.5, and 1. + """ + cmx = .5 * (4 * mmx - (c1x + c2x)) + cmy = .5 * (4 * mmy - (c1y + c2y)) + return [(c1x, c1y), (cmx, cmy), (c2x, c2y)] + + +def make_wedged_bezier2(bezier2, width, w1=1., wm=0.5, w2=0.): + """ + Being similar to `get_parallels`, returns control points of two quadratic + Bézier lines having a width roughly parallel to given one separated by + *width*. + """ + + # c1, cm, c2 + c1x, c1y = bezier2[0] + cmx, cmy = bezier2[1] + c3x, c3y = bezier2[2] + + # t1 and t2 is the angle between c1 and cm, cm, c3. + # They are also an angle of the tangential line of the path at c1 and c3 + cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy) + cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c3x, c3y) + + # find c1_left, c1_right which are located along the lines + # through c1 and perpendicular to the tangential lines of the + # Bezier path at a distance of width. Same thing for c3_left and + # c3_right with respect to c3. + c1x_left, c1y_left, c1x_right, c1y_right = ( + get_normal_points(c1x, c1y, cos_t1, sin_t1, width * w1) + ) + c3x_left, c3y_left, c3x_right, c3y_right = ( + get_normal_points(c3x, c3y, cos_t2, sin_t2, width * w2) + ) + + # find c12, c23 and c123 which are middle points of c1-cm, cm-c3 and + # c12-c23 + c12x, c12y = (c1x + cmx) * .5, (c1y + cmy) * .5 + c23x, c23y = (cmx + c3x) * .5, (cmy + c3y) * .5 + c123x, c123y = (c12x + c23x) * .5, (c12y + c23y) * .5 + + # tangential angle of c123 (angle between c12 and c23) + cos_t123, sin_t123 = get_cos_sin(c12x, c12y, c23x, c23y) + + c123x_left, c123y_left, c123x_right, c123y_right = ( + get_normal_points(c123x, c123y, cos_t123, sin_t123, width * wm) + ) + + path_left = find_control_points(c1x_left, c1y_left, + c123x_left, c123y_left, + c3x_left, c3y_left) + path_right = find_control_points(c1x_right, c1y_right, + c123x_right, c123y_right, + c3x_right, c3y_right) + + return path_left, path_right diff --git a/moondream/lib/python3.10/site-packages/matplotlib/category.py b/moondream/lib/python3.10/site-packages/matplotlib/category.py new file mode 100644 index 0000000000000000000000000000000000000000..225c837006f726aa97b990c82a3265ec06e55df3 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/category.py @@ -0,0 +1,235 @@ +""" +Plotting of string "category" data: ``plot(['d', 'f', 'a'], [1, 2, 3])`` will +plot three points with x-axis values of 'd', 'f', 'a'. + +See :doc:`/gallery/lines_bars_and_markers/categorical_variables` for an +example. + +The module uses Matplotlib's `matplotlib.units` mechanism to convert from +strings to integers and provides a tick locator, a tick formatter, and the +`.UnitData` class that creates and stores the string-to-integer mapping. +""" + +from collections import OrderedDict +import dateutil.parser +import itertools +import logging + +import numpy as np + +from matplotlib import _api, cbook, ticker, units + + +_log = logging.getLogger(__name__) + + +class StrCategoryConverter(units.ConversionInterface): + @staticmethod + def convert(value, unit, axis): + """ + Convert strings in *value* to floats using mapping information stored + in the *unit* object. + + Parameters + ---------- + value : str or iterable + Value or list of values to be converted. + unit : `.UnitData` + An object mapping strings to integers. + axis : `~matplotlib.axis.Axis` + The axis on which the converted value is plotted. + + .. note:: *axis* is unused. + + Returns + ------- + float or `~numpy.ndarray` of float + """ + if unit is None: + raise ValueError( + 'Missing category information for StrCategoryConverter; ' + 'this might be caused by unintendedly mixing categorical and ' + 'numeric data') + StrCategoryConverter._validate_unit(unit) + # dtype = object preserves numerical pass throughs + values = np.atleast_1d(np.array(value, dtype=object)) + # force an update so it also does type checking + unit.update(values) + s = np.vectorize(unit._mapping.__getitem__, otypes=[float])(values) + return s if not cbook.is_scalar_or_string(value) else s[0] + + @staticmethod + def axisinfo(unit, axis): + """ + Set the default axis ticks and labels. + + Parameters + ---------- + unit : `.UnitData` + object string unit information for value + axis : `~matplotlib.axis.Axis` + axis for which information is being set + + .. note:: *axis* is not used + + Returns + ------- + `~matplotlib.units.AxisInfo` + Information to support default tick labeling + + """ + StrCategoryConverter._validate_unit(unit) + # locator and formatter take mapping dict because + # args need to be pass by reference for updates + majloc = StrCategoryLocator(unit._mapping) + majfmt = StrCategoryFormatter(unit._mapping) + return units.AxisInfo(majloc=majloc, majfmt=majfmt) + + @staticmethod + def default_units(data, axis): + """ + Set and update the `~matplotlib.axis.Axis` units. + + Parameters + ---------- + data : str or iterable of str + axis : `~matplotlib.axis.Axis` + axis on which the data is plotted + + Returns + ------- + `.UnitData` + object storing string to integer mapping + """ + # the conversion call stack is default_units -> axis_info -> convert + if axis.units is None: + axis.set_units(UnitData(data)) + else: + axis.units.update(data) + return axis.units + + @staticmethod + def _validate_unit(unit): + if not hasattr(unit, '_mapping'): + raise ValueError( + f'Provided unit "{unit}" is not valid for a categorical ' + 'converter, as it does not have a _mapping attribute.') + + +class StrCategoryLocator(ticker.Locator): + """Tick at every integer mapping of the string data.""" + def __init__(self, units_mapping): + """ + Parameters + ---------- + units_mapping : dict + Mapping of category names (str) to indices (int). + """ + self._units = units_mapping + + def __call__(self): + # docstring inherited + return list(self._units.values()) + + def tick_values(self, vmin, vmax): + # docstring inherited + return self() + + +class StrCategoryFormatter(ticker.Formatter): + """String representation of the data at every tick.""" + def __init__(self, units_mapping): + """ + Parameters + ---------- + units_mapping : dict + Mapping of category names (str) to indices (int). + """ + self._units = units_mapping + + def __call__(self, x, pos=None): + # docstring inherited + return self.format_ticks([x])[0] + + def format_ticks(self, values): + # docstring inherited + r_mapping = {v: self._text(k) for k, v in self._units.items()} + return [r_mapping.get(round(val), '') for val in values] + + @staticmethod + def _text(value): + """Convert text values into utf-8 or ascii strings.""" + if isinstance(value, bytes): + value = value.decode(encoding='utf-8') + elif not isinstance(value, str): + value = str(value) + return value + + +class UnitData: + def __init__(self, data=None): + """ + Create mapping between unique categorical values and integer ids. + + Parameters + ---------- + data : iterable + sequence of string values + """ + self._mapping = OrderedDict() + self._counter = itertools.count() + if data is not None: + self.update(data) + + @staticmethod + def _str_is_convertible(val): + """ + Helper method to check whether a string can be parsed as float or date. + """ + try: + float(val) + except ValueError: + try: + dateutil.parser.parse(val) + except (ValueError, TypeError): + # TypeError if dateutil >= 2.8.1 else ValueError + return False + return True + + def update(self, data): + """ + Map new values to integer identifiers. + + Parameters + ---------- + data : iterable of str or bytes + + Raises + ------ + TypeError + If elements in *data* are neither str nor bytes. + """ + data = np.atleast_1d(np.array(data, dtype=object)) + # check if convertible to number: + convertible = True + for val in OrderedDict.fromkeys(data): + # OrderedDict just iterates over unique values in data. + _api.check_isinstance((str, bytes), value=val) + if convertible: + # this will only be called so long as convertible is True. + convertible = self._str_is_convertible(val) + if val not in self._mapping: + self._mapping[val] = next(self._counter) + if data.size and convertible: + _log.info('Using categorical units to plot a list of strings ' + 'that are all parsable as floats or dates. If these ' + 'strings should be plotted as numbers, cast to the ' + 'appropriate data type before plotting.') + + +# Register the converter with Matplotlib's unit framework +# Intentionally set to a single instance +units.registry[str] = \ + units.registry[np.str_] = \ + units.registry[bytes] = \ + units.registry[np.bytes_] = StrCategoryConverter() diff --git a/moondream/lib/python3.10/site-packages/matplotlib/cm.pyi b/moondream/lib/python3.10/site-packages/matplotlib/cm.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c3c62095684aaa7b7a59490412889096b3cded61 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/cm.pyi @@ -0,0 +1,24 @@ +from collections.abc import Iterator, Mapping +from matplotlib import colors +from matplotlib.colorizer import _ScalarMappable + + +class ColormapRegistry(Mapping[str, colors.Colormap]): + def __init__(self, cmaps: Mapping[str, colors.Colormap]) -> None: ... + def __getitem__(self, item: str) -> colors.Colormap: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __call__(self) -> list[str]: ... + def register( + self, cmap: colors.Colormap, *, name: str | None = ..., force: bool = ... + ) -> None: ... + def unregister(self, name: str) -> None: ... + def get_cmap(self, cmap: str | colors.Colormap) -> colors.Colormap: ... + +_colormaps: ColormapRegistry = ... +_multivar_colormaps: ColormapRegistry = ... +_bivar_colormaps: ColormapRegistry = ... + +def get_cmap(name: str | colors.Colormap | None = ..., lut: int | None = ...) -> colors.Colormap: ... + +ScalarMappable = _ScalarMappable diff --git a/moondream/lib/python3.10/site-packages/matplotlib/collections.py b/moondream/lib/python3.10/site-packages/matplotlib/collections.py new file mode 100644 index 0000000000000000000000000000000000000000..f18d5a4c3a8c90ec65d943e495b3928de1672689 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/collections.py @@ -0,0 +1,2582 @@ +""" +Classes for the efficient drawing of large collections of objects that +share most properties, e.g., a large number of line segments or +polygons. + +The classes are not meant to be as flexible as their single element +counterparts (e.g., you may not be able to select all line styles) but +they are meant to be fast for common use cases (e.g., a large set of solid +line segments). +""" + +import itertools +import functools +import math +from numbers import Number, Real +import warnings + +import numpy as np + +import matplotlib as mpl +from . import (_api, _path, artist, cbook, colorizer as mcolorizer, colors as mcolors, + _docstring, hatch as mhatch, lines as mlines, path as mpath, transforms) +from ._enums import JoinStyle, CapStyle + + +# "color" is excluded; it is a compound setter, and its docstring differs +# in LineCollection. +@_api.define_aliases({ + "antialiased": ["antialiaseds", "aa"], + "edgecolor": ["edgecolors", "ec"], + "facecolor": ["facecolors", "fc"], + "linestyle": ["linestyles", "dashes", "ls"], + "linewidth": ["linewidths", "lw"], + "offset_transform": ["transOffset"], +}) +class Collection(mcolorizer.ColorizingArtist): + r""" + Base class for Collections. Must be subclassed to be usable. + + A Collection represents a sequence of `.Patch`\es that can be drawn + more efficiently together than individually. For example, when a single + path is being drawn repeatedly at different offsets, the renderer can + typically execute a ``draw_marker()`` call much more efficiently than a + series of repeated calls to ``draw_path()`` with the offsets put in + one-by-one. + + Most properties of a collection can be configured per-element. Therefore, + Collections have "plural" versions of many of the properties of a `.Patch` + (e.g. `.Collection.get_paths` instead of `.Patch.get_path`). Exceptions are + the *zorder*, *hatch*, *pickradius*, *capstyle* and *joinstyle* properties, + which can only be set globally for the whole collection. + + Besides these exceptions, all properties can be specified as single values + (applying to all elements) or sequences of values. The property of the + ``i``\th element of the collection is:: + + prop[i % len(prop)] + + Each Collection can optionally be used as its own `.ScalarMappable` by + passing the *norm* and *cmap* parameters to its constructor. If the + Collection's `.ScalarMappable` matrix ``_A`` has been set (via a call + to `.Collection.set_array`), then at draw time this internal scalar + mappable will be used to set the ``facecolors`` and ``edgecolors``, + ignoring those that were manually passed in. + """ + #: Either a list of 3x3 arrays or an Nx3x3 array (representing N + #: transforms), suitable for the `all_transforms` argument to + #: `~matplotlib.backend_bases.RendererBase.draw_path_collection`; + #: each 3x3 array is used to initialize an + #: `~matplotlib.transforms.Affine2D` object. + #: Each kind of collection defines this based on its arguments. + _transforms = np.empty((0, 3, 3)) + + # Whether to draw an edge by default. Set on a + # subclass-by-subclass basis. + _edge_default = False + + @_docstring.interpd + def __init__(self, *, + edgecolors=None, + facecolors=None, + linewidths=None, + linestyles='solid', + capstyle=None, + joinstyle=None, + antialiaseds=None, + offsets=None, + offset_transform=None, + norm=None, # optional for ScalarMappable + cmap=None, # ditto + colorizer=None, + pickradius=5.0, + hatch=None, + urls=None, + zorder=1, + **kwargs + ): + """ + Parameters + ---------- + edgecolors : :mpltype:`color` or list of colors, default: :rc:`patch.edgecolor` + Edge color for each patch making up the collection. The special + value 'face' can be passed to make the edgecolor match the + facecolor. + facecolors : :mpltype:`color` or list of colors, default: :rc:`patch.facecolor` + Face color for each patch making up the collection. + linewidths : float or list of floats, default: :rc:`patch.linewidth` + Line width for each patch making up the collection. + linestyles : str or tuple or list thereof, default: 'solid' + Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-', + '--', '-.', ':']. Dash tuples should be of the form:: + + (offset, onoffseq), + + where *onoffseq* is an even length tuple of on and off ink lengths + in points. For examples, see + :doc:`/gallery/lines_bars_and_markers/linestyles`. + capstyle : `.CapStyle`-like, default: 'butt' + Style to use for capping lines for all paths in the collection. + Allowed values are %(CapStyle)s. + joinstyle : `.JoinStyle`-like, default: 'round' + Style to use for joining lines for all paths in the collection. + Allowed values are %(JoinStyle)s. + antialiaseds : bool or list of bool, default: :rc:`patch.antialiased` + Whether each patch in the collection should be drawn with + antialiasing. + offsets : (float, float) or list thereof, default: (0, 0) + A vector by which to translate each patch after rendering (default + is no translation). The translation is performed in screen (pixel) + coordinates (i.e. after the Artist's transform is applied). + offset_transform : `~.Transform`, default: `.IdentityTransform` + A single transform which will be applied to each *offsets* vector + before it is used. + cmap, norm + Data normalization and colormapping parameters. See + `.ScalarMappable` for a detailed description. + hatch : str, optional + Hatching pattern to use in filled paths, if any. Valid strings are + ['/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*']. See + :doc:`/gallery/shapes_and_collections/hatch_style_reference` for + the meaning of each hatch type. + pickradius : float, default: 5.0 + If ``pickradius <= 0``, then `.Collection.contains` will return + ``True`` whenever the test point is inside of one of the polygons + formed by the control points of a Path in the Collection. On the + other hand, if it is greater than 0, then we instead check if the + test point is contained in a stroke of width ``2*pickradius`` + following any of the Paths in the Collection. + urls : list of str, default: None + A URL for each patch to link to once drawn. Currently only works + for the SVG backend. See :doc:`/gallery/misc/hyperlinks_sgskip` for + examples. + zorder : float, default: 1 + The drawing order, shared by all Patches in the Collection. See + :doc:`/gallery/misc/zorder_demo` for all defaults and examples. + **kwargs + Remaining keyword arguments will be used to set properties as + ``Collection.set_{key}(val)`` for each key-value pair in *kwargs*. + """ + + super().__init__(self._get_colorizer(cmap, norm, colorizer)) + # list of un-scaled dash patterns + # this is needed scaling the dash pattern by linewidth + self._us_linestyles = [(0, None)] + # list of dash patterns + self._linestyles = [(0, None)] + # list of unbroadcast/scaled linewidths + self._us_lw = [0] + self._linewidths = [0] + + self._gapcolor = None # Currently only used by LineCollection. + + # Flags set by _set_mappable_flags: are colors from mapping an array? + self._face_is_mapped = None + self._edge_is_mapped = None + self._mapped_colors = None # calculated in update_scalarmappable + self._hatch_color = mcolors.to_rgba(mpl.rcParams['hatch.color']) + self._hatch_linewidth = mpl.rcParams['hatch.linewidth'] + self.set_facecolor(facecolors) + self.set_edgecolor(edgecolors) + self.set_linewidth(linewidths) + self.set_linestyle(linestyles) + self.set_antialiased(antialiaseds) + self.set_pickradius(pickradius) + self.set_urls(urls) + self.set_hatch(hatch) + self.set_zorder(zorder) + + if capstyle: + self.set_capstyle(capstyle) + else: + self._capstyle = None + + if joinstyle: + self.set_joinstyle(joinstyle) + else: + self._joinstyle = None + + if offsets is not None: + offsets = np.asanyarray(offsets, float) + # Broadcast (2,) -> (1, 2) but nothing else. + if offsets.shape == (2,): + offsets = offsets[None, :] + + self._offsets = offsets + self._offset_transform = offset_transform + + self._path_effects = None + self._internal_update(kwargs) + self._paths = None + + def get_paths(self): + return self._paths + + def set_paths(self, paths): + self._paths = paths + self.stale = True + + def get_transforms(self): + return self._transforms + + def get_offset_transform(self): + """Return the `.Transform` instance used by this artist offset.""" + if self._offset_transform is None: + self._offset_transform = transforms.IdentityTransform() + elif (not isinstance(self._offset_transform, transforms.Transform) + and hasattr(self._offset_transform, '_as_mpl_transform')): + self._offset_transform = \ + self._offset_transform._as_mpl_transform(self.axes) + return self._offset_transform + + def set_offset_transform(self, offset_transform): + """ + Set the artist offset transform. + + Parameters + ---------- + offset_transform : `.Transform` + """ + self._offset_transform = offset_transform + + def get_datalim(self, transData): + # Calculate the data limits and return them as a `.Bbox`. + # + # This operation depends on the transforms for the data in the + # collection and whether the collection has offsets: + # + # 1. offsets = None, transform child of transData: use the paths for + # the automatic limits (i.e. for LineCollection in streamline). + # 2. offsets != None: offset_transform is child of transData: + # + # a. transform is child of transData: use the path + offset for + # limits (i.e for bar). + # b. transform is not a child of transData: just use the offsets + # for the limits (i.e. for scatter) + # + # 3. otherwise return a null Bbox. + + transform = self.get_transform() + offset_trf = self.get_offset_transform() + if not (isinstance(offset_trf, transforms.IdentityTransform) + or offset_trf.contains_branch(transData)): + # if the offsets are in some coords other than data, + # then don't use them for autoscaling. + return transforms.Bbox.null() + + paths = self.get_paths() + if not len(paths): + # No paths to transform + return transforms.Bbox.null() + + if not transform.is_affine: + paths = [transform.transform_path_non_affine(p) for p in paths] + # Don't convert transform to transform.get_affine() here because + # we may have transform.contains_branch(transData) but not + # transforms.get_affine().contains_branch(transData). But later, + # be careful to only apply the affine part that remains. + + offsets = self.get_offsets() + + if any(transform.contains_branch_seperately(transData)): + # collections that are just in data units (like quiver) + # can properly have the axes limits set by their shape + + # offset. LineCollections that have no offsets can + # also use this algorithm (like streamplot). + if isinstance(offsets, np.ma.MaskedArray): + offsets = offsets.filled(np.nan) + # get_path_collection_extents handles nan but not masked arrays + return mpath.get_path_collection_extents( + transform.get_affine() - transData, paths, + self.get_transforms(), + offset_trf.transform_non_affine(offsets), + offset_trf.get_affine().frozen()) + + # NOTE: None is the default case where no offsets were passed in + if self._offsets is not None: + # this is for collections that have their paths (shapes) + # in physical, axes-relative, or figure-relative units + # (i.e. like scatter). We can't uniquely set limits based on + # those shapes, so we just set the limits based on their + # location. + offsets = (offset_trf - transData).transform(offsets) + # note A-B means A B^{-1} + offsets = np.ma.masked_invalid(offsets) + if not offsets.mask.all(): + bbox = transforms.Bbox.null() + bbox.update_from_data_xy(offsets) + return bbox + return transforms.Bbox.null() + + def get_window_extent(self, renderer=None): + # TODO: check to ensure that this does not fail for + # cases other than scatter plot legend + return self.get_datalim(transforms.IdentityTransform()) + + def _prepare_points(self): + # Helper for drawing and hit testing. + + transform = self.get_transform() + offset_trf = self.get_offset_transform() + offsets = self.get_offsets() + paths = self.get_paths() + + if self.have_units(): + paths = [] + for path in self.get_paths(): + vertices = path.vertices + xs, ys = vertices[:, 0], vertices[:, 1] + xs = self.convert_xunits(xs) + ys = self.convert_yunits(ys) + paths.append(mpath.Path(np.column_stack([xs, ys]), path.codes)) + xs = self.convert_xunits(offsets[:, 0]) + ys = self.convert_yunits(offsets[:, 1]) + offsets = np.ma.column_stack([xs, ys]) + + if not transform.is_affine: + paths = [transform.transform_path_non_affine(path) + for path in paths] + transform = transform.get_affine() + if not offset_trf.is_affine: + offsets = offset_trf.transform_non_affine(offsets) + # This might have changed an ndarray into a masked array. + offset_trf = offset_trf.get_affine() + + if isinstance(offsets, np.ma.MaskedArray): + offsets = offsets.filled(np.nan) + # Changing from a masked array to nan-filled ndarray + # is probably most efficient at this point. + + return transform, offset_trf, offsets, paths + + @artist.allow_rasterization + def draw(self, renderer): + if not self.get_visible(): + return + renderer.open_group(self.__class__.__name__, self.get_gid()) + + self.update_scalarmappable() + + transform, offset_trf, offsets, paths = self._prepare_points() + + gc = renderer.new_gc() + self._set_gc_clip(gc) + gc.set_snap(self.get_snap()) + + if self._hatch: + gc.set_hatch(self._hatch) + gc.set_hatch_color(self._hatch_color) + gc.set_hatch_linewidth(self._hatch_linewidth) + + if self.get_sketch_params() is not None: + gc.set_sketch_params(*self.get_sketch_params()) + + if self.get_path_effects(): + from matplotlib.patheffects import PathEffectRenderer + renderer = PathEffectRenderer(self.get_path_effects(), renderer) + + # If the collection is made up of a single shape/color/stroke, + # it can be rendered once and blitted multiple times, using + # `draw_markers` rather than `draw_path_collection`. This is + # *much* faster for Agg, and results in smaller file sizes in + # PDF/SVG/PS. + + trans = self.get_transforms() + facecolors = self.get_facecolor() + edgecolors = self.get_edgecolor() + do_single_path_optimization = False + if (len(paths) == 1 and len(trans) <= 1 and + len(facecolors) == 1 and len(edgecolors) == 1 and + len(self._linewidths) == 1 and + all(ls[1] is None for ls in self._linestyles) and + len(self._antialiaseds) == 1 and len(self._urls) == 1 and + self.get_hatch() is None): + if len(trans): + combined_transform = transforms.Affine2D(trans[0]) + transform + else: + combined_transform = transform + extents = paths[0].get_extents(combined_transform) + if (extents.width < self.get_figure(root=True).bbox.width + and extents.height < self.get_figure(root=True).bbox.height): + do_single_path_optimization = True + + if self._joinstyle: + gc.set_joinstyle(self._joinstyle) + + if self._capstyle: + gc.set_capstyle(self._capstyle) + + if do_single_path_optimization: + gc.set_foreground(tuple(edgecolors[0])) + gc.set_linewidth(self._linewidths[0]) + gc.set_dashes(*self._linestyles[0]) + gc.set_antialiased(self._antialiaseds[0]) + gc.set_url(self._urls[0]) + renderer.draw_markers( + gc, paths[0], combined_transform.frozen(), + mpath.Path(offsets), offset_trf, tuple(facecolors[0])) + else: + if self._gapcolor is not None: + # First draw paths within the gaps. + ipaths, ilinestyles = self._get_inverse_paths_linestyles() + renderer.draw_path_collection( + gc, transform.frozen(), ipaths, + self.get_transforms(), offsets, offset_trf, + [mcolors.to_rgba("none")], self._gapcolor, + self._linewidths, ilinestyles, + self._antialiaseds, self._urls, + "screen") + + renderer.draw_path_collection( + gc, transform.frozen(), paths, + self.get_transforms(), offsets, offset_trf, + self.get_facecolor(), self.get_edgecolor(), + self._linewidths, self._linestyles, + self._antialiaseds, self._urls, + "screen") # offset_position, kept for backcompat. + + gc.restore() + renderer.close_group(self.__class__.__name__) + self.stale = False + + def set_pickradius(self, pickradius): + """ + Set the pick radius used for containment tests. + + Parameters + ---------- + pickradius : float + Pick radius, in points. + """ + if not isinstance(pickradius, Real): + raise ValueError( + f"pickradius must be a real-valued number, not {pickradius!r}") + self._pickradius = pickradius + + def get_pickradius(self): + return self._pickradius + + def contains(self, mouseevent): + """ + Test whether the mouse event occurred in the collection. + + Returns ``bool, dict(ind=itemlist)``, where every item in itemlist + contains the event. + """ + if self._different_canvas(mouseevent) or not self.get_visible(): + return False, {} + pickradius = ( + float(self._picker) + if isinstance(self._picker, Number) and + self._picker is not True # the bool, not just nonzero or 1 + else self._pickradius) + if self.axes: + self.axes._unstale_viewLim() + transform, offset_trf, offsets, paths = self._prepare_points() + # Tests if the point is contained on one of the polygons formed + # by the control points of each of the paths. A point is considered + # "on" a path if it would lie within a stroke of width 2*pickradius + # following the path. If pickradius <= 0, then we instead simply check + # if the point is *inside* of the path instead. + ind = _path.point_in_path_collection( + mouseevent.x, mouseevent.y, pickradius, + transform.frozen(), paths, self.get_transforms(), + offsets, offset_trf, pickradius <= 0) + return len(ind) > 0, dict(ind=ind) + + def set_urls(self, urls): + """ + Parameters + ---------- + urls : list of str or None + + Notes + ----- + URLs are currently only implemented by the SVG backend. They are + ignored by all other backends. + """ + self._urls = urls if urls is not None else [None] + self.stale = True + + def get_urls(self): + """ + Return a list of URLs, one for each element of the collection. + + The list contains *None* for elements without a URL. See + :doc:`/gallery/misc/hyperlinks_sgskip` for an example. + """ + return self._urls + + def set_hatch(self, hatch): + r""" + Set the hatching pattern + + *hatch* can be one of:: + + / - diagonal hatching + \ - back diagonal + | - vertical + - - horizontal + + - crossed + x - crossed diagonal + o - small circle + O - large circle + . - dots + * - stars + + Letters can be combined, in which case all the specified + hatchings are done. If same letter repeats, it increases the + density of hatching of that pattern. + + Unlike other properties such as linewidth and colors, hatching + can only be specified for the collection as a whole, not separately + for each member. + + Parameters + ---------- + hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'} + """ + # Use validate_hatch(list) after deprecation. + mhatch._validate_hatch_pattern(hatch) + self._hatch = hatch + self.stale = True + + def get_hatch(self): + """Return the current hatching pattern.""" + return self._hatch + + def set_hatch_linewidth(self, lw): + """Set the hatch linewidth.""" + self._hatch_linewidth = lw + + def get_hatch_linewidth(self): + """Return the hatch linewidth.""" + return self._hatch_linewidth + + def set_offsets(self, offsets): + """ + Set the offsets for the collection. + + Parameters + ---------- + offsets : (N, 2) or (2,) array-like + """ + offsets = np.asanyarray(offsets) + if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else. + offsets = offsets[None, :] + cstack = (np.ma.column_stack if isinstance(offsets, np.ma.MaskedArray) + else np.column_stack) + self._offsets = cstack( + (np.asanyarray(self.convert_xunits(offsets[:, 0]), float), + np.asanyarray(self.convert_yunits(offsets[:, 1]), float))) + self.stale = True + + def get_offsets(self): + """Return the offsets for the collection.""" + # Default to zeros in the no-offset (None) case + return np.zeros((1, 2)) if self._offsets is None else self._offsets + + def _get_default_linewidth(self): + # This may be overridden in a subclass. + return mpl.rcParams['patch.linewidth'] # validated as float + + def set_linewidth(self, lw): + """ + Set the linewidth(s) for the collection. *lw* can be a scalar + or a sequence; if it is a sequence the patches will cycle + through the sequence + + Parameters + ---------- + lw : float or list of floats + """ + if lw is None: + lw = self._get_default_linewidth() + # get the un-scaled/broadcast lw + self._us_lw = np.atleast_1d(lw) + + # scale all of the dash patterns. + self._linewidths, self._linestyles = self._bcast_lwls( + self._us_lw, self._us_linestyles) + self.stale = True + + def set_linestyle(self, ls): + """ + Set the linestyle(s) for the collection. + + =========================== ================= + linestyle description + =========================== ================= + ``'-'`` or ``'solid'`` solid line + ``'--'`` or ``'dashed'`` dashed line + ``'-.'`` or ``'dashdot'`` dash-dotted line + ``':'`` or ``'dotted'`` dotted line + =========================== ================= + + Alternatively a dash tuple of the following form can be provided:: + + (offset, onoffseq), + + where ``onoffseq`` is an even length tuple of on and off ink in points. + + Parameters + ---------- + ls : str or tuple or list thereof + Valid values for individual linestyles include {'-', '--', '-.', + ':', '', (offset, on-off-seq)}. See `.Line2D.set_linestyle` for a + complete description. + """ + try: + dashes = [mlines._get_dash_pattern(ls)] + except ValueError: + try: + dashes = [mlines._get_dash_pattern(x) for x in ls] + except ValueError as err: + emsg = f'Do not know how to convert {ls!r} to dashes' + raise ValueError(emsg) from err + + # get the list of raw 'unscaled' dash patterns + self._us_linestyles = dashes + + # broadcast and scale the lw and dash patterns + self._linewidths, self._linestyles = self._bcast_lwls( + self._us_lw, self._us_linestyles) + + @_docstring.interpd + def set_capstyle(self, cs): + """ + Set the `.CapStyle` for the collection (for all its elements). + + Parameters + ---------- + cs : `.CapStyle` or %(CapStyle)s + """ + self._capstyle = CapStyle(cs) + + @_docstring.interpd + def get_capstyle(self): + """ + Return the cap style for the collection (for all its elements). + + Returns + ------- + %(CapStyle)s or None + """ + return self._capstyle.name if self._capstyle else None + + @_docstring.interpd + def set_joinstyle(self, js): + """ + Set the `.JoinStyle` for the collection (for all its elements). + + Parameters + ---------- + js : `.JoinStyle` or %(JoinStyle)s + """ + self._joinstyle = JoinStyle(js) + + @_docstring.interpd + def get_joinstyle(self): + """ + Return the join style for the collection (for all its elements). + + Returns + ------- + %(JoinStyle)s or None + """ + return self._joinstyle.name if self._joinstyle else None + + @staticmethod + def _bcast_lwls(linewidths, dashes): + """ + Internal helper function to broadcast + scale ls/lw + + In the collection drawing code, the linewidth and linestyle are cycled + through as circular buffers (via ``v[i % len(v)]``). Thus, if we are + going to scale the dash pattern at set time (not draw time) we need to + do the broadcasting now and expand both lists to be the same length. + + Parameters + ---------- + linewidths : list + line widths of collection + dashes : list + dash specification (offset, (dash pattern tuple)) + + Returns + ------- + linewidths, dashes : list + Will be the same length, dashes are scaled by paired linewidth + """ + if mpl.rcParams['_internal.classic_mode']: + return linewidths, dashes + # make sure they are the same length so we can zip them + if len(dashes) != len(linewidths): + l_dashes = len(dashes) + l_lw = len(linewidths) + gcd = math.gcd(l_dashes, l_lw) + dashes = list(dashes) * (l_lw // gcd) + linewidths = list(linewidths) * (l_dashes // gcd) + + # scale the dash patterns + dashes = [mlines._scale_dashes(o, d, lw) + for (o, d), lw in zip(dashes, linewidths)] + + return linewidths, dashes + + def get_antialiased(self): + """ + Get the antialiasing state for rendering. + + Returns + ------- + array of bools + """ + return self._antialiaseds + + def set_antialiased(self, aa): + """ + Set the antialiasing state for rendering. + + Parameters + ---------- + aa : bool or list of bools + """ + if aa is None: + aa = self._get_default_antialiased() + self._antialiaseds = np.atleast_1d(np.asarray(aa, bool)) + self.stale = True + + def _get_default_antialiased(self): + # This may be overridden in a subclass. + return mpl.rcParams['patch.antialiased'] + + def set_color(self, c): + """ + Set both the edgecolor and the facecolor. + + Parameters + ---------- + c : :mpltype:`color` or list of RGBA tuples + + See Also + -------- + Collection.set_facecolor, Collection.set_edgecolor + For setting the edge or face color individually. + """ + self.set_facecolor(c) + self.set_edgecolor(c) + + def _get_default_facecolor(self): + # This may be overridden in a subclass. + return mpl.rcParams['patch.facecolor'] + + def _set_facecolor(self, c): + if c is None: + c = self._get_default_facecolor() + + self._facecolors = mcolors.to_rgba_array(c, self._alpha) + self.stale = True + + def set_facecolor(self, c): + """ + Set the facecolor(s) of the collection. *c* can be a color (all patches + have same color), or a sequence of colors; if it is a sequence the + patches will cycle through the sequence. + + If *c* is 'none', the patch will not be filled. + + Parameters + ---------- + c : :mpltype:`color` or list of :mpltype:`color` + """ + if isinstance(c, str) and c.lower() in ("none", "face"): + c = c.lower() + self._original_facecolor = c + self._set_facecolor(c) + + def get_facecolor(self): + return self._facecolors + + def get_edgecolor(self): + if cbook._str_equal(self._edgecolors, 'face'): + return self.get_facecolor() + else: + return self._edgecolors + + def _get_default_edgecolor(self): + # This may be overridden in a subclass. + return mpl.rcParams['patch.edgecolor'] + + def _set_edgecolor(self, c): + set_hatch_color = True + if c is None: + if (mpl.rcParams['patch.force_edgecolor'] + or self._edge_default + or cbook._str_equal(self._original_facecolor, 'none')): + c = self._get_default_edgecolor() + else: + c = 'none' + set_hatch_color = False + if cbook._str_lower_equal(c, 'face'): + self._edgecolors = 'face' + self.stale = True + return + self._edgecolors = mcolors.to_rgba_array(c, self._alpha) + if set_hatch_color and len(self._edgecolors): + self._hatch_color = tuple(self._edgecolors[0]) + self.stale = True + + def set_edgecolor(self, c): + """ + Set the edgecolor(s) of the collection. + + Parameters + ---------- + c : :mpltype:`color` or list of :mpltype:`color` or 'face' + The collection edgecolor(s). If a sequence, the patches cycle + through it. If 'face', match the facecolor. + """ + # We pass through a default value for use in LineCollection. + # This allows us to maintain None as the default indicator in + # _original_edgecolor. + if isinstance(c, str) and c.lower() in ("none", "face"): + c = c.lower() + self._original_edgecolor = c + self._set_edgecolor(c) + + def set_alpha(self, alpha): + """ + Set the transparency of the collection. + + Parameters + ---------- + alpha : float or array of float or None + If not None, *alpha* values must be between 0 and 1, inclusive. + If an array is provided, its length must match the number of + elements in the collection. Masked values and nans are not + supported. + """ + artist.Artist._set_alpha_for_array(self, alpha) + self._set_facecolor(self._original_facecolor) + self._set_edgecolor(self._original_edgecolor) + + set_alpha.__doc__ = artist.Artist._set_alpha_for_array.__doc__ + + def get_linewidth(self): + return self._linewidths + + def get_linestyle(self): + return self._linestyles + + def _set_mappable_flags(self): + """ + Determine whether edges and/or faces are color-mapped. + + This is a helper for update_scalarmappable. + It sets Boolean flags '_edge_is_mapped' and '_face_is_mapped'. + + Returns + ------- + mapping_change : bool + True if either flag is True, or if a flag has changed. + """ + # The flags are initialized to None to ensure this returns True + # the first time it is called. + edge0 = self._edge_is_mapped + face0 = self._face_is_mapped + # After returning, the flags must be Booleans, not None. + self._edge_is_mapped = False + self._face_is_mapped = False + if self._A is not None: + if not cbook._str_equal(self._original_facecolor, 'none'): + self._face_is_mapped = True + if cbook._str_equal(self._original_edgecolor, 'face'): + self._edge_is_mapped = True + else: + if self._original_edgecolor is None: + self._edge_is_mapped = True + + mapped = self._face_is_mapped or self._edge_is_mapped + changed = (edge0 is None or face0 is None + or self._edge_is_mapped != edge0 + or self._face_is_mapped != face0) + return mapped or changed + + def update_scalarmappable(self): + """ + Update colors from the scalar mappable array, if any. + + Assign colors to edges and faces based on the array and/or + colors that were directly set, as appropriate. + """ + if not self._set_mappable_flags(): + return + # Allow possibility to call 'self.set_array(None)'. + if self._A is not None: + # QuadMesh can map 2d arrays (but pcolormesh supplies 1d array) + if self._A.ndim > 1 and not isinstance(self, _MeshData): + raise ValueError('Collections can only map rank 1 arrays') + if np.iterable(self._alpha): + if self._alpha.size != self._A.size: + raise ValueError( + f'Data array shape, {self._A.shape} ' + 'is incompatible with alpha array shape, ' + f'{self._alpha.shape}. ' + 'This can occur with the deprecated ' + 'behavior of the "flat" shading option, ' + 'in which a row and/or column of the data ' + 'array is dropped.') + # pcolormesh, scatter, maybe others flatten their _A + self._alpha = self._alpha.reshape(self._A.shape) + self._mapped_colors = self.to_rgba(self._A, self._alpha) + + if self._face_is_mapped: + self._facecolors = self._mapped_colors + else: + self._set_facecolor(self._original_facecolor) + if self._edge_is_mapped: + self._edgecolors = self._mapped_colors + else: + self._set_edgecolor(self._original_edgecolor) + self.stale = True + + def get_fill(self): + """Return whether face is colored.""" + return not cbook._str_lower_equal(self._original_facecolor, "none") + + def update_from(self, other): + """Copy properties from other to self.""" + + artist.Artist.update_from(self, other) + self._antialiaseds = other._antialiaseds + self._mapped_colors = other._mapped_colors + self._edge_is_mapped = other._edge_is_mapped + self._original_edgecolor = other._original_edgecolor + self._edgecolors = other._edgecolors + self._face_is_mapped = other._face_is_mapped + self._original_facecolor = other._original_facecolor + self._facecolors = other._facecolors + self._linewidths = other._linewidths + self._linestyles = other._linestyles + self._us_linestyles = other._us_linestyles + self._pickradius = other._pickradius + self._hatch = other._hatch + + # update_from for scalarmappable + self._A = other._A + self.norm = other.norm + self.cmap = other.cmap + self.stale = True + + +class _CollectionWithSizes(Collection): + """ + Base class for collections that have an array of sizes. + """ + _factor = 1.0 + + def get_sizes(self): + """ + Return the sizes ('areas') of the elements in the collection. + + Returns + ------- + array + The 'area' of each element. + """ + return self._sizes + + def set_sizes(self, sizes, dpi=72.0): + """ + Set the sizes of each member of the collection. + + Parameters + ---------- + sizes : `numpy.ndarray` or None + The size to set for each element of the collection. The + value is the 'area' of the element. + dpi : float, default: 72 + The dpi of the canvas. + """ + if sizes is None: + self._sizes = np.array([]) + self._transforms = np.empty((0, 3, 3)) + else: + self._sizes = np.asarray(sizes) + self._transforms = np.zeros((len(self._sizes), 3, 3)) + scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor + self._transforms[:, 0, 0] = scale + self._transforms[:, 1, 1] = scale + self._transforms[:, 2, 2] = 1.0 + self.stale = True + + @artist.allow_rasterization + def draw(self, renderer): + self.set_sizes(self._sizes, self.get_figure(root=True).dpi) + super().draw(renderer) + + +class PathCollection(_CollectionWithSizes): + r""" + A collection of `~.path.Path`\s, as created by e.g. `~.Axes.scatter`. + """ + + def __init__(self, paths, sizes=None, **kwargs): + """ + Parameters + ---------- + paths : list of `.path.Path` + The paths that will make up the `.Collection`. + sizes : array-like + The factor by which to scale each drawn `~.path.Path`. One unit + squared in the Path's data space is scaled to be ``sizes**2`` + points when rendered. + **kwargs + Forwarded to `.Collection`. + """ + + super().__init__(**kwargs) + self.set_paths(paths) + self.set_sizes(sizes) + self.stale = True + + def get_paths(self): + return self._paths + + def legend_elements(self, prop="colors", num="auto", + fmt=None, func=lambda x: x, **kwargs): + """ + Create legend handles and labels for a PathCollection. + + Each legend handle is a `.Line2D` representing the Path that was drawn, + and each label is a string that represents the Path. + + This is useful for obtaining a legend for a `~.Axes.scatter` plot; + e.g.:: + + scatter = plt.scatter([1, 2, 3], [4, 5, 6], c=[7, 2, 3], num=None) + plt.legend(*scatter.legend_elements()) + + creates three legend elements, one for each color with the numerical + values passed to *c* as the labels. + + Also see the :ref:`automatedlegendcreation` example. + + Parameters + ---------- + prop : {"colors", "sizes"}, default: "colors" + If "colors", the legend handles will show the different colors of + the collection. If "sizes", the legend will show the different + sizes. To set both, use *kwargs* to directly edit the `.Line2D` + properties. + num : int, None, "auto" (default), array-like, or `~.ticker.Locator` + Target number of elements to create. + If None, use all unique elements of the mappable array. If an + integer, target to use *num* elements in the normed range. + If *"auto"*, try to determine which option better suits the nature + of the data. + The number of created elements may slightly deviate from *num* due + to a `~.ticker.Locator` being used to find useful locations. + If a list or array, use exactly those elements for the legend. + Finally, a `~.ticker.Locator` can be provided. + fmt : str, `~matplotlib.ticker.Formatter`, or None (default) + The format or formatter to use for the labels. If a string must be + a valid input for a `.StrMethodFormatter`. If None (the default), + use a `.ScalarFormatter`. + func : function, default: ``lambda x: x`` + Function to calculate the labels. Often the size (or color) + argument to `~.Axes.scatter` will have been pre-processed by the + user using a function ``s = f(x)`` to make the markers visible; + e.g. ``size = np.log10(x)``. Providing the inverse of this + function here allows that pre-processing to be inverted, so that + the legend labels have the correct values; e.g. ``func = lambda + x: 10**x``. + **kwargs + Allowed keyword arguments are *color* and *size*. E.g. it may be + useful to set the color of the markers if *prop="sizes"* is used; + similarly to set the size of the markers if *prop="colors"* is + used. Any further parameters are passed onto the `.Line2D` + instance. This may be useful to e.g. specify a different + *markeredgecolor* or *alpha* for the legend handles. + + Returns + ------- + handles : list of `.Line2D` + Visual representation of each element of the legend. + labels : list of str + The string labels for elements of the legend. + """ + handles = [] + labels = [] + hasarray = self.get_array() is not None + if fmt is None: + fmt = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=True) + elif isinstance(fmt, str): + fmt = mpl.ticker.StrMethodFormatter(fmt) + fmt.create_dummy_axis() + + if prop == "colors": + if not hasarray: + warnings.warn("Collection without array used. Make sure to " + "specify the values to be colormapped via the " + "`c` argument.") + return handles, labels + u = np.unique(self.get_array()) + size = kwargs.pop("size", mpl.rcParams["lines.markersize"]) + elif prop == "sizes": + u = np.unique(self.get_sizes()) + color = kwargs.pop("color", "k") + else: + raise ValueError("Valid values for `prop` are 'colors' or " + f"'sizes'. You supplied '{prop}' instead.") + + fu = func(u) + fmt.axis.set_view_interval(fu.min(), fu.max()) + fmt.axis.set_data_interval(fu.min(), fu.max()) + if num == "auto": + num = 9 + if len(u) <= num: + num = None + if num is None: + values = u + label_values = func(values) + else: + if prop == "colors": + arr = self.get_array() + elif prop == "sizes": + arr = self.get_sizes() + if isinstance(num, mpl.ticker.Locator): + loc = num + elif np.iterable(num): + loc = mpl.ticker.FixedLocator(num) + else: + num = int(num) + loc = mpl.ticker.MaxNLocator(nbins=num, min_n_ticks=num-1, + steps=[1, 2, 2.5, 3, 5, 6, 8, 10]) + label_values = loc.tick_values(func(arr).min(), func(arr).max()) + cond = ((label_values >= func(arr).min()) & + (label_values <= func(arr).max())) + label_values = label_values[cond] + yarr = np.linspace(arr.min(), arr.max(), 256) + xarr = func(yarr) + ix = np.argsort(xarr) + values = np.interp(label_values, xarr[ix], yarr[ix]) + + kw = {"markeredgewidth": self.get_linewidths()[0], + "alpha": self.get_alpha(), + **kwargs} + + for val, lab in zip(values, label_values): + if prop == "colors": + color = self.cmap(self.norm(val)) + elif prop == "sizes": + size = np.sqrt(val) + if np.isclose(size, 0.0): + continue + h = mlines.Line2D([0], [0], ls="", color=color, ms=size, + marker=self.get_paths()[0], **kw) + handles.append(h) + if hasattr(fmt, "set_locs"): + fmt.set_locs(label_values) + l = fmt(lab) + labels.append(l) + + return handles, labels + + +class PolyCollection(_CollectionWithSizes): + + def __init__(self, verts, sizes=None, *, closed=True, **kwargs): + """ + Parameters + ---------- + verts : list of array-like + The sequence of polygons [*verts0*, *verts1*, ...] where each + element *verts_i* defines the vertices of polygon *i* as a 2D + array-like of shape (M, 2). + sizes : array-like, default: None + Squared scaling factors for the polygons. The coordinates of each + polygon *verts_i* are multiplied by the square-root of the + corresponding entry in *sizes* (i.e., *sizes* specify the scaling + of areas). The scaling is applied before the Artist master + transform. + closed : bool, default: True + Whether the polygon should be closed by adding a CLOSEPOLY + connection at the end. + **kwargs + Forwarded to `.Collection`. + """ + super().__init__(**kwargs) + self.set_sizes(sizes) + self.set_verts(verts, closed) + self.stale = True + + def set_verts(self, verts, closed=True): + """ + Set the vertices of the polygons. + + Parameters + ---------- + verts : list of array-like + The sequence of polygons [*verts0*, *verts1*, ...] where each + element *verts_i* defines the vertices of polygon *i* as a 2D + array-like of shape (M, 2). + closed : bool, default: True + Whether the polygon should be closed by adding a CLOSEPOLY + connection at the end. + """ + self.stale = True + if isinstance(verts, np.ma.MaskedArray): + verts = verts.astype(float).filled(np.nan) + + # No need to do anything fancy if the path isn't closed. + if not closed: + self._paths = [mpath.Path(xy) for xy in verts] + return + + # Fast path for arrays + if isinstance(verts, np.ndarray) and len(verts.shape) == 3: + verts_pad = np.concatenate((verts, verts[:, :1]), axis=1) + # Creating the codes once is much faster than having Path do it + # separately each time by passing closed=True. + codes = np.empty(verts_pad.shape[1], dtype=mpath.Path.code_type) + codes[:] = mpath.Path.LINETO + codes[0] = mpath.Path.MOVETO + codes[-1] = mpath.Path.CLOSEPOLY + self._paths = [mpath.Path(xy, codes) for xy in verts_pad] + return + + self._paths = [] + for xy in verts: + if len(xy): + self._paths.append(mpath.Path._create_closed(xy)) + else: + self._paths.append(mpath.Path(xy)) + + set_paths = set_verts + + def set_verts_and_codes(self, verts, codes): + """Initialize vertices with path codes.""" + if len(verts) != len(codes): + raise ValueError("'codes' must be a 1D list or array " + "with the same length of 'verts'") + self._paths = [mpath.Path(xy, cds) if len(xy) else mpath.Path(xy) + for xy, cds in zip(verts, codes)] + self.stale = True + + +class FillBetweenPolyCollection(PolyCollection): + """ + `.PolyCollection` that fills the area between two x- or y-curves. + """ + def __init__( + self, t_direction, t, f1, f2, *, + where=None, interpolate=False, step=None, **kwargs): + """ + Parameters + ---------- + t_direction : {{'x', 'y'}} + The axes on which the variable lies. + + - 'x': the curves are ``(t, f1)`` and ``(t, f2)``. + - 'y': the curves are ``(f1, t)`` and ``(f2, t)``. + + t : array (length N) + The ``t_direction`` coordinates of the nodes defining the curves. + + f1 : array (length N) or scalar + The other coordinates of the nodes defining the first curve. + + f2 : array (length N) or scalar + The other coordinates of the nodes defining the second curve. + + where : array of bool (length N), optional + Define *where* to exclude some {dir} regions from being filled. + The filled regions are defined by the coordinates ``t[where]``. + More precisely, fill between ``t[i]`` and ``t[i+1]`` if + ``where[i] and where[i+1]``. Note that this definition implies + that an isolated *True* value between two *False* values in *where* + will not result in filling. Both sides of the *True* position + remain unfilled due to the adjacent *False* values. + + interpolate : bool, default: False + This option is only relevant if *where* is used and the two curves + are crossing each other. + + Semantically, *where* is often used for *f1* > *f2* or + similar. By default, the nodes of the polygon defining the filled + region will only be placed at the positions in the *t* array. + Such a polygon cannot describe the above semantics close to the + intersection. The t-sections containing the intersection are + simply clipped. + + Setting *interpolate* to *True* will calculate the actual + intersection point and extend the filled region up to this point. + + step : {{'pre', 'post', 'mid'}}, optional + Define *step* if the filling should be a step function, + i.e. constant in between *t*. The value determines where the + step will occur: + + - 'pre': The f value is continued constantly to the left from + every *t* position, i.e. the interval ``(t[i-1], t[i]]`` has the + value ``f[i]``. + - 'post': The y value is continued constantly to the right from + every *x* position, i.e. the interval ``[t[i], t[i+1])`` has the + value ``f[i]``. + - 'mid': Steps occur half-way between the *t* positions. + + **kwargs + Forwarded to `.PolyCollection`. + + See Also + -------- + .Axes.fill_between, .Axes.fill_betweenx + """ + self.t_direction = t_direction + self._interpolate = interpolate + self._step = step + verts = self._make_verts(t, f1, f2, where) + super().__init__(verts, **kwargs) + + @staticmethod + def _f_dir_from_t(t_direction): + """The direction that is other than `t_direction`.""" + if t_direction == "x": + return "y" + elif t_direction == "y": + return "x" + else: + msg = f"t_direction must be 'x' or 'y', got {t_direction!r}" + raise ValueError(msg) + + @property + def _f_direction(self): + """The direction that is other than `self.t_direction`.""" + return self._f_dir_from_t(self.t_direction) + + def set_data(self, t, f1, f2, *, where=None): + """ + Set new values for the two bounding curves. + + Parameters + ---------- + t : array (length N) + The ``self.t_direction`` coordinates of the nodes defining the curves. + + f1 : array (length N) or scalar + The other coordinates of the nodes defining the first curve. + + f2 : array (length N) or scalar + The other coordinates of the nodes defining the second curve. + + where : array of bool (length N), optional + Define *where* to exclude some {dir} regions from being filled. + The filled regions are defined by the coordinates ``t[where]``. + More precisely, fill between ``t[i]`` and ``t[i+1]`` if + ``where[i] and where[i+1]``. Note that this definition implies + that an isolated *True* value between two *False* values in *where* + will not result in filling. Both sides of the *True* position + remain unfilled due to the adjacent *False* values. + + See Also + -------- + .PolyCollection.set_verts, .Line2D.set_data + """ + t, f1, f2 = self.axes._fill_between_process_units( + self.t_direction, self._f_direction, t, f1, f2) + + verts = self._make_verts(t, f1, f2, where) + self.set_verts(verts) + + def get_datalim(self, transData): + """Calculate the data limits and return them as a `.Bbox`.""" + datalim = transforms.Bbox.null() + datalim.update_from_data_xy((self.get_transform() - transData).transform( + np.concatenate([self._bbox, [self._bbox.minpos]]))) + return datalim + + def _make_verts(self, t, f1, f2, where): + """ + Make verts that can be forwarded to `.PolyCollection`. + """ + self._validate_shapes(self.t_direction, self._f_direction, t, f1, f2) + + where = self._get_data_mask(t, f1, f2, where) + t, f1, f2 = np.broadcast_arrays(np.atleast_1d(t), f1, f2, subok=True) + + self._bbox = transforms.Bbox.null() + self._bbox.update_from_data_xy(self._fix_pts_xy_order(np.concatenate([ + np.stack((t[where], f[where]), axis=-1) for f in (f1, f2)]))) + + return [ + self._make_verts_for_region(t, f1, f2, idx0, idx1) + for idx0, idx1 in cbook.contiguous_regions(where) + ] + + def _get_data_mask(self, t, f1, f2, where): + """ + Return a bool array, with True at all points that should eventually be rendered. + + The array is True at a point if none of the data inputs + *t*, *f1*, *f2* is masked and if the input *where* is true at that point. + """ + if where is None: + where = True + else: + where = np.asarray(where, dtype=bool) + if where.size != t.size: + msg = "where size ({}) does not match {!r} size ({})".format( + where.size, self.t_direction, t.size) + raise ValueError(msg) + return where & ~functools.reduce( + np.logical_or, map(np.ma.getmaskarray, [t, f1, f2])) + + @staticmethod + def _validate_shapes(t_dir, f_dir, t, f1, f2): + """Validate that t, f1 and f2 are 1-dimensional and have the same length.""" + names = (d + s for d, s in zip((t_dir, f_dir, f_dir), ("", "1", "2"))) + for name, array in zip(names, [t, f1, f2]): + if array.ndim > 1: + raise ValueError(f"{name!r} is not 1-dimensional") + if t.size > 1 and array.size > 1 and t.size != array.size: + msg = "{!r} has size {}, but {!r} has an unequal size of {}".format( + t_dir, t.size, name, array.size) + raise ValueError(msg) + + def _make_verts_for_region(self, t, f1, f2, idx0, idx1): + """ + Make ``verts`` for a contiguous region between ``idx0`` and ``idx1``, taking + into account ``step`` and ``interpolate``. + """ + t_slice = t[idx0:idx1] + f1_slice = f1[idx0:idx1] + f2_slice = f2[idx0:idx1] + if self._step is not None: + step_func = cbook.STEP_LOOKUP_MAP["steps-" + self._step] + t_slice, f1_slice, f2_slice = step_func(t_slice, f1_slice, f2_slice) + + if self._interpolate: + start = self._get_interpolating_points(t, f1, f2, idx0) + end = self._get_interpolating_points(t, f1, f2, idx1) + else: + # Handle scalar f2 (e.g. 0): the fill should go all + # the way down to 0 even if none of the dep1 sample points do. + start = t_slice[0], f2_slice[0] + end = t_slice[-1], f2_slice[-1] + + pts = np.concatenate(( + np.asarray([start]), + np.stack((t_slice, f1_slice), axis=-1), + np.asarray([end]), + np.stack((t_slice, f2_slice), axis=-1)[::-1])) + + return self._fix_pts_xy_order(pts) + + @classmethod + def _get_interpolating_points(cls, t, f1, f2, idx): + """Calculate interpolating points.""" + im1 = max(idx - 1, 0) + t_values = t[im1:idx+1] + diff_values = f1[im1:idx+1] - f2[im1:idx+1] + f1_values = f1[im1:idx+1] + + if len(diff_values) == 2: + if np.ma.is_masked(diff_values[1]): + return t[im1], f1[im1] + elif np.ma.is_masked(diff_values[0]): + return t[idx], f1[idx] + + diff_root_t = cls._get_diff_root(0, diff_values, t_values) + diff_root_f = cls._get_diff_root(diff_root_t, t_values, f1_values) + return diff_root_t, diff_root_f + + @staticmethod + def _get_diff_root(x, xp, fp): + """Calculate diff root.""" + order = xp.argsort() + return np.interp(x, xp[order], fp[order]) + + def _fix_pts_xy_order(self, pts): + """ + Fix pts calculation results with `self.t_direction`. + + In the workflow, it is assumed that `self.t_direction` is 'x'. If this + is not true, we need to exchange the coordinates. + """ + return pts[:, ::-1] if self.t_direction == "y" else pts + + +class RegularPolyCollection(_CollectionWithSizes): + """A collection of n-sided regular polygons.""" + + _path_generator = mpath.Path.unit_regular_polygon + _factor = np.pi ** (-1/2) + + def __init__(self, + numsides, + *, + rotation=0, + sizes=(1,), + **kwargs): + """ + Parameters + ---------- + numsides : int + The number of sides of the polygon. + rotation : float + The rotation of the polygon in radians. + sizes : tuple of float + The area of the circle circumscribing the polygon in points^2. + **kwargs + Forwarded to `.Collection`. + + Examples + -------- + See :doc:`/gallery/event_handling/lasso_demo` for a complete example:: + + offsets = np.random.rand(20, 2) + facecolors = [cm.jet(x) for x in np.random.rand(20)] + + collection = RegularPolyCollection( + numsides=5, # a pentagon + rotation=0, sizes=(50,), + facecolors=facecolors, + edgecolors=("black",), + linewidths=(1,), + offsets=offsets, + offset_transform=ax.transData, + ) + """ + super().__init__(**kwargs) + self.set_sizes(sizes) + self._numsides = numsides + self._paths = [self._path_generator(numsides)] + self._rotation = rotation + self.set_transform(transforms.IdentityTransform()) + + def get_numsides(self): + return self._numsides + + def get_rotation(self): + return self._rotation + + @artist.allow_rasterization + def draw(self, renderer): + self.set_sizes(self._sizes, self.get_figure(root=True).dpi) + self._transforms = [ + transforms.Affine2D(x).rotate(-self._rotation).get_matrix() + for x in self._transforms + ] + # Explicitly not super().draw, because set_sizes must be called before + # updating self._transforms. + Collection.draw(self, renderer) + + +class StarPolygonCollection(RegularPolyCollection): + """Draw a collection of regular stars with *numsides* points.""" + _path_generator = mpath.Path.unit_regular_star + + +class AsteriskPolygonCollection(RegularPolyCollection): + """Draw a collection of regular asterisks with *numsides* points.""" + _path_generator = mpath.Path.unit_regular_asterisk + + +class LineCollection(Collection): + r""" + Represents a sequence of `.Line2D`\s that should be drawn together. + + This class extends `.Collection` to represent a sequence of + `.Line2D`\s instead of just a sequence of `.Patch`\s. + Just as in `.Collection`, each property of a *LineCollection* may be either + a single value or a list of values. This list is then used cyclically for + each element of the LineCollection, so the property of the ``i``\th element + of the collection is:: + + prop[i % len(prop)] + + The properties of each member of a *LineCollection* default to their values + in :rc:`lines.*` instead of :rc:`patch.*`, and the property *colors* is + added in place of *edgecolors*. + """ + + _edge_default = True + + def __init__(self, segments, # Can be None. + *, + zorder=2, # Collection.zorder is 1 + **kwargs + ): + """ + Parameters + ---------- + segments : list of (N, 2) array-like + A sequence ``[line0, line1, ...]`` where each line is a (N, 2)-shape + array-like containing points:: + + line0 = [(x0, y0), (x1, y1), ...] + + Each line can contain a different number of points. + linewidths : float or list of float, default: :rc:`lines.linewidth` + The width of each line in points. + colors : :mpltype:`color` or list of color, default: :rc:`lines.color` + A sequence of RGBA tuples (e.g., arbitrary color strings, etc, not + allowed). + antialiaseds : bool or list of bool, default: :rc:`lines.antialiased` + Whether to use antialiasing for each line. + zorder : float, default: 2 + zorder of the lines once drawn. + + facecolors : :mpltype:`color` or list of :mpltype:`color`, default: 'none' + When setting *facecolors*, each line is interpreted as a boundary + for an area, implicitly closing the path from the last point to the + first point. The enclosed area is filled with *facecolor*. + In order to manually specify what should count as the "interior" of + each line, please use `.PathCollection` instead, where the + "interior" can be specified by appropriate usage of + `~.path.Path.CLOSEPOLY`. + + **kwargs + Forwarded to `.Collection`. + """ + # Unfortunately, mplot3d needs this explicit setting of 'facecolors'. + kwargs.setdefault('facecolors', 'none') + super().__init__( + zorder=zorder, + **kwargs) + self.set_segments(segments) + + def set_segments(self, segments): + if segments is None: + return + + self._paths = [mpath.Path(seg) if isinstance(seg, np.ma.MaskedArray) + else mpath.Path(np.asarray(seg, float)) + for seg in segments] + self.stale = True + + set_verts = set_segments # for compatibility with PolyCollection + set_paths = set_segments + + def get_segments(self): + """ + Returns + ------- + list + List of segments in the LineCollection. Each list item contains an + array of vertices. + """ + segments = [] + + for path in self._paths: + vertices = [ + vertex + for vertex, _ + # Never simplify here, we want to get the data-space values + # back and there in no way to know the "right" simplification + # threshold so never try. + in path.iter_segments(simplify=False) + ] + vertices = np.asarray(vertices) + segments.append(vertices) + + return segments + + def _get_default_linewidth(self): + return mpl.rcParams['lines.linewidth'] + + def _get_default_antialiased(self): + return mpl.rcParams['lines.antialiased'] + + def _get_default_edgecolor(self): + return mpl.rcParams['lines.color'] + + def _get_default_facecolor(self): + return 'none' + + def set_alpha(self, alpha): + # docstring inherited + super().set_alpha(alpha) + if self._gapcolor is not None: + self.set_gapcolor(self._original_gapcolor) + + def set_color(self, c): + """ + Set the edgecolor(s) of the LineCollection. + + Parameters + ---------- + c : :mpltype:`color` or list of :mpltype:`color` + Single color (all lines have same color), or a + sequence of RGBA tuples; if it is a sequence the lines will + cycle through the sequence. + """ + self.set_edgecolor(c) + + set_colors = set_color + + def get_color(self): + return self._edgecolors + + get_colors = get_color # for compatibility with old versions + + def set_gapcolor(self, gapcolor): + """ + Set a color to fill the gaps in the dashed line style. + + .. note:: + + Striped lines are created by drawing two interleaved dashed lines. + There can be overlaps between those two, which may result in + artifacts when using transparency. + + This functionality is experimental and may change. + + Parameters + ---------- + gapcolor : :mpltype:`color` or list of :mpltype:`color` or None + The color with which to fill the gaps. If None, the gaps are + unfilled. + """ + self._original_gapcolor = gapcolor + self._set_gapcolor(gapcolor) + + def _set_gapcolor(self, gapcolor): + if gapcolor is not None: + gapcolor = mcolors.to_rgba_array(gapcolor, self._alpha) + self._gapcolor = gapcolor + self.stale = True + + def get_gapcolor(self): + return self._gapcolor + + def _get_inverse_paths_linestyles(self): + """ + Returns the path and pattern for the gaps in the non-solid lines. + + This path and pattern is the inverse of the path and pattern used to + construct the non-solid lines. For solid lines, we set the inverse path + to nans to prevent drawing an inverse line. + """ + path_patterns = [ + (mpath.Path(np.full((1, 2), np.nan)), ls) + if ls == (0, None) else + (path, mlines._get_inverse_dash_pattern(*ls)) + for (path, ls) in + zip(self._paths, itertools.cycle(self._linestyles))] + + return zip(*path_patterns) + + +class EventCollection(LineCollection): + """ + A collection of locations along a single axis at which an "event" occurred. + + The events are given by a 1-dimensional array. They do not have an + amplitude and are displayed as parallel lines. + """ + + _edge_default = True + + def __init__(self, + positions, # Cannot be None. + orientation='horizontal', + *, + lineoffset=0, + linelength=1, + linewidth=None, + color=None, + linestyle='solid', + antialiased=None, + **kwargs + ): + """ + Parameters + ---------- + positions : 1D array-like + Each value is an event. + orientation : {'horizontal', 'vertical'}, default: 'horizontal' + The sequence of events is plotted along this direction. + The marker lines of the single events are along the orthogonal + direction. + lineoffset : float, default: 0 + The offset of the center of the markers from the origin, in the + direction orthogonal to *orientation*. + linelength : float, default: 1 + The total height of the marker (i.e. the marker stretches from + ``lineoffset - linelength/2`` to ``lineoffset + linelength/2``). + linewidth : float or list thereof, default: :rc:`lines.linewidth` + The line width of the event lines, in points. + color : :mpltype:`color` or list of :mpltype:`color`, default: :rc:`lines.color` + The color of the event lines. + linestyle : str or tuple or list thereof, default: 'solid' + Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', + '-', '--', '-.', ':']. Dash tuples should be of the form:: + + (offset, onoffseq), + + where *onoffseq* is an even length tuple of on and off ink + in points. + antialiased : bool or list thereof, default: :rc:`lines.antialiased` + Whether to use antialiasing for drawing the lines. + **kwargs + Forwarded to `.LineCollection`. + + Examples + -------- + .. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py + """ + super().__init__([], + linewidths=linewidth, linestyles=linestyle, + colors=color, antialiaseds=antialiased, + **kwargs) + self._is_horizontal = True # Initial value, may be switched below. + self._linelength = linelength + self._lineoffset = lineoffset + self.set_orientation(orientation) + self.set_positions(positions) + + def get_positions(self): + """ + Return an array containing the floating-point values of the positions. + """ + pos = 0 if self.is_horizontal() else 1 + return [segment[0, pos] for segment in self.get_segments()] + + def set_positions(self, positions): + """Set the positions of the events.""" + if positions is None: + positions = [] + if np.ndim(positions) != 1: + raise ValueError('positions must be one-dimensional') + lineoffset = self.get_lineoffset() + linelength = self.get_linelength() + pos_idx = 0 if self.is_horizontal() else 1 + segments = np.empty((len(positions), 2, 2)) + segments[:, :, pos_idx] = np.sort(positions)[:, None] + segments[:, 0, 1 - pos_idx] = lineoffset + linelength / 2 + segments[:, 1, 1 - pos_idx] = lineoffset - linelength / 2 + self.set_segments(segments) + + def add_positions(self, position): + """Add one or more events at the specified positions.""" + if position is None or (hasattr(position, 'len') and + len(position) == 0): + return + positions = self.get_positions() + positions = np.hstack([positions, np.asanyarray(position)]) + self.set_positions(positions) + extend_positions = append_positions = add_positions + + def is_horizontal(self): + """True if the eventcollection is horizontal, False if vertical.""" + return self._is_horizontal + + def get_orientation(self): + """ + Return the orientation of the event line ('horizontal' or 'vertical'). + """ + return 'horizontal' if self.is_horizontal() else 'vertical' + + def switch_orientation(self): + """ + Switch the orientation of the event line, either from vertical to + horizontal or vice versus. + """ + segments = self.get_segments() + for i, segment in enumerate(segments): + segments[i] = np.fliplr(segment) + self.set_segments(segments) + self._is_horizontal = not self.is_horizontal() + self.stale = True + + def set_orientation(self, orientation): + """ + Set the orientation of the event line. + + Parameters + ---------- + orientation : {'horizontal', 'vertical'} + """ + is_horizontal = _api.check_getitem( + {"horizontal": True, "vertical": False}, + orientation=orientation) + if is_horizontal == self.is_horizontal(): + return + self.switch_orientation() + + def get_linelength(self): + """Return the length of the lines used to mark each event.""" + return self._linelength + + def set_linelength(self, linelength): + """Set the length of the lines used to mark each event.""" + if linelength == self.get_linelength(): + return + lineoffset = self.get_lineoffset() + segments = self.get_segments() + pos = 1 if self.is_horizontal() else 0 + for segment in segments: + segment[0, pos] = lineoffset + linelength / 2. + segment[1, pos] = lineoffset - linelength / 2. + self.set_segments(segments) + self._linelength = linelength + + def get_lineoffset(self): + """Return the offset of the lines used to mark each event.""" + return self._lineoffset + + def set_lineoffset(self, lineoffset): + """Set the offset of the lines used to mark each event.""" + if lineoffset == self.get_lineoffset(): + return + linelength = self.get_linelength() + segments = self.get_segments() + pos = 1 if self.is_horizontal() else 0 + for segment in segments: + segment[0, pos] = lineoffset + linelength / 2. + segment[1, pos] = lineoffset - linelength / 2. + self.set_segments(segments) + self._lineoffset = lineoffset + + def get_linewidth(self): + """Get the width of the lines used to mark each event.""" + return super().get_linewidth()[0] + + def get_linewidths(self): + return super().get_linewidth() + + def get_color(self): + """Return the color of the lines used to mark each event.""" + return self.get_colors()[0] + + +class CircleCollection(_CollectionWithSizes): + """A collection of circles, drawn using splines.""" + + _factor = np.pi ** (-1/2) + + def __init__(self, sizes, **kwargs): + """ + Parameters + ---------- + sizes : float or array-like + The area of each circle in points^2. + **kwargs + Forwarded to `.Collection`. + """ + super().__init__(**kwargs) + self.set_sizes(sizes) + self.set_transform(transforms.IdentityTransform()) + self._paths = [mpath.Path.unit_circle()] + + +class EllipseCollection(Collection): + """A collection of ellipses, drawn using splines.""" + + def __init__(self, widths, heights, angles, *, units='points', **kwargs): + """ + Parameters + ---------- + widths : array-like + The lengths of the first axes (e.g., major axis lengths). + heights : array-like + The lengths of second axes. + angles : array-like + The angles of the first axes, degrees CCW from the x-axis. + units : {'points', 'inches', 'dots', 'width', 'height', 'x', 'y', 'xy'} + The units in which majors and minors are given; 'width' and + 'height' refer to the dimensions of the axes, while 'x' and 'y' + refer to the *offsets* data units. 'xy' differs from all others in + that the angle as plotted varies with the aspect ratio, and equals + the specified angle only when the aspect ratio is unity. Hence + it behaves the same as the `~.patches.Ellipse` with + ``axes.transData`` as its transform. + **kwargs + Forwarded to `Collection`. + """ + super().__init__(**kwargs) + self.set_widths(widths) + self.set_heights(heights) + self.set_angles(angles) + self._units = units + self.set_transform(transforms.IdentityTransform()) + self._transforms = np.empty((0, 3, 3)) + self._paths = [mpath.Path.unit_circle()] + + def _set_transforms(self): + """Calculate transforms immediately before drawing.""" + + ax = self.axes + fig = self.get_figure(root=False) + + if self._units == 'xy': + sc = 1 + elif self._units == 'x': + sc = ax.bbox.width / ax.viewLim.width + elif self._units == 'y': + sc = ax.bbox.height / ax.viewLim.height + elif self._units == 'inches': + sc = fig.dpi + elif self._units == 'points': + sc = fig.dpi / 72.0 + elif self._units == 'width': + sc = ax.bbox.width + elif self._units == 'height': + sc = ax.bbox.height + elif self._units == 'dots': + sc = 1.0 + else: + raise ValueError(f'Unrecognized units: {self._units!r}') + + self._transforms = np.zeros((len(self._widths), 3, 3)) + widths = self._widths * sc + heights = self._heights * sc + sin_angle = np.sin(self._angles) + cos_angle = np.cos(self._angles) + self._transforms[:, 0, 0] = widths * cos_angle + self._transforms[:, 0, 1] = heights * -sin_angle + self._transforms[:, 1, 0] = widths * sin_angle + self._transforms[:, 1, 1] = heights * cos_angle + self._transforms[:, 2, 2] = 1.0 + + _affine = transforms.Affine2D + if self._units == 'xy': + m = ax.transData.get_affine().get_matrix().copy() + m[:2, 2:] = 0 + self.set_transform(_affine(m)) + + def set_widths(self, widths): + """Set the lengths of the first axes (e.g., major axis).""" + self._widths = 0.5 * np.asarray(widths).ravel() + self.stale = True + + def set_heights(self, heights): + """Set the lengths of second axes (e.g., minor axes).""" + self._heights = 0.5 * np.asarray(heights).ravel() + self.stale = True + + def set_angles(self, angles): + """Set the angles of the first axes, degrees CCW from the x-axis.""" + self._angles = np.deg2rad(angles).ravel() + self.stale = True + + def get_widths(self): + """Get the lengths of the first axes (e.g., major axis).""" + return self._widths * 2 + + def get_heights(self): + """Set the lengths of second axes (e.g., minor axes).""" + return self._heights * 2 + + def get_angles(self): + """Get the angles of the first axes, degrees CCW from the x-axis.""" + return np.rad2deg(self._angles) + + @artist.allow_rasterization + def draw(self, renderer): + self._set_transforms() + super().draw(renderer) + + +class PatchCollection(Collection): + """ + A generic collection of patches. + + PatchCollection draws faster than a large number of equivalent individual + Patches. It also makes it easier to assign a colormap to a heterogeneous + collection of patches. + """ + + def __init__(self, patches, *, match_original=False, **kwargs): + """ + Parameters + ---------- + patches : list of `.Patch` + A sequence of Patch objects. This list may include + a heterogeneous assortment of different patch types. + + match_original : bool, default: False + If True, use the colors and linewidths of the original + patches. If False, new colors may be assigned by + providing the standard collection arguments, facecolor, + edgecolor, linewidths, norm or cmap. + + **kwargs + All other parameters are forwarded to `.Collection`. + + If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds* + are None, they default to their `.rcParams` patch setting, in + sequence form. + + Notes + ----- + The use of `~matplotlib.cm.ScalarMappable` functionality is optional. + If the `~matplotlib.cm.ScalarMappable` matrix ``_A`` has been set (via + a call to `~.ScalarMappable.set_array`), at draw time a call to scalar + mappable will be made to set the face colors. + """ + + if match_original: + def determine_facecolor(patch): + if patch.get_fill(): + return patch.get_facecolor() + return [0, 0, 0, 0] + + kwargs['facecolors'] = [determine_facecolor(p) for p in patches] + kwargs['edgecolors'] = [p.get_edgecolor() for p in patches] + kwargs['linewidths'] = [p.get_linewidth() for p in patches] + kwargs['linestyles'] = [p.get_linestyle() for p in patches] + kwargs['antialiaseds'] = [p.get_antialiased() for p in patches] + + super().__init__(**kwargs) + + self.set_paths(patches) + + def set_paths(self, patches): + paths = [p.get_transform().transform_path(p.get_path()) + for p in patches] + self._paths = paths + + +class TriMesh(Collection): + """ + Class for the efficient drawing of a triangular mesh using Gouraud shading. + + A triangular mesh is a `~matplotlib.tri.Triangulation` object. + """ + def __init__(self, triangulation, **kwargs): + super().__init__(**kwargs) + self._triangulation = triangulation + self._shading = 'gouraud' + + self._bbox = transforms.Bbox.unit() + + # Unfortunately this requires a copy, unless Triangulation + # was rewritten. + xy = np.hstack((triangulation.x.reshape(-1, 1), + triangulation.y.reshape(-1, 1))) + self._bbox.update_from_data_xy(xy) + + def get_paths(self): + if self._paths is None: + self.set_paths() + return self._paths + + def set_paths(self): + self._paths = self.convert_mesh_to_paths(self._triangulation) + + @staticmethod + def convert_mesh_to_paths(tri): + """ + Convert a given mesh into a sequence of `.Path` objects. + + This function is primarily of use to implementers of backends that do + not directly support meshes. + """ + triangles = tri.get_masked_triangles() + verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1) + return [mpath.Path(x) for x in verts] + + @artist.allow_rasterization + def draw(self, renderer): + if not self.get_visible(): + return + renderer.open_group(self.__class__.__name__, gid=self.get_gid()) + transform = self.get_transform() + + # Get a list of triangles and the color at each vertex. + tri = self._triangulation + triangles = tri.get_masked_triangles() + + verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1) + + self.update_scalarmappable() + colors = self._facecolors[triangles] + + gc = renderer.new_gc() + self._set_gc_clip(gc) + gc.set_linewidth(self.get_linewidth()[0]) + renderer.draw_gouraud_triangles(gc, verts, colors, transform.frozen()) + gc.restore() + renderer.close_group(self.__class__.__name__) + + +class _MeshData: + r""" + Class for managing the two dimensional coordinates of Quadrilateral meshes + and the associated data with them. This class is a mixin and is intended to + be used with another collection that will implement the draw separately. + + A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are + defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is + defined by the vertices :: + + (m+1, n) ----------- (m+1, n+1) + / / + / / + / / + (m, n) -------- (m, n+1) + + The mesh need not be regular and the polygons need not be convex. + + Parameters + ---------- + coordinates : (M+1, N+1, 2) array-like + The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates + of vertex (m, n). + + shading : {'flat', 'gouraud'}, default: 'flat' + """ + def __init__(self, coordinates, *, shading='flat'): + _api.check_shape((None, None, 2), coordinates=coordinates) + self._coordinates = coordinates + self._shading = shading + + def set_array(self, A): + """ + Set the data values. + + Parameters + ---------- + A : array-like + The mesh data. Supported array shapes are: + + - (M, N) or (M*N,): a mesh with scalar data. The values are mapped + to colors using normalization and a colormap. See parameters + *norm*, *cmap*, *vmin*, *vmax*. + - (M, N, 3): an image with RGB values (0-1 float or 0-255 int). + - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), + i.e. including transparency. + + If the values are provided as a 2D grid, the shape must match the + coordinates grid. If the values are 1D, they are reshaped to 2D. + M, N follow from the coordinates grid, where the coordinates grid + shape is (M, N) for 'gouraud' *shading* and (M+1, N+1) for 'flat' + shading. + """ + height, width = self._coordinates.shape[0:-1] + if self._shading == 'flat': + h, w = height - 1, width - 1 + else: + h, w = height, width + ok_shapes = [(h, w, 3), (h, w, 4), (h, w), (h * w,)] + if A is not None: + shape = np.shape(A) + if shape not in ok_shapes: + raise ValueError( + f"For X ({width}) and Y ({height}) with {self._shading} " + f"shading, A should have shape " + f"{' or '.join(map(str, ok_shapes))}, not {A.shape}") + return super().set_array(A) + + def get_coordinates(self): + """ + Return the vertices of the mesh as an (M+1, N+1, 2) array. + + M, N are the number of quadrilaterals in the rows / columns of the + mesh, corresponding to (M+1, N+1) vertices. + The last dimension specifies the components (x, y). + """ + return self._coordinates + + def get_edgecolor(self): + # docstring inherited + # Note that we want to return an array of shape (N*M, 4) + # a flattened RGBA collection + return super().get_edgecolor().reshape(-1, 4) + + def get_facecolor(self): + # docstring inherited + # Note that we want to return an array of shape (N*M, 4) + # a flattened RGBA collection + return super().get_facecolor().reshape(-1, 4) + + @staticmethod + def _convert_mesh_to_paths(coordinates): + """ + Convert a given mesh into a sequence of `.Path` objects. + + This function is primarily of use to implementers of backends that do + not directly support quadmeshes. + """ + if isinstance(coordinates, np.ma.MaskedArray): + c = coordinates.data + else: + c = coordinates + points = np.concatenate([ + c[:-1, :-1], + c[:-1, 1:], + c[1:, 1:], + c[1:, :-1], + c[:-1, :-1] + ], axis=2).reshape((-1, 5, 2)) + return [mpath.Path(x) for x in points] + + def _convert_mesh_to_triangles(self, coordinates): + """ + Convert a given mesh into a sequence of triangles, each point + with its own color. The result can be used to construct a call to + `~.RendererBase.draw_gouraud_triangles`. + """ + if isinstance(coordinates, np.ma.MaskedArray): + p = coordinates.data + else: + p = coordinates + + p_a = p[:-1, :-1] + p_b = p[:-1, 1:] + p_c = p[1:, 1:] + p_d = p[1:, :-1] + p_center = (p_a + p_b + p_c + p_d) / 4.0 + triangles = np.concatenate([ + p_a, p_b, p_center, + p_b, p_c, p_center, + p_c, p_d, p_center, + p_d, p_a, p_center, + ], axis=2).reshape((-1, 3, 2)) + + c = self.get_facecolor().reshape((*coordinates.shape[:2], 4)) + z = self.get_array() + mask = z.mask if np.ma.is_masked(z) else None + if mask is not None: + c[mask, 3] = np.nan + c_a = c[:-1, :-1] + c_b = c[:-1, 1:] + c_c = c[1:, 1:] + c_d = c[1:, :-1] + c_center = (c_a + c_b + c_c + c_d) / 4.0 + colors = np.concatenate([ + c_a, c_b, c_center, + c_b, c_c, c_center, + c_c, c_d, c_center, + c_d, c_a, c_center, + ], axis=2).reshape((-1, 3, 4)) + tmask = np.isnan(colors[..., 2, 3]) + return triangles[~tmask], colors[~tmask] + + +class QuadMesh(_MeshData, Collection): + r""" + Class for the efficient drawing of a quadrilateral mesh. + + A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are + defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is + defined by the vertices :: + + (m+1, n) ----------- (m+1, n+1) + / / + / / + / / + (m, n) -------- (m, n+1) + + The mesh need not be regular and the polygons need not be convex. + + Parameters + ---------- + coordinates : (M+1, N+1, 2) array-like + The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates + of vertex (m, n). + + antialiased : bool, default: True + + shading : {'flat', 'gouraud'}, default: 'flat' + + Notes + ----- + Unlike other `.Collection`\s, the default *pickradius* of `.QuadMesh` is 0, + i.e. `~.Artist.contains` checks whether the test point is within any of the + mesh quadrilaterals. + + """ + + def __init__(self, coordinates, *, antialiased=True, shading='flat', + **kwargs): + kwargs.setdefault("pickradius", 0) + super().__init__(coordinates=coordinates, shading=shading) + Collection.__init__(self, **kwargs) + + self._antialiased = antialiased + self._bbox = transforms.Bbox.unit() + self._bbox.update_from_data_xy(self._coordinates.reshape(-1, 2)) + self.set_mouseover(False) + + def get_paths(self): + if self._paths is None: + self.set_paths() + return self._paths + + def set_paths(self): + self._paths = self._convert_mesh_to_paths(self._coordinates) + self.stale = True + + def get_datalim(self, transData): + return (self.get_transform() - transData).transform_bbox(self._bbox) + + @artist.allow_rasterization + def draw(self, renderer): + if not self.get_visible(): + return + renderer.open_group(self.__class__.__name__, self.get_gid()) + transform = self.get_transform() + offset_trf = self.get_offset_transform() + offsets = self.get_offsets() + + if self.have_units(): + xs = self.convert_xunits(offsets[:, 0]) + ys = self.convert_yunits(offsets[:, 1]) + offsets = np.column_stack([xs, ys]) + + self.update_scalarmappable() + + if not transform.is_affine: + coordinates = self._coordinates.reshape((-1, 2)) + coordinates = transform.transform(coordinates) + coordinates = coordinates.reshape(self._coordinates.shape) + transform = transforms.IdentityTransform() + else: + coordinates = self._coordinates + + if not offset_trf.is_affine: + offsets = offset_trf.transform_non_affine(offsets) + offset_trf = offset_trf.get_affine() + + gc = renderer.new_gc() + gc.set_snap(self.get_snap()) + self._set_gc_clip(gc) + gc.set_linewidth(self.get_linewidth()[0]) + + if self._shading == 'gouraud': + triangles, colors = self._convert_mesh_to_triangles(coordinates) + renderer.draw_gouraud_triangles( + gc, triangles, colors, transform.frozen()) + else: + renderer.draw_quad_mesh( + gc, transform.frozen(), + coordinates.shape[1] - 1, coordinates.shape[0] - 1, + coordinates, offsets, offset_trf, + # Backends expect flattened rgba arrays (n*m, 4) for fc and ec + self.get_facecolor().reshape((-1, 4)), + self._antialiased, self.get_edgecolors().reshape((-1, 4))) + gc.restore() + renderer.close_group(self.__class__.__name__) + self.stale = False + + def get_cursor_data(self, event): + contained, info = self.contains(event) + if contained and self.get_array() is not None: + return self.get_array().ravel()[info["ind"]] + return None + + +class PolyQuadMesh(_MeshData, PolyCollection): + """ + Class for drawing a quadrilateral mesh as individual Polygons. + + A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are + defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is + defined by the vertices :: + + (m+1, n) ----------- (m+1, n+1) + / / + / / + / / + (m, n) -------- (m, n+1) + + The mesh need not be regular and the polygons need not be convex. + + Parameters + ---------- + coordinates : (M+1, N+1, 2) array-like + The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates + of vertex (m, n). + + Notes + ----- + Unlike `.QuadMesh`, this class will draw each cell as an individual Polygon. + This is significantly slower, but allows for more flexibility when wanting + to add additional properties to the cells, such as hatching. + + Another difference from `.QuadMesh` is that if any of the vertices or data + of a cell are masked, that Polygon will **not** be drawn and it won't be in + the list of paths returned. + """ + + def __init__(self, coordinates, **kwargs): + super().__init__(coordinates=coordinates) + PolyCollection.__init__(self, verts=[], **kwargs) + # Setting the verts updates the paths of the PolyCollection + # This is called after the initializers to make sure the kwargs + # have all been processed and available for the masking calculations + self._set_unmasked_verts() + + def _get_unmasked_polys(self): + """Get the unmasked regions using the coordinates and array""" + # mask(X) | mask(Y) + mask = np.any(np.ma.getmaskarray(self._coordinates), axis=-1) + + # We want the shape of the polygon, which is the corner of each X/Y array + mask = (mask[0:-1, 0:-1] | mask[1:, 1:] | mask[0:-1, 1:] | mask[1:, 0:-1]) + arr = self.get_array() + if arr is not None: + arr = np.ma.getmaskarray(arr) + if arr.ndim == 3: + # RGB(A) case + mask |= np.any(arr, axis=-1) + elif arr.ndim == 2: + mask |= arr + else: + mask |= arr.reshape(self._coordinates[:-1, :-1, :].shape[:2]) + return ~mask + + def _set_unmasked_verts(self): + X = self._coordinates[..., 0] + Y = self._coordinates[..., 1] + + unmask = self._get_unmasked_polys() + X1 = np.ma.filled(X[:-1, :-1])[unmask] + Y1 = np.ma.filled(Y[:-1, :-1])[unmask] + X2 = np.ma.filled(X[1:, :-1])[unmask] + Y2 = np.ma.filled(Y[1:, :-1])[unmask] + X3 = np.ma.filled(X[1:, 1:])[unmask] + Y3 = np.ma.filled(Y[1:, 1:])[unmask] + X4 = np.ma.filled(X[:-1, 1:])[unmask] + Y4 = np.ma.filled(Y[:-1, 1:])[unmask] + npoly = len(X1) + + xy = np.ma.stack([X1, Y1, X2, Y2, X3, Y3, X4, Y4, X1, Y1], axis=-1) + verts = xy.reshape((npoly, 5, 2)) + self.set_verts(verts) + + def get_edgecolor(self): + # docstring inherited + # We only want to return the facecolors of the polygons + # that were drawn. + ec = super().get_edgecolor() + unmasked_polys = self._get_unmasked_polys().ravel() + if len(ec) != len(unmasked_polys): + # Mapping is off + return ec + return ec[unmasked_polys, :] + + def get_facecolor(self): + # docstring inherited + # We only want to return the facecolors of the polygons + # that were drawn. + fc = super().get_facecolor() + unmasked_polys = self._get_unmasked_polys().ravel() + if len(fc) != len(unmasked_polys): + # Mapping is off + return fc + return fc[unmasked_polys, :] + + def set_array(self, A): + # docstring inherited + prev_unmask = self._get_unmasked_polys() + super().set_array(A) + # If the mask has changed at all we need to update + # the set of Polys that we are drawing + if not np.array_equal(prev_unmask, self._get_unmasked_polys()): + self._set_unmasked_verts() diff --git a/moondream/lib/python3.10/site-packages/matplotlib/container.pyi b/moondream/lib/python3.10/site-packages/matplotlib/container.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c66e7ba4b4c32fc5e27fe06761efb6a3c7f86172 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/container.pyi @@ -0,0 +1,56 @@ +from matplotlib.artist import Artist +from matplotlib.lines import Line2D +from matplotlib.collections import LineCollection +from matplotlib.patches import Rectangle + +from collections.abc import Callable +from typing import Any, Literal +from numpy.typing import ArrayLike + +class Container(tuple): + def __new__(cls, *args, **kwargs): ... + def __init__(self, kl, label: Any | None = ...) -> None: ... + def remove(self) -> None: ... + def get_children(self) -> list[Artist]: ... + def get_label(self) -> str | None: ... + def set_label(self, s: Any) -> None: ... + def add_callback(self, func: Callable[[Artist], Any]) -> int: ... + def remove_callback(self, oid: int) -> None: ... + def pchanged(self) -> None: ... + +class BarContainer(Container): + patches: list[Rectangle] + errorbar: None | ErrorbarContainer + datavalues: None | ArrayLike + orientation: None | Literal["vertical", "horizontal"] + def __init__( + self, + patches: list[Rectangle], + errorbar: ErrorbarContainer | None = ..., + *, + datavalues: ArrayLike | None = ..., + orientation: Literal["vertical", "horizontal"] | None = ..., + **kwargs + ) -> None: ... + +class ErrorbarContainer(Container): + lines: tuple[Line2D, tuple[Line2D, ...], tuple[LineCollection, ...]] + has_xerr: bool + has_yerr: bool + def __init__( + self, + lines: tuple[Line2D, tuple[Line2D, ...], tuple[LineCollection, ...]], + has_xerr: bool = ..., + has_yerr: bool = ..., + **kwargs + ) -> None: ... + +class StemContainer(Container): + markerline: Line2D + stemlines: LineCollection + baseline: Line2D + def __init__( + self, + markerline_stemlines_baseline: tuple[Line2D, LineCollection, Line2D], + **kwargs + ) -> None: ... diff --git a/moondream/lib/python3.10/site-packages/matplotlib/contour.pyi b/moondream/lib/python3.10/site-packages/matplotlib/contour.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7400fac50993f4560c0fd76d12c530abdd286f26 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/contour.pyi @@ -0,0 +1,140 @@ +import matplotlib.cm as cm +from matplotlib.artist import Artist +from matplotlib.axes import Axes +from matplotlib.collections import Collection, PathCollection +from matplotlib.colorizer import Colorizer, ColorizingArtist +from matplotlib.colors import Colormap, Normalize +from matplotlib.path import Path +from matplotlib.patches import Patch +from matplotlib.text import Text +from matplotlib.transforms import Transform, TransformedPatchPath, TransformedPath +from matplotlib.ticker import Locator, Formatter + +from numpy.typing import ArrayLike +import numpy as np +from collections.abc import Callable, Iterable, Sequence +from typing import Literal +from .typing import ColorType + + + +class ContourLabeler: + labelFmt: str | Formatter | Callable[[float], str] | dict[float, str] + labelManual: bool | Iterable[tuple[float, float]] + rightside_up: bool + labelLevelList: list[float] + labelIndiceList: list[int] + labelMappable: cm.ScalarMappable | ColorizingArtist + labelCValueList: list[ColorType] + labelXYs: list[tuple[float, float]] + def clabel( + self, + levels: ArrayLike | None = ..., + *, + fontsize: str | float | None = ..., + inline: bool = ..., + inline_spacing: float = ..., + fmt: str | Formatter | Callable[[float], str] | dict[float, str] | None = ..., + colors: ColorType | Sequence[ColorType] | None = ..., + use_clabeltext: bool = ..., + manual: bool | Iterable[tuple[float, float]] = ..., + rightside_up: bool = ..., + zorder: float | None = ... + ) -> list[Text]: ... + def print_label(self, linecontour: ArrayLike, labelwidth: float) -> bool: ... + def too_close(self, x: float, y: float, lw: float) -> bool: ... + def get_text( + self, + lev: float, + fmt: str | Formatter | Callable[[float], str] | dict[float, str], + ) -> str: ... + def locate_label( + self, linecontour: ArrayLike, labelwidth: float + ) -> tuple[float, float, float]: ... + def add_label( + self, x: float, y: float, rotation: float, lev: float, cvalue: ColorType + ) -> None: ... + def add_label_near( + self, + x: float, + y: float, + inline: bool = ..., + inline_spacing: int = ..., + transform: Transform | Literal[False] | None = ..., + ) -> None: ... + def pop_label(self, index: int = ...) -> None: ... + def labels(self, inline: bool, inline_spacing: int) -> None: ... + def remove(self) -> None: ... + +class ContourSet(ContourLabeler, Collection): + axes: Axes + levels: Iterable[float] + filled: bool + linewidths: float | ArrayLike | None + hatches: Iterable[str | None] + origin: Literal["upper", "lower", "image"] | None + extent: tuple[float, float, float, float] | None + colors: ColorType | Sequence[ColorType] + extend: Literal["neither", "both", "min", "max"] + nchunk: int + locator: Locator | None + logscale: bool + negative_linestyles: None | Literal[ + "solid", "dashed", "dashdot", "dotted" + ] | Iterable[Literal["solid", "dashed", "dashdot", "dotted"]] + clip_path: Patch | Path | TransformedPath | TransformedPatchPath | None + labelTexts: list[Text] + labelCValues: list[ColorType] + + @property + def allkinds(self) -> list[list[np.ndarray | None]]: ... + @property + def allsegs(self) -> list[list[np.ndarray]]: ... + @property + def alpha(self) -> float | None: ... + @property + def linestyles(self) -> ( + None | + Literal["solid", "dashed", "dashdot", "dotted"] | + Iterable[Literal["solid", "dashed", "dashdot", "dotted"]] + ): ... + + def __init__( + self, + ax: Axes, + *args, + levels: Iterable[float] | None = ..., + filled: bool = ..., + linewidths: float | ArrayLike | None = ..., + linestyles: Literal["solid", "dashed", "dashdot", "dotted"] + | Iterable[Literal["solid", "dashed", "dashdot", "dotted"]] + | None = ..., + hatches: Iterable[str | None] = ..., + alpha: float | None = ..., + origin: Literal["upper", "lower", "image"] | None = ..., + extent: tuple[float, float, float, float] | None = ..., + cmap: str | Colormap | None = ..., + colors: ColorType | Sequence[ColorType] | None = ..., + norm: str | Normalize | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + colorizer: Colorizer | None = ..., + extend: Literal["neither", "both", "min", "max"] = ..., + antialiased: bool | None = ..., + nchunk: int = ..., + locator: Locator | None = ..., + transform: Transform | None = ..., + negative_linestyles: Literal["solid", "dashed", "dashdot", "dotted"] + | Iterable[Literal["solid", "dashed", "dashdot", "dotted"]] + | None = ..., + clip_path: Patch | Path | TransformedPath | TransformedPatchPath | None = ..., + **kwargs + ) -> None: ... + def legend_elements( + self, variable_name: str = ..., str_format: Callable[[float], str] = ... + ) -> tuple[list[Artist], list[str]]: ... + def find_nearest_contour( + self, x: float, y: float, indices: Iterable[int] | None = ..., pixel: bool = ... + ) -> tuple[int, int, int, float, float, float]: ... + +class QuadContourSet(ContourSet): ... diff --git a/moondream/lib/python3.10/site-packages/matplotlib/dates.py b/moondream/lib/python3.10/site-packages/matplotlib/dates.py new file mode 100644 index 0000000000000000000000000000000000000000..511e1c6df6ccbd8747c76f297e0a6c20947cda3a --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/dates.py @@ -0,0 +1,1840 @@ +""" +Matplotlib provides sophisticated date plotting capabilities, standing on the +shoulders of python :mod:`datetime` and the add-on module dateutil_. + +By default, Matplotlib uses the units machinery described in +`~matplotlib.units` to convert `datetime.datetime`, and `numpy.datetime64` +objects when plotted on an x- or y-axis. The user does not +need to do anything for dates to be formatted, but dates often have strict +formatting needs, so this module provides many tick locators and formatters. +A basic example using `numpy.datetime64` is:: + + import numpy as np + + times = np.arange(np.datetime64('2001-01-02'), + np.datetime64('2002-02-03'), np.timedelta64(75, 'm')) + y = np.random.randn(len(times)) + + fig, ax = plt.subplots() + ax.plot(times, y) + +.. seealso:: + + - :doc:`/gallery/text_labels_and_annotations/date` + - :doc:`/gallery/ticks/date_concise_formatter` + - :doc:`/gallery/ticks/date_demo_convert` + +.. _date-format: + +Matplotlib date format +---------------------- + +Matplotlib represents dates using floating point numbers specifying the number +of days since a default epoch of 1970-01-01 UTC; for example, +1970-01-01, 06:00 is the floating point number 0.25. The formatters and +locators require the use of `datetime.datetime` objects, so only dates between +year 0001 and 9999 can be represented. Microsecond precision +is achievable for (approximately) 70 years on either side of the epoch, and +20 microseconds for the rest of the allowable range of dates (year 0001 to +9999). The epoch can be changed at import time via `.dates.set_epoch` or +:rc:`date.epoch` to other dates if necessary; see +:doc:`/gallery/ticks/date_precision_and_epochs` for a discussion. + +.. note:: + + Before Matplotlib 3.3, the epoch was 0000-12-31 which lost modern + microsecond precision and also made the default axis limit of 0 an invalid + datetime. In 3.3 the epoch was changed as above. To convert old + ordinal floats to the new epoch, users can do:: + + new_ordinal = old_ordinal + mdates.date2num(np.datetime64('0000-12-31')) + + +There are a number of helper functions to convert between :mod:`datetime` +objects and Matplotlib dates: + +.. currentmodule:: matplotlib.dates + +.. autosummary:: + :nosignatures: + + datestr2num + date2num + num2date + num2timedelta + drange + set_epoch + get_epoch + +.. note:: + + Like Python's `datetime.datetime`, Matplotlib uses the Gregorian calendar + for all conversions between dates and floating point numbers. This practice + is not universal, and calendar differences can cause confusing + differences between what Python and Matplotlib give as the number of days + since 0001-01-01 and what other software and databases yield. For + example, the US Naval Observatory uses a calendar that switches + from Julian to Gregorian in October, 1582. Hence, using their + calculator, the number of days between 0001-01-01 and 2006-04-01 is + 732403, whereas using the Gregorian calendar via the datetime + module we find:: + + In [1]: date(2006, 4, 1).toordinal() - date(1, 1, 1).toordinal() + Out[1]: 732401 + +All the Matplotlib date converters, locators and formatters are timezone aware. +If no explicit timezone is provided, :rc:`timezone` is assumed, provided as a +string. If you want to use a different timezone, pass the *tz* keyword +argument of `num2date` to any date tick locators or formatters you create. This +can be either a `datetime.tzinfo` instance or a string with the timezone name +that can be parsed by `~dateutil.tz.gettz`. + +A wide range of specific and general purpose date tick locators and +formatters are provided in this module. See +:mod:`matplotlib.ticker` for general information on tick locators +and formatters. These are described below. + +The dateutil_ module provides additional code to handle date ticking, making it +easy to place ticks on any kinds of dates. See examples below. + +.. _dateutil: https://dateutil.readthedocs.io + +.. _date-locators: + +Date tick locators +------------------ + +Most of the date tick locators can locate single or multiple ticks. For example:: + + # import constants for the days of the week + from matplotlib.dates import MO, TU, WE, TH, FR, SA, SU + + # tick on Mondays every week + loc = WeekdayLocator(byweekday=MO, tz=tz) + + # tick on Mondays and Saturdays + loc = WeekdayLocator(byweekday=(MO, SA)) + +In addition, most of the constructors take an interval argument:: + + # tick on Mondays every second week + loc = WeekdayLocator(byweekday=MO, interval=2) + +The rrule locator allows completely general date ticking:: + + # tick every 5th easter + rule = rrulewrapper(YEARLY, byeaster=1, interval=5) + loc = RRuleLocator(rule) + +The available date tick locators are: + +* `MicrosecondLocator`: Locate microseconds. + +* `SecondLocator`: Locate seconds. + +* `MinuteLocator`: Locate minutes. + +* `HourLocator`: Locate hours. + +* `DayLocator`: Locate specified days of the month. + +* `WeekdayLocator`: Locate days of the week, e.g., MO, TU. + +* `MonthLocator`: Locate months, e.g., 7 for July. + +* `YearLocator`: Locate years that are multiples of base. + +* `RRuleLocator`: Locate using a `rrulewrapper`. + `rrulewrapper` is a simple wrapper around dateutil_'s `dateutil.rrule` + which allow almost arbitrary date tick specifications. + See :doc:`rrule example `. + +* `AutoDateLocator`: On autoscale, this class picks the best `DateLocator` + (e.g., `RRuleLocator`) to set the view limits and the tick locations. If + called with ``interval_multiples=True`` it will make ticks line up with + sensible multiples of the tick intervals. For example, if the interval is + 4 hours, it will pick hours 0, 4, 8, etc. as ticks. This behaviour is not + guaranteed by default. + +.. _date-formatters: + +Date formatters +--------------- + +The available date formatters are: + +* `AutoDateFormatter`: attempts to figure out the best format to use. This is + most useful when used with the `AutoDateLocator`. + +* `ConciseDateFormatter`: also attempts to figure out the best format to use, + and to make the format as compact as possible while still having complete + date information. This is most useful when used with the `AutoDateLocator`. + +* `DateFormatter`: use `~datetime.datetime.strftime` format strings. +""" + +import datetime +import functools +import logging +import re + +from dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY, + MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, + SECONDLY) +from dateutil.relativedelta import relativedelta +import dateutil.parser +import dateutil.tz +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook, ticker, units + +__all__ = ('datestr2num', 'date2num', 'num2date', 'num2timedelta', 'drange', + 'set_epoch', 'get_epoch', 'DateFormatter', 'ConciseDateFormatter', + 'AutoDateFormatter', 'DateLocator', 'RRuleLocator', + 'AutoDateLocator', 'YearLocator', 'MonthLocator', 'WeekdayLocator', + 'DayLocator', 'HourLocator', 'MinuteLocator', + 'SecondLocator', 'MicrosecondLocator', + 'rrule', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU', + 'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', + 'HOURLY', 'MINUTELY', 'SECONDLY', 'MICROSECONDLY', 'relativedelta', + 'DateConverter', 'ConciseDateConverter', 'rrulewrapper') + + +_log = logging.getLogger(__name__) +UTC = datetime.timezone.utc + + +def _get_tzinfo(tz=None): + """ + Generate `~datetime.tzinfo` from a string or return `~datetime.tzinfo`. + If None, retrieve the preferred timezone from the rcParams dictionary. + """ + tz = mpl._val_or_rc(tz, 'timezone') + if tz == 'UTC': + return UTC + if isinstance(tz, str): + tzinfo = dateutil.tz.gettz(tz) + if tzinfo is None: + raise ValueError(f"{tz} is not a valid timezone as parsed by" + " dateutil.tz.gettz.") + return tzinfo + if isinstance(tz, datetime.tzinfo): + return tz + raise TypeError(f"tz must be string or tzinfo subclass, not {tz!r}.") + + +# Time-related constants. +EPOCH_OFFSET = float(datetime.datetime(1970, 1, 1).toordinal()) +# EPOCH_OFFSET is not used by matplotlib +MICROSECONDLY = SECONDLY + 1 +HOURS_PER_DAY = 24. +MIN_PER_HOUR = 60. +SEC_PER_MIN = 60. +MONTHS_PER_YEAR = 12. + +DAYS_PER_WEEK = 7. +DAYS_PER_MONTH = 30. +DAYS_PER_YEAR = 365.0 + +MINUTES_PER_DAY = MIN_PER_HOUR * HOURS_PER_DAY + +SEC_PER_HOUR = SEC_PER_MIN * MIN_PER_HOUR +SEC_PER_DAY = SEC_PER_HOUR * HOURS_PER_DAY +SEC_PER_WEEK = SEC_PER_DAY * DAYS_PER_WEEK + +MUSECONDS_PER_DAY = 1e6 * SEC_PER_DAY + +MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = ( + MO, TU, WE, TH, FR, SA, SU) +WEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) + +# default epoch: passed to np.datetime64... +_epoch = None + + +def _reset_epoch_test_example(): + """ + Reset the Matplotlib date epoch so it can be set again. + + Only for use in tests and examples. + """ + global _epoch + _epoch = None + + +def set_epoch(epoch): + """ + Set the epoch (origin for dates) for datetime calculations. + + The default epoch is :rc:`date.epoch`. + + If microsecond accuracy is desired, the date being plotted needs to be + within approximately 70 years of the epoch. Matplotlib internally + represents dates as days since the epoch, so floating point dynamic + range needs to be within a factor of 2^52. + + `~.dates.set_epoch` must be called before any dates are converted + (i.e. near the import section) or a RuntimeError will be raised. + + See also :doc:`/gallery/ticks/date_precision_and_epochs`. + + Parameters + ---------- + epoch : str + valid UTC date parsable by `numpy.datetime64` (do not include + timezone). + + """ + global _epoch + if _epoch is not None: + raise RuntimeError('set_epoch must be called before dates plotted.') + _epoch = epoch + + +def get_epoch(): + """ + Get the epoch used by `.dates`. + + Returns + ------- + epoch : str + String for the epoch (parsable by `numpy.datetime64`). + """ + global _epoch + + _epoch = mpl._val_or_rc(_epoch, 'date.epoch') + return _epoch + + +def _dt64_to_ordinalf(d): + """ + Convert `numpy.datetime64` or an `numpy.ndarray` of those types to + Gregorian date as UTC float relative to the epoch (see `.get_epoch`). + Roundoff is float64 precision. Practically: microseconds for dates + between 290301 BC, 294241 AD, milliseconds for larger dates + (see `numpy.datetime64`). + """ + + # the "extra" ensures that we at least allow the dynamic range out to + # seconds. That should get out to +/-2e11 years. + dseconds = d.astype('datetime64[s]') + extra = (d - dseconds).astype('timedelta64[ns]') + t0 = np.datetime64(get_epoch(), 's') + dt = (dseconds - t0).astype(np.float64) + dt += extra.astype(np.float64) / 1.0e9 + dt = dt / SEC_PER_DAY + + NaT_int = np.datetime64('NaT').astype(np.int64) + d_int = d.astype(np.int64) + dt[d_int == NaT_int] = np.nan + return dt + + +def _from_ordinalf(x, tz=None): + """ + Convert Gregorian float of the date, preserving hours, minutes, + seconds and microseconds. Return value is a `.datetime`. + + The input date *x* is a float in ordinal days at UTC, and the output will + be the specified `.datetime` object corresponding to that time in + timezone *tz*, or if *tz* is ``None``, in the timezone specified in + :rc:`timezone`. + """ + + tz = _get_tzinfo(tz) + + dt = (np.datetime64(get_epoch()) + + np.timedelta64(int(np.round(x * MUSECONDS_PER_DAY)), 'us')) + if dt < np.datetime64('0001-01-01') or dt >= np.datetime64('10000-01-01'): + raise ValueError(f'Date ordinal {x} converts to {dt} (using ' + f'epoch {get_epoch()}), but Matplotlib dates must be ' + 'between year 0001 and 9999.') + # convert from datetime64 to datetime: + dt = dt.tolist() + + # datetime64 is always UTC: + dt = dt.replace(tzinfo=dateutil.tz.gettz('UTC')) + # but maybe we are working in a different timezone so move. + dt = dt.astimezone(tz) + # fix round off errors + if np.abs(x) > 70 * 365: + # if x is big, round off to nearest twenty microseconds. + # This avoids floating point roundoff error + ms = round(dt.microsecond / 20) * 20 + if ms == 1000000: + dt = dt.replace(microsecond=0) + datetime.timedelta(seconds=1) + else: + dt = dt.replace(microsecond=ms) + + return dt + + +# a version of _from_ordinalf that can operate on numpy arrays +_from_ordinalf_np_vectorized = np.vectorize(_from_ordinalf, otypes="O") +# a version of dateutil.parser.parse that can operate on numpy arrays +_dateutil_parser_parse_np_vectorized = np.vectorize(dateutil.parser.parse) + + +def datestr2num(d, default=None): + """ + Convert a date string to a datenum using `dateutil.parser.parse`. + + Parameters + ---------- + d : str or sequence of str + The dates to convert. + + default : datetime.datetime, optional + The default date to use when fields are missing in *d*. + """ + if isinstance(d, str): + dt = dateutil.parser.parse(d, default=default) + return date2num(dt) + else: + if default is not None: + d = [date2num(dateutil.parser.parse(s, default=default)) + for s in d] + return np.asarray(d) + d = np.asarray(d) + if not d.size: + return d + return date2num(_dateutil_parser_parse_np_vectorized(d)) + + +def date2num(d): + """ + Convert datetime objects to Matplotlib dates. + + Parameters + ---------- + d : `datetime.datetime` or `numpy.datetime64` or sequences of these + + Returns + ------- + float or sequence of floats + Number of days since the epoch. See `.get_epoch` for the + epoch, which can be changed by :rc:`date.epoch` or `.set_epoch`. If + the epoch is "1970-01-01T00:00:00" (default) then noon Jan 1 1970 + ("1970-01-01T12:00:00") returns 0.5. + + Notes + ----- + The Gregorian calendar is assumed; this is not universal practice. + For details see the module docstring. + """ + # Unpack in case of e.g. Pandas or xarray object + d = cbook._unpack_to_numpy(d) + + # make an iterable, but save state to unpack later: + iterable = np.iterable(d) + if not iterable: + d = [d] + + masked = np.ma.is_masked(d) + mask = np.ma.getmask(d) + d = np.asarray(d) + + # convert to datetime64 arrays, if not already: + if not np.issubdtype(d.dtype, np.datetime64): + # datetime arrays + if not d.size: + # deals with an empty array... + return d + tzi = getattr(d[0], 'tzinfo', None) + if tzi is not None: + # make datetime naive: + d = [dt.astimezone(UTC).replace(tzinfo=None) for dt in d] + d = np.asarray(d) + d = d.astype('datetime64[us]') + + d = np.ma.masked_array(d, mask=mask) if masked else d + d = _dt64_to_ordinalf(d) + + return d if iterable else d[0] + + +def num2date(x, tz=None): + """ + Convert Matplotlib dates to `~datetime.datetime` objects. + + Parameters + ---------- + x : float or sequence of floats + Number of days (fraction part represents hours, minutes, seconds) + since the epoch. See `.get_epoch` for the + epoch, which can be changed by :rc:`date.epoch` or `.set_epoch`. + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Timezone of *x*. If a string, *tz* is passed to `dateutil.tz`. + + Returns + ------- + `~datetime.datetime` or sequence of `~datetime.datetime` + Dates are returned in timezone *tz*. + + If *x* is a sequence, a sequence of `~datetime.datetime` objects will + be returned. + + Notes + ----- + The Gregorian calendar is assumed; this is not universal practice. + For details, see the module docstring. + """ + tz = _get_tzinfo(tz) + return _from_ordinalf_np_vectorized(x, tz).tolist() + + +_ordinalf_to_timedelta_np_vectorized = np.vectorize( + lambda x: datetime.timedelta(days=x), otypes="O") + + +def num2timedelta(x): + """ + Convert number of days to a `~datetime.timedelta` object. + + If *x* is a sequence, a sequence of `~datetime.timedelta` objects will + be returned. + + Parameters + ---------- + x : float, sequence of floats + Number of days. The fraction part represents hours, minutes, seconds. + + Returns + ------- + `datetime.timedelta` or list[`datetime.timedelta`] + """ + return _ordinalf_to_timedelta_np_vectorized(x).tolist() + + +def drange(dstart, dend, delta): + """ + Return a sequence of equally spaced Matplotlib dates. + + The dates start at *dstart* and reach up to, but not including *dend*. + They are spaced by *delta*. + + Parameters + ---------- + dstart, dend : `~datetime.datetime` + The date limits. + delta : `datetime.timedelta` + Spacing of the dates. + + Returns + ------- + `numpy.array` + A list floats representing Matplotlib dates. + + """ + f1 = date2num(dstart) + f2 = date2num(dend) + step = delta.total_seconds() / SEC_PER_DAY + + # calculate the difference between dend and dstart in times of delta + num = int(np.ceil((f2 - f1) / step)) + + # calculate end of the interval which will be generated + dinterval_end = dstart + num * delta + + # ensure, that an half open interval will be generated [dstart, dend) + if dinterval_end >= dend: + # if the endpoint is greater than or equal to dend, + # just subtract one delta + dinterval_end -= delta + num -= 1 + + f2 = date2num(dinterval_end) # new float-endpoint + return np.linspace(f1, f2, num + 1) + + +def _wrap_in_tex(text): + p = r'([a-zA-Z]+)' + ret_text = re.sub(p, r'}$\1$\\mathdefault{', text) + + # Braces ensure symbols are not spaced like binary operators. + ret_text = ret_text.replace('-', '{-}').replace(':', '{:}') + # To not concatenate space between numbers. + ret_text = ret_text.replace(' ', r'\;') + ret_text = '$\\mathdefault{' + ret_text + '}$' + ret_text = ret_text.replace('$\\mathdefault{}$', '') + return ret_text + + +## date tick locators and formatters ### + + +class DateFormatter(ticker.Formatter): + """ + Format a tick (in days since the epoch) with a + `~datetime.datetime.strftime` format string. + """ + + def __init__(self, fmt, tz=None, *, usetex=None): + """ + Parameters + ---------- + fmt : str + `~datetime.datetime.strftime` format string + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone. If a string, *tz* is passed to `dateutil.tz`. + usetex : bool, default: :rc:`text.usetex` + To enable/disable the use of TeX's math mode for rendering the + results of the formatter. + """ + self.tz = _get_tzinfo(tz) + self.fmt = fmt + self._usetex = mpl._val_or_rc(usetex, 'text.usetex') + + def __call__(self, x, pos=0): + result = num2date(x, self.tz).strftime(self.fmt) + return _wrap_in_tex(result) if self._usetex else result + + def set_tzinfo(self, tz): + self.tz = _get_tzinfo(tz) + + +class ConciseDateFormatter(ticker.Formatter): + """ + A `.Formatter` which attempts to figure out the best format to use for the + date, and to make it as compact as possible, but still be complete. This is + most useful when used with the `AutoDateLocator`:: + + >>> locator = AutoDateLocator() + >>> formatter = ConciseDateFormatter(locator) + + Parameters + ---------- + locator : `.ticker.Locator` + Locator that this axis is using. + + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone, passed to `.dates.num2date`. + + formats : list of 6 strings, optional + Format strings for 6 levels of tick labelling: mostly years, + months, days, hours, minutes, and seconds. Strings use + the same format codes as `~datetime.datetime.strftime`. Default is + ``['%Y', '%b', '%d', '%H:%M', '%H:%M', '%S.%f']`` + + zero_formats : list of 6 strings, optional + Format strings for tick labels that are "zeros" for a given tick + level. For instance, if most ticks are months, ticks around 1 Jan 2005 + will be labeled "Dec", "2005", "Feb". The default is + ``['', '%Y', '%b', '%b-%d', '%H:%M', '%H:%M']`` + + offset_formats : list of 6 strings, optional + Format strings for the 6 levels that is applied to the "offset" + string found on the right side of an x-axis, or top of a y-axis. + Combined with the tick labels this should completely specify the + date. The default is:: + + ['', '%Y', '%Y-%b', '%Y-%b-%d', '%Y-%b-%d', '%Y-%b-%d %H:%M'] + + show_offset : bool, default: True + Whether to show the offset or not. + + usetex : bool, default: :rc:`text.usetex` + To enable/disable the use of TeX's math mode for rendering the results + of the formatter. + + Examples + -------- + See :doc:`/gallery/ticks/date_concise_formatter` + + .. plot:: + + import datetime + import matplotlib.dates as mdates + + base = datetime.datetime(2005, 2, 1) + dates = np.array([base + datetime.timedelta(hours=(2 * i)) + for i in range(732)]) + N = len(dates) + np.random.seed(19680801) + y = np.cumsum(np.random.randn(N)) + + fig, ax = plt.subplots(constrained_layout=True) + locator = mdates.AutoDateLocator() + formatter = mdates.ConciseDateFormatter(locator) + ax.xaxis.set_major_locator(locator) + ax.xaxis.set_major_formatter(formatter) + + ax.plot(dates, y) + ax.set_title('Concise Date Formatter') + + """ + + def __init__(self, locator, tz=None, formats=None, offset_formats=None, + zero_formats=None, show_offset=True, *, usetex=None): + """ + Autoformat the date labels. The default format is used to form an + initial string, and then redundant elements are removed. + """ + self._locator = locator + self._tz = tz + self.defaultfmt = '%Y' + # there are 6 levels with each level getting a specific format + # 0: mostly years, 1: months, 2: days, + # 3: hours, 4: minutes, 5: seconds + if formats: + if len(formats) != 6: + raise ValueError('formats argument must be a list of ' + '6 format strings (or None)') + self.formats = formats + else: + self.formats = ['%Y', # ticks are mostly years + '%b', # ticks are mostly months + '%d', # ticks are mostly days + '%H:%M', # hrs + '%H:%M', # min + '%S.%f', # secs + ] + # fmt for zeros ticks at this level. These are + # ticks that should be labeled w/ info the level above. + # like 1 Jan can just be labelled "Jan". 02:02:00 can + # just be labeled 02:02. + if zero_formats: + if len(zero_formats) != 6: + raise ValueError('zero_formats argument must be a list of ' + '6 format strings (or None)') + self.zero_formats = zero_formats + elif formats: + # use the users formats for the zero tick formats + self.zero_formats = [''] + self.formats[:-1] + else: + # make the defaults a bit nicer: + self.zero_formats = [''] + self.formats[:-1] + self.zero_formats[3] = '%b-%d' + + if offset_formats: + if len(offset_formats) != 6: + raise ValueError('offset_formats argument must be a list of ' + '6 format strings (or None)') + self.offset_formats = offset_formats + else: + self.offset_formats = ['', + '%Y', + '%Y-%b', + '%Y-%b-%d', + '%Y-%b-%d', + '%Y-%b-%d %H:%M'] + self.offset_string = '' + self.show_offset = show_offset + self._usetex = mpl._val_or_rc(usetex, 'text.usetex') + + def __call__(self, x, pos=None): + formatter = DateFormatter(self.defaultfmt, self._tz, + usetex=self._usetex) + return formatter(x, pos=pos) + + def format_ticks(self, values): + tickdatetime = [num2date(value, tz=self._tz) for value in values] + tickdate = np.array([tdt.timetuple()[:6] for tdt in tickdatetime]) + + # basic algorithm: + # 1) only display a part of the date if it changes over the ticks. + # 2) don't display the smaller part of the date if: + # it is always the same or if it is the start of the + # year, month, day etc. + # fmt for most ticks at this level + fmts = self.formats + # format beginnings of days, months, years, etc. + zerofmts = self.zero_formats + # offset fmt are for the offset in the upper left of the + # or lower right of the axis. + offsetfmts = self.offset_formats + show_offset = self.show_offset + + # determine the level we will label at: + # mostly 0: years, 1: months, 2: days, + # 3: hours, 4: minutes, 5: seconds, 6: microseconds + for level in range(5, -1, -1): + unique = np.unique(tickdate[:, level]) + if len(unique) > 1: + # if 1 is included in unique, the year is shown in ticks + if level < 2 and np.any(unique == 1): + show_offset = False + break + elif level == 0: + # all tickdate are the same, so only micros might be different + # set to the most precise (6: microseconds doesn't exist...) + level = 5 + + # level is the basic level we will label at. + # now loop through and decide the actual ticklabels + zerovals = [0, 1, 1, 0, 0, 0, 0] + labels = [''] * len(tickdate) + for nn in range(len(tickdate)): + if level < 5: + if tickdate[nn][level] == zerovals[level]: + fmt = zerofmts[level] + else: + fmt = fmts[level] + else: + # special handling for seconds + microseconds + if (tickdatetime[nn].second == tickdatetime[nn].microsecond + == 0): + fmt = zerofmts[level] + else: + fmt = fmts[level] + labels[nn] = tickdatetime[nn].strftime(fmt) + + # special handling of seconds and microseconds: + # strip extra zeros and decimal if possible. + # this is complicated by two factors. 1) we have some level-4 strings + # here (i.e. 03:00, '0.50000', '1.000') 2) we would like to have the + # same number of decimals for each string (i.e. 0.5 and 1.0). + if level >= 5: + trailing_zeros = min( + (len(s) - len(s.rstrip('0')) for s in labels if '.' in s), + default=None) + if trailing_zeros: + for nn in range(len(labels)): + if '.' in labels[nn]: + labels[nn] = labels[nn][:-trailing_zeros].rstrip('.') + + if show_offset: + # set the offset string: + if (self._locator.axis and + self._locator.axis.__name__ in ('xaxis', 'yaxis') + and self._locator.axis.get_inverted()): + self.offset_string = tickdatetime[0].strftime(offsetfmts[level]) + else: + self.offset_string = tickdatetime[-1].strftime(offsetfmts[level]) + if self._usetex: + self.offset_string = _wrap_in_tex(self.offset_string) + else: + self.offset_string = '' + + if self._usetex: + return [_wrap_in_tex(l) for l in labels] + else: + return labels + + def get_offset(self): + return self.offset_string + + def format_data_short(self, value): + return num2date(value, tz=self._tz).strftime('%Y-%m-%d %H:%M:%S') + + +class AutoDateFormatter(ticker.Formatter): + """ + A `.Formatter` which attempts to figure out the best format to use. This + is most useful when used with the `AutoDateLocator`. + + `.AutoDateFormatter` has a ``.scale`` dictionary that maps tick scales (the + interval in days between one major tick) to format strings; this dictionary + defaults to :: + + self.scaled = { + DAYS_PER_YEAR: rcParams['date.autoformatter.year'], + DAYS_PER_MONTH: rcParams['date.autoformatter.month'], + 1: rcParams['date.autoformatter.day'], + 1 / HOURS_PER_DAY: rcParams['date.autoformatter.hour'], + 1 / MINUTES_PER_DAY: rcParams['date.autoformatter.minute'], + 1 / SEC_PER_DAY: rcParams['date.autoformatter.second'], + 1 / MUSECONDS_PER_DAY: rcParams['date.autoformatter.microsecond'], + } + + The formatter uses the format string corresponding to the lowest key in + the dictionary that is greater or equal to the current scale. Dictionary + entries can be customized:: + + locator = AutoDateLocator() + formatter = AutoDateFormatter(locator) + formatter.scaled[1/(24*60)] = '%M:%S' # only show min and sec + + Custom callables can also be used instead of format strings. The following + example shows how to use a custom format function to strip trailing zeros + from decimal seconds and adds the date to the first ticklabel:: + + def my_format_function(x, pos=None): + x = matplotlib.dates.num2date(x) + if pos == 0: + fmt = '%D %H:%M:%S.%f' + else: + fmt = '%H:%M:%S.%f' + label = x.strftime(fmt) + label = label.rstrip("0") + label = label.rstrip(".") + return label + + formatter.scaled[1/(24*60)] = my_format_function + """ + + # This can be improved by providing some user-level direction on + # how to choose the best format (precedence, etc.). + + # Perhaps a 'struct' that has a field for each time-type where a + # zero would indicate "don't show" and a number would indicate + # "show" with some sort of priority. Same priorities could mean + # show all with the same priority. + + # Or more simply, perhaps just a format string for each + # possibility... + + def __init__(self, locator, tz=None, defaultfmt='%Y-%m-%d', *, + usetex=None): + """ + Autoformat the date labels. + + Parameters + ---------- + locator : `.ticker.Locator` + Locator that this axis is using. + + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone. If a string, *tz* is passed to `dateutil.tz`. + + defaultfmt : str + The default format to use if none of the values in ``self.scaled`` + are greater than the unit returned by ``locator._get_unit()``. + + usetex : bool, default: :rc:`text.usetex` + To enable/disable the use of TeX's math mode for rendering the + results of the formatter. If any entries in ``self.scaled`` are set + as functions, then it is up to the customized function to enable or + disable TeX's math mode itself. + """ + self._locator = locator + self._tz = tz + self.defaultfmt = defaultfmt + self._formatter = DateFormatter(self.defaultfmt, tz) + rcParams = mpl.rcParams + self._usetex = mpl._val_or_rc(usetex, 'text.usetex') + self.scaled = { + DAYS_PER_YEAR: rcParams['date.autoformatter.year'], + DAYS_PER_MONTH: rcParams['date.autoformatter.month'], + 1: rcParams['date.autoformatter.day'], + 1 / HOURS_PER_DAY: rcParams['date.autoformatter.hour'], + 1 / MINUTES_PER_DAY: rcParams['date.autoformatter.minute'], + 1 / SEC_PER_DAY: rcParams['date.autoformatter.second'], + 1 / MUSECONDS_PER_DAY: rcParams['date.autoformatter.microsecond'] + } + + def _set_locator(self, locator): + self._locator = locator + + def __call__(self, x, pos=None): + try: + locator_unit_scale = float(self._locator._get_unit()) + except AttributeError: + locator_unit_scale = 1 + # Pick the first scale which is greater than the locator unit. + fmt = next((fmt for scale, fmt in sorted(self.scaled.items()) + if scale >= locator_unit_scale), + self.defaultfmt) + + if isinstance(fmt, str): + self._formatter = DateFormatter(fmt, self._tz, usetex=self._usetex) + result = self._formatter(x, pos) + elif callable(fmt): + result = fmt(x, pos) + else: + raise TypeError(f'Unexpected type passed to {self!r}.') + + return result + + +class rrulewrapper: + """ + A simple wrapper around a `dateutil.rrule` allowing flexible + date tick specifications. + """ + def __init__(self, freq, tzinfo=None, **kwargs): + """ + Parameters + ---------- + freq : {YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY} + Tick frequency. These constants are defined in `dateutil.rrule`, + but they are accessible from `matplotlib.dates` as well. + tzinfo : `datetime.tzinfo`, optional + Time zone information. The default is None. + **kwargs + Additional keyword arguments are passed to the `dateutil.rrule`. + """ + kwargs['freq'] = freq + self._base_tzinfo = tzinfo + + self._update_rrule(**kwargs) + + def set(self, **kwargs): + """Set parameters for an existing wrapper.""" + self._construct.update(kwargs) + + self._update_rrule(**self._construct) + + def _update_rrule(self, **kwargs): + tzinfo = self._base_tzinfo + + # rrule does not play nicely with timezones - especially pytz time + # zones, it's best to use naive zones and attach timezones once the + # datetimes are returned + if 'dtstart' in kwargs: + dtstart = kwargs['dtstart'] + if dtstart.tzinfo is not None: + if tzinfo is None: + tzinfo = dtstart.tzinfo + else: + dtstart = dtstart.astimezone(tzinfo) + + kwargs['dtstart'] = dtstart.replace(tzinfo=None) + + if 'until' in kwargs: + until = kwargs['until'] + if until.tzinfo is not None: + if tzinfo is not None: + until = until.astimezone(tzinfo) + else: + raise ValueError('until cannot be aware if dtstart ' + 'is naive and tzinfo is None') + + kwargs['until'] = until.replace(tzinfo=None) + + self._construct = kwargs.copy() + self._tzinfo = tzinfo + self._rrule = rrule(**self._construct) + + def _attach_tzinfo(self, dt, tzinfo): + # pytz zones are attached by "localizing" the datetime + if hasattr(tzinfo, 'localize'): + return tzinfo.localize(dt, is_dst=True) + + return dt.replace(tzinfo=tzinfo) + + def _aware_return_wrapper(self, f, returns_list=False): + """Decorator function that allows rrule methods to handle tzinfo.""" + # This is only necessary if we're actually attaching a tzinfo + if self._tzinfo is None: + return f + + # All datetime arguments must be naive. If they are not naive, they are + # converted to the _tzinfo zone before dropping the zone. + def normalize_arg(arg): + if isinstance(arg, datetime.datetime) and arg.tzinfo is not None: + if arg.tzinfo is not self._tzinfo: + arg = arg.astimezone(self._tzinfo) + + return arg.replace(tzinfo=None) + + return arg + + def normalize_args(args, kwargs): + args = tuple(normalize_arg(arg) for arg in args) + kwargs = {kw: normalize_arg(arg) for kw, arg in kwargs.items()} + + return args, kwargs + + # There are two kinds of functions we care about - ones that return + # dates and ones that return lists of dates. + if not returns_list: + def inner_func(*args, **kwargs): + args, kwargs = normalize_args(args, kwargs) + dt = f(*args, **kwargs) + return self._attach_tzinfo(dt, self._tzinfo) + else: + def inner_func(*args, **kwargs): + args, kwargs = normalize_args(args, kwargs) + dts = f(*args, **kwargs) + return [self._attach_tzinfo(dt, self._tzinfo) for dt in dts] + + return functools.wraps(f)(inner_func) + + def __getattr__(self, name): + if name in self.__dict__: + return self.__dict__[name] + + f = getattr(self._rrule, name) + + if name in {'after', 'before'}: + return self._aware_return_wrapper(f) + elif name in {'xafter', 'xbefore', 'between'}: + return self._aware_return_wrapper(f, returns_list=True) + else: + return f + + def __setstate__(self, state): + self.__dict__.update(state) + + +class DateLocator(ticker.Locator): + """ + Determines the tick locations when plotting dates. + + This class is subclassed by other Locators and + is not meant to be used on its own. + """ + hms0d = {'byhour': 0, 'byminute': 0, 'bysecond': 0} + + def __init__(self, tz=None): + """ + Parameters + ---------- + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone. If a string, *tz* is passed to `dateutil.tz`. + """ + self.tz = _get_tzinfo(tz) + + def set_tzinfo(self, tz): + """ + Set timezone info. + + Parameters + ---------- + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone. If a string, *tz* is passed to `dateutil.tz`. + """ + self.tz = _get_tzinfo(tz) + + def datalim_to_dt(self): + """Convert axis data interval to datetime objects.""" + dmin, dmax = self.axis.get_data_interval() + if dmin > dmax: + dmin, dmax = dmax, dmin + + return num2date(dmin, self.tz), num2date(dmax, self.tz) + + def viewlim_to_dt(self): + """Convert the view interval to datetime objects.""" + vmin, vmax = self.axis.get_view_interval() + if vmin > vmax: + vmin, vmax = vmax, vmin + return num2date(vmin, self.tz), num2date(vmax, self.tz) + + def _get_unit(self): + """ + Return how many days a unit of the locator is; used for + intelligent autoscaling. + """ + return 1 + + def _get_interval(self): + """ + Return the number of units for each tick. + """ + return 1 + + def nonsingular(self, vmin, vmax): + """ + Given the proposed upper and lower extent, adjust the range + if it is too close to being singular (i.e. a range of ~0). + """ + if not np.isfinite(vmin) or not np.isfinite(vmax): + # Except if there is no data, then use 1970 as default. + return (date2num(datetime.date(1970, 1, 1)), + date2num(datetime.date(1970, 1, 2))) + if vmax < vmin: + vmin, vmax = vmax, vmin + unit = self._get_unit() + interval = self._get_interval() + if abs(vmax - vmin) < 1e-6: + vmin -= 2 * unit * interval + vmax += 2 * unit * interval + return vmin, vmax + + +class RRuleLocator(DateLocator): + # use the dateutil rrule instance + + def __init__(self, o, tz=None): + super().__init__(tz) + self.rule = o + + def __call__(self): + # if no data have been set, this will tank with a ValueError + try: + dmin, dmax = self.viewlim_to_dt() + except ValueError: + return [] + + return self.tick_values(dmin, dmax) + + def tick_values(self, vmin, vmax): + start, stop = self._create_rrule(vmin, vmax) + dates = self.rule.between(start, stop, True) + if len(dates) == 0: + return date2num([vmin, vmax]) + return self.raise_if_exceeds(date2num(dates)) + + def _create_rrule(self, vmin, vmax): + # set appropriate rrule dtstart and until and return + # start and end + delta = relativedelta(vmax, vmin) + + # We need to cap at the endpoints of valid datetime + try: + start = vmin - delta + except (ValueError, OverflowError): + # cap + start = datetime.datetime(1, 1, 1, 0, 0, 0, + tzinfo=datetime.timezone.utc) + + try: + stop = vmax + delta + except (ValueError, OverflowError): + # cap + stop = datetime.datetime(9999, 12, 31, 23, 59, 59, + tzinfo=datetime.timezone.utc) + + self.rule.set(dtstart=start, until=stop) + + return vmin, vmax + + def _get_unit(self): + # docstring inherited + freq = self.rule._rrule._freq + return self.get_unit_generic(freq) + + @staticmethod + def get_unit_generic(freq): + if freq == YEARLY: + return DAYS_PER_YEAR + elif freq == MONTHLY: + return DAYS_PER_MONTH + elif freq == WEEKLY: + return DAYS_PER_WEEK + elif freq == DAILY: + return 1.0 + elif freq == HOURLY: + return 1.0 / HOURS_PER_DAY + elif freq == MINUTELY: + return 1.0 / MINUTES_PER_DAY + elif freq == SECONDLY: + return 1.0 / SEC_PER_DAY + else: + # error + return -1 # or should this just return '1'? + + def _get_interval(self): + return self.rule._rrule._interval + + +class AutoDateLocator(DateLocator): + """ + On autoscale, this class picks the best `DateLocator` to set the view + limits and the tick locations. + + Attributes + ---------- + intervald : dict + + Mapping of tick frequencies to multiples allowed for that ticking. + The default is :: + + self.intervald = { + YEARLY : [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500, + 1000, 2000, 4000, 5000, 10000], + MONTHLY : [1, 2, 3, 4, 6], + DAILY : [1, 2, 3, 7, 14, 21], + HOURLY : [1, 2, 3, 4, 6, 12], + MINUTELY: [1, 5, 10, 15, 30], + SECONDLY: [1, 5, 10, 15, 30], + MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500, + 1000, 2000, 5000, 10000, 20000, 50000, + 100000, 200000, 500000, 1000000], + } + + where the keys are defined in `dateutil.rrule`. + + The interval is used to specify multiples that are appropriate for + the frequency of ticking. For instance, every 7 days is sensible + for daily ticks, but for minutes/seconds, 15 or 30 make sense. + + When customizing, you should only modify the values for the existing + keys. You should not add or delete entries. + + Example for forcing ticks every 3 hours:: + + locator = AutoDateLocator() + locator.intervald[HOURLY] = [3] # only show every 3 hours + """ + + def __init__(self, tz=None, minticks=5, maxticks=None, + interval_multiples=True): + """ + Parameters + ---------- + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone. If a string, *tz* is passed to `dateutil.tz`. + minticks : int + The minimum number of ticks desired; controls whether ticks occur + yearly, monthly, etc. + maxticks : int + The maximum number of ticks desired; controls the interval between + ticks (ticking every other, every 3, etc.). For fine-grained + control, this can be a dictionary mapping individual rrule + frequency constants (YEARLY, MONTHLY, etc.) to their own maximum + number of ticks. This can be used to keep the number of ticks + appropriate to the format chosen in `AutoDateFormatter`. Any + frequency not specified in this dictionary is given a default + value. + interval_multiples : bool, default: True + Whether ticks should be chosen to be multiple of the interval, + locking them to 'nicer' locations. For example, this will force + the ticks to be at hours 0, 6, 12, 18 when hourly ticking is done + at 6 hour intervals. + """ + super().__init__(tz=tz) + self._freq = YEARLY + self._freqs = [YEARLY, MONTHLY, DAILY, HOURLY, MINUTELY, + SECONDLY, MICROSECONDLY] + self.minticks = minticks + + self.maxticks = {YEARLY: 11, MONTHLY: 12, DAILY: 11, HOURLY: 12, + MINUTELY: 11, SECONDLY: 11, MICROSECONDLY: 8} + if maxticks is not None: + try: + self.maxticks.update(maxticks) + except TypeError: + # Assume we were given an integer. Use this as the maximum + # number of ticks for every frequency and create a + # dictionary for this + self.maxticks = dict.fromkeys(self._freqs, maxticks) + self.interval_multiples = interval_multiples + self.intervald = { + YEARLY: [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500, + 1000, 2000, 4000, 5000, 10000], + MONTHLY: [1, 2, 3, 4, 6], + DAILY: [1, 2, 3, 7, 14, 21], + HOURLY: [1, 2, 3, 4, 6, 12], + MINUTELY: [1, 5, 10, 15, 30], + SECONDLY: [1, 5, 10, 15, 30], + MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, + 5000, 10000, 20000, 50000, 100000, 200000, 500000, + 1000000], + } + if interval_multiples: + # Swap "3" for "4" in the DAILY list; If we use 3 we get bad + # tick loc for months w/ 31 days: 1, 4, ..., 28, 31, 1 + # If we use 4 then we get: 1, 5, ... 25, 29, 1 + self.intervald[DAILY] = [1, 2, 4, 7, 14] + + self._byranges = [None, range(1, 13), range(1, 32), + range(0, 24), range(0, 60), range(0, 60), None] + + def __call__(self): + # docstring inherited + dmin, dmax = self.viewlim_to_dt() + locator = self.get_locator(dmin, dmax) + return locator() + + def tick_values(self, vmin, vmax): + return self.get_locator(vmin, vmax).tick_values(vmin, vmax) + + def nonsingular(self, vmin, vmax): + # whatever is thrown at us, we can scale the unit. + # But default nonsingular date plots at an ~4 year period. + if not np.isfinite(vmin) or not np.isfinite(vmax): + # Except if there is no data, then use 1970 as default. + return (date2num(datetime.date(1970, 1, 1)), + date2num(datetime.date(1970, 1, 2))) + if vmax < vmin: + vmin, vmax = vmax, vmin + if vmin == vmax: + vmin = vmin - DAYS_PER_YEAR * 2 + vmax = vmax + DAYS_PER_YEAR * 2 + return vmin, vmax + + def _get_unit(self): + if self._freq in [MICROSECONDLY]: + return 1. / MUSECONDS_PER_DAY + else: + return RRuleLocator.get_unit_generic(self._freq) + + def get_locator(self, dmin, dmax): + """Pick the best locator based on a distance.""" + delta = relativedelta(dmax, dmin) + tdelta = dmax - dmin + + # take absolute difference + if dmin > dmax: + delta = -delta + tdelta = -tdelta + # The following uses a mix of calls to relativedelta and timedelta + # methods because there is incomplete overlap in the functionality of + # these similar functions, and it's best to avoid doing our own math + # whenever possible. + numYears = float(delta.years) + numMonths = numYears * MONTHS_PER_YEAR + delta.months + numDays = tdelta.days # Avoids estimates of days/month, days/year. + numHours = numDays * HOURS_PER_DAY + delta.hours + numMinutes = numHours * MIN_PER_HOUR + delta.minutes + numSeconds = np.floor(tdelta.total_seconds()) + numMicroseconds = np.floor(tdelta.total_seconds() * 1e6) + + nums = [numYears, numMonths, numDays, numHours, numMinutes, + numSeconds, numMicroseconds] + + use_rrule_locator = [True] * 6 + [False] + + # Default setting of bymonth, etc. to pass to rrule + # [unused (for year), bymonth, bymonthday, byhour, byminute, + # bysecond, unused (for microseconds)] + byranges = [None, 1, 1, 0, 0, 0, None] + + # Loop over all the frequencies and try to find one that gives at + # least a minticks tick positions. Once this is found, look for + # an interval from a list specific to that frequency that gives no + # more than maxticks tick positions. Also, set up some ranges + # (bymonth, etc.) as appropriate to be passed to rrulewrapper. + for i, (freq, num) in enumerate(zip(self._freqs, nums)): + # If this particular frequency doesn't give enough ticks, continue + if num < self.minticks: + # Since we're not using this particular frequency, set + # the corresponding by_ to None so the rrule can act as + # appropriate + byranges[i] = None + continue + + # Find the first available interval that doesn't give too many + # ticks + for interval in self.intervald[freq]: + if num <= interval * (self.maxticks[freq] - 1): + break + else: + if not (self.interval_multiples and freq == DAILY): + _api.warn_external( + f"AutoDateLocator was unable to pick an appropriate " + f"interval for this date range. It may be necessary " + f"to add an interval value to the AutoDateLocator's " + f"intervald dictionary. Defaulting to {interval}.") + + # Set some parameters as appropriate + self._freq = freq + + if self._byranges[i] and self.interval_multiples: + byranges[i] = self._byranges[i][::interval] + if i in (DAILY, WEEKLY): + if interval == 14: + # just make first and 15th. Avoids 30th. + byranges[i] = [1, 15] + elif interval == 7: + byranges[i] = [1, 8, 15, 22] + + interval = 1 + else: + byranges[i] = self._byranges[i] + break + else: + interval = 1 + + if (freq == YEARLY) and self.interval_multiples: + locator = YearLocator(interval, tz=self.tz) + elif use_rrule_locator[i]: + _, bymonth, bymonthday, byhour, byminute, bysecond, _ = byranges + rrule = rrulewrapper(self._freq, interval=interval, + dtstart=dmin, until=dmax, + bymonth=bymonth, bymonthday=bymonthday, + byhour=byhour, byminute=byminute, + bysecond=bysecond) + + locator = RRuleLocator(rrule, tz=self.tz) + else: + locator = MicrosecondLocator(interval, tz=self.tz) + if date2num(dmin) > 70 * 365 and interval < 1000: + _api.warn_external( + 'Plotting microsecond time intervals for dates far from ' + f'the epoch (time origin: {get_epoch()}) is not well-' + 'supported. See matplotlib.dates.set_epoch to change the ' + 'epoch.') + + locator.set_axis(self.axis) + return locator + + +class YearLocator(RRuleLocator): + """ + Make ticks on a given day of each year that is a multiple of base. + + Examples:: + + # Tick every year on Jan 1st + locator = YearLocator() + + # Tick every 5 years on July 4th + locator = YearLocator(5, month=7, day=4) + """ + def __init__(self, base=1, month=1, day=1, tz=None): + """ + Parameters + ---------- + base : int, default: 1 + Mark ticks every *base* years. + month : int, default: 1 + The month on which to place the ticks, starting from 1. Default is + January. + day : int, default: 1 + The day on which to place the ticks. + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone. If a string, *tz* is passed to `dateutil.tz`. + """ + rule = rrulewrapper(YEARLY, interval=base, bymonth=month, + bymonthday=day, **self.hms0d) + super().__init__(rule, tz=tz) + self.base = ticker._Edge_integer(base, 0) + + def _create_rrule(self, vmin, vmax): + # 'start' needs to be a multiple of the interval to create ticks on + # interval multiples when the tick frequency is YEARLY + ymin = max(self.base.le(vmin.year) * self.base.step, 1) + ymax = min(self.base.ge(vmax.year) * self.base.step, 9999) + + c = self.rule._construct + replace = {'year': ymin, + 'month': c.get('bymonth', 1), + 'day': c.get('bymonthday', 1), + 'hour': 0, 'minute': 0, 'second': 0} + + start = vmin.replace(**replace) + stop = start.replace(year=ymax) + self.rule.set(dtstart=start, until=stop) + + return start, stop + + +class MonthLocator(RRuleLocator): + """ + Make ticks on occurrences of each month, e.g., 1, 3, 12. + """ + def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None): + """ + Parameters + ---------- + bymonth : int or list of int, default: all months + Ticks will be placed on every month in *bymonth*. Default is + ``range(1, 13)``, i.e. every month. + bymonthday : int, default: 1 + The day on which to place the ticks. + interval : int, default: 1 + The interval between each iteration. For example, if + ``interval=2``, mark every second occurrence. + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone. If a string, *tz* is passed to `dateutil.tz`. + """ + if bymonth is None: + bymonth = range(1, 13) + + rule = rrulewrapper(MONTHLY, bymonth=bymonth, bymonthday=bymonthday, + interval=interval, **self.hms0d) + super().__init__(rule, tz=tz) + + +class WeekdayLocator(RRuleLocator): + """ + Make ticks on occurrences of each weekday. + """ + + def __init__(self, byweekday=1, interval=1, tz=None): + """ + Parameters + ---------- + byweekday : int or list of int, default: all days + Ticks will be placed on every weekday in *byweekday*. Default is + every day. + + Elements of *byweekday* must be one of MO, TU, WE, TH, FR, SA, + SU, the constants from :mod:`dateutil.rrule`, which have been + imported into the :mod:`matplotlib.dates` namespace. + interval : int, default: 1 + The interval between each iteration. For example, if + ``interval=2``, mark every second occurrence. + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone. If a string, *tz* is passed to `dateutil.tz`. + """ + rule = rrulewrapper(DAILY, byweekday=byweekday, + interval=interval, **self.hms0d) + super().__init__(rule, tz=tz) + + +class DayLocator(RRuleLocator): + """ + Make ticks on occurrences of each day of the month. For example, + 1, 15, 30. + """ + def __init__(self, bymonthday=None, interval=1, tz=None): + """ + Parameters + ---------- + bymonthday : int or list of int, default: all days + Ticks will be placed on every day in *bymonthday*. Default is + ``bymonthday=range(1, 32)``, i.e., every day of the month. + interval : int, default: 1 + The interval between each iteration. For example, if + ``interval=2``, mark every second occurrence. + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone. If a string, *tz* is passed to `dateutil.tz`. + """ + if interval != int(interval) or interval < 1: + raise ValueError("interval must be an integer greater than 0") + if bymonthday is None: + bymonthday = range(1, 32) + + rule = rrulewrapper(DAILY, bymonthday=bymonthday, + interval=interval, **self.hms0d) + super().__init__(rule, tz=tz) + + +class HourLocator(RRuleLocator): + """ + Make ticks on occurrences of each hour. + """ + def __init__(self, byhour=None, interval=1, tz=None): + """ + Parameters + ---------- + byhour : int or list of int, default: all hours + Ticks will be placed on every hour in *byhour*. Default is + ``byhour=range(24)``, i.e., every hour. + interval : int, default: 1 + The interval between each iteration. For example, if + ``interval=2``, mark every second occurrence. + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone. If a string, *tz* is passed to `dateutil.tz`. + """ + if byhour is None: + byhour = range(24) + + rule = rrulewrapper(HOURLY, byhour=byhour, interval=interval, + byminute=0, bysecond=0) + super().__init__(rule, tz=tz) + + +class MinuteLocator(RRuleLocator): + """ + Make ticks on occurrences of each minute. + """ + def __init__(self, byminute=None, interval=1, tz=None): + """ + Parameters + ---------- + byminute : int or list of int, default: all minutes + Ticks will be placed on every minute in *byminute*. Default is + ``byminute=range(60)``, i.e., every minute. + interval : int, default: 1 + The interval between each iteration. For example, if + ``interval=2``, mark every second occurrence. + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone. If a string, *tz* is passed to `dateutil.tz`. + """ + if byminute is None: + byminute = range(60) + + rule = rrulewrapper(MINUTELY, byminute=byminute, interval=interval, + bysecond=0) + super().__init__(rule, tz=tz) + + +class SecondLocator(RRuleLocator): + """ + Make ticks on occurrences of each second. + """ + def __init__(self, bysecond=None, interval=1, tz=None): + """ + Parameters + ---------- + bysecond : int or list of int, default: all seconds + Ticks will be placed on every second in *bysecond*. Default is + ``bysecond = range(60)``, i.e., every second. + interval : int, default: 1 + The interval between each iteration. For example, if + ``interval=2``, mark every second occurrence. + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone. If a string, *tz* is passed to `dateutil.tz`. + """ + if bysecond is None: + bysecond = range(60) + + rule = rrulewrapper(SECONDLY, bysecond=bysecond, interval=interval) + super().__init__(rule, tz=tz) + + +class MicrosecondLocator(DateLocator): + """ + Make ticks on regular intervals of one or more microsecond(s). + + .. note:: + + By default, Matplotlib uses a floating point representation of time in + days since the epoch, so plotting data with + microsecond time resolution does not work well for + dates that are far (about 70 years) from the epoch (check with + `~.dates.get_epoch`). + + If you want sub-microsecond resolution time plots, it is strongly + recommended to use floating point seconds, not datetime-like + time representation. + + If you really must use datetime.datetime() or similar and still + need microsecond precision, change the time origin via + `.dates.set_epoch` to something closer to the dates being plotted. + See :doc:`/gallery/ticks/date_precision_and_epochs`. + + """ + def __init__(self, interval=1, tz=None): + """ + Parameters + ---------- + interval : int, default: 1 + The interval between each iteration. For example, if + ``interval=2``, mark every second occurrence. + tz : str or `~datetime.tzinfo`, default: :rc:`timezone` + Ticks timezone. If a string, *tz* is passed to `dateutil.tz`. + """ + super().__init__(tz=tz) + self._interval = interval + self._wrapped_locator = ticker.MultipleLocator(interval) + + def set_axis(self, axis): + self._wrapped_locator.set_axis(axis) + return super().set_axis(axis) + + def __call__(self): + # if no data have been set, this will tank with a ValueError + try: + dmin, dmax = self.viewlim_to_dt() + except ValueError: + return [] + + return self.tick_values(dmin, dmax) + + def tick_values(self, vmin, vmax): + nmin, nmax = date2num((vmin, vmax)) + t0 = np.floor(nmin) + nmax = nmax - t0 + nmin = nmin - t0 + nmin *= MUSECONDS_PER_DAY + nmax *= MUSECONDS_PER_DAY + + ticks = self._wrapped_locator.tick_values(nmin, nmax) + + ticks = ticks / MUSECONDS_PER_DAY + t0 + return ticks + + def _get_unit(self): + # docstring inherited + return 1. / MUSECONDS_PER_DAY + + def _get_interval(self): + # docstring inherited + return self._interval + + +class DateConverter(units.ConversionInterface): + """ + Converter for `datetime.date` and `datetime.datetime` data, or for + date/time data represented as it would be converted by `date2num`. + + The 'unit' tag for such data is None or a `~datetime.tzinfo` instance. + """ + + def __init__(self, *, interval_multiples=True): + self._interval_multiples = interval_multiples + super().__init__() + + def axisinfo(self, unit, axis): + """ + Return the `~matplotlib.units.AxisInfo` for *unit*. + + *unit* is a `~datetime.tzinfo` instance or None. + The *axis* argument is required but not used. + """ + tz = unit + + majloc = AutoDateLocator(tz=tz, + interval_multiples=self._interval_multiples) + majfmt = AutoDateFormatter(majloc, tz=tz) + datemin = datetime.date(1970, 1, 1) + datemax = datetime.date(1970, 1, 2) + + return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='', + default_limits=(datemin, datemax)) + + @staticmethod + def convert(value, unit, axis): + """ + If *value* is not already a number or sequence of numbers, convert it + with `date2num`. + + The *unit* and *axis* arguments are not used. + """ + return date2num(value) + + @staticmethod + def default_units(x, axis): + """ + Return the `~datetime.tzinfo` instance of *x* or of its first element, + or None + """ + if isinstance(x, np.ndarray): + x = x.ravel() + + try: + x = cbook._safe_first_finite(x) + except (TypeError, StopIteration): + pass + + try: + return x.tzinfo + except AttributeError: + pass + return None + + +class ConciseDateConverter(DateConverter): + # docstring inherited + + def __init__(self, formats=None, zero_formats=None, offset_formats=None, + show_offset=True, *, interval_multiples=True): + self._formats = formats + self._zero_formats = zero_formats + self._offset_formats = offset_formats + self._show_offset = show_offset + self._interval_multiples = interval_multiples + super().__init__() + + def axisinfo(self, unit, axis): + # docstring inherited + tz = unit + majloc = AutoDateLocator(tz=tz, + interval_multiples=self._interval_multiples) + majfmt = ConciseDateFormatter(majloc, tz=tz, formats=self._formats, + zero_formats=self._zero_formats, + offset_formats=self._offset_formats, + show_offset=self._show_offset) + datemin = datetime.date(1970, 1, 1) + datemax = datetime.date(1970, 1, 2) + return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='', + default_limits=(datemin, datemax)) + + +class _SwitchableDateConverter: + """ + Helper converter-like object that generates and dispatches to + temporary ConciseDateConverter or DateConverter instances based on + :rc:`date.converter` and :rc:`date.interval_multiples`. + """ + + @staticmethod + def _get_converter(): + converter_cls = { + "concise": ConciseDateConverter, "auto": DateConverter}[ + mpl.rcParams["date.converter"]] + interval_multiples = mpl.rcParams["date.interval_multiples"] + return converter_cls(interval_multiples=interval_multiples) + + def axisinfo(self, *args, **kwargs): + return self._get_converter().axisinfo(*args, **kwargs) + + def default_units(self, *args, **kwargs): + return self._get_converter().default_units(*args, **kwargs) + + def convert(self, *args, **kwargs): + return self._get_converter().convert(*args, **kwargs) + + +units.registry[np.datetime64] = \ + units.registry[datetime.date] = \ + units.registry[datetime.datetime] = \ + _SwitchableDateConverter() diff --git a/moondream/lib/python3.10/site-packages/matplotlib/figure.pyi b/moondream/lib/python3.10/site-packages/matplotlib/figure.pyi new file mode 100644 index 0000000000000000000000000000000000000000..08bf1505532bb8f097db7d2e907f5f4243aa652f --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/figure.pyi @@ -0,0 +1,421 @@ +from collections.abc import Callable, Hashable, Iterable, Sequence +import os +from typing import Any, IO, Literal, TypeVar, overload + +import numpy as np +from numpy.typing import ArrayLike + +from matplotlib.artist import Artist +from matplotlib.axes import Axes +from matplotlib.backend_bases import ( + FigureCanvasBase, + MouseButton, + MouseEvent, + RendererBase, +) +from matplotlib.colors import Colormap, Normalize +from matplotlib.colorbar import Colorbar +from matplotlib.colorizer import ColorizingArtist, Colorizer +from matplotlib.cm import ScalarMappable +from matplotlib.gridspec import GridSpec, SubplotSpec, SubplotParams as SubplotParams +from matplotlib.image import _ImageBase, FigureImage +from matplotlib.layout_engine import LayoutEngine +from matplotlib.legend import Legend +from matplotlib.lines import Line2D +from matplotlib.patches import Rectangle, Patch +from matplotlib.text import Text +from matplotlib.transforms import Affine2D, Bbox, BboxBase, Transform +from .typing import ColorType, HashableList + +_T = TypeVar("_T") + +class FigureBase(Artist): + artists: list[Artist] + lines: list[Line2D] + patches: list[Patch] + texts: list[Text] + images: list[_ImageBase] + legends: list[Legend] + subfigs: list[SubFigure] + stale: bool + suppressComposite: bool | None + def __init__(self, **kwargs) -> None: ... + def autofmt_xdate( + self, + bottom: float = ..., + rotation: int = ..., + ha: Literal["left", "center", "right"] = ..., + which: Literal["major", "minor", "both"] = ..., + ) -> None: ... + def get_children(self) -> list[Artist]: ... + def contains(self, mouseevent: MouseEvent) -> tuple[bool, dict[Any, Any]]: ... + def suptitle(self, t: str, **kwargs) -> Text: ... + def get_suptitle(self) -> str: ... + def supxlabel(self, t: str, **kwargs) -> Text: ... + def get_supxlabel(self) -> str: ... + def supylabel(self, t: str, **kwargs) -> Text: ... + def get_supylabel(self) -> str: ... + def get_edgecolor(self) -> ColorType: ... + def get_facecolor(self) -> ColorType: ... + def get_frameon(self) -> bool: ... + def set_linewidth(self, linewidth: float) -> None: ... + def get_linewidth(self) -> float: ... + def set_edgecolor(self, color: ColorType) -> None: ... + def set_facecolor(self, color: ColorType) -> None: ... + @overload + def get_figure(self, root: Literal[True]) -> Figure: ... + @overload + def get_figure(self, root: Literal[False]) -> Figure | SubFigure: ... + @overload + def get_figure(self, root: bool = ...) -> Figure | SubFigure: ... + def set_frameon(self, b: bool) -> None: ... + @property + def frameon(self) -> bool: ... + @frameon.setter + def frameon(self, b: bool) -> None: ... + def add_artist(self, artist: Artist, clip: bool = ...) -> Artist: ... + @overload + def add_axes(self, ax: Axes) -> Axes: ... + @overload + def add_axes( + self, + rect: tuple[float, float, float, float], + projection: None | str = ..., + polar: bool = ..., + **kwargs + ) -> Axes: ... + + # TODO: docstring indicates SubplotSpec a valid arg, but none of the listed signatures appear to be that + @overload + def add_subplot( + self, nrows: int, ncols: int, index: int | tuple[int, int], **kwargs + ) -> Axes: ... + @overload + def add_subplot(self, pos: int, **kwargs) -> Axes: ... + @overload + def add_subplot(self, ax: Axes, **kwargs) -> Axes: ... + @overload + def add_subplot(self, ax: SubplotSpec, **kwargs) -> Axes: ... + @overload + def add_subplot(self, **kwargs) -> Axes: ... + @overload + def subplots( + self, + nrows: Literal[1] = ..., + ncols: Literal[1] = ..., + *, + sharex: bool | Literal["none", "all", "row", "col"] = ..., + sharey: bool | Literal["none", "all", "row", "col"] = ..., + squeeze: Literal[True] = ..., + width_ratios: Sequence[float] | None = ..., + height_ratios: Sequence[float] | None = ..., + subplot_kw: dict[str, Any] | None = ..., + gridspec_kw: dict[str, Any] | None = ..., + ) -> Axes: ... + @overload + def subplots( + self, + nrows: int = ..., + ncols: int = ..., + *, + sharex: bool | Literal["none", "all", "row", "col"] = ..., + sharey: bool | Literal["none", "all", "row", "col"] = ..., + squeeze: Literal[False], + width_ratios: Sequence[float] | None = ..., + height_ratios: Sequence[float] | None = ..., + subplot_kw: dict[str, Any] | None = ..., + gridspec_kw: dict[str, Any] | None = ..., + ) -> np.ndarray: ... # TODO numpy/numpy#24738 + @overload + def subplots( + self, + nrows: int = ..., + ncols: int = ..., + *, + sharex: bool | Literal["none", "all", "row", "col"] = ..., + sharey: bool | Literal["none", "all", "row", "col"] = ..., + squeeze: bool = ..., + width_ratios: Sequence[float] | None = ..., + height_ratios: Sequence[float] | None = ..., + subplot_kw: dict[str, Any] | None = ..., + gridspec_kw: dict[str, Any] | None = ..., + ) -> Any: ... + def delaxes(self, ax: Axes) -> None: ... + def clear(self, keep_observers: bool = ...) -> None: ... + def clf(self, keep_observers: bool = ...) -> None: ... + + @overload + def legend(self) -> Legend: ... + @overload + def legend(self, handles: Iterable[Artist], labels: Iterable[str], **kwargs) -> Legend: ... + @overload + def legend(self, *, handles: Iterable[Artist], **kwargs) -> Legend: ... + @overload + def legend(self, labels: Iterable[str], **kwargs) -> Legend: ... + @overload + def legend(self, **kwargs) -> Legend: ... + + def text( + self, + x: float, + y: float, + s: str, + fontdict: dict[str, Any] | None = ..., + **kwargs + ) -> Text: ... + def colorbar( + self, + mappable: ScalarMappable | ColorizingArtist, + cax: Axes | None = ..., + ax: Axes | Iterable[Axes] | None = ..., + use_gridspec: bool = ..., + **kwargs + ) -> Colorbar: ... + def subplots_adjust( + self, + left: float | None = ..., + bottom: float | None = ..., + right: float | None = ..., + top: float | None = ..., + wspace: float | None = ..., + hspace: float | None = ..., + ) -> None: ... + def align_xlabels(self, axs: Iterable[Axes] | None = ...) -> None: ... + def align_ylabels(self, axs: Iterable[Axes] | None = ...) -> None: ... + def align_titles(self, axs: Iterable[Axes] | None = ...) -> None: ... + def align_labels(self, axs: Iterable[Axes] | None = ...) -> None: ... + def add_gridspec(self, nrows: int = ..., ncols: int = ..., **kwargs) -> GridSpec: ... + @overload + def subfigures( + self, + nrows: int = ..., + ncols: int = ..., + squeeze: Literal[False] = ..., + wspace: float | None = ..., + hspace: float | None = ..., + width_ratios: ArrayLike | None = ..., + height_ratios: ArrayLike | None = ..., + **kwargs + ) -> np.ndarray: ... + @overload + def subfigures( + self, + nrows: int = ..., + ncols: int = ..., + squeeze: Literal[True] = ..., + wspace: float | None = ..., + hspace: float | None = ..., + width_ratios: ArrayLike | None = ..., + height_ratios: ArrayLike | None = ..., + **kwargs + ) -> np.ndarray | SubFigure: ... + def add_subfigure(self, subplotspec: SubplotSpec, **kwargs) -> SubFigure: ... + def sca(self, a: Axes) -> Axes: ... + def gca(self) -> Axes: ... + def _gci(self) -> ColorizingArtist | None: ... + def _process_projection_requirements( + self, *, axes_class=None, polar=False, projection=None, **kwargs + ) -> tuple[type[Axes], dict[str, Any]]: ... + def get_default_bbox_extra_artists(self) -> list[Artist]: ... + def get_tightbbox( + self, + renderer: RendererBase | None = ..., + *, + bbox_extra_artists: Iterable[Artist] | None = ..., + ) -> Bbox: ... + @overload + def subplot_mosaic( + self, + mosaic: str, + *, + sharex: bool = ..., + sharey: bool = ..., + width_ratios: ArrayLike | None = ..., + height_ratios: ArrayLike | None = ..., + empty_sentinel: str = ..., + subplot_kw: dict[str, Any] | None = ..., + per_subplot_kw: dict[str | tuple[str, ...], dict[str, Any]] | None = ..., + gridspec_kw: dict[str, Any] | None = ..., + ) -> dict[str, Axes]: ... + @overload + def subplot_mosaic( + self, + mosaic: list[HashableList[_T]], + *, + sharex: bool = ..., + sharey: bool = ..., + width_ratios: ArrayLike | None = ..., + height_ratios: ArrayLike | None = ..., + empty_sentinel: _T = ..., + subplot_kw: dict[str, Any] | None = ..., + per_subplot_kw: dict[_T | tuple[_T, ...], dict[str, Any]] | None = ..., + gridspec_kw: dict[str, Any] | None = ..., + ) -> dict[_T, Axes]: ... + @overload + def subplot_mosaic( + self, + mosaic: list[HashableList[Hashable]], + *, + sharex: bool = ..., + sharey: bool = ..., + width_ratios: ArrayLike | None = ..., + height_ratios: ArrayLike | None = ..., + empty_sentinel: Any = ..., + subplot_kw: dict[str, Any] | None = ..., + per_subplot_kw: dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None = ..., + gridspec_kw: dict[str, Any] | None = ..., + ) -> dict[Hashable, Axes]: ... + +class SubFigure(FigureBase): + @property + def figure(self) -> Figure: ... + subplotpars: SubplotParams + dpi_scale_trans: Affine2D + transFigure: Transform + bbox_relative: Bbox + figbbox: BboxBase + bbox: BboxBase + transSubfigure: Transform + patch: Rectangle + def __init__( + self, + parent: Figure | SubFigure, + subplotspec: SubplotSpec, + *, + facecolor: ColorType | None = ..., + edgecolor: ColorType | None = ..., + linewidth: float = ..., + frameon: bool | None = ..., + **kwargs + ) -> None: ... + @property + def canvas(self) -> FigureCanvasBase: ... + @property + def dpi(self) -> float: ... + @dpi.setter + def dpi(self, value: float) -> None: ... + def get_dpi(self) -> float: ... + def set_dpi(self, val) -> None: ... + def get_constrained_layout(self) -> bool: ... + def get_constrained_layout_pads( + self, relative: bool = ... + ) -> tuple[float, float, float, float]: ... + def get_layout_engine(self) -> LayoutEngine: ... + @property # type: ignore[misc] + def axes(self) -> list[Axes]: ... # type: ignore[override] + def get_axes(self) -> list[Axes]: ... + +class Figure(FigureBase): + @property + def figure(self) -> Figure: ... + bbox_inches: Bbox + dpi_scale_trans: Affine2D + bbox: BboxBase + figbbox: BboxBase + transFigure: Transform + transSubfigure: Transform + patch: Rectangle + subplotpars: SubplotParams + def __init__( + self, + figsize: tuple[float, float] | None = ..., + dpi: float | None = ..., + *, + facecolor: ColorType | None = ..., + edgecolor: ColorType | None = ..., + linewidth: float = ..., + frameon: bool | None = ..., + subplotpars: SubplotParams | None = ..., + tight_layout: bool | dict[str, Any] | None = ..., + constrained_layout: bool | dict[str, Any] | None = ..., + layout: Literal["constrained", "compressed", "tight"] + | LayoutEngine + | None = ..., + **kwargs + ) -> None: ... + def pick(self, mouseevent: MouseEvent) -> None: ... + def set_layout_engine( + self, + layout: Literal["constrained", "compressed", "tight", "none"] + | LayoutEngine + | None = ..., + **kwargs + ) -> None: ... + def get_layout_engine(self) -> LayoutEngine | None: ... + def _repr_html_(self) -> str | None: ... + def show(self, warn: bool = ...) -> None: ... + @property + def number(self) -> int | str: ... + @number.setter + def number(self, num: int | str) -> None: ... + @property # type: ignore[misc] + def axes(self) -> list[Axes]: ... # type: ignore[override] + def get_axes(self) -> list[Axes]: ... + @property + def dpi(self) -> float: ... + @dpi.setter + def dpi(self, dpi: float) -> None: ... + def get_tight_layout(self) -> bool: ... + def get_constrained_layout_pads( + self, relative: bool = ... + ) -> tuple[float, float, float, float]: ... + def get_constrained_layout(self) -> bool: ... + canvas: FigureCanvasBase + def set_canvas(self, canvas: FigureCanvasBase) -> None: ... + def figimage( + self, + X: ArrayLike, + xo: int = ..., + yo: int = ..., + alpha: float | None = ..., + norm: str | Normalize | None = ..., + cmap: str | Colormap | None = ..., + vmin: float | None = ..., + vmax: float | None = ..., + origin: Literal["upper", "lower"] | None = ..., + resize: bool = ..., + *, + colorizer: Colorizer | None = ..., + **kwargs + ) -> FigureImage: ... + def set_size_inches( + self, w: float | tuple[float, float], h: float | None = ..., forward: bool = ... + ) -> None: ... + def get_size_inches(self) -> np.ndarray: ... + def get_figwidth(self) -> float: ... + def get_figheight(self) -> float: ... + def get_dpi(self) -> float: ... + def set_dpi(self, val: float) -> None: ... + def set_figwidth(self, val: float, forward: bool = ...) -> None: ... + def set_figheight(self, val: float, forward: bool = ...) -> None: ... + def clear(self, keep_observers: bool = ...) -> None: ... + def draw_without_rendering(self) -> None: ... + def draw_artist(self, a: Artist) -> None: ... + def add_axobserver(self, func: Callable[[Figure], Any]) -> None: ... + def savefig( + self, + fname: str | os.PathLike | IO, + *, + transparent: bool | None = ..., + **kwargs + ) -> None: ... + def ginput( + self, + n: int = ..., + timeout: float = ..., + show_clicks: bool = ..., + mouse_add: MouseButton = ..., + mouse_pop: MouseButton = ..., + mouse_stop: MouseButton = ..., + ) -> list[tuple[int, int]]: ... + def waitforbuttonpress(self, timeout: float = ...) -> None | bool: ... + def tight_layout( + self, + *, + pad: float = ..., + h_pad: float | None = ..., + w_pad: float | None = ..., + rect: tuple[float, float, float, float] | None = ... + ) -> None: ... + +def figaspect(arg: float | ArrayLike) -> tuple[float, float]: ... diff --git a/moondream/lib/python3.10/site-packages/matplotlib/font_manager.py b/moondream/lib/python3.10/site-packages/matplotlib/font_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..9aa8dccde444b8998f34ded5cd9cfe07e7b46f6a --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/font_manager.py @@ -0,0 +1,1645 @@ +""" +A module for finding, managing, and using fonts across platforms. + +This module provides a single `FontManager` instance, ``fontManager``, that can +be shared across backends and platforms. The `findfont` +function returns the best TrueType (TTF) font file in the local or +system font path that matches the specified `FontProperties` +instance. The `FontManager` also handles Adobe Font Metrics +(AFM) font files for use by the PostScript backend. +The `FontManager.addfont` function adds a custom font from a file without +installing it into your operating system. + +The design is based on the `W3C Cascading Style Sheet, Level 1 (CSS1) +font specification `_. +Future versions may implement the Level 2 or 2.1 specifications. +""" + +# KNOWN ISSUES +# +# - documentation +# - font variant is untested +# - font stretch is incomplete +# - font size is incomplete +# - default font algorithm needs improvement and testing +# - setWeights function needs improvement +# - 'light' is an invalid weight value, remove it. + +from __future__ import annotations + +from base64 import b64encode +import copy +import dataclasses +from functools import lru_cache +import functools +from io import BytesIO +import json +import logging +from numbers import Number +import os +from pathlib import Path +import plistlib +import re +import subprocess +import sys +import threading + +import matplotlib as mpl +from matplotlib import _api, _afm, cbook, ft2font +from matplotlib._fontconfig_pattern import ( + parse_fontconfig_pattern, generate_fontconfig_pattern) +from matplotlib.rcsetup import _validators + +_log = logging.getLogger(__name__) + +font_scalings = { + 'xx-small': 0.579, + 'x-small': 0.694, + 'small': 0.833, + 'medium': 1.0, + 'large': 1.200, + 'x-large': 1.440, + 'xx-large': 1.728, + 'larger': 1.2, + 'smaller': 0.833, + None: 1.0, +} +stretch_dict = { + 'ultra-condensed': 100, + 'extra-condensed': 200, + 'condensed': 300, + 'semi-condensed': 400, + 'normal': 500, + 'semi-expanded': 600, + 'semi-extended': 600, + 'expanded': 700, + 'extended': 700, + 'extra-expanded': 800, + 'extra-extended': 800, + 'ultra-expanded': 900, + 'ultra-extended': 900, +} +weight_dict = { + 'ultralight': 100, + 'light': 200, + 'normal': 400, + 'regular': 400, + 'book': 400, + 'medium': 500, + 'roman': 500, + 'semibold': 600, + 'demibold': 600, + 'demi': 600, + 'bold': 700, + 'heavy': 800, + 'extra bold': 800, + 'black': 900, +} +_weight_regexes = [ + # From fontconfig's FcFreeTypeQueryFaceInternal; not the same as + # weight_dict! + ("thin", 100), + ("extralight", 200), + ("ultralight", 200), + ("demilight", 350), + ("semilight", 350), + ("light", 300), # Needs to come *after* demi/semilight! + ("book", 380), + ("regular", 400), + ("normal", 400), + ("medium", 500), + ("demibold", 600), + ("demi", 600), + ("semibold", 600), + ("extrabold", 800), + ("superbold", 800), + ("ultrabold", 800), + ("bold", 700), # Needs to come *after* extra/super/ultrabold! + ("ultrablack", 1000), + ("superblack", 1000), + ("extrablack", 1000), + (r"\bultra", 1000), + ("black", 900), # Needs to come *after* ultra/super/extrablack! + ("heavy", 900), +] +font_family_aliases = { + 'serif', + 'sans-serif', + 'sans serif', + 'cursive', + 'fantasy', + 'monospace', + 'sans', +} + +# OS Font paths +try: + _HOME = Path.home() +except Exception: # Exceptions thrown by home() are not specified... + _HOME = Path(os.devnull) # Just an arbitrary path with no children. +MSFolders = \ + r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders' +MSFontDirectories = [ + r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts', + r'SOFTWARE\Microsoft\Windows\CurrentVersion\Fonts'] +MSUserFontDirectories = [ + str(_HOME / 'AppData/Local/Microsoft/Windows/Fonts'), + str(_HOME / 'AppData/Roaming/Microsoft/Windows/Fonts'), +] +X11FontDirectories = [ + # an old standard installation point + "/usr/X11R6/lib/X11/fonts/TTF/", + "/usr/X11/lib/X11/fonts", + # here is the new standard location for fonts + "/usr/share/fonts/", + # documented as a good place to install new fonts + "/usr/local/share/fonts/", + # common application, not really useful + "/usr/lib/openoffice/share/fonts/truetype/", + # user fonts + str((Path(os.environ.get('XDG_DATA_HOME') or _HOME / ".local/share")) + / "fonts"), + str(_HOME / ".fonts"), +] +OSXFontDirectories = [ + "/Library/Fonts/", + "/Network/Library/Fonts/", + "/System/Library/Fonts/", + # fonts installed via MacPorts + "/opt/local/share/fonts", + # user fonts + str(_HOME / "Library/Fonts"), +] + + +def get_fontext_synonyms(fontext): + """ + Return a list of file extensions that are synonyms for + the given file extension *fileext*. + """ + return { + 'afm': ['afm'], + 'otf': ['otf', 'ttc', 'ttf'], + 'ttc': ['otf', 'ttc', 'ttf'], + 'ttf': ['otf', 'ttc', 'ttf'], + }[fontext] + + +def list_fonts(directory, extensions): + """ + Return a list of all fonts matching any of the extensions, found + recursively under the directory. + """ + extensions = ["." + ext for ext in extensions] + return [os.path.join(dirpath, filename) + # os.walk ignores access errors, unlike Path.glob. + for dirpath, _, filenames in os.walk(directory) + for filename in filenames + if Path(filename).suffix.lower() in extensions] + + +def win32FontDirectory(): + r""" + Return the user-specified font directory for Win32. This is + looked up from the registry key :: + + \\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts + + If the key is not found, ``%WINDIR%\Fonts`` will be returned. + """ # noqa: E501 + import winreg + try: + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders) as user: + return winreg.QueryValueEx(user, 'Fonts')[0] + except OSError: + return os.path.join(os.environ['WINDIR'], 'Fonts') + + +def _get_win32_installed_fonts(): + """List the font paths known to the Windows registry.""" + import winreg + items = set() + # Search and resolve fonts listed in the registry. + for domain, base_dirs in [ + (winreg.HKEY_LOCAL_MACHINE, [win32FontDirectory()]), # System. + (winreg.HKEY_CURRENT_USER, MSUserFontDirectories), # User. + ]: + for base_dir in base_dirs: + for reg_path in MSFontDirectories: + try: + with winreg.OpenKey(domain, reg_path) as local: + for j in range(winreg.QueryInfoKey(local)[1]): + # value may contain the filename of the font or its + # absolute path. + key, value, tp = winreg.EnumValue(local, j) + if not isinstance(value, str): + continue + try: + # If value contains already an absolute path, + # then it is not changed further. + path = Path(base_dir, value).resolve() + except RuntimeError: + # Don't fail with invalid entries. + continue + items.add(path) + except (OSError, MemoryError): + continue + return items + + +@lru_cache +def _get_fontconfig_fonts(): + """Cache and list the font paths known to ``fc-list``.""" + try: + if b'--format' not in subprocess.check_output(['fc-list', '--help']): + _log.warning( # fontconfig 2.7 implemented --format. + 'Matplotlib needs fontconfig>=2.7 to query system fonts.') + return [] + out = subprocess.check_output(['fc-list', '--format=%{file}\\n']) + except (OSError, subprocess.CalledProcessError): + return [] + return [Path(os.fsdecode(fname)) for fname in out.split(b'\n')] + + +@lru_cache +def _get_macos_fonts(): + """Cache and list the font paths known to ``system_profiler SPFontsDataType``.""" + try: + d, = plistlib.loads( + subprocess.check_output(["system_profiler", "-xml", "SPFontsDataType"])) + except (OSError, subprocess.CalledProcessError, plistlib.InvalidFileException): + return [] + return [Path(entry["path"]) for entry in d["_items"]] + + +def findSystemFonts(fontpaths=None, fontext='ttf'): + """ + Search for fonts in the specified font paths. If no paths are + given, will use a standard set of system paths, as well as the + list of fonts tracked by fontconfig if fontconfig is installed and + available. A list of TrueType fonts are returned by default with + AFM fonts as an option. + """ + fontfiles = set() + fontexts = get_fontext_synonyms(fontext) + + if fontpaths is None: + if sys.platform == 'win32': + installed_fonts = _get_win32_installed_fonts() + fontpaths = [] + else: + installed_fonts = _get_fontconfig_fonts() + if sys.platform == 'darwin': + installed_fonts += _get_macos_fonts() + fontpaths = [*X11FontDirectories, *OSXFontDirectories] + else: + fontpaths = X11FontDirectories + fontfiles.update(str(path) for path in installed_fonts + if path.suffix.lower()[1:] in fontexts) + + elif isinstance(fontpaths, str): + fontpaths = [fontpaths] + + for path in fontpaths: + fontfiles.update(map(os.path.abspath, list_fonts(path, fontexts))) + + return [fname for fname in fontfiles if os.path.exists(fname)] + + +@dataclasses.dataclass(frozen=True) +class FontEntry: + """ + A class for storing Font properties. + + It is used when populating the font lookup dictionary. + """ + + fname: str = '' + name: str = '' + style: str = 'normal' + variant: str = 'normal' + weight: str | int = 'normal' + stretch: str = 'normal' + size: str = 'medium' + + def _repr_html_(self) -> str: + png_stream = self._repr_png_() + png_b64 = b64encode(png_stream).decode() + return f"" + + def _repr_png_(self) -> bytes: + from matplotlib.figure import Figure # Circular import. + fig = Figure() + font_path = Path(self.fname) if self.fname != '' else None + fig.text(0, 0, self.name, font=font_path) + with BytesIO() as buf: + fig.savefig(buf, bbox_inches='tight', transparent=True) + return buf.getvalue() + + +def ttfFontProperty(font): + """ + Extract information from a TrueType font file. + + Parameters + ---------- + font : `.FT2Font` + The TrueType font file from which information will be extracted. + + Returns + ------- + `FontEntry` + The extracted font properties. + + """ + name = font.family_name + + # Styles are: italic, oblique, and normal (default) + + sfnt = font.get_sfnt() + mac_key = (1, # platform: macintosh + 0, # id: roman + 0) # langid: english + ms_key = (3, # platform: microsoft + 1, # id: unicode_cs + 0x0409) # langid: english_united_states + + # These tables are actually mac_roman-encoded, but mac_roman support may be + # missing in some alternative Python implementations and we are only going + # to look for ASCII substrings, where any ASCII-compatible encoding works + # - or big-endian UTF-16, since important Microsoft fonts use that. + sfnt2 = (sfnt.get((*mac_key, 2), b'').decode('latin-1').lower() or + sfnt.get((*ms_key, 2), b'').decode('utf_16_be').lower()) + sfnt4 = (sfnt.get((*mac_key, 4), b'').decode('latin-1').lower() or + sfnt.get((*ms_key, 4), b'').decode('utf_16_be').lower()) + + if sfnt4.find('oblique') >= 0: + style = 'oblique' + elif sfnt4.find('italic') >= 0: + style = 'italic' + elif sfnt2.find('regular') >= 0: + style = 'normal' + elif ft2font.StyleFlags.ITALIC in font.style_flags: + style = 'italic' + else: + style = 'normal' + + # Variants are: small-caps and normal (default) + + # !!!! Untested + if name.lower() in ['capitals', 'small-caps']: + variant = 'small-caps' + else: + variant = 'normal' + + # The weight-guessing algorithm is directly translated from fontconfig + # 2.13.1's FcFreeTypeQueryFaceInternal (fcfreetype.c). + wws_subfamily = 22 + typographic_subfamily = 16 + font_subfamily = 2 + styles = [ + sfnt.get((*mac_key, wws_subfamily), b'').decode('latin-1'), + sfnt.get((*mac_key, typographic_subfamily), b'').decode('latin-1'), + sfnt.get((*mac_key, font_subfamily), b'').decode('latin-1'), + sfnt.get((*ms_key, wws_subfamily), b'').decode('utf-16-be'), + sfnt.get((*ms_key, typographic_subfamily), b'').decode('utf-16-be'), + sfnt.get((*ms_key, font_subfamily), b'').decode('utf-16-be'), + ] + styles = [*filter(None, styles)] or [font.style_name] + + def get_weight(): # From fontconfig's FcFreeTypeQueryFaceInternal. + # OS/2 table weight. + os2 = font.get_sfnt_table("OS/2") + if os2 and os2["version"] != 0xffff: + return os2["usWeightClass"] + # PostScript font info weight. + try: + ps_font_info_weight = ( + font.get_ps_font_info()["weight"].replace(" ", "") or "") + except ValueError: + pass + else: + for regex, weight in _weight_regexes: + if re.fullmatch(regex, ps_font_info_weight, re.I): + return weight + # Style name weight. + for style in styles: + style = style.replace(" ", "") + for regex, weight in _weight_regexes: + if re.search(regex, style, re.I): + return weight + if ft2font.StyleFlags.BOLD in font.style_flags: + return 700 # "bold" + return 500 # "medium", not "regular"! + + weight = int(get_weight()) + + # Stretch can be absolute and relative + # Absolute stretches are: ultra-condensed, extra-condensed, condensed, + # semi-condensed, normal, semi-expanded, expanded, extra-expanded, + # and ultra-expanded. + # Relative stretches are: wider, narrower + # Child value is: inherit + + if any(word in sfnt4 for word in ['narrow', 'condensed', 'cond']): + stretch = 'condensed' + elif 'demi cond' in sfnt4: + stretch = 'semi-condensed' + elif any(word in sfnt4 for word in ['wide', 'expanded', 'extended']): + stretch = 'expanded' + else: + stretch = 'normal' + + # Sizes can be absolute and relative. + # Absolute sizes are: xx-small, x-small, small, medium, large, x-large, + # and xx-large. + # Relative sizes are: larger, smaller + # Length value is an absolute font size, e.g., 12pt + # Percentage values are in 'em's. Most robust specification. + + if not font.scalable: + raise NotImplementedError("Non-scalable fonts are not supported") + size = 'scalable' + + return FontEntry(font.fname, name, style, variant, weight, stretch, size) + + +def afmFontProperty(fontpath, font): + """ + Extract information from an AFM font file. + + Parameters + ---------- + fontpath : str + The filename corresponding to *font*. + font : AFM + The AFM font file from which information will be extracted. + + Returns + ------- + `FontEntry` + The extracted font properties. + """ + + name = font.get_familyname() + fontname = font.get_fontname().lower() + + # Styles are: italic, oblique, and normal (default) + + if font.get_angle() != 0 or 'italic' in name.lower(): + style = 'italic' + elif 'oblique' in name.lower(): + style = 'oblique' + else: + style = 'normal' + + # Variants are: small-caps and normal (default) + + # !!!! Untested + if name.lower() in ['capitals', 'small-caps']: + variant = 'small-caps' + else: + variant = 'normal' + + weight = font.get_weight().lower() + if weight not in weight_dict: + weight = 'normal' + + # Stretch can be absolute and relative + # Absolute stretches are: ultra-condensed, extra-condensed, condensed, + # semi-condensed, normal, semi-expanded, expanded, extra-expanded, + # and ultra-expanded. + # Relative stretches are: wider, narrower + # Child value is: inherit + if 'demi cond' in fontname: + stretch = 'semi-condensed' + elif any(word in fontname for word in ['narrow', 'cond']): + stretch = 'condensed' + elif any(word in fontname for word in ['wide', 'expanded', 'extended']): + stretch = 'expanded' + else: + stretch = 'normal' + + # Sizes can be absolute and relative. + # Absolute sizes are: xx-small, x-small, small, medium, large, x-large, + # and xx-large. + # Relative sizes are: larger, smaller + # Length value is an absolute font size, e.g., 12pt + # Percentage values are in 'em's. Most robust specification. + + # All AFM fonts are apparently scalable. + + size = 'scalable' + + return FontEntry(fontpath, name, style, variant, weight, stretch, size) + + +def _cleanup_fontproperties_init(init_method): + """ + A decorator to limit the call signature to single a positional argument + or alternatively only keyword arguments. + + We still accept but deprecate all other call signatures. + + When the deprecation expires we can switch the signature to:: + + __init__(self, pattern=None, /, *, family=None, style=None, ...) + + plus a runtime check that pattern is not used alongside with the + keyword arguments. This results eventually in the two possible + call signatures:: + + FontProperties(pattern) + FontProperties(family=..., size=..., ...) + + """ + @functools.wraps(init_method) + def wrapper(self, *args, **kwargs): + # multiple args with at least some positional ones + if len(args) > 1 or len(args) == 1 and kwargs: + # Note: Both cases were previously handled as individual properties. + # Therefore, we do not mention the case of font properties here. + _api.warn_deprecated( + "3.10", + message="Passing individual properties to FontProperties() " + "positionally was deprecated in Matplotlib %(since)s and " + "will be removed in %(removal)s. Please pass all properties " + "via keyword arguments." + ) + # single non-string arg -> clearly a family not a pattern + if len(args) == 1 and not kwargs and not cbook.is_scalar_or_string(args[0]): + # Case font-family list passed as single argument + _api.warn_deprecated( + "3.10", + message="Passing family as positional argument to FontProperties() " + "was deprecated in Matplotlib %(since)s and will be removed " + "in %(removal)s. Please pass family names as keyword" + "argument." + ) + # Note on single string arg: + # This has been interpreted as pattern so far. We are already raising if a + # non-pattern compatible family string was given. Therefore, we do not need + # to warn for this case. + return init_method(self, *args, **kwargs) + + return wrapper + + +class FontProperties: + """ + A class for storing and manipulating font properties. + + The font properties are the six properties described in the + `W3C Cascading Style Sheet, Level 1 + `_ font + specification and *math_fontfamily* for math fonts: + + - family: A list of font names in decreasing order of priority. + The items may include a generic font family name, either 'sans-serif', + 'serif', 'cursive', 'fantasy', or 'monospace'. In that case, the actual + font to be used will be looked up from the associated rcParam during the + search process in `.findfont`. Default: :rc:`font.family` + + - style: Either 'normal', 'italic' or 'oblique'. + Default: :rc:`font.style` + + - variant: Either 'normal' or 'small-caps'. + Default: :rc:`font.variant` + + - stretch: A numeric value in the range 0-1000 or one of + 'ultra-condensed', 'extra-condensed', 'condensed', + 'semi-condensed', 'normal', 'semi-expanded', 'expanded', + 'extra-expanded' or 'ultra-expanded'. Default: :rc:`font.stretch` + + - weight: A numeric value in the range 0-1000 or one of + 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', + 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', + 'extra bold', 'black'. Default: :rc:`font.weight` + + - size: Either a relative value of 'xx-small', 'x-small', + 'small', 'medium', 'large', 'x-large', 'xx-large' or an + absolute font size, e.g., 10. Default: :rc:`font.size` + + - math_fontfamily: The family of fonts used to render math text. + Supported values are: 'dejavusans', 'dejavuserif', 'cm', + 'stix', 'stixsans' and 'custom'. Default: :rc:`mathtext.fontset` + + Alternatively, a font may be specified using the absolute path to a font + file, by using the *fname* kwarg. However, in this case, it is typically + simpler to just pass the path (as a `pathlib.Path`, not a `str`) to the + *font* kwarg of the `.Text` object. + + The preferred usage of font sizes is to use the relative values, + e.g., 'large', instead of absolute font sizes, e.g., 12. This + approach allows all text sizes to be made larger or smaller based + on the font manager's default font size. + + This class accepts a single positional string as fontconfig_ pattern_, + or alternatively individual properties as keyword arguments:: + + FontProperties(pattern) + FontProperties(*, family=None, style=None, variant=None, ...) + + This support does not depend on fontconfig; we are merely borrowing its + pattern syntax for use here. + + .. _fontconfig: https://www.freedesktop.org/wiki/Software/fontconfig/ + .. _pattern: + https://www.freedesktop.org/software/fontconfig/fontconfig-user.html + + Note that Matplotlib's internal font manager and fontconfig use a + different algorithm to lookup fonts, so the results of the same pattern + may be different in Matplotlib than in other applications that use + fontconfig. + """ + + @_cleanup_fontproperties_init + def __init__(self, family=None, style=None, variant=None, weight=None, + stretch=None, size=None, + fname=None, # if set, it's a hardcoded filename to use + math_fontfamily=None): + self.set_family(family) + self.set_style(style) + self.set_variant(variant) + self.set_weight(weight) + self.set_stretch(stretch) + self.set_file(fname) + self.set_size(size) + self.set_math_fontfamily(math_fontfamily) + # Treat family as a fontconfig pattern if it is the only parameter + # provided. Even in that case, call the other setters first to set + # attributes not specified by the pattern to the rcParams defaults. + if (isinstance(family, str) + and style is None and variant is None and weight is None + and stretch is None and size is None and fname is None): + self.set_fontconfig_pattern(family) + + @classmethod + def _from_any(cls, arg): + """ + Generic constructor which can build a `.FontProperties` from any of the + following: + + - a `.FontProperties`: it is passed through as is; + - `None`: a `.FontProperties` using rc values is used; + - an `os.PathLike`: it is used as path to the font file; + - a `str`: it is parsed as a fontconfig pattern; + - a `dict`: it is passed as ``**kwargs`` to `.FontProperties`. + """ + if arg is None: + return cls() + elif isinstance(arg, cls): + return arg + elif isinstance(arg, os.PathLike): + return cls(fname=arg) + elif isinstance(arg, str): + return cls(arg) + else: + return cls(**arg) + + def __hash__(self): + l = (tuple(self.get_family()), + self.get_slant(), + self.get_variant(), + self.get_weight(), + self.get_stretch(), + self.get_size(), + self.get_file(), + self.get_math_fontfamily()) + return hash(l) + + def __eq__(self, other): + return hash(self) == hash(other) + + def __str__(self): + return self.get_fontconfig_pattern() + + def get_family(self): + """ + Return a list of individual font family names or generic family names. + + The font families or generic font families (which will be resolved + from their respective rcParams when searching for a matching font) in + the order of preference. + """ + return self._family + + def get_name(self): + """ + Return the name of the font that best matches the font properties. + """ + return get_font(findfont(self)).family_name + + def get_style(self): + """ + Return the font style. Values are: 'normal', 'italic' or 'oblique'. + """ + return self._slant + + def get_variant(self): + """ + Return the font variant. Values are: 'normal' or 'small-caps'. + """ + return self._variant + + def get_weight(self): + """ + Set the font weight. Options are: A numeric value in the + range 0-1000 or one of 'light', 'normal', 'regular', 'book', + 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', + 'heavy', 'extra bold', 'black' + """ + return self._weight + + def get_stretch(self): + """ + Return the font stretch or width. Options are: 'ultra-condensed', + 'extra-condensed', 'condensed', 'semi-condensed', 'normal', + 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'. + """ + return self._stretch + + def get_size(self): + """ + Return the font size. + """ + return self._size + + def get_file(self): + """ + Return the filename of the associated font. + """ + return self._file + + def get_fontconfig_pattern(self): + """ + Get a fontconfig_ pattern_ suitable for looking up the font as + specified with fontconfig's ``fc-match`` utility. + + This support does not depend on fontconfig; we are merely borrowing its + pattern syntax for use here. + """ + return generate_fontconfig_pattern(self) + + def set_family(self, family): + """ + Change the font family. Can be either an alias (generic name + is CSS parlance), such as: 'serif', 'sans-serif', 'cursive', + 'fantasy', or 'monospace', a real font name or a list of real + font names. Real font names are not supported when + :rc:`text.usetex` is `True`. Default: :rc:`font.family` + """ + if family is None: + family = mpl.rcParams['font.family'] + if isinstance(family, str): + family = [family] + self._family = family + + def set_style(self, style): + """ + Set the font style. + + Parameters + ---------- + style : {'normal', 'italic', 'oblique'}, default: :rc:`font.style` + """ + if style is None: + style = mpl.rcParams['font.style'] + _api.check_in_list(['normal', 'italic', 'oblique'], style=style) + self._slant = style + + def set_variant(self, variant): + """ + Set the font variant. + + Parameters + ---------- + variant : {'normal', 'small-caps'}, default: :rc:`font.variant` + """ + if variant is None: + variant = mpl.rcParams['font.variant'] + _api.check_in_list(['normal', 'small-caps'], variant=variant) + self._variant = variant + + def set_weight(self, weight): + """ + Set the font weight. + + Parameters + ---------- + weight : int or {'ultralight', 'light', 'normal', 'regular', 'book', \ +'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', \ +'extra bold', 'black'}, default: :rc:`font.weight` + If int, must be in the range 0-1000. + """ + if weight is None: + weight = mpl.rcParams['font.weight'] + if weight in weight_dict: + self._weight = weight + return + try: + weight = int(weight) + except ValueError: + pass + else: + if 0 <= weight <= 1000: + self._weight = weight + return + raise ValueError(f"{weight=} is invalid") + + def set_stretch(self, stretch): + """ + Set the font stretch or width. + + Parameters + ---------- + stretch : int or {'ultra-condensed', 'extra-condensed', 'condensed', \ +'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', \ +'ultra-expanded'}, default: :rc:`font.stretch` + If int, must be in the range 0-1000. + """ + if stretch is None: + stretch = mpl.rcParams['font.stretch'] + if stretch in stretch_dict: + self._stretch = stretch + return + try: + stretch = int(stretch) + except ValueError: + pass + else: + if 0 <= stretch <= 1000: + self._stretch = stretch + return + raise ValueError(f"{stretch=} is invalid") + + def set_size(self, size): + """ + Set the font size. + + Parameters + ---------- + size : float or {'xx-small', 'x-small', 'small', 'medium', \ +'large', 'x-large', 'xx-large'}, default: :rc:`font.size` + If a float, the font size in points. The string values denote + sizes relative to the default font size. + """ + if size is None: + size = mpl.rcParams['font.size'] + try: + size = float(size) + except ValueError: + try: + scale = font_scalings[size] + except KeyError as err: + raise ValueError( + "Size is invalid. Valid font size are " + + ", ".join(map(str, font_scalings))) from err + else: + size = scale * FontManager.get_default_size() + if size < 1.0: + _log.info('Fontsize %1.2f < 1.0 pt not allowed by FreeType. ' + 'Setting fontsize = 1 pt', size) + size = 1.0 + self._size = size + + def set_file(self, file): + """ + Set the filename of the fontfile to use. In this case, all + other properties will be ignored. + """ + self._file = os.fspath(file) if file is not None else None + + def set_fontconfig_pattern(self, pattern): + """ + Set the properties by parsing a fontconfig_ *pattern*. + + This support does not depend on fontconfig; we are merely borrowing its + pattern syntax for use here. + """ + for key, val in parse_fontconfig_pattern(pattern).items(): + if type(val) is list: + getattr(self, "set_" + key)(val[0]) + else: + getattr(self, "set_" + key)(val) + + def get_math_fontfamily(self): + """ + Return the name of the font family used for math text. + + The default font is :rc:`mathtext.fontset`. + """ + return self._math_fontfamily + + def set_math_fontfamily(self, fontfamily): + """ + Set the font family for text in math mode. + + If not set explicitly, :rc:`mathtext.fontset` will be used. + + Parameters + ---------- + fontfamily : str + The name of the font family. + + Available font families are defined in the + :ref:`default matplotlibrc file `. + + See Also + -------- + .text.Text.get_math_fontfamily + """ + if fontfamily is None: + fontfamily = mpl.rcParams['mathtext.fontset'] + else: + valid_fonts = _validators['mathtext.fontset'].valid.values() + # _check_in_list() Validates the parameter math_fontfamily as + # if it were passed to rcParams['mathtext.fontset'] + _api.check_in_list(valid_fonts, math_fontfamily=fontfamily) + self._math_fontfamily = fontfamily + + def copy(self): + """Return a copy of self.""" + return copy.copy(self) + + # Aliases + set_name = set_family + get_slant = get_style + set_slant = set_style + get_size_in_points = get_size + + +class _JSONEncoder(json.JSONEncoder): + def default(self, o): + if isinstance(o, FontManager): + return dict(o.__dict__, __class__='FontManager') + elif isinstance(o, FontEntry): + d = dict(o.__dict__, __class__='FontEntry') + try: + # Cache paths of fonts shipped with Matplotlib relative to the + # Matplotlib data path, which helps in the presence of venvs. + d["fname"] = str(Path(d["fname"]).relative_to(mpl.get_data_path())) + except ValueError: + pass + return d + else: + return super().default(o) + + +def _json_decode(o): + cls = o.pop('__class__', None) + if cls is None: + return o + elif cls == 'FontManager': + r = FontManager.__new__(FontManager) + r.__dict__.update(o) + return r + elif cls == 'FontEntry': + if not os.path.isabs(o['fname']): + o['fname'] = os.path.join(mpl.get_data_path(), o['fname']) + r = FontEntry(**o) + return r + else: + raise ValueError("Don't know how to deserialize __class__=%s" % cls) + + +def json_dump(data, filename): + """ + Dump `FontManager` *data* as JSON to the file named *filename*. + + See Also + -------- + json_load + + Notes + ----- + File paths that are children of the Matplotlib data path (typically, fonts + shipped with Matplotlib) are stored relative to that data path (to remain + valid across virtualenvs). + + This function temporarily locks the output file to prevent multiple + processes from overwriting one another's output. + """ + try: + with cbook._lock_path(filename), open(filename, 'w') as fh: + json.dump(data, fh, cls=_JSONEncoder, indent=2) + except OSError as e: + _log.warning('Could not save font_manager cache %s', e) + + +def json_load(filename): + """ + Load a `FontManager` from the JSON file named *filename*. + + See Also + -------- + json_dump + """ + with open(filename) as fh: + return json.load(fh, object_hook=_json_decode) + + +class FontManager: + """ + On import, the `FontManager` singleton instance creates a list of ttf and + afm fonts and caches their `FontProperties`. The `FontManager.findfont` + method does a nearest neighbor search to find the font that most closely + matches the specification. If no good enough match is found, the default + font is returned. + + Fonts added with the `FontManager.addfont` method will not persist in the + cache; therefore, `addfont` will need to be called every time Matplotlib is + imported. This method should only be used if and when a font cannot be + installed on your operating system by other means. + + Notes + ----- + The `FontManager.addfont` method must be called on the global `FontManager` + instance. + + Example usage:: + + import matplotlib.pyplot as plt + from matplotlib import font_manager + + font_dirs = ["/resources/fonts"] # The path to the custom font file. + font_files = font_manager.findSystemFonts(fontpaths=font_dirs) + + for font_file in font_files: + font_manager.fontManager.addfont(font_file) + """ + # Increment this version number whenever the font cache data + # format or behavior has changed and requires an existing font + # cache files to be rebuilt. + __version__ = 390 + + def __init__(self, size=None, weight='normal'): + self._version = self.__version__ + + self.__default_weight = weight + self.default_size = size + + # Create list of font paths. + paths = [cbook._get_data_path('fonts', subdir) + for subdir in ['ttf', 'afm', 'pdfcorefonts']] + _log.debug('font search path %s', paths) + + self.defaultFamily = { + 'ttf': 'DejaVu Sans', + 'afm': 'Helvetica'} + + self.afmlist = [] + self.ttflist = [] + + # Delay the warning by 5s. + timer = threading.Timer(5, lambda: _log.warning( + 'Matplotlib is building the font cache; this may take a moment.')) + timer.start() + try: + for fontext in ["afm", "ttf"]: + for path in [*findSystemFonts(paths, fontext=fontext), + *findSystemFonts(fontext=fontext)]: + try: + self.addfont(path) + except OSError as exc: + _log.info("Failed to open font file %s: %s", path, exc) + except Exception as exc: + _log.info("Failed to extract font properties from %s: " + "%s", path, exc) + finally: + timer.cancel() + + def addfont(self, path): + """ + Cache the properties of the font at *path* to make it available to the + `FontManager`. The type of font is inferred from the path suffix. + + Parameters + ---------- + path : str or path-like + + Notes + ----- + This method is useful for adding a custom font without installing it in + your operating system. See the `FontManager` singleton instance for + usage and caveats about this function. + """ + # Convert to string in case of a path as + # afmFontProperty and FT2Font expect this + path = os.fsdecode(path) + if Path(path).suffix.lower() == ".afm": + with open(path, "rb") as fh: + font = _afm.AFM(fh) + prop = afmFontProperty(path, font) + self.afmlist.append(prop) + else: + font = ft2font.FT2Font(path) + prop = ttfFontProperty(font) + self.ttflist.append(prop) + self._findfont_cached.cache_clear() + + @property + def defaultFont(self): + # Lazily evaluated (findfont then caches the result) to avoid including + # the venv path in the json serialization. + return {ext: self.findfont(family, fontext=ext) + for ext, family in self.defaultFamily.items()} + + def get_default_weight(self): + """ + Return the default font weight. + """ + return self.__default_weight + + @staticmethod + def get_default_size(): + """ + Return the default font size. + """ + return mpl.rcParams['font.size'] + + def set_default_weight(self, weight): + """ + Set the default font weight. The initial value is 'normal'. + """ + self.__default_weight = weight + + @staticmethod + def _expand_aliases(family): + if family in ('sans', 'sans serif'): + family = 'sans-serif' + return mpl.rcParams['font.' + family] + + # Each of the scoring functions below should return a value between + # 0.0 (perfect match) and 1.0 (terrible match) + def score_family(self, families, family2): + """ + Return a match score between the list of font families in + *families* and the font family name *family2*. + + An exact match at the head of the list returns 0.0. + + A match further down the list will return between 0 and 1. + + No match will return 1.0. + """ + if not isinstance(families, (list, tuple)): + families = [families] + elif len(families) == 0: + return 1.0 + family2 = family2.lower() + step = 1 / len(families) + for i, family1 in enumerate(families): + family1 = family1.lower() + if family1 in font_family_aliases: + options = [*map(str.lower, self._expand_aliases(family1))] + if family2 in options: + idx = options.index(family2) + return (i + (idx / len(options))) * step + elif family1 == family2: + # The score should be weighted by where in the + # list the font was found. + return i * step + return 1.0 + + def score_style(self, style1, style2): + """ + Return a match score between *style1* and *style2*. + + An exact match returns 0.0. + + A match between 'italic' and 'oblique' returns 0.1. + + No match returns 1.0. + """ + if style1 == style2: + return 0.0 + elif (style1 in ('italic', 'oblique') + and style2 in ('italic', 'oblique')): + return 0.1 + return 1.0 + + def score_variant(self, variant1, variant2): + """ + Return a match score between *variant1* and *variant2*. + + An exact match returns 0.0, otherwise 1.0. + """ + if variant1 == variant2: + return 0.0 + else: + return 1.0 + + def score_stretch(self, stretch1, stretch2): + """ + Return a match score between *stretch1* and *stretch2*. + + The result is the absolute value of the difference between the + CSS numeric values of *stretch1* and *stretch2*, normalized + between 0.0 and 1.0. + """ + try: + stretchval1 = int(stretch1) + except ValueError: + stretchval1 = stretch_dict.get(stretch1, 500) + try: + stretchval2 = int(stretch2) + except ValueError: + stretchval2 = stretch_dict.get(stretch2, 500) + return abs(stretchval1 - stretchval2) / 1000.0 + + def score_weight(self, weight1, weight2): + """ + Return a match score between *weight1* and *weight2*. + + The result is 0.0 if both weight1 and weight 2 are given as strings + and have the same value. + + Otherwise, the result is the absolute value of the difference between + the CSS numeric values of *weight1* and *weight2*, normalized between + 0.05 and 1.0. + """ + # exact match of the weight names, e.g. weight1 == weight2 == "regular" + if cbook._str_equal(weight1, weight2): + return 0.0 + w1 = weight1 if isinstance(weight1, Number) else weight_dict[weight1] + w2 = weight2 if isinstance(weight2, Number) else weight_dict[weight2] + return 0.95 * (abs(w1 - w2) / 1000) + 0.05 + + def score_size(self, size1, size2): + """ + Return a match score between *size1* and *size2*. + + If *size2* (the size specified in the font file) is 'scalable', this + function always returns 0.0, since any font size can be generated. + + Otherwise, the result is the absolute distance between *size1* and + *size2*, normalized so that the usual range of font sizes (6pt - + 72pt) will lie between 0.0 and 1.0. + """ + if size2 == 'scalable': + return 0.0 + # Size value should have already been + try: + sizeval1 = float(size1) + except ValueError: + sizeval1 = self.default_size * font_scalings[size1] + try: + sizeval2 = float(size2) + except ValueError: + return 1.0 + return abs(sizeval1 - sizeval2) / 72 + + def findfont(self, prop, fontext='ttf', directory=None, + fallback_to_default=True, rebuild_if_missing=True): + """ + Find the path to the font file most closely matching the given font properties. + + Parameters + ---------- + prop : str or `~matplotlib.font_manager.FontProperties` + The font properties to search for. This can be either a + `.FontProperties` object or a string defining a + `fontconfig patterns`_. + + fontext : {'ttf', 'afm'}, default: 'ttf' + The extension of the font file: + + - 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf) + - 'afm': Adobe Font Metrics (.afm) + + directory : str, optional + If given, only search this directory and its subdirectories. + + fallback_to_default : bool + If True, will fall back to the default font family (usually + "DejaVu Sans" or "Helvetica") if the first lookup hard-fails. + + rebuild_if_missing : bool + Whether to rebuild the font cache and search again if the first + match appears to point to a nonexisting font (i.e., the font cache + contains outdated entries). + + Returns + ------- + str + The filename of the best matching font. + + Notes + ----- + This performs a nearest neighbor search. Each font is given a + similarity score to the target font properties. The first font with + the highest score is returned. If no matches below a certain + threshold are found, the default font (usually DejaVu Sans) is + returned. + + The result is cached, so subsequent lookups don't have to + perform the O(n) nearest neighbor search. + + See the `W3C Cascading Style Sheet, Level 1 + `_ documentation + for a description of the font finding algorithm. + + .. _fontconfig patterns: + https://www.freedesktop.org/software/fontconfig/fontconfig-user.html + """ + # Pass the relevant rcParams (and the font manager, as `self`) to + # _findfont_cached so to prevent using a stale cache entry after an + # rcParam was changed. + rc_params = tuple(tuple(mpl.rcParams[key]) for key in [ + "font.serif", "font.sans-serif", "font.cursive", "font.fantasy", + "font.monospace"]) + ret = self._findfont_cached( + prop, fontext, directory, fallback_to_default, rebuild_if_missing, + rc_params) + if isinstance(ret, cbook._ExceptionInfo): + raise ret.to_exception() + return ret + + def get_font_names(self): + """Return the list of available fonts.""" + return list({font.name for font in self.ttflist}) + + def _find_fonts_by_props(self, prop, fontext='ttf', directory=None, + fallback_to_default=True, rebuild_if_missing=True): + """ + Find the paths to the font files most closely matching the given properties. + + Parameters + ---------- + prop : str or `~matplotlib.font_manager.FontProperties` + The font properties to search for. This can be either a + `.FontProperties` object or a string defining a + `fontconfig patterns`_. + + fontext : {'ttf', 'afm'}, default: 'ttf' + The extension of the font file: + + - 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf) + - 'afm': Adobe Font Metrics (.afm) + + directory : str, optional + If given, only search this directory and its subdirectories. + + fallback_to_default : bool + If True, will fall back to the default font family (usually + "DejaVu Sans" or "Helvetica") if none of the families were found. + + rebuild_if_missing : bool + Whether to rebuild the font cache and search again if the first + match appears to point to a nonexisting font (i.e., the font cache + contains outdated entries). + + Returns + ------- + list[str] + The paths of the fonts found. + + Notes + ----- + This is an extension/wrapper of the original findfont API, which only + returns a single font for given font properties. Instead, this API + returns a list of filepaths of multiple fonts which closely match the + given font properties. Since this internally uses the original API, + there's no change to the logic of performing the nearest neighbor + search. See `findfont` for more details. + """ + + prop = FontProperties._from_any(prop) + + fpaths = [] + for family in prop.get_family(): + cprop = prop.copy() + cprop.set_family(family) # set current prop's family + + try: + fpaths.append( + self.findfont( + cprop, fontext, directory, + fallback_to_default=False, # don't fallback to default + rebuild_if_missing=rebuild_if_missing, + ) + ) + except ValueError: + if family in font_family_aliases: + _log.warning( + "findfont: Generic family %r not found because " + "none of the following families were found: %s", + family, ", ".join(self._expand_aliases(family)) + ) + else: + _log.warning("findfont: Font family %r not found.", family) + + # only add default family if no other font was found and + # fallback_to_default is enabled + if not fpaths: + if fallback_to_default: + dfamily = self.defaultFamily[fontext] + cprop = prop.copy() + cprop.set_family(dfamily) + fpaths.append( + self.findfont( + cprop, fontext, directory, + fallback_to_default=True, + rebuild_if_missing=rebuild_if_missing, + ) + ) + else: + raise ValueError("Failed to find any font, and fallback " + "to the default font was disabled") + + return fpaths + + @lru_cache(1024) + def _findfont_cached(self, prop, fontext, directory, fallback_to_default, + rebuild_if_missing, rc_params): + + prop = FontProperties._from_any(prop) + + fname = prop.get_file() + if fname is not None: + return fname + + if fontext == 'afm': + fontlist = self.afmlist + else: + fontlist = self.ttflist + + best_score = 1e64 + best_font = None + + _log.debug('findfont: Matching %s.', prop) + for font in fontlist: + if (directory is not None and + Path(directory) not in Path(font.fname).parents): + continue + # Matching family should have top priority, so multiply it by 10. + score = (self.score_family(prop.get_family(), font.name) * 10 + + self.score_style(prop.get_style(), font.style) + + self.score_variant(prop.get_variant(), font.variant) + + self.score_weight(prop.get_weight(), font.weight) + + self.score_stretch(prop.get_stretch(), font.stretch) + + self.score_size(prop.get_size(), font.size)) + _log.debug('findfont: score(%s) = %s', font, score) + if score < best_score: + best_score = score + best_font = font + if score == 0: + break + + if best_font is None or best_score >= 10.0: + if fallback_to_default: + _log.warning( + 'findfont: Font family %s not found. Falling back to %s.', + prop.get_family(), self.defaultFamily[fontext]) + for family in map(str.lower, prop.get_family()): + if family in font_family_aliases: + _log.warning( + "findfont: Generic family %r not found because " + "none of the following families were found: %s", + family, ", ".join(self._expand_aliases(family))) + default_prop = prop.copy() + default_prop.set_family(self.defaultFamily[fontext]) + return self.findfont(default_prop, fontext, directory, + fallback_to_default=False) + else: + # This return instead of raise is intentional, as we wish to + # cache that it was not found, which will not occur if it was + # actually raised. + return cbook._ExceptionInfo( + ValueError, + f"Failed to find font {prop}, and fallback to the default font was " + f"disabled" + ) + else: + _log.debug('findfont: Matching %s to %s (%r) with score of %f.', + prop, best_font.name, best_font.fname, best_score) + result = best_font.fname + + if not os.path.isfile(result): + if rebuild_if_missing: + _log.info( + 'findfont: Found a missing font file. Rebuilding cache.') + new_fm = _load_fontmanager(try_read_cache=False) + # Replace self by the new fontmanager, because users may have + # a reference to this specific instance. + # TODO: _load_fontmanager should really be (used by) a method + # modifying the instance in place. + vars(self).update(vars(new_fm)) + return self.findfont( + prop, fontext, directory, rebuild_if_missing=False) + else: + # This return instead of raise is intentional, as we wish to + # cache that it was not found, which will not occur if it was + # actually raised. + return cbook._ExceptionInfo(ValueError, "No valid font could be found") + + return _cached_realpath(result) + + +@lru_cache +def is_opentype_cff_font(filename): + """ + Return whether the given font is a Postscript Compact Font Format Font + embedded in an OpenType wrapper. Used by the PostScript and PDF backends + that cannot subset these fonts. + """ + if os.path.splitext(filename)[1].lower() == '.otf': + with open(filename, 'rb') as fd: + return fd.read(4) == b"OTTO" + else: + return False + + +@lru_cache(64) +def _get_font(font_filepaths, hinting_factor, *, _kerning_factor, thread_id): + first_fontpath, *rest = font_filepaths + return ft2font.FT2Font( + first_fontpath, hinting_factor, + _fallback_list=[ + ft2font.FT2Font( + fpath, hinting_factor, + _kerning_factor=_kerning_factor + ) + for fpath in rest + ], + _kerning_factor=_kerning_factor + ) + + +# FT2Font objects cannot be used across fork()s because they reference the same +# FT_Library object. While invalidating *all* existing FT2Fonts after a fork +# would be too complicated to be worth it, the main way FT2Fonts get reused is +# via the cache of _get_font, which we can empty upon forking (not on Windows, +# which has no fork() or register_at_fork()). +if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=_get_font.cache_clear) + + +@lru_cache(64) +def _cached_realpath(path): + # Resolving the path avoids embedding the font twice in pdf/ps output if a + # single font is selected using two different relative paths. + return os.path.realpath(path) + + +def get_font(font_filepaths, hinting_factor=None): + """ + Get an `.ft2font.FT2Font` object given a list of file paths. + + Parameters + ---------- + font_filepaths : Iterable[str, Path, bytes], str, Path, bytes + Relative or absolute paths to the font files to be used. + + If a single string, bytes, or `pathlib.Path`, then it will be treated + as a list with that entry only. + + If more than one filepath is passed, then the returned FT2Font object + will fall back through the fonts, in the order given, to find a needed + glyph. + + Returns + ------- + `.ft2font.FT2Font` + + """ + if isinstance(font_filepaths, (str, Path, bytes)): + paths = (_cached_realpath(font_filepaths),) + else: + paths = tuple(_cached_realpath(fname) for fname in font_filepaths) + + if hinting_factor is None: + hinting_factor = mpl.rcParams['text.hinting_factor'] + + return _get_font( + # must be a tuple to be cached + paths, + hinting_factor, + _kerning_factor=mpl.rcParams['text.kerning_factor'], + # also key on the thread ID to prevent segfaults with multi-threading + thread_id=threading.get_ident() + ) + + +def _load_fontmanager(*, try_read_cache=True): + fm_path = Path( + mpl.get_cachedir(), f"fontlist-v{FontManager.__version__}.json") + if try_read_cache: + try: + fm = json_load(fm_path) + except Exception: + pass + else: + if getattr(fm, "_version", object()) == FontManager.__version__: + _log.debug("Using fontManager instance from %s", fm_path) + return fm + fm = FontManager() + json_dump(fm, fm_path) + _log.info("generated new fontManager") + return fm + + +fontManager = _load_fontmanager() +findfont = fontManager.findfont +get_font_names = fontManager.get_font_names diff --git a/moondream/lib/python3.10/site-packages/matplotlib/image.py b/moondream/lib/python3.10/site-packages/matplotlib/image.py new file mode 100644 index 0000000000000000000000000000000000000000..37a1d11678fa6d464262813c9ffc13f6ad62f268 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/image.py @@ -0,0 +1,1763 @@ +""" +The image module supports basic image loading, rescaling and display +operations. +""" + +import math +import os +import logging +from pathlib import Path +import warnings + +import numpy as np +import PIL.Image +import PIL.PngImagePlugin + +import matplotlib as mpl +from matplotlib import _api, cbook +# For clarity, names from _image are given explicitly in this module +from matplotlib import _image +# For user convenience, the names from _image are also imported into +# the image namespace +from matplotlib._image import * # noqa: F401, F403 +import matplotlib.artist as martist +import matplotlib.colorizer as mcolorizer +from matplotlib.backend_bases import FigureCanvasBase +import matplotlib.colors as mcolors +from matplotlib.transforms import ( + Affine2D, BboxBase, Bbox, BboxTransform, BboxTransformTo, + IdentityTransform, TransformedBbox) + +_log = logging.getLogger(__name__) + +# map interpolation strings to module constants +_interpd_ = { + 'auto': _image.NEAREST, # this will use nearest or Hanning... + 'none': _image.NEAREST, # fall back to nearest when not supported + 'nearest': _image.NEAREST, + 'bilinear': _image.BILINEAR, + 'bicubic': _image.BICUBIC, + 'spline16': _image.SPLINE16, + 'spline36': _image.SPLINE36, + 'hanning': _image.HANNING, + 'hamming': _image.HAMMING, + 'hermite': _image.HERMITE, + 'kaiser': _image.KAISER, + 'quadric': _image.QUADRIC, + 'catrom': _image.CATROM, + 'gaussian': _image.GAUSSIAN, + 'bessel': _image.BESSEL, + 'mitchell': _image.MITCHELL, + 'sinc': _image.SINC, + 'lanczos': _image.LANCZOS, + 'blackman': _image.BLACKMAN, + 'antialiased': _image.NEAREST, # this will use nearest or Hanning... +} + +interpolations_names = set(_interpd_) + + +def composite_images(images, renderer, magnification=1.0): + """ + Composite a number of RGBA images into one. The images are + composited in the order in which they appear in the *images* list. + + Parameters + ---------- + images : list of Images + Each must have a `make_image` method. For each image, + `can_composite` should return `True`, though this is not + enforced by this function. Each image must have a purely + affine transformation with no shear. + + renderer : `.RendererBase` + + magnification : float, default: 1 + The additional magnification to apply for the renderer in use. + + Returns + ------- + image : (M, N, 4) `numpy.uint8` array + The composited RGBA image. + offset_x, offset_y : float + The (left, bottom) offset where the composited image should be placed + in the output figure. + """ + if len(images) == 0: + return np.empty((0, 0, 4), dtype=np.uint8), 0, 0 + + parts = [] + bboxes = [] + for image in images: + data, x, y, trans = image.make_image(renderer, magnification) + if data is not None: + x *= magnification + y *= magnification + parts.append((data, x, y, image._get_scalar_alpha())) + bboxes.append( + Bbox([[x, y], [x + data.shape[1], y + data.shape[0]]])) + + if len(parts) == 0: + return np.empty((0, 0, 4), dtype=np.uint8), 0, 0 + + bbox = Bbox.union(bboxes) + + output = np.zeros( + (int(bbox.height), int(bbox.width), 4), dtype=np.uint8) + + for data, x, y, alpha in parts: + trans = Affine2D().translate(x - bbox.x0, y - bbox.y0) + _image.resample(data, output, trans, _image.NEAREST, + resample=False, alpha=alpha) + + return output, bbox.x0 / magnification, bbox.y0 / magnification + + +def _draw_list_compositing_images( + renderer, parent, artists, suppress_composite=None): + """ + Draw a sorted list of artists, compositing images into a single + image where possible. + + For internal Matplotlib use only: It is here to reduce duplication + between `Figure.draw` and `Axes.draw`, but otherwise should not be + generally useful. + """ + has_images = any(isinstance(x, _ImageBase) for x in artists) + + # override the renderer default if suppressComposite is not None + not_composite = (suppress_composite if suppress_composite is not None + else renderer.option_image_nocomposite()) + + if not_composite or not has_images: + for a in artists: + a.draw(renderer) + else: + # Composite any adjacent images together + image_group = [] + mag = renderer.get_image_magnification() + + def flush_images(): + if len(image_group) == 1: + image_group[0].draw(renderer) + elif len(image_group) > 1: + data, l, b = composite_images(image_group, renderer, mag) + if data.size != 0: + gc = renderer.new_gc() + gc.set_clip_rectangle(parent.bbox) + gc.set_clip_path(parent.get_clip_path()) + renderer.draw_image(gc, round(l), round(b), data) + gc.restore() + del image_group[:] + + for a in artists: + if (isinstance(a, _ImageBase) and a.can_composite() and + a.get_clip_on() and not a.get_clip_path()): + image_group.append(a) + else: + flush_images() + a.draw(renderer) + flush_images() + + +def _resample( + image_obj, data, out_shape, transform, *, resample=None, alpha=1): + """ + Convenience wrapper around `._image.resample` to resample *data* to + *out_shape* (with a third dimension if *data* is RGBA) that takes care of + allocating the output array and fetching the relevant properties from the + Image object *image_obj*. + """ + # AGG can only handle coordinates smaller than 24-bit signed integers, + # so raise errors if the input data is larger than _image.resample can + # handle. + msg = ('Data with more than {n} cannot be accurately displayed. ' + 'Downsampling to less than {n} before displaying. ' + 'To remove this warning, manually downsample your data.') + if data.shape[1] > 2**23: + warnings.warn(msg.format(n='2**23 columns')) + step = int(np.ceil(data.shape[1] / 2**23)) + data = data[:, ::step] + transform = Affine2D().scale(step, 1) + transform + if data.shape[0] > 2**24: + warnings.warn(msg.format(n='2**24 rows')) + step = int(np.ceil(data.shape[0] / 2**24)) + data = data[::step, :] + transform = Affine2D().scale(1, step) + transform + # decide if we need to apply anti-aliasing if the data is upsampled: + # compare the number of displayed pixels to the number of + # the data pixels. + interpolation = image_obj.get_interpolation() + if interpolation in ['antialiased', 'auto']: + # don't antialias if upsampling by an integer number or + # if zooming in more than a factor of 3 + pos = np.array([[0, 0], [data.shape[1], data.shape[0]]]) + disp = transform.transform(pos) + dispx = np.abs(np.diff(disp[:, 0])) + dispy = np.abs(np.diff(disp[:, 1])) + if ((dispx > 3 * data.shape[1] or + dispx == data.shape[1] or + dispx == 2 * data.shape[1]) and + (dispy > 3 * data.shape[0] or + dispy == data.shape[0] or + dispy == 2 * data.shape[0])): + interpolation = 'nearest' + else: + interpolation = 'hanning' + out = np.zeros(out_shape + data.shape[2:], data.dtype) # 2D->2D, 3D->3D. + if resample is None: + resample = image_obj.get_resample() + _image.resample(data, out, transform, + _interpd_[interpolation], + resample, + alpha, + image_obj.get_filternorm(), + image_obj.get_filterrad()) + return out + + +def _rgb_to_rgba(A): + """ + Convert an RGB image to RGBA, as required by the image resample C++ + extension. + """ + rgba = np.zeros((A.shape[0], A.shape[1], 4), dtype=A.dtype) + rgba[:, :, :3] = A + if rgba.dtype == np.uint8: + rgba[:, :, 3] = 255 + else: + rgba[:, :, 3] = 1.0 + return rgba + + +class _ImageBase(mcolorizer.ColorizingArtist): + """ + Base class for images. + + interpolation and cmap default to their rc settings + + cmap is a colors.Colormap instance + norm is a colors.Normalize instance to map luminance to 0-1 + + extent is data axes (left, right, bottom, top) for making image plots + registered with data plots. Default is to label the pixel + centers with the zero-based row and column indices. + + Additional kwargs are matplotlib.artist properties + """ + zorder = 0 + + def __init__(self, ax, + cmap=None, + norm=None, + colorizer=None, + interpolation=None, + origin=None, + filternorm=True, + filterrad=4.0, + resample=False, + *, + interpolation_stage=None, + **kwargs + ): + super().__init__(self._get_colorizer(cmap, norm, colorizer)) + if origin is None: + origin = mpl.rcParams['image.origin'] + _api.check_in_list(["upper", "lower"], origin=origin) + self.origin = origin + self.set_filternorm(filternorm) + self.set_filterrad(filterrad) + self.set_interpolation(interpolation) + self.set_interpolation_stage(interpolation_stage) + self.set_resample(resample) + self.axes = ax + + self._imcache = None + + self._internal_update(kwargs) + + def __str__(self): + try: + shape = self.get_shape() + return f"{type(self).__name__}(shape={shape!r})" + except RuntimeError: + return type(self).__name__ + + def __getstate__(self): + # Save some space on the pickle by not saving the cache. + return {**super().__getstate__(), "_imcache": None} + + def get_size(self): + """Return the size of the image as tuple (numrows, numcols).""" + return self.get_shape()[:2] + + def get_shape(self): + """ + Return the shape of the image as tuple (numrows, numcols, channels). + """ + if self._A is None: + raise RuntimeError('You must first set the image array') + + return self._A.shape + + def set_alpha(self, alpha): + """ + Set the alpha value used for blending - not supported on all backends. + + Parameters + ---------- + alpha : float or 2D array-like or None + """ + martist.Artist._set_alpha_for_array(self, alpha) + if np.ndim(alpha) not in (0, 2): + raise TypeError('alpha must be a float, two-dimensional ' + 'array, or None') + self._imcache = None + + def _get_scalar_alpha(self): + """ + Get a scalar alpha value to be applied to the artist as a whole. + + If the alpha value is a matrix, the method returns 1.0 because pixels + have individual alpha values (see `~._ImageBase._make_image` for + details). If the alpha value is a scalar, the method returns said value + to be applied to the artist as a whole because pixels do not have + individual alpha values. + """ + return 1.0 if self._alpha is None or np.ndim(self._alpha) > 0 \ + else self._alpha + + def changed(self): + """ + Call this whenever the mappable is changed so observers can update. + """ + self._imcache = None + super().changed() + + def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0, + unsampled=False, round_to_pixel_border=True): + """ + Normalize, rescale, and colormap the image *A* from the given *in_bbox* + (in data space), to the given *out_bbox* (in pixel space) clipped to + the given *clip_bbox* (also in pixel space), and magnified by the + *magnification* factor. + + Parameters + ---------- + A : ndarray + + - a (M, N) array interpreted as scalar (greyscale) image, + with one of the dtypes `~numpy.float32`, `~numpy.float64`, + `~numpy.float128`, `~numpy.uint16` or `~numpy.uint8`. + - (M, N, 4) RGBA image with a dtype of `~numpy.float32`, + `~numpy.float64`, `~numpy.float128`, or `~numpy.uint8`. + + in_bbox : `~matplotlib.transforms.Bbox` + + out_bbox : `~matplotlib.transforms.Bbox` + + clip_bbox : `~matplotlib.transforms.Bbox` + + magnification : float, default: 1 + + unsampled : bool, default: False + If True, the image will not be scaled, but an appropriate + affine transformation will be returned instead. + + round_to_pixel_border : bool, default: True + If True, the output image size will be rounded to the nearest pixel + boundary. This makes the images align correctly with the Axes. + It should not be used if exact scaling is needed, such as for + `.FigureImage`. + + Returns + ------- + image : (M, N, 4) `numpy.uint8` array + The RGBA image, resampled unless *unsampled* is True. + x, y : float + The upper left corner where the image should be drawn, in pixel + space. + trans : `~matplotlib.transforms.Affine2D` + The affine transformation from image to pixel space. + """ + if A is None: + raise RuntimeError('You must first set the image ' + 'array or the image attribute') + if A.size == 0: + raise RuntimeError("_make_image must get a non-empty image. " + "Your Artist's draw method must filter before " + "this method is called.") + + clipped_bbox = Bbox.intersection(out_bbox, clip_bbox) + + if clipped_bbox is None: + return None, 0, 0, None + + out_width_base = clipped_bbox.width * magnification + out_height_base = clipped_bbox.height * magnification + + if out_width_base == 0 or out_height_base == 0: + return None, 0, 0, None + + if self.origin == 'upper': + # Flip the input image using a transform. This avoids the + # problem with flipping the array, which results in a copy + # when it is converted to contiguous in the C wrapper + t0 = Affine2D().translate(0, -A.shape[0]).scale(1, -1) + else: + t0 = IdentityTransform() + + t0 += ( + Affine2D() + .scale( + in_bbox.width / A.shape[1], + in_bbox.height / A.shape[0]) + .translate(in_bbox.x0, in_bbox.y0) + + self.get_transform()) + + t = (t0 + + (Affine2D() + .translate(-clipped_bbox.x0, -clipped_bbox.y0) + .scale(magnification))) + + # So that the image is aligned with the edge of the Axes, we want to + # round up the output width to the next integer. This also means + # scaling the transform slightly to account for the extra subpixel. + if ((not unsampled) and t.is_affine and round_to_pixel_border and + (out_width_base % 1.0 != 0.0 or out_height_base % 1.0 != 0.0)): + out_width = math.ceil(out_width_base) + out_height = math.ceil(out_height_base) + extra_width = (out_width - out_width_base) / out_width_base + extra_height = (out_height - out_height_base) / out_height_base + t += Affine2D().scale(1.0 + extra_width, 1.0 + extra_height) + else: + out_width = int(out_width_base) + out_height = int(out_height_base) + out_shape = (out_height, out_width) + + if not unsampled: + if not (A.ndim == 2 or A.ndim == 3 and A.shape[-1] in (3, 4)): + raise ValueError(f"Invalid shape {A.shape} for image data") + + # if antialiased, this needs to change as window sizes + # change: + interpolation_stage = self._interpolation_stage + if interpolation_stage in ['antialiased', 'auto']: + pos = np.array([[0, 0], [A.shape[1], A.shape[0]]]) + disp = t.transform(pos) + dispx = np.abs(np.diff(disp[:, 0])) / A.shape[1] + dispy = np.abs(np.diff(disp[:, 1])) / A.shape[0] + if (dispx < 3) or (dispy < 3): + interpolation_stage = 'rgba' + else: + interpolation_stage = 'data' + + if A.ndim == 2 and interpolation_stage == 'data': + # if we are a 2D array, then we are running through the + # norm + colormap transformation. However, in general the + # input data is not going to match the size on the screen so we + # have to resample to the correct number of pixels + + if A.dtype.kind == 'f': # Float dtype: scale to same dtype. + scaled_dtype = np.dtype("f8" if A.dtype.itemsize > 4 else "f4") + if scaled_dtype.itemsize < A.dtype.itemsize: + _api.warn_external(f"Casting input data from {A.dtype}" + f" to {scaled_dtype} for imshow.") + else: # Int dtype, likely. + # TODO slice input array first + # Scale to appropriately sized float: use float32 if the + # dynamic range is small, to limit the memory footprint. + da = A.max().astype("f8") - A.min().astype("f8") + scaled_dtype = "f8" if da > 1e8 else "f4" + + # resample the input data to the correct resolution and shape + A_resampled = _resample(self, A.astype(scaled_dtype), out_shape, t) + + # if using NoNorm, cast back to the original datatype + if isinstance(self.norm, mcolors.NoNorm): + A_resampled = A_resampled.astype(A.dtype) + + # Compute out_mask (what screen pixels include "bad" data + # pixels) and out_alpha (to what extent screen pixels are + # covered by data pixels: 0 outside the data extent, 1 inside + # (even for bad data), and intermediate values at the edges). + mask = (np.where(A.mask, np.float32(np.nan), np.float32(1)) + if A.mask.shape == A.shape # nontrivial mask + else np.ones_like(A, np.float32)) + # we always have to interpolate the mask to account for + # non-affine transformations + out_alpha = _resample(self, mask, out_shape, t, resample=True) + del mask # Make sure we don't use mask anymore! + out_mask = np.isnan(out_alpha) + out_alpha[out_mask] = 1 + # Apply the pixel-by-pixel alpha values if present + alpha = self.get_alpha() + if alpha is not None and np.ndim(alpha) > 0: + out_alpha *= _resample(self, alpha, out_shape, t, resample=True) + # mask and run through the norm + resampled_masked = np.ma.masked_array(A_resampled, out_mask) + output = self.norm(resampled_masked) + else: + if A.ndim == 2: # interpolation_stage = 'rgba' + self.norm.autoscale_None(A) + A = self.to_rgba(A) + alpha = self._get_scalar_alpha() + if A.shape[2] == 3: + # No need to resample alpha or make a full array; NumPy will expand + # this out and cast to uint8 if necessary when it's assigned to the + # alpha channel below. + output_alpha = (255 * alpha) if A.dtype == np.uint8 else alpha + else: + output_alpha = _resample( # resample alpha channel + self, A[..., 3], out_shape, t, alpha=alpha) + output = _resample( # resample rgb channels + self, _rgb_to_rgba(A[..., :3]), out_shape, t, alpha=alpha) + output[..., 3] = output_alpha # recombine rgb and alpha + + # output is now either a 2D array of normed (int or float) data + # or an RGBA array of re-sampled input + output = self.to_rgba(output, bytes=True, norm=False) + # output is now a correctly sized RGBA array of uint8 + + # Apply alpha *after* if the input was greyscale without a mask + if A.ndim == 2: + alpha = self._get_scalar_alpha() + alpha_channel = output[:, :, 3] + alpha_channel[:] = ( # Assignment will cast to uint8. + alpha_channel.astype(np.float32) * out_alpha * alpha) + + else: + if self._imcache is None: + self._imcache = self.to_rgba(A, bytes=True, norm=(A.ndim == 2)) + output = self._imcache + + # Subset the input image to only the part that will be displayed. + subset = TransformedBbox(clip_bbox, t0.inverted()).frozen() + output = output[ + int(max(subset.ymin, 0)): + int(min(subset.ymax + 1, output.shape[0])), + int(max(subset.xmin, 0)): + int(min(subset.xmax + 1, output.shape[1]))] + + t = Affine2D().translate( + int(max(subset.xmin, 0)), int(max(subset.ymin, 0))) + t + + return output, clipped_bbox.x0, clipped_bbox.y0, t + + def make_image(self, renderer, magnification=1.0, unsampled=False): + """ + Normalize, rescale, and colormap this image's data for rendering using + *renderer*, with the given *magnification*. + + If *unsampled* is True, the image will not be scaled, but an + appropriate affine transformation will be returned instead. + + Returns + ------- + image : (M, N, 4) `numpy.uint8` array + The RGBA image, resampled unless *unsampled* is True. + x, y : float + The upper left corner where the image should be drawn, in pixel + space. + trans : `~matplotlib.transforms.Affine2D` + The affine transformation from image to pixel space. + """ + raise NotImplementedError('The make_image method must be overridden') + + def _check_unsampled_image(self): + """ + Return whether the image is better to be drawn unsampled. + + The derived class needs to override it. + """ + return False + + @martist.allow_rasterization + def draw(self, renderer): + # if not visible, declare victory and return + if not self.get_visible(): + self.stale = False + return + # for empty images, there is nothing to draw! + if self.get_array().size == 0: + self.stale = False + return + # actually render the image. + gc = renderer.new_gc() + self._set_gc_clip(gc) + gc.set_alpha(self._get_scalar_alpha()) + gc.set_url(self.get_url()) + gc.set_gid(self.get_gid()) + if (renderer.option_scale_image() # Renderer supports transform kwarg. + and self._check_unsampled_image() + and self.get_transform().is_affine): + im, l, b, trans = self.make_image(renderer, unsampled=True) + if im is not None: + trans = Affine2D().scale(im.shape[1], im.shape[0]) + trans + renderer.draw_image(gc, l, b, im, trans) + else: + im, l, b, trans = self.make_image( + renderer, renderer.get_image_magnification()) + if im is not None: + renderer.draw_image(gc, l, b, im) + gc.restore() + self.stale = False + + def contains(self, mouseevent): + """Test whether the mouse event occurred within the image.""" + if (self._different_canvas(mouseevent) + # This doesn't work for figimage. + or not self.axes.contains(mouseevent)[0]): + return False, {} + # TODO: make sure this is consistent with patch and patch + # collection on nonlinear transformed coordinates. + # TODO: consider returning image coordinates (shouldn't + # be too difficult given that the image is rectilinear + trans = self.get_transform().inverted() + x, y = trans.transform([mouseevent.x, mouseevent.y]) + xmin, xmax, ymin, ymax = self.get_extent() + # This checks xmin <= x <= xmax *or* xmax <= x <= xmin. + inside = (x is not None and (x - xmin) * (x - xmax) <= 0 + and y is not None and (y - ymin) * (y - ymax) <= 0) + return inside, {} + + def write_png(self, fname): + """Write the image to png file *fname*.""" + im = self.to_rgba(self._A[::-1] if self.origin == 'lower' else self._A, + bytes=True, norm=True) + PIL.Image.fromarray(im).save(fname, format="png") + + @staticmethod + def _normalize_image_array(A): + """ + Check validity of image-like input *A* and normalize it to a format suitable for + Image subclasses. + """ + A = cbook.safe_masked_invalid(A, copy=True) + if A.dtype != np.uint8 and not np.can_cast(A.dtype, float, "same_kind"): + raise TypeError(f"Image data of dtype {A.dtype} cannot be " + f"converted to float") + if A.ndim == 3 and A.shape[-1] == 1: + A = A.squeeze(-1) # If just (M, N, 1), assume scalar and apply colormap. + if not (A.ndim == 2 or A.ndim == 3 and A.shape[-1] in [3, 4]): + raise TypeError(f"Invalid shape {A.shape} for image data") + if A.ndim == 3: + # If the input data has values outside the valid range (after + # normalisation), we issue a warning and then clip X to the bounds + # - otherwise casting wraps extreme values, hiding outliers and + # making reliable interpretation impossible. + high = 255 if np.issubdtype(A.dtype, np.integer) else 1 + if A.min() < 0 or high < A.max(): + _log.warning( + 'Clipping input data to the valid range for imshow with ' + 'RGB data ([0..1] for floats or [0..255] for integers). ' + 'Got range [%s..%s].', + A.min(), A.max() + ) + A = np.clip(A, 0, high) + # Cast unsupported integer types to uint8 + if A.dtype != np.uint8 and np.issubdtype(A.dtype, np.integer): + A = A.astype(np.uint8) + return A + + def set_data(self, A): + """ + Set the image array. + + Note that this function does *not* update the normalization used. + + Parameters + ---------- + A : array-like or `PIL.Image.Image` + """ + if isinstance(A, PIL.Image.Image): + A = pil_to_array(A) # Needed e.g. to apply png palette. + self._A = self._normalize_image_array(A) + self._imcache = None + self.stale = True + + def set_array(self, A): + """ + Retained for backwards compatibility - use set_data instead. + + Parameters + ---------- + A : array-like + """ + # This also needs to be here to override the inherited + # cm.ScalarMappable.set_array method so it is not invoked by mistake. + self.set_data(A) + + def get_interpolation(self): + """ + Return the interpolation method the image uses when resizing. + + One of 'auto', 'antialiased', 'nearest', 'bilinear', 'bicubic', + 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', + 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', + or 'none'. + """ + return self._interpolation + + def set_interpolation(self, s): + """ + Set the interpolation method the image uses when resizing. + + If None, use :rc:`image.interpolation`. If 'none', the image is + shown as is without interpolating. 'none' is only supported in + agg, ps and pdf backends and will fall back to 'nearest' mode + for other backends. + + Parameters + ---------- + s : {'auto', 'nearest', 'bilinear', 'bicubic', 'spline16', \ +'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', \ +'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'none'} or None + """ + s = mpl._val_or_rc(s, 'image.interpolation').lower() + _api.check_in_list(interpolations_names, interpolation=s) + self._interpolation = s + self.stale = True + + def get_interpolation_stage(self): + """ + Return when interpolation happens during the transform to RGBA. + + One of 'data', 'rgba', 'auto'. + """ + return self._interpolation_stage + + def set_interpolation_stage(self, s): + """ + Set when interpolation happens during the transform to RGBA. + + Parameters + ---------- + s : {'data', 'rgba', 'auto'} or None + Whether to apply up/downsampling interpolation in data or RGBA + space. If None, use :rc:`image.interpolation_stage`. + If 'auto' we will check upsampling rate and if less + than 3 then use 'rgba', otherwise use 'data'. + """ + s = mpl._val_or_rc(s, 'image.interpolation_stage') + _api.check_in_list(['data', 'rgba', 'auto'], s=s) + self._interpolation_stage = s + self.stale = True + + def can_composite(self): + """Return whether the image can be composited with its neighbors.""" + trans = self.get_transform() + return ( + self._interpolation != 'none' and + trans.is_affine and + trans.is_separable) + + def set_resample(self, v): + """ + Set whether image resampling is used. + + Parameters + ---------- + v : bool or None + If None, use :rc:`image.resample`. + """ + v = mpl._val_or_rc(v, 'image.resample') + self._resample = v + self.stale = True + + def get_resample(self): + """Return whether image resampling is used.""" + return self._resample + + def set_filternorm(self, filternorm): + """ + Set whether the resize filter normalizes the weights. + + See help for `~.Axes.imshow`. + + Parameters + ---------- + filternorm : bool + """ + self._filternorm = bool(filternorm) + self.stale = True + + def get_filternorm(self): + """Return whether the resize filter normalizes the weights.""" + return self._filternorm + + def set_filterrad(self, filterrad): + """ + Set the resize filter radius only applicable to some + interpolation schemes -- see help for imshow + + Parameters + ---------- + filterrad : positive float + """ + r = float(filterrad) + if r <= 0: + raise ValueError("The filter radius must be a positive number") + self._filterrad = r + self.stale = True + + def get_filterrad(self): + """Return the filterrad setting.""" + return self._filterrad + + +class AxesImage(_ImageBase): + """ + An image attached to an Axes. + + Parameters + ---------- + ax : `~matplotlib.axes.Axes` + The Axes the image will belong to. + cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap` + The Colormap instance or registered colormap name used to map scalar + data to colors. + norm : str or `~matplotlib.colors.Normalize` + Maps luminance to 0-1. + interpolation : str, default: :rc:`image.interpolation` + Supported values are 'none', 'auto', 'nearest', 'bilinear', + 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', + 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', + 'sinc', 'lanczos', 'blackman'. + interpolation_stage : {'data', 'rgba'}, default: 'data' + If 'data', interpolation + is carried out on the data provided by the user. If 'rgba', the + interpolation is carried out after the colormapping has been + applied (visual interpolation). + origin : {'upper', 'lower'}, default: :rc:`image.origin` + Place the [0, 0] index of the array in the upper left or lower left + corner of the Axes. The convention 'upper' is typically used for + matrices and images. + extent : tuple, optional + The data axes (left, right, bottom, top) for making image plots + registered with data plots. Default is to label the pixel + centers with the zero-based row and column indices. + filternorm : bool, default: True + A parameter for the antigrain image resize filter + (see the antigrain documentation). + If filternorm is set, the filter normalizes integer values and corrects + the rounding errors. It doesn't do anything with the source floating + point values, it corrects only integers according to the rule of 1.0 + which means that any sum of pixel weights must be equal to 1.0. So, + the filter function must produce a graph of the proper shape. + filterrad : float > 0, default: 4 + The filter radius for filters that have a radius parameter, i.e. when + interpolation is one of: 'sinc', 'lanczos' or 'blackman'. + resample : bool, default: False + When True, use a full resampling method. When False, only resample when + the output image is larger than the input image. + **kwargs : `~matplotlib.artist.Artist` properties + """ + + def __init__(self, ax, + *, + cmap=None, + norm=None, + colorizer=None, + interpolation=None, + origin=None, + extent=None, + filternorm=True, + filterrad=4.0, + resample=False, + interpolation_stage=None, + **kwargs + ): + + self._extent = extent + + super().__init__( + ax, + cmap=cmap, + norm=norm, + colorizer=colorizer, + interpolation=interpolation, + origin=origin, + filternorm=filternorm, + filterrad=filterrad, + resample=resample, + interpolation_stage=interpolation_stage, + **kwargs + ) + + def get_window_extent(self, renderer=None): + x0, x1, y0, y1 = self._extent + bbox = Bbox.from_extents([x0, y0, x1, y1]) + return bbox.transformed(self.get_transform()) + + def make_image(self, renderer, magnification=1.0, unsampled=False): + # docstring inherited + trans = self.get_transform() + # image is created in the canvas coordinate. + x1, x2, y1, y2 = self.get_extent() + bbox = Bbox(np.array([[x1, y1], [x2, y2]])) + transformed_bbox = TransformedBbox(bbox, trans) + clip = ((self.get_clip_box() or self.axes.bbox) if self.get_clip_on() + else self.get_figure(root=True).bbox) + return self._make_image(self._A, bbox, transformed_bbox, clip, + magnification, unsampled=unsampled) + + def _check_unsampled_image(self): + """Return whether the image would be better drawn unsampled.""" + return self.get_interpolation() == "none" + + def set_extent(self, extent, **kwargs): + """ + Set the image extent. + + Parameters + ---------- + extent : 4-tuple of float + The position and size of the image as tuple + ``(left, right, bottom, top)`` in data coordinates. + **kwargs + Other parameters from which unit info (i.e., the *xunits*, + *yunits*, *zunits* (for 3D Axes), *runits* and *thetaunits* (for + polar Axes) entries are applied, if present. + + Notes + ----- + This updates `.Axes.dataLim`, and, if autoscaling, sets `.Axes.viewLim` + to tightly fit the image, regardless of `~.Axes.dataLim`. Autoscaling + state is not changed, so a subsequent call to `.Axes.autoscale_view` + will redo the autoscaling in accord with `~.Axes.dataLim`. + """ + (xmin, xmax), (ymin, ymax) = self.axes._process_unit_info( + [("x", [extent[0], extent[1]]), + ("y", [extent[2], extent[3]])], + kwargs) + if kwargs: + raise _api.kwarg_error("set_extent", kwargs) + xmin = self.axes._validate_converted_limits( + xmin, self.convert_xunits) + xmax = self.axes._validate_converted_limits( + xmax, self.convert_xunits) + ymin = self.axes._validate_converted_limits( + ymin, self.convert_yunits) + ymax = self.axes._validate_converted_limits( + ymax, self.convert_yunits) + extent = [xmin, xmax, ymin, ymax] + + self._extent = extent + corners = (xmin, ymin), (xmax, ymax) + self.axes.update_datalim(corners) + self.sticky_edges.x[:] = [xmin, xmax] + self.sticky_edges.y[:] = [ymin, ymax] + if self.axes.get_autoscalex_on(): + self.axes.set_xlim((xmin, xmax), auto=None) + if self.axes.get_autoscaley_on(): + self.axes.set_ylim((ymin, ymax), auto=None) + self.stale = True + + def get_extent(self): + """Return the image extent as tuple (left, right, bottom, top).""" + if self._extent is not None: + return self._extent + else: + sz = self.get_size() + numrows, numcols = sz + if self.origin == 'upper': + return (-0.5, numcols-0.5, numrows-0.5, -0.5) + else: + return (-0.5, numcols-0.5, -0.5, numrows-0.5) + + def get_cursor_data(self, event): + """ + Return the image value at the event position or *None* if the event is + outside the image. + + See Also + -------- + matplotlib.artist.Artist.get_cursor_data + """ + xmin, xmax, ymin, ymax = self.get_extent() + if self.origin == 'upper': + ymin, ymax = ymax, ymin + arr = self.get_array() + data_extent = Bbox([[xmin, ymin], [xmax, ymax]]) + array_extent = Bbox([[0, 0], [arr.shape[1], arr.shape[0]]]) + trans = self.get_transform().inverted() + trans += BboxTransform(boxin=data_extent, boxout=array_extent) + point = trans.transform([event.x, event.y]) + if any(np.isnan(point)): + return None + j, i = point.astype(int) + # Clip the coordinates at array bounds + if not (0 <= i < arr.shape[0]) or not (0 <= j < arr.shape[1]): + return None + else: + return arr[i, j] + + +class NonUniformImage(AxesImage): + + def __init__(self, ax, *, interpolation='nearest', **kwargs): + """ + Parameters + ---------- + ax : `~matplotlib.axes.Axes` + The Axes the image will belong to. + interpolation : {'nearest', 'bilinear'}, default: 'nearest' + The interpolation scheme used in the resampling. + **kwargs + All other keyword arguments are identical to those of `.AxesImage`. + """ + super().__init__(ax, **kwargs) + self.set_interpolation(interpolation) + + def _check_unsampled_image(self): + """Return False. Do not use unsampled image.""" + return False + + def make_image(self, renderer, magnification=1.0, unsampled=False): + # docstring inherited + if self._A is None: + raise RuntimeError('You must first set the image array') + if unsampled: + raise ValueError('unsampled not supported on NonUniformImage') + A = self._A + if A.ndim == 2: + if A.dtype != np.uint8: + A = self.to_rgba(A, bytes=True) + else: + A = np.repeat(A[:, :, np.newaxis], 4, 2) + A[:, :, 3] = 255 + else: + if A.dtype != np.uint8: + A = (255*A).astype(np.uint8) + if A.shape[2] == 3: + B = np.zeros(tuple([*A.shape[0:2], 4]), np.uint8) + B[:, :, 0:3] = A + B[:, :, 3] = 255 + A = B + l, b, r, t = self.axes.bbox.extents + width = int(((round(r) + 0.5) - (round(l) - 0.5)) * magnification) + height = int(((round(t) + 0.5) - (round(b) - 0.5)) * magnification) + + invertedTransform = self.axes.transData.inverted() + x_pix = invertedTransform.transform( + [(x, b) for x in np.linspace(l, r, width)])[:, 0] + y_pix = invertedTransform.transform( + [(l, y) for y in np.linspace(b, t, height)])[:, 1] + + if self._interpolation == "nearest": + x_mid = (self._Ax[:-1] + self._Ax[1:]) / 2 + y_mid = (self._Ay[:-1] + self._Ay[1:]) / 2 + x_int = x_mid.searchsorted(x_pix) + y_int = y_mid.searchsorted(y_pix) + # The following is equal to `A[y_int[:, None], x_int[None, :]]`, + # but many times faster. Both casting to uint32 (to have an + # effectively 1D array) and manual index flattening matter. + im = ( + np.ascontiguousarray(A).view(np.uint32).ravel()[ + np.add.outer(y_int * A.shape[1], x_int)] + .view(np.uint8).reshape((height, width, 4))) + else: # self._interpolation == "bilinear" + # Use np.interp to compute x_int/x_float has similar speed. + x_int = np.clip( + self._Ax.searchsorted(x_pix) - 1, 0, len(self._Ax) - 2) + y_int = np.clip( + self._Ay.searchsorted(y_pix) - 1, 0, len(self._Ay) - 2) + idx_int = np.add.outer(y_int * A.shape[1], x_int) + x_frac = np.clip( + np.divide(x_pix - self._Ax[x_int], np.diff(self._Ax)[x_int], + dtype=np.float32), # Downcasting helps with speed. + 0, 1) + y_frac = np.clip( + np.divide(y_pix - self._Ay[y_int], np.diff(self._Ay)[y_int], + dtype=np.float32), + 0, 1) + f00 = np.outer(1 - y_frac, 1 - x_frac) + f10 = np.outer(y_frac, 1 - x_frac) + f01 = np.outer(1 - y_frac, x_frac) + f11 = np.outer(y_frac, x_frac) + im = np.empty((height, width, 4), np.uint8) + for chan in range(4): + ac = A[:, :, chan].reshape(-1) # reshape(-1) avoids a copy. + # Shifting the buffer start (`ac[offset:]`) avoids an array + # addition (`ac[idx_int + offset]`). + buf = f00 * ac[idx_int] + buf += f10 * ac[A.shape[1]:][idx_int] + buf += f01 * ac[1:][idx_int] + buf += f11 * ac[A.shape[1] + 1:][idx_int] + im[:, :, chan] = buf # Implicitly casts to uint8. + return im, l, b, IdentityTransform() + + def set_data(self, x, y, A): + """ + Set the grid for the pixel centers, and the pixel values. + + Parameters + ---------- + x, y : 1D array-like + Monotonic arrays of shapes (N,) and (M,), respectively, specifying + pixel centers. + A : array-like + (M, N) `~numpy.ndarray` or masked array of values to be + colormapped, or (M, N, 3) RGB array, or (M, N, 4) RGBA array. + """ + A = self._normalize_image_array(A) + x = np.array(x, np.float32) + y = np.array(y, np.float32) + if not (x.ndim == y.ndim == 1 and A.shape[:2] == y.shape + x.shape): + raise TypeError("Axes don't match array shape") + self._A = A + self._Ax = x + self._Ay = y + self._imcache = None + self.stale = True + + def set_array(self, *args): + raise NotImplementedError('Method not supported') + + def set_interpolation(self, s): + """ + Parameters + ---------- + s : {'nearest', 'bilinear'} or None + If None, use :rc:`image.interpolation`. + """ + if s is not None and s not in ('nearest', 'bilinear'): + raise NotImplementedError('Only nearest neighbor and ' + 'bilinear interpolations are supported') + super().set_interpolation(s) + + def get_extent(self): + if self._A is None: + raise RuntimeError('Must set data first') + return self._Ax[0], self._Ax[-1], self._Ay[0], self._Ay[-1] + + def set_filternorm(self, filternorm): + pass + + def set_filterrad(self, filterrad): + pass + + def set_norm(self, norm): + if self._A is not None: + raise RuntimeError('Cannot change colors after loading data') + super().set_norm(norm) + + def set_cmap(self, cmap): + if self._A is not None: + raise RuntimeError('Cannot change colors after loading data') + super().set_cmap(cmap) + + def get_cursor_data(self, event): + # docstring inherited + x, y = event.xdata, event.ydata + if (x < self._Ax[0] or x > self._Ax[-1] or + y < self._Ay[0] or y > self._Ay[-1]): + return None + j = np.searchsorted(self._Ax, x) - 1 + i = np.searchsorted(self._Ay, y) - 1 + return self._A[i, j] + + +class PcolorImage(AxesImage): + """ + Make a pcolor-style plot with an irregular rectangular grid. + + This uses a variation of the original irregular image code, + and it is used by pcolorfast for the corresponding grid type. + """ + + def __init__(self, ax, + x=None, + y=None, + A=None, + *, + cmap=None, + norm=None, + colorizer=None, + **kwargs + ): + """ + Parameters + ---------- + ax : `~matplotlib.axes.Axes` + The Axes the image will belong to. + x, y : 1D array-like, optional + Monotonic arrays of length N+1 and M+1, respectively, specifying + rectangle boundaries. If not given, will default to + ``range(N + 1)`` and ``range(M + 1)``, respectively. + A : array-like + The data to be color-coded. The interpretation depends on the + shape: + + - (M, N) `~numpy.ndarray` or masked array: values to be colormapped + - (M, N, 3): RGB array + - (M, N, 4): RGBA array + + cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap` + The Colormap instance or registered colormap name used to map + scalar data to colors. + norm : str or `~matplotlib.colors.Normalize` + Maps luminance to 0-1. + **kwargs : `~matplotlib.artist.Artist` properties + """ + super().__init__(ax, norm=norm, cmap=cmap, colorizer=colorizer) + self._internal_update(kwargs) + if A is not None: + self.set_data(x, y, A) + + def make_image(self, renderer, magnification=1.0, unsampled=False): + # docstring inherited + if self._A is None: + raise RuntimeError('You must first set the image array') + if unsampled: + raise ValueError('unsampled not supported on PColorImage') + + if self._imcache is None: + A = self.to_rgba(self._A, bytes=True) + self._imcache = np.pad(A, [(1, 1), (1, 1), (0, 0)], "constant") + padded_A = self._imcache + bg = mcolors.to_rgba(self.axes.patch.get_facecolor(), 0) + bg = (np.array(bg) * 255).astype(np.uint8) + if (padded_A[0, 0] != bg).all(): + padded_A[[0, -1], :] = padded_A[:, [0, -1]] = bg + + l, b, r, t = self.axes.bbox.extents + width = (round(r) + 0.5) - (round(l) - 0.5) + height = (round(t) + 0.5) - (round(b) - 0.5) + width = round(width * magnification) + height = round(height * magnification) + vl = self.axes.viewLim + + x_pix = np.linspace(vl.x0, vl.x1, width) + y_pix = np.linspace(vl.y0, vl.y1, height) + x_int = self._Ax.searchsorted(x_pix) + y_int = self._Ay.searchsorted(y_pix) + im = ( # See comment in NonUniformImage.make_image re: performance. + padded_A.view(np.uint32).ravel()[ + np.add.outer(y_int * padded_A.shape[1], x_int)] + .view(np.uint8).reshape((height, width, 4))) + return im, l, b, IdentityTransform() + + def _check_unsampled_image(self): + return False + + def set_data(self, x, y, A): + """ + Set the grid for the rectangle boundaries, and the data values. + + Parameters + ---------- + x, y : 1D array-like, optional + Monotonic arrays of length N+1 and M+1, respectively, specifying + rectangle boundaries. If not given, will default to + ``range(N + 1)`` and ``range(M + 1)``, respectively. + A : array-like + The data to be color-coded. The interpretation depends on the + shape: + + - (M, N) `~numpy.ndarray` or masked array: values to be colormapped + - (M, N, 3): RGB array + - (M, N, 4): RGBA array + """ + A = self._normalize_image_array(A) + x = np.arange(0., A.shape[1] + 1) if x is None else np.array(x, float).ravel() + y = np.arange(0., A.shape[0] + 1) if y is None else np.array(y, float).ravel() + if A.shape[:2] != (y.size - 1, x.size - 1): + raise ValueError( + "Axes don't match array shape. Got %s, expected %s." % + (A.shape[:2], (y.size - 1, x.size - 1))) + # For efficient cursor readout, ensure x and y are increasing. + if x[-1] < x[0]: + x = x[::-1] + A = A[:, ::-1] + if y[-1] < y[0]: + y = y[::-1] + A = A[::-1] + self._A = A + self._Ax = x + self._Ay = y + self._imcache = None + self.stale = True + + def set_array(self, *args): + raise NotImplementedError('Method not supported') + + def get_cursor_data(self, event): + # docstring inherited + x, y = event.xdata, event.ydata + if (x < self._Ax[0] or x > self._Ax[-1] or + y < self._Ay[0] or y > self._Ay[-1]): + return None + j = np.searchsorted(self._Ax, x) - 1 + i = np.searchsorted(self._Ay, y) - 1 + return self._A[i, j] + + +class FigureImage(_ImageBase): + """An image attached to a figure.""" + + zorder = 0 + + _interpolation = 'nearest' + + def __init__(self, fig, + *, + cmap=None, + norm=None, + colorizer=None, + offsetx=0, + offsety=0, + origin=None, + **kwargs + ): + """ + cmap is a colors.Colormap instance + norm is a colors.Normalize instance to map luminance to 0-1 + + kwargs are an optional list of Artist keyword args + """ + super().__init__( + None, + norm=norm, + cmap=cmap, + colorizer=colorizer, + origin=origin + ) + self.set_figure(fig) + self.ox = offsetx + self.oy = offsety + self._internal_update(kwargs) + self.magnification = 1.0 + + def get_extent(self): + """Return the image extent as tuple (left, right, bottom, top).""" + numrows, numcols = self.get_size() + return (-0.5 + self.ox, numcols-0.5 + self.ox, + -0.5 + self.oy, numrows-0.5 + self.oy) + + def make_image(self, renderer, magnification=1.0, unsampled=False): + # docstring inherited + fig = self.get_figure(root=True) + fac = renderer.dpi/fig.dpi + # fac here is to account for pdf, eps, svg backends where + # figure.dpi is set to 72. This means we need to scale the + # image (using magnification) and offset it appropriately. + bbox = Bbox([[self.ox/fac, self.oy/fac], + [(self.ox/fac + self._A.shape[1]), + (self.oy/fac + self._A.shape[0])]]) + width, height = fig.get_size_inches() + width *= renderer.dpi + height *= renderer.dpi + clip = Bbox([[0, 0], [width, height]]) + return self._make_image( + self._A, bbox, bbox, clip, magnification=magnification / fac, + unsampled=unsampled, round_to_pixel_border=False) + + def set_data(self, A): + """Set the image array.""" + super().set_data(A) + self.stale = True + + +class BboxImage(_ImageBase): + """The Image class whose size is determined by the given bbox.""" + + def __init__(self, bbox, + *, + cmap=None, + norm=None, + colorizer=None, + interpolation=None, + origin=None, + filternorm=True, + filterrad=4.0, + resample=False, + **kwargs + ): + """ + cmap is a colors.Colormap instance + norm is a colors.Normalize instance to map luminance to 0-1 + + kwargs are an optional list of Artist keyword args + """ + super().__init__( + None, + cmap=cmap, + norm=norm, + colorizer=colorizer, + interpolation=interpolation, + origin=origin, + filternorm=filternorm, + filterrad=filterrad, + resample=resample, + **kwargs + ) + self.bbox = bbox + + def get_window_extent(self, renderer=None): + if renderer is None: + renderer = self.get_figure()._get_renderer() + + if isinstance(self.bbox, BboxBase): + return self.bbox + elif callable(self.bbox): + return self.bbox(renderer) + else: + raise ValueError("Unknown type of bbox") + + def contains(self, mouseevent): + """Test whether the mouse event occurred within the image.""" + if self._different_canvas(mouseevent) or not self.get_visible(): + return False, {} + x, y = mouseevent.x, mouseevent.y + inside = self.get_window_extent().contains(x, y) + return inside, {} + + def make_image(self, renderer, magnification=1.0, unsampled=False): + # docstring inherited + width, height = renderer.get_canvas_width_height() + bbox_in = self.get_window_extent(renderer).frozen() + bbox_in._points /= [width, height] + bbox_out = self.get_window_extent(renderer) + clip = Bbox([[0, 0], [width, height]]) + self._transform = BboxTransformTo(clip) + return self._make_image( + self._A, + bbox_in, bbox_out, clip, magnification, unsampled=unsampled) + + +def imread(fname, format=None): + """ + Read an image from a file into an array. + + .. note:: + + This function exists for historical reasons. It is recommended to + use `PIL.Image.open` instead for loading images. + + Parameters + ---------- + fname : str or file-like + The image file to read: a filename, a URL or a file-like object opened + in read-binary mode. + + Passing a URL is deprecated. Please open the URL + for reading and pass the result to Pillow, e.g. with + ``np.array(PIL.Image.open(urllib.request.urlopen(url)))``. + format : str, optional + The image file format assumed for reading the data. The image is + loaded as a PNG file if *format* is set to "png", if *fname* is a path + or opened file with a ".png" extension, or if it is a URL. In all + other cases, *format* is ignored and the format is auto-detected by + `PIL.Image.open`. + + Returns + ------- + `numpy.array` + The image data. The returned array has shape + + - (M, N) for grayscale images. + - (M, N, 3) for RGB images. + - (M, N, 4) for RGBA images. + + PNG images are returned as float arrays (0-1). All other formats are + returned as int arrays, with a bit depth determined by the file's + contents. + """ + # hide imports to speed initial import on systems with slow linkers + from urllib import parse + + if format is None: + if isinstance(fname, str): + parsed = parse.urlparse(fname) + # If the string is a URL (Windows paths appear as if they have a + # length-1 scheme), assume png. + if len(parsed.scheme) > 1: + ext = 'png' + else: + ext = Path(fname).suffix.lower()[1:] + elif hasattr(fname, 'geturl'): # Returned by urlopen(). + # We could try to parse the url's path and use the extension, but + # returning png is consistent with the block above. Note that this + # if clause has to come before checking for fname.name as + # urlopen("file:///...") also has a name attribute (with the fixed + # value ""). + ext = 'png' + elif hasattr(fname, 'name'): + ext = Path(fname.name).suffix.lower()[1:] + else: + ext = 'png' + else: + ext = format + img_open = ( + PIL.PngImagePlugin.PngImageFile if ext == 'png' else PIL.Image.open) + if isinstance(fname, str) and len(parse.urlparse(fname).scheme) > 1: + # Pillow doesn't handle URLs directly. + raise ValueError( + "Please open the URL for reading and pass the " + "result to Pillow, e.g. with " + "``np.array(PIL.Image.open(urllib.request.urlopen(url)))``." + ) + with img_open(fname) as image: + return (_pil_png_to_float_array(image) + if isinstance(image, PIL.PngImagePlugin.PngImageFile) else + pil_to_array(image)) + + +def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, + origin=None, dpi=100, *, metadata=None, pil_kwargs=None): + """ + Colormap and save an array as an image file. + + RGB(A) images are passed through. Single channel images will be + colormapped according to *cmap* and *norm*. + + .. note:: + + If you want to save a single channel image as gray scale please use an + image I/O library (such as pillow, tifffile, or imageio) directly. + + Parameters + ---------- + fname : str or path-like or file-like + A path or a file-like object to store the image in. + If *format* is not set, then the output format is inferred from the + extension of *fname*, if any, and from :rc:`savefig.format` otherwise. + If *format* is set, it determines the output format. + arr : array-like + The image data. The shape can be one of + MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA). + vmin, vmax : float, optional + *vmin* and *vmax* set the color scaling for the image by fixing the + values that map to the colormap color limits. If either *vmin* + or *vmax* is None, that limit is determined from the *arr* + min/max value. + cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap` + A Colormap instance or registered colormap name. The colormap + maps scalar data to colors. It is ignored for RGB(A) data. + format : str, optional + The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this + is unset is documented under *fname*. + origin : {'upper', 'lower'}, default: :rc:`image.origin` + Indicates whether the ``(0, 0)`` index of the array is in the upper + left or lower left corner of the Axes. + dpi : float + The DPI to store in the metadata of the file. This does not affect the + resolution of the output image. Depending on file format, this may be + rounded to the nearest integer. + metadata : dict, optional + Metadata in the image file. The supported keys depend on the output + format, see the documentation of the respective backends for more + information. + Currently only supported for "png", "pdf", "ps", "eps", and "svg". + pil_kwargs : dict, optional + Keyword arguments passed to `PIL.Image.Image.save`. If the 'pnginfo' + key is present, it completely overrides *metadata*, including the + default 'Software' key. + """ + from matplotlib.figure import Figure + if isinstance(fname, os.PathLike): + fname = os.fspath(fname) + if format is None: + format = (Path(fname).suffix[1:] if isinstance(fname, str) + else mpl.rcParams["savefig.format"]).lower() + if format in ["pdf", "ps", "eps", "svg"]: + # Vector formats that are not handled by PIL. + if pil_kwargs is not None: + raise ValueError( + f"Cannot use 'pil_kwargs' when saving to {format}") + fig = Figure(dpi=dpi, frameon=False) + fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin, + resize=True) + fig.savefig(fname, dpi=dpi, format=format, transparent=True, + metadata=metadata) + else: + # Don't bother creating an image; this avoids rounding errors on the + # size when dividing and then multiplying by dpi. + if origin is None: + origin = mpl.rcParams["image.origin"] + else: + _api.check_in_list(('upper', 'lower'), origin=origin) + if origin == "lower": + arr = arr[::-1] + if (isinstance(arr, memoryview) and arr.format == "B" + and arr.ndim == 3 and arr.shape[-1] == 4): + # Such an ``arr`` would also be handled fine by sm.to_rgba below + # (after casting with asarray), but it is useful to special-case it + # because that's what backend_agg passes, and can be in fact used + # as is, saving a few operations. + rgba = arr + else: + sm = mcolorizer.Colorizer(cmap=cmap) + sm.set_clim(vmin, vmax) + rgba = sm.to_rgba(arr, bytes=True) + if pil_kwargs is None: + pil_kwargs = {} + else: + # we modify this below, so make a copy (don't modify caller's dict) + pil_kwargs = pil_kwargs.copy() + pil_shape = (rgba.shape[1], rgba.shape[0]) + rgba = np.require(rgba, requirements='C') + image = PIL.Image.frombuffer( + "RGBA", pil_shape, rgba, "raw", "RGBA", 0, 1) + if format == "png": + # Only use the metadata kwarg if pnginfo is not set, because the + # semantics of duplicate keys in pnginfo is unclear. + if "pnginfo" in pil_kwargs: + if metadata: + _api.warn_external("'metadata' is overridden by the " + "'pnginfo' entry in 'pil_kwargs'.") + else: + metadata = { + "Software": (f"Matplotlib version{mpl.__version__}, " + f"https://matplotlib.org/"), + **(metadata if metadata is not None else {}), + } + pil_kwargs["pnginfo"] = pnginfo = PIL.PngImagePlugin.PngInfo() + for k, v in metadata.items(): + if v is not None: + pnginfo.add_text(k, v) + elif metadata is not None: + raise ValueError(f"metadata not supported for format {format!r}") + if format in ["jpg", "jpeg"]: + format = "jpeg" # Pillow doesn't recognize "jpg". + facecolor = mpl.rcParams["savefig.facecolor"] + if cbook._str_equal(facecolor, "auto"): + facecolor = mpl.rcParams["figure.facecolor"] + color = tuple(int(x * 255) for x in mcolors.to_rgb(facecolor)) + background = PIL.Image.new("RGB", pil_shape, color) + background.paste(image, image) + image = background + pil_kwargs.setdefault("format", format) + pil_kwargs.setdefault("dpi", (dpi, dpi)) + image.save(fname, **pil_kwargs) + + +def pil_to_array(pilImage): + """ + Load a `PIL image`_ and return it as a numpy int array. + + .. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html + + Returns + ------- + numpy.array + + The array shape depends on the image type: + + - (M, N) for grayscale images. + - (M, N, 3) for RGB images. + - (M, N, 4) for RGBA images. + """ + if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']: + # return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array + return np.asarray(pilImage) + elif pilImage.mode.startswith('I;16'): + # return MxN luminance array of uint16 + raw = pilImage.tobytes('raw', pilImage.mode) + if pilImage.mode.endswith('B'): + x = np.frombuffer(raw, '>u2') + else: + x = np.frombuffer(raw, ' None: ... + def set_alpha(self, alpha: float | None) -> None: ... + def set_edgecolor(self, color: ColorType | None) -> None: ... + def set_color(self, c: ColorType | None) -> None: ... + def set_linewidth(self, w: float | None) -> None: ... + def set_linestyle(self, ls: LineStyleType | None) -> None: ... + @property + def rectangle(self) -> Rectangle: ... + @property + def connectors(self) -> tuple[ConnectionPatch, ConnectionPatch, ConnectionPatch, ConnectionPatch] | None: ... + def draw(self, renderer: RendererBase) -> None: ... diff --git a/moondream/lib/python3.10/site-packages/matplotlib/lines.pyi b/moondream/lib/python3.10/site-packages/matplotlib/lines.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7989a03dae3a0680f63511a0d5347517753a2d1e --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/lines.pyi @@ -0,0 +1,153 @@ +from .artist import Artist +from .axes import Axes +from .backend_bases import MouseEvent, FigureCanvasBase +from .path import Path +from .transforms import Bbox + +from collections.abc import Callable, Sequence +from typing import Any, Literal, overload +from .typing import ( + ColorType, + DrawStyleType, + FillStyleType, + LineStyleType, + CapStyleType, + JoinStyleType, + MarkEveryType, + MarkerType, +) +from numpy.typing import ArrayLike + +def segment_hits( + cx: ArrayLike, cy: ArrayLike, x: ArrayLike, y: ArrayLike, radius: ArrayLike +) -> ArrayLike: ... + +class Line2D(Artist): + lineStyles: dict[str, str] + drawStyles: dict[str, str] + drawStyleKeys: list[str] + markers: dict[str | int, str] + filled_markers: tuple[str, ...] + fillStyles: tuple[str, ...] + zorder: float + ind_offset: float + def __init__( + self, + xdata: ArrayLike, + ydata: ArrayLike, + *, + linewidth: float | None = ..., + linestyle: LineStyleType | None = ..., + color: ColorType | None = ..., + gapcolor: ColorType | None = ..., + marker: MarkerType | None = ..., + markersize: float | None = ..., + markeredgewidth: float | None = ..., + markeredgecolor: ColorType | None = ..., + markerfacecolor: ColorType | None = ..., + markerfacecoloralt: ColorType = ..., + fillstyle: FillStyleType | None = ..., + antialiased: bool | None = ..., + dash_capstyle: CapStyleType | None = ..., + solid_capstyle: CapStyleType | None = ..., + dash_joinstyle: JoinStyleType | None = ..., + solid_joinstyle: JoinStyleType | None = ..., + pickradius: float = ..., + drawstyle: DrawStyleType | None = ..., + markevery: MarkEveryType | None = ..., + **kwargs + ) -> None: ... + def contains(self, mouseevent: MouseEvent) -> tuple[bool, dict]: ... + def get_pickradius(self) -> float: ... + def set_pickradius(self, pickradius: float) -> None: ... + pickradius: float + def get_fillstyle(self) -> FillStyleType: ... + stale: bool + def set_fillstyle(self, fs: FillStyleType) -> None: ... + def set_markevery(self, every: MarkEveryType) -> None: ... + def get_markevery(self) -> MarkEveryType: ... + def set_picker( + self, p: None | bool | float | Callable[[Artist, MouseEvent], tuple[bool, dict]] + ) -> None: ... + def get_bbox(self) -> Bbox: ... + @overload + def set_data(self, args: ArrayLike) -> None: ... + @overload + def set_data(self, x: ArrayLike, y: ArrayLike) -> None: ... + def recache_always(self) -> None: ... + def recache(self, always: bool = ...) -> None: ... + def get_antialiased(self) -> bool: ... + def get_color(self) -> ColorType: ... + def get_drawstyle(self) -> DrawStyleType: ... + def get_gapcolor(self) -> ColorType: ... + def get_linestyle(self) -> LineStyleType: ... + def get_linewidth(self) -> float: ... + def get_marker(self) -> MarkerType: ... + def get_markeredgecolor(self) -> ColorType: ... + def get_markeredgewidth(self) -> float: ... + def get_markerfacecolor(self) -> ColorType: ... + def get_markerfacecoloralt(self) -> ColorType: ... + def get_markersize(self) -> float: ... + def get_data(self, orig: bool = ...) -> tuple[ArrayLike, ArrayLike]: ... + def get_xdata(self, orig: bool = ...) -> ArrayLike: ... + def get_ydata(self, orig: bool = ...) -> ArrayLike: ... + def get_path(self) -> Path: ... + def get_xydata(self) -> ArrayLike: ... + def set_antialiased(self, b: bool) -> None: ... + def set_color(self, color: ColorType) -> None: ... + def set_drawstyle(self, drawstyle: DrawStyleType | None) -> None: ... + def set_gapcolor(self, gapcolor: ColorType | None) -> None: ... + def set_linewidth(self, w: float) -> None: ... + def set_linestyle(self, ls: LineStyleType) -> None: ... + def set_marker(self, marker: MarkerType) -> None: ... + def set_markeredgecolor(self, ec: ColorType | None) -> None: ... + def set_markerfacecolor(self, fc: ColorType | None) -> None: ... + def set_markerfacecoloralt(self, fc: ColorType | None) -> None: ... + def set_markeredgewidth(self, ew: float | None) -> None: ... + def set_markersize(self, sz: float) -> None: ... + def set_xdata(self, x: ArrayLike) -> None: ... + def set_ydata(self, y: ArrayLike) -> None: ... + def set_dashes(self, seq: Sequence[float] | tuple[None, None]) -> None: ... + def update_from(self, other: Artist) -> None: ... + def set_dash_joinstyle(self, s: JoinStyleType) -> None: ... + def set_solid_joinstyle(self, s: JoinStyleType) -> None: ... + def get_dash_joinstyle(self) -> Literal["miter", "round", "bevel"]: ... + def get_solid_joinstyle(self) -> Literal["miter", "round", "bevel"]: ... + def set_dash_capstyle(self, s: CapStyleType) -> None: ... + def set_solid_capstyle(self, s: CapStyleType) -> None: ... + def get_dash_capstyle(self) -> Literal["butt", "projecting", "round"]: ... + def get_solid_capstyle(self) -> Literal["butt", "projecting", "round"]: ... + def is_dashed(self) -> bool: ... + +class AxLine(Line2D): + def __init__( + self, + xy1: tuple[float, float], + xy2: tuple[float, float] | None, + slope: float | None, + **kwargs + ) -> None: ... + def get_xy1(self) -> tuple[float, float] | None: ... + def get_xy2(self) -> tuple[float, float] | None: ... + def get_slope(self) -> float: ... + def set_xy1(self, xy1: tuple[float, float]) -> None: ... + def set_xy2(self, xy2: tuple[float, float]) -> None: ... + def set_slope(self, slope: float) -> None: ... + +class VertexSelector: + axes: Axes + line: Line2D + cid: int + ind: set[int] + def __init__(self, line: Line2D) -> None: ... + @property + def canvas(self) -> FigureCanvasBase: ... + def process_selected( + self, ind: Sequence[int], xs: ArrayLike, ys: ArrayLike + ) -> None: ... + def onpick(self, event: Any) -> None: ... + +lineStyles: dict[str, str] +lineMarkers: dict[str | int, str] +drawStyles: dict[str, str] +fillStyles: tuple[FillStyleType, ...] diff --git a/moondream/lib/python3.10/site-packages/matplotlib/pylab.py b/moondream/lib/python3.10/site-packages/matplotlib/pylab.py new file mode 100644 index 0000000000000000000000000000000000000000..a50779cf6d264408f1f99a086a25cb5c9d525588 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/pylab.py @@ -0,0 +1,67 @@ +""" +`pylab` is a historic interface and its use is strongly discouraged. The equivalent +replacement is `matplotlib.pyplot`. See :ref:`api_interfaces` for a full overview +of Matplotlib interfaces. + +`pylab` was designed to support a MATLAB-like way of working with all plotting related +functions directly available in the global namespace. This was achieved through a +wildcard import (``from pylab import *``). + +.. warning:: + The use of `pylab` is discouraged for the following reasons: + + ``from pylab import *`` imports all the functions from `matplotlib.pyplot`, `numpy`, + `numpy.fft`, `numpy.linalg`, and `numpy.random`, and some additional functions into + the global namespace. + + Such a pattern is considered bad practice in modern python, as it clutters the global + namespace. Even more severely, in the case of `pylab`, this will overwrite some + builtin functions (e.g. the builtin `sum` will be replaced by `numpy.sum`), which + can lead to unexpected behavior. + +""" + +from matplotlib.cbook import flatten, silent_list + +import matplotlib as mpl + +from matplotlib.dates import ( + date2num, num2date, datestr2num, drange, DateFormatter, DateLocator, + RRuleLocator, YearLocator, MonthLocator, WeekdayLocator, DayLocator, + HourLocator, MinuteLocator, SecondLocator, rrule, MO, TU, WE, TH, FR, + SA, SU, YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY, + relativedelta) + +# bring all the symbols in so folks can import them from +# pylab in one fell swoop + +## We are still importing too many things from mlab; more cleanup is needed. + +from matplotlib.mlab import ( + detrend, detrend_linear, detrend_mean, detrend_none, window_hanning, + window_none) + +from matplotlib import cbook, mlab, pyplot as plt +from matplotlib.pyplot import * + +from numpy import * +from numpy.fft import * +from numpy.random import * +from numpy.linalg import * + +import numpy as np +import numpy.ma as ma + +# don't let numpy's datetime hide stdlib +import datetime + +# This is needed, or bytes will be numpy.random.bytes from +# "from numpy.random import *" above +bytes = __import__("builtins").bytes +# We also don't want the numpy version of these functions +abs = __import__("builtins").abs +bool = __import__("builtins").bool +max = __import__("builtins").max +min = __import__("builtins").min +pow = __import__("builtins").pow +round = __import__("builtins").round diff --git a/moondream/lib/python3.10/site-packages/matplotlib/quiver.py b/moondream/lib/python3.10/site-packages/matplotlib/quiver.py new file mode 100644 index 0000000000000000000000000000000000000000..e66f1f97b21f65ac3cdeaadd4ff6ef4b74ddaed8 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/quiver.py @@ -0,0 +1,1228 @@ +""" +Support for plotting vector fields. + +Presently this contains Quiver and Barb. Quiver plots an arrow in the +direction of the vector, with the size of the arrow related to the +magnitude of the vector. + +Barbs are like quiver in that they point along a vector, but +the magnitude of the vector is given schematically by the presence of barbs +or flags on the barb. + +This will also become a home for things such as standard +deviation ellipses, which can and will be derived very easily from +the Quiver code. +""" + +import math + +import numpy as np +from numpy import ma + +from matplotlib import _api, cbook, _docstring +import matplotlib.artist as martist +import matplotlib.collections as mcollections +from matplotlib.patches import CirclePolygon +import matplotlib.text as mtext +import matplotlib.transforms as transforms + + +_quiver_doc = """ +Plot a 2D field of arrows. + +Call signature:: + + quiver([X, Y], U, V, [C], /, **kwargs) + +*X*, *Y* define the arrow locations, *U*, *V* define the arrow directions, and +*C* optionally sets the color. The arguments *X*, *Y*, *U*, *V*, *C* are +positional-only. + +**Arrow length** + +The default settings auto-scales the length of the arrows to a reasonable size. +To change this behavior see the *scale* and *scale_units* parameters. + +**Arrow shape** + +The arrow shape is determined by *width*, *headwidth*, *headlength* and +*headaxislength*. See the notes below. + +**Arrow styling** + +Each arrow is internally represented by a filled polygon with a default edge +linewidth of 0. As a result, an arrow is rather a filled area, not a line with +a head, and `.PolyCollection` properties like *linewidth*, *edgecolor*, +*facecolor*, etc. act accordingly. + + +Parameters +---------- +X, Y : 1D or 2D array-like, optional + The x and y coordinates of the arrow locations. + + If not given, they will be generated as a uniform integer meshgrid based + on the dimensions of *U* and *V*. + + If *X* and *Y* are 1D but *U*, *V* are 2D, *X*, *Y* are expanded to 2D + using ``X, Y = np.meshgrid(X, Y)``. In this case ``len(X)`` and ``len(Y)`` + must match the column and row dimensions of *U* and *V*. + +U, V : 1D or 2D array-like + The x and y direction components of the arrow vectors. The interpretation + of these components (in data or in screen space) depends on *angles*. + + *U* and *V* must have the same number of elements, matching the number of + arrow locations in *X*, *Y*. *U* and *V* may be masked. Locations masked + in any of *U*, *V*, and *C* will not be drawn. + +C : 1D or 2D array-like, optional + Numeric data that defines the arrow colors by colormapping via *norm* and + *cmap*. + + This does not support explicit colors. If you want to set colors directly, + use *color* instead. The size of *C* must match the number of arrow + locations. + +angles : {'uv', 'xy'} or array-like, default: 'uv' + Method for determining the angle of the arrows. + + - 'uv': Arrow directions are based on + :ref:`display coordinates `; i.e. a 45° angle will + always show up as diagonal on the screen, irrespective of figure or Axes + aspect ratio or Axes data ranges. This is useful when the arrows represent + a quantity whose direction is not tied to the x and y data coordinates. + + If *U* == *V* the orientation of the arrow on the plot is 45 degrees + counter-clockwise from the horizontal axis (positive to the right). + + - 'xy': Arrow direction in data coordinates, i.e. the arrows point from + (x, y) to (x+u, y+v). This is ideal for vector fields or gradient plots + where the arrows should directly represent movements or gradients in the + x and y directions. + + - Arbitrary angles may be specified explicitly as an array of values + in degrees, counter-clockwise from the horizontal axis. + + In this case *U*, *V* is only used to determine the length of the + arrows. + + For example, ``angles=[30, 60, 90]`` will orient the arrows at 30, 60, and 90 + degrees respectively, regardless of the *U* and *V* components. + + Note: inverting a data axis will correspondingly invert the + arrows only with ``angles='xy'``. + +pivot : {'tail', 'mid', 'middle', 'tip'}, default: 'tail' + The part of the arrow that is anchored to the *X*, *Y* grid. The arrow + rotates about this point. + + 'mid' is a synonym for 'middle'. + +scale : float, optional + Scales the length of the arrow inversely. + + Number of data values represented by one unit of arrow length on the plot. + For example, if the data represents velocity in meters per second (m/s), the + scale parameter determines how many meters per second correspond to one unit of + arrow length relative to the width of the plot. + Smaller scale parameter makes the arrow longer. + + By default, an autoscaling algorithm is used to scale the arrow length to a + reasonable size, which is based on the average vector length and the number of + vectors. + + The arrow length unit is given by the *scale_units* parameter. + +scale_units : {'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, default: 'width' + + The physical image unit, which is used for rendering the scaled arrow data *U*, *V*. + + The rendered arrow length is given by + + length in x direction = $\\frac{u}{\\mathrm{scale}} \\mathrm{scale_unit}$ + + length in y direction = $\\frac{v}{\\mathrm{scale}} \\mathrm{scale_unit}$ + + For example, ``(u, v) = (0.5, 0)`` with ``scale=10, scale_unit="width"`` results + in a horizontal arrow with a length of *0.5 / 10 * "width"*, i.e. 0.05 times the + Axes width. + + Supported values are: + + - 'width' or 'height': The arrow length is scaled relative to the width or height + of the Axes. + For example, ``scale_units='width', scale=1.0``, will result in an arrow length + of width of the Axes. + + - 'dots': The arrow length of the arrows is in measured in display dots (pixels). + + - 'inches': Arrow lengths are scaled based on the DPI (dots per inch) of the figure. + This ensures that the arrows have a consistent physical size on the figure, + in inches, regardless of data values or plot scaling. + For example, ``(u, v) = (1, 0)`` with ``scale_units='inches', scale=2`` results + in a 0.5 inch-long arrow. + + - 'x' or 'y': The arrow length is scaled relative to the x or y axis units. + For example, ``(u, v) = (0, 1)`` with ``scale_units='x', scale=1`` results + in a vertical arrow with the length of 1 x-axis unit. + + - 'xy': Arrow length will be same as 'x' or 'y' units. + This is useful for creating vectors in the x-y plane where u and v have + the same units as x and y. To plot vectors in the x-y plane with u and v having + the same units as x and y, use ``angles='xy', scale_units='xy', scale=1``. + + Note: Setting *scale_units* without setting scale does not have any effect because + the scale units only differ by a constant factor and that is rescaled through + autoscaling. + +units : {'width', 'height', 'dots', 'inches', 'x', 'y', 'xy'}, default: 'width' + Affects the arrow size (except for the length). In particular, the shaft + *width* is measured in multiples of this unit. + + Supported values are: + + - 'width', 'height': The width or height of the Axes. + - 'dots', 'inches': Pixels or inches based on the figure dpi. + - 'x', 'y', 'xy': *X*, *Y* or :math:`\\sqrt{X^2 + Y^2}` in data units. + + The following table summarizes how these values affect the visible arrow + size under zooming and figure size changes: + + ================= ================= ================== + units zoom figure size change + ================= ================= ================== + 'x', 'y', 'xy' arrow size scales — + 'width', 'height' — arrow size scales + 'dots', 'inches' — — + ================= ================= ================== + +width : float, optional + Shaft width in arrow units. All head parameters are relative to *width*. + + The default depends on choice of *units* above, and number of vectors; + a typical starting value is about 0.005 times the width of the plot. + +headwidth : float, default: 3 + Head width as multiple of shaft *width*. See the notes below. + +headlength : float, default: 5 + Head length as multiple of shaft *width*. See the notes below. + +headaxislength : float, default: 4.5 + Head length at shaft intersection as multiple of shaft *width*. + See the notes below. + +minshaft : float, default: 1 + Length below which arrow scales, in units of head length. Do not + set this to less than 1, or small arrows will look terrible! + +minlength : float, default: 1 + Minimum length as a multiple of shaft width; if an arrow length + is less than this, plot a dot (hexagon) of this diameter instead. + +color : :mpltype:`color` or list :mpltype:`color`, optional + Explicit color(s) for the arrows. If *C* has been set, *color* has no + effect. + + This is a synonym for the `.PolyCollection` *facecolor* parameter. + +Other Parameters +---------------- +data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + +**kwargs : `~matplotlib.collections.PolyCollection` properties, optional + All other keyword arguments are passed on to `.PolyCollection`: + + %(PolyCollection:kwdoc)s + +Returns +------- +`~matplotlib.quiver.Quiver` + +See Also +-------- +.Axes.quiverkey : Add a key to a quiver plot. + +Notes +----- + +**Arrow shape** + +The arrow is drawn as a polygon using the nodes as shown below. The values +*headwidth*, *headlength*, and *headaxislength* are in units of *width*. + +.. image:: /_static/quiver_sizes.svg + :width: 500px + +The defaults give a slightly swept-back arrow. Here are some guidelines how to +get other head shapes: + +- To make the head a triangle, make *headaxislength* the same as *headlength*. +- To make the arrow more pointed, reduce *headwidth* or increase *headlength* + and *headaxislength*. +- To make the head smaller relative to the shaft, scale down all the head + parameters proportionally. +- To remove the head completely, set all *head* parameters to 0. +- To get a diamond-shaped head, make *headaxislength* larger than *headlength*. +- Warning: For *headaxislength* < (*headlength* / *headwidth*), the "headaxis" + nodes (i.e. the ones connecting the head with the shaft) will protrude out + of the head in forward direction so that the arrow head looks broken. +""" % _docstring.interpd.params + +_docstring.interpd.register(quiver_doc=_quiver_doc) + + +class QuiverKey(martist.Artist): + """Labelled arrow for use as a quiver plot scale key.""" + halign = {'N': 'center', 'S': 'center', 'E': 'left', 'W': 'right'} + valign = {'N': 'bottom', 'S': 'top', 'E': 'center', 'W': 'center'} + pivot = {'N': 'middle', 'S': 'middle', 'E': 'tip', 'W': 'tail'} + + def __init__(self, Q, X, Y, U, label, + *, angle=0, coordinates='axes', color=None, labelsep=0.1, + labelpos='N', labelcolor=None, fontproperties=None, + zorder=None, **kwargs): + """ + Add a key to a quiver plot. + + The positioning of the key depends on *X*, *Y*, *coordinates*, and + *labelpos*. If *labelpos* is 'N' or 'S', *X*, *Y* give the position of + the middle of the key arrow. If *labelpos* is 'E', *X*, *Y* positions + the head, and if *labelpos* is 'W', *X*, *Y* positions the tail; in + either of these two cases, *X*, *Y* is somewhere in the middle of the + arrow+label key object. + + Parameters + ---------- + Q : `~matplotlib.quiver.Quiver` + A `.Quiver` object as returned by a call to `~.Axes.quiver()`. + X, Y : float + The location of the key. + U : float + The length of the key. + label : str + The key label (e.g., length and units of the key). + angle : float, default: 0 + The angle of the key arrow, in degrees anti-clockwise from the + horizontal axis. + coordinates : {'axes', 'figure', 'data', 'inches'}, default: 'axes' + Coordinate system and units for *X*, *Y*: 'axes' and 'figure' are + normalized coordinate systems with (0, 0) in the lower left and + (1, 1) in the upper right; 'data' are the axes data coordinates + (used for the locations of the vectors in the quiver plot itself); + 'inches' is position in the figure in inches, with (0, 0) at the + lower left corner. + color : :mpltype:`color` + Overrides face and edge colors from *Q*. + labelpos : {'N', 'S', 'E', 'W'} + Position the label above, below, to the right, to the left of the + arrow, respectively. + labelsep : float, default: 0.1 + Distance in inches between the arrow and the label. + labelcolor : :mpltype:`color`, default: :rc:`text.color` + Label color. + fontproperties : dict, optional + A dictionary with keyword arguments accepted by the + `~matplotlib.font_manager.FontProperties` initializer: + *family*, *style*, *variant*, *size*, *weight*. + zorder : float + The zorder of the key. The default is 0.1 above *Q*. + **kwargs + Any additional keyword arguments are used to override vector + properties taken from *Q*. + """ + super().__init__() + self.Q = Q + self.X = X + self.Y = Y + self.U = U + self.angle = angle + self.coord = coordinates + self.color = color + self.label = label + self._labelsep_inches = labelsep + + self.labelpos = labelpos + self.labelcolor = labelcolor + self.fontproperties = fontproperties or dict() + self.kw = kwargs + self.text = mtext.Text( + text=label, + horizontalalignment=self.halign[self.labelpos], + verticalalignment=self.valign[self.labelpos], + fontproperties=self.fontproperties) + if self.labelcolor is not None: + self.text.set_color(self.labelcolor) + self._dpi_at_last_init = None + self.zorder = zorder if zorder is not None else Q.zorder + 0.1 + + @property + def labelsep(self): + return self._labelsep_inches * self.Q.axes.get_figure(root=True).dpi + + def _init(self): + if True: # self._dpi_at_last_init != self.axes.get_figure().dpi + if self.Q._dpi_at_last_init != self.Q.axes.get_figure(root=True).dpi: + self.Q._init() + self._set_transform() + with cbook._setattr_cm(self.Q, pivot=self.pivot[self.labelpos], + # Hack: save and restore the Umask + Umask=ma.nomask): + u = self.U * np.cos(np.radians(self.angle)) + v = self.U * np.sin(np.radians(self.angle)) + self.verts = self.Q._make_verts([[0., 0.]], + np.array([u]), np.array([v]), 'uv') + kwargs = self.Q.polykw + kwargs.update(self.kw) + self.vector = mcollections.PolyCollection( + self.verts, + offsets=[(self.X, self.Y)], + offset_transform=self.get_transform(), + **kwargs) + if self.color is not None: + self.vector.set_color(self.color) + self.vector.set_transform(self.Q.get_transform()) + self.vector.set_figure(self.get_figure()) + self._dpi_at_last_init = self.Q.axes.get_figure(root=True).dpi + + def _text_shift(self): + return { + "N": (0, +self.labelsep), + "S": (0, -self.labelsep), + "E": (+self.labelsep, 0), + "W": (-self.labelsep, 0), + }[self.labelpos] + + @martist.allow_rasterization + def draw(self, renderer): + self._init() + self.vector.draw(renderer) + pos = self.get_transform().transform((self.X, self.Y)) + self.text.set_position(pos + self._text_shift()) + self.text.draw(renderer) + self.stale = False + + def _set_transform(self): + fig = self.Q.axes.get_figure(root=False) + self.set_transform(_api.check_getitem({ + "data": self.Q.axes.transData, + "axes": self.Q.axes.transAxes, + "figure": fig.transFigure, + "inches": fig.dpi_scale_trans, + }, coordinates=self.coord)) + + def set_figure(self, fig): + super().set_figure(fig) + self.text.set_figure(fig) + + def contains(self, mouseevent): + if self._different_canvas(mouseevent): + return False, {} + # Maybe the dictionary should allow one to + # distinguish between a text hit and a vector hit. + if (self.text.contains(mouseevent)[0] or + self.vector.contains(mouseevent)[0]): + return True, {} + return False, {} + + +def _parse_args(*args, caller_name='function'): + """ + Helper function to parse positional parameters for colored vector plots. + + This is currently used for Quiver and Barbs. + + Parameters + ---------- + *args : list + list of 2-5 arguments. Depending on their number they are parsed to:: + + U, V + U, V, C + X, Y, U, V + X, Y, U, V, C + + caller_name : str + Name of the calling method (used in error messages). + """ + X = Y = C = None + + nargs = len(args) + if nargs == 2: + # The use of atleast_1d allows for handling scalar arguments while also + # keeping masked arrays + U, V = np.atleast_1d(*args) + elif nargs == 3: + U, V, C = np.atleast_1d(*args) + elif nargs == 4: + X, Y, U, V = np.atleast_1d(*args) + elif nargs == 5: + X, Y, U, V, C = np.atleast_1d(*args) + else: + raise _api.nargs_error(caller_name, takes="from 2 to 5", given=nargs) + + nr, nc = (1, U.shape[0]) if U.ndim == 1 else U.shape + + if X is not None: + X = X.ravel() + Y = Y.ravel() + if len(X) == nc and len(Y) == nr: + X, Y = (a.ravel() for a in np.meshgrid(X, Y)) + elif len(X) != len(Y): + raise ValueError('X and Y must be the same size, but ' + f'X.size is {X.size} and Y.size is {Y.size}.') + else: + indexgrid = np.meshgrid(np.arange(nc), np.arange(nr)) + X, Y = (np.ravel(a) for a in indexgrid) + # Size validation for U, V, C is left to the set_UVC method. + return X, Y, U, V, C + + +def _check_consistent_shapes(*arrays): + all_shapes = {a.shape for a in arrays} + if len(all_shapes) != 1: + raise ValueError('The shapes of the passed in arrays do not match') + + +class Quiver(mcollections.PolyCollection): + """ + Specialized PolyCollection for arrows. + + The only API method is set_UVC(), which can be used + to change the size, orientation, and color of the + arrows; their locations are fixed when the class is + instantiated. Possibly this method will be useful + in animations. + + Much of the work in this class is done in the draw() + method so that as much information as possible is available + about the plot. In subsequent draw() calls, recalculation + is limited to things that might have changed, so there + should be no performance penalty from putting the calculations + in the draw() method. + """ + + _PIVOT_VALS = ('tail', 'middle', 'tip') + + @_docstring.Substitution(_quiver_doc) + def __init__(self, ax, *args, + scale=None, headwidth=3, headlength=5, headaxislength=4.5, + minshaft=1, minlength=1, units='width', scale_units=None, + angles='uv', width=None, color='k', pivot='tail', **kwargs): + """ + The constructor takes one required argument, an Axes + instance, followed by the args and kwargs described + by the following pyplot interface documentation: + %s + """ + self._axes = ax # The attr actually set by the Artist.axes property. + X, Y, U, V, C = _parse_args(*args, caller_name='quiver') + self.X = X + self.Y = Y + self.XY = np.column_stack((X, Y)) + self.N = len(X) + self.scale = scale + self.headwidth = headwidth + self.headlength = float(headlength) + self.headaxislength = headaxislength + self.minshaft = minshaft + self.minlength = minlength + self.units = units + self.scale_units = scale_units + self.angles = angles + self.width = width + + if pivot.lower() == 'mid': + pivot = 'middle' + self.pivot = pivot.lower() + _api.check_in_list(self._PIVOT_VALS, pivot=self.pivot) + + self.transform = kwargs.pop('transform', ax.transData) + kwargs.setdefault('facecolors', color) + kwargs.setdefault('linewidths', (0,)) + super().__init__([], offsets=self.XY, offset_transform=self.transform, + closed=False, **kwargs) + self.polykw = kwargs + self.set_UVC(U, V, C) + self._dpi_at_last_init = None + + def _init(self): + """ + Initialization delayed until first draw; + allow time for axes setup. + """ + # It seems that there are not enough event notifications + # available to have this work on an as-needed basis at present. + if True: # self._dpi_at_last_init != self.axes.figure.dpi + trans = self._set_transform() + self.span = trans.inverted().transform_bbox(self.axes.bbox).width + if self.width is None: + sn = np.clip(math.sqrt(self.N), 8, 25) + self.width = 0.06 * self.span / sn + + # _make_verts sets self.scale if not already specified + if (self._dpi_at_last_init != self.axes.get_figure(root=True).dpi + and self.scale is None): + self._make_verts(self.XY, self.U, self.V, self.angles) + + self._dpi_at_last_init = self.axes.get_figure(root=True).dpi + + def get_datalim(self, transData): + trans = self.get_transform() + offset_trf = self.get_offset_transform() + full_transform = (trans - transData) + (offset_trf - transData) + XY = full_transform.transform(self.XY) + bbox = transforms.Bbox.null() + bbox.update_from_data_xy(XY, ignore=True) + return bbox + + @martist.allow_rasterization + def draw(self, renderer): + self._init() + verts = self._make_verts(self.XY, self.U, self.V, self.angles) + self.set_verts(verts, closed=False) + super().draw(renderer) + self.stale = False + + def set_UVC(self, U, V, C=None): + # We need to ensure we have a copy, not a reference + # to an array that might change before draw(). + U = ma.masked_invalid(U, copy=True).ravel() + V = ma.masked_invalid(V, copy=True).ravel() + if C is not None: + C = ma.masked_invalid(C, copy=True).ravel() + for name, var in zip(('U', 'V', 'C'), (U, V, C)): + if not (var is None or var.size == self.N or var.size == 1): + raise ValueError(f'Argument {name} has a size {var.size}' + f' which does not match {self.N},' + ' the number of arrow positions') + + mask = ma.mask_or(U.mask, V.mask, copy=False, shrink=True) + if C is not None: + mask = ma.mask_or(mask, C.mask, copy=False, shrink=True) + if mask is ma.nomask: + C = C.filled() + else: + C = ma.array(C, mask=mask, copy=False) + self.U = U.filled(1) + self.V = V.filled(1) + self.Umask = mask + if C is not None: + self.set_array(C) + self.stale = True + + def _dots_per_unit(self, units): + """Return a scale factor for converting from units to pixels.""" + bb = self.axes.bbox + vl = self.axes.viewLim + return _api.check_getitem({ + 'x': bb.width / vl.width, + 'y': bb.height / vl.height, + 'xy': np.hypot(*bb.size) / np.hypot(*vl.size), + 'width': bb.width, + 'height': bb.height, + 'dots': 1., + 'inches': self.axes.get_figure(root=True).dpi, + }, units=units) + + def _set_transform(self): + """ + Set the PolyCollection transform to go + from arrow width units to pixels. + """ + dx = self._dots_per_unit(self.units) + self._trans_scale = dx # pixels per arrow width unit + trans = transforms.Affine2D().scale(dx) + self.set_transform(trans) + return trans + + # Calculate angles and lengths for segment between (x, y), (x+u, y+v) + def _angles_lengths(self, XY, U, V, eps=1): + xy = self.axes.transData.transform(XY) + uv = np.column_stack((U, V)) + xyp = self.axes.transData.transform(XY + eps * uv) + dxy = xyp - xy + angles = np.arctan2(dxy[:, 1], dxy[:, 0]) + lengths = np.hypot(*dxy.T) / eps + return angles, lengths + + # XY is stacked [X, Y]. + # See quiver() doc for meaning of X, Y, U, V, angles. + def _make_verts(self, XY, U, V, angles): + uv = (U + V * 1j) + str_angles = angles if isinstance(angles, str) else '' + if str_angles == 'xy' and self.scale_units == 'xy': + # Here eps is 1 so that if we get U, V by diffing + # the X, Y arrays, the vectors will connect the + # points, regardless of the axis scaling (including log). + angles, lengths = self._angles_lengths(XY, U, V, eps=1) + elif str_angles == 'xy' or self.scale_units == 'xy': + # Calculate eps based on the extents of the plot + # so that we don't end up with roundoff error from + # adding a small number to a large. + eps = np.abs(self.axes.dataLim.extents).max() * 0.001 + angles, lengths = self._angles_lengths(XY, U, V, eps=eps) + + if str_angles and self.scale_units == 'xy': + a = lengths + else: + a = np.abs(uv) + + if self.scale is None: + sn = max(10, math.sqrt(self.N)) + if self.Umask is not ma.nomask: + amean = a[~self.Umask].mean() + else: + amean = a.mean() + # crude auto-scaling + # scale is typical arrow length as a multiple of the arrow width + scale = 1.8 * amean * sn / self.span + + if self.scale_units is None: + if self.scale is None: + self.scale = scale + widthu_per_lenu = 1.0 + else: + if self.scale_units == 'xy': + dx = 1 + else: + dx = self._dots_per_unit(self.scale_units) + widthu_per_lenu = dx / self._trans_scale + if self.scale is None: + self.scale = scale * widthu_per_lenu + length = a * (widthu_per_lenu / (self.scale * self.width)) + X, Y = self._h_arrows(length) + if str_angles == 'xy': + theta = angles + elif str_angles == 'uv': + theta = np.angle(uv) + else: + theta = ma.masked_invalid(np.deg2rad(angles)).filled(0) + theta = theta.reshape((-1, 1)) # for broadcasting + xy = (X + Y * 1j) * np.exp(1j * theta) * self.width + XY = np.stack((xy.real, xy.imag), axis=2) + if self.Umask is not ma.nomask: + XY = ma.array(XY) + XY[self.Umask] = ma.masked + # This might be handled more efficiently with nans, given + # that nans will end up in the paths anyway. + + return XY + + def _h_arrows(self, length): + """Length is in arrow width units.""" + # It might be possible to streamline the code + # and speed it up a bit by using complex (x, y) + # instead of separate arrays; but any gain would be slight. + minsh = self.minshaft * self.headlength + N = len(length) + length = length.reshape(N, 1) + # This number is chosen based on when pixel values overflow in Agg + # causing rendering errors + # length = np.minimum(length, 2 ** 16) + np.clip(length, 0, 2 ** 16, out=length) + # x, y: normal horizontal arrow + x = np.array([0, -self.headaxislength, + -self.headlength, 0], + np.float64) + x = x + np.array([0, 1, 1, 1]) * length + y = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64) + y = np.repeat(y[np.newaxis, :], N, axis=0) + # x0, y0: arrow without shaft, for short vectors + x0 = np.array([0, minsh - self.headaxislength, + minsh - self.headlength, minsh], np.float64) + y0 = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64) + ii = [0, 1, 2, 3, 2, 1, 0, 0] + X = x[:, ii] + Y = y[:, ii] + Y[:, 3:-1] *= -1 + X0 = x0[ii] + Y0 = y0[ii] + Y0[3:-1] *= -1 + shrink = length / minsh if minsh != 0. else 0. + X0 = shrink * X0[np.newaxis, :] + Y0 = shrink * Y0[np.newaxis, :] + short = np.repeat(length < minsh, 8, axis=1) + # Now select X0, Y0 if short, otherwise X, Y + np.copyto(X, X0, where=short) + np.copyto(Y, Y0, where=short) + if self.pivot == 'middle': + X -= 0.5 * X[:, 3, np.newaxis] + elif self.pivot == 'tip': + # numpy bug? using -= does not work here unless we multiply by a + # float first, as with 'mid'. + X = X - X[:, 3, np.newaxis] + elif self.pivot != 'tail': + _api.check_in_list(["middle", "tip", "tail"], pivot=self.pivot) + + tooshort = length < self.minlength + if tooshort.any(): + # Use a heptagonal dot: + th = np.arange(0, 8, 1, np.float64) * (np.pi / 3.0) + x1 = np.cos(th) * self.minlength * 0.5 + y1 = np.sin(th) * self.minlength * 0.5 + X1 = np.repeat(x1[np.newaxis, :], N, axis=0) + Y1 = np.repeat(y1[np.newaxis, :], N, axis=0) + tooshort = np.repeat(tooshort, 8, 1) + np.copyto(X, X1, where=tooshort) + np.copyto(Y, Y1, where=tooshort) + # Mask handling is deferred to the caller, _make_verts. + return X, Y + + +_barbs_doc = r""" +Plot a 2D field of wind barbs. + +Call signature:: + + barbs([X, Y], U, V, [C], /, **kwargs) + +Where *X*, *Y* define the barb locations, *U*, *V* define the barb +directions, and *C* optionally sets the color. + +The arguments *X*, *Y*, *U*, *V*, *C* are positional-only and may be +1D or 2D. *U*, *V*, *C* may be masked arrays, but masked *X*, *Y* +are not supported at present. + +Barbs are traditionally used in meteorology as a way to plot the speed +and direction of wind observations, but can technically be used to +plot any two dimensional vector quantity. As opposed to arrows, which +give vector magnitude by the length of the arrow, the barbs give more +quantitative information about the vector magnitude by putting slanted +lines or a triangle for various increments in magnitude, as show +schematically below:: + + : /\ \ + : / \ \ + : / \ \ \ + : / \ \ \ + : ------------------------------ + +The largest increment is given by a triangle (or "flag"). After those +come full lines (barbs). The smallest increment is a half line. There +is only, of course, ever at most 1 half line. If the magnitude is +small and only needs a single half-line and no full lines or +triangles, the half-line is offset from the end of the barb so that it +can be easily distinguished from barbs with a single full line. The +magnitude for the barb shown above would nominally be 65, using the +standard increments of 50, 10, and 5. + +See also https://en.wikipedia.org/wiki/Wind_barb. + +Parameters +---------- +X, Y : 1D or 2D array-like, optional + The x and y coordinates of the barb locations. See *pivot* for how the + barbs are drawn to the x, y positions. + + If not given, they will be generated as a uniform integer meshgrid based + on the dimensions of *U* and *V*. + + If *X* and *Y* are 1D but *U*, *V* are 2D, *X*, *Y* are expanded to 2D + using ``X, Y = np.meshgrid(X, Y)``. In this case ``len(X)`` and ``len(Y)`` + must match the column and row dimensions of *U* and *V*. + +U, V : 1D or 2D array-like + The x and y components of the barb shaft. + +C : 1D or 2D array-like, optional + Numeric data that defines the barb colors by colormapping via *norm* and + *cmap*. + + This does not support explicit colors. If you want to set colors directly, + use *barbcolor* instead. + +length : float, default: 7 + Length of the barb in points; the other parts of the barb + are scaled against this. + +pivot : {'tip', 'middle'} or float, default: 'tip' + The part of the arrow that is anchored to the *X*, *Y* grid. The barb + rotates about this point. This can also be a number, which shifts the + start of the barb that many points away from grid point. + +barbcolor : :mpltype:`color` or color sequence + The color of all parts of the barb except for the flags. This parameter + is analogous to the *edgecolor* parameter for polygons, which can be used + instead. However this parameter will override facecolor. + +flagcolor : :mpltype:`color` or color sequence + The color of any flags on the barb. This parameter is analogous to the + *facecolor* parameter for polygons, which can be used instead. However, + this parameter will override facecolor. If this is not set (and *C* has + not either) then *flagcolor* will be set to match *barbcolor* so that the + barb has a uniform color. If *C* has been set, *flagcolor* has no effect. + +sizes : dict, optional + A dictionary of coefficients specifying the ratio of a given + feature to the length of the barb. Only those values one wishes to + override need to be included. These features include: + + - 'spacing' - space between features (flags, full/half barbs) + - 'height' - height (distance from shaft to top) of a flag or full barb + - 'width' - width of a flag, twice the width of a full barb + - 'emptybarb' - radius of the circle used for low magnitudes + +fill_empty : bool, default: False + Whether the empty barbs (circles) that are drawn should be filled with + the flag color. If they are not filled, the center is transparent. + +rounding : bool, default: True + Whether the vector magnitude should be rounded when allocating barb + components. If True, the magnitude is rounded to the nearest multiple + of the half-barb increment. If False, the magnitude is simply truncated + to the next lowest multiple. + +barb_increments : dict, optional + A dictionary of increments specifying values to associate with + different parts of the barb. Only those values one wishes to + override need to be included. + + - 'half' - half barbs (Default is 5) + - 'full' - full barbs (Default is 10) + - 'flag' - flags (default is 50) + +flip_barb : bool or array-like of bool, default: False + Whether the lines and flags should point opposite to normal. + Normal behavior is for the barbs and lines to point right (comes from wind + barbs having these features point towards low pressure in the Northern + Hemisphere). + + A single value is applied to all barbs. Individual barbs can be flipped by + passing a bool array of the same size as *U* and *V*. + +Returns +------- +barbs : `~matplotlib.quiver.Barbs` + +Other Parameters +---------------- +data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + +**kwargs + The barbs can further be customized using `.PolyCollection` keyword + arguments: + + %(PolyCollection:kwdoc)s +""" % _docstring.interpd.params + +_docstring.interpd.register(barbs_doc=_barbs_doc) + + +class Barbs(mcollections.PolyCollection): + """ + Specialized PolyCollection for barbs. + + The only API method is :meth:`set_UVC`, which can be used to + change the size, orientation, and color of the arrows. Locations + are changed using the :meth:`set_offsets` collection method. + Possibly this method will be useful in animations. + + There is one internal function :meth:`_find_tails` which finds + exactly what should be put on the barb given the vector magnitude. + From there :meth:`_make_barbs` is used to find the vertices of the + polygon to represent the barb based on this information. + """ + + # This may be an abuse of polygons here to render what is essentially maybe + # 1 triangle and a series of lines. It works fine as far as I can tell + # however. + + @_docstring.interpd + def __init__(self, ax, *args, + pivot='tip', length=7, barbcolor=None, flagcolor=None, + sizes=None, fill_empty=False, barb_increments=None, + rounding=True, flip_barb=False, **kwargs): + """ + The constructor takes one required argument, an Axes + instance, followed by the args and kwargs described + by the following pyplot interface documentation: + %(barbs_doc)s + """ + self.sizes = sizes or dict() + self.fill_empty = fill_empty + self.barb_increments = barb_increments or dict() + self.rounding = rounding + self.flip = np.atleast_1d(flip_barb) + transform = kwargs.pop('transform', ax.transData) + self._pivot = pivot + self._length = length + + # Flagcolor and barbcolor provide convenience parameters for + # setting the facecolor and edgecolor, respectively, of the barb + # polygon. We also work here to make the flag the same color as the + # rest of the barb by default + + if None in (barbcolor, flagcolor): + kwargs['edgecolors'] = 'face' + if flagcolor: + kwargs['facecolors'] = flagcolor + elif barbcolor: + kwargs['facecolors'] = barbcolor + else: + # Set to facecolor passed in or default to black + kwargs.setdefault('facecolors', 'k') + else: + kwargs['edgecolors'] = barbcolor + kwargs['facecolors'] = flagcolor + + # Explicitly set a line width if we're not given one, otherwise + # polygons are not outlined and we get no barbs + if 'linewidth' not in kwargs and 'lw' not in kwargs: + kwargs['linewidth'] = 1 + + # Parse out the data arrays from the various configurations supported + x, y, u, v, c = _parse_args(*args, caller_name='barbs') + self.x = x + self.y = y + xy = np.column_stack((x, y)) + + # Make a collection + barb_size = self._length ** 2 / 4 # Empirically determined + super().__init__( + [], (barb_size,), offsets=xy, offset_transform=transform, **kwargs) + self.set_transform(transforms.IdentityTransform()) + + self.set_UVC(u, v, c) + + def _find_tails(self, mag, rounding=True, half=5, full=10, flag=50): + """ + Find how many of each of the tail pieces is necessary. + + Parameters + ---------- + mag : `~numpy.ndarray` + Vector magnitudes; must be non-negative (and an actual ndarray). + rounding : bool, default: True + Whether to round or to truncate to the nearest half-barb. + half, full, flag : float, defaults: 5, 10, 50 + Increments for a half-barb, a barb, and a flag. + + Returns + ------- + n_flags, n_barbs : int array + For each entry in *mag*, the number of flags and barbs. + half_flag : bool array + For each entry in *mag*, whether a half-barb is needed. + empty_flag : bool array + For each entry in *mag*, whether nothing is drawn. + """ + # If rounding, round to the nearest multiple of half, the smallest + # increment + if rounding: + mag = half * np.around(mag / half) + n_flags, mag = divmod(mag, flag) + n_barb, mag = divmod(mag, full) + half_flag = mag >= half + empty_flag = ~(half_flag | (n_flags > 0) | (n_barb > 0)) + return n_flags.astype(int), n_barb.astype(int), half_flag, empty_flag + + def _make_barbs(self, u, v, nflags, nbarbs, half_barb, empty_flag, length, + pivot, sizes, fill_empty, flip): + """ + Create the wind barbs. + + Parameters + ---------- + u, v + Components of the vector in the x and y directions, respectively. + + nflags, nbarbs, half_barb, empty_flag + Respectively, the number of flags, number of barbs, flag for + half a barb, and flag for empty barb, ostensibly obtained from + :meth:`_find_tails`. + + length + The length of the barb staff in points. + + pivot : {"tip", "middle"} or number + The point on the barb around which the entire barb should be + rotated. If a number, the start of the barb is shifted by that + many points from the origin. + + sizes : dict + Coefficients specifying the ratio of a given feature to the length + of the barb. These features include: + + - *spacing*: space between features (flags, full/half barbs). + - *height*: distance from shaft of top of a flag or full barb. + - *width*: width of a flag, twice the width of a full barb. + - *emptybarb*: radius of the circle used for low magnitudes. + + fill_empty : bool + Whether the circle representing an empty barb should be filled or + not (this changes the drawing of the polygon). + + flip : list of bool + Whether the features should be flipped to the other side of the + barb (useful for winds in the southern hemisphere). + + Returns + ------- + list of arrays of vertices + Polygon vertices for each of the wind barbs. These polygons have + been rotated to properly align with the vector direction. + """ + + # These control the spacing and size of barb elements relative to the + # length of the shaft + spacing = length * sizes.get('spacing', 0.125) + full_height = length * sizes.get('height', 0.4) + full_width = length * sizes.get('width', 0.25) + empty_rad = length * sizes.get('emptybarb', 0.15) + + # Controls y point where to pivot the barb. + pivot_points = dict(tip=0.0, middle=-length / 2.) + + endx = 0.0 + try: + endy = float(pivot) + except ValueError: + endy = pivot_points[pivot.lower()] + + # Get the appropriate angle for the vector components. The offset is + # due to the way the barb is initially drawn, going down the y-axis. + # This makes sense in a meteorological mode of thinking since there 0 + # degrees corresponds to north (the y-axis traditionally) + angles = -(ma.arctan2(v, u) + np.pi / 2) + + # Used for low magnitude. We just get the vertices, so if we make it + # out here, it can be reused. The center set here should put the + # center of the circle at the location(offset), rather than at the + # same point as the barb pivot; this seems more sensible. + circ = CirclePolygon((0, 0), radius=empty_rad).get_verts() + if fill_empty: + empty_barb = circ + else: + # If we don't want the empty one filled, we make a degenerate + # polygon that wraps back over itself + empty_barb = np.concatenate((circ, circ[::-1])) + + barb_list = [] + for index, angle in np.ndenumerate(angles): + # If the vector magnitude is too weak to draw anything, plot an + # empty circle instead + if empty_flag[index]: + # We can skip the transform since the circle has no preferred + # orientation + barb_list.append(empty_barb) + continue + + poly_verts = [(endx, endy)] + offset = length + + # Handle if this barb should be flipped + barb_height = -full_height if flip[index] else full_height + + # Add vertices for each flag + for i in range(nflags[index]): + # The spacing that works for the barbs is a little to much for + # the flags, but this only occurs when we have more than 1 + # flag. + if offset != length: + offset += spacing / 2. + poly_verts.extend( + [[endx, endy + offset], + [endx + barb_height, endy - full_width / 2 + offset], + [endx, endy - full_width + offset]]) + + offset -= full_width + spacing + + # Add vertices for each barb. These really are lines, but works + # great adding 3 vertices that basically pull the polygon out and + # back down the line + for i in range(nbarbs[index]): + poly_verts.extend( + [(endx, endy + offset), + (endx + barb_height, endy + offset + full_width / 2), + (endx, endy + offset)]) + + offset -= spacing + + # Add the vertices for half a barb, if needed + if half_barb[index]: + # If the half barb is the first on the staff, traditionally it + # is offset from the end to make it easy to distinguish from a + # barb with a full one + if offset == length: + poly_verts.append((endx, endy + offset)) + offset -= 1.5 * spacing + poly_verts.extend( + [(endx, endy + offset), + (endx + barb_height / 2, endy + offset + full_width / 4), + (endx, endy + offset)]) + + # Rotate the barb according the angle. Making the barb first and + # then rotating it made the math for drawing the barb really easy. + # Also, the transform framework makes doing the rotation simple. + poly_verts = transforms.Affine2D().rotate(-angle).transform( + poly_verts) + barb_list.append(poly_verts) + + return barb_list + + def set_UVC(self, U, V, C=None): + # We need to ensure we have a copy, not a reference to an array that + # might change before draw(). + self.u = ma.masked_invalid(U, copy=True).ravel() + self.v = ma.masked_invalid(V, copy=True).ravel() + + # Flip needs to have the same number of entries as everything else. + # Use broadcast_to to avoid a bloated array of identical values. + # (can't rely on actual broadcasting) + if len(self.flip) == 1: + flip = np.broadcast_to(self.flip, self.u.shape) + else: + flip = self.flip + + if C is not None: + c = ma.masked_invalid(C, copy=True).ravel() + x, y, u, v, c, flip = cbook.delete_masked_points( + self.x.ravel(), self.y.ravel(), self.u, self.v, c, + flip.ravel()) + _check_consistent_shapes(x, y, u, v, c, flip) + else: + x, y, u, v, flip = cbook.delete_masked_points( + self.x.ravel(), self.y.ravel(), self.u, self.v, flip.ravel()) + _check_consistent_shapes(x, y, u, v, flip) + + magnitude = np.hypot(u, v) + flags, barbs, halves, empty = self._find_tails( + magnitude, self.rounding, **self.barb_increments) + + # Get the vertices for each of the barbs + + plot_barbs = self._make_barbs(u, v, flags, barbs, halves, empty, + self._length, self._pivot, self.sizes, + self.fill_empty, flip) + self.set_verts(plot_barbs) + + # Set the color array + if C is not None: + self.set_array(c) + + # Update the offsets in case the masked data changed + xy = np.column_stack((x, y)) + self._offsets = xy + self.stale = True + + def set_offsets(self, xy): + """ + Set the offsets for the barb polygons. This saves the offsets passed + in and masks them as appropriate for the existing U/V data. + + Parameters + ---------- + xy : sequence of pairs of floats + """ + self.x = xy[:, 0] + self.y = xy[:, 1] + x, y, u, v = cbook.delete_masked_points( + self.x.ravel(), self.y.ravel(), self.u, self.v) + _check_consistent_shapes(x, y, u, v) + xy = np.column_stack((x, y)) + super().set_offsets(xy) + self.stale = True diff --git a/moondream/lib/python3.10/site-packages/matplotlib/text.pyi b/moondream/lib/python3.10/site-packages/matplotlib/text.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d65a3dc4c7da2754b35e59f79e47318e55effa7e --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/text.pyi @@ -0,0 +1,181 @@ +from .artist import Artist +from .backend_bases import RendererBase +from .font_manager import FontProperties +from .offsetbox import DraggableAnnotation +from .path import Path +from .patches import FancyArrowPatch, FancyBboxPatch +from .textpath import ( # noqa: F401, reexported API + TextPath as TextPath, + TextToPath as TextToPath, +) +from .transforms import ( + Bbox, + BboxBase, + Transform, +) + +from collections.abc import Callable, Iterable +from typing import Any, Literal +from .typing import ColorType, CoordsType + +class Text(Artist): + zorder: float + def __init__( + self, + x: float = ..., + y: float = ..., + text: Any = ..., + *, + color: ColorType | None = ..., + verticalalignment: Literal[ + "bottom", "baseline", "center", "center_baseline", "top" + ] = ..., + horizontalalignment: Literal["left", "center", "right"] = ..., + multialignment: Literal["left", "center", "right"] | None = ..., + fontproperties: str | Path | FontProperties | None = ..., + rotation: float | Literal["vertical", "horizontal"] | None = ..., + linespacing: float | None = ..., + rotation_mode: Literal["default", "anchor"] | None = ..., + usetex: bool | None = ..., + wrap: bool = ..., + transform_rotates_text: bool = ..., + parse_math: bool | None = ..., + antialiased: bool | None = ..., + **kwargs + ) -> None: ... + def update(self, kwargs: dict[str, Any]) -> list[Any]: ... + def get_rotation(self) -> float: ... + def get_transform_rotates_text(self) -> bool: ... + def set_rotation_mode(self, m: None | Literal["default", "anchor"]) -> None: ... + def get_rotation_mode(self) -> Literal["default", "anchor"]: ... + def set_bbox(self, rectprops: dict[str, Any]) -> None: ... + def get_bbox_patch(self) -> None | FancyBboxPatch: ... + def update_bbox_position_size(self, renderer: RendererBase) -> None: ... + def get_wrap(self) -> bool: ... + def set_wrap(self, wrap: bool) -> None: ... + def get_color(self) -> ColorType: ... + def get_fontproperties(self) -> FontProperties: ... + def get_fontfamily(self) -> list[str]: ... + def get_fontname(self) -> str: ... + def get_fontstyle(self) -> Literal["normal", "italic", "oblique"]: ... + def get_fontsize(self) -> float | str: ... + def get_fontvariant(self) -> Literal["normal", "small-caps"]: ... + def get_fontweight(self) -> int | str: ... + def get_stretch(self) -> int | str: ... + def get_horizontalalignment(self) -> Literal["left", "center", "right"]: ... + def get_unitless_position(self) -> tuple[float, float]: ... + def get_position(self) -> tuple[float, float]: ... + def get_text(self) -> str: ... + def get_verticalalignment( + self, + ) -> Literal["bottom", "baseline", "center", "center_baseline", "top"]: ... + def get_window_extent( + self, renderer: RendererBase | None = ..., dpi: float | None = ... + ) -> Bbox: ... + def set_backgroundcolor(self, color: ColorType) -> None: ... + def set_color(self, color: ColorType) -> None: ... + def set_horizontalalignment( + self, align: Literal["left", "center", "right"] + ) -> None: ... + def set_multialignment(self, align: Literal["left", "center", "right"]) -> None: ... + def set_linespacing(self, spacing: float) -> None: ... + def set_fontfamily(self, fontname: str | Iterable[str]) -> None: ... + def set_fontvariant(self, variant: Literal["normal", "small-caps"]) -> None: ... + def set_fontstyle( + self, fontstyle: Literal["normal", "italic", "oblique"] + ) -> None: ... + def set_fontsize(self, fontsize: float | str) -> None: ... + def get_math_fontfamily(self) -> str: ... + def set_math_fontfamily(self, fontfamily: str) -> None: ... + def set_fontweight(self, weight: int | str) -> None: ... + def set_fontstretch(self, stretch: int | str) -> None: ... + def set_position(self, xy: tuple[float, float]) -> None: ... + def set_x(self, x: float) -> None: ... + def set_y(self, y: float) -> None: ... + def set_rotation(self, s: float) -> None: ... + def set_transform_rotates_text(self, t: bool) -> None: ... + def set_verticalalignment( + self, align: Literal["bottom", "baseline", "center", "center_baseline", "top"] + ) -> None: ... + def set_text(self, s: Any) -> None: ... + def set_fontproperties(self, fp: FontProperties | str | Path | None) -> None: ... + def set_usetex(self, usetex: bool | None) -> None: ... + def get_usetex(self) -> bool: ... + def set_parse_math(self, parse_math: bool) -> None: ... + def get_parse_math(self) -> bool: ... + def set_fontname(self, fontname: str | Iterable[str]) -> None: ... + def get_antialiased(self) -> bool: ... + def set_antialiased(self, antialiased: bool) -> None: ... + +class OffsetFrom: + def __init__( + self, + artist: Artist | BboxBase | Transform, + ref_coord: tuple[float, float], + unit: Literal["points", "pixels"] = ..., + ) -> None: ... + def set_unit(self, unit: Literal["points", "pixels"]) -> None: ... + def get_unit(self) -> Literal["points", "pixels"]: ... + def __call__(self, renderer: RendererBase) -> Transform: ... + +class _AnnotationBase: + xy: tuple[float, float] + xycoords: CoordsType + def __init__( + self, + xy, + xycoords: CoordsType = ..., + annotation_clip: bool | None = ..., + ) -> None: ... + def set_annotation_clip(self, b: bool | None) -> None: ... + def get_annotation_clip(self) -> bool | None: ... + def draggable( + self, state: bool | None = ..., use_blit: bool = ... + ) -> DraggableAnnotation | None: ... + +class Annotation(Text, _AnnotationBase): + arrowprops: dict[str, Any] | None + arrow_patch: FancyArrowPatch | None + def __init__( + self, + text: str, + xy: tuple[float, float], + xytext: tuple[float, float] | None = ..., + xycoords: CoordsType = ..., + textcoords: CoordsType | None = ..., + arrowprops: dict[str, Any] | None = ..., + annotation_clip: bool | None = ..., + **kwargs + ) -> None: ... + @property + def xycoords( + self, + ) -> CoordsType: ... + @xycoords.setter + def xycoords( + self, + xycoords: CoordsType, + ) -> None: ... + @property + def xyann(self) -> tuple[float, float]: ... + @xyann.setter + def xyann(self, xytext: tuple[float, float]) -> None: ... + def get_anncoords( + self, + ) -> CoordsType: ... + def set_anncoords( + self, + coords: CoordsType, + ) -> None: ... + @property + def anncoords( + self, + ) -> CoordsType: ... + @anncoords.setter + def anncoords( + self, + coords: CoordsType, + ) -> None: ... + def update_positions(self, renderer: RendererBase) -> None: ... + # Drops `dpi` parameter from superclass + def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ... # type: ignore[override] diff --git a/moondream/lib/python3.10/site-packages/matplotlib/textpath.pyi b/moondream/lib/python3.10/site-packages/matplotlib/textpath.pyi new file mode 100644 index 0000000000000000000000000000000000000000..34d4e92ac47ef45c70ab906bc3b8d1fa2bac07dd --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/textpath.pyi @@ -0,0 +1,74 @@ +from matplotlib.font_manager import FontProperties +from matplotlib.ft2font import FT2Font +from matplotlib.mathtext import MathTextParser, VectorParse +from matplotlib.path import Path + +import numpy as np + +from typing import Literal + +class TextToPath: + FONT_SCALE: float + DPI: float + mathtext_parser: MathTextParser[VectorParse] + def __init__(self) -> None: ... + def get_text_width_height_descent( + self, s: str, prop: FontProperties, ismath: bool | Literal["TeX"] + ) -> tuple[float, float, float]: ... + def get_text_path( + self, prop: FontProperties, s: str, ismath: bool | Literal["TeX"] = ... + ) -> list[np.ndarray]: ... + def get_glyphs_with_font( + self, + font: FT2Font, + s: str, + glyph_map: dict[str, tuple[np.ndarray, np.ndarray]] | None = ..., + return_new_glyphs_only: bool = ..., + ) -> tuple[ + list[tuple[str, float, float, float]], + dict[str, tuple[np.ndarray, np.ndarray]], + list[tuple[list[tuple[float, float]], list[int]]], + ]: ... + def get_glyphs_mathtext( + self, + prop: FontProperties, + s: str, + glyph_map: dict[str, tuple[np.ndarray, np.ndarray]] | None = ..., + return_new_glyphs_only: bool = ..., + ) -> tuple[ + list[tuple[str, float, float, float]], + dict[str, tuple[np.ndarray, np.ndarray]], + list[tuple[list[tuple[float, float]], list[int]]], + ]: ... + def get_glyphs_tex( + self, + prop: FontProperties, + s: str, + glyph_map: dict[str, tuple[np.ndarray, np.ndarray]] | None = ..., + return_new_glyphs_only: bool = ..., + ) -> tuple[ + list[tuple[str, float, float, float]], + dict[str, tuple[np.ndarray, np.ndarray]], + list[tuple[list[tuple[float, float]], list[int]]], + ]: ... + +text_to_path: TextToPath + +class TextPath(Path): + def __init__( + self, + xy: tuple[float, float], + s: str, + size: float | None = ..., + prop: FontProperties | None = ..., + _interpolation_steps: int = ..., + usetex: bool = ..., + ) -> None: ... + def set_size(self, size: float | None) -> None: ... + def get_size(self) -> float | None: ... + + # These are read only... there actually are protections in the base class, so probably can be deleted... + @property # type: ignore[misc] + def vertices(self) -> np.ndarray: ... # type: ignore[override] + @property # type: ignore[misc] + def codes(self) -> np.ndarray: ... # type: ignore[override] diff --git a/moondream/lib/python3.10/site-packages/matplotlib/transforms.pyi b/moondream/lib/python3.10/site-packages/matplotlib/transforms.pyi new file mode 100644 index 0000000000000000000000000000000000000000..551487a11c6015ba392d32fa1a86b5c7b61090e5 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/matplotlib/transforms.pyi @@ -0,0 +1,341 @@ +from .path import Path +from .patches import Patch +from .figure import Figure +import numpy as np +from numpy.typing import ArrayLike +from collections.abc import Iterable, Sequence +from typing import Literal + +DEBUG: bool + +class TransformNode: + INVALID_NON_AFFINE: int + INVALID_AFFINE: int + INVALID: int + is_bbox: bool + # Implemented as a standard attr in base class, but functionally readonly and some subclasses implement as such + @property + def is_affine(self) -> bool: ... + pass_through: bool + def __init__(self, shorthand_name: str | None = ...) -> None: ... + def __copy__(self) -> TransformNode: ... + def invalidate(self) -> None: ... + def set_children(self, *children: TransformNode) -> None: ... + def frozen(self) -> TransformNode: ... + +class BboxBase(TransformNode): + is_bbox: bool + is_affine: bool + def frozen(self) -> Bbox: ... + def __array__(self, *args, **kwargs): ... + @property + def x0(self) -> float: ... + @property + def y0(self) -> float: ... + @property + def x1(self) -> float: ... + @property + def y1(self) -> float: ... + @property + def p0(self) -> tuple[float, float]: ... + @property + def p1(self) -> tuple[float, float]: ... + @property + def xmin(self) -> float: ... + @property + def ymin(self) -> float: ... + @property + def xmax(self) -> float: ... + @property + def ymax(self) -> float: ... + @property + def min(self) -> tuple[float, float]: ... + @property + def max(self) -> tuple[float, float]: ... + @property + def intervalx(self) -> tuple[float, float]: ... + @property + def intervaly(self) -> tuple[float, float]: ... + @property + def width(self) -> float: ... + @property + def height(self) -> float: ... + @property + def size(self) -> tuple[float, float]: ... + @property + def bounds(self) -> tuple[float, float, float, float]: ... + @property + def extents(self) -> tuple[float, float, float, float]: ... + def get_points(self) -> np.ndarray: ... + def containsx(self, x: float) -> bool: ... + def containsy(self, y: float) -> bool: ... + def contains(self, x: float, y: float) -> bool: ... + def overlaps(self, other: BboxBase) -> bool: ... + def fully_containsx(self, x: float) -> bool: ... + def fully_containsy(self, y: float) -> bool: ... + def fully_contains(self, x: float, y: float) -> bool: ... + def fully_overlaps(self, other: BboxBase) -> bool: ... + def transformed(self, transform: Transform) -> Bbox: ... + coefs: dict[str, tuple[float, float]] + def anchored( + self, + c: tuple[float, float] | Literal['C', 'SW', 'S', 'SE', 'E', 'NE', 'N', 'NW', 'W'], + container: BboxBase, + ) -> Bbox: ... + def shrunk(self, mx: float, my: float) -> Bbox: ... + def shrunk_to_aspect( + self, + box_aspect: float, + container: BboxBase | None = ..., + fig_aspect: float = ..., + ) -> Bbox: ... + def splitx(self, *args: float) -> list[Bbox]: ... + def splity(self, *args: float) -> list[Bbox]: ... + def count_contains(self, vertices: ArrayLike) -> int: ... + def count_overlaps(self, bboxes: Iterable[BboxBase]) -> int: ... + def expanded(self, sw: float, sh: float) -> Bbox: ... + def padded(self, w_pad: float, h_pad: float | None = ...) -> Bbox: ... + def translated(self, tx: float, ty: float) -> Bbox: ... + def corners(self) -> np.ndarray: ... + def rotated(self, radians: float) -> Bbox: ... + @staticmethod + def union(bboxes: Sequence[BboxBase]) -> Bbox: ... + @staticmethod + def intersection(bbox1: BboxBase, bbox2: BboxBase) -> Bbox | None: ... + +class Bbox(BboxBase): + def __init__(self, points: ArrayLike, **kwargs) -> None: ... + @staticmethod + def unit() -> Bbox: ... + @staticmethod + def null() -> Bbox: ... + @staticmethod + def from_bounds(x0: float, y0: float, width: float, height: float) -> Bbox: ... + @staticmethod + def from_extents(*args: float, minpos: float | None = ...) -> Bbox: ... + def __format__(self, fmt: str) -> str: ... + def ignore(self, value: bool) -> None: ... + def update_from_path( + self, + path: Path, + ignore: bool | None = ..., + updatex: bool = ..., + updatey: bool = ..., + ) -> None: ... + def update_from_data_x(self, x: ArrayLike, ignore: bool | None = ...) -> None: ... + def update_from_data_y(self, y: ArrayLike, ignore: bool | None = ...) -> None: ... + def update_from_data_xy( + self, + xy: ArrayLike, + ignore: bool | None = ..., + updatex: bool = ..., + updatey: bool = ..., + ) -> None: ... + @property + def minpos(self) -> float: ... + @property + def minposx(self) -> float: ... + @property + def minposy(self) -> float: ... + def get_points(self) -> np.ndarray: ... + def set_points(self, points: ArrayLike) -> None: ... + def set(self, other: Bbox) -> None: ... + def mutated(self) -> bool: ... + def mutatedx(self) -> bool: ... + def mutatedy(self) -> bool: ... + +class TransformedBbox(BboxBase): + def __init__(self, bbox: Bbox, transform: Transform, **kwargs) -> None: ... + def get_points(self) -> np.ndarray: ... + +class LockableBbox(BboxBase): + def __init__( + self, + bbox: BboxBase, + x0: float | None = ..., + y0: float | None = ..., + x1: float | None = ..., + y1: float | None = ..., + **kwargs + ) -> None: ... + @property + def locked_x0(self) -> float | None: ... + @locked_x0.setter + def locked_x0(self, x0: float | None) -> None: ... + @property + def locked_y0(self) -> float | None: ... + @locked_y0.setter + def locked_y0(self, y0: float | None) -> None: ... + @property + def locked_x1(self) -> float | None: ... + @locked_x1.setter + def locked_x1(self, x1: float | None) -> None: ... + @property + def locked_y1(self) -> float | None: ... + @locked_y1.setter + def locked_y1(self, y1: float | None) -> None: ... + +class Transform(TransformNode): + + # Implemented as a standard attrs in base class, but functionally readonly and some subclasses implement as such + @property + def input_dims(self) -> int | None: ... + @property + def output_dims(self) -> int | None: ... + @property + def is_separable(self) -> bool: ... + @property + def has_inverse(self) -> bool: ... + + def __add__(self, other: Transform) -> Transform: ... + @property + def depth(self) -> int: ... + def contains_branch(self, other: Transform) -> bool: ... + def contains_branch_seperately( + self, other_transform: Transform + ) -> Sequence[bool]: ... + def __sub__(self, other: Transform) -> Transform: ... + def __array__(self, *args, **kwargs) -> np.ndarray: ... + def transform(self, values: ArrayLike) -> np.ndarray: ... + def transform_affine(self, values: ArrayLike) -> np.ndarray: ... + def transform_non_affine(self, values: ArrayLike) -> ArrayLike: ... + def transform_bbox(self, bbox: BboxBase) -> Bbox: ... + def get_affine(self) -> Transform: ... + def get_matrix(self) -> np.ndarray: ... + def transform_point(self, point: ArrayLike) -> np.ndarray: ... + def transform_path(self, path: Path) -> Path: ... + def transform_path_affine(self, path: Path) -> Path: ... + def transform_path_non_affine(self, path: Path) -> Path: ... + def transform_angles( + self, + angles: ArrayLike, + pts: ArrayLike, + radians: bool = ..., + pushoff: float = ..., + ) -> np.ndarray: ... + def inverted(self) -> Transform: ... + +class TransformWrapper(Transform): + pass_through: bool + def __init__(self, child: Transform) -> None: ... + def __eq__(self, other: object) -> bool: ... + def frozen(self) -> Transform: ... + def set(self, child: Transform) -> None: ... + +class AffineBase(Transform): + is_affine: Literal[True] + def __init__(self, *args, **kwargs) -> None: ... + def __eq__(self, other: object) -> bool: ... + +class Affine2DBase(AffineBase): + input_dims: Literal[2] + output_dims: Literal[2] + def frozen(self) -> Affine2D: ... + def to_values(self) -> tuple[float, float, float, float, float, float]: ... + +class Affine2D(Affine2DBase): + def __init__(self, matrix: ArrayLike | None = ..., **kwargs) -> None: ... + @staticmethod + def from_values( + a: float, b: float, c: float, d: float, e: float, f: float + ) -> Affine2D: ... + def set_matrix(self, mtx: ArrayLike) -> None: ... + def clear(self) -> Affine2D: ... + def rotate(self, theta: float) -> Affine2D: ... + def rotate_deg(self, degrees: float) -> Affine2D: ... + def rotate_around(self, x: float, y: float, theta: float) -> Affine2D: ... + def rotate_deg_around(self, x: float, y: float, degrees: float) -> Affine2D: ... + def translate(self, tx: float, ty: float) -> Affine2D: ... + def scale(self, sx: float, sy: float | None = ...) -> Affine2D: ... + def skew(self, xShear: float, yShear: float) -> Affine2D: ... + def skew_deg(self, xShear: float, yShear: float) -> Affine2D: ... + +class IdentityTransform(Affine2DBase): ... + +class _BlendedMixin: + def __eq__(self, other: object) -> bool: ... + def contains_branch_seperately(self, transform: Transform) -> Sequence[bool]: ... + +class BlendedGenericTransform(_BlendedMixin, Transform): + input_dims: Literal[2] + output_dims: Literal[2] + pass_through: bool + def __init__( + self, x_transform: Transform, y_transform: Transform, **kwargs + ) -> None: ... + @property + def depth(self) -> int: ... + def contains_branch(self, other: Transform) -> Literal[False]: ... + @property + def is_affine(self) -> bool: ... + +class BlendedAffine2D(_BlendedMixin, Affine2DBase): + def __init__( + self, x_transform: Transform, y_transform: Transform, **kwargs + ) -> None: ... + +def blended_transform_factory( + x_transform: Transform, y_transform: Transform +) -> BlendedGenericTransform | BlendedAffine2D: ... + +class CompositeGenericTransform(Transform): + pass_through: bool + def __init__(self, a: Transform, b: Transform, **kwargs) -> None: ... + +class CompositeAffine2D(Affine2DBase): + def __init__(self, a: Affine2DBase, b: Affine2DBase, **kwargs) -> None: ... + @property + def depth(self) -> int: ... + +def composite_transform_factory(a: Transform, b: Transform) -> Transform: ... + +class BboxTransform(Affine2DBase): + def __init__(self, boxin: BboxBase, boxout: BboxBase, **kwargs) -> None: ... + +class BboxTransformTo(Affine2DBase): + def __init__(self, boxout: BboxBase, **kwargs) -> None: ... + +class BboxTransformToMaxOnly(BboxTransformTo): ... + +class BboxTransformFrom(Affine2DBase): + def __init__(self, boxin: BboxBase, **kwargs) -> None: ... + +class ScaledTranslation(Affine2DBase): + def __init__( + self, xt: float, yt: float, scale_trans: Affine2DBase, **kwargs + ) -> None: ... + +class AffineDeltaTransform(Affine2DBase): + def __init__(self, transform: Affine2DBase, **kwargs) -> None: ... + +class TransformedPath(TransformNode): + def __init__(self, path: Path, transform: Transform) -> None: ... + def get_transformed_points_and_affine(self) -> tuple[Path, Transform]: ... + def get_transformed_path_and_affine(self) -> tuple[Path, Transform]: ... + def get_fully_transformed_path(self) -> Path: ... + def get_affine(self) -> Transform: ... + +class TransformedPatchPath(TransformedPath): + def __init__(self, patch: Patch) -> None: ... + +def nonsingular( + vmin: float, + vmax: float, + expander: float = ..., + tiny: float = ..., + increasing: bool = ..., +) -> tuple[float, float]: ... +def interval_contains(interval: tuple[float, float], val: float) -> bool: ... +def interval_contains_open(interval: tuple[float, float], val: float) -> bool: ... +def offset_copy( + trans: Transform, + fig: Figure | None = ..., + x: float = ..., + y: float = ..., + units: Literal["inches", "points", "dots"] = ..., +) -> Transform: ... + + +class _ScaledRotation(Affine2DBase): + def __init__(self, theta: float, trans_shift: Transform) -> None: ... + def get_matrix(self) -> np.ndarray: ... diff --git a/moondream/lib/python3.10/site-packages/narwhals-1.21.1.dist-info/WHEEL b/moondream/lib/python3.10/site-packages/narwhals-1.21.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/narwhals-1.21.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/moondream/lib/python3.10/site-packages/numpy/random/mtrand.cpython-310-x86_64-linux-gnu.so b/moondream/lib/python3.10/site-packages/numpy/random/mtrand.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d4025b522272a19edbae00a8790bd78f2b47d421 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/numpy/random/mtrand.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b917e2f0ada2ef00b0cc509b76f14d8bce4815e3643abd58481803bbb6b585fe +size 783752 diff --git a/moondream/lib/python3.10/site-packages/onnx/onnx_cpp2py_export.cpython-310-x86_64-linux-gnu.so b/moondream/lib/python3.10/site-packages/onnx/onnx_cpp2py_export.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..bd68c22430106916452c6d5dd6697c4871e406f6 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/onnx/onnx_cpp2py_export.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bef7bdc2abd59a7fb87de9a60e222127b14a7a6f44b064b0c0fe7c6d1adc5a70 +size 5838032 diff --git a/moondream/lib/python3.10/site-packages/pkg_resources/__init__.py b/moondream/lib/python3.10/site-packages/pkg_resources/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..68feeb05935737250bd23c4726131b83e1a71de5 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/pkg_resources/__init__.py @@ -0,0 +1,3709 @@ +""" +Package resource API +-------------------- + +A resource is a logical file contained within a package, or a logical +subdirectory thereof. The package resource API expects resource names +to have their path parts separated with ``/``, *not* whatever the local +path separator is. Do not use os.path operations to manipulate resource +names being passed into the API. + +The package resource API is designed to work with normal filesystem packages, +.egg files, and unpacked .egg files. It can also work in a limited way with +.zip files and with custom PEP 302 loaders that support the ``get_data()`` +method. + +This module is deprecated. Users are directed to :mod:`importlib.resources`, +:mod:`importlib.metadata` and :pypi:`packaging` instead. +""" + +from __future__ import annotations + +import sys + +if sys.version_info < (3, 9): # noqa: UP036 # Check for unsupported versions + raise RuntimeError("Python 3.9 or later is required") + +import _imp +import collections +import email.parser +import errno +import functools +import importlib +import importlib.abc +import importlib.machinery +import inspect +import io +import ntpath +import operator +import os +import pkgutil +import platform +import plistlib +import posixpath +import re +import stat +import tempfile +import textwrap +import time +import types +import warnings +import zipfile +import zipimport +from collections.abc import Iterable, Iterator, Mapping, MutableSequence +from pkgutil import get_importer +from typing import ( + TYPE_CHECKING, + Any, + BinaryIO, + Callable, + Literal, + NamedTuple, + NoReturn, + Protocol, + TypeVar, + Union, + overload, +) + +sys.path.extend(((vendor_path := os.path.join(os.path.dirname(os.path.dirname(__file__)), 'setuptools', '_vendor')) not in sys.path) * [vendor_path]) # fmt: skip +# workaround for #4476 +sys.modules.pop('backports', None) + +# capture these to bypass sandboxing +from os import open as os_open, utime # isort: skip +from os.path import isdir, split # isort: skip + +try: + from os import mkdir, rename, unlink + + WRITE_SUPPORT = True +except ImportError: + # no write support, probably under GAE + WRITE_SUPPORT = False + +import packaging.markers +import packaging.requirements +import packaging.specifiers +import packaging.utils +import packaging.version +from jaraco.text import drop_comment, join_continuation, yield_lines +from platformdirs import user_cache_dir as _user_cache_dir + +if TYPE_CHECKING: + from _typeshed import BytesPath, StrOrBytesPath, StrPath + from _typeshed.importlib import LoaderProtocol + from typing_extensions import Self, TypeAlias + +warnings.warn( + "pkg_resources is deprecated as an API. " + "See https://setuptools.pypa.io/en/latest/pkg_resources.html", + DeprecationWarning, + stacklevel=2, +) + +_T = TypeVar("_T") +_DistributionT = TypeVar("_DistributionT", bound="Distribution") +# Type aliases +_NestedStr: TypeAlias = Union[str, Iterable[Union[str, Iterable["_NestedStr"]]]] +_StrictInstallerType: TypeAlias = Callable[["Requirement"], "_DistributionT"] +_InstallerType: TypeAlias = Callable[["Requirement"], Union["Distribution", None]] +_PkgReqType: TypeAlias = Union[str, "Requirement"] +_EPDistType: TypeAlias = Union["Distribution", _PkgReqType] +_MetadataType: TypeAlias = Union["IResourceProvider", None] +_ResolvedEntryPoint: TypeAlias = Any # Can be any attribute in the module +_ResourceStream: TypeAlias = Any # TODO / Incomplete: A readable file-like object +# Any object works, but let's indicate we expect something like a module (optionally has __loader__ or __file__) +_ModuleLike: TypeAlias = Union[object, types.ModuleType] +# Any: Should be _ModuleLike but we end up with issues where _ModuleLike doesn't have _ZipLoaderModule's __loader__ +_ProviderFactoryType: TypeAlias = Callable[[Any], "IResourceProvider"] +_DistFinderType: TypeAlias = Callable[[_T, str, bool], Iterable["Distribution"]] +_NSHandlerType: TypeAlias = Callable[[_T, str, str, types.ModuleType], Union[str, None]] +_AdapterT = TypeVar( + "_AdapterT", _DistFinderType[Any], _ProviderFactoryType, _NSHandlerType[Any] +) + + +class _ZipLoaderModule(Protocol): + __loader__: zipimport.zipimporter + + +_PEP440_FALLBACK = re.compile(r"^v?(?P(?:[0-9]+!)?[0-9]+(?:\.[0-9]+)*)", re.I) + + +class PEP440Warning(RuntimeWarning): + """ + Used when there is an issue with a version or specifier not complying with + PEP 440. + """ + + +parse_version = packaging.version.Version + +_state_vars: dict[str, str] = {} + + +def _declare_state(vartype: str, varname: str, initial_value: _T) -> _T: + _state_vars[varname] = vartype + return initial_value + + +def __getstate__() -> dict[str, Any]: + state = {} + g = globals() + for k, v in _state_vars.items(): + state[k] = g['_sget_' + v](g[k]) + return state + + +def __setstate__(state: dict[str, Any]) -> dict[str, Any]: + g = globals() + for k, v in state.items(): + g['_sset_' + _state_vars[k]](k, g[k], v) + return state + + +def _sget_dict(val): + return val.copy() + + +def _sset_dict(key, ob, state) -> None: + ob.clear() + ob.update(state) + + +def _sget_object(val): + return val.__getstate__() + + +def _sset_object(key, ob, state) -> None: + ob.__setstate__(state) + + +_sget_none = _sset_none = lambda *args: None + + +def get_supported_platform(): + """Return this platform's maximum compatible version. + + distutils.util.get_platform() normally reports the minimum version + of macOS that would be required to *use* extensions produced by + distutils. But what we want when checking compatibility is to know the + version of macOS that we are *running*. To allow usage of packages that + explicitly require a newer version of macOS, we must also know the + current version of the OS. + + If this condition occurs for any other platform with a version in its + platform strings, this function should be extended accordingly. + """ + plat = get_build_platform() + m = macosVersionString.match(plat) + if m is not None and sys.platform == "darwin": + try: + major_minor = '.'.join(_macos_vers()[:2]) + build = m.group(3) + plat = f'macosx-{major_minor}-{build}' + except ValueError: + # not macOS + pass + return plat + + +__all__ = [ + # Basic resource access and distribution/entry point discovery + 'require', + 'run_script', + 'get_provider', + 'get_distribution', + 'load_entry_point', + 'get_entry_map', + 'get_entry_info', + 'iter_entry_points', + 'resource_string', + 'resource_stream', + 'resource_filename', + 'resource_listdir', + 'resource_exists', + 'resource_isdir', + # Environmental control + 'declare_namespace', + 'working_set', + 'add_activation_listener', + 'find_distributions', + 'set_extraction_path', + 'cleanup_resources', + 'get_default_cache', + # Primary implementation classes + 'Environment', + 'WorkingSet', + 'ResourceManager', + 'Distribution', + 'Requirement', + 'EntryPoint', + # Exceptions + 'ResolutionError', + 'VersionConflict', + 'DistributionNotFound', + 'UnknownExtra', + 'ExtractionError', + # Warnings + 'PEP440Warning', + # Parsing functions and string utilities + 'parse_requirements', + 'parse_version', + 'safe_name', + 'safe_version', + 'get_platform', + 'compatible_platforms', + 'yield_lines', + 'split_sections', + 'safe_extra', + 'to_filename', + 'invalid_marker', + 'evaluate_marker', + # filesystem utilities + 'ensure_directory', + 'normalize_path', + # Distribution "precedence" constants + 'EGG_DIST', + 'BINARY_DIST', + 'SOURCE_DIST', + 'CHECKOUT_DIST', + 'DEVELOP_DIST', + # "Provider" interfaces, implementations, and registration/lookup APIs + 'IMetadataProvider', + 'IResourceProvider', + 'FileMetadata', + 'PathMetadata', + 'EggMetadata', + 'EmptyProvider', + 'empty_provider', + 'NullProvider', + 'EggProvider', + 'DefaultProvider', + 'ZipProvider', + 'register_finder', + 'register_namespace_handler', + 'register_loader_type', + 'fixup_namespace_packages', + 'get_importer', + # Warnings + 'PkgResourcesDeprecationWarning', + # Deprecated/backward compatibility only + 'run_main', + 'AvailableDistributions', +] + + +class ResolutionError(Exception): + """Abstract base for dependency resolution errors""" + + def __repr__(self) -> str: + return self.__class__.__name__ + repr(self.args) + + +class VersionConflict(ResolutionError): + """ + An already-installed version conflicts with the requested version. + + Should be initialized with the installed Distribution and the requested + Requirement. + """ + + _template = "{self.dist} is installed but {self.req} is required" + + @property + def dist(self) -> Distribution: + return self.args[0] + + @property + def req(self) -> Requirement: + return self.args[1] + + def report(self): + return self._template.format(**locals()) + + def with_context( + self, required_by: set[Distribution | str] + ) -> Self | ContextualVersionConflict: + """ + If required_by is non-empty, return a version of self that is a + ContextualVersionConflict. + """ + if not required_by: + return self + args = self.args + (required_by,) + return ContextualVersionConflict(*args) + + +class ContextualVersionConflict(VersionConflict): + """ + A VersionConflict that accepts a third parameter, the set of the + requirements that required the installed Distribution. + """ + + _template = VersionConflict._template + ' by {self.required_by}' + + @property + def required_by(self) -> set[str]: + return self.args[2] + + +class DistributionNotFound(ResolutionError): + """A requested distribution was not found""" + + _template = ( + "The '{self.req}' distribution was not found " + "and is required by {self.requirers_str}" + ) + + @property + def req(self) -> Requirement: + return self.args[0] + + @property + def requirers(self) -> set[str] | None: + return self.args[1] + + @property + def requirers_str(self): + if not self.requirers: + return 'the application' + return ', '.join(self.requirers) + + def report(self): + return self._template.format(**locals()) + + def __str__(self) -> str: + return self.report() + + +class UnknownExtra(ResolutionError): + """Distribution doesn't have an "extra feature" of the given name""" + + +_provider_factories: dict[type[_ModuleLike], _ProviderFactoryType] = {} + +PY_MAJOR = f'{sys.version_info.major}.{sys.version_info.minor}' +EGG_DIST = 3 +BINARY_DIST = 2 +SOURCE_DIST = 1 +CHECKOUT_DIST = 0 +DEVELOP_DIST = -1 + + +def register_loader_type( + loader_type: type[_ModuleLike], provider_factory: _ProviderFactoryType +) -> None: + """Register `provider_factory` to make providers for `loader_type` + + `loader_type` is the type or class of a PEP 302 ``module.__loader__``, + and `provider_factory` is a function that, passed a *module* object, + returns an ``IResourceProvider`` for that module. + """ + _provider_factories[loader_type] = provider_factory + + +@overload +def get_provider(moduleOrReq: str) -> IResourceProvider: ... +@overload +def get_provider(moduleOrReq: Requirement) -> Distribution: ... +def get_provider(moduleOrReq: str | Requirement) -> IResourceProvider | Distribution: + """Return an IResourceProvider for the named module or requirement""" + if isinstance(moduleOrReq, Requirement): + return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] + try: + module = sys.modules[moduleOrReq] + except KeyError: + __import__(moduleOrReq) + module = sys.modules[moduleOrReq] + loader = getattr(module, '__loader__', None) + return _find_adapter(_provider_factories, loader)(module) + + +@functools.cache +def _macos_vers(): + version = platform.mac_ver()[0] + # fallback for MacPorts + if version == '': + plist = '/System/Library/CoreServices/SystemVersion.plist' + if os.path.exists(plist): + with open(plist, 'rb') as fh: + plist_content = plistlib.load(fh) + if 'ProductVersion' in plist_content: + version = plist_content['ProductVersion'] + return version.split('.') + + +def _macos_arch(machine): + return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine) + + +def get_build_platform(): + """Return this platform's string for platform-specific distributions + + XXX Currently this is the same as ``distutils.util.get_platform()``, but it + needs some hacks for Linux and macOS. + """ + from sysconfig import get_platform + + plat = get_platform() + if sys.platform == "darwin" and not plat.startswith('macosx-'): + try: + version = _macos_vers() + machine = _macos_arch(os.uname()[4].replace(" ", "_")) + return f"macosx-{version[0]}.{version[1]}-{machine}" + except ValueError: + # if someone is running a non-Mac darwin system, this will fall + # through to the default implementation + pass + return plat + + +macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)") +darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)") +# XXX backward compat +get_platform = get_build_platform + + +def compatible_platforms(provided: str | None, required: str | None) -> bool: + """Can code for the `provided` platform run on the `required` platform? + + Returns true if either platform is ``None``, or the platforms are equal. + + XXX Needs compatibility checks for Linux and other unixy OSes. + """ + if provided is None or required is None or provided == required: + # easy case + return True + + # macOS special cases + reqMac = macosVersionString.match(required) + if reqMac: + provMac = macosVersionString.match(provided) + + # is this a Mac package? + if not provMac: + # this is backwards compatibility for packages built before + # setuptools 0.6. All packages built after this point will + # use the new macOS designation. + provDarwin = darwinVersionString.match(provided) + if provDarwin: + dversion = int(provDarwin.group(1)) + macosversion = f"{reqMac.group(1)}.{reqMac.group(2)}" + if ( + dversion == 7 + and macosversion >= "10.3" + or dversion == 8 + and macosversion >= "10.4" + ): + return True + # egg isn't macOS or legacy darwin + return False + + # are they the same major version and machine type? + if provMac.group(1) != reqMac.group(1) or provMac.group(3) != reqMac.group(3): + return False + + # is the required OS major update >= the provided one? + if int(provMac.group(2)) > int(reqMac.group(2)): + return False + + return True + + # XXX Linux and other platforms' special cases should go here + return False + + +@overload +def get_distribution(dist: _DistributionT) -> _DistributionT: ... +@overload +def get_distribution(dist: _PkgReqType) -> Distribution: ... +def get_distribution(dist: Distribution | _PkgReqType) -> Distribution: + """Return a current distribution object for a Requirement or string""" + if isinstance(dist, str): + dist = Requirement.parse(dist) + if isinstance(dist, Requirement): + dist = get_provider(dist) + if not isinstance(dist, Distribution): + raise TypeError("Expected str, Requirement, or Distribution", dist) + return dist + + +def load_entry_point(dist: _EPDistType, group: str, name: str) -> _ResolvedEntryPoint: + """Return `name` entry point of `group` for `dist` or raise ImportError""" + return get_distribution(dist).load_entry_point(group, name) + + +@overload +def get_entry_map( + dist: _EPDistType, group: None = None +) -> dict[str, dict[str, EntryPoint]]: ... +@overload +def get_entry_map(dist: _EPDistType, group: str) -> dict[str, EntryPoint]: ... +def get_entry_map(dist: _EPDistType, group: str | None = None): + """Return the entry point map for `group`, or the full entry map""" + return get_distribution(dist).get_entry_map(group) + + +def get_entry_info(dist: _EPDistType, group: str, name: str) -> EntryPoint | None: + """Return the EntryPoint object for `group`+`name`, or ``None``""" + return get_distribution(dist).get_entry_info(group, name) + + +class IMetadataProvider(Protocol): + def has_metadata(self, name: str) -> bool: + """Does the package's distribution contain the named metadata?""" + ... + + def get_metadata(self, name: str) -> str: + """The named metadata resource as a string""" + ... + + def get_metadata_lines(self, name: str) -> Iterator[str]: + """Yield named metadata resource as list of non-blank non-comment lines + + Leading and trailing whitespace is stripped from each line, and lines + with ``#`` as the first non-blank character are omitted.""" + ... + + def metadata_isdir(self, name: str) -> bool: + """Is the named metadata a directory? (like ``os.path.isdir()``)""" + ... + + def metadata_listdir(self, name: str) -> list[str]: + """List of metadata names in the directory (like ``os.listdir()``)""" + ... + + def run_script(self, script_name: str, namespace: dict[str, Any]) -> None: + """Execute the named script in the supplied namespace dictionary""" + ... + + +class IResourceProvider(IMetadataProvider, Protocol): + """An object that provides access to package resources""" + + def get_resource_filename( + self, manager: ResourceManager, resource_name: str + ) -> str: + """Return a true filesystem path for `resource_name` + + `manager` must be a ``ResourceManager``""" + ... + + def get_resource_stream( + self, manager: ResourceManager, resource_name: str + ) -> _ResourceStream: + """Return a readable file-like object for `resource_name` + + `manager` must be a ``ResourceManager``""" + ... + + def get_resource_string( + self, manager: ResourceManager, resource_name: str + ) -> bytes: + """Return the contents of `resource_name` as :obj:`bytes` + + `manager` must be a ``ResourceManager``""" + ... + + def has_resource(self, resource_name: str) -> bool: + """Does the package contain the named resource?""" + ... + + def resource_isdir(self, resource_name: str) -> bool: + """Is the named resource a directory? (like ``os.path.isdir()``)""" + ... + + def resource_listdir(self, resource_name: str) -> list[str]: + """List of resource names in the directory (like ``os.listdir()``)""" + ... + + +class WorkingSet: + """A collection of active distributions on sys.path (or a similar list)""" + + def __init__(self, entries: Iterable[str] | None = None) -> None: + """Create working set from list of path entries (default=sys.path)""" + self.entries: list[str] = [] + self.entry_keys: dict[str | None, list[str]] = {} + self.by_key: dict[str, Distribution] = {} + self.normalized_to_canonical_keys: dict[str, str] = {} + self.callbacks: list[Callable[[Distribution], object]] = [] + + if entries is None: + entries = sys.path + + for entry in entries: + self.add_entry(entry) + + @classmethod + def _build_master(cls): + """ + Prepare the master working set. + """ + ws = cls() + try: + from __main__ import __requires__ + except ImportError: + # The main program does not list any requirements + return ws + + # ensure the requirements are met + try: + ws.require(__requires__) + except VersionConflict: + return cls._build_from_requirements(__requires__) + + return ws + + @classmethod + def _build_from_requirements(cls, req_spec): + """ + Build a working set from a requirement spec. Rewrites sys.path. + """ + # try it without defaults already on sys.path + # by starting with an empty path + ws = cls([]) + reqs = parse_requirements(req_spec) + dists = ws.resolve(reqs, Environment()) + for dist in dists: + ws.add(dist) + + # add any missing entries from sys.path + for entry in sys.path: + if entry not in ws.entries: + ws.add_entry(entry) + + # then copy back to sys.path + sys.path[:] = ws.entries + return ws + + def add_entry(self, entry: str) -> None: + """Add a path item to ``.entries``, finding any distributions on it + + ``find_distributions(entry, True)`` is used to find distributions + corresponding to the path entry, and they are added. `entry` is + always appended to ``.entries``, even if it is already present. + (This is because ``sys.path`` can contain the same value more than + once, and the ``.entries`` of the ``sys.path`` WorkingSet should always + equal ``sys.path``.) + """ + self.entry_keys.setdefault(entry, []) + self.entries.append(entry) + for dist in find_distributions(entry, True): + self.add(dist, entry, False) + + def __contains__(self, dist: Distribution) -> bool: + """True if `dist` is the active distribution for its project""" + return self.by_key.get(dist.key) == dist + + def find(self, req: Requirement) -> Distribution | None: + """Find a distribution matching requirement `req` + + If there is an active distribution for the requested project, this + returns it as long as it meets the version requirement specified by + `req`. But, if there is an active distribution for the project and it + does *not* meet the `req` requirement, ``VersionConflict`` is raised. + If there is no active distribution for the requested project, ``None`` + is returned. + """ + dist = self.by_key.get(req.key) + + if dist is None: + canonical_key = self.normalized_to_canonical_keys.get(req.key) + + if canonical_key is not None: + req.key = canonical_key + dist = self.by_key.get(canonical_key) + + if dist is not None and dist not in req: + # XXX add more info + raise VersionConflict(dist, req) + return dist + + def iter_entry_points( + self, group: str, name: str | None = None + ) -> Iterator[EntryPoint]: + """Yield entry point objects from `group` matching `name` + + If `name` is None, yields all entry points in `group` from all + distributions in the working set, otherwise only ones matching + both `group` and `name` are yielded (in distribution order). + """ + return ( + entry + for dist in self + for entry in dist.get_entry_map(group).values() + if name is None or name == entry.name + ) + + def run_script(self, requires: str, script_name: str) -> None: + """Locate distribution for `requires` and run `script_name` script""" + ns = sys._getframe(1).f_globals + name = ns['__name__'] + ns.clear() + ns['__name__'] = name + self.require(requires)[0].run_script(script_name, ns) + + def __iter__(self) -> Iterator[Distribution]: + """Yield distributions for non-duplicate projects in the working set + + The yield order is the order in which the items' path entries were + added to the working set. + """ + seen = set() + for item in self.entries: + if item not in self.entry_keys: + # workaround a cache issue + continue + + for key in self.entry_keys[item]: + if key not in seen: + seen.add(key) + yield self.by_key[key] + + def add( + self, + dist: Distribution, + entry: str | None = None, + insert: bool = True, + replace: bool = False, + ) -> None: + """Add `dist` to working set, associated with `entry` + + If `entry` is unspecified, it defaults to the ``.location`` of `dist`. + On exit from this routine, `entry` is added to the end of the working + set's ``.entries`` (if it wasn't already present). + + `dist` is only added to the working set if it's for a project that + doesn't already have a distribution in the set, unless `replace=True`. + If it's added, any callbacks registered with the ``subscribe()`` method + will be called. + """ + if insert: + dist.insert_on(self.entries, entry, replace=replace) + + if entry is None: + entry = dist.location + keys = self.entry_keys.setdefault(entry, []) + keys2 = self.entry_keys.setdefault(dist.location, []) + if not replace and dist.key in self.by_key: + # ignore hidden distros + return + + self.by_key[dist.key] = dist + normalized_name = packaging.utils.canonicalize_name(dist.key) + self.normalized_to_canonical_keys[normalized_name] = dist.key + if dist.key not in keys: + keys.append(dist.key) + if dist.key not in keys2: + keys2.append(dist.key) + self._added_new(dist) + + @overload + def resolve( + self, + requirements: Iterable[Requirement], + env: Environment | None, + installer: _StrictInstallerType[_DistributionT], + replace_conflicting: bool = False, + extras: tuple[str, ...] | None = None, + ) -> list[_DistributionT]: ... + @overload + def resolve( + self, + requirements: Iterable[Requirement], + env: Environment | None = None, + *, + installer: _StrictInstallerType[_DistributionT], + replace_conflicting: bool = False, + extras: tuple[str, ...] | None = None, + ) -> list[_DistributionT]: ... + @overload + def resolve( + self, + requirements: Iterable[Requirement], + env: Environment | None = None, + installer: _InstallerType | None = None, + replace_conflicting: bool = False, + extras: tuple[str, ...] | None = None, + ) -> list[Distribution]: ... + def resolve( + self, + requirements: Iterable[Requirement], + env: Environment | None = None, + installer: _InstallerType | None | _StrictInstallerType[_DistributionT] = None, + replace_conflicting: bool = False, + extras: tuple[str, ...] | None = None, + ) -> list[Distribution] | list[_DistributionT]: + """List all distributions needed to (recursively) meet `requirements` + + `requirements` must be a sequence of ``Requirement`` objects. `env`, + if supplied, should be an ``Environment`` instance. If + not supplied, it defaults to all distributions available within any + entry or distribution in the working set. `installer`, if supplied, + will be invoked with each requirement that cannot be met by an + already-installed distribution; it should return a ``Distribution`` or + ``None``. + + Unless `replace_conflicting=True`, raises a VersionConflict exception + if + any requirements are found on the path that have the correct name but + the wrong version. Otherwise, if an `installer` is supplied it will be + invoked to obtain the correct version of the requirement and activate + it. + + `extras` is a list of the extras to be used with these requirements. + This is important because extra requirements may look like `my_req; + extra = "my_extra"`, which would otherwise be interpreted as a purely + optional requirement. Instead, we want to be able to assert that these + requirements are truly required. + """ + + # set up the stack + requirements = list(requirements)[::-1] + # set of processed requirements + processed = set() + # key -> dist + best: dict[str, Distribution] = {} + to_activate: list[Distribution] = [] + + req_extras = _ReqExtras() + + # Mapping of requirement to set of distributions that required it; + # useful for reporting info about conflicts. + required_by = collections.defaultdict[Requirement, set[str]](set) + + while requirements: + # process dependencies breadth-first + req = requirements.pop(0) + if req in processed: + # Ignore cyclic or redundant dependencies + continue + + if not req_extras.markers_pass(req, extras): + continue + + dist = self._resolve_dist( + req, best, replace_conflicting, env, installer, required_by, to_activate + ) + + # push the new requirements onto the stack + new_requirements = dist.requires(req.extras)[::-1] + requirements.extend(new_requirements) + + # Register the new requirements needed by req + for new_requirement in new_requirements: + required_by[new_requirement].add(req.project_name) + req_extras[new_requirement] = req.extras + + processed.add(req) + + # return list of distros to activate + return to_activate + + def _resolve_dist( + self, req, best, replace_conflicting, env, installer, required_by, to_activate + ) -> Distribution: + dist = best.get(req.key) + if dist is None: + # Find the best distribution and add it to the map + dist = self.by_key.get(req.key) + if dist is None or (dist not in req and replace_conflicting): + ws = self + if env is None: + if dist is None: + env = Environment(self.entries) + else: + # Use an empty environment and workingset to avoid + # any further conflicts with the conflicting + # distribution + env = Environment([]) + ws = WorkingSet([]) + dist = best[req.key] = env.best_match( + req, ws, installer, replace_conflicting=replace_conflicting + ) + if dist is None: + requirers = required_by.get(req, None) + raise DistributionNotFound(req, requirers) + to_activate.append(dist) + if dist not in req: + # Oops, the "best" so far conflicts with a dependency + dependent_req = required_by[req] + raise VersionConflict(dist, req).with_context(dependent_req) + return dist + + @overload + def find_plugins( + self, + plugin_env: Environment, + full_env: Environment | None, + installer: _StrictInstallerType[_DistributionT], + fallback: bool = True, + ) -> tuple[list[_DistributionT], dict[Distribution, Exception]]: ... + @overload + def find_plugins( + self, + plugin_env: Environment, + full_env: Environment | None = None, + *, + installer: _StrictInstallerType[_DistributionT], + fallback: bool = True, + ) -> tuple[list[_DistributionT], dict[Distribution, Exception]]: ... + @overload + def find_plugins( + self, + plugin_env: Environment, + full_env: Environment | None = None, + installer: _InstallerType | None = None, + fallback: bool = True, + ) -> tuple[list[Distribution], dict[Distribution, Exception]]: ... + def find_plugins( + self, + plugin_env: Environment, + full_env: Environment | None = None, + installer: _InstallerType | None | _StrictInstallerType[_DistributionT] = None, + fallback: bool = True, + ) -> tuple[ + list[Distribution] | list[_DistributionT], + dict[Distribution, Exception], + ]: + """Find all activatable distributions in `plugin_env` + + Example usage:: + + distributions, errors = working_set.find_plugins( + Environment(plugin_dirlist) + ) + # add plugins+libs to sys.path + map(working_set.add, distributions) + # display errors + print('Could not load', errors) + + The `plugin_env` should be an ``Environment`` instance that contains + only distributions that are in the project's "plugin directory" or + directories. The `full_env`, if supplied, should be an ``Environment`` + contains all currently-available distributions. If `full_env` is not + supplied, one is created automatically from the ``WorkingSet`` this + method is called on, which will typically mean that every directory on + ``sys.path`` will be scanned for distributions. + + `installer` is a standard installer callback as used by the + ``resolve()`` method. The `fallback` flag indicates whether we should + attempt to resolve older versions of a plugin if the newest version + cannot be resolved. + + This method returns a 2-tuple: (`distributions`, `error_info`), where + `distributions` is a list of the distributions found in `plugin_env` + that were loadable, along with any other distributions that are needed + to resolve their dependencies. `error_info` is a dictionary mapping + unloadable plugin distributions to an exception instance describing the + error that occurred. Usually this will be a ``DistributionNotFound`` or + ``VersionConflict`` instance. + """ + + plugin_projects = list(plugin_env) + # scan project names in alphabetic order + plugin_projects.sort() + + error_info: dict[Distribution, Exception] = {} + distributions: dict[Distribution, Exception | None] = {} + + if full_env is None: + env = Environment(self.entries) + env += plugin_env + else: + env = full_env + plugin_env + + shadow_set = self.__class__([]) + # put all our entries in shadow_set + list(map(shadow_set.add, self)) + + for project_name in plugin_projects: + for dist in plugin_env[project_name]: + req = [dist.as_requirement()] + + try: + resolvees = shadow_set.resolve(req, env, installer) + + except ResolutionError as v: + # save error info + error_info[dist] = v + if fallback: + # try the next older version of project + continue + else: + # give up on this project, keep going + break + + else: + list(map(shadow_set.add, resolvees)) + distributions.update(dict.fromkeys(resolvees)) + + # success, no need to try any more versions of this project + break + + sorted_distributions = list(distributions) + sorted_distributions.sort() + + return sorted_distributions, error_info + + def require(self, *requirements: _NestedStr) -> list[Distribution]: + """Ensure that distributions matching `requirements` are activated + + `requirements` must be a string or a (possibly-nested) sequence + thereof, specifying the distributions and versions required. The + return value is a sequence of the distributions that needed to be + activated to fulfill the requirements; all relevant distributions are + included, even if they were already activated in this working set. + """ + needed = self.resolve(parse_requirements(requirements)) + + for dist in needed: + self.add(dist) + + return needed + + def subscribe( + self, callback: Callable[[Distribution], object], existing: bool = True + ) -> None: + """Invoke `callback` for all distributions + + If `existing=True` (default), + call on all existing ones, as well. + """ + if callback in self.callbacks: + return + self.callbacks.append(callback) + if not existing: + return + for dist in self: + callback(dist) + + def _added_new(self, dist) -> None: + for callback in self.callbacks: + callback(dist) + + def __getstate__( + self, + ) -> tuple[ + list[str], + dict[str | None, list[str]], + dict[str, Distribution], + dict[str, str], + list[Callable[[Distribution], object]], + ]: + return ( + self.entries[:], + self.entry_keys.copy(), + self.by_key.copy(), + self.normalized_to_canonical_keys.copy(), + self.callbacks[:], + ) + + def __setstate__(self, e_k_b_n_c) -> None: + entries, keys, by_key, normalized_to_canonical_keys, callbacks = e_k_b_n_c + self.entries = entries[:] + self.entry_keys = keys.copy() + self.by_key = by_key.copy() + self.normalized_to_canonical_keys = normalized_to_canonical_keys.copy() + self.callbacks = callbacks[:] + + +class _ReqExtras(dict["Requirement", tuple[str, ...]]): + """ + Map each requirement to the extras that demanded it. + """ + + def markers_pass(self, req: Requirement, extras: tuple[str, ...] | None = None): + """ + Evaluate markers for req against each extra that + demanded it. + + Return False if the req has a marker and fails + evaluation. Otherwise, return True. + """ + return not req.marker or any( + req.marker.evaluate({'extra': extra}) + for extra in self.get(req, ()) + (extras or ("",)) + ) + + +class Environment: + """Searchable snapshot of distributions on a search path""" + + def __init__( + self, + search_path: Iterable[str] | None = None, + platform: str | None = get_supported_platform(), + python: str | None = PY_MAJOR, + ) -> None: + """Snapshot distributions available on a search path + + Any distributions found on `search_path` are added to the environment. + `search_path` should be a sequence of ``sys.path`` items. If not + supplied, ``sys.path`` is used. + + `platform` is an optional string specifying the name of the platform + that platform-specific distributions must be compatible with. If + unspecified, it defaults to the current platform. `python` is an + optional string naming the desired version of Python (e.g. ``'3.6'``); + it defaults to the current version. + + You may explicitly set `platform` (and/or `python`) to ``None`` if you + wish to map *all* distributions, not just those compatible with the + running platform or Python version. + """ + self._distmap: dict[str, list[Distribution]] = {} + self.platform = platform + self.python = python + self.scan(search_path) + + def can_add(self, dist: Distribution) -> bool: + """Is distribution `dist` acceptable for this environment? + + The distribution must match the platform and python version + requirements specified when this environment was created, or False + is returned. + """ + py_compat = ( + self.python is None + or dist.py_version is None + or dist.py_version == self.python + ) + return py_compat and compatible_platforms(dist.platform, self.platform) + + def remove(self, dist: Distribution) -> None: + """Remove `dist` from the environment""" + self._distmap[dist.key].remove(dist) + + def scan(self, search_path: Iterable[str] | None = None) -> None: + """Scan `search_path` for distributions usable in this environment + + Any distributions found are added to the environment. + `search_path` should be a sequence of ``sys.path`` items. If not + supplied, ``sys.path`` is used. Only distributions conforming to + the platform/python version defined at initialization are added. + """ + if search_path is None: + search_path = sys.path + + for item in search_path: + for dist in find_distributions(item): + self.add(dist) + + def __getitem__(self, project_name: str) -> list[Distribution]: + """Return a newest-to-oldest list of distributions for `project_name` + + Uses case-insensitive `project_name` comparison, assuming all the + project's distributions use their project's name converted to all + lowercase as their key. + + """ + distribution_key = project_name.lower() + return self._distmap.get(distribution_key, []) + + def add(self, dist: Distribution) -> None: + """Add `dist` if we ``can_add()`` it and it has not already been added""" + if self.can_add(dist) and dist.has_version(): + dists = self._distmap.setdefault(dist.key, []) + if dist not in dists: + dists.append(dist) + dists.sort(key=operator.attrgetter('hashcmp'), reverse=True) + + @overload + def best_match( + self, + req: Requirement, + working_set: WorkingSet, + installer: _StrictInstallerType[_DistributionT], + replace_conflicting: bool = False, + ) -> _DistributionT: ... + @overload + def best_match( + self, + req: Requirement, + working_set: WorkingSet, + installer: _InstallerType | None = None, + replace_conflicting: bool = False, + ) -> Distribution | None: ... + def best_match( + self, + req: Requirement, + working_set: WorkingSet, + installer: _InstallerType | None | _StrictInstallerType[_DistributionT] = None, + replace_conflicting: bool = False, + ) -> Distribution | None: + """Find distribution best matching `req` and usable on `working_set` + + This calls the ``find(req)`` method of the `working_set` to see if a + suitable distribution is already active. (This may raise + ``VersionConflict`` if an unsuitable version of the project is already + active in the specified `working_set`.) If a suitable distribution + isn't active, this method returns the newest distribution in the + environment that meets the ``Requirement`` in `req`. If no suitable + distribution is found, and `installer` is supplied, then the result of + calling the environment's ``obtain(req, installer)`` method will be + returned. + """ + try: + dist = working_set.find(req) + except VersionConflict: + if not replace_conflicting: + raise + dist = None + if dist is not None: + return dist + for dist in self[req.key]: + if dist in req: + return dist + # try to download/install + return self.obtain(req, installer) + + @overload + def obtain( + self, + requirement: Requirement, + installer: _StrictInstallerType[_DistributionT], + ) -> _DistributionT: ... + @overload + def obtain( + self, + requirement: Requirement, + installer: Callable[[Requirement], None] | None = None, + ) -> None: ... + @overload + def obtain( + self, + requirement: Requirement, + installer: _InstallerType | None = None, + ) -> Distribution | None: ... + def obtain( + self, + requirement: Requirement, + installer: Callable[[Requirement], None] + | _InstallerType + | None + | _StrictInstallerType[_DistributionT] = None, + ) -> Distribution | None: + """Obtain a distribution matching `requirement` (e.g. via download) + + Obtain a distro that matches requirement (e.g. via download). In the + base ``Environment`` class, this routine just returns + ``installer(requirement)``, unless `installer` is None, in which case + None is returned instead. This method is a hook that allows subclasses + to attempt other ways of obtaining a distribution before falling back + to the `installer` argument.""" + return installer(requirement) if installer else None + + def __iter__(self) -> Iterator[str]: + """Yield the unique project names of the available distributions""" + for key in self._distmap.keys(): + if self[key]: + yield key + + def __iadd__(self, other: Distribution | Environment) -> Self: + """In-place addition of a distribution or environment""" + if isinstance(other, Distribution): + self.add(other) + elif isinstance(other, Environment): + for project in other: + for dist in other[project]: + self.add(dist) + else: + raise TypeError(f"Can't add {other!r} to environment") + return self + + def __add__(self, other: Distribution | Environment) -> Self: + """Add an environment or distribution to an environment""" + new = self.__class__([], platform=None, python=None) + for env in self, other: + new += env + return new + + +# XXX backward compatibility +AvailableDistributions = Environment + + +class ExtractionError(RuntimeError): + """An error occurred extracting a resource + + The following attributes are available from instances of this exception: + + manager + The resource manager that raised this exception + + cache_path + The base directory for resource extraction + + original_error + The exception instance that caused extraction to fail + """ + + manager: ResourceManager + cache_path: str + original_error: BaseException | None + + +class ResourceManager: + """Manage resource extraction and packages""" + + extraction_path: str | None = None + + def __init__(self) -> None: + # acts like a set + self.cached_files: dict[str, Literal[True]] = {} + + def resource_exists( + self, package_or_requirement: _PkgReqType, resource_name: str + ) -> bool: + """Does the named resource exist?""" + return get_provider(package_or_requirement).has_resource(resource_name) + + def resource_isdir( + self, package_or_requirement: _PkgReqType, resource_name: str + ) -> bool: + """Is the named resource an existing directory?""" + return get_provider(package_or_requirement).resource_isdir(resource_name) + + def resource_filename( + self, package_or_requirement: _PkgReqType, resource_name: str + ) -> str: + """Return a true filesystem path for specified resource""" + return get_provider(package_or_requirement).get_resource_filename( + self, resource_name + ) + + def resource_stream( + self, package_or_requirement: _PkgReqType, resource_name: str + ) -> _ResourceStream: + """Return a readable file-like object for specified resource""" + return get_provider(package_or_requirement).get_resource_stream( + self, resource_name + ) + + def resource_string( + self, package_or_requirement: _PkgReqType, resource_name: str + ) -> bytes: + """Return specified resource as :obj:`bytes`""" + return get_provider(package_or_requirement).get_resource_string( + self, resource_name + ) + + def resource_listdir( + self, package_or_requirement: _PkgReqType, resource_name: str + ) -> list[str]: + """List the contents of the named resource directory""" + return get_provider(package_or_requirement).resource_listdir(resource_name) + + def extraction_error(self) -> NoReturn: + """Give an error message for problems extracting file(s)""" + + old_exc = sys.exc_info()[1] + cache_path = self.extraction_path or get_default_cache() + + tmpl = textwrap.dedent( + """ + Can't extract file(s) to egg cache + + The following error occurred while trying to extract file(s) + to the Python egg cache: + + {old_exc} + + The Python egg cache directory is currently set to: + + {cache_path} + + Perhaps your account does not have write access to this directory? + You can change the cache directory by setting the PYTHON_EGG_CACHE + environment variable to point to an accessible directory. + """ + ).lstrip() + err = ExtractionError(tmpl.format(**locals())) + err.manager = self + err.cache_path = cache_path + err.original_error = old_exc + raise err + + def get_cache_path(self, archive_name: str, names: Iterable[StrPath] = ()) -> str: + """Return absolute location in cache for `archive_name` and `names` + + The parent directory of the resulting path will be created if it does + not already exist. `archive_name` should be the base filename of the + enclosing egg (which may not be the name of the enclosing zipfile!), + including its ".egg" extension. `names`, if provided, should be a + sequence of path name parts "under" the egg's extraction location. + + This method should only be called by resource providers that need to + obtain an extraction location, and only for names they intend to + extract, as it tracks the generated names for possible cleanup later. + """ + extract_path = self.extraction_path or get_default_cache() + target_path = os.path.join(extract_path, archive_name + '-tmp', *names) + try: + _bypass_ensure_directory(target_path) + except Exception: + self.extraction_error() + + self._warn_unsafe_extraction_path(extract_path) + + self.cached_files[target_path] = True + return target_path + + @staticmethod + def _warn_unsafe_extraction_path(path) -> None: + """ + If the default extraction path is overridden and set to an insecure + location, such as /tmp, it opens up an opportunity for an attacker to + replace an extracted file with an unauthorized payload. Warn the user + if a known insecure location is used. + + See Distribute #375 for more details. + """ + if os.name == 'nt' and not path.startswith(os.environ['windir']): + # On Windows, permissions are generally restrictive by default + # and temp directories are not writable by other users, so + # bypass the warning. + return + mode = os.stat(path).st_mode + if mode & stat.S_IWOTH or mode & stat.S_IWGRP: + msg = ( + "Extraction path is writable by group/others " + "and vulnerable to attack when " + "used with get_resource_filename ({path}). " + "Consider a more secure " + "location (set with .set_extraction_path or the " + "PYTHON_EGG_CACHE environment variable)." + ).format(**locals()) + warnings.warn(msg, UserWarning) + + def postprocess(self, tempname: StrOrBytesPath, filename: StrOrBytesPath) -> None: + """Perform any platform-specific postprocessing of `tempname` + + This is where Mac header rewrites should be done; other platforms don't + have anything special they should do. + + Resource providers should call this method ONLY after successfully + extracting a compressed resource. They must NOT call it on resources + that are already in the filesystem. + + `tempname` is the current (temporary) name of the file, and `filename` + is the name it will be renamed to by the caller after this routine + returns. + """ + + if os.name == 'posix': + # Make the resource executable + mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777 + os.chmod(tempname, mode) + + def set_extraction_path(self, path: str) -> None: + """Set the base path where resources will be extracted to, if needed. + + If you do not call this routine before any extractions take place, the + path defaults to the return value of ``get_default_cache()``. (Which + is based on the ``PYTHON_EGG_CACHE`` environment variable, with various + platform-specific fallbacks. See that routine's documentation for more + details.) + + Resources are extracted to subdirectories of this path based upon + information given by the ``IResourceProvider``. You may set this to a + temporary directory, but then you must call ``cleanup_resources()`` to + delete the extracted files when done. There is no guarantee that + ``cleanup_resources()`` will be able to remove all extracted files. + + (Note: you may not change the extraction path for a given resource + manager once resources have been extracted, unless you first call + ``cleanup_resources()``.) + """ + if self.cached_files: + raise ValueError("Can't change extraction path, files already extracted") + + self.extraction_path = path + + def cleanup_resources(self, force: bool = False) -> list[str]: + """ + Delete all extracted resource files and directories, returning a list + of the file and directory names that could not be successfully removed. + This function does not have any concurrency protection, so it should + generally only be called when the extraction path is a temporary + directory exclusive to a single process. This method is not + automatically called; you must call it explicitly or register it as an + ``atexit`` function if you wish to ensure cleanup of a temporary + directory used for extractions. + """ + # XXX + return [] + + +def get_default_cache() -> str: + """ + Return the ``PYTHON_EGG_CACHE`` environment variable + or a platform-relevant user cache dir for an app + named "Python-Eggs". + """ + return os.environ.get('PYTHON_EGG_CACHE') or _user_cache_dir(appname='Python-Eggs') + + +def safe_name(name: str) -> str: + """Convert an arbitrary string to a standard distribution name + + Any runs of non-alphanumeric/. characters are replaced with a single '-'. + """ + return re.sub('[^A-Za-z0-9.]+', '-', name) + + +def safe_version(version: str) -> str: + """ + Convert an arbitrary string to a standard version string + """ + try: + # normalize the version + return str(packaging.version.Version(version)) + except packaging.version.InvalidVersion: + version = version.replace(' ', '.') + return re.sub('[^A-Za-z0-9.]+', '-', version) + + +def _forgiving_version(version) -> str: + """Fallback when ``safe_version`` is not safe enough + >>> parse_version(_forgiving_version('0.23ubuntu1')) + + >>> parse_version(_forgiving_version('0.23-')) + + >>> parse_version(_forgiving_version('0.-_')) + + >>> parse_version(_forgiving_version('42.+?1')) + + >>> parse_version(_forgiving_version('hello world')) + + """ + version = version.replace(' ', '.') + match = _PEP440_FALLBACK.search(version) + if match: + safe = match["safe"] + rest = version[len(safe) :] + else: + safe = "0" + rest = version + local = f"sanitized.{_safe_segment(rest)}".strip(".") + return f"{safe}.dev0+{local}" + + +def _safe_segment(segment): + """Convert an arbitrary string into a safe segment""" + segment = re.sub('[^A-Za-z0-9.]+', '-', segment) + segment = re.sub('-[^A-Za-z0-9]+', '-', segment) + return re.sub(r'\.[^A-Za-z0-9]+', '.', segment).strip(".-") + + +def safe_extra(extra: str) -> str: + """Convert an arbitrary string to a standard 'extra' name + + Any runs of non-alphanumeric characters are replaced with a single '_', + and the result is always lowercased. + """ + return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower() + + +def to_filename(name: str) -> str: + """Convert a project or version name to its filename-escaped form + + Any '-' characters are currently replaced with '_'. + """ + return name.replace('-', '_') + + +def invalid_marker(text: str) -> SyntaxError | Literal[False]: + """ + Validate text as a PEP 508 environment marker; return an exception + if invalid or False otherwise. + """ + try: + evaluate_marker(text) + except SyntaxError as e: + e.filename = None + e.lineno = None + return e + return False + + +def evaluate_marker(text: str, extra: str | None = None) -> bool: + """ + Evaluate a PEP 508 environment marker. + Return a boolean indicating the marker result in this environment. + Raise SyntaxError if marker is invalid. + + This implementation uses the 'pyparsing' module. + """ + try: + marker = packaging.markers.Marker(text) + return marker.evaluate() + except packaging.markers.InvalidMarker as e: + raise SyntaxError(e) from e + + +class NullProvider: + """Try to implement resources and metadata for arbitrary PEP 302 loaders""" + + egg_name: str | None = None + egg_info: str | None = None + loader: LoaderProtocol | None = None + + def __init__(self, module: _ModuleLike) -> None: + self.loader = getattr(module, '__loader__', None) + self.module_path = os.path.dirname(getattr(module, '__file__', '')) + + def get_resource_filename( + self, manager: ResourceManager, resource_name: str + ) -> str: + return self._fn(self.module_path, resource_name) + + def get_resource_stream( + self, manager: ResourceManager, resource_name: str + ) -> BinaryIO: + return io.BytesIO(self.get_resource_string(manager, resource_name)) + + def get_resource_string( + self, manager: ResourceManager, resource_name: str + ) -> bytes: + return self._get(self._fn(self.module_path, resource_name)) + + def has_resource(self, resource_name: str) -> bool: + return self._has(self._fn(self.module_path, resource_name)) + + def _get_metadata_path(self, name): + return self._fn(self.egg_info, name) + + def has_metadata(self, name: str) -> bool: + if not self.egg_info: + return False + + path = self._get_metadata_path(name) + return self._has(path) + + def get_metadata(self, name: str) -> str: + if not self.egg_info: + return "" + path = self._get_metadata_path(name) + value = self._get(path) + try: + return value.decode('utf-8') + except UnicodeDecodeError as exc: + # Include the path in the error message to simplify + # troubleshooting, and without changing the exception type. + exc.reason += f' in {name} file at path: {path}' + raise + + def get_metadata_lines(self, name: str) -> Iterator[str]: + return yield_lines(self.get_metadata(name)) + + def resource_isdir(self, resource_name: str) -> bool: + return self._isdir(self._fn(self.module_path, resource_name)) + + def metadata_isdir(self, name: str) -> bool: + return bool(self.egg_info and self._isdir(self._fn(self.egg_info, name))) + + def resource_listdir(self, resource_name: str) -> list[str]: + return self._listdir(self._fn(self.module_path, resource_name)) + + def metadata_listdir(self, name: str) -> list[str]: + if self.egg_info: + return self._listdir(self._fn(self.egg_info, name)) + return [] + + def run_script(self, script_name: str, namespace: dict[str, Any]) -> None: + script = 'scripts/' + script_name + if not self.has_metadata(script): + raise ResolutionError( + "Script {script!r} not found in metadata at {self.egg_info!r}".format( + **locals() + ), + ) + + script_text = self.get_metadata(script).replace('\r\n', '\n') + script_text = script_text.replace('\r', '\n') + script_filename = self._fn(self.egg_info, script) + namespace['__file__'] = script_filename + if os.path.exists(script_filename): + source = _read_utf8_with_fallback(script_filename) + code = compile(source, script_filename, 'exec') + exec(code, namespace, namespace) + else: + from linecache import cache + + cache[script_filename] = ( + len(script_text), + 0, + script_text.split('\n'), + script_filename, + ) + script_code = compile(script_text, script_filename, 'exec') + exec(script_code, namespace, namespace) + + def _has(self, path) -> bool: + raise NotImplementedError( + "Can't perform this operation for unregistered loader type" + ) + + def _isdir(self, path) -> bool: + raise NotImplementedError( + "Can't perform this operation for unregistered loader type" + ) + + def _listdir(self, path) -> list[str]: + raise NotImplementedError( + "Can't perform this operation for unregistered loader type" + ) + + def _fn(self, base: str | None, resource_name: str): + if base is None: + raise TypeError( + "`base` parameter in `_fn` is `None`. Either override this method or check the parameter first." + ) + self._validate_resource_path(resource_name) + if resource_name: + return os.path.join(base, *resource_name.split('/')) + return base + + @staticmethod + def _validate_resource_path(path) -> None: + """ + Validate the resource paths according to the docs. + https://setuptools.pypa.io/en/latest/pkg_resources.html#basic-resource-access + + >>> warned = getfixture('recwarn') + >>> warnings.simplefilter('always') + >>> vrp = NullProvider._validate_resource_path + >>> vrp('foo/bar.txt') + >>> bool(warned) + False + >>> vrp('../foo/bar.txt') + >>> bool(warned) + True + >>> warned.clear() + >>> vrp('/foo/bar.txt') + >>> bool(warned) + True + >>> vrp('foo/../../bar.txt') + >>> bool(warned) + True + >>> warned.clear() + >>> vrp('foo/f../bar.txt') + >>> bool(warned) + False + + Windows path separators are straight-up disallowed. + >>> vrp(r'\\foo/bar.txt') + Traceback (most recent call last): + ... + ValueError: Use of .. or absolute path in a resource path \ +is not allowed. + + >>> vrp(r'C:\\foo/bar.txt') + Traceback (most recent call last): + ... + ValueError: Use of .. or absolute path in a resource path \ +is not allowed. + + Blank values are allowed + + >>> vrp('') + >>> bool(warned) + False + + Non-string values are not. + + >>> vrp(None) + Traceback (most recent call last): + ... + AttributeError: ... + """ + invalid = ( + os.path.pardir in path.split(posixpath.sep) + or posixpath.isabs(path) + or ntpath.isabs(path) + or path.startswith("\\") + ) + if not invalid: + return + + msg = "Use of .. or absolute path in a resource path is not allowed." + + # Aggressively disallow Windows absolute paths + if (path.startswith("\\") or ntpath.isabs(path)) and not posixpath.isabs(path): + raise ValueError(msg) + + # for compatibility, warn; in future + # raise ValueError(msg) + issue_warning( + msg[:-1] + " and will raise exceptions in a future release.", + DeprecationWarning, + ) + + def _get(self, path) -> bytes: + if hasattr(self.loader, 'get_data') and self.loader: + # Already checked get_data exists + return self.loader.get_data(path) # type: ignore[attr-defined] + raise NotImplementedError( + "Can't perform this operation for loaders without 'get_data()'" + ) + + +register_loader_type(object, NullProvider) + + +def _parents(path): + """ + yield all parents of path including path + """ + last = None + while path != last: + yield path + last = path + path, _ = os.path.split(path) + + +class EggProvider(NullProvider): + """Provider based on a virtual filesystem""" + + def __init__(self, module: _ModuleLike) -> None: + super().__init__(module) + self._setup_prefix() + + def _setup_prefix(self): + # Assume that metadata may be nested inside a "basket" + # of multiple eggs and use module_path instead of .archive. + eggs = filter(_is_egg_path, _parents(self.module_path)) + egg = next(eggs, None) + egg and self._set_egg(egg) + + def _set_egg(self, path: str) -> None: + self.egg_name = os.path.basename(path) + self.egg_info = os.path.join(path, 'EGG-INFO') + self.egg_root = path + + +class DefaultProvider(EggProvider): + """Provides access to package resources in the filesystem""" + + def _has(self, path) -> bool: + return os.path.exists(path) + + def _isdir(self, path) -> bool: + return os.path.isdir(path) + + def _listdir(self, path): + return os.listdir(path) + + def get_resource_stream( + self, manager: object, resource_name: str + ) -> io.BufferedReader: + return open(self._fn(self.module_path, resource_name), 'rb') + + def _get(self, path) -> bytes: + with open(path, 'rb') as stream: + return stream.read() + + @classmethod + def _register(cls) -> None: + loader_names = ( + 'SourceFileLoader', + 'SourcelessFileLoader', + ) + for name in loader_names: + loader_cls = getattr(importlib.machinery, name, type(None)) + register_loader_type(loader_cls, cls) + + +DefaultProvider._register() + + +class EmptyProvider(NullProvider): + """Provider that returns nothing for all requests""" + + # A special case, we don't want all Providers inheriting from NullProvider to have a potentially None module_path + module_path: str | None = None # type: ignore[assignment] + + _isdir = _has = lambda self, path: False + + def _get(self, path) -> bytes: + return b'' + + def _listdir(self, path): + return [] + + def __init__(self) -> None: + pass + + +empty_provider = EmptyProvider() + + +class ZipManifests(dict[str, "MemoizedZipManifests.manifest_mod"]): + """ + zip manifest builder + """ + + # `path` could be `StrPath | IO[bytes]` but that violates the LSP for `MemoizedZipManifests.load` + @classmethod + def build(cls, path: str) -> dict[str, zipfile.ZipInfo]: + """ + Build a dictionary similar to the zipimport directory + caches, except instead of tuples, store ZipInfo objects. + + Use a platform-specific path separator (os.sep) for the path keys + for compatibility with pypy on Windows. + """ + with zipfile.ZipFile(path) as zfile: + items = ( + ( + name.replace('/', os.sep), + zfile.getinfo(name), + ) + for name in zfile.namelist() + ) + return dict(items) + + load = build + + +class MemoizedZipManifests(ZipManifests): + """ + Memoized zipfile manifests. + """ + + class manifest_mod(NamedTuple): + manifest: dict[str, zipfile.ZipInfo] + mtime: float + + def load(self, path: str) -> dict[str, zipfile.ZipInfo]: # type: ignore[override] # ZipManifests.load is a classmethod + """ + Load a manifest at path or return a suitable manifest already loaded. + """ + path = os.path.normpath(path) + mtime = os.stat(path).st_mtime + + if path not in self or self[path].mtime != mtime: + manifest = self.build(path) + self[path] = self.manifest_mod(manifest, mtime) + + return self[path].manifest + + +class ZipProvider(EggProvider): + """Resource support for zips and eggs""" + + eagers: list[str] | None = None + _zip_manifests = MemoizedZipManifests() + # ZipProvider's loader should always be a zipimporter or equivalent + loader: zipimport.zipimporter + + def __init__(self, module: _ZipLoaderModule) -> None: + super().__init__(module) + self.zip_pre = self.loader.archive + os.sep + + def _zipinfo_name(self, fspath): + # Convert a virtual filename (full path to file) into a zipfile subpath + # usable with the zipimport directory cache for our target archive + fspath = fspath.rstrip(os.sep) + if fspath == self.loader.archive: + return '' + if fspath.startswith(self.zip_pre): + return fspath[len(self.zip_pre) :] + raise AssertionError(f"{fspath} is not a subpath of {self.zip_pre}") + + def _parts(self, zip_path): + # Convert a zipfile subpath into an egg-relative path part list. + # pseudo-fs path + fspath = self.zip_pre + zip_path + if fspath.startswith(self.egg_root + os.sep): + return fspath[len(self.egg_root) + 1 :].split(os.sep) + raise AssertionError(f"{fspath} is not a subpath of {self.egg_root}") + + @property + def zipinfo(self): + return self._zip_manifests.load(self.loader.archive) + + def get_resource_filename( + self, manager: ResourceManager, resource_name: str + ) -> str: + if not self.egg_name: + raise NotImplementedError( + "resource_filename() only supported for .egg, not .zip" + ) + # no need to lock for extraction, since we use temp names + zip_path = self._resource_to_zip(resource_name) + eagers = self._get_eager_resources() + if '/'.join(self._parts(zip_path)) in eagers: + for name in eagers: + self._extract_resource(manager, self._eager_to_zip(name)) + return self._extract_resource(manager, zip_path) + + @staticmethod + def _get_date_and_size(zip_stat): + size = zip_stat.file_size + # ymdhms+wday, yday, dst + date_time = zip_stat.date_time + (0, 0, -1) + # 1980 offset already done + timestamp = time.mktime(date_time) + return timestamp, size + + # FIXME: 'ZipProvider._extract_resource' is too complex (12) + def _extract_resource(self, manager: ResourceManager, zip_path) -> str: # noqa: C901 + if zip_path in self._index(): + for name in self._index()[zip_path]: + last = self._extract_resource(manager, os.path.join(zip_path, name)) + # return the extracted directory name + return os.path.dirname(last) + + timestamp, _size = self._get_date_and_size(self.zipinfo[zip_path]) + + if not WRITE_SUPPORT: + raise OSError( + '"os.rename" and "os.unlink" are not supported on this platform' + ) + try: + if not self.egg_name: + raise OSError( + '"egg_name" is empty. This likely means no egg could be found from the "module_path".' + ) + real_path = manager.get_cache_path(self.egg_name, self._parts(zip_path)) + + if self._is_current(real_path, zip_path): + return real_path + + outf, tmpnam = _mkstemp( + ".$extract", + dir=os.path.dirname(real_path), + ) + os.write(outf, self.loader.get_data(zip_path)) + os.close(outf) + utime(tmpnam, (timestamp, timestamp)) + manager.postprocess(tmpnam, real_path) + + try: + rename(tmpnam, real_path) + + except OSError: + if os.path.isfile(real_path): + if self._is_current(real_path, zip_path): + # the file became current since it was checked above, + # so proceed. + return real_path + # Windows, del old file and retry + elif os.name == 'nt': + unlink(real_path) + rename(tmpnam, real_path) + return real_path + raise + + except OSError: + # report a user-friendly error + manager.extraction_error() + + return real_path + + def _is_current(self, file_path, zip_path): + """ + Return True if the file_path is current for this zip_path + """ + timestamp, size = self._get_date_and_size(self.zipinfo[zip_path]) + if not os.path.isfile(file_path): + return False + stat = os.stat(file_path) + if stat.st_size != size or stat.st_mtime != timestamp: + return False + # check that the contents match + zip_contents = self.loader.get_data(zip_path) + with open(file_path, 'rb') as f: + file_contents = f.read() + return zip_contents == file_contents + + def _get_eager_resources(self): + if self.eagers is None: + eagers = [] + for name in ('native_libs.txt', 'eager_resources.txt'): + if self.has_metadata(name): + eagers.extend(self.get_metadata_lines(name)) + self.eagers = eagers + return self.eagers + + def _index(self): + try: + return self._dirindex + except AttributeError: + ind = {} + for path in self.zipinfo: + parts = path.split(os.sep) + while parts: + parent = os.sep.join(parts[:-1]) + if parent in ind: + ind[parent].append(parts[-1]) + break + else: + ind[parent] = [parts.pop()] + self._dirindex = ind + return ind + + def _has(self, fspath) -> bool: + zip_path = self._zipinfo_name(fspath) + return zip_path in self.zipinfo or zip_path in self._index() + + def _isdir(self, fspath) -> bool: + return self._zipinfo_name(fspath) in self._index() + + def _listdir(self, fspath): + return list(self._index().get(self._zipinfo_name(fspath), ())) + + def _eager_to_zip(self, resource_name: str): + return self._zipinfo_name(self._fn(self.egg_root, resource_name)) + + def _resource_to_zip(self, resource_name: str): + return self._zipinfo_name(self._fn(self.module_path, resource_name)) + + +register_loader_type(zipimport.zipimporter, ZipProvider) + + +class FileMetadata(EmptyProvider): + """Metadata handler for standalone PKG-INFO files + + Usage:: + + metadata = FileMetadata("/path/to/PKG-INFO") + + This provider rejects all data and metadata requests except for PKG-INFO, + which is treated as existing, and will be the contents of the file at + the provided location. + """ + + def __init__(self, path: StrPath) -> None: + self.path = path + + def _get_metadata_path(self, name): + return self.path + + def has_metadata(self, name: str) -> bool: + return name == 'PKG-INFO' and os.path.isfile(self.path) + + def get_metadata(self, name: str) -> str: + if name != 'PKG-INFO': + raise KeyError("No metadata except PKG-INFO is available") + + with open(self.path, encoding='utf-8', errors="replace") as f: + metadata = f.read() + self._warn_on_replacement(metadata) + return metadata + + def _warn_on_replacement(self, metadata) -> None: + replacement_char = '�' + if replacement_char in metadata: + tmpl = "{self.path} could not be properly decoded in UTF-8" + msg = tmpl.format(**locals()) + warnings.warn(msg) + + def get_metadata_lines(self, name: str) -> Iterator[str]: + return yield_lines(self.get_metadata(name)) + + +class PathMetadata(DefaultProvider): + """Metadata provider for egg directories + + Usage:: + + # Development eggs: + + egg_info = "/path/to/PackageName.egg-info" + base_dir = os.path.dirname(egg_info) + metadata = PathMetadata(base_dir, egg_info) + dist_name = os.path.splitext(os.path.basename(egg_info))[0] + dist = Distribution(basedir, project_name=dist_name, metadata=metadata) + + # Unpacked egg directories: + + egg_path = "/path/to/PackageName-ver-pyver-etc.egg" + metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO')) + dist = Distribution.from_filename(egg_path, metadata=metadata) + """ + + def __init__(self, path: str, egg_info: str) -> None: + self.module_path = path + self.egg_info = egg_info + + +class EggMetadata(ZipProvider): + """Metadata provider for .egg files""" + + def __init__(self, importer: zipimport.zipimporter) -> None: + """Create a metadata provider from a zipimporter""" + + self.zip_pre = importer.archive + os.sep + self.loader = importer + if importer.prefix: + self.module_path = os.path.join(importer.archive, importer.prefix) + else: + self.module_path = importer.archive + self._setup_prefix() + + +_distribution_finders: dict[type, _DistFinderType[Any]] = _declare_state( + 'dict', '_distribution_finders', {} +) + + +def register_finder( + importer_type: type[_T], distribution_finder: _DistFinderType[_T] +) -> None: + """Register `distribution_finder` to find distributions in sys.path items + + `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item + handler), and `distribution_finder` is a callable that, passed a path + item and the importer instance, yields ``Distribution`` instances found on + that path item. See ``pkg_resources.find_on_path`` for an example.""" + _distribution_finders[importer_type] = distribution_finder + + +def find_distributions(path_item: str, only: bool = False) -> Iterable[Distribution]: + """Yield distributions accessible via `path_item`""" + importer = get_importer(path_item) + finder = _find_adapter(_distribution_finders, importer) + return finder(importer, path_item, only) + + +def find_eggs_in_zip( + importer: zipimport.zipimporter, path_item: str, only: bool = False +) -> Iterator[Distribution]: + """ + Find eggs in zip files; possibly multiple nested eggs. + """ + if importer.archive.endswith('.whl'): + # wheels are not supported with this finder + # they don't have PKG-INFO metadata, and won't ever contain eggs + return + metadata = EggMetadata(importer) + if metadata.has_metadata('PKG-INFO'): + yield Distribution.from_filename(path_item, metadata=metadata) + if only: + # don't yield nested distros + return + for subitem in metadata.resource_listdir(''): + if _is_egg_path(subitem): + subpath = os.path.join(path_item, subitem) + dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath) + yield from dists + elif subitem.lower().endswith(('.dist-info', '.egg-info')): + subpath = os.path.join(path_item, subitem) + submeta = EggMetadata(zipimport.zipimporter(subpath)) + submeta.egg_info = subpath + yield Distribution.from_location(path_item, subitem, submeta) + + +register_finder(zipimport.zipimporter, find_eggs_in_zip) + + +def find_nothing( + importer: object | None, path_item: str | None, only: bool | None = False +): + return () + + +register_finder(object, find_nothing) + + +def find_on_path(importer: object | None, path_item, only=False): + """Yield distributions accessible on a sys.path directory""" + path_item = _normalize_cached(path_item) + + if _is_unpacked_egg(path_item): + yield Distribution.from_filename( + path_item, + metadata=PathMetadata(path_item, os.path.join(path_item, 'EGG-INFO')), + ) + return + + entries = (os.path.join(path_item, child) for child in safe_listdir(path_item)) + + # scan for .egg and .egg-info in directory + for entry in sorted(entries): + fullpath = os.path.join(path_item, entry) + factory = dist_factory(path_item, entry, only) + yield from factory(fullpath) + + +def dist_factory(path_item, entry, only): + """Return a dist_factory for the given entry.""" + lower = entry.lower() + is_egg_info = lower.endswith('.egg-info') + is_dist_info = lower.endswith('.dist-info') and os.path.isdir( + os.path.join(path_item, entry) + ) + is_meta = is_egg_info or is_dist_info + return ( + distributions_from_metadata + if is_meta + else find_distributions + if not only and _is_egg_path(entry) + else resolve_egg_link + if not only and lower.endswith('.egg-link') + else NoDists() + ) + + +class NoDists: + """ + >>> bool(NoDists()) + False + + >>> list(NoDists()('anything')) + [] + """ + + def __bool__(self) -> Literal[False]: + return False + + def __call__(self, fullpath: object): + return iter(()) + + +def safe_listdir(path: StrOrBytesPath): + """ + Attempt to list contents of path, but suppress some exceptions. + """ + try: + return os.listdir(path) + except (PermissionError, NotADirectoryError): + pass + except OSError as e: + # Ignore the directory if does not exist, not a directory or + # permission denied + if e.errno not in (errno.ENOTDIR, errno.EACCES, errno.ENOENT): + raise + return () + + +def distributions_from_metadata(path: str): + root = os.path.dirname(path) + if os.path.isdir(path): + if len(os.listdir(path)) == 0: + # empty metadata dir; skip + return + metadata: _MetadataType = PathMetadata(root, path) + else: + metadata = FileMetadata(path) + entry = os.path.basename(path) + yield Distribution.from_location( + root, + entry, + metadata, + precedence=DEVELOP_DIST, + ) + + +def non_empty_lines(path): + """ + Yield non-empty lines from file at path + """ + for line in _read_utf8_with_fallback(path).splitlines(): + line = line.strip() + if line: + yield line + + +def resolve_egg_link(path): + """ + Given a path to an .egg-link, resolve distributions + present in the referenced path. + """ + referenced_paths = non_empty_lines(path) + resolved_paths = ( + os.path.join(os.path.dirname(path), ref) for ref in referenced_paths + ) + dist_groups = map(find_distributions, resolved_paths) + return next(dist_groups, ()) + + +if hasattr(pkgutil, 'ImpImporter'): + register_finder(pkgutil.ImpImporter, find_on_path) + +register_finder(importlib.machinery.FileFinder, find_on_path) + +_namespace_handlers: dict[type, _NSHandlerType[Any]] = _declare_state( + 'dict', '_namespace_handlers', {} +) +_namespace_packages: dict[str | None, list[str]] = _declare_state( + 'dict', '_namespace_packages', {} +) + + +def register_namespace_handler( + importer_type: type[_T], namespace_handler: _NSHandlerType[_T] +) -> None: + """Register `namespace_handler` to declare namespace packages + + `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item + handler), and `namespace_handler` is a callable like this:: + + def namespace_handler(importer, path_entry, moduleName, module): + # return a path_entry to use for child packages + + Namespace handlers are only called if the importer object has already + agreed that it can handle the relevant path item, and they should only + return a subpath if the module __path__ does not already contain an + equivalent subpath. For an example namespace handler, see + ``pkg_resources.file_ns_handler``. + """ + _namespace_handlers[importer_type] = namespace_handler + + +def _handle_ns(packageName, path_item): + """Ensure that named package includes a subpath of path_item (if needed)""" + + importer = get_importer(path_item) + if importer is None: + return None + + # use find_spec (PEP 451) and fall-back to find_module (PEP 302) + try: + spec = importer.find_spec(packageName) + except AttributeError: + # capture warnings due to #1111 + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + loader = importer.find_module(packageName) + else: + loader = spec.loader if spec else None + + if loader is None: + return None + module = sys.modules.get(packageName) + if module is None: + module = sys.modules[packageName] = types.ModuleType(packageName) + module.__path__ = [] + _set_parent_ns(packageName) + elif not hasattr(module, '__path__'): + raise TypeError("Not a package:", packageName) + handler = _find_adapter(_namespace_handlers, importer) + subpath = handler(importer, path_item, packageName, module) + if subpath is not None: + path = module.__path__ + path.append(subpath) + importlib.import_module(packageName) + _rebuild_mod_path(path, packageName, module) + return subpath + + +def _rebuild_mod_path(orig_path, package_name, module: types.ModuleType) -> None: + """ + Rebuild module.__path__ ensuring that all entries are ordered + corresponding to their sys.path order + """ + sys_path = [_normalize_cached(p) for p in sys.path] + + def safe_sys_path_index(entry): + """ + Workaround for #520 and #513. + """ + try: + return sys_path.index(entry) + except ValueError: + return float('inf') + + def position_in_sys_path(path): + """ + Return the ordinal of the path based on its position in sys.path + """ + path_parts = path.split(os.sep) + module_parts = package_name.count('.') + 1 + parts = path_parts[:-module_parts] + return safe_sys_path_index(_normalize_cached(os.sep.join(parts))) + + new_path = sorted(orig_path, key=position_in_sys_path) + new_path = [_normalize_cached(p) for p in new_path] + + if isinstance(module.__path__, list): + module.__path__[:] = new_path + else: + module.__path__ = new_path + + +def declare_namespace(packageName: str) -> None: + """Declare that package 'packageName' is a namespace package""" + + msg = ( + f"Deprecated call to `pkg_resources.declare_namespace({packageName!r})`.\n" + "Implementing implicit namespace packages (as specified in PEP 420) " + "is preferred to `pkg_resources.declare_namespace`. " + "See https://setuptools.pypa.io/en/latest/references/" + "keywords.html#keyword-namespace-packages" + ) + warnings.warn(msg, DeprecationWarning, stacklevel=2) + + _imp.acquire_lock() + try: + if packageName in _namespace_packages: + return + + path: MutableSequence[str] = sys.path + parent, _, _ = packageName.rpartition('.') + + if parent: + declare_namespace(parent) + if parent not in _namespace_packages: + __import__(parent) + try: + path = sys.modules[parent].__path__ + except AttributeError as e: + raise TypeError("Not a package:", parent) from e + + # Track what packages are namespaces, so when new path items are added, + # they can be updated + _namespace_packages.setdefault(parent or None, []).append(packageName) + _namespace_packages.setdefault(packageName, []) + + for path_item in path: + # Ensure all the parent's path items are reflected in the child, + # if they apply + _handle_ns(packageName, path_item) + + finally: + _imp.release_lock() + + +def fixup_namespace_packages(path_item: str, parent: str | None = None) -> None: + """Ensure that previously-declared namespace packages include path_item""" + _imp.acquire_lock() + try: + for package in _namespace_packages.get(parent, ()): + subpath = _handle_ns(package, path_item) + if subpath: + fixup_namespace_packages(subpath, package) + finally: + _imp.release_lock() + + +def file_ns_handler( + importer: object, + path_item: StrPath, + packageName: str, + module: types.ModuleType, +): + """Compute an ns-package subpath for a filesystem or zipfile importer""" + + subpath = os.path.join(path_item, packageName.split('.')[-1]) + normalized = _normalize_cached(subpath) + for item in module.__path__: + if _normalize_cached(item) == normalized: + break + else: + # Only return the path if it's not already there + return subpath + + +if hasattr(pkgutil, 'ImpImporter'): + register_namespace_handler(pkgutil.ImpImporter, file_ns_handler) + +register_namespace_handler(zipimport.zipimporter, file_ns_handler) +register_namespace_handler(importlib.machinery.FileFinder, file_ns_handler) + + +def null_ns_handler( + importer: object, + path_item: str | None, + packageName: str | None, + module: _ModuleLike | None, +) -> None: + return None + + +register_namespace_handler(object, null_ns_handler) + + +@overload +def normalize_path(filename: StrPath) -> str: ... +@overload +def normalize_path(filename: BytesPath) -> bytes: ... +def normalize_path(filename: StrOrBytesPath) -> str | bytes: + """Normalize a file/dir name for comparison purposes""" + return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename)))) + + +def _cygwin_patch(filename: StrOrBytesPath): # pragma: nocover + """ + Contrary to POSIX 2008, on Cygwin, getcwd (3) contains + symlink components. Using + os.path.abspath() works around this limitation. A fix in os.getcwd() + would probably better, in Cygwin even more so, except + that this seems to be by design... + """ + return os.path.abspath(filename) if sys.platform == 'cygwin' else filename + + +if TYPE_CHECKING: + # https://github.com/python/mypy/issues/16261 + # https://github.com/python/typeshed/issues/6347 + @overload + def _normalize_cached(filename: StrPath) -> str: ... + @overload + def _normalize_cached(filename: BytesPath) -> bytes: ... + def _normalize_cached(filename: StrOrBytesPath) -> str | bytes: ... + +else: + + @functools.cache + def _normalize_cached(filename): + return normalize_path(filename) + + +def _is_egg_path(path): + """ + Determine if given path appears to be an egg. + """ + return _is_zip_egg(path) or _is_unpacked_egg(path) + + +def _is_zip_egg(path): + return ( + path.lower().endswith('.egg') + and os.path.isfile(path) + and zipfile.is_zipfile(path) + ) + + +def _is_unpacked_egg(path): + """ + Determine if given path appears to be an unpacked egg. + """ + return path.lower().endswith('.egg') and os.path.isfile( + os.path.join(path, 'EGG-INFO', 'PKG-INFO') + ) + + +def _set_parent_ns(packageName) -> None: + parts = packageName.split('.') + name = parts.pop() + if parts: + parent = '.'.join(parts) + setattr(sys.modules[parent], name, sys.modules[packageName]) + + +MODULE = re.compile(r"\w+(\.\w+)*$").match +EGG_NAME = re.compile( + r""" + (?P[^-]+) ( + -(?P[^-]+) ( + -py(?P[^-]+) ( + -(?P.+) + )? + )? + )? + """, + re.VERBOSE | re.IGNORECASE, +).match + + +class EntryPoint: + """Object representing an advertised importable object""" + + def __init__( + self, + name: str, + module_name: str, + attrs: Iterable[str] = (), + extras: Iterable[str] = (), + dist: Distribution | None = None, + ) -> None: + if not MODULE(module_name): + raise ValueError("Invalid module name", module_name) + self.name = name + self.module_name = module_name + self.attrs = tuple(attrs) + self.extras = tuple(extras) + self.dist = dist + + def __str__(self) -> str: + s = f"{self.name} = {self.module_name}" + if self.attrs: + s += ':' + '.'.join(self.attrs) + if self.extras: + extras = ','.join(self.extras) + s += f' [{extras}]' + return s + + def __repr__(self) -> str: + return f"EntryPoint.parse({str(self)!r})" + + @overload + def load( + self, + require: Literal[True] = True, + env: Environment | None = None, + installer: _InstallerType | None = None, + ) -> _ResolvedEntryPoint: ... + @overload + def load( + self, + require: Literal[False], + *args: Any, + **kwargs: Any, + ) -> _ResolvedEntryPoint: ... + def load( + self, + require: bool = True, + *args: Environment | _InstallerType | None, + **kwargs: Environment | _InstallerType | None, + ) -> _ResolvedEntryPoint: + """ + Require packages for this EntryPoint, then resolve it. + """ + if not require or args or kwargs: + warnings.warn( + "Parameters to load are deprecated. Call .resolve and " + ".require separately.", + PkgResourcesDeprecationWarning, + stacklevel=2, + ) + if require: + # We could pass `env` and `installer` directly, + # but keeping `*args` and `**kwargs` for backwards compatibility + self.require(*args, **kwargs) # type: ignore[arg-type] + return self.resolve() + + def resolve(self) -> _ResolvedEntryPoint: + """ + Resolve the entry point from its module and attrs. + """ + module = __import__(self.module_name, fromlist=['__name__'], level=0) + try: + return functools.reduce(getattr, self.attrs, module) + except AttributeError as exc: + raise ImportError(str(exc)) from exc + + def require( + self, + env: Environment | None = None, + installer: _InstallerType | None = None, + ) -> None: + if not self.dist: + error_cls = UnknownExtra if self.extras else AttributeError + raise error_cls("Can't require() without a distribution", self) + + # Get the requirements for this entry point with all its extras and + # then resolve them. We have to pass `extras` along when resolving so + # that the working set knows what extras we want. Otherwise, for + # dist-info distributions, the working set will assume that the + # requirements for that extra are purely optional and skip over them. + reqs = self.dist.requires(self.extras) + items = working_set.resolve(reqs, env, installer, extras=self.extras) + list(map(working_set.add, items)) + + pattern = re.compile( + r'\s*' + r'(?P.+?)\s*' + r'=\s*' + r'(?P[\w.]+)\s*' + r'(:\s*(?P[\w.]+))?\s*' + r'(?P\[.*\])?\s*$' + ) + + @classmethod + def parse(cls, src: str, dist: Distribution | None = None) -> Self: + """Parse a single entry point from string `src` + + Entry point syntax follows the form:: + + name = some.module:some.attr [extra1, extra2] + + The entry name and module name are required, but the ``:attrs`` and + ``[extras]`` parts are optional + """ + m = cls.pattern.match(src) + if not m: + msg = "EntryPoint must be in 'name=module:attrs [extras]' format" + raise ValueError(msg, src) + res = m.groupdict() + extras = cls._parse_extras(res['extras']) + attrs = res['attr'].split('.') if res['attr'] else () + return cls(res['name'], res['module'], attrs, extras, dist) + + @classmethod + def _parse_extras(cls, extras_spec): + if not extras_spec: + return () + req = Requirement.parse('x' + extras_spec) + if req.specs: + raise ValueError + return req.extras + + @classmethod + def parse_group( + cls, + group: str, + lines: _NestedStr, + dist: Distribution | None = None, + ) -> dict[str, Self]: + """Parse an entry point group""" + if not MODULE(group): + raise ValueError("Invalid group name", group) + this: dict[str, Self] = {} + for line in yield_lines(lines): + ep = cls.parse(line, dist) + if ep.name in this: + raise ValueError("Duplicate entry point", group, ep.name) + this[ep.name] = ep + return this + + @classmethod + def parse_map( + cls, + data: str | Iterable[str] | dict[str, str | Iterable[str]], + dist: Distribution | None = None, + ) -> dict[str, dict[str, Self]]: + """Parse a map of entry point groups""" + _data: Iterable[tuple[str | None, str | Iterable[str]]] + if isinstance(data, dict): + _data = data.items() + else: + _data = split_sections(data) + maps: dict[str, dict[str, Self]] = {} + for group, lines in _data: + if group is None: + if not lines: + continue + raise ValueError("Entry points must be listed in groups") + group = group.strip() + if group in maps: + raise ValueError("Duplicate group name", group) + maps[group] = cls.parse_group(group, lines, dist) + return maps + + +def _version_from_file(lines): + """ + Given an iterable of lines from a Metadata file, return + the value of the Version field, if present, or None otherwise. + """ + + def is_version_line(line): + return line.lower().startswith('version:') + + version_lines = filter(is_version_line, lines) + line = next(iter(version_lines), '') + _, _, value = line.partition(':') + return safe_version(value.strip()) or None + + +class Distribution: + """Wrap an actual or potential sys.path entry w/metadata""" + + PKG_INFO = 'PKG-INFO' + + def __init__( + self, + location: str | None = None, + metadata: _MetadataType = None, + project_name: str | None = None, + version: str | None = None, + py_version: str | None = PY_MAJOR, + platform: str | None = None, + precedence: int = EGG_DIST, + ) -> None: + self.project_name = safe_name(project_name or 'Unknown') + if version is not None: + self._version = safe_version(version) + self.py_version = py_version + self.platform = platform + self.location = location + self.precedence = precedence + self._provider = metadata or empty_provider + + @classmethod + def from_location( + cls, + location: str, + basename: StrPath, + metadata: _MetadataType = None, + **kw: int, # We could set `precedence` explicitly, but keeping this as `**kw` for full backwards and subclassing compatibility + ) -> Distribution: + project_name, version, py_version, platform = [None] * 4 + basename, ext = os.path.splitext(basename) + if ext.lower() in _distributionImpl: + cls = _distributionImpl[ext.lower()] + + match = EGG_NAME(basename) + if match: + project_name, version, py_version, platform = match.group( + 'name', 'ver', 'pyver', 'plat' + ) + return cls( + location, + metadata, + project_name=project_name, + version=version, + py_version=py_version, + platform=platform, + **kw, + )._reload_version() + + def _reload_version(self): + return self + + @property + def hashcmp(self): + return ( + self._forgiving_parsed_version, + self.precedence, + self.key, + self.location, + self.py_version or '', + self.platform or '', + ) + + def __hash__(self) -> int: + return hash(self.hashcmp) + + def __lt__(self, other: Distribution) -> bool: + return self.hashcmp < other.hashcmp + + def __le__(self, other: Distribution) -> bool: + return self.hashcmp <= other.hashcmp + + def __gt__(self, other: Distribution) -> bool: + return self.hashcmp > other.hashcmp + + def __ge__(self, other: Distribution) -> bool: + return self.hashcmp >= other.hashcmp + + def __eq__(self, other: object) -> bool: + if not isinstance(other, self.__class__): + # It's not a Distribution, so they are not equal + return False + return self.hashcmp == other.hashcmp + + def __ne__(self, other: object) -> bool: + return not self == other + + # These properties have to be lazy so that we don't have to load any + # metadata until/unless it's actually needed. (i.e., some distributions + # may not know their name or version without loading PKG-INFO) + + @property + def key(self): + try: + return self._key + except AttributeError: + self._key = key = self.project_name.lower() + return key + + @property + def parsed_version(self): + if not hasattr(self, "_parsed_version"): + try: + self._parsed_version = parse_version(self.version) + except packaging.version.InvalidVersion as ex: + info = f"(package: {self.project_name})" + if hasattr(ex, "add_note"): + ex.add_note(info) # PEP 678 + raise + raise packaging.version.InvalidVersion(f"{str(ex)} {info}") from None + + return self._parsed_version + + @property + def _forgiving_parsed_version(self): + try: + return self.parsed_version + except packaging.version.InvalidVersion as ex: + self._parsed_version = parse_version(_forgiving_version(self.version)) + + notes = "\n".join(getattr(ex, "__notes__", [])) # PEP 678 + msg = f"""!!\n\n + ************************************************************************* + {str(ex)}\n{notes} + + This is a long overdue deprecation. + For the time being, `pkg_resources` will use `{self._parsed_version}` + as a replacement to avoid breaking existing environments, + but no future compatibility is guaranteed. + + If you maintain package {self.project_name} you should implement + the relevant changes to adequate the project to PEP 440 immediately. + ************************************************************************* + \n\n!! + """ + warnings.warn(msg, DeprecationWarning) + + return self._parsed_version + + @property + def version(self): + try: + return self._version + except AttributeError as e: + version = self._get_version() + if version is None: + path = self._get_metadata_path_for_display(self.PKG_INFO) + msg = f"Missing 'Version:' header and/or {self.PKG_INFO} file at path: {path}" + raise ValueError(msg, self) from e + + return version + + @property + def _dep_map(self): + """ + A map of extra to its list of (direct) requirements + for this distribution, including the null extra. + """ + try: + return self.__dep_map + except AttributeError: + self.__dep_map = self._filter_extras(self._build_dep_map()) + return self.__dep_map + + @staticmethod + def _filter_extras( + dm: dict[str | None, list[Requirement]], + ) -> dict[str | None, list[Requirement]]: + """ + Given a mapping of extras to dependencies, strip off + environment markers and filter out any dependencies + not matching the markers. + """ + for extra in list(filter(None, dm)): + new_extra: str | None = extra + reqs = dm.pop(extra) + new_extra, _, marker = extra.partition(':') + fails_marker = marker and ( + invalid_marker(marker) or not evaluate_marker(marker) + ) + if fails_marker: + reqs = [] + new_extra = safe_extra(new_extra) or None + + dm.setdefault(new_extra, []).extend(reqs) + return dm + + def _build_dep_map(self): + dm = {} + for name in 'requires.txt', 'depends.txt': + for extra, reqs in split_sections(self._get_metadata(name)): + dm.setdefault(extra, []).extend(parse_requirements(reqs)) + return dm + + def requires(self, extras: Iterable[str] = ()) -> list[Requirement]: + """List of Requirements needed for this distro if `extras` are used""" + dm = self._dep_map + deps: list[Requirement] = [] + deps.extend(dm.get(None, ())) + for ext in extras: + try: + deps.extend(dm[safe_extra(ext)]) + except KeyError as e: + raise UnknownExtra(f"{self} has no such extra feature {ext!r}") from e + return deps + + def _get_metadata_path_for_display(self, name): + """ + Return the path to the given metadata file, if available. + """ + try: + # We need to access _get_metadata_path() on the provider object + # directly rather than through this class's __getattr__() + # since _get_metadata_path() is marked private. + path = self._provider._get_metadata_path(name) + + # Handle exceptions e.g. in case the distribution's metadata + # provider doesn't support _get_metadata_path(). + except Exception: + return '[could not detect]' + + return path + + def _get_metadata(self, name): + if self.has_metadata(name): + yield from self.get_metadata_lines(name) + + def _get_version(self): + lines = self._get_metadata(self.PKG_INFO) + return _version_from_file(lines) + + def activate(self, path: list[str] | None = None, replace: bool = False) -> None: + """Ensure distribution is importable on `path` (default=sys.path)""" + if path is None: + path = sys.path + self.insert_on(path, replace=replace) + if path is sys.path and self.location is not None: + fixup_namespace_packages(self.location) + for pkg in self._get_metadata('namespace_packages.txt'): + if pkg in sys.modules: + declare_namespace(pkg) + + def egg_name(self): + """Return what this distribution's standard .egg filename should be""" + filename = f"{to_filename(self.project_name)}-{to_filename(self.version)}-py{self.py_version or PY_MAJOR}" + + if self.platform: + filename += '-' + self.platform + return filename + + def __repr__(self) -> str: + if self.location: + return f"{self} ({self.location})" + else: + return str(self) + + def __str__(self) -> str: + try: + version = getattr(self, 'version', None) + except ValueError: + version = None + version = version or "[unknown version]" + return f"{self.project_name} {version}" + + def __getattr__(self, attr: str): + """Delegate all unrecognized public attributes to .metadata provider""" + if attr.startswith('_'): + raise AttributeError(attr) + return getattr(self._provider, attr) + + def __dir__(self): + return list( + set(super().__dir__()) + | set(attr for attr in self._provider.__dir__() if not attr.startswith('_')) + ) + + @classmethod + def from_filename( + cls, + filename: StrPath, + metadata: _MetadataType = None, + **kw: int, # We could set `precedence` explicitly, but keeping this as `**kw` for full backwards and subclassing compatibility + ) -> Distribution: + return cls.from_location( + _normalize_cached(filename), os.path.basename(filename), metadata, **kw + ) + + def as_requirement(self): + """Return a ``Requirement`` that matches this distribution exactly""" + if isinstance(self.parsed_version, packaging.version.Version): + spec = f"{self.project_name}=={self.parsed_version}" + else: + spec = f"{self.project_name}==={self.parsed_version}" + + return Requirement.parse(spec) + + def load_entry_point(self, group: str, name: str) -> _ResolvedEntryPoint: + """Return the `name` entry point of `group` or raise ImportError""" + ep = self.get_entry_info(group, name) + if ep is None: + raise ImportError(f"Entry point {(group, name)!r} not found") + return ep.load() + + @overload + def get_entry_map(self, group: None = None) -> dict[str, dict[str, EntryPoint]]: ... + @overload + def get_entry_map(self, group: str) -> dict[str, EntryPoint]: ... + def get_entry_map(self, group: str | None = None): + """Return the entry point map for `group`, or the full entry map""" + if not hasattr(self, "_ep_map"): + self._ep_map = EntryPoint.parse_map( + self._get_metadata('entry_points.txt'), self + ) + if group is not None: + return self._ep_map.get(group, {}) + return self._ep_map + + def get_entry_info(self, group: str, name: str) -> EntryPoint | None: + """Return the EntryPoint object for `group`+`name`, or ``None``""" + return self.get_entry_map(group).get(name) + + # FIXME: 'Distribution.insert_on' is too complex (13) + def insert_on( # noqa: C901 + self, + path: list[str], + loc=None, + replace: bool = False, + ) -> None: + """Ensure self.location is on path + + If replace=False (default): + - If location is already in path anywhere, do nothing. + - Else: + - If it's an egg and its parent directory is on path, + insert just ahead of the parent. + - Else: add to the end of path. + If replace=True: + - If location is already on path anywhere (not eggs) + or higher priority than its parent (eggs) + do nothing. + - Else: + - If it's an egg and its parent directory is on path, + insert just ahead of the parent, + removing any lower-priority entries. + - Else: add it to the front of path. + """ + + loc = loc or self.location + if not loc: + return + + nloc = _normalize_cached(loc) + bdir = os.path.dirname(nloc) + npath = [(p and _normalize_cached(p) or p) for p in path] + + for p, item in enumerate(npath): + if item == nloc: + if replace: + break + else: + # don't modify path (even removing duplicates) if + # found and not replace + return + elif item == bdir and self.precedence == EGG_DIST: + # if it's an .egg, give it precedence over its directory + # UNLESS it's already been added to sys.path and replace=False + if (not replace) and nloc in npath[p:]: + return + if path is sys.path: + self.check_version_conflict() + path.insert(p, loc) + npath.insert(p, nloc) + break + else: + if path is sys.path: + self.check_version_conflict() + if replace: + path.insert(0, loc) + else: + path.append(loc) + return + + # p is the spot where we found or inserted loc; now remove duplicates + while True: + try: + np = npath.index(nloc, p + 1) + except ValueError: + break + else: + del npath[np], path[np] + # ha! + p = np + + return + + def check_version_conflict(self): + if self.key == 'setuptools': + # ignore the inevitable setuptools self-conflicts :( + return + + nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt')) + loc = normalize_path(self.location) + for modname in self._get_metadata('top_level.txt'): + if ( + modname not in sys.modules + or modname in nsp + or modname in _namespace_packages + ): + continue + if modname in ('pkg_resources', 'setuptools', 'site'): + continue + fn = getattr(sys.modules[modname], '__file__', None) + if fn and ( + normalize_path(fn).startswith(loc) or fn.startswith(self.location) + ): + continue + issue_warning( + f"Module {modname} was already imported from {fn}, " + f"but {self.location} is being added to sys.path", + ) + + def has_version(self) -> bool: + try: + self.version + except ValueError: + issue_warning("Unbuilt egg for " + repr(self)) + return False + except SystemError: + # TODO: remove this except clause when python/cpython#103632 is fixed. + return False + return True + + def clone(self, **kw: str | int | IResourceProvider | None) -> Self: + """Copy this distribution, substituting in any changed keyword args""" + names = 'project_name version py_version platform location precedence' + for attr in names.split(): + kw.setdefault(attr, getattr(self, attr, None)) + kw.setdefault('metadata', self._provider) + # Unsafely unpacking. But keeping **kw for backwards and subclassing compatibility + return self.__class__(**kw) # type:ignore[arg-type] + + @property + def extras(self): + return [dep for dep in self._dep_map if dep] + + +class EggInfoDistribution(Distribution): + def _reload_version(self): + """ + Packages installed by distutils (e.g. numpy or scipy), + which uses an old safe_version, and so + their version numbers can get mangled when + converted to filenames (e.g., 1.11.0.dev0+2329eae to + 1.11.0.dev0_2329eae). These distributions will not be + parsed properly + downstream by Distribution and safe_version, so + take an extra step and try to get the version number from + the metadata file itself instead of the filename. + """ + md_version = self._get_version() + if md_version: + self._version = md_version + return self + + +class DistInfoDistribution(Distribution): + """ + Wrap an actual or potential sys.path entry + w/metadata, .dist-info style. + """ + + PKG_INFO = 'METADATA' + EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])") + + @property + def _parsed_pkg_info(self): + """Parse and cache metadata""" + try: + return self._pkg_info + except AttributeError: + metadata = self.get_metadata(self.PKG_INFO) + self._pkg_info = email.parser.Parser().parsestr(metadata) + return self._pkg_info + + @property + def _dep_map(self): + try: + return self.__dep_map + except AttributeError: + self.__dep_map = self._compute_dependencies() + return self.__dep_map + + def _compute_dependencies(self) -> dict[str | None, list[Requirement]]: + """Recompute this distribution's dependencies.""" + self.__dep_map: dict[str | None, list[Requirement]] = {None: []} + + reqs: list[Requirement] = [] + # Including any condition expressions + for req in self._parsed_pkg_info.get_all('Requires-Dist') or []: + reqs.extend(parse_requirements(req)) + + def reqs_for_extra(extra): + for req in reqs: + if not req.marker or req.marker.evaluate({'extra': extra}): + yield req + + common = types.MappingProxyType(dict.fromkeys(reqs_for_extra(None))) + self.__dep_map[None].extend(common) + + for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []: + s_extra = safe_extra(extra.strip()) + self.__dep_map[s_extra] = [ + r for r in reqs_for_extra(extra) if r not in common + ] + + return self.__dep_map + + +_distributionImpl = { + '.egg': Distribution, + '.egg-info': EggInfoDistribution, + '.dist-info': DistInfoDistribution, +} + + +def issue_warning(*args, **kw): + level = 1 + g = globals() + try: + # find the first stack frame that is *not* code in + # the pkg_resources module, to use for the warning + while sys._getframe(level).f_globals is g: + level += 1 + except ValueError: + pass + warnings.warn(stacklevel=level + 1, *args, **kw) + + +def parse_requirements(strs: _NestedStr) -> map[Requirement]: + """ + Yield ``Requirement`` objects for each specification in `strs`. + + `strs` must be a string, or a (possibly-nested) iterable thereof. + """ + return map(Requirement, join_continuation(map(drop_comment, yield_lines(strs)))) + + +class RequirementParseError(packaging.requirements.InvalidRequirement): + "Compatibility wrapper for InvalidRequirement" + + +class Requirement(packaging.requirements.Requirement): + # prefer variable length tuple to set (as found in + # packaging.requirements.Requirement) + extras: tuple[str, ...] # type: ignore[assignment] + + def __init__(self, requirement_string: str) -> None: + """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!""" + super().__init__(requirement_string) + self.unsafe_name = self.name + project_name = safe_name(self.name) + self.project_name, self.key = project_name, project_name.lower() + self.specs = [(spec.operator, spec.version) for spec in self.specifier] + self.extras = tuple(map(safe_extra, self.extras)) + self.hashCmp = ( + self.key, + self.url, + self.specifier, + frozenset(self.extras), + str(self.marker) if self.marker else None, + ) + self.__hash = hash(self.hashCmp) + + def __eq__(self, other: object) -> bool: + return isinstance(other, Requirement) and self.hashCmp == other.hashCmp + + def __ne__(self, other: object) -> bool: + return not self == other + + def __contains__( + self, item: Distribution | packaging.specifiers.UnparsedVersion + ) -> bool: + if isinstance(item, Distribution): + if item.key != self.key: + return False + + version = item.version + else: + version = item + + # Allow prereleases always in order to match the previous behavior of + # this method. In the future this should be smarter and follow PEP 440 + # more accurately. + return self.specifier.contains( + version, + prereleases=True, + ) + + def __hash__(self) -> int: + return self.__hash + + def __repr__(self) -> str: + return f"Requirement.parse({str(self)!r})" + + @staticmethod + def parse(s: str | Iterable[str]) -> Requirement: + (req,) = parse_requirements(s) + return req + + +def _always_object(classes): + """ + Ensure object appears in the mro even + for old-style classes. + """ + if object not in classes: + return classes + (object,) + return classes + + +def _find_adapter(registry: Mapping[type, _AdapterT], ob: object) -> _AdapterT: + """Return an adapter factory for `ob` from `registry`""" + types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob)))) + for t in types: + if t in registry: + return registry[t] + # _find_adapter would previously return None, and immediately be called. + # So we're raising a TypeError to keep backward compatibility if anyone depended on that behaviour. + raise TypeError(f"Could not find adapter for {registry} and {ob}") + + +def ensure_directory(path: StrOrBytesPath) -> None: + """Ensure that the parent directory of `path` exists""" + dirname = os.path.dirname(path) + os.makedirs(dirname, exist_ok=True) + + +def _bypass_ensure_directory(path) -> None: + """Sandbox-bypassing version of ensure_directory()""" + if not WRITE_SUPPORT: + raise OSError('"os.mkdir" not supported on this platform.') + dirname, filename = split(path) + if dirname and filename and not isdir(dirname): + _bypass_ensure_directory(dirname) + try: + mkdir(dirname, 0o755) + except FileExistsError: + pass + + +def split_sections(s: _NestedStr) -> Iterator[tuple[str | None, list[str]]]: + """Split a string or iterable thereof into (section, content) pairs + + Each ``section`` is a stripped version of the section header ("[section]") + and each ``content`` is a list of stripped lines excluding blank lines and + comment-only lines. If there are any such lines before the first section + header, they're returned in a first ``section`` of ``None``. + """ + section = None + content: list[str] = [] + for line in yield_lines(s): + if line.startswith("["): + if line.endswith("]"): + if section or content: + yield section, content + section = line[1:-1].strip() + content = [] + else: + raise ValueError("Invalid section heading", line) + else: + content.append(line) + + # wrap up last segment + yield section, content + + +def _mkstemp(*args, **kw): + old_open = os.open + try: + # temporarily bypass sandboxing + os.open = os_open + return tempfile.mkstemp(*args, **kw) + finally: + # and then put it back + os.open = old_open + + +# Silence the PEP440Warning by default, so that end users don't get hit by it +# randomly just because they use pkg_resources. We want to append the rule +# because we want earlier uses of filterwarnings to take precedence over this +# one. +warnings.filterwarnings("ignore", category=PEP440Warning, append=True) + + +class PkgResourcesDeprecationWarning(Warning): + """ + Base class for warning about deprecations in ``pkg_resources`` + + This class is not derived from ``DeprecationWarning``, and as such is + visible by default. + """ + + +# Ported from ``setuptools`` to avoid introducing an import inter-dependency: +_LOCALE_ENCODING = "locale" if sys.version_info >= (3, 10) else None + + +# This must go before calls to `_call_aside`. See https://github.com/pypa/setuptools/pull/4422 +def _read_utf8_with_fallback(file: str, fallback_encoding=_LOCALE_ENCODING) -> str: + """See setuptools.unicode_utils._read_utf8_with_fallback""" + try: + with open(file, "r", encoding="utf-8") as f: + return f.read() + except UnicodeDecodeError: # pragma: no cover + msg = f"""\ + ******************************************************************************** + `encoding="utf-8"` fails with {file!r}, trying `encoding={fallback_encoding!r}`. + + This fallback behaviour is considered **deprecated** and future versions of + `setuptools/pkg_resources` may not implement it. + + Please encode {file!r} with "utf-8" to ensure future builds will succeed. + + If this file was produced by `setuptools` itself, cleaning up the cached files + and re-building/re-installing the package with a newer version of `setuptools` + (e.g. by updating `build-system.requires` in its `pyproject.toml`) + might solve the problem. + ******************************************************************************** + """ + # TODO: Add a deadline? + # See comment in setuptools.unicode_utils._Utf8EncodingNeeded + warnings.warn(msg, PkgResourcesDeprecationWarning, stacklevel=2) + with open(file, "r", encoding=fallback_encoding) as f: + return f.read() + + +# from jaraco.functools 1.3 +def _call_aside(f, *args, **kwargs): + f(*args, **kwargs) + return f + + +@_call_aside +def _initialize(g=globals()) -> None: + "Set up global resource manager (deliberately not state-saved)" + manager = ResourceManager() + g['_manager'] = manager + g.update( + (name, getattr(manager, name)) + for name in dir(manager) + if not name.startswith('_') + ) + + +@_call_aside +def _initialize_master_working_set() -> None: + """ + Prepare the master working set and make the ``require()`` + API available. + + This function has explicit effects on the global state + of pkg_resources. It is intended to be invoked once at + the initialization of this module. + + Invocation by other packages is unsupported and done + at their own risk. + """ + working_set = _declare_state('object', 'working_set', WorkingSet._build_master()) + + require = working_set.require + iter_entry_points = working_set.iter_entry_points + add_activation_listener = working_set.subscribe + run_script = working_set.run_script + # backward compatibility + run_main = run_script + # Activate all distributions already on sys.path with replace=False and + # ensure that all distributions added to the working set in the future + # (e.g. by calling ``require()``) will get activated as well, + # with higher priority (replace=True). + tuple(dist.activate(replace=False) for dist in working_set) + add_activation_listener( + lambda dist: dist.activate(replace=True), + existing=False, + ) + working_set.entries = [] + # match order + list(map(working_set.add_entry, sys.path)) + globals().update(locals()) + + +if TYPE_CHECKING: + # All of these are set by the @_call_aside methods above + __resource_manager = ResourceManager() # Won't exist at runtime + resource_exists = __resource_manager.resource_exists + resource_isdir = __resource_manager.resource_isdir + resource_filename = __resource_manager.resource_filename + resource_stream = __resource_manager.resource_stream + resource_string = __resource_manager.resource_string + resource_listdir = __resource_manager.resource_listdir + set_extraction_path = __resource_manager.set_extraction_path + cleanup_resources = __resource_manager.cleanup_resources + + working_set = WorkingSet() + require = working_set.require + iter_entry_points = working_set.iter_entry_points + add_activation_listener = working_set.subscribe + run_script = working_set.run_script + run_main = run_script diff --git a/moondream/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..645bdadd744b44ed0b9f3b42073526f638907e6b --- /dev/null +++ b/moondream/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:191fd421685d609268ca1cf8363261f6cc101d545a1bc2b3ba669e28e3512464 +size 115599 diff --git a/moondream/lib/python3.10/site-packages/pkg_resources/tests/__init__.py b/moondream/lib/python3.10/site-packages/pkg_resources/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/moondream/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/__init__.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05399a72d830191b0a08b1c9dced0962439572fa Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_find_distributions.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_find_distributions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eda818fe6fe4637858e3e925b54918012fc2a316 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_find_distributions.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_resources.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_resources.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c513db5ec96dee613173162a116171eb99ab323 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_resources.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_working_set.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_working_set.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c982017a551fdcc0419e37556fad51df7ca7e769 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_working_set.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/__pycache__/setup.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/__pycache__/setup.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70f44220880239e161fc75da8e5b5d7b2ce51839 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/__pycache__/setup.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip b/moondream/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip new file mode 100644 index 0000000000000000000000000000000000000000..400905eecf0385de4d3b8e50b9892e1302b2b894 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01845c437f4655e3cf9cc4fc4e49cfd607431f22675e1b611129a90239f34822 +size 1809 diff --git a/moondream/lib/python3.10/site-packages/pkg_resources/tests/test_find_distributions.py b/moondream/lib/python3.10/site-packages/pkg_resources/tests/test_find_distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..301b36d6cdbf128f839db473aa6b191eba694937 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/pkg_resources/tests/test_find_distributions.py @@ -0,0 +1,56 @@ +import shutil +from pathlib import Path + +import pytest + +import pkg_resources + +TESTS_DATA_DIR = Path(__file__).parent / 'data' + + +class TestFindDistributions: + @pytest.fixture + def target_dir(self, tmpdir): + target_dir = tmpdir.mkdir('target') + # place a .egg named directory in the target that is not an egg: + target_dir.mkdir('not.an.egg') + return target_dir + + def test_non_egg_dir_named_egg(self, target_dir): + dists = pkg_resources.find_distributions(str(target_dir)) + assert not list(dists) + + def test_standalone_egg_directory(self, target_dir): + shutil.copytree( + TESTS_DATA_DIR / 'my-test-package_unpacked-egg', + target_dir, + dirs_exist_ok=True, + ) + dists = pkg_resources.find_distributions(str(target_dir)) + assert [dist.project_name for dist in dists] == ['my-test-package'] + dists = pkg_resources.find_distributions(str(target_dir), only=True) + assert not list(dists) + + def test_zipped_egg(self, target_dir): + shutil.copytree( + TESTS_DATA_DIR / 'my-test-package_zipped-egg', + target_dir, + dirs_exist_ok=True, + ) + dists = pkg_resources.find_distributions(str(target_dir)) + assert [dist.project_name for dist in dists] == ['my-test-package'] + dists = pkg_resources.find_distributions(str(target_dir), only=True) + assert not list(dists) + + def test_zipped_sdist_one_level_removed(self, target_dir): + shutil.copytree( + TESTS_DATA_DIR / 'my-test-package-zip', target_dir, dirs_exist_ok=True + ) + dists = pkg_resources.find_distributions( + str(target_dir / "my-test-package.zip") + ) + assert [dist.project_name for dist in dists] == ['my-test-package'] + dists = pkg_resources.find_distributions( + str(target_dir / "my-test-package.zip"), only=True + ) + assert not list(dists) diff --git a/moondream/lib/python3.10/site-packages/pkg_resources/tests/test_integration_zope_interface.py b/moondream/lib/python3.10/site-packages/pkg_resources/tests/test_integration_zope_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..4e37c3401b50c9f7387647303990887c7ce670f5 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/pkg_resources/tests/test_integration_zope_interface.py @@ -0,0 +1,54 @@ +import platform +from inspect import cleandoc + +import jaraco.path +import pytest + +pytestmark = pytest.mark.integration + + +# For the sake of simplicity this test uses fixtures defined in +# `setuptools.test.fixtures`, +# and it also exercise conditions considered deprecated... +# So if needed this test can be deleted. +@pytest.mark.skipif( + platform.system() != "Linux", + reason="only demonstrated to fail on Linux in #4399", +) +def test_interop_pkg_resources_iter_entry_points(tmp_path, venv): + """ + Importing pkg_resources.iter_entry_points on console_scripts + seems to cause trouble with zope-interface, when deprecates installation method + is used. See #4399. + """ + project = { + "pkg": { + "foo.py": cleandoc( + """ + from pkg_resources import iter_entry_points + + def bar(): + print("Print me if you can") + """ + ), + "setup.py": cleandoc( + """ + from setuptools import setup, find_packages + + setup( + install_requires=["zope-interface==6.4.post2"], + entry_points={ + "console_scripts": [ + "foo=foo:bar", + ], + }, + ) + """ + ), + } + } + jaraco.path.build(project, prefix=tmp_path) + cmd = ["pip", "install", "-e", ".", "--no-use-pep517"] + venv.run(cmd, cwd=tmp_path / "pkg") # Needs this version of pkg_resources installed + out = venv.run(["foo"]) + assert "Print me if you can" in out diff --git a/moondream/lib/python3.10/site-packages/pkg_resources/tests/test_markers.py b/moondream/lib/python3.10/site-packages/pkg_resources/tests/test_markers.py new file mode 100644 index 0000000000000000000000000000000000000000..9306d5b3483e8913b4a04d702091fb5efbc3f444 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/pkg_resources/tests/test_markers.py @@ -0,0 +1,8 @@ +from unittest import mock + +from pkg_resources import evaluate_marker + + +@mock.patch('platform.python_version', return_value='2.7.10') +def test_ordering(python_version_mock): + assert evaluate_marker("python_full_version > '2.7.3'") is True diff --git a/moondream/lib/python3.10/site-packages/pkg_resources/tests/test_pkg_resources.py b/moondream/lib/python3.10/site-packages/pkg_resources/tests/test_pkg_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..0f696e85026ff81873962d398c7ebdd112373322 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/pkg_resources/tests/test_pkg_resources.py @@ -0,0 +1,427 @@ +from __future__ import annotations + +import builtins +import datetime +import os +import plistlib +import stat +import subprocess +import sys +import tempfile +import zipfile +from unittest import mock + +import pytest + +import pkg_resources +from pkg_resources import DistInfoDistribution, Distribution, EggInfoDistribution + +import distutils.command.install_egg_info +import distutils.dist + + +class EggRemover(str): + def __call__(self): + if self in sys.path: + sys.path.remove(self) + if os.path.exists(self): + os.remove(self) + + +class TestZipProvider: + finalizers: list[EggRemover] = [] + + ref_time = datetime.datetime(2013, 5, 12, 13, 25, 0) + "A reference time for a file modification" + + @classmethod + def setup_class(cls): + "create a zip egg and add it to sys.path" + egg = tempfile.NamedTemporaryFile(suffix='.egg', delete=False) + zip_egg = zipfile.ZipFile(egg, 'w') + zip_info = zipfile.ZipInfo() + zip_info.filename = 'mod.py' + zip_info.date_time = cls.ref_time.timetuple() + zip_egg.writestr(zip_info, 'x = 3\n') + zip_info = zipfile.ZipInfo() + zip_info.filename = 'data.dat' + zip_info.date_time = cls.ref_time.timetuple() + zip_egg.writestr(zip_info, 'hello, world!') + zip_info = zipfile.ZipInfo() + zip_info.filename = 'subdir/mod2.py' + zip_info.date_time = cls.ref_time.timetuple() + zip_egg.writestr(zip_info, 'x = 6\n') + zip_info = zipfile.ZipInfo() + zip_info.filename = 'subdir/data2.dat' + zip_info.date_time = cls.ref_time.timetuple() + zip_egg.writestr(zip_info, 'goodbye, world!') + zip_egg.close() + egg.close() + + sys.path.append(egg.name) + subdir = os.path.join(egg.name, 'subdir') + sys.path.append(subdir) + cls.finalizers.append(EggRemover(subdir)) + cls.finalizers.append(EggRemover(egg.name)) + + @classmethod + def teardown_class(cls): + for finalizer in cls.finalizers: + finalizer() + + def test_resource_listdir(self): + import mod # pyright: ignore[reportMissingImports] # Temporary package for test + + zp = pkg_resources.ZipProvider(mod) + + expected_root = ['data.dat', 'mod.py', 'subdir'] + assert sorted(zp.resource_listdir('')) == expected_root + + expected_subdir = ['data2.dat', 'mod2.py'] + assert sorted(zp.resource_listdir('subdir')) == expected_subdir + assert sorted(zp.resource_listdir('subdir/')) == expected_subdir + + assert zp.resource_listdir('nonexistent') == [] + assert zp.resource_listdir('nonexistent/') == [] + + import mod2 # pyright: ignore[reportMissingImports] # Temporary package for test + + zp2 = pkg_resources.ZipProvider(mod2) + + assert sorted(zp2.resource_listdir('')) == expected_subdir + + assert zp2.resource_listdir('subdir') == [] + assert zp2.resource_listdir('subdir/') == [] + + def test_resource_filename_rewrites_on_change(self): + """ + If a previous call to get_resource_filename has saved the file, but + the file has been subsequently mutated with different file of the + same size and modification time, it should not be overwritten on a + subsequent call to get_resource_filename. + """ + import mod # pyright: ignore[reportMissingImports] # Temporary package for test + + manager = pkg_resources.ResourceManager() + zp = pkg_resources.ZipProvider(mod) + filename = zp.get_resource_filename(manager, 'data.dat') + actual = datetime.datetime.fromtimestamp(os.stat(filename).st_mtime) + assert actual == self.ref_time + f = open(filename, 'w', encoding="utf-8") + f.write('hello, world?') + f.close() + ts = self.ref_time.timestamp() + os.utime(filename, (ts, ts)) + filename = zp.get_resource_filename(manager, 'data.dat') + with open(filename, encoding="utf-8") as f: + assert f.read() == 'hello, world!' + manager.cleanup_resources() + + +class TestResourceManager: + def test_get_cache_path(self): + mgr = pkg_resources.ResourceManager() + path = mgr.get_cache_path('foo') + type_ = str(type(path)) + message = "Unexpected type from get_cache_path: " + type_ + assert isinstance(path, str), message + + def test_get_cache_path_race(self, tmpdir): + # Patch to os.path.isdir to create a race condition + def patched_isdir(dirname, unpatched_isdir=pkg_resources.isdir): + patched_isdir.dirnames.append(dirname) + + was_dir = unpatched_isdir(dirname) + if not was_dir: + os.makedirs(dirname) + return was_dir + + patched_isdir.dirnames = [] + + # Get a cache path with a "race condition" + mgr = pkg_resources.ResourceManager() + mgr.set_extraction_path(str(tmpdir)) + + archive_name = os.sep.join(('foo', 'bar', 'baz')) + with mock.patch.object(pkg_resources, 'isdir', new=patched_isdir): + mgr.get_cache_path(archive_name) + + # Because this test relies on the implementation details of this + # function, these assertions are a sentinel to ensure that the + # test suite will not fail silently if the implementation changes. + called_dirnames = patched_isdir.dirnames + assert len(called_dirnames) == 2 + assert called_dirnames[0].split(os.sep)[-2:] == ['foo', 'bar'] + assert called_dirnames[1].split(os.sep)[-1:] == ['foo'] + + """ + Tests to ensure that pkg_resources runs independently from setuptools. + """ + + def test_setuptools_not_imported(self): + """ + In a separate Python environment, import pkg_resources and assert + that action doesn't cause setuptools to be imported. + """ + lines = ( + 'import pkg_resources', + 'import sys', + ('assert "setuptools" not in sys.modules, "setuptools was imported"'), + ) + cmd = [sys.executable, '-c', '; '.join(lines)] + subprocess.check_call(cmd) + + +def make_test_distribution(metadata_path, metadata): + """ + Make a test Distribution object, and return it. + + :param metadata_path: the path to the metadata file that should be + created. This should be inside a distribution directory that should + also be created. For example, an argument value might end with + ".dist-info/METADATA". + :param metadata: the desired contents of the metadata file, as bytes. + """ + dist_dir = os.path.dirname(metadata_path) + os.mkdir(dist_dir) + with open(metadata_path, 'wb') as f: + f.write(metadata) + dists = list(pkg_resources.distributions_from_metadata(dist_dir)) + (dist,) = dists + + return dist + + +def test_get_metadata__bad_utf8(tmpdir): + """ + Test a metadata file with bytes that can't be decoded as utf-8. + """ + filename = 'METADATA' + # Convert the tmpdir LocalPath object to a string before joining. + metadata_path = os.path.join(str(tmpdir), 'foo.dist-info', filename) + # Encode a non-ascii string with the wrong encoding (not utf-8). + metadata = 'née'.encode('iso-8859-1') + dist = make_test_distribution(metadata_path, metadata=metadata) + + with pytest.raises(UnicodeDecodeError) as excinfo: + dist.get_metadata(filename) + + exc = excinfo.value + actual = str(exc) + expected = ( + # The error message starts with "'utf-8' codec ..." However, the + # spelling of "utf-8" can vary (e.g. "utf8") so we don't include it + "codec can't decode byte 0xe9 in position 1: " + 'invalid continuation byte in METADATA file at path: ' + ) + assert expected in actual, f'actual: {actual}' + assert actual.endswith(metadata_path), f'actual: {actual}' + + +def make_distribution_no_version(tmpdir, basename): + """ + Create a distribution directory with no file containing the version. + """ + dist_dir = tmpdir / basename + dist_dir.ensure_dir() + # Make the directory non-empty so distributions_from_metadata() + # will detect it and yield it. + dist_dir.join('temp.txt').ensure() + + dists = list(pkg_resources.distributions_from_metadata(dist_dir)) + assert len(dists) == 1 + (dist,) = dists + + return dist, dist_dir + + +@pytest.mark.parametrize( + ("suffix", "expected_filename", "expected_dist_type"), + [ + ('egg-info', 'PKG-INFO', EggInfoDistribution), + ('dist-info', 'METADATA', DistInfoDistribution), + ], +) +@pytest.mark.xfail( + sys.version_info[:2] == (3, 12) and sys.version_info.releaselevel != 'final', + reason="https://github.com/python/cpython/issues/103632", +) +def test_distribution_version_missing( + tmpdir, suffix, expected_filename, expected_dist_type +): + """ + Test Distribution.version when the "Version" header is missing. + """ + basename = f'foo.{suffix}' + dist, dist_dir = make_distribution_no_version(tmpdir, basename) + + expected_text = ( + f"Missing 'Version:' header and/or {expected_filename} file at path: " + ) + metadata_path = os.path.join(dist_dir, expected_filename) + + # Now check the exception raised when the "version" attribute is accessed. + with pytest.raises(ValueError) as excinfo: + dist.version + + err = str(excinfo.value) + # Include a string expression after the assert so the full strings + # will be visible for inspection on failure. + assert expected_text in err, str((expected_text, err)) + + # Also check the args passed to the ValueError. + msg, dist = excinfo.value.args + assert expected_text in msg + # Check that the message portion contains the path. + assert metadata_path in msg, str((metadata_path, msg)) + assert type(dist) is expected_dist_type + + +@pytest.mark.xfail( + sys.version_info[:2] == (3, 12) and sys.version_info.releaselevel != 'final', + reason="https://github.com/python/cpython/issues/103632", +) +def test_distribution_version_missing_undetected_path(): + """ + Test Distribution.version when the "Version" header is missing and + the path can't be detected. + """ + # Create a Distribution object with no metadata argument, which results + # in an empty metadata provider. + dist = Distribution('/foo') + with pytest.raises(ValueError) as excinfo: + dist.version + + msg, dist = excinfo.value.args + expected = ( + "Missing 'Version:' header and/or PKG-INFO file at path: [could not detect]" + ) + assert msg == expected + + +@pytest.mark.parametrize('only', [False, True]) +def test_dist_info_is_not_dir(tmp_path, only): + """Test path containing a file with dist-info extension.""" + dist_info = tmp_path / 'foobar.dist-info' + dist_info.touch() + assert not pkg_resources.dist_factory(str(tmp_path), str(dist_info), only) + + +def test_macos_vers_fallback(monkeypatch, tmp_path): + """Regression test for pkg_resources._macos_vers""" + orig_open = builtins.open + + # Pretend we need to use the plist file + monkeypatch.setattr('platform.mac_ver', mock.Mock(return_value=('', (), ''))) + + # Create fake content for the fake plist file + with open(tmp_path / 'fake.plist', 'wb') as fake_file: + plistlib.dump({"ProductVersion": "11.4"}, fake_file) + + # Pretend the fake file exists + monkeypatch.setattr('os.path.exists', mock.Mock(return_value=True)) + + def fake_open(file, *args, **kwargs): + return orig_open(tmp_path / 'fake.plist', *args, **kwargs) + + # Ensure that the _macos_vers works correctly + with mock.patch('builtins.open', mock.Mock(side_effect=fake_open)) as m: + pkg_resources._macos_vers.cache_clear() + assert pkg_resources._macos_vers() == ["11", "4"] + pkg_resources._macos_vers.cache_clear() + + m.assert_called() + + +class TestDeepVersionLookupDistutils: + @pytest.fixture + def env(self, tmpdir): + """ + Create a package environment, similar to a virtualenv, + in which packages are installed. + """ + + class Environment(str): + pass + + env = Environment(tmpdir) + tmpdir.chmod(stat.S_IRWXU) + subs = 'home', 'lib', 'scripts', 'data', 'egg-base' + env.paths = dict((dirname, str(tmpdir / dirname)) for dirname in subs) + list(map(os.mkdir, env.paths.values())) + return env + + def create_foo_pkg(self, env, version): + """ + Create a foo package installed (distutils-style) to env.paths['lib'] + as version. + """ + ld = "This package has unicode metadata! ❄" + attrs = dict(name='foo', version=version, long_description=ld) + dist = distutils.dist.Distribution(attrs) + iei_cmd = distutils.command.install_egg_info.install_egg_info(dist) + iei_cmd.initialize_options() + iei_cmd.install_dir = env.paths['lib'] + iei_cmd.finalize_options() + iei_cmd.run() + + def test_version_resolved_from_egg_info(self, env): + version = '1.11.0.dev0+2329eae' + self.create_foo_pkg(env, version) + + # this requirement parsing will raise a VersionConflict unless the + # .egg-info file is parsed (see #419 on BitBucket) + req = pkg_resources.Requirement.parse('foo>=1.9') + dist = pkg_resources.WorkingSet([env.paths['lib']]).find(req) + assert dist.version == version + + @pytest.mark.parametrize( + ("unnormalized", "normalized"), + [ + ('foo', 'foo'), + ('foo/', 'foo'), + ('foo/bar', 'foo/bar'), + ('foo/bar/', 'foo/bar'), + ], + ) + def test_normalize_path_trailing_sep(self, unnormalized, normalized): + """Ensure the trailing slash is cleaned for path comparison. + + See pypa/setuptools#1519. + """ + result_from_unnormalized = pkg_resources.normalize_path(unnormalized) + result_from_normalized = pkg_resources.normalize_path(normalized) + assert result_from_unnormalized == result_from_normalized + + @pytest.mark.skipif( + os.path.normcase('A') != os.path.normcase('a'), + reason='Testing case-insensitive filesystems.', + ) + @pytest.mark.parametrize( + ("unnormalized", "normalized"), + [ + ('MiXeD/CasE', 'mixed/case'), + ], + ) + def test_normalize_path_normcase(self, unnormalized, normalized): + """Ensure mixed case is normalized on case-insensitive filesystems.""" + result_from_unnormalized = pkg_resources.normalize_path(unnormalized) + result_from_normalized = pkg_resources.normalize_path(normalized) + assert result_from_unnormalized == result_from_normalized + + @pytest.mark.skipif( + os.path.sep != '\\', + reason='Testing systems using backslashes as path separators.', + ) + @pytest.mark.parametrize( + ("unnormalized", "expected"), + [ + ('forward/slash', 'forward\\slash'), + ('forward/slash/', 'forward\\slash'), + ('backward\\slash\\', 'backward\\slash'), + ], + ) + def test_normalize_path_backslash_sep(self, unnormalized, expected): + """Ensure path seps are cleaned on backslash path sep systems.""" + result = pkg_resources.normalize_path(unnormalized) + assert result.endswith(expected)