Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- shared/package-files/06/0601c8a246923a8de7c099463bf71a247cf7ee7eb2a00f0678cf578e7e333297/__init__.py +18 -0
- shared/package-files/06/0608d0efcab1ab370a7fe56a4aa6f03fdc614d6e5842db40a23fa01ed0b5ea93/_upsample_nearest_exact1d_ops.h +50 -0
- shared/package-files/06/060b265df364fc0e0d52935962d9740be0a3dfaf0388bae5ac1465a29f028b14/onedark.py +59 -0
- shared/package-files/06/060b8d3904bb5aa34de99cd03f48f24b13a234c366f96416f01bea90f22f22a9/wrapper.py +133 -0
- shared/package-files/06/061299b38f8bae11547ca8dc1b4c9e9724a313a6484ccc462016161831cc45bf/test_isfile.py +32 -0
- shared/package-files/06/0614b3def4c0fd0e8851b30bb212d0b1e119f42be35a58f6cac9f5a4d1c06239/ones_like_ops.h +39 -0
- shared/package-files/06/06156ade0ac8265a4b890ca6975ceb3a50307af09502bf9c699f4deae943902f/fbgemm_pack_gemm_matrix_fp16.h +30 -0
- shared/package-files/06/061ac0d79ef9c745baedeee80383727a8dd12bf8d4468a0ea24d66b5cac53404/round_meta.h +32 -0
- shared/package-files/06/061b31fe08f972962fe0185525142887194a93fadca788c7b524654cffa6ff1b/test_pauli.py +159 -0
- shared/package-files/06/061bade60c4a6fc1fe44dbbc2caa749c49b2413e45655440f9a3ab57a5fc8771/test_cuda_auto_context.py +21 -0
- shared/package-files/06/061c60d3203f41ed6dd8a11d995116d8dd5b984ed5651e9237311554d505baed/grid_sampler_3d_backward_ops.h +39 -0
- shared/package-files/06/061d04926ec6ed9a1bbd24fb080af251baa46049bedeec45bf37f3ed6264e361/special_modified_bessel_i1_meta.h +27 -0
- shared/package-files/06/061db31605bf37551e63eb0784478ebc9407462d77656bafec824cb5fbc55ec9/xterm+alt+title +0 -0
- shared/package-files/06/06234ed24ba85fdaae4110d0b273cbaf4e1564b1ce8f9ec29ab2493793ae067e/urllib_robotparser.pyi +1 -0
- shared/package-files/06/06246ec9f0873add1dec5e35327eb41594e7c8be3cab7345f1336ff3e50bd9c1/dw4 +0 -0
- shared/package-files/06/062495c2be304c1c2d12d7e01e4e20485b3cbf3b57fb71a9cf576ad344ac29b6/METADATA +79 -0
- shared/package-files/06/062823e5781d180eb73814ffe5fe3805fd0a90eedc468e77d05915bdafa53ab9/operator_name.h +92 -0
- shared/package-files/06/062a7186a599ccd871ba9ec9297e39bf3903a0c257e65225d55c9b0d62351208/is_leaf_ops.h +28 -0
- shared/package-files/06/062dfb39ffb903e81f0a8101a3ad906c03673c3f5605d5bf3157187d8b1ecb8b/_rbm.py +445 -0
- shared/package-files/06/062ff42827438675946e1f4a5b01a82e457805327a161d054fc990538d4851af/test__shgo.py +1156 -0
- shared/package-files/06/0638a95de3398b9d3c9cc2ac7345556beb7d2c946ebeed367b3467f88e7642f6/mm_native.h +30 -0
- shared/package-files/06/063bc02a80235e17483eec69635db81c9205b300dbd29abc0e3ca7cc9395c2a7/_macos.py +501 -0
- shared/package-files/06/063c92d566e718c67fde87955ac5d62e93f9dbf0262ffc2d1eed273b41279a45/unfold_copy_ops.h +39 -0
- shared/package-files/06/063de18848173015f30e2d0b9a0f24f908380a13d9ad056a194d107e1ed2bfce/test_ticker.py +1939 -0
- shared/package-files/06/0642d38ff9e1addb42a845d6134f25a72d72b3a55c01e5022fdc234fe6329003/model.py +0 -0
- shared/package-files/06/06443070da247d3f658ce4042c0a69e5b785a902808279427f097122843658ce/special_digamma_native.h +22 -0
- shared/package-files/06/0644947fedb1a228fe7977e9576b7bcb5245286d730f582d57a6808375e2ff01/matplotlib.pdf +0 -0
- shared/package-files/06/0645aef3d7df9a27e405d2c7fbe210ec3896d21bc3915122b9d531e0745599c2/_onenormest.py +467 -0
- shared/package-files/06/06474d45271bdfef20742bf0414eb87935942601969000a4be23fa345ba63f3a/native_layer_norm_backward_native.h +24 -0
- shared/package-files/06/064c0c5a812384deb8751898da757ca6696daa03c14cd3dcb303273e3879beec/ttkmenu.tcl +53 -0
- shared/package-files/06/064d6dd8bb636b3af33f338112552beb14d7c26d5b4914fdcaa5fcef1ac475e4/converters.pyi +11 -0
- shared/package-files/06/06512b22eb481311b9b644a58e810bbb239dda1854d815488c067748dd852ddb/_triton_multi_head_attention_native.h +22 -0
- shared/package-files/06/06517ec2f74f1c6562d0a1a500c48ba43f2e6e9d0c3d28356d747f274f1a4c8d/cp1254.py +307 -0
- shared/package-files/06/065295d14dfa8ea9e5c4ce7e3f19fc388898e6424470b96ddd0668f86b0cce56/Dawson +0 -0
- shared/package-files/06/0652de1cead19b444d340db8c639054e7b1fb41dce25baab5633241d5c2107c2/linalg_norm_ops.h +61 -0
- shared/package-files/06/06539aac034cde1ba42acc1401fd615f521c2874306ac54869e5fe1d71be92c9/ttkpane.tcl +112 -0
- shared/package-files/06/065a77e08b2cf3ba737881076f45f3fa301f3b3c694fe3629c6e8b8d73594979/METADATA +119 -0
- shared/package-files/06/065c39bcfce917a75c4f2be1391b08c2c9ab2bf8c89311f78786172c4d1d5941/METADATA +55 -0
- shared/package-files/06/065d481c6f109875b7d9e7686ef29f9440b857127e998896ebbe3961b4008abe/test_json_table_schema.py +873 -0
- shared/package-files/06/065e6597af214f795d16c018fdfe60ec93ab1d2703bdb159e0576173a19a72f8/_strptime.py +579 -0
- shared/package-files/06/06619670ff86b58913d1659471b92ef6f1c259f095e95f299e2ba52ac6f2aef5/__init__.py +16 -0
- shared/package-files/06/0663c5c7805e9b2f331ecb92aae1ad8b59913f2ff047be8a2a77c8f62c4716d2/_prelu_kernel_backward_cpu_dispatch.h +23 -0
- shared/package-files/06/0669132a68939389b6723fa2b9e9626adc33deeb7ff52b000415b9d6f9d09d95/scripts.py +437 -0
- shared/package-files/06/0669a58a817af3261c88ad611491ae32a55c708efbb5c3b694e2edb845859729/bitwise_and_ops.h +105 -0
- shared/package-files/06/0669c432544417b1b4079cdd68946c773a8845d87c7628938ac05b09523a169d/common.py +63 -0
- shared/package-files/06/066a541e6d38ead952d63cc32afbac51a33acf354799f235c582eab17488105d/tty.py +36 -0
- shared/package-files/06/066ec787f6844f1e8c4cddd6bbb4a28f2e2b60647fd6168d1ac8b7c5fceb00a3/test_digamma.py +45 -0
- shared/package-files/06/0670145a35bbb055059594c037004fc42d9a35eeef98e1324eceaa53915fba22/__init__.py +130 -0
- shared/package-files/06/06705a8a4257644a5ad1df45722647238d0f0c97b88355af9f934bda6ca815fc/graphmatrix.py +157 -0
- shared/package-files/06/067298ce39044746278cb1c81360130a8b514f0e97fdea9ad28210836ce6ed26/vi200 +0 -0
shared/package-files/06/0601c8a246923a8de7c099463bf71a247cf7ee7eb2a00f0678cf578e7e333297/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
The :py:mod:`~sympy.holonomic` module is intended to deal with holonomic functions along
|
| 3 |
+
with various operations on them like addition, multiplication, composition,
|
| 4 |
+
integration and differentiation. The module also implements various kinds of
|
| 5 |
+
conversions such as converting holonomic functions to a different form and the
|
| 6 |
+
other way around.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from .holonomic import (DifferentialOperator, HolonomicFunction, DifferentialOperators,
|
| 10 |
+
from_hyper, from_meijerg, expr_to_holonomic)
|
| 11 |
+
from .recurrence import RecurrenceOperators, RecurrenceOperator, HolonomicSequence
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
'DifferentialOperator', 'HolonomicFunction', 'DifferentialOperators',
|
| 15 |
+
'from_hyper', 'from_meijerg', 'expr_to_holonomic',
|
| 16 |
+
|
| 17 |
+
'RecurrenceOperators', 'RecurrenceOperator', 'HolonomicSequence',
|
| 18 |
+
]
|
shared/package-files/06/0608d0efcab1ab370a7fe56a4aa6f03fdc614d6e5842db40a23fa01ed0b5ea93/_upsample_nearest_exact1d_ops.h
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API _upsample_nearest_exact1d_vec {
|
| 18 |
+
using schema = at::Tensor (const at::Tensor &, at::OptionalSymIntArrayRef, c10::optional<at::ArrayRef<double>>);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_upsample_nearest_exact1d")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "vec")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_upsample_nearest_exact1d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor")
|
| 24 |
+
static at::Tensor call(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, c10::optional<at::ArrayRef<double>> scale_factors);
|
| 25 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, at::OptionalSymIntArrayRef output_size, c10::optional<at::ArrayRef<double>> scale_factors);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API _upsample_nearest_exact1d_out {
|
| 29 |
+
using schema = at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, c10::optional<double>, at::Tensor &);
|
| 30 |
+
using ptr_schema = schema*;
|
| 31 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 32 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_upsample_nearest_exact1d")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_upsample_nearest_exact1d.out(Tensor self, SymInt[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!)")
|
| 35 |
+
static at::Tensor & call(const at::Tensor & self, c10::SymIntArrayRef output_size, c10::optional<double> scales, at::Tensor & out);
|
| 36 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef output_size, c10::optional<double> scales, at::Tensor & out);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
struct TORCH_API _upsample_nearest_exact1d {
|
| 40 |
+
using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, c10::optional<double>);
|
| 41 |
+
using ptr_schema = schema*;
|
| 42 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 43 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_upsample_nearest_exact1d")
|
| 44 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 45 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_upsample_nearest_exact1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor")
|
| 46 |
+
static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef output_size, c10::optional<double> scales);
|
| 47 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef output_size, c10::optional<double> scales);
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
}} // namespace at::_ops
|
shared/package-files/06/060b265df364fc0e0d52935962d9740be0a3dfaf0388bae5ac1465a29f028b14/onedark.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.styles.onedark
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
One Dark Theme for Pygments by Tobias Zoghaib (https://github.com/TobiZog)
|
| 6 |
+
|
| 7 |
+
Inspired by one-dark-ui for the code editor Atom
|
| 8 |
+
(https://atom.io/themes/one-dark-ui).
|
| 9 |
+
|
| 10 |
+
:copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
|
| 11 |
+
:license: BSD, see LICENSE for details.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from pygments.style import Style
|
| 15 |
+
from pygments.token import Comment, Keyword, Name, Number, Operator, \
|
| 16 |
+
Punctuation, String, Token
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class OneDarkStyle(Style):
|
| 20 |
+
"""
|
| 21 |
+
Theme inspired by One Dark Pro for Atom.
|
| 22 |
+
|
| 23 |
+
.. versionadded:: 2.11
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
background_color = '#282C34'
|
| 27 |
+
|
| 28 |
+
styles = {
|
| 29 |
+
Token: '#ABB2BF',
|
| 30 |
+
|
| 31 |
+
Punctuation: '#ABB2BF',
|
| 32 |
+
Punctuation.Marker: '#ABB2BF',
|
| 33 |
+
|
| 34 |
+
Keyword: '#C678DD',
|
| 35 |
+
Keyword.Constant: '#E5C07B',
|
| 36 |
+
Keyword.Declaration: '#C678DD',
|
| 37 |
+
Keyword.Namespace: '#C678DD',
|
| 38 |
+
Keyword.Reserved: '#C678DD',
|
| 39 |
+
Keyword.Type: '#E5C07B',
|
| 40 |
+
|
| 41 |
+
Name: '#E06C75',
|
| 42 |
+
Name.Attribute: '#E06C75',
|
| 43 |
+
Name.Builtin: '#E5C07B',
|
| 44 |
+
Name.Class: '#E5C07B',
|
| 45 |
+
Name.Function: 'bold #61AFEF',
|
| 46 |
+
Name.Function.Magic: 'bold #56B6C2',
|
| 47 |
+
Name.Other: '#E06C75',
|
| 48 |
+
Name.Tag: '#E06C75',
|
| 49 |
+
Name.Decorator: '#61AFEF',
|
| 50 |
+
Name.Variable.Class: '',
|
| 51 |
+
|
| 52 |
+
String: '#98C379',
|
| 53 |
+
|
| 54 |
+
Number: '#D19A66',
|
| 55 |
+
|
| 56 |
+
Operator: '#56B6C2',
|
| 57 |
+
|
| 58 |
+
Comment: '#7F848E'
|
| 59 |
+
}
|
shared/package-files/06/060b8d3904bb5aa34de99cd03f48f24b13a234c366f96416f01bea90f22f22a9/wrapper.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import inspect
|
| 3 |
+
from textwrap import dedent
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class ResultsWrapper:
|
| 7 |
+
"""
|
| 8 |
+
Class which wraps a statsmodels estimation Results class and steps in to
|
| 9 |
+
reattach metadata to results (if available)
|
| 10 |
+
"""
|
| 11 |
+
_wrap_attrs = {}
|
| 12 |
+
_wrap_methods = {}
|
| 13 |
+
|
| 14 |
+
def __init__(self, results):
|
| 15 |
+
self._results = results
|
| 16 |
+
self.__doc__ = results.__doc__
|
| 17 |
+
|
| 18 |
+
def __dir__(self):
|
| 19 |
+
return list(dir(self._results))
|
| 20 |
+
|
| 21 |
+
def __getattribute__(self, attr):
|
| 22 |
+
def get(name):
|
| 23 |
+
return object.__getattribute__(self, name)
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
results = get("_results")
|
| 27 |
+
except AttributeError:
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
return get(attr)
|
| 32 |
+
except AttributeError:
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
obj = getattr(results, attr)
|
| 36 |
+
data = results.model.data
|
| 37 |
+
how = self._wrap_attrs.get(attr)
|
| 38 |
+
if how and isinstance(how, tuple):
|
| 39 |
+
obj = data.wrap_output(obj, how[0], *how[1:])
|
| 40 |
+
elif how:
|
| 41 |
+
obj = data.wrap_output(obj, how=how)
|
| 42 |
+
|
| 43 |
+
return obj
|
| 44 |
+
|
| 45 |
+
def __getstate__(self):
|
| 46 |
+
# print 'pickling wrapper', self.__dict__
|
| 47 |
+
return self.__dict__
|
| 48 |
+
|
| 49 |
+
def __setstate__(self, dict_):
|
| 50 |
+
# print 'unpickling wrapper', dict_
|
| 51 |
+
self.__dict__.update(dict_)
|
| 52 |
+
|
| 53 |
+
def save(self, fname, remove_data=False):
|
| 54 |
+
"""
|
| 55 |
+
Save a pickle of this instance.
|
| 56 |
+
|
| 57 |
+
Parameters
|
| 58 |
+
----------
|
| 59 |
+
fname : str or handle
|
| 60 |
+
Either a filename or a valid file handle.
|
| 61 |
+
remove_data : bool, optional
|
| 62 |
+
If False (default), then the instance is pickled without changes.
|
| 63 |
+
If True, then all arrays with length nobs are set to None before
|
| 64 |
+
pickling. See the remove_data method.
|
| 65 |
+
In some cases not all arrays will be set to None.
|
| 66 |
+
"""
|
| 67 |
+
from statsmodels.iolib.smpickle import save_pickle
|
| 68 |
+
|
| 69 |
+
if remove_data:
|
| 70 |
+
self.remove_data()
|
| 71 |
+
|
| 72 |
+
save_pickle(self, fname)
|
| 73 |
+
|
| 74 |
+
@classmethod
|
| 75 |
+
def load(cls, fname):
|
| 76 |
+
"""
|
| 77 |
+
Load a pickled results instance
|
| 78 |
+
|
| 79 |
+
.. warning::
|
| 80 |
+
|
| 81 |
+
Loading pickled models is not secure against erroneous or
|
| 82 |
+
maliciously constructed data. Never unpickle data received from
|
| 83 |
+
an untrusted or unauthenticated source.
|
| 84 |
+
|
| 85 |
+
Parameters
|
| 86 |
+
----------
|
| 87 |
+
fname : str or handle
|
| 88 |
+
A string filename or a file handle.
|
| 89 |
+
|
| 90 |
+
Returns
|
| 91 |
+
-------
|
| 92 |
+
Results
|
| 93 |
+
The unpickled results instance.
|
| 94 |
+
"""
|
| 95 |
+
from statsmodels.iolib.smpickle import load_pickle
|
| 96 |
+
return load_pickle(fname)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def union_dicts(*dicts):
|
| 100 |
+
result = {}
|
| 101 |
+
for d in dicts:
|
| 102 |
+
result.update(d)
|
| 103 |
+
return result
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def make_wrapper(func, how):
|
| 107 |
+
@functools.wraps(func)
|
| 108 |
+
def wrapper(self, *args, **kwargs):
|
| 109 |
+
results = object.__getattribute__(self, "_results")
|
| 110 |
+
data = results.model.data
|
| 111 |
+
if how and isinstance(how, tuple):
|
| 112 |
+
obj = data.wrap_output(func(results, *args, **kwargs), how[0], how[1:])
|
| 113 |
+
elif how:
|
| 114 |
+
obj = data.wrap_output(func(results, *args, **kwargs), how)
|
| 115 |
+
return obj
|
| 116 |
+
|
| 117 |
+
sig = inspect.signature(func)
|
| 118 |
+
formatted = str(sig)
|
| 119 |
+
|
| 120 |
+
doc = dedent(wrapper.__doc__) if wrapper.__doc__ else ""
|
| 121 |
+
wrapper.__doc__ = f"\n{func.__name__}{formatted}\n{doc}"
|
| 122 |
+
|
| 123 |
+
return wrapper
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def populate_wrapper(klass, wrapping):
|
| 127 |
+
for meth, how in klass._wrap_methods.items():
|
| 128 |
+
if not hasattr(wrapping, meth):
|
| 129 |
+
continue
|
| 130 |
+
|
| 131 |
+
func = getattr(wrapping, meth)
|
| 132 |
+
wrapper = make_wrapper(func, how)
|
| 133 |
+
setattr(klass, meth, wrapper)
|
shared/package-files/06/061299b38f8bae11547ca8dc1b4c9e9724a313a6484ccc462016161831cc45bf/test_isfile.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from numpy.testing import assert_
|
| 7 |
+
|
| 8 |
+
ROOT = Path(np.__file__).parents[0]
|
| 9 |
+
FILES = [
|
| 10 |
+
ROOT / "py.typed",
|
| 11 |
+
ROOT / "__init__.pyi",
|
| 12 |
+
ROOT / "ctypeslib.pyi",
|
| 13 |
+
ROOT / "core" / "__init__.pyi",
|
| 14 |
+
ROOT / "f2py" / "__init__.pyi",
|
| 15 |
+
ROOT / "fft" / "__init__.pyi",
|
| 16 |
+
ROOT / "lib" / "__init__.pyi",
|
| 17 |
+
ROOT / "linalg" / "__init__.pyi",
|
| 18 |
+
ROOT / "ma" / "__init__.pyi",
|
| 19 |
+
ROOT / "matrixlib" / "__init__.pyi",
|
| 20 |
+
ROOT / "polynomial" / "__init__.pyi",
|
| 21 |
+
ROOT / "random" / "__init__.pyi",
|
| 22 |
+
ROOT / "testing" / "__init__.pyi",
|
| 23 |
+
]
|
| 24 |
+
if sys.version_info < (3, 12):
|
| 25 |
+
FILES += [ROOT / "distutils" / "__init__.pyi"]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class TestIsFile:
|
| 29 |
+
def test_isfile(self):
|
| 30 |
+
"""Test if all ``.pyi`` files are properly installed."""
|
| 31 |
+
for file in FILES:
|
| 32 |
+
assert_(os.path.isfile(file))
|
shared/package-files/06/0614b3def4c0fd0e8851b30bb212d0b1e119f42be35a58f6cac9f5a4d1c06239/ones_like_ops.h
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API ones_like {
|
| 18 |
+
using schema = at::Tensor (const at::Tensor &, c10::optional<at::ScalarType>, c10::optional<at::Layout>, c10::optional<at::Device>, c10::optional<bool>, c10::optional<at::MemoryFormat>);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::ones_like")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ones_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor")
|
| 24 |
+
static at::Tensor call(const at::Tensor & self, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory, c10::optional<at::MemoryFormat> memory_format);
|
| 25 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory, c10::optional<at::MemoryFormat> memory_format);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API ones_like_out {
|
| 29 |
+
using schema = at::Tensor & (const at::Tensor &, c10::optional<at::MemoryFormat>, at::Tensor &);
|
| 30 |
+
using ptr_schema = schema*;
|
| 31 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 32 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::ones_like")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ones_like.out(Tensor self, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)")
|
| 35 |
+
static at::Tensor & call(const at::Tensor & self, c10::optional<at::MemoryFormat> memory_format, at::Tensor & out);
|
| 36 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional<at::MemoryFormat> memory_format, at::Tensor & out);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
}} // namespace at::_ops
|
shared/package-files/06/06156ade0ac8265a4b890ca6975ceb3a50307af09502bf9c699f4deae943902f/fbgemm_pack_gemm_matrix_fp16.h
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <c10/util/Optional.h>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/fbgemm_pack_gemm_matrix_fp16_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::fbgemm_pack_gemm_matrix_fp16(Tensor input) -> Tensor
|
| 26 |
+
inline at::Tensor fbgemm_pack_gemm_matrix_fp16(const at::Tensor & input) {
|
| 27 |
+
return at::_ops::fbgemm_pack_gemm_matrix_fp16::call(input);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
}
|
shared/package-files/06/061ac0d79ef9c745baedeee80383727a8dd12bf8d4468a0ea24d66b5cac53404/round_meta.h
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeMetaFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/TensorIterator.h>
|
| 13 |
+
#include <ATen/TensorMeta.h>
|
| 14 |
+
#include <tuple>
|
| 15 |
+
#include <vector>
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace meta {
|
| 19 |
+
|
| 20 |
+
struct TORCH_API structured_round : public TensorIteratorBase {
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
void meta(const at::Tensor & self);
|
| 24 |
+
};
|
| 25 |
+
struct TORCH_API structured_round_decimals : public TensorIteratorBase {
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
void meta(const at::Tensor & self, int64_t decimals);
|
| 29 |
+
};
|
| 30 |
+
|
| 31 |
+
} // namespace native
|
| 32 |
+
} // namespace at
|
shared/package-files/06/061b31fe08f972962fe0185525142887194a93fadca788c7b524654cffa6ff1b/test_pauli.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.mul import Mul
|
| 2 |
+
from sympy.core.numbers import I
|
| 3 |
+
from sympy.matrices.dense import Matrix
|
| 4 |
+
from sympy.printing.latex import latex
|
| 5 |
+
from sympy.physics.quantum import (Dagger, Commutator, AntiCommutator, qapply,
|
| 6 |
+
Operator, represent)
|
| 7 |
+
from sympy.physics.quantum.pauli import (SigmaOpBase, SigmaX, SigmaY, SigmaZ,
|
| 8 |
+
SigmaMinus, SigmaPlus,
|
| 9 |
+
qsimplify_pauli)
|
| 10 |
+
from sympy.physics.quantum.pauli import SigmaZKet, SigmaZBra
|
| 11 |
+
from sympy.testing.pytest import raises
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
sx, sy, sz = SigmaX(), SigmaY(), SigmaZ()
|
| 15 |
+
sx1, sy1, sz1 = SigmaX(1), SigmaY(1), SigmaZ(1)
|
| 16 |
+
sx2, sy2, sz2 = SigmaX(2), SigmaY(2), SigmaZ(2)
|
| 17 |
+
|
| 18 |
+
sm, sp = SigmaMinus(), SigmaPlus()
|
| 19 |
+
sm1, sp1 = SigmaMinus(1), SigmaPlus(1)
|
| 20 |
+
A, B = Operator("A"), Operator("B")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_pauli_operators_types():
|
| 24 |
+
|
| 25 |
+
assert isinstance(sx, SigmaOpBase) and isinstance(sx, SigmaX)
|
| 26 |
+
assert isinstance(sy, SigmaOpBase) and isinstance(sy, SigmaY)
|
| 27 |
+
assert isinstance(sz, SigmaOpBase) and isinstance(sz, SigmaZ)
|
| 28 |
+
assert isinstance(sm, SigmaOpBase) and isinstance(sm, SigmaMinus)
|
| 29 |
+
assert isinstance(sp, SigmaOpBase) and isinstance(sp, SigmaPlus)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_pauli_operators_commutator():
|
| 33 |
+
|
| 34 |
+
assert Commutator(sx, sy).doit() == 2 * I * sz
|
| 35 |
+
assert Commutator(sy, sz).doit() == 2 * I * sx
|
| 36 |
+
assert Commutator(sz, sx).doit() == 2 * I * sy
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_pauli_operators_commutator_with_labels():
|
| 40 |
+
|
| 41 |
+
assert Commutator(sx1, sy1).doit() == 2 * I * sz1
|
| 42 |
+
assert Commutator(sy1, sz1).doit() == 2 * I * sx1
|
| 43 |
+
assert Commutator(sz1, sx1).doit() == 2 * I * sy1
|
| 44 |
+
|
| 45 |
+
assert Commutator(sx2, sy2).doit() == 2 * I * sz2
|
| 46 |
+
assert Commutator(sy2, sz2).doit() == 2 * I * sx2
|
| 47 |
+
assert Commutator(sz2, sx2).doit() == 2 * I * sy2
|
| 48 |
+
|
| 49 |
+
assert Commutator(sx1, sy2).doit() == 0
|
| 50 |
+
assert Commutator(sy1, sz2).doit() == 0
|
| 51 |
+
assert Commutator(sz1, sx2).doit() == 0
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_pauli_operators_anticommutator():
|
| 55 |
+
|
| 56 |
+
assert AntiCommutator(sy, sz).doit() == 0
|
| 57 |
+
assert AntiCommutator(sz, sx).doit() == 0
|
| 58 |
+
assert AntiCommutator(sx, sm).doit() == 1
|
| 59 |
+
assert AntiCommutator(sx, sp).doit() == 1
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_pauli_operators_adjoint():
|
| 63 |
+
|
| 64 |
+
assert Dagger(sx) == sx
|
| 65 |
+
assert Dagger(sy) == sy
|
| 66 |
+
assert Dagger(sz) == sz
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_pauli_operators_adjoint_with_labels():
|
| 70 |
+
|
| 71 |
+
assert Dagger(sx1) == sx1
|
| 72 |
+
assert Dagger(sy1) == sy1
|
| 73 |
+
assert Dagger(sz1) == sz1
|
| 74 |
+
|
| 75 |
+
assert Dagger(sx1) != sx2
|
| 76 |
+
assert Dagger(sy1) != sy2
|
| 77 |
+
assert Dagger(sz1) != sz2
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_pauli_operators_multiplication():
|
| 81 |
+
|
| 82 |
+
assert qsimplify_pauli(sx * sx) == 1
|
| 83 |
+
assert qsimplify_pauli(sy * sy) == 1
|
| 84 |
+
assert qsimplify_pauli(sz * sz) == 1
|
| 85 |
+
|
| 86 |
+
assert qsimplify_pauli(sx * sy) == I * sz
|
| 87 |
+
assert qsimplify_pauli(sy * sz) == I * sx
|
| 88 |
+
assert qsimplify_pauli(sz * sx) == I * sy
|
| 89 |
+
|
| 90 |
+
assert qsimplify_pauli(sy * sx) == - I * sz
|
| 91 |
+
assert qsimplify_pauli(sz * sy) == - I * sx
|
| 92 |
+
assert qsimplify_pauli(sx * sz) == - I * sy
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def test_pauli_operators_multiplication_with_labels():
|
| 96 |
+
|
| 97 |
+
assert qsimplify_pauli(sx1 * sx1) == 1
|
| 98 |
+
assert qsimplify_pauli(sy1 * sy1) == 1
|
| 99 |
+
assert qsimplify_pauli(sz1 * sz1) == 1
|
| 100 |
+
|
| 101 |
+
assert isinstance(sx1 * sx2, Mul)
|
| 102 |
+
assert isinstance(sy1 * sy2, Mul)
|
| 103 |
+
assert isinstance(sz1 * sz2, Mul)
|
| 104 |
+
|
| 105 |
+
assert qsimplify_pauli(sx1 * sy1 * sx2 * sy2) == - sz1 * sz2
|
| 106 |
+
assert qsimplify_pauli(sy1 * sz1 * sz2 * sx2) == - sx1 * sy2
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_pauli_states():
|
| 110 |
+
sx, sz = SigmaX(), SigmaZ()
|
| 111 |
+
|
| 112 |
+
up = SigmaZKet(0)
|
| 113 |
+
down = SigmaZKet(1)
|
| 114 |
+
|
| 115 |
+
assert qapply(sx * up) == down
|
| 116 |
+
assert qapply(sx * down) == up
|
| 117 |
+
assert qapply(sz * up) == up
|
| 118 |
+
assert qapply(sz * down) == - down
|
| 119 |
+
|
| 120 |
+
up = SigmaZBra(0)
|
| 121 |
+
down = SigmaZBra(1)
|
| 122 |
+
|
| 123 |
+
assert qapply(up * sx, dagger=True) == down
|
| 124 |
+
assert qapply(down * sx, dagger=True) == up
|
| 125 |
+
assert qapply(up * sz, dagger=True) == up
|
| 126 |
+
assert qapply(down * sz, dagger=True) == - down
|
| 127 |
+
|
| 128 |
+
assert Dagger(SigmaZKet(0)) == SigmaZBra(0)
|
| 129 |
+
assert Dagger(SigmaZBra(1)) == SigmaZKet(1)
|
| 130 |
+
raises(ValueError, lambda: SigmaZBra(2))
|
| 131 |
+
raises(ValueError, lambda: SigmaZKet(2))
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def test_use_name():
|
| 135 |
+
assert sm.use_name is False
|
| 136 |
+
assert sm1.use_name is True
|
| 137 |
+
assert sx.use_name is False
|
| 138 |
+
assert sx1.use_name is True
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def test_printing():
|
| 142 |
+
assert latex(sx) == r'{\sigma_x}'
|
| 143 |
+
assert latex(sx1) == r'{\sigma_x^{(1)}}'
|
| 144 |
+
assert latex(sy) == r'{\sigma_y}'
|
| 145 |
+
assert latex(sy1) == r'{\sigma_y^{(1)}}'
|
| 146 |
+
assert latex(sz) == r'{\sigma_z}'
|
| 147 |
+
assert latex(sz1) == r'{\sigma_z^{(1)}}'
|
| 148 |
+
assert latex(sm) == r'{\sigma_-}'
|
| 149 |
+
assert latex(sm1) == r'{\sigma_-^{(1)}}'
|
| 150 |
+
assert latex(sp) == r'{\sigma_+}'
|
| 151 |
+
assert latex(sp1) == r'{\sigma_+^{(1)}}'
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def test_represent():
|
| 155 |
+
assert represent(sx) == Matrix([[0, 1], [1, 0]])
|
| 156 |
+
assert represent(sy) == Matrix([[0, -I], [I, 0]])
|
| 157 |
+
assert represent(sz) == Matrix([[1, 0], [0, -1]])
|
| 158 |
+
assert represent(sm) == Matrix([[0, 0], [1, 0]])
|
| 159 |
+
assert represent(sp) == Matrix([[0, 1], [0, 0]])
|
shared/package-files/06/061bade60c4a6fc1fe44dbbc2caa749c49b2413e45655440f9a3ab57a5fc8771/test_cuda_auto_context.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from numba import cuda
|
| 3 |
+
from numba.cuda.testing import unittest, CUDATestCase
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestCudaAutoContext(CUDATestCase):
|
| 7 |
+
def test_auto_context(self):
|
| 8 |
+
"""A problem was revealed by a customer that the use cuda.to_device
|
| 9 |
+
does not create a CUDA context.
|
| 10 |
+
This tests the problem
|
| 11 |
+
"""
|
| 12 |
+
A = np.arange(10, dtype=np.float32)
|
| 13 |
+
newA = np.empty_like(A)
|
| 14 |
+
dA = cuda.to_device(A)
|
| 15 |
+
|
| 16 |
+
dA.copy_to_host(newA)
|
| 17 |
+
self.assertTrue(np.allclose(A, newA))
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if __name__ == '__main__':
|
| 21 |
+
unittest.main()
|
shared/package-files/06/061c60d3203f41ed6dd8a11d995116d8dd5b984ed5651e9237311554d505baed/grid_sampler_3d_backward_ops.h
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API grid_sampler_3d_backward {
|
| 18 |
+
using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, int64_t, bool, ::std::array<bool,2>);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::grid_sampler_3d_backward")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "grid_sampler_3d_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, bool[2] output_mask) -> (Tensor, Tensor)")
|
| 24 |
+
static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, ::std::array<bool,2> output_mask);
|
| 25 |
+
static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, ::std::array<bool,2> output_mask);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API grid_sampler_3d_backward_out {
|
| 29 |
+
using schema = ::std::tuple<at::Tensor &,at::Tensor &> (const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, int64_t, bool, ::std::array<bool,2>, at::Tensor &, at::Tensor &);
|
| 30 |
+
using ptr_schema = schema*;
|
| 31 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 32 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::grid_sampler_3d_backward")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "grid_sampler_3d_backward.out(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, bool[2] output_mask, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))")
|
| 35 |
+
static ::std::tuple<at::Tensor &,at::Tensor &> call(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, ::std::array<bool,2> output_mask, at::Tensor & out0, at::Tensor & out1);
|
| 36 |
+
static ::std::tuple<at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, ::std::array<bool,2> output_mask, at::Tensor & out0, at::Tensor & out1);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
}} // namespace at::_ops
|
shared/package-files/06/061d04926ec6ed9a1bbd24fb080af251baa46049bedeec45bf37f3ed6264e361/special_modified_bessel_i1_meta.h
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeMetaFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/TensorIterator.h>
|
| 13 |
+
#include <ATen/TensorMeta.h>
|
| 14 |
+
#include <tuple>
|
| 15 |
+
#include <vector>
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace meta {
|
| 19 |
+
|
| 20 |
+
struct TORCH_API structured_special_modified_bessel_i1 : public TensorIteratorBase {
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
void meta(const at::Tensor & self);
|
| 24 |
+
};
|
| 25 |
+
|
| 26 |
+
} // namespace native
|
| 27 |
+
} // namespace at
|
shared/package-files/06/061db31605bf37551e63eb0784478ebc9407462d77656bafec824cb5fbc55ec9/xterm+alt+title
ADDED
|
Binary file (182 Bytes). View file
|
|
|
shared/package-files/06/06234ed24ba85fdaae4110d0b273cbaf4e1564b1ce8f9ec29ab2493793ae067e/urllib_robotparser.pyi
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from urllib.robotparser import *
|
shared/package-files/06/06246ec9f0873add1dec5e35327eb41594e7c8be3cab7345f1336ff3e50bd9c1/dw4
ADDED
|
Binary file (373 Bytes). View file
|
|
|
shared/package-files/06/062495c2be304c1c2d12d7e01e4e20485b3cbf3b57fb71a9cf576ad344ac29b6/METADATA
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: conda-libmamba-solver
|
| 3 |
+
Version: 23.7.0
|
| 4 |
+
Summary: The fast mamba solver, now in conda
|
| 5 |
+
Project-URL: homepage, https://github.com/conda/conda-libmamba-solver
|
| 6 |
+
Author-email: "Anaconda, Inc." <conda@continuum.io>
|
| 7 |
+
License: BSD 3-Clause License
|
| 8 |
+
|
| 9 |
+
Copyright (c) 2022, Anaconda, Inc.
|
| 10 |
+
Copyright (c) 2023, conda
|
| 11 |
+
All rights reserved.
|
| 12 |
+
|
| 13 |
+
Redistribution and use in source and binary forms, with or without
|
| 14 |
+
modification, are permitted provided that the following conditions are met:
|
| 15 |
+
|
| 16 |
+
* Redistributions of source code must retain the above copyright
|
| 17 |
+
notice, this list of conditions and the following disclaimer.
|
| 18 |
+
* Redistributions in binary form must reproduce the above copyright
|
| 19 |
+
notice, this list of conditions and the following disclaimer in the
|
| 20 |
+
documentation and/or other materials provided with the distribution.
|
| 21 |
+
* Neither the name of the copyright holder nor the names of its
|
| 22 |
+
contributors may be used to endorse or promote products
|
| 23 |
+
derived from this software without specific prior written permission.
|
| 24 |
+
|
| 25 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
| 26 |
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
| 27 |
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 28 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
|
| 29 |
+
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
| 30 |
+
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 31 |
+
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
| 32 |
+
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 33 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 34 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 35 |
+
|
| 36 |
+
---
|
| 37 |
+
|
| 38 |
+
This work also includes code borrowed from mamba.utils v0.19, licensed as BSD 3-Clause
|
| 39 |
+
License-File: AUTHORS.md
|
| 40 |
+
License-File: LICENSE
|
| 41 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 42 |
+
Classifier: Programming Language :: Python :: 3
|
| 43 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 44 |
+
Classifier: Programming Language :: Python :: 3.7
|
| 45 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 46 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 47 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 48 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 49 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 50 |
+
Requires-Python: >=3.8
|
| 51 |
+
Requires-Dist: boltons>=23.0.0
|
| 52 |
+
Requires-Dist: conda>=23.5.0
|
| 53 |
+
Requires-Dist: libmambapy>=1.4.1
|
| 54 |
+
Description-Content-Type: text/markdown
|
| 55 |
+
|
| 56 |
+
# conda-libmamba-solver
|
| 57 |
+
|
| 58 |
+
[](https://anaconda.org/main/conda-libmamba-solver)
|
| 59 |
+
[](https://anaconda.org/main/conda-libmamba-solver)
|
| 60 |
+
[](https://github.com/conda/conda-libmamba-solver/actions/workflows/tests.yml)
|
| 61 |
+
[](https://calver.org)
|
| 62 |
+
|
| 63 |
+
The fast mamba solver, now in conda!
|
| 64 |
+
|
| 65 |
+
## What is this exactly?
|
| 66 |
+
|
| 67 |
+
conda-libmamba-solver is a new solver for the
|
| 68 |
+
[conda package manager](https://docs.conda.io/) which uses the solver from the
|
| 69 |
+
[mamba project](https://mamba.readthedocs.io/) behind the scenes, while
|
| 70 |
+
carefully implementing conda's functionality and expected behaviors on top.
|
| 71 |
+
The library used by mamba to do the heavy-lifting is called [libsolv](https://github.com/openSUSE/libsolv).
|
| 72 |
+
|
| 73 |
+
Additional information about the project can be found in the blog post on Anaconda's weblog:
|
| 74 |
+
[A Faster Solver for Conda: Libmamba](https://www.anaconda.com/blog/a-faster-conda-for-a-growing-community).
|
| 75 |
+
|
| 76 |
+
## Documentation
|
| 77 |
+
|
| 78 |
+
Check the [documentation](https://conda.github.io/conda-libmamba-solver/) for
|
| 79 |
+
instructions on how to install, use and make the most out the new conda solver!
|
shared/package-files/06/062823e5781d180eb73814ffe5fe3805fd0a90eedc468e77d05915bdafa53ab9/operator_name.h
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <c10/macros/Macros.h>
|
| 4 |
+
#include <c10/util/Exception.h>
|
| 5 |
+
#include <c10/util/Optional.h>
|
| 6 |
+
#include <c10/util/string_view.h>
|
| 7 |
+
#include <string>
|
| 8 |
+
#include <utility>
|
| 9 |
+
#include <ostream>
|
| 10 |
+
|
| 11 |
+
namespace c10 {
|
| 12 |
+
|
| 13 |
+
// TODO: consider storing namespace separately too
|
| 14 |
+
struct OperatorName final {
|
| 15 |
+
std::string name;
|
| 16 |
+
std::string overload_name;
|
| 17 |
+
OperatorName(std::string name, std::string overload_name)
|
| 18 |
+
: name(std::move(name)), overload_name(std::move(overload_name)) {}
|
| 19 |
+
|
| 20 |
+
// TODO: These two functions below are slow! Fix internal data structures so
|
| 21 |
+
// I don't have to manually reconstruct the namespaces!
|
| 22 |
+
|
| 23 |
+
// Return the namespace of this OperatorName, if it exists. The
|
| 24 |
+
// returned string_view is only live as long as the OperatorName
|
| 25 |
+
// exists and name is not mutated
|
| 26 |
+
c10::optional<c10::string_view> getNamespace() const {
|
| 27 |
+
auto pos = name.find("::");
|
| 28 |
+
if (pos == std::string::npos) {
|
| 29 |
+
return c10::nullopt;
|
| 30 |
+
} else {
|
| 31 |
+
return c10::make_optional(c10::string_view(name.data(), pos));
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
// Returns true if we successfully set the namespace
|
| 36 |
+
bool setNamespaceIfNotSet(const char* ns) {
|
| 37 |
+
if (!getNamespace().has_value()) {
|
| 38 |
+
const auto ns_len = strlen(ns);
|
| 39 |
+
const auto old_name_size = name.size();
|
| 40 |
+
name.resize(ns_len + 2 + old_name_size);
|
| 41 |
+
// Shift current value of name to the end of the new space.
|
| 42 |
+
name.replace(name.size() - old_name_size, old_name_size, name, 0, old_name_size);
|
| 43 |
+
name.replace(0, ns_len, ns, ns_len);
|
| 44 |
+
name[ns_len] = ':';
|
| 45 |
+
name[ns_len + 1] = ':';
|
| 46 |
+
return true;
|
| 47 |
+
} else {
|
| 48 |
+
return false;
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
};
|
| 52 |
+
|
| 53 |
+
// Non-owning view of an OperatorName. Unlike OperatorName, most of
|
| 54 |
+
// its functions are constexpr, so it can be used for compile time
|
| 55 |
+
// computations
|
| 56 |
+
struct OperatorNameView final {
|
| 57 |
+
c10::string_view name;
|
| 58 |
+
c10::string_view overload_name;
|
| 59 |
+
constexpr OperatorNameView(c10::string_view name, c10::string_view overload_name)
|
| 60 |
+
: name(name), overload_name(overload_name) {}
|
| 61 |
+
// Parses strings like "foo.overload" and also "foo"
|
| 62 |
+
constexpr static OperatorNameView parse(c10::string_view full_name) {
|
| 63 |
+
auto i = full_name.find('.');
|
| 64 |
+
if (i == c10::string_view::npos) {
|
| 65 |
+
return OperatorNameView(full_name, c10::string_view());
|
| 66 |
+
} else {
|
| 67 |
+
return OperatorNameView(full_name.substr(0, i), full_name.substr(i + 1));
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
};
|
| 71 |
+
|
| 72 |
+
inline bool operator==(const OperatorName& lhs, const OperatorName& rhs) {
|
| 73 |
+
return lhs.name == rhs.name && lhs.overload_name == rhs.overload_name;
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
inline bool operator!=(const OperatorName& lhs, const OperatorName& rhs) {
|
| 77 |
+
return !operator==(lhs, rhs);
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
TORCH_API std::string toString(const OperatorName& opName);
|
| 81 |
+
TORCH_API std::ostream& operator<<(std::ostream&, const OperatorName&);
|
| 82 |
+
|
| 83 |
+
} // namespace c10
|
| 84 |
+
|
| 85 |
+
namespace std {
|
| 86 |
+
template <>
|
| 87 |
+
struct hash<::c10::OperatorName> {
|
| 88 |
+
size_t operator()(const ::c10::OperatorName& x) const {
|
| 89 |
+
return std::hash<std::string>()(x.name) ^ (~ std::hash<std::string>()(x.overload_name));
|
| 90 |
+
}
|
| 91 |
+
};
|
| 92 |
+
}
|
shared/package-files/06/062a7186a599ccd871ba9ec9297e39bf3903a0c257e65225d55c9b0d62351208/is_leaf_ops.h
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API is_leaf {
|
| 18 |
+
using schema = bool (const at::Tensor &);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::is_leaf")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "is_leaf(Tensor self) -> bool")
|
| 24 |
+
static bool call(const at::Tensor & self);
|
| 25 |
+
static bool redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
}} // namespace at::_ops
|
shared/package-files/06/062dfb39ffb903e81f0a8101a3ad906c03673c3f5605d5bf3157187d8b1ecb8b/_rbm.py
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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-3-Clause
|
| 5 |
+
|
| 6 |
+
import time
|
| 7 |
+
from numbers import Integral, Real
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import scipy.sparse as sp
|
| 11 |
+
from scipy.special import expit # logistic function
|
| 12 |
+
|
| 13 |
+
from ..base import (
|
| 14 |
+
BaseEstimator,
|
| 15 |
+
ClassNamePrefixFeaturesOutMixin,
|
| 16 |
+
TransformerMixin,
|
| 17 |
+
_fit_context,
|
| 18 |
+
)
|
| 19 |
+
from ..utils import check_random_state, gen_even_slices
|
| 20 |
+
from ..utils._param_validation import Interval
|
| 21 |
+
from ..utils.extmath import safe_sparse_dot
|
| 22 |
+
from ..utils.validation import check_is_fitted, validate_data
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class BernoulliRBM(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator):
|
| 26 |
+
"""Bernoulli Restricted Boltzmann Machine (RBM).
|
| 27 |
+
|
| 28 |
+
A Restricted Boltzmann Machine with binary visible units and
|
| 29 |
+
binary hidden units. Parameters are estimated using Stochastic Maximum
|
| 30 |
+
Likelihood (SML), also known as Persistent Contrastive Divergence (PCD)
|
| 31 |
+
[2].
|
| 32 |
+
|
| 33 |
+
The time complexity of this implementation is ``O(d ** 2)`` assuming
|
| 34 |
+
d ~ n_features ~ n_components.
|
| 35 |
+
|
| 36 |
+
Read more in the :ref:`User Guide <rbm>`.
|
| 37 |
+
|
| 38 |
+
Parameters
|
| 39 |
+
----------
|
| 40 |
+
n_components : int, default=256
|
| 41 |
+
Number of binary hidden units.
|
| 42 |
+
|
| 43 |
+
learning_rate : float, default=0.1
|
| 44 |
+
The learning rate for weight updates. It is *highly* recommended
|
| 45 |
+
to tune this hyper-parameter. Reasonable values are in the
|
| 46 |
+
10**[0., -3.] range.
|
| 47 |
+
|
| 48 |
+
batch_size : int, default=10
|
| 49 |
+
Number of examples per minibatch.
|
| 50 |
+
|
| 51 |
+
n_iter : int, default=10
|
| 52 |
+
Number of iterations/sweeps over the training dataset to perform
|
| 53 |
+
during training.
|
| 54 |
+
|
| 55 |
+
verbose : int, default=0
|
| 56 |
+
The verbosity level. The default, zero, means silent mode. Range
|
| 57 |
+
of values is [0, inf].
|
| 58 |
+
|
| 59 |
+
random_state : int, RandomState instance or None, default=None
|
| 60 |
+
Determines random number generation for:
|
| 61 |
+
|
| 62 |
+
- Gibbs sampling from visible and hidden layers.
|
| 63 |
+
|
| 64 |
+
- Initializing components, sampling from layers during fit.
|
| 65 |
+
|
| 66 |
+
- Corrupting the data when scoring samples.
|
| 67 |
+
|
| 68 |
+
Pass an int for reproducible results across multiple function calls.
|
| 69 |
+
See :term:`Glossary <random_state>`.
|
| 70 |
+
|
| 71 |
+
Attributes
|
| 72 |
+
----------
|
| 73 |
+
intercept_hidden_ : array-like of shape (n_components,)
|
| 74 |
+
Biases of the hidden units.
|
| 75 |
+
|
| 76 |
+
intercept_visible_ : array-like of shape (n_features,)
|
| 77 |
+
Biases of the visible units.
|
| 78 |
+
|
| 79 |
+
components_ : array-like of shape (n_components, n_features)
|
| 80 |
+
Weight matrix, where `n_features` is the number of
|
| 81 |
+
visible units and `n_components` is the number of hidden units.
|
| 82 |
+
|
| 83 |
+
h_samples_ : array-like of shape (batch_size, n_components)
|
| 84 |
+
Hidden Activation sampled from the model distribution,
|
| 85 |
+
where `batch_size` is the number of examples per minibatch and
|
| 86 |
+
`n_components` is the number of hidden units.
|
| 87 |
+
|
| 88 |
+
n_features_in_ : int
|
| 89 |
+
Number of features seen during :term:`fit`.
|
| 90 |
+
|
| 91 |
+
.. versionadded:: 0.24
|
| 92 |
+
|
| 93 |
+
feature_names_in_ : ndarray of shape (`n_features_in_`,)
|
| 94 |
+
Names of features seen during :term:`fit`. Defined only when `X`
|
| 95 |
+
has feature names that are all strings.
|
| 96 |
+
|
| 97 |
+
.. versionadded:: 1.0
|
| 98 |
+
|
| 99 |
+
See Also
|
| 100 |
+
--------
|
| 101 |
+
sklearn.neural_network.MLPRegressor : Multi-layer Perceptron regressor.
|
| 102 |
+
sklearn.neural_network.MLPClassifier : Multi-layer Perceptron classifier.
|
| 103 |
+
sklearn.decomposition.PCA : An unsupervised linear dimensionality
|
| 104 |
+
reduction model.
|
| 105 |
+
|
| 106 |
+
References
|
| 107 |
+
----------
|
| 108 |
+
|
| 109 |
+
[1] Hinton, G. E., Osindero, S. and Teh, Y. A fast learning algorithm for
|
| 110 |
+
deep belief nets. Neural Computation 18, pp 1527-1554.
|
| 111 |
+
https://www.cs.toronto.edu/~hinton/absps/fastnc.pdf
|
| 112 |
+
|
| 113 |
+
[2] Tieleman, T. Training Restricted Boltzmann Machines using
|
| 114 |
+
Approximations to the Likelihood Gradient. International Conference
|
| 115 |
+
on Machine Learning (ICML) 2008
|
| 116 |
+
|
| 117 |
+
Examples
|
| 118 |
+
--------
|
| 119 |
+
|
| 120 |
+
>>> import numpy as np
|
| 121 |
+
>>> from sklearn.neural_network import BernoulliRBM
|
| 122 |
+
>>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]])
|
| 123 |
+
>>> model = BernoulliRBM(n_components=2)
|
| 124 |
+
>>> model.fit(X)
|
| 125 |
+
BernoulliRBM(n_components=2)
|
| 126 |
+
|
| 127 |
+
For a more detailed example usage, see
|
| 128 |
+
:ref:`sphx_glr_auto_examples_neural_networks_plot_rbm_logistic_classification.py`.
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
_parameter_constraints: dict = {
|
| 132 |
+
"n_components": [Interval(Integral, 1, None, closed="left")],
|
| 133 |
+
"learning_rate": [Interval(Real, 0, None, closed="neither")],
|
| 134 |
+
"batch_size": [Interval(Integral, 1, None, closed="left")],
|
| 135 |
+
"n_iter": [Interval(Integral, 0, None, closed="left")],
|
| 136 |
+
"verbose": ["verbose"],
|
| 137 |
+
"random_state": ["random_state"],
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
def __init__(
|
| 141 |
+
self,
|
| 142 |
+
n_components=256,
|
| 143 |
+
*,
|
| 144 |
+
learning_rate=0.1,
|
| 145 |
+
batch_size=10,
|
| 146 |
+
n_iter=10,
|
| 147 |
+
verbose=0,
|
| 148 |
+
random_state=None,
|
| 149 |
+
):
|
| 150 |
+
self.n_components = n_components
|
| 151 |
+
self.learning_rate = learning_rate
|
| 152 |
+
self.batch_size = batch_size
|
| 153 |
+
self.n_iter = n_iter
|
| 154 |
+
self.verbose = verbose
|
| 155 |
+
self.random_state = random_state
|
| 156 |
+
|
| 157 |
+
def transform(self, X):
|
| 158 |
+
"""Compute the hidden layer activation probabilities, P(h=1|v=X).
|
| 159 |
+
|
| 160 |
+
Parameters
|
| 161 |
+
----------
|
| 162 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
| 163 |
+
The data to be transformed.
|
| 164 |
+
|
| 165 |
+
Returns
|
| 166 |
+
-------
|
| 167 |
+
h : ndarray of shape (n_samples, n_components)
|
| 168 |
+
Latent representations of the data.
|
| 169 |
+
"""
|
| 170 |
+
check_is_fitted(self)
|
| 171 |
+
|
| 172 |
+
X = validate_data(
|
| 173 |
+
self, X, accept_sparse="csr", reset=False, dtype=(np.float64, np.float32)
|
| 174 |
+
)
|
| 175 |
+
return self._mean_hiddens(X)
|
| 176 |
+
|
| 177 |
+
def _mean_hiddens(self, v):
|
| 178 |
+
"""Computes the probabilities P(h=1|v).
|
| 179 |
+
|
| 180 |
+
Parameters
|
| 181 |
+
----------
|
| 182 |
+
v : ndarray of shape (n_samples, n_features)
|
| 183 |
+
Values of the visible layer.
|
| 184 |
+
|
| 185 |
+
Returns
|
| 186 |
+
-------
|
| 187 |
+
h : ndarray of shape (n_samples, n_components)
|
| 188 |
+
Corresponding mean field values for the hidden layer.
|
| 189 |
+
"""
|
| 190 |
+
p = safe_sparse_dot(v, self.components_.T)
|
| 191 |
+
p += self.intercept_hidden_
|
| 192 |
+
return expit(p, out=p)
|
| 193 |
+
|
| 194 |
+
def _sample_hiddens(self, v, rng):
|
| 195 |
+
"""Sample from the distribution P(h|v).
|
| 196 |
+
|
| 197 |
+
Parameters
|
| 198 |
+
----------
|
| 199 |
+
v : ndarray of shape (n_samples, n_features)
|
| 200 |
+
Values of the visible layer to sample from.
|
| 201 |
+
|
| 202 |
+
rng : RandomState instance
|
| 203 |
+
Random number generator to use.
|
| 204 |
+
|
| 205 |
+
Returns
|
| 206 |
+
-------
|
| 207 |
+
h : ndarray of shape (n_samples, n_components)
|
| 208 |
+
Values of the hidden layer.
|
| 209 |
+
"""
|
| 210 |
+
p = self._mean_hiddens(v)
|
| 211 |
+
return rng.uniform(size=p.shape) < p
|
| 212 |
+
|
| 213 |
+
def _sample_visibles(self, h, rng):
|
| 214 |
+
"""Sample from the distribution P(v|h).
|
| 215 |
+
|
| 216 |
+
Parameters
|
| 217 |
+
----------
|
| 218 |
+
h : ndarray of shape (n_samples, n_components)
|
| 219 |
+
Values of the hidden layer to sample from.
|
| 220 |
+
|
| 221 |
+
rng : RandomState instance
|
| 222 |
+
Random number generator to use.
|
| 223 |
+
|
| 224 |
+
Returns
|
| 225 |
+
-------
|
| 226 |
+
v : ndarray of shape (n_samples, n_features)
|
| 227 |
+
Values of the visible layer.
|
| 228 |
+
"""
|
| 229 |
+
p = np.dot(h, self.components_)
|
| 230 |
+
p += self.intercept_visible_
|
| 231 |
+
expit(p, out=p)
|
| 232 |
+
return rng.uniform(size=p.shape) < p
|
| 233 |
+
|
| 234 |
+
def _free_energy(self, v):
|
| 235 |
+
"""Computes the free energy F(v) = - log sum_h exp(-E(v,h)).
|
| 236 |
+
|
| 237 |
+
Parameters
|
| 238 |
+
----------
|
| 239 |
+
v : ndarray of shape (n_samples, n_features)
|
| 240 |
+
Values of the visible layer.
|
| 241 |
+
|
| 242 |
+
Returns
|
| 243 |
+
-------
|
| 244 |
+
free_energy : ndarray of shape (n_samples,)
|
| 245 |
+
The value of the free energy.
|
| 246 |
+
"""
|
| 247 |
+
return -safe_sparse_dot(v, self.intercept_visible_) - np.logaddexp(
|
| 248 |
+
0, safe_sparse_dot(v, self.components_.T) + self.intercept_hidden_
|
| 249 |
+
).sum(axis=1)
|
| 250 |
+
|
| 251 |
+
def gibbs(self, v):
|
| 252 |
+
"""Perform one Gibbs sampling step.
|
| 253 |
+
|
| 254 |
+
Parameters
|
| 255 |
+
----------
|
| 256 |
+
v : ndarray of shape (n_samples, n_features)
|
| 257 |
+
Values of the visible layer to start from.
|
| 258 |
+
|
| 259 |
+
Returns
|
| 260 |
+
-------
|
| 261 |
+
v_new : ndarray of shape (n_samples, n_features)
|
| 262 |
+
Values of the visible layer after one Gibbs step.
|
| 263 |
+
"""
|
| 264 |
+
check_is_fitted(self)
|
| 265 |
+
if not hasattr(self, "random_state_"):
|
| 266 |
+
self.random_state_ = check_random_state(self.random_state)
|
| 267 |
+
h_ = self._sample_hiddens(v, self.random_state_)
|
| 268 |
+
v_ = self._sample_visibles(h_, self.random_state_)
|
| 269 |
+
|
| 270 |
+
return v_
|
| 271 |
+
|
| 272 |
+
@_fit_context(prefer_skip_nested_validation=True)
|
| 273 |
+
def partial_fit(self, X, y=None):
|
| 274 |
+
"""Fit the model to the partial segment of the data X.
|
| 275 |
+
|
| 276 |
+
Parameters
|
| 277 |
+
----------
|
| 278 |
+
X : ndarray of shape (n_samples, n_features)
|
| 279 |
+
Training data.
|
| 280 |
+
|
| 281 |
+
y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None
|
| 282 |
+
Target values (None for unsupervised transformations).
|
| 283 |
+
|
| 284 |
+
Returns
|
| 285 |
+
-------
|
| 286 |
+
self : BernoulliRBM
|
| 287 |
+
The fitted model.
|
| 288 |
+
"""
|
| 289 |
+
first_pass = not hasattr(self, "components_")
|
| 290 |
+
X = validate_data(
|
| 291 |
+
self, X, accept_sparse="csr", dtype=np.float64, reset=first_pass
|
| 292 |
+
)
|
| 293 |
+
if not hasattr(self, "random_state_"):
|
| 294 |
+
self.random_state_ = check_random_state(self.random_state)
|
| 295 |
+
if not hasattr(self, "components_"):
|
| 296 |
+
self.components_ = np.asarray(
|
| 297 |
+
self.random_state_.normal(0, 0.01, (self.n_components, X.shape[1])),
|
| 298 |
+
order="F",
|
| 299 |
+
)
|
| 300 |
+
self._n_features_out = self.components_.shape[0]
|
| 301 |
+
if not hasattr(self, "intercept_hidden_"):
|
| 302 |
+
self.intercept_hidden_ = np.zeros(
|
| 303 |
+
self.n_components,
|
| 304 |
+
)
|
| 305 |
+
if not hasattr(self, "intercept_visible_"):
|
| 306 |
+
self.intercept_visible_ = np.zeros(
|
| 307 |
+
X.shape[1],
|
| 308 |
+
)
|
| 309 |
+
if not hasattr(self, "h_samples_"):
|
| 310 |
+
self.h_samples_ = np.zeros((self.batch_size, self.n_components))
|
| 311 |
+
|
| 312 |
+
self._fit(X, self.random_state_)
|
| 313 |
+
|
| 314 |
+
def _fit(self, v_pos, rng):
|
| 315 |
+
"""Inner fit for one mini-batch.
|
| 316 |
+
|
| 317 |
+
Adjust the parameters to maximize the likelihood of v using
|
| 318 |
+
Stochastic Maximum Likelihood (SML).
|
| 319 |
+
|
| 320 |
+
Parameters
|
| 321 |
+
----------
|
| 322 |
+
v_pos : ndarray of shape (n_samples, n_features)
|
| 323 |
+
The data to use for training.
|
| 324 |
+
|
| 325 |
+
rng : RandomState instance
|
| 326 |
+
Random number generator to use for sampling.
|
| 327 |
+
"""
|
| 328 |
+
h_pos = self._mean_hiddens(v_pos)
|
| 329 |
+
v_neg = self._sample_visibles(self.h_samples_, rng)
|
| 330 |
+
h_neg = self._mean_hiddens(v_neg)
|
| 331 |
+
|
| 332 |
+
lr = float(self.learning_rate) / v_pos.shape[0]
|
| 333 |
+
update = safe_sparse_dot(v_pos.T, h_pos, dense_output=True).T
|
| 334 |
+
update -= np.dot(h_neg.T, v_neg)
|
| 335 |
+
self.components_ += lr * update
|
| 336 |
+
self.intercept_hidden_ += lr * (h_pos.sum(axis=0) - h_neg.sum(axis=0))
|
| 337 |
+
self.intercept_visible_ += lr * (
|
| 338 |
+
np.asarray(v_pos.sum(axis=0)).squeeze() - v_neg.sum(axis=0)
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
h_neg[rng.uniform(size=h_neg.shape) < h_neg] = 1.0 # sample binomial
|
| 342 |
+
self.h_samples_ = np.floor(h_neg, h_neg)
|
| 343 |
+
|
| 344 |
+
def score_samples(self, X):
|
| 345 |
+
"""Compute the pseudo-likelihood of X.
|
| 346 |
+
|
| 347 |
+
Parameters
|
| 348 |
+
----------
|
| 349 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
| 350 |
+
Values of the visible layer. Must be all-boolean (not checked).
|
| 351 |
+
|
| 352 |
+
Returns
|
| 353 |
+
-------
|
| 354 |
+
pseudo_likelihood : ndarray of shape (n_samples,)
|
| 355 |
+
Value of the pseudo-likelihood (proxy for likelihood).
|
| 356 |
+
|
| 357 |
+
Notes
|
| 358 |
+
-----
|
| 359 |
+
This method is not deterministic: it computes a quantity called the
|
| 360 |
+
free energy on X, then on a randomly corrupted version of X, and
|
| 361 |
+
returns the log of the logistic function of the difference.
|
| 362 |
+
"""
|
| 363 |
+
check_is_fitted(self)
|
| 364 |
+
|
| 365 |
+
v = validate_data(self, X, accept_sparse="csr", reset=False)
|
| 366 |
+
rng = check_random_state(self.random_state)
|
| 367 |
+
|
| 368 |
+
# Randomly corrupt one feature in each sample in v.
|
| 369 |
+
ind = (np.arange(v.shape[0]), rng.randint(0, v.shape[1], v.shape[0]))
|
| 370 |
+
if sp.issparse(v):
|
| 371 |
+
data = -2 * v[ind] + 1
|
| 372 |
+
if isinstance(data, np.matrix): # v is a sparse matrix
|
| 373 |
+
v_ = v + sp.csr_matrix((data.A.ravel(), ind), shape=v.shape)
|
| 374 |
+
else: # v is a sparse array
|
| 375 |
+
v_ = v + sp.csr_array((data.ravel(), ind), shape=v.shape)
|
| 376 |
+
else:
|
| 377 |
+
v_ = v.copy()
|
| 378 |
+
v_[ind] = 1 - v_[ind]
|
| 379 |
+
|
| 380 |
+
fe = self._free_energy(v)
|
| 381 |
+
fe_ = self._free_energy(v_)
|
| 382 |
+
# log(expit(x)) = log(1 / (1 + exp(-x)) = -np.logaddexp(0, -x)
|
| 383 |
+
return -v.shape[1] * np.logaddexp(0, -(fe_ - fe))
|
| 384 |
+
|
| 385 |
+
@_fit_context(prefer_skip_nested_validation=True)
|
| 386 |
+
def fit(self, X, y=None):
|
| 387 |
+
"""Fit the model to the data X.
|
| 388 |
+
|
| 389 |
+
Parameters
|
| 390 |
+
----------
|
| 391 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
| 392 |
+
Training data.
|
| 393 |
+
|
| 394 |
+
y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None
|
| 395 |
+
Target values (None for unsupervised transformations).
|
| 396 |
+
|
| 397 |
+
Returns
|
| 398 |
+
-------
|
| 399 |
+
self : BernoulliRBM
|
| 400 |
+
The fitted model.
|
| 401 |
+
"""
|
| 402 |
+
X = validate_data(self, X, accept_sparse="csr", dtype=(np.float64, np.float32))
|
| 403 |
+
n_samples = X.shape[0]
|
| 404 |
+
rng = check_random_state(self.random_state)
|
| 405 |
+
|
| 406 |
+
self.components_ = np.asarray(
|
| 407 |
+
rng.normal(0, 0.01, (self.n_components, X.shape[1])),
|
| 408 |
+
order="F",
|
| 409 |
+
dtype=X.dtype,
|
| 410 |
+
)
|
| 411 |
+
self._n_features_out = self.components_.shape[0]
|
| 412 |
+
self.intercept_hidden_ = np.zeros(self.n_components, dtype=X.dtype)
|
| 413 |
+
self.intercept_visible_ = np.zeros(X.shape[1], dtype=X.dtype)
|
| 414 |
+
self.h_samples_ = np.zeros((self.batch_size, self.n_components), dtype=X.dtype)
|
| 415 |
+
|
| 416 |
+
n_batches = int(np.ceil(float(n_samples) / self.batch_size))
|
| 417 |
+
batch_slices = list(
|
| 418 |
+
gen_even_slices(n_batches * self.batch_size, n_batches, n_samples=n_samples)
|
| 419 |
+
)
|
| 420 |
+
verbose = self.verbose
|
| 421 |
+
begin = time.time()
|
| 422 |
+
for iteration in range(1, self.n_iter + 1):
|
| 423 |
+
for batch_slice in batch_slices:
|
| 424 |
+
self._fit(X[batch_slice], rng)
|
| 425 |
+
|
| 426 |
+
if verbose:
|
| 427 |
+
end = time.time()
|
| 428 |
+
print(
|
| 429 |
+
"[%s] Iteration %d, pseudo-likelihood = %.2f, time = %.2fs"
|
| 430 |
+
% (
|
| 431 |
+
type(self).__name__,
|
| 432 |
+
iteration,
|
| 433 |
+
self.score_samples(X).mean(),
|
| 434 |
+
end - begin,
|
| 435 |
+
)
|
| 436 |
+
)
|
| 437 |
+
begin = end
|
| 438 |
+
|
| 439 |
+
return self
|
| 440 |
+
|
| 441 |
+
def __sklearn_tags__(self):
|
| 442 |
+
tags = super().__sklearn_tags__()
|
| 443 |
+
tags.input_tags.sparse = True
|
| 444 |
+
tags.transformer_tags.preserves_dtype = ["float64", "float32"]
|
| 445 |
+
return tags
|
shared/package-files/06/062ff42827438675946e1f4a5b01a82e457805327a161d054fc990538d4851af/test__shgo.py
ADDED
|
@@ -0,0 +1,1156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import time
|
| 6 |
+
from multiprocessing import Pool
|
| 7 |
+
from numpy.testing import assert_allclose, IS_PYPY
|
| 8 |
+
import pytest
|
| 9 |
+
from pytest import raises as assert_raises, warns
|
| 10 |
+
from scipy.optimize import (shgo, Bounds, minimize_scalar, minimize, rosen,
|
| 11 |
+
rosen_der, rosen_hess, NonlinearConstraint)
|
| 12 |
+
from scipy.optimize._constraints import new_constraint_to_old
|
| 13 |
+
from scipy.optimize._shgo import SHGO
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class StructTestFunction:
|
| 17 |
+
def __init__(self, bounds, expected_x, expected_fun=None,
|
| 18 |
+
expected_xl=None, expected_funl=None):
|
| 19 |
+
self.bounds = bounds
|
| 20 |
+
self.expected_x = expected_x
|
| 21 |
+
self.expected_fun = expected_fun
|
| 22 |
+
self.expected_xl = expected_xl
|
| 23 |
+
self.expected_funl = expected_funl
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def wrap_constraints(g):
|
| 27 |
+
cons = []
|
| 28 |
+
if g is not None:
|
| 29 |
+
if not isinstance(g, (tuple, list)):
|
| 30 |
+
g = (g,)
|
| 31 |
+
else:
|
| 32 |
+
pass
|
| 33 |
+
for g in g:
|
| 34 |
+
cons.append({'type': 'ineq',
|
| 35 |
+
'fun': g})
|
| 36 |
+
cons = tuple(cons)
|
| 37 |
+
else:
|
| 38 |
+
cons = None
|
| 39 |
+
return cons
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class StructTest1(StructTestFunction):
|
| 43 |
+
def f(self, x):
|
| 44 |
+
return x[0] ** 2 + x[1] ** 2
|
| 45 |
+
|
| 46 |
+
def g(x):
|
| 47 |
+
return -(np.sum(x, axis=0) - 6.0)
|
| 48 |
+
|
| 49 |
+
cons = wrap_constraints(g)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
test1_1 = StructTest1(bounds=[(-1, 6), (-1, 6)],
|
| 53 |
+
expected_x=[0, 0])
|
| 54 |
+
test1_2 = StructTest1(bounds=[(0, 1), (0, 1)],
|
| 55 |
+
expected_x=[0, 0])
|
| 56 |
+
test1_3 = StructTest1(bounds=[(None, None), (None, None)],
|
| 57 |
+
expected_x=[0, 0])
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class StructTest2(StructTestFunction):
|
| 61 |
+
"""
|
| 62 |
+
Scalar function with several minima to test all minimiser retrievals
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def f(self, x):
|
| 66 |
+
return (x - 30) * np.sin(x)
|
| 67 |
+
|
| 68 |
+
def g(x):
|
| 69 |
+
return 58 - np.sum(x, axis=0)
|
| 70 |
+
|
| 71 |
+
cons = wrap_constraints(g)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
test2_1 = StructTest2(bounds=[(0, 60)],
|
| 75 |
+
expected_x=[1.53567906],
|
| 76 |
+
expected_fun=-28.44677132,
|
| 77 |
+
# Important: test that funl return is in the correct
|
| 78 |
+
# order
|
| 79 |
+
expected_xl=np.array([[1.53567906],
|
| 80 |
+
[55.01782167],
|
| 81 |
+
[7.80894889],
|
| 82 |
+
[48.74797493],
|
| 83 |
+
[14.07445705],
|
| 84 |
+
[42.4913859],
|
| 85 |
+
[20.31743841],
|
| 86 |
+
[36.28607535],
|
| 87 |
+
[26.43039605],
|
| 88 |
+
[30.76371366]]),
|
| 89 |
+
|
| 90 |
+
expected_funl=np.array([-28.44677132, -24.99785984,
|
| 91 |
+
-22.16855376, -18.72136195,
|
| 92 |
+
-15.89423937, -12.45154942,
|
| 93 |
+
-9.63133158, -6.20801301,
|
| 94 |
+
-3.43727232, -0.46353338])
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
test2_2 = StructTest2(bounds=[(0, 4.5)],
|
| 98 |
+
expected_x=[1.53567906],
|
| 99 |
+
expected_fun=[-28.44677132],
|
| 100 |
+
expected_xl=np.array([[1.53567906]]),
|
| 101 |
+
expected_funl=np.array([-28.44677132])
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class StructTest3(StructTestFunction):
|
| 106 |
+
"""
|
| 107 |
+
Hock and Schittkowski 18 problem (HS18). Hoch and Schittkowski (1981)
|
| 108 |
+
http://www.ai7.uni-bayreuth.de/test_problem_coll.pdf
|
| 109 |
+
Minimize: f = 0.01 * (x_1)**2 + (x_2)**2
|
| 110 |
+
|
| 111 |
+
Subject to: x_1 * x_2 - 25.0 >= 0,
|
| 112 |
+
(x_1)**2 + (x_2)**2 - 25.0 >= 0,
|
| 113 |
+
2 <= x_1 <= 50,
|
| 114 |
+
0 <= x_2 <= 50.
|
| 115 |
+
|
| 116 |
+
Approx. Answer:
|
| 117 |
+
f([(250)**0.5 , (2.5)**0.5]) = 5.0
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
# amended to test vectorisation of constraints
|
| 123 |
+
def f(self, x):
|
| 124 |
+
return 0.01 * (x[0]) ** 2 + (x[1]) ** 2
|
| 125 |
+
|
| 126 |
+
def g1(x):
|
| 127 |
+
return x[0] * x[1] - 25.0
|
| 128 |
+
|
| 129 |
+
def g2(x):
|
| 130 |
+
return x[0] ** 2 + x[1] ** 2 - 25.0
|
| 131 |
+
|
| 132 |
+
# g = (g1, g2)
|
| 133 |
+
# cons = wrap_constraints(g)
|
| 134 |
+
|
| 135 |
+
def g(x):
|
| 136 |
+
return x[0] * x[1] - 25.0, x[0] ** 2 + x[1] ** 2 - 25.0
|
| 137 |
+
|
| 138 |
+
# this checks that shgo can be sent new-style constraints
|
| 139 |
+
__nlc = NonlinearConstraint(g, 0, np.inf)
|
| 140 |
+
cons = (__nlc,)
|
| 141 |
+
|
| 142 |
+
test3_1 = StructTest3(bounds=[(2, 50), (0, 50)],
|
| 143 |
+
expected_x=[250 ** 0.5, 2.5 ** 0.5],
|
| 144 |
+
expected_fun=5.0
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class StructTest4(StructTestFunction):
|
| 149 |
+
"""
|
| 150 |
+
Hock and Schittkowski 11 problem (HS11). Hoch and Schittkowski (1981)
|
| 151 |
+
|
| 152 |
+
NOTE: Did not find in original reference to HS collection, refer to
|
| 153 |
+
Henderson (2015) problem 7 instead. 02.03.2016
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
def f(self, x):
|
| 157 |
+
return ((x[0] - 10) ** 2 + 5 * (x[1] - 12) ** 2 + x[2] ** 4
|
| 158 |
+
+ 3 * (x[3] - 11) ** 2 + 10 * x[4] ** 6 + 7 * x[5] ** 2 + x[
|
| 159 |
+
6] ** 4
|
| 160 |
+
- 4 * x[5] * x[6] - 10 * x[5] - 8 * x[6]
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
def g1(x):
|
| 164 |
+
return -(2 * x[0] ** 2 + 3 * x[1] ** 4 + x[2] + 4 * x[3] ** 2
|
| 165 |
+
+ 5 * x[4] - 127)
|
| 166 |
+
|
| 167 |
+
def g2(x):
|
| 168 |
+
return -(7 * x[0] + 3 * x[1] + 10 * x[2] ** 2 + x[3] - x[4] - 282.0)
|
| 169 |
+
|
| 170 |
+
def g3(x):
|
| 171 |
+
return -(23 * x[0] + x[1] ** 2 + 6 * x[5] ** 2 - 8 * x[6] - 196)
|
| 172 |
+
|
| 173 |
+
def g4(x):
|
| 174 |
+
return -(4 * x[0] ** 2 + x[1] ** 2 - 3 * x[0] * x[1] + 2 * x[2] ** 2
|
| 175 |
+
+ 5 * x[5] - 11 * x[6])
|
| 176 |
+
|
| 177 |
+
g = (g1, g2, g3, g4)
|
| 178 |
+
|
| 179 |
+
cons = wrap_constraints(g)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
test4_1 = StructTest4(bounds=[(-10, 10), ] * 7,
|
| 183 |
+
expected_x=[2.330499, 1.951372, -0.4775414,
|
| 184 |
+
4.365726, -0.6244870, 1.038131, 1.594227],
|
| 185 |
+
expected_fun=680.6300573
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class StructTest5(StructTestFunction):
|
| 190 |
+
def f(self, x):
|
| 191 |
+
return (
|
| 192 |
+
-(x[1] + 47.0)*np.sin(np.sqrt(abs(x[0]/2.0 + (x[1] + 47.0))))
|
| 193 |
+
- x[0]*np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0))))
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
g = None
|
| 197 |
+
cons = wrap_constraints(g)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
test5_1 = StructTest5(bounds=[(-512, 512), (-512, 512)],
|
| 201 |
+
expected_fun=[-959.64066272085051],
|
| 202 |
+
expected_x=[512., 404.23180542])
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class StructTestLJ(StructTestFunction):
|
| 206 |
+
"""
|
| 207 |
+
LennardJones objective function. Used to test symmetry constraints
|
| 208 |
+
settings.
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
def f(self, x, *args):
|
| 212 |
+
print(f'x = {x}')
|
| 213 |
+
self.N = args[0]
|
| 214 |
+
k = int(self.N / 3)
|
| 215 |
+
s = 0.0
|
| 216 |
+
|
| 217 |
+
for i in range(k - 1):
|
| 218 |
+
for j in range(i + 1, k):
|
| 219 |
+
a = 3 * i
|
| 220 |
+
b = 3 * j
|
| 221 |
+
xd = x[a] - x[b]
|
| 222 |
+
yd = x[a + 1] - x[b + 1]
|
| 223 |
+
zd = x[a + 2] - x[b + 2]
|
| 224 |
+
ed = xd * xd + yd * yd + zd * zd
|
| 225 |
+
ud = ed * ed * ed
|
| 226 |
+
if ed > 0.0:
|
| 227 |
+
s += (1.0 / ud - 2.0) / ud
|
| 228 |
+
|
| 229 |
+
return s
|
| 230 |
+
|
| 231 |
+
g = None
|
| 232 |
+
cons = wrap_constraints(g)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
N = 6
|
| 236 |
+
boundsLJ = list(zip([-4.0] * 6, [4.0] * 6))
|
| 237 |
+
|
| 238 |
+
testLJ = StructTestLJ(bounds=boundsLJ,
|
| 239 |
+
expected_fun=[-1.0],
|
| 240 |
+
expected_x=None,
|
| 241 |
+
# expected_x=[-2.71247337e-08,
|
| 242 |
+
# -2.71247337e-08,
|
| 243 |
+
# -2.50000222e+00,
|
| 244 |
+
# -2.71247337e-08,
|
| 245 |
+
# -2.71247337e-08,
|
| 246 |
+
# -1.50000222e+00]
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class StructTestS(StructTestFunction):
|
| 251 |
+
def f(self, x):
|
| 252 |
+
return ((x[0] - 0.5) ** 2 + (x[1] - 0.5) ** 2
|
| 253 |
+
+ (x[2] - 0.5) ** 2 + (x[3] - 0.5) ** 2)
|
| 254 |
+
|
| 255 |
+
g = None
|
| 256 |
+
cons = wrap_constraints(g)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
test_s = StructTestS(bounds=[(0, 2.0), ] * 4,
|
| 260 |
+
expected_fun=0.0,
|
| 261 |
+
expected_x=np.ones(4) - 0.5
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class StructTestTable(StructTestFunction):
|
| 266 |
+
def f(self, x):
|
| 267 |
+
if x[0] == 3.0 and x[1] == 3.0:
|
| 268 |
+
return 50
|
| 269 |
+
else:
|
| 270 |
+
return 100
|
| 271 |
+
|
| 272 |
+
g = None
|
| 273 |
+
cons = wrap_constraints(g)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
test_table = StructTestTable(bounds=[(-10, 10), (-10, 10)],
|
| 277 |
+
expected_fun=[50],
|
| 278 |
+
expected_x=[3.0, 3.0])
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class StructTestInfeasible(StructTestFunction):
|
| 282 |
+
"""
|
| 283 |
+
Test function with no feasible domain.
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
def f(self, x, *args):
|
| 287 |
+
return x[0] ** 2 + x[1] ** 2
|
| 288 |
+
|
| 289 |
+
def g1(x):
|
| 290 |
+
return x[0] + x[1] - 1
|
| 291 |
+
|
| 292 |
+
def g2(x):
|
| 293 |
+
return -(x[0] + x[1] - 1)
|
| 294 |
+
|
| 295 |
+
def g3(x):
|
| 296 |
+
return -x[0] + x[1] - 1
|
| 297 |
+
|
| 298 |
+
def g4(x):
|
| 299 |
+
return -(-x[0] + x[1] - 1)
|
| 300 |
+
|
| 301 |
+
g = (g1, g2, g3, g4)
|
| 302 |
+
cons = wrap_constraints(g)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
test_infeasible = StructTestInfeasible(bounds=[(2, 50), (-1, 1)],
|
| 306 |
+
expected_fun=None,
|
| 307 |
+
expected_x=None
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
@pytest.mark.skip("Not a test")
|
| 312 |
+
def run_test(test, args=(), test_atol=1e-5, n=100, iters=None,
|
| 313 |
+
callback=None, minimizer_kwargs=None, options=None,
|
| 314 |
+
sampling_method='sobol', workers=1):
|
| 315 |
+
res = shgo(test.f, test.bounds, args=args, constraints=test.cons,
|
| 316 |
+
n=n, iters=iters, callback=callback,
|
| 317 |
+
minimizer_kwargs=minimizer_kwargs, options=options,
|
| 318 |
+
sampling_method=sampling_method, workers=workers)
|
| 319 |
+
|
| 320 |
+
print(f'res = {res}')
|
| 321 |
+
logging.info(f'res = {res}')
|
| 322 |
+
if test.expected_x is not None:
|
| 323 |
+
np.testing.assert_allclose(res.x, test.expected_x,
|
| 324 |
+
rtol=test_atol,
|
| 325 |
+
atol=test_atol)
|
| 326 |
+
|
| 327 |
+
# (Optional tests)
|
| 328 |
+
if test.expected_fun is not None:
|
| 329 |
+
np.testing.assert_allclose(res.fun,
|
| 330 |
+
test.expected_fun,
|
| 331 |
+
atol=test_atol)
|
| 332 |
+
|
| 333 |
+
if test.expected_xl is not None:
|
| 334 |
+
np.testing.assert_allclose(res.xl,
|
| 335 |
+
test.expected_xl,
|
| 336 |
+
atol=test_atol)
|
| 337 |
+
|
| 338 |
+
if test.expected_funl is not None:
|
| 339 |
+
np.testing.assert_allclose(res.funl,
|
| 340 |
+
test.expected_funl,
|
| 341 |
+
atol=test_atol)
|
| 342 |
+
return
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
# Base test functions:
|
| 346 |
+
class TestShgoSobolTestFunctions:
|
| 347 |
+
"""
|
| 348 |
+
Global optimisation tests with Sobol sampling:
|
| 349 |
+
"""
|
| 350 |
+
|
| 351 |
+
# Sobol algorithm
|
| 352 |
+
def test_f1_1_sobol(self):
|
| 353 |
+
"""Multivariate test function 1:
|
| 354 |
+
x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]"""
|
| 355 |
+
run_test(test1_1)
|
| 356 |
+
|
| 357 |
+
def test_f1_2_sobol(self):
|
| 358 |
+
"""Multivariate test function 1:
|
| 359 |
+
x[0]**2 + x[1]**2 with bounds=[(0, 1), (0, 1)]"""
|
| 360 |
+
run_test(test1_2)
|
| 361 |
+
|
| 362 |
+
def test_f1_3_sobol(self):
|
| 363 |
+
"""Multivariate test function 1:
|
| 364 |
+
x[0]**2 + x[1]**2 with bounds=[(None, None),(None, None)]"""
|
| 365 |
+
options = {'disp': True}
|
| 366 |
+
run_test(test1_3, options=options)
|
| 367 |
+
|
| 368 |
+
def test_f2_1_sobol(self):
|
| 369 |
+
"""Univariate test function on
|
| 370 |
+
f(x) = (x - 30) * sin(x) with bounds=[(0, 60)]"""
|
| 371 |
+
run_test(test2_1)
|
| 372 |
+
|
| 373 |
+
def test_f2_2_sobol(self):
|
| 374 |
+
"""Univariate test function on
|
| 375 |
+
f(x) = (x - 30) * sin(x) bounds=[(0, 4.5)]"""
|
| 376 |
+
run_test(test2_2)
|
| 377 |
+
|
| 378 |
+
def test_f3_sobol(self):
|
| 379 |
+
"""NLP: Hock and Schittkowski problem 18"""
|
| 380 |
+
run_test(test3_1)
|
| 381 |
+
|
| 382 |
+
@pytest.mark.slow
|
| 383 |
+
def test_f4_sobol(self):
|
| 384 |
+
"""NLP: (High dimensional) Hock and Schittkowski 11 problem (HS11)"""
|
| 385 |
+
options = {'infty_constraints': False}
|
| 386 |
+
# run_test(test4_1, n=990, options=options)
|
| 387 |
+
run_test(test4_1, n=990 * 2, options=options)
|
| 388 |
+
|
| 389 |
+
def test_f5_1_sobol(self):
|
| 390 |
+
"""NLP: Eggholder, multimodal"""
|
| 391 |
+
# run_test(test5_1, n=30)
|
| 392 |
+
run_test(test5_1, n=60)
|
| 393 |
+
|
| 394 |
+
def test_f5_2_sobol(self):
|
| 395 |
+
"""NLP: Eggholder, multimodal"""
|
| 396 |
+
# run_test(test5_1, n=60, iters=5)
|
| 397 |
+
run_test(test5_1, n=60, iters=5)
|
| 398 |
+
|
| 399 |
+
# def test_t911(self):
|
| 400 |
+
# """1D tabletop function"""
|
| 401 |
+
# run_test(test11_1)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class TestShgoSimplicialTestFunctions:
|
| 405 |
+
"""
|
| 406 |
+
Global optimisation tests with Simplicial sampling:
|
| 407 |
+
"""
|
| 408 |
+
|
| 409 |
+
def test_f1_1_simplicial(self):
|
| 410 |
+
"""Multivariate test function 1:
|
| 411 |
+
x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]"""
|
| 412 |
+
run_test(test1_1, n=1, sampling_method='simplicial')
|
| 413 |
+
|
| 414 |
+
def test_f1_2_simplicial(self):
|
| 415 |
+
"""Multivariate test function 1:
|
| 416 |
+
x[0]**2 + x[1]**2 with bounds=[(0, 1), (0, 1)]"""
|
| 417 |
+
run_test(test1_2, n=1, sampling_method='simplicial')
|
| 418 |
+
|
| 419 |
+
def test_f1_3_simplicial(self):
|
| 420 |
+
"""Multivariate test function 1: x[0]**2 + x[1]**2
|
| 421 |
+
with bounds=[(None, None),(None, None)]"""
|
| 422 |
+
run_test(test1_3, n=5, sampling_method='simplicial')
|
| 423 |
+
|
| 424 |
+
def test_f2_1_simplicial(self):
|
| 425 |
+
"""Univariate test function on
|
| 426 |
+
f(x) = (x - 30) * sin(x) with bounds=[(0, 60)]"""
|
| 427 |
+
options = {'minimize_every_iter': False}
|
| 428 |
+
run_test(test2_1, n=200, iters=7, options=options,
|
| 429 |
+
sampling_method='simplicial')
|
| 430 |
+
|
| 431 |
+
def test_f2_2_simplicial(self):
|
| 432 |
+
"""Univariate test function on
|
| 433 |
+
f(x) = (x - 30) * sin(x) bounds=[(0, 4.5)]"""
|
| 434 |
+
run_test(test2_2, n=1, sampling_method='simplicial')
|
| 435 |
+
|
| 436 |
+
def test_f3_simplicial(self):
|
| 437 |
+
"""NLP: Hock and Schittkowski problem 18"""
|
| 438 |
+
run_test(test3_1, n=1, sampling_method='simplicial')
|
| 439 |
+
|
| 440 |
+
@pytest.mark.slow
|
| 441 |
+
def test_f4_simplicial(self):
|
| 442 |
+
"""NLP: (High dimensional) Hock and Schittkowski 11 problem (HS11)"""
|
| 443 |
+
run_test(test4_1, n=1, sampling_method='simplicial')
|
| 444 |
+
|
| 445 |
+
def test_lj_symmetry_old(self):
|
| 446 |
+
"""LJ: Symmetry-constrained test function"""
|
| 447 |
+
options = {'symmetry': True,
|
| 448 |
+
'disp': True}
|
| 449 |
+
args = (6,) # Number of atoms
|
| 450 |
+
run_test(testLJ, args=args, n=300,
|
| 451 |
+
options=options, iters=1,
|
| 452 |
+
sampling_method='simplicial')
|
| 453 |
+
|
| 454 |
+
def test_f5_1_lj_symmetry(self):
|
| 455 |
+
"""LJ: Symmetry constrained test function"""
|
| 456 |
+
options = {'symmetry': [0, ] * 6,
|
| 457 |
+
'disp': True}
|
| 458 |
+
args = (6,) # No. of atoms
|
| 459 |
+
|
| 460 |
+
run_test(testLJ, args=args, n=300,
|
| 461 |
+
options=options, iters=1,
|
| 462 |
+
sampling_method='simplicial')
|
| 463 |
+
|
| 464 |
+
def test_f5_2_cons_symmetry(self):
|
| 465 |
+
"""Symmetry constrained test function"""
|
| 466 |
+
options = {'symmetry': [0, 0],
|
| 467 |
+
'disp': True}
|
| 468 |
+
|
| 469 |
+
run_test(test1_1, n=200,
|
| 470 |
+
options=options, iters=1,
|
| 471 |
+
sampling_method='simplicial')
|
| 472 |
+
|
| 473 |
+
@pytest.mark.fail_slow(10)
|
| 474 |
+
def test_f5_3_cons_symmetry(self):
|
| 475 |
+
"""Asymmetrically constrained test function"""
|
| 476 |
+
options = {'symmetry': [0, 0, 0, 3],
|
| 477 |
+
'disp': True}
|
| 478 |
+
|
| 479 |
+
run_test(test_s, n=10000,
|
| 480 |
+
options=options,
|
| 481 |
+
iters=1,
|
| 482 |
+
sampling_method='simplicial')
|
| 483 |
+
|
| 484 |
+
@pytest.mark.skip("Not a test")
|
| 485 |
+
def test_f0_min_variance(self):
|
| 486 |
+
"""Return a minimum on a perfectly symmetric problem, based on
|
| 487 |
+
gh10429"""
|
| 488 |
+
avg = 0.5 # Given average value of x
|
| 489 |
+
cons = {'type': 'eq', 'fun': lambda x: np.mean(x) - avg}
|
| 490 |
+
|
| 491 |
+
# Minimize the variance of x under the given constraint
|
| 492 |
+
res = shgo(np.var, bounds=6 * [(0, 1)], constraints=cons)
|
| 493 |
+
assert res.success
|
| 494 |
+
assert_allclose(res.fun, 0, atol=1e-15)
|
| 495 |
+
assert_allclose(res.x, 0.5)
|
| 496 |
+
|
| 497 |
+
@pytest.mark.skip("Not a test")
|
| 498 |
+
def test_f0_min_variance_1D(self):
|
| 499 |
+
"""Return a minimum on a perfectly symmetric 1D problem, based on
|
| 500 |
+
gh10538"""
|
| 501 |
+
|
| 502 |
+
def fun(x):
|
| 503 |
+
return x * (x - 1.0) * (x - 0.5)
|
| 504 |
+
|
| 505 |
+
bounds = [(0, 1)]
|
| 506 |
+
res = shgo(fun, bounds=bounds)
|
| 507 |
+
ref = minimize_scalar(fun, bounds=bounds[0])
|
| 508 |
+
assert res.success
|
| 509 |
+
assert_allclose(res.fun, ref.fun)
|
| 510 |
+
assert_allclose(res.x, ref.x, rtol=1e-6)
|
| 511 |
+
|
| 512 |
+
# Argument test functions
|
| 513 |
+
class TestShgoArguments:
|
| 514 |
+
def test_1_1_simpl_iter(self):
|
| 515 |
+
"""Iterative simplicial sampling on TestFunction 1 (multivariate)"""
|
| 516 |
+
run_test(test1_2, n=None, iters=2, sampling_method='simplicial')
|
| 517 |
+
|
| 518 |
+
def test_1_2_simpl_iter(self):
|
| 519 |
+
"""Iterative simplicial on TestFunction 2 (univariate)"""
|
| 520 |
+
options = {'minimize_every_iter': False}
|
| 521 |
+
run_test(test2_1, n=None, iters=9, options=options,
|
| 522 |
+
sampling_method='simplicial')
|
| 523 |
+
|
| 524 |
+
def test_2_1_sobol_iter(self):
|
| 525 |
+
"""Iterative Sobol sampling on TestFunction 1 (multivariate)"""
|
| 526 |
+
run_test(test1_2, n=None, iters=1, sampling_method='sobol')
|
| 527 |
+
|
| 528 |
+
def test_2_2_sobol_iter(self):
|
| 529 |
+
"""Iterative Sobol sampling on TestFunction 2 (univariate)"""
|
| 530 |
+
res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons,
|
| 531 |
+
n=None, iters=1, sampling_method='sobol')
|
| 532 |
+
|
| 533 |
+
np.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5, atol=1e-5)
|
| 534 |
+
np.testing.assert_allclose(res.fun, test2_1.expected_fun, atol=1e-5)
|
| 535 |
+
|
| 536 |
+
def test_3_1_disp_simplicial(self):
|
| 537 |
+
"""Iterative sampling on TestFunction 1 and 2 (multi and univariate)
|
| 538 |
+
"""
|
| 539 |
+
|
| 540 |
+
def callback_func(x):
|
| 541 |
+
print("Local minimization callback test")
|
| 542 |
+
|
| 543 |
+
for test in [test1_1, test2_1]:
|
| 544 |
+
shgo(test.f, test.bounds, iters=1,
|
| 545 |
+
sampling_method='simplicial',
|
| 546 |
+
callback=callback_func, options={'disp': True})
|
| 547 |
+
shgo(test.f, test.bounds, n=1, sampling_method='simplicial',
|
| 548 |
+
callback=callback_func, options={'disp': True})
|
| 549 |
+
|
| 550 |
+
def test_3_2_disp_sobol(self):
|
| 551 |
+
"""Iterative sampling on TestFunction 1 and 2 (multi and univariate)"""
|
| 552 |
+
|
| 553 |
+
def callback_func(x):
|
| 554 |
+
print("Local minimization callback test")
|
| 555 |
+
|
| 556 |
+
for test in [test1_1, test2_1]:
|
| 557 |
+
shgo(test.f, test.bounds, iters=1, sampling_method='sobol',
|
| 558 |
+
callback=callback_func, options={'disp': True})
|
| 559 |
+
|
| 560 |
+
shgo(test.f, test.bounds, n=1, sampling_method='simplicial',
|
| 561 |
+
callback=callback_func, options={'disp': True})
|
| 562 |
+
|
| 563 |
+
def test_args_gh14589(self):
|
| 564 |
+
"""Using `args` used to cause `shgo` to fail; see #14589, #15986,
|
| 565 |
+
#16506"""
|
| 566 |
+
res = shgo(func=lambda x, y, z: x * z + y, bounds=[(0, 3)], args=(1, 2)
|
| 567 |
+
)
|
| 568 |
+
ref = shgo(func=lambda x: 2 * x + 1, bounds=[(0, 3)])
|
| 569 |
+
assert_allclose(res.fun, ref.fun)
|
| 570 |
+
assert_allclose(res.x, ref.x)
|
| 571 |
+
|
| 572 |
+
@pytest.mark.slow
|
| 573 |
+
def test_4_1_known_f_min(self):
|
| 574 |
+
"""Test known function minima stopping criteria"""
|
| 575 |
+
# Specify known function value
|
| 576 |
+
options = {'f_min': test4_1.expected_fun,
|
| 577 |
+
'f_tol': 1e-6,
|
| 578 |
+
'minimize_every_iter': True}
|
| 579 |
+
# TODO: Make default n higher for faster tests
|
| 580 |
+
run_test(test4_1, n=None, test_atol=1e-5, options=options,
|
| 581 |
+
sampling_method='simplicial')
|
| 582 |
+
|
| 583 |
+
@pytest.mark.slow
|
| 584 |
+
def test_4_2_known_f_min(self):
|
| 585 |
+
"""Test Global mode limiting local evaluations"""
|
| 586 |
+
options = { # Specify known function value
|
| 587 |
+
'f_min': test4_1.expected_fun,
|
| 588 |
+
'f_tol': 1e-6,
|
| 589 |
+
# Specify number of local iterations to perform
|
| 590 |
+
'minimize_every_iter': True,
|
| 591 |
+
'local_iter': 1}
|
| 592 |
+
|
| 593 |
+
run_test(test4_1, n=None, test_atol=1e-5, options=options,
|
| 594 |
+
sampling_method='simplicial')
|
| 595 |
+
|
| 596 |
+
def test_4_4_known_f_min(self):
|
| 597 |
+
"""Test Global mode limiting local evaluations for 1D funcs"""
|
| 598 |
+
options = { # Specify known function value
|
| 599 |
+
'f_min': test2_1.expected_fun,
|
| 600 |
+
'f_tol': 1e-6,
|
| 601 |
+
# Specify number of local iterations to perform+
|
| 602 |
+
'minimize_every_iter': True,
|
| 603 |
+
'local_iter': 1,
|
| 604 |
+
'infty_constraints': False}
|
| 605 |
+
|
| 606 |
+
res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons,
|
| 607 |
+
n=None, iters=None, options=options,
|
| 608 |
+
sampling_method='sobol')
|
| 609 |
+
np.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5, atol=1e-5)
|
| 610 |
+
|
| 611 |
+
def test_5_1_simplicial_argless(self):
|
| 612 |
+
"""Test Default simplicial sampling settings on TestFunction 1"""
|
| 613 |
+
res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons)
|
| 614 |
+
np.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5, atol=1e-5)
|
| 615 |
+
|
| 616 |
+
def test_5_2_sobol_argless(self):
|
| 617 |
+
"""Test Default sobol sampling settings on TestFunction 1"""
|
| 618 |
+
res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons,
|
| 619 |
+
sampling_method='sobol')
|
| 620 |
+
np.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5, atol=1e-5)
|
| 621 |
+
|
| 622 |
+
def test_6_1_simplicial_max_iter(self):
|
| 623 |
+
"""Test that maximum iteration option works on TestFunction 3"""
|
| 624 |
+
options = {'max_iter': 2}
|
| 625 |
+
res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons,
|
| 626 |
+
options=options, sampling_method='simplicial')
|
| 627 |
+
np.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5, atol=1e-5)
|
| 628 |
+
np.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5)
|
| 629 |
+
|
| 630 |
+
def test_6_2_simplicial_min_iter(self):
|
| 631 |
+
"""Test that maximum iteration option works on TestFunction 3"""
|
| 632 |
+
options = {'min_iter': 2}
|
| 633 |
+
res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons,
|
| 634 |
+
options=options, sampling_method='simplicial')
|
| 635 |
+
np.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5, atol=1e-5)
|
| 636 |
+
np.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5)
|
| 637 |
+
|
| 638 |
+
def test_7_1_minkwargs(self):
|
| 639 |
+
"""Test the minimizer_kwargs arguments for solvers with constraints"""
|
| 640 |
+
# Test solvers
|
| 641 |
+
for solver in ['COBYLA', 'COBYQA', 'SLSQP']:
|
| 642 |
+
# Note that passing global constraints to SLSQP is tested in other
|
| 643 |
+
# unittests which run test4_1 normally
|
| 644 |
+
minimizer_kwargs = {'method': solver,
|
| 645 |
+
'constraints': test3_1.cons}
|
| 646 |
+
run_test(test3_1, n=100, test_atol=1e-3,
|
| 647 |
+
minimizer_kwargs=minimizer_kwargs,
|
| 648 |
+
sampling_method='sobol')
|
| 649 |
+
|
| 650 |
+
def test_7_2_minkwargs(self):
|
| 651 |
+
"""Test the minimizer_kwargs default inits"""
|
| 652 |
+
minimizer_kwargs = {'ftol': 1e-5}
|
| 653 |
+
options = {'disp': True} # For coverage purposes
|
| 654 |
+
SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0],
|
| 655 |
+
minimizer_kwargs=minimizer_kwargs, options=options)
|
| 656 |
+
|
| 657 |
+
def test_7_3_minkwargs(self):
|
| 658 |
+
"""Test minimizer_kwargs arguments for solvers without constraints"""
|
| 659 |
+
for solver in ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG',
|
| 660 |
+
'L-BFGS-B', 'TNC', 'dogleg', 'trust-ncg', 'trust-exact',
|
| 661 |
+
'trust-krylov']:
|
| 662 |
+
def jac(x):
|
| 663 |
+
return np.array([2 * x[0], 2 * x[1]]).T
|
| 664 |
+
|
| 665 |
+
def hess(x):
|
| 666 |
+
return np.array([[2, 0], [0, 2]])
|
| 667 |
+
|
| 668 |
+
minimizer_kwargs = {'method': solver,
|
| 669 |
+
'jac': jac,
|
| 670 |
+
'hess': hess}
|
| 671 |
+
logging.info(f"Solver = {solver}")
|
| 672 |
+
logging.info("=" * 100)
|
| 673 |
+
run_test(test1_1, n=100, test_atol=1e-3,
|
| 674 |
+
minimizer_kwargs=minimizer_kwargs,
|
| 675 |
+
sampling_method='sobol')
|
| 676 |
+
|
| 677 |
+
def test_8_homology_group_diff(self):
|
| 678 |
+
options = {'minhgrd': 1,
|
| 679 |
+
'minimize_every_iter': True}
|
| 680 |
+
|
| 681 |
+
run_test(test1_1, n=None, iters=None, options=options,
|
| 682 |
+
sampling_method='simplicial')
|
| 683 |
+
|
| 684 |
+
def test_9_cons_g(self):
|
| 685 |
+
"""Test single function constraint passing"""
|
| 686 |
+
SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0])
|
| 687 |
+
|
| 688 |
+
@pytest.mark.xfail(IS_PYPY and sys.platform == 'win32',
|
| 689 |
+
reason="Failing and fix in PyPy not planned (see gh-18632)")
|
| 690 |
+
def test_10_finite_time(self):
|
| 691 |
+
"""Test single function constraint passing"""
|
| 692 |
+
options = {'maxtime': 1e-15}
|
| 693 |
+
|
| 694 |
+
def f(x):
|
| 695 |
+
time.sleep(1e-14)
|
| 696 |
+
return 0.0
|
| 697 |
+
|
| 698 |
+
res = shgo(f, test1_1.bounds, iters=5, options=options)
|
| 699 |
+
# Assert that only 1 rather than 5 requested iterations ran:
|
| 700 |
+
assert res.nit == 1
|
| 701 |
+
|
| 702 |
+
def test_11_f_min_0(self):
|
| 703 |
+
"""Test to cover the case where f_lowest == 0"""
|
| 704 |
+
options = {'f_min': 0.0,
|
| 705 |
+
'disp': True}
|
| 706 |
+
res = shgo(test1_2.f, test1_2.bounds, n=10, iters=None,
|
| 707 |
+
options=options, sampling_method='sobol')
|
| 708 |
+
np.testing.assert_equal(0, res.x[0])
|
| 709 |
+
np.testing.assert_equal(0, res.x[1])
|
| 710 |
+
|
| 711 |
+
# @nottest
|
| 712 |
+
@pytest.mark.skip(reason="no way of currently testing this")
|
| 713 |
+
def test_12_sobol_inf_cons(self):
|
| 714 |
+
"""Test to cover the case where f_lowest == 0"""
|
| 715 |
+
# TODO: This test doesn't cover anything new, it is unknown what the
|
| 716 |
+
# original test was intended for as it was never complete. Delete or
|
| 717 |
+
# replace in the future.
|
| 718 |
+
options = {'maxtime': 1e-15,
|
| 719 |
+
'f_min': 0.0}
|
| 720 |
+
res = shgo(test1_2.f, test1_2.bounds, n=1, iters=None,
|
| 721 |
+
options=options, sampling_method='sobol')
|
| 722 |
+
np.testing.assert_equal(0.0, res.fun)
|
| 723 |
+
|
| 724 |
+
def test_13_high_sobol(self):
|
| 725 |
+
"""Test init of high-dimensional sobol sequences"""
|
| 726 |
+
|
| 727 |
+
def f(x):
|
| 728 |
+
return 0
|
| 729 |
+
|
| 730 |
+
bounds = [(None, None), ] * 41
|
| 731 |
+
SHGOc = SHGO(f, bounds, sampling_method='sobol')
|
| 732 |
+
# SHGOc.sobol_points(2, 50)
|
| 733 |
+
SHGOc.sampling_function(2, 50)
|
| 734 |
+
|
| 735 |
+
def test_14_local_iter(self):
|
| 736 |
+
"""Test limited local iterations for a pseudo-global mode"""
|
| 737 |
+
options = {'local_iter': 4}
|
| 738 |
+
run_test(test5_1, n=60, options=options)
|
| 739 |
+
|
| 740 |
+
def test_15_min_every_iter(self):
|
| 741 |
+
"""Test minimize every iter options and cover function cache"""
|
| 742 |
+
options = {'minimize_every_iter': True}
|
| 743 |
+
run_test(test1_1, n=1, iters=7, options=options,
|
| 744 |
+
sampling_method='sobol')
|
| 745 |
+
|
| 746 |
+
def test_16_disp_bounds_minimizer(self, capsys):
|
| 747 |
+
"""Test disp=True with minimizers that do not support bounds """
|
| 748 |
+
options = {'disp': True}
|
| 749 |
+
minimizer_kwargs = {'method': 'nelder-mead'}
|
| 750 |
+
run_test(test1_2, sampling_method='simplicial',
|
| 751 |
+
options=options, minimizer_kwargs=minimizer_kwargs)
|
| 752 |
+
|
| 753 |
+
def test_17_custom_sampling(self):
|
| 754 |
+
"""Test the functionality to add custom sampling methods to shgo"""
|
| 755 |
+
|
| 756 |
+
def sample(n, d):
|
| 757 |
+
return np.random.uniform(size=(n, d))
|
| 758 |
+
|
| 759 |
+
run_test(test1_1, n=30, sampling_method=sample)
|
| 760 |
+
|
| 761 |
+
def test_18_bounds_class(self):
|
| 762 |
+
# test that new and old bounds yield same result
|
| 763 |
+
def f(x):
|
| 764 |
+
return np.square(x).sum()
|
| 765 |
+
|
| 766 |
+
lb = [-6., 1., -5.]
|
| 767 |
+
ub = [-1., 3., 5.]
|
| 768 |
+
bounds_old = list(zip(lb, ub))
|
| 769 |
+
bounds_new = Bounds(lb, ub)
|
| 770 |
+
|
| 771 |
+
res_old_bounds = shgo(f, bounds_old)
|
| 772 |
+
res_new_bounds = shgo(f, bounds_new)
|
| 773 |
+
|
| 774 |
+
assert res_new_bounds.nfev == res_old_bounds.nfev
|
| 775 |
+
assert res_new_bounds.message == res_old_bounds.message
|
| 776 |
+
assert res_new_bounds.success == res_old_bounds.success
|
| 777 |
+
x_opt = np.array([-1., 1., 0.])
|
| 778 |
+
np.testing.assert_allclose(res_new_bounds.x, x_opt)
|
| 779 |
+
np.testing.assert_allclose(res_new_bounds.x, res_old_bounds.x)
|
| 780 |
+
|
| 781 |
+
@pytest.mark.fail_slow(10)
|
| 782 |
+
def test_19_parallelization(self):
|
| 783 |
+
"""Test the functionality to add custom sampling methods to shgo"""
|
| 784 |
+
|
| 785 |
+
with Pool(2) as p:
|
| 786 |
+
run_test(test1_1, n=30, workers=p.map) # Constrained
|
| 787 |
+
run_test(test1_1, n=30, workers=map) # Constrained
|
| 788 |
+
with Pool(2) as p:
|
| 789 |
+
run_test(test_s, n=30, workers=p.map) # Unconstrained
|
| 790 |
+
run_test(test_s, n=30, workers=map) # Unconstrained
|
| 791 |
+
|
| 792 |
+
def test_20_constrained_args(self):
|
| 793 |
+
"""Test that constraints can be passed to arguments"""
|
| 794 |
+
|
| 795 |
+
def eggholder(x):
|
| 796 |
+
return (
|
| 797 |
+
-(x[1] + 47.0)*np.sin(np.sqrt(abs(x[0] / 2.0 + (x[1] + 47.0))))
|
| 798 |
+
- x[0]*np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0))))
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
def f(x): # (cattle-feed)
|
| 802 |
+
return 24.55 * x[0] + 26.75 * x[1] + 39 * x[2] + 40.50 * x[3]
|
| 803 |
+
|
| 804 |
+
bounds = [(0, 1.0), ] * 4
|
| 805 |
+
|
| 806 |
+
def g1_modified(x, i):
|
| 807 |
+
return i * 2.3 * x[0] + i * 5.6 * x[1] + 11.1 * x[2] + 1.3 * x[
|
| 808 |
+
3] - 5 # >=0
|
| 809 |
+
|
| 810 |
+
def g2(x):
|
| 811 |
+
return (
|
| 812 |
+
12*x[0] + 11.9*x[1] + 41.8*x[2] + 52.1*x[3] - 21
|
| 813 |
+
- 1.645*np.sqrt(
|
| 814 |
+
0.28*x[0]**2 + 0.19*x[1]**2 + 20.5*x[2]**2 + 0.62*x[3]**2
|
| 815 |
+
)
|
| 816 |
+
) # >=0
|
| 817 |
+
|
| 818 |
+
def h1(x):
|
| 819 |
+
return x[0] + x[1] + x[2] + x[3] - 1 # == 0
|
| 820 |
+
|
| 821 |
+
cons = ({'type': 'ineq', 'fun': g1_modified, "args": (0,)},
|
| 822 |
+
{'type': 'ineq', 'fun': g2},
|
| 823 |
+
{'type': 'eq', 'fun': h1})
|
| 824 |
+
|
| 825 |
+
shgo(f, bounds, n=300, iters=1, constraints=cons)
|
| 826 |
+
# using constrain with arguments AND sampling method sobol
|
| 827 |
+
shgo(f, bounds, n=300, iters=1, constraints=cons,
|
| 828 |
+
sampling_method='sobol')
|
| 829 |
+
|
| 830 |
+
def test_21_1_jac_true(self):
|
| 831 |
+
"""Test that shgo can handle objective functions that return the
|
| 832 |
+
gradient alongside the objective value. Fixes gh-13547"""
|
| 833 |
+
# previous
|
| 834 |
+
def func(x):
|
| 835 |
+
return np.sum(np.power(x, 2)), 2 * x
|
| 836 |
+
|
| 837 |
+
shgo(
|
| 838 |
+
func,
|
| 839 |
+
bounds=[[-1, 1], [1, 2]],
|
| 840 |
+
n=100, iters=5,
|
| 841 |
+
sampling_method="sobol",
|
| 842 |
+
minimizer_kwargs={'method': 'SLSQP', 'jac': True}
|
| 843 |
+
)
|
| 844 |
+
|
| 845 |
+
# new
|
| 846 |
+
def func(x):
|
| 847 |
+
return np.sum(x ** 2), 2 * x
|
| 848 |
+
|
| 849 |
+
bounds = [[-1, 1], [1, 2], [-1, 1], [1, 2], [0, 3]]
|
| 850 |
+
|
| 851 |
+
res = shgo(func, bounds=bounds, sampling_method="sobol",
|
| 852 |
+
minimizer_kwargs={'method': 'SLSQP', 'jac': True})
|
| 853 |
+
ref = minimize(func, x0=[1, 1, 1, 1, 1], bounds=bounds,
|
| 854 |
+
jac=True)
|
| 855 |
+
assert res.success
|
| 856 |
+
assert_allclose(res.fun, ref.fun)
|
| 857 |
+
assert_allclose(res.x, ref.x, atol=1e-15)
|
| 858 |
+
|
| 859 |
+
@pytest.mark.parametrize('derivative', ['jac', 'hess', 'hessp'])
|
| 860 |
+
def test_21_2_derivative_options(self, derivative):
|
| 861 |
+
"""shgo used to raise an error when passing `options` with 'jac'
|
| 862 |
+
# see gh-12963. check that this is resolved
|
| 863 |
+
"""
|
| 864 |
+
|
| 865 |
+
def objective(x):
|
| 866 |
+
return 3 * x[0] * x[0] + 2 * x[0] + 5
|
| 867 |
+
|
| 868 |
+
def gradient(x):
|
| 869 |
+
return 6 * x[0] + 2
|
| 870 |
+
|
| 871 |
+
def hess(x):
|
| 872 |
+
return 6
|
| 873 |
+
|
| 874 |
+
def hessp(x, p):
|
| 875 |
+
return 6 * p
|
| 876 |
+
|
| 877 |
+
derivative_funcs = {'jac': gradient, 'hess': hess, 'hessp': hessp}
|
| 878 |
+
options = {derivative: derivative_funcs[derivative]}
|
| 879 |
+
minimizer_kwargs = {'method': 'trust-constr'}
|
| 880 |
+
|
| 881 |
+
bounds = [(-100, 100)]
|
| 882 |
+
res = shgo(objective, bounds, minimizer_kwargs=minimizer_kwargs,
|
| 883 |
+
options=options)
|
| 884 |
+
ref = minimize(objective, x0=[0], bounds=bounds, **minimizer_kwargs,
|
| 885 |
+
**options)
|
| 886 |
+
|
| 887 |
+
assert res.success
|
| 888 |
+
np.testing.assert_allclose(res.fun, ref.fun)
|
| 889 |
+
np.testing.assert_allclose(res.x, ref.x)
|
| 890 |
+
|
| 891 |
+
def test_21_3_hess_options_rosen(self):
|
| 892 |
+
"""Ensure the Hessian gets passed correctly to the local minimizer
|
| 893 |
+
routine. Previous report gh-14533.
|
| 894 |
+
"""
|
| 895 |
+
bounds = [(0, 1.6), (0, 1.6), (0, 1.4), (0, 1.4), (0, 1.4)]
|
| 896 |
+
options = {'jac': rosen_der, 'hess': rosen_hess}
|
| 897 |
+
minimizer_kwargs = {'method': 'Newton-CG'}
|
| 898 |
+
res = shgo(rosen, bounds, minimizer_kwargs=minimizer_kwargs,
|
| 899 |
+
options=options)
|
| 900 |
+
ref = minimize(rosen, np.zeros(5), method='Newton-CG',
|
| 901 |
+
**options)
|
| 902 |
+
assert res.success
|
| 903 |
+
assert_allclose(res.fun, ref.fun)
|
| 904 |
+
assert_allclose(res.x, ref.x, atol=1e-15)
|
| 905 |
+
|
| 906 |
+
def test_21_arg_tuple_sobol(self):
|
| 907 |
+
"""shgo used to raise an error when passing `args` with Sobol sampling
|
| 908 |
+
# see gh-12114. check that this is resolved"""
|
| 909 |
+
|
| 910 |
+
def fun(x, k):
|
| 911 |
+
return x[0] ** k
|
| 912 |
+
|
| 913 |
+
constraints = ({'type': 'ineq', 'fun': lambda x: x[0] - 1})
|
| 914 |
+
|
| 915 |
+
bounds = [(0, 10)]
|
| 916 |
+
res = shgo(fun, bounds, args=(1,), constraints=constraints,
|
| 917 |
+
sampling_method='sobol')
|
| 918 |
+
ref = minimize(fun, np.zeros(1), bounds=bounds, args=(1,),
|
| 919 |
+
constraints=constraints)
|
| 920 |
+
assert res.success
|
| 921 |
+
assert_allclose(res.fun, ref.fun)
|
| 922 |
+
assert_allclose(res.x, ref.x)
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
# Failure test functions
|
| 926 |
+
class TestShgoFailures:
|
| 927 |
+
def test_1_maxiter(self):
|
| 928 |
+
"""Test failure on insufficient iterations"""
|
| 929 |
+
options = {'maxiter': 2}
|
| 930 |
+
res = shgo(test4_1.f, test4_1.bounds, n=2, iters=None,
|
| 931 |
+
options=options, sampling_method='sobol')
|
| 932 |
+
|
| 933 |
+
np.testing.assert_equal(False, res.success)
|
| 934 |
+
# np.testing.assert_equal(4, res.nfev)
|
| 935 |
+
np.testing.assert_equal(4, res.tnev)
|
| 936 |
+
|
| 937 |
+
def test_2_sampling(self):
|
| 938 |
+
"""Rejection of unknown sampling method"""
|
| 939 |
+
assert_raises(ValueError, shgo, test1_1.f, test1_1.bounds,
|
| 940 |
+
sampling_method='not_Sobol')
|
| 941 |
+
|
| 942 |
+
def test_3_1_no_min_pool_sobol(self):
|
| 943 |
+
"""Check that the routine stops when no minimiser is found
|
| 944 |
+
after maximum specified function evaluations"""
|
| 945 |
+
options = {'maxfev': 10,
|
| 946 |
+
# 'maxev': 10,
|
| 947 |
+
'disp': True}
|
| 948 |
+
res = shgo(test_table.f, test_table.bounds, n=3, options=options,
|
| 949 |
+
sampling_method='sobol')
|
| 950 |
+
np.testing.assert_equal(False, res.success)
|
| 951 |
+
# np.testing.assert_equal(9, res.nfev)
|
| 952 |
+
np.testing.assert_equal(12, res.nfev)
|
| 953 |
+
|
| 954 |
+
def test_3_2_no_min_pool_simplicial(self):
|
| 955 |
+
"""Check that the routine stops when no minimiser is found
|
| 956 |
+
after maximum specified sampling evaluations"""
|
| 957 |
+
options = {'maxev': 10,
|
| 958 |
+
'disp': True}
|
| 959 |
+
res = shgo(test_table.f, test_table.bounds, n=3, options=options,
|
| 960 |
+
sampling_method='simplicial')
|
| 961 |
+
np.testing.assert_equal(False, res.success)
|
| 962 |
+
|
| 963 |
+
def test_4_1_bound_err(self):
|
| 964 |
+
"""Specified bounds ub > lb"""
|
| 965 |
+
bounds = [(6, 3), (3, 5)]
|
| 966 |
+
assert_raises(ValueError, shgo, test1_1.f, bounds)
|
| 967 |
+
|
| 968 |
+
def test_4_2_bound_err(self):
|
| 969 |
+
"""Specified bounds are of the form (lb, ub)"""
|
| 970 |
+
bounds = [(3, 5, 5), (3, 5)]
|
| 971 |
+
assert_raises(ValueError, shgo, test1_1.f, bounds)
|
| 972 |
+
|
| 973 |
+
def test_5_1_1_infeasible_sobol(self):
|
| 974 |
+
"""Ensures the algorithm terminates on infeasible problems
|
| 975 |
+
after maxev is exceeded. Use infty constraints option"""
|
| 976 |
+
options = {'maxev': 100,
|
| 977 |
+
'disp': True}
|
| 978 |
+
|
| 979 |
+
res = shgo(test_infeasible.f, test_infeasible.bounds,
|
| 980 |
+
constraints=test_infeasible.cons, n=100, options=options,
|
| 981 |
+
sampling_method='sobol')
|
| 982 |
+
|
| 983 |
+
np.testing.assert_equal(False, res.success)
|
| 984 |
+
|
| 985 |
+
def test_5_1_2_infeasible_sobol(self):
|
| 986 |
+
"""Ensures the algorithm terminates on infeasible problems
|
| 987 |
+
after maxev is exceeded. Do not use infty constraints option"""
|
| 988 |
+
options = {'maxev': 100,
|
| 989 |
+
'disp': True,
|
| 990 |
+
'infty_constraints': False}
|
| 991 |
+
|
| 992 |
+
res = shgo(test_infeasible.f, test_infeasible.bounds,
|
| 993 |
+
constraints=test_infeasible.cons, n=100, options=options,
|
| 994 |
+
sampling_method='sobol')
|
| 995 |
+
|
| 996 |
+
np.testing.assert_equal(False, res.success)
|
| 997 |
+
|
| 998 |
+
def test_5_2_infeasible_simplicial(self):
|
| 999 |
+
"""Ensures the algorithm terminates on infeasible problems
|
| 1000 |
+
after maxev is exceeded."""
|
| 1001 |
+
options = {'maxev': 1000,
|
| 1002 |
+
'disp': False}
|
| 1003 |
+
|
| 1004 |
+
res = shgo(test_infeasible.f, test_infeasible.bounds,
|
| 1005 |
+
constraints=test_infeasible.cons, n=100, options=options,
|
| 1006 |
+
sampling_method='simplicial')
|
| 1007 |
+
|
| 1008 |
+
np.testing.assert_equal(False, res.success)
|
| 1009 |
+
|
| 1010 |
+
@pytest.mark.thread_unsafe
|
| 1011 |
+
def test_6_1_lower_known_f_min(self):
|
| 1012 |
+
"""Test Global mode limiting local evaluations with f* too high"""
|
| 1013 |
+
options = { # Specify known function value
|
| 1014 |
+
'f_min': test2_1.expected_fun + 2.0,
|
| 1015 |
+
'f_tol': 1e-6,
|
| 1016 |
+
# Specify number of local iterations to perform+
|
| 1017 |
+
'minimize_every_iter': True,
|
| 1018 |
+
'local_iter': 1,
|
| 1019 |
+
'infty_constraints': False}
|
| 1020 |
+
args = (test2_1.f, test2_1.bounds)
|
| 1021 |
+
kwargs = {'constraints': test2_1.cons,
|
| 1022 |
+
'n': None,
|
| 1023 |
+
'iters': None,
|
| 1024 |
+
'options': options,
|
| 1025 |
+
'sampling_method': 'sobol'
|
| 1026 |
+
}
|
| 1027 |
+
warns(UserWarning, shgo, *args, **kwargs)
|
| 1028 |
+
|
| 1029 |
+
def test(self):
|
| 1030 |
+
from scipy.optimize import rosen, shgo
|
| 1031 |
+
bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)]
|
| 1032 |
+
|
| 1033 |
+
def fun(x):
|
| 1034 |
+
fun.nfev += 1
|
| 1035 |
+
return rosen(x)
|
| 1036 |
+
|
| 1037 |
+
fun.nfev = 0
|
| 1038 |
+
|
| 1039 |
+
result = shgo(fun, bounds)
|
| 1040 |
+
print(result.x, result.fun, fun.nfev) # 50
|
| 1041 |
+
|
| 1042 |
+
|
| 1043 |
+
# Returns
|
| 1044 |
+
class TestShgoReturns:
|
| 1045 |
+
def test_1_nfev_simplicial(self):
|
| 1046 |
+
bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)]
|
| 1047 |
+
|
| 1048 |
+
def fun(x):
|
| 1049 |
+
fun.nfev += 1
|
| 1050 |
+
return rosen(x)
|
| 1051 |
+
|
| 1052 |
+
fun.nfev = 0
|
| 1053 |
+
|
| 1054 |
+
result = shgo(fun, bounds)
|
| 1055 |
+
np.testing.assert_equal(fun.nfev, result.nfev)
|
| 1056 |
+
|
| 1057 |
+
def test_1_nfev_sobol(self):
|
| 1058 |
+
bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)]
|
| 1059 |
+
|
| 1060 |
+
def fun(x):
|
| 1061 |
+
fun.nfev += 1
|
| 1062 |
+
return rosen(x)
|
| 1063 |
+
|
| 1064 |
+
fun.nfev = 0
|
| 1065 |
+
|
| 1066 |
+
result = shgo(fun, bounds, sampling_method='sobol')
|
| 1067 |
+
np.testing.assert_equal(fun.nfev, result.nfev)
|
| 1068 |
+
|
| 1069 |
+
|
| 1070 |
+
def test_vector_constraint():
|
| 1071 |
+
# gh15514
|
| 1072 |
+
def quad(x):
|
| 1073 |
+
x = np.asarray(x)
|
| 1074 |
+
return [np.sum(x ** 2)]
|
| 1075 |
+
|
| 1076 |
+
nlc = NonlinearConstraint(quad, [2.2], [3])
|
| 1077 |
+
oldc = new_constraint_to_old(nlc, np.array([1.0, 1.0]))
|
| 1078 |
+
|
| 1079 |
+
res = shgo(rosen, [(0, 10), (0, 10)], constraints=oldc, sampling_method='sobol')
|
| 1080 |
+
assert np.all(np.sum((res.x)**2) >= 2.2)
|
| 1081 |
+
assert np.all(np.sum((res.x) ** 2) <= 3.0)
|
| 1082 |
+
assert res.success
|
| 1083 |
+
|
| 1084 |
+
|
| 1085 |
+
@pytest.mark.filterwarnings("ignore:delta_grad")
|
| 1086 |
+
def test_trust_constr():
|
| 1087 |
+
def quad(x):
|
| 1088 |
+
x = np.asarray(x)
|
| 1089 |
+
return [np.sum(x ** 2)]
|
| 1090 |
+
|
| 1091 |
+
nlc = NonlinearConstraint(quad, [2.6], [3])
|
| 1092 |
+
minimizer_kwargs = {'method': 'trust-constr'}
|
| 1093 |
+
# note that we don't supply the constraints in minimizer_kwargs,
|
| 1094 |
+
# so if the final result obeys the constraints we know that shgo
|
| 1095 |
+
# passed them on to 'trust-constr'
|
| 1096 |
+
res = shgo(
|
| 1097 |
+
rosen,
|
| 1098 |
+
[(0, 10), (0, 10)],
|
| 1099 |
+
constraints=nlc,
|
| 1100 |
+
sampling_method='sobol',
|
| 1101 |
+
minimizer_kwargs=minimizer_kwargs
|
| 1102 |
+
)
|
| 1103 |
+
assert np.all(np.sum((res.x)**2) >= 2.6)
|
| 1104 |
+
assert np.all(np.sum((res.x) ** 2) <= 3.0)
|
| 1105 |
+
assert res.success
|
| 1106 |
+
|
| 1107 |
+
|
| 1108 |
+
def test_equality_constraints():
|
| 1109 |
+
# gh16260
|
| 1110 |
+
bounds = [(0.9, 4.0)] * 2 # Constrain probabilities to 0 and 1.
|
| 1111 |
+
|
| 1112 |
+
def faulty(x):
|
| 1113 |
+
return x[0] + x[1]
|
| 1114 |
+
|
| 1115 |
+
nlc = NonlinearConstraint(faulty, 3.9, 3.9)
|
| 1116 |
+
res = shgo(rosen, bounds=bounds, constraints=nlc)
|
| 1117 |
+
assert_allclose(np.sum(res.x), 3.9)
|
| 1118 |
+
|
| 1119 |
+
def faulty(x):
|
| 1120 |
+
return x[0] + x[1] - 3.9
|
| 1121 |
+
|
| 1122 |
+
constraints = {'type': 'eq', 'fun': faulty}
|
| 1123 |
+
res = shgo(rosen, bounds=bounds, constraints=constraints)
|
| 1124 |
+
assert_allclose(np.sum(res.x), 3.9)
|
| 1125 |
+
|
| 1126 |
+
bounds = [(0, 1.0)] * 4
|
| 1127 |
+
# sum of variable should equal 1.
|
| 1128 |
+
def faulty(x):
|
| 1129 |
+
return x[0] + x[1] + x[2] + x[3] - 1
|
| 1130 |
+
|
| 1131 |
+
# options = {'minimize_every_iter': True, 'local_iter':10}
|
| 1132 |
+
constraints = {'type': 'eq', 'fun': faulty}
|
| 1133 |
+
res = shgo(
|
| 1134 |
+
lambda x: - np.prod(x),
|
| 1135 |
+
bounds=bounds,
|
| 1136 |
+
constraints=constraints,
|
| 1137 |
+
sampling_method='sobol'
|
| 1138 |
+
)
|
| 1139 |
+
assert_allclose(np.sum(res.x), 1.0)
|
| 1140 |
+
|
| 1141 |
+
def test_gh16971():
|
| 1142 |
+
def cons(x):
|
| 1143 |
+
return np.sum(x**2) - 0
|
| 1144 |
+
|
| 1145 |
+
c = {'fun': cons, 'type': 'ineq'}
|
| 1146 |
+
minimizer_kwargs = {
|
| 1147 |
+
'method': 'COBYLA',
|
| 1148 |
+
'options': {'rhobeg': 5, 'tol': 5e-1, 'catol': 0.05}
|
| 1149 |
+
}
|
| 1150 |
+
|
| 1151 |
+
s = SHGO(
|
| 1152 |
+
rosen, [(0, 10)]*2, constraints=c, minimizer_kwargs=minimizer_kwargs
|
| 1153 |
+
)
|
| 1154 |
+
|
| 1155 |
+
assert s.minimizer_kwargs['method'].lower() == 'cobyla'
|
| 1156 |
+
assert s.minimizer_kwargs['options']['catol'] == 0.05
|
shared/package-files/06/0638a95de3398b9d3c9cc2ac7345556beb7d2c946ebeed367b3467f88e7642f6/mm_native.h
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
#include <ATen/ops/mm_meta.h>
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
struct TORCH_API structured_mm_out_cpu : public at::meta::structured_mm {
|
| 20 |
+
void impl(const at::Tensor & self, const at::Tensor & mat2, const at::Tensor & out);
|
| 21 |
+
};
|
| 22 |
+
struct TORCH_API structured_mm_out_cuda : public at::meta::structured_mm {
|
| 23 |
+
void impl(const at::Tensor & self, const at::Tensor & mat2, const at::Tensor & out);
|
| 24 |
+
};
|
| 25 |
+
TORCH_API at::Tensor _sparse_mm(const at::Tensor & self, const at::Tensor & mat2);
|
| 26 |
+
TORCH_API at::Tensor & _sparse_mm_out(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out);
|
| 27 |
+
TORCH_API at::Tensor _sparse_csr_mm(const at::Tensor & self, const at::Tensor & mat2);
|
| 28 |
+
TORCH_API at::Tensor & _sparse_csr_mm_out(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out);
|
| 29 |
+
} // namespace native
|
| 30 |
+
} // namespace at
|
shared/package-files/06/063bc02a80235e17483eec69635db81c9205b300dbd29abc0e3ca7cc9395c2a7/_macos.py
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import contextlib
|
| 2 |
+
import ctypes
|
| 3 |
+
import platform
|
| 4 |
+
import ssl
|
| 5 |
+
import typing
|
| 6 |
+
from ctypes import (
|
| 7 |
+
CDLL,
|
| 8 |
+
POINTER,
|
| 9 |
+
c_bool,
|
| 10 |
+
c_char_p,
|
| 11 |
+
c_int32,
|
| 12 |
+
c_long,
|
| 13 |
+
c_uint32,
|
| 14 |
+
c_ulong,
|
| 15 |
+
c_void_p,
|
| 16 |
+
)
|
| 17 |
+
from ctypes.util import find_library
|
| 18 |
+
|
| 19 |
+
from ._ssl_constants import _set_ssl_context_verify_mode
|
| 20 |
+
|
| 21 |
+
_mac_version = platform.mac_ver()[0]
|
| 22 |
+
_mac_version_info = tuple(map(int, _mac_version.split(".")))
|
| 23 |
+
if _mac_version_info < (10, 8):
|
| 24 |
+
raise ImportError(
|
| 25 |
+
f"Only OS X 10.8 and newer are supported, not {_mac_version_info[0]}.{_mac_version_info[1]}"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _load_cdll(name: str, macos10_16_path: str) -> CDLL:
|
| 30 |
+
"""Loads a CDLL by name, falling back to known path on 10.16+"""
|
| 31 |
+
try:
|
| 32 |
+
# Big Sur is technically 11 but we use 10.16 due to the Big Sur
|
| 33 |
+
# beta being labeled as 10.16.
|
| 34 |
+
path: str | None
|
| 35 |
+
if _mac_version_info >= (10, 16):
|
| 36 |
+
path = macos10_16_path
|
| 37 |
+
else:
|
| 38 |
+
path = find_library(name)
|
| 39 |
+
if not path:
|
| 40 |
+
raise OSError # Caught and reraised as 'ImportError'
|
| 41 |
+
return CDLL(path, use_errno=True)
|
| 42 |
+
except OSError:
|
| 43 |
+
raise ImportError(f"The library {name} failed to load") from None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
Security = _load_cdll(
|
| 47 |
+
"Security", "/System/Library/Frameworks/Security.framework/Security"
|
| 48 |
+
)
|
| 49 |
+
CoreFoundation = _load_cdll(
|
| 50 |
+
"CoreFoundation",
|
| 51 |
+
"/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation",
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
Boolean = c_bool
|
| 55 |
+
CFIndex = c_long
|
| 56 |
+
CFStringEncoding = c_uint32
|
| 57 |
+
CFData = c_void_p
|
| 58 |
+
CFString = c_void_p
|
| 59 |
+
CFArray = c_void_p
|
| 60 |
+
CFMutableArray = c_void_p
|
| 61 |
+
CFError = c_void_p
|
| 62 |
+
CFType = c_void_p
|
| 63 |
+
CFTypeID = c_ulong
|
| 64 |
+
CFTypeRef = POINTER(CFType)
|
| 65 |
+
CFAllocatorRef = c_void_p
|
| 66 |
+
|
| 67 |
+
OSStatus = c_int32
|
| 68 |
+
|
| 69 |
+
CFErrorRef = POINTER(CFError)
|
| 70 |
+
CFDataRef = POINTER(CFData)
|
| 71 |
+
CFStringRef = POINTER(CFString)
|
| 72 |
+
CFArrayRef = POINTER(CFArray)
|
| 73 |
+
CFMutableArrayRef = POINTER(CFMutableArray)
|
| 74 |
+
CFArrayCallBacks = c_void_p
|
| 75 |
+
CFOptionFlags = c_uint32
|
| 76 |
+
|
| 77 |
+
SecCertificateRef = POINTER(c_void_p)
|
| 78 |
+
SecPolicyRef = POINTER(c_void_p)
|
| 79 |
+
SecTrustRef = POINTER(c_void_p)
|
| 80 |
+
SecTrustResultType = c_uint32
|
| 81 |
+
SecTrustOptionFlags = c_uint32
|
| 82 |
+
|
| 83 |
+
try:
|
| 84 |
+
Security.SecCertificateCreateWithData.argtypes = [CFAllocatorRef, CFDataRef]
|
| 85 |
+
Security.SecCertificateCreateWithData.restype = SecCertificateRef
|
| 86 |
+
|
| 87 |
+
Security.SecCertificateCopyData.argtypes = [SecCertificateRef]
|
| 88 |
+
Security.SecCertificateCopyData.restype = CFDataRef
|
| 89 |
+
|
| 90 |
+
Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p]
|
| 91 |
+
Security.SecCopyErrorMessageString.restype = CFStringRef
|
| 92 |
+
|
| 93 |
+
Security.SecTrustSetAnchorCertificates.argtypes = [SecTrustRef, CFArrayRef]
|
| 94 |
+
Security.SecTrustSetAnchorCertificates.restype = OSStatus
|
| 95 |
+
|
| 96 |
+
Security.SecTrustSetAnchorCertificatesOnly.argtypes = [SecTrustRef, Boolean]
|
| 97 |
+
Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus
|
| 98 |
+
|
| 99 |
+
Security.SecTrustEvaluate.argtypes = [SecTrustRef, POINTER(SecTrustResultType)]
|
| 100 |
+
Security.SecTrustEvaluate.restype = OSStatus
|
| 101 |
+
|
| 102 |
+
Security.SecPolicyCreateRevocation.argtypes = [CFOptionFlags]
|
| 103 |
+
Security.SecPolicyCreateRevocation.restype = SecPolicyRef
|
| 104 |
+
|
| 105 |
+
Security.SecPolicyCreateSSL.argtypes = [Boolean, CFStringRef]
|
| 106 |
+
Security.SecPolicyCreateSSL.restype = SecPolicyRef
|
| 107 |
+
|
| 108 |
+
Security.SecTrustCreateWithCertificates.argtypes = [
|
| 109 |
+
CFTypeRef,
|
| 110 |
+
CFTypeRef,
|
| 111 |
+
POINTER(SecTrustRef),
|
| 112 |
+
]
|
| 113 |
+
Security.SecTrustCreateWithCertificates.restype = OSStatus
|
| 114 |
+
|
| 115 |
+
Security.SecTrustGetTrustResult.argtypes = [
|
| 116 |
+
SecTrustRef,
|
| 117 |
+
POINTER(SecTrustResultType),
|
| 118 |
+
]
|
| 119 |
+
Security.SecTrustGetTrustResult.restype = OSStatus
|
| 120 |
+
|
| 121 |
+
Security.SecTrustRef = SecTrustRef # type: ignore[attr-defined]
|
| 122 |
+
Security.SecTrustResultType = SecTrustResultType # type: ignore[attr-defined]
|
| 123 |
+
Security.OSStatus = OSStatus # type: ignore[attr-defined]
|
| 124 |
+
|
| 125 |
+
kSecRevocationUseAnyAvailableMethod = 3
|
| 126 |
+
kSecRevocationRequirePositiveResponse = 8
|
| 127 |
+
|
| 128 |
+
CoreFoundation.CFRelease.argtypes = [CFTypeRef]
|
| 129 |
+
CoreFoundation.CFRelease.restype = None
|
| 130 |
+
|
| 131 |
+
CoreFoundation.CFGetTypeID.argtypes = [CFTypeRef]
|
| 132 |
+
CoreFoundation.CFGetTypeID.restype = CFTypeID
|
| 133 |
+
|
| 134 |
+
CoreFoundation.CFStringCreateWithCString.argtypes = [
|
| 135 |
+
CFAllocatorRef,
|
| 136 |
+
c_char_p,
|
| 137 |
+
CFStringEncoding,
|
| 138 |
+
]
|
| 139 |
+
CoreFoundation.CFStringCreateWithCString.restype = CFStringRef
|
| 140 |
+
|
| 141 |
+
CoreFoundation.CFStringGetCStringPtr.argtypes = [CFStringRef, CFStringEncoding]
|
| 142 |
+
CoreFoundation.CFStringGetCStringPtr.restype = c_char_p
|
| 143 |
+
|
| 144 |
+
CoreFoundation.CFStringGetCString.argtypes = [
|
| 145 |
+
CFStringRef,
|
| 146 |
+
c_char_p,
|
| 147 |
+
CFIndex,
|
| 148 |
+
CFStringEncoding,
|
| 149 |
+
]
|
| 150 |
+
CoreFoundation.CFStringGetCString.restype = c_bool
|
| 151 |
+
|
| 152 |
+
CoreFoundation.CFDataCreate.argtypes = [CFAllocatorRef, c_char_p, CFIndex]
|
| 153 |
+
CoreFoundation.CFDataCreate.restype = CFDataRef
|
| 154 |
+
|
| 155 |
+
CoreFoundation.CFDataGetLength.argtypes = [CFDataRef]
|
| 156 |
+
CoreFoundation.CFDataGetLength.restype = CFIndex
|
| 157 |
+
|
| 158 |
+
CoreFoundation.CFDataGetBytePtr.argtypes = [CFDataRef]
|
| 159 |
+
CoreFoundation.CFDataGetBytePtr.restype = c_void_p
|
| 160 |
+
|
| 161 |
+
CoreFoundation.CFArrayCreate.argtypes = [
|
| 162 |
+
CFAllocatorRef,
|
| 163 |
+
POINTER(CFTypeRef),
|
| 164 |
+
CFIndex,
|
| 165 |
+
CFArrayCallBacks,
|
| 166 |
+
]
|
| 167 |
+
CoreFoundation.CFArrayCreate.restype = CFArrayRef
|
| 168 |
+
|
| 169 |
+
CoreFoundation.CFArrayCreateMutable.argtypes = [
|
| 170 |
+
CFAllocatorRef,
|
| 171 |
+
CFIndex,
|
| 172 |
+
CFArrayCallBacks,
|
| 173 |
+
]
|
| 174 |
+
CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef
|
| 175 |
+
|
| 176 |
+
CoreFoundation.CFArrayAppendValue.argtypes = [CFMutableArrayRef, c_void_p]
|
| 177 |
+
CoreFoundation.CFArrayAppendValue.restype = None
|
| 178 |
+
|
| 179 |
+
CoreFoundation.CFArrayGetCount.argtypes = [CFArrayRef]
|
| 180 |
+
CoreFoundation.CFArrayGetCount.restype = CFIndex
|
| 181 |
+
|
| 182 |
+
CoreFoundation.CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex]
|
| 183 |
+
CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p
|
| 184 |
+
|
| 185 |
+
CoreFoundation.CFErrorGetCode.argtypes = [CFErrorRef]
|
| 186 |
+
CoreFoundation.CFErrorGetCode.restype = CFIndex
|
| 187 |
+
|
| 188 |
+
CoreFoundation.CFErrorCopyDescription.argtypes = [CFErrorRef]
|
| 189 |
+
CoreFoundation.CFErrorCopyDescription.restype = CFStringRef
|
| 190 |
+
|
| 191 |
+
CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll( # type: ignore[attr-defined]
|
| 192 |
+
CoreFoundation, "kCFAllocatorDefault"
|
| 193 |
+
)
|
| 194 |
+
CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll( # type: ignore[attr-defined]
|
| 195 |
+
CoreFoundation, "kCFTypeArrayCallBacks"
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
CoreFoundation.CFTypeRef = CFTypeRef # type: ignore[attr-defined]
|
| 199 |
+
CoreFoundation.CFArrayRef = CFArrayRef # type: ignore[attr-defined]
|
| 200 |
+
CoreFoundation.CFStringRef = CFStringRef # type: ignore[attr-defined]
|
| 201 |
+
CoreFoundation.CFErrorRef = CFErrorRef # type: ignore[attr-defined]
|
| 202 |
+
|
| 203 |
+
except AttributeError:
|
| 204 |
+
raise ImportError("Error initializing ctypes") from None
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _handle_osstatus(result: OSStatus, _: typing.Any, args: typing.Any) -> typing.Any:
|
| 208 |
+
"""
|
| 209 |
+
Raises an error if the OSStatus value is non-zero.
|
| 210 |
+
"""
|
| 211 |
+
if int(result) == 0:
|
| 212 |
+
return args
|
| 213 |
+
|
| 214 |
+
# Returns a CFString which we need to transform
|
| 215 |
+
# into a UTF-8 Python string.
|
| 216 |
+
error_message_cfstring = None
|
| 217 |
+
try:
|
| 218 |
+
error_message_cfstring = Security.SecCopyErrorMessageString(result, None)
|
| 219 |
+
|
| 220 |
+
# First step is convert the CFString into a C string pointer.
|
| 221 |
+
# We try the fast no-copy way first.
|
| 222 |
+
error_message_cfstring_c_void_p = ctypes.cast(
|
| 223 |
+
error_message_cfstring, ctypes.POINTER(ctypes.c_void_p)
|
| 224 |
+
)
|
| 225 |
+
message = CoreFoundation.CFStringGetCStringPtr(
|
| 226 |
+
error_message_cfstring_c_void_p, CFConst.kCFStringEncodingUTF8
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
# Quoting the Apple dev docs:
|
| 230 |
+
#
|
| 231 |
+
# "A pointer to a C string or NULL if the internal
|
| 232 |
+
# storage of theString does not allow this to be
|
| 233 |
+
# returned efficiently."
|
| 234 |
+
#
|
| 235 |
+
# So we need to get our hands dirty.
|
| 236 |
+
if message is None:
|
| 237 |
+
buffer = ctypes.create_string_buffer(1024)
|
| 238 |
+
result = CoreFoundation.CFStringGetCString(
|
| 239 |
+
error_message_cfstring_c_void_p,
|
| 240 |
+
buffer,
|
| 241 |
+
1024,
|
| 242 |
+
CFConst.kCFStringEncodingUTF8,
|
| 243 |
+
)
|
| 244 |
+
if not result:
|
| 245 |
+
raise OSError("Error copying C string from CFStringRef")
|
| 246 |
+
message = buffer.value
|
| 247 |
+
|
| 248 |
+
finally:
|
| 249 |
+
if error_message_cfstring is not None:
|
| 250 |
+
CoreFoundation.CFRelease(error_message_cfstring)
|
| 251 |
+
|
| 252 |
+
# If no message can be found for this status we come
|
| 253 |
+
# up with a generic one that forwards the status code.
|
| 254 |
+
if message is None or message == "":
|
| 255 |
+
message = f"SecureTransport operation returned a non-zero OSStatus: {result}"
|
| 256 |
+
|
| 257 |
+
raise ssl.SSLError(message)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
Security.SecTrustCreateWithCertificates.errcheck = _handle_osstatus # type: ignore[assignment]
|
| 261 |
+
Security.SecTrustSetAnchorCertificates.errcheck = _handle_osstatus # type: ignore[assignment]
|
| 262 |
+
Security.SecTrustGetTrustResult.errcheck = _handle_osstatus # type: ignore[assignment]
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class CFConst:
|
| 266 |
+
"""CoreFoundation constants"""
|
| 267 |
+
|
| 268 |
+
kCFStringEncodingUTF8 = CFStringEncoding(0x08000100)
|
| 269 |
+
|
| 270 |
+
errSecIncompleteCertRevocationCheck = -67635
|
| 271 |
+
errSecHostNameMismatch = -67602
|
| 272 |
+
errSecCertificateExpired = -67818
|
| 273 |
+
errSecNotTrusted = -67843
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def _bytes_to_cf_data_ref(value: bytes) -> CFDataRef: # type: ignore[valid-type]
|
| 277 |
+
return CoreFoundation.CFDataCreate( # type: ignore[no-any-return]
|
| 278 |
+
CoreFoundation.kCFAllocatorDefault, value, len(value)
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _bytes_to_cf_string(value: bytes) -> CFString:
|
| 283 |
+
"""
|
| 284 |
+
Given a Python binary data, create a CFString.
|
| 285 |
+
The string must be CFReleased by the caller.
|
| 286 |
+
"""
|
| 287 |
+
c_str = ctypes.c_char_p(value)
|
| 288 |
+
cf_str = CoreFoundation.CFStringCreateWithCString(
|
| 289 |
+
CoreFoundation.kCFAllocatorDefault,
|
| 290 |
+
c_str,
|
| 291 |
+
CFConst.kCFStringEncodingUTF8,
|
| 292 |
+
)
|
| 293 |
+
return cf_str # type: ignore[no-any-return]
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _cf_string_ref_to_str(cf_string_ref: CFStringRef) -> str | None: # type: ignore[valid-type]
|
| 297 |
+
"""
|
| 298 |
+
Creates a Unicode string from a CFString object. Used entirely for error
|
| 299 |
+
reporting.
|
| 300 |
+
Yes, it annoys me quite a lot that this function is this complex.
|
| 301 |
+
"""
|
| 302 |
+
|
| 303 |
+
string = CoreFoundation.CFStringGetCStringPtr(
|
| 304 |
+
cf_string_ref, CFConst.kCFStringEncodingUTF8
|
| 305 |
+
)
|
| 306 |
+
if string is None:
|
| 307 |
+
buffer = ctypes.create_string_buffer(1024)
|
| 308 |
+
result = CoreFoundation.CFStringGetCString(
|
| 309 |
+
cf_string_ref, buffer, 1024, CFConst.kCFStringEncodingUTF8
|
| 310 |
+
)
|
| 311 |
+
if not result:
|
| 312 |
+
raise OSError("Error copying C string from CFStringRef")
|
| 313 |
+
string = buffer.value
|
| 314 |
+
if string is not None:
|
| 315 |
+
string = string.decode("utf-8")
|
| 316 |
+
return string # type: ignore[no-any-return]
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def _der_certs_to_cf_cert_array(certs: list[bytes]) -> CFMutableArrayRef: # type: ignore[valid-type]
|
| 320 |
+
"""Builds a CFArray of SecCertificateRefs from a list of DER-encoded certificates.
|
| 321 |
+
Responsibility of the caller to call CoreFoundation.CFRelease on the CFArray.
|
| 322 |
+
"""
|
| 323 |
+
cf_array = CoreFoundation.CFArrayCreateMutable(
|
| 324 |
+
CoreFoundation.kCFAllocatorDefault,
|
| 325 |
+
0,
|
| 326 |
+
ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),
|
| 327 |
+
)
|
| 328 |
+
if not cf_array:
|
| 329 |
+
raise MemoryError("Unable to allocate memory!")
|
| 330 |
+
|
| 331 |
+
for cert_data in certs:
|
| 332 |
+
cf_data = None
|
| 333 |
+
sec_cert_ref = None
|
| 334 |
+
try:
|
| 335 |
+
cf_data = _bytes_to_cf_data_ref(cert_data)
|
| 336 |
+
sec_cert_ref = Security.SecCertificateCreateWithData(
|
| 337 |
+
CoreFoundation.kCFAllocatorDefault, cf_data
|
| 338 |
+
)
|
| 339 |
+
CoreFoundation.CFArrayAppendValue(cf_array, sec_cert_ref)
|
| 340 |
+
finally:
|
| 341 |
+
if cf_data:
|
| 342 |
+
CoreFoundation.CFRelease(cf_data)
|
| 343 |
+
if sec_cert_ref:
|
| 344 |
+
CoreFoundation.CFRelease(sec_cert_ref)
|
| 345 |
+
|
| 346 |
+
return cf_array # type: ignore[no-any-return]
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
@contextlib.contextmanager
|
| 350 |
+
def _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]:
|
| 351 |
+
check_hostname = ctx.check_hostname
|
| 352 |
+
verify_mode = ctx.verify_mode
|
| 353 |
+
ctx.check_hostname = False
|
| 354 |
+
_set_ssl_context_verify_mode(ctx, ssl.CERT_NONE)
|
| 355 |
+
try:
|
| 356 |
+
yield
|
| 357 |
+
finally:
|
| 358 |
+
ctx.check_hostname = check_hostname
|
| 359 |
+
_set_ssl_context_verify_mode(ctx, verify_mode)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def _verify_peercerts_impl(
|
| 363 |
+
ssl_context: ssl.SSLContext,
|
| 364 |
+
cert_chain: list[bytes],
|
| 365 |
+
server_hostname: str | None = None,
|
| 366 |
+
) -> None:
|
| 367 |
+
certs = None
|
| 368 |
+
policies = None
|
| 369 |
+
trust = None
|
| 370 |
+
cf_error = None
|
| 371 |
+
try:
|
| 372 |
+
if server_hostname is not None:
|
| 373 |
+
cf_str_hostname = None
|
| 374 |
+
try:
|
| 375 |
+
cf_str_hostname = _bytes_to_cf_string(server_hostname.encode("ascii"))
|
| 376 |
+
ssl_policy = Security.SecPolicyCreateSSL(True, cf_str_hostname)
|
| 377 |
+
finally:
|
| 378 |
+
if cf_str_hostname:
|
| 379 |
+
CoreFoundation.CFRelease(cf_str_hostname)
|
| 380 |
+
else:
|
| 381 |
+
ssl_policy = Security.SecPolicyCreateSSL(True, None)
|
| 382 |
+
|
| 383 |
+
policies = ssl_policy
|
| 384 |
+
if ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_CHAIN:
|
| 385 |
+
# Add explicit policy requiring positive revocation checks
|
| 386 |
+
policies = CoreFoundation.CFArrayCreateMutable(
|
| 387 |
+
CoreFoundation.kCFAllocatorDefault,
|
| 388 |
+
0,
|
| 389 |
+
ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),
|
| 390 |
+
)
|
| 391 |
+
CoreFoundation.CFArrayAppendValue(policies, ssl_policy)
|
| 392 |
+
CoreFoundation.CFRelease(ssl_policy)
|
| 393 |
+
revocation_policy = Security.SecPolicyCreateRevocation(
|
| 394 |
+
kSecRevocationUseAnyAvailableMethod
|
| 395 |
+
| kSecRevocationRequirePositiveResponse
|
| 396 |
+
)
|
| 397 |
+
CoreFoundation.CFArrayAppendValue(policies, revocation_policy)
|
| 398 |
+
CoreFoundation.CFRelease(revocation_policy)
|
| 399 |
+
elif ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF:
|
| 400 |
+
raise NotImplementedError("VERIFY_CRL_CHECK_LEAF not implemented for macOS")
|
| 401 |
+
|
| 402 |
+
certs = None
|
| 403 |
+
try:
|
| 404 |
+
certs = _der_certs_to_cf_cert_array(cert_chain)
|
| 405 |
+
|
| 406 |
+
# Now that we have certificates loaded and a SecPolicy
|
| 407 |
+
# we can finally create a SecTrust object!
|
| 408 |
+
trust = Security.SecTrustRef()
|
| 409 |
+
Security.SecTrustCreateWithCertificates(
|
| 410 |
+
certs, policies, ctypes.byref(trust)
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
finally:
|
| 414 |
+
# The certs are now being held by SecTrust so we can
|
| 415 |
+
# release our handles for the array.
|
| 416 |
+
if certs:
|
| 417 |
+
CoreFoundation.CFRelease(certs)
|
| 418 |
+
|
| 419 |
+
# If there are additional trust anchors to load we need to transform
|
| 420 |
+
# the list of DER-encoded certificates into a CFArray. Otherwise
|
| 421 |
+
# pass 'None' to signal that we only want system / fetched certificates.
|
| 422 |
+
ctx_ca_certs_der: list[bytes] | None = ssl_context.get_ca_certs(
|
| 423 |
+
binary_form=True
|
| 424 |
+
)
|
| 425 |
+
if ctx_ca_certs_der:
|
| 426 |
+
ctx_ca_certs = None
|
| 427 |
+
try:
|
| 428 |
+
ctx_ca_certs = _der_certs_to_cf_cert_array(cert_chain)
|
| 429 |
+
Security.SecTrustSetAnchorCertificates(trust, ctx_ca_certs)
|
| 430 |
+
finally:
|
| 431 |
+
if ctx_ca_certs:
|
| 432 |
+
CoreFoundation.CFRelease(ctx_ca_certs)
|
| 433 |
+
else:
|
| 434 |
+
Security.SecTrustSetAnchorCertificates(trust, None)
|
| 435 |
+
|
| 436 |
+
cf_error = CoreFoundation.CFErrorRef()
|
| 437 |
+
sec_trust_eval_result = Security.SecTrustEvaluateWithError(
|
| 438 |
+
trust, ctypes.byref(cf_error)
|
| 439 |
+
)
|
| 440 |
+
# sec_trust_eval_result is a bool (0 or 1)
|
| 441 |
+
# where 1 means that the certs are trusted.
|
| 442 |
+
if sec_trust_eval_result == 1:
|
| 443 |
+
is_trusted = True
|
| 444 |
+
elif sec_trust_eval_result == 0:
|
| 445 |
+
is_trusted = False
|
| 446 |
+
else:
|
| 447 |
+
raise ssl.SSLError(
|
| 448 |
+
f"Unknown result from Security.SecTrustEvaluateWithError: {sec_trust_eval_result!r}"
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
cf_error_code = 0
|
| 452 |
+
if not is_trusted:
|
| 453 |
+
cf_error_code = CoreFoundation.CFErrorGetCode(cf_error)
|
| 454 |
+
|
| 455 |
+
# If the error is a known failure that we're
|
| 456 |
+
# explicitly okay with from SSLContext configuration
|
| 457 |
+
# we can set is_trusted accordingly.
|
| 458 |
+
if ssl_context.verify_mode != ssl.CERT_REQUIRED and (
|
| 459 |
+
cf_error_code == CFConst.errSecNotTrusted
|
| 460 |
+
or cf_error_code == CFConst.errSecCertificateExpired
|
| 461 |
+
):
|
| 462 |
+
is_trusted = True
|
| 463 |
+
elif (
|
| 464 |
+
not ssl_context.check_hostname
|
| 465 |
+
and cf_error_code == CFConst.errSecHostNameMismatch
|
| 466 |
+
):
|
| 467 |
+
is_trusted = True
|
| 468 |
+
|
| 469 |
+
# If we're still not trusted then we start to
|
| 470 |
+
# construct and raise the SSLCertVerificationError.
|
| 471 |
+
if not is_trusted:
|
| 472 |
+
cf_error_string_ref = None
|
| 473 |
+
try:
|
| 474 |
+
cf_error_string_ref = CoreFoundation.CFErrorCopyDescription(cf_error)
|
| 475 |
+
|
| 476 |
+
# Can this ever return 'None' if there's a CFError?
|
| 477 |
+
cf_error_message = (
|
| 478 |
+
_cf_string_ref_to_str(cf_error_string_ref)
|
| 479 |
+
or "Certificate verification failed"
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
# TODO: Not sure if we need the SecTrustResultType for anything?
|
| 483 |
+
# We only care whether or not it's a success or failure for now.
|
| 484 |
+
sec_trust_result_type = Security.SecTrustResultType()
|
| 485 |
+
Security.SecTrustGetTrustResult(
|
| 486 |
+
trust, ctypes.byref(sec_trust_result_type)
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
err = ssl.SSLCertVerificationError(cf_error_message)
|
| 490 |
+
err.verify_message = cf_error_message
|
| 491 |
+
err.verify_code = cf_error_code
|
| 492 |
+
raise err
|
| 493 |
+
finally:
|
| 494 |
+
if cf_error_string_ref:
|
| 495 |
+
CoreFoundation.CFRelease(cf_error_string_ref)
|
| 496 |
+
|
| 497 |
+
finally:
|
| 498 |
+
if policies:
|
| 499 |
+
CoreFoundation.CFRelease(policies)
|
| 500 |
+
if trust:
|
| 501 |
+
CoreFoundation.CFRelease(trust)
|
shared/package-files/06/063c92d566e718c67fde87955ac5d62e93f9dbf0262ffc2d1eed273b41279a45/unfold_copy_ops.h
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API unfold_copy {
|
| 18 |
+
using schema = at::Tensor (const at::Tensor &, int64_t, int64_t, int64_t);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::unfold_copy")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "unfold_copy(Tensor self, int dimension, int size, int step) -> Tensor")
|
| 24 |
+
static at::Tensor call(const at::Tensor & self, int64_t dimension, int64_t size, int64_t step);
|
| 25 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dimension, int64_t size, int64_t step);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API unfold_copy_out {
|
| 29 |
+
using schema = at::Tensor & (const at::Tensor &, int64_t, int64_t, int64_t, at::Tensor &);
|
| 30 |
+
using ptr_schema = schema*;
|
| 31 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 32 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::unfold_copy")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "unfold_copy.out(Tensor self, int dimension, int size, int step, *, Tensor(a!) out) -> Tensor(a!)")
|
| 35 |
+
static at::Tensor & call(const at::Tensor & self, int64_t dimension, int64_t size, int64_t step, at::Tensor & out);
|
| 36 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dimension, int64_t size, int64_t step, at::Tensor & out);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
}} // namespace at::_ops
|
shared/package-files/06/063de18848173015f30e2d0b9a0f24f908380a13d9ad056a194d107e1ed2bfce/test_ticker.py
ADDED
|
@@ -0,0 +1,1939 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import nullcontext
|
| 2 |
+
import itertools
|
| 3 |
+
import locale
|
| 4 |
+
import logging
|
| 5 |
+
import re
|
| 6 |
+
from packaging.version import parse as parse_version
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
from numpy.testing import assert_almost_equal, assert_array_equal
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
import matplotlib as mpl
|
| 13 |
+
import matplotlib.pyplot as plt
|
| 14 |
+
import matplotlib.ticker as mticker
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class TestMaxNLocator:
|
| 18 |
+
basic_data = [
|
| 19 |
+
(20, 100, np.array([20., 40., 60., 80., 100.])),
|
| 20 |
+
(0.001, 0.0001, np.array([0., 0.0002, 0.0004, 0.0006, 0.0008, 0.001])),
|
| 21 |
+
(-1e15, 1e15, np.array([-1.0e+15, -5.0e+14, 0e+00, 5e+14, 1.0e+15])),
|
| 22 |
+
(0, 0.85e-50, np.arange(6) * 2e-51),
|
| 23 |
+
(-0.85e-50, 0, np.arange(-5, 1) * 2e-51),
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
integer_data = [
|
| 27 |
+
(-0.1, 1.1, None, np.array([-1, 0, 1, 2])),
|
| 28 |
+
(-0.1, 0.95, None, np.array([-0.25, 0, 0.25, 0.5, 0.75, 1.0])),
|
| 29 |
+
(1, 55, [1, 1.5, 5, 6, 10], np.array([0, 15, 30, 45, 60])),
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
@pytest.mark.parametrize('vmin, vmax, expected', basic_data)
|
| 33 |
+
def test_basic(self, vmin, vmax, expected):
|
| 34 |
+
loc = mticker.MaxNLocator(nbins=5)
|
| 35 |
+
assert_almost_equal(loc.tick_values(vmin, vmax), expected)
|
| 36 |
+
|
| 37 |
+
@pytest.mark.parametrize('vmin, vmax, steps, expected', integer_data)
|
| 38 |
+
def test_integer(self, vmin, vmax, steps, expected):
|
| 39 |
+
loc = mticker.MaxNLocator(nbins=5, integer=True, steps=steps)
|
| 40 |
+
assert_almost_equal(loc.tick_values(vmin, vmax), expected)
|
| 41 |
+
|
| 42 |
+
@pytest.mark.parametrize('kwargs, errortype, match', [
|
| 43 |
+
({'foo': 0}, TypeError,
|
| 44 |
+
re.escape("set_params() got an unexpected keyword argument 'foo'")),
|
| 45 |
+
({'steps': [2, 1]}, ValueError, "steps argument must be an increasing"),
|
| 46 |
+
({'steps': 2}, ValueError, "steps argument must be an increasing"),
|
| 47 |
+
({'steps': [2, 11]}, ValueError, "steps argument must be an increasing"),
|
| 48 |
+
])
|
| 49 |
+
def test_errors(self, kwargs, errortype, match):
|
| 50 |
+
with pytest.raises(errortype, match=match):
|
| 51 |
+
mticker.MaxNLocator(**kwargs)
|
| 52 |
+
|
| 53 |
+
@pytest.mark.parametrize('steps, result', [
|
| 54 |
+
([1, 2, 10], [1, 2, 10]),
|
| 55 |
+
([2, 10], [1, 2, 10]),
|
| 56 |
+
([1, 2], [1, 2, 10]),
|
| 57 |
+
([2], [1, 2, 10]),
|
| 58 |
+
])
|
| 59 |
+
def test_padding(self, steps, result):
|
| 60 |
+
loc = mticker.MaxNLocator(steps=steps)
|
| 61 |
+
assert (loc._steps == result).all()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class TestLinearLocator:
|
| 65 |
+
def test_basic(self):
|
| 66 |
+
loc = mticker.LinearLocator(numticks=3)
|
| 67 |
+
test_value = np.array([-0.8, -0.3, 0.2])
|
| 68 |
+
assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value)
|
| 69 |
+
|
| 70 |
+
def test_zero_numticks(self):
|
| 71 |
+
loc = mticker.LinearLocator(numticks=0)
|
| 72 |
+
loc.tick_values(-0.8, 0.2) == []
|
| 73 |
+
|
| 74 |
+
def test_set_params(self):
|
| 75 |
+
"""
|
| 76 |
+
Create linear locator with presets={}, numticks=2 and change it to
|
| 77 |
+
something else. See if change was successful. Should not exception.
|
| 78 |
+
"""
|
| 79 |
+
loc = mticker.LinearLocator(numticks=2)
|
| 80 |
+
loc.set_params(numticks=8, presets={(0, 1): []})
|
| 81 |
+
assert loc.numticks == 8
|
| 82 |
+
assert loc.presets == {(0, 1): []}
|
| 83 |
+
|
| 84 |
+
def test_presets(self):
|
| 85 |
+
loc = mticker.LinearLocator(presets={(1, 2): [1, 1.25, 1.75],
|
| 86 |
+
(0, 2): [0.5, 1.5]})
|
| 87 |
+
assert loc.tick_values(1, 2) == [1, 1.25, 1.75]
|
| 88 |
+
assert loc.tick_values(2, 1) == [1, 1.25, 1.75]
|
| 89 |
+
assert loc.tick_values(0, 2) == [0.5, 1.5]
|
| 90 |
+
assert loc.tick_values(0.0, 2.0) == [0.5, 1.5]
|
| 91 |
+
assert (loc.tick_values(0, 1) == np.linspace(0, 1, 11)).all()
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class TestMultipleLocator:
|
| 95 |
+
def test_basic(self):
|
| 96 |
+
loc = mticker.MultipleLocator(base=3.147)
|
| 97 |
+
test_value = np.array([-9.441, -6.294, -3.147, 0., 3.147, 6.294,
|
| 98 |
+
9.441, 12.588])
|
| 99 |
+
assert_almost_equal(loc.tick_values(-7, 10), test_value)
|
| 100 |
+
|
| 101 |
+
def test_basic_with_offset(self):
|
| 102 |
+
loc = mticker.MultipleLocator(base=3.147, offset=1.2)
|
| 103 |
+
test_value = np.array([-8.241, -5.094, -1.947, 1.2, 4.347, 7.494,
|
| 104 |
+
10.641])
|
| 105 |
+
assert_almost_equal(loc.tick_values(-7, 10), test_value)
|
| 106 |
+
|
| 107 |
+
def test_view_limits(self):
|
| 108 |
+
"""
|
| 109 |
+
Test basic behavior of view limits.
|
| 110 |
+
"""
|
| 111 |
+
with mpl.rc_context({'axes.autolimit_mode': 'data'}):
|
| 112 |
+
loc = mticker.MultipleLocator(base=3.147)
|
| 113 |
+
assert_almost_equal(loc.view_limits(-5, 5), (-5, 5))
|
| 114 |
+
|
| 115 |
+
def test_view_limits_round_numbers(self):
|
| 116 |
+
"""
|
| 117 |
+
Test that everything works properly with 'round_numbers' for auto
|
| 118 |
+
limit.
|
| 119 |
+
"""
|
| 120 |
+
with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}):
|
| 121 |
+
loc = mticker.MultipleLocator(base=3.147)
|
| 122 |
+
assert_almost_equal(loc.view_limits(-4, 4), (-6.294, 6.294))
|
| 123 |
+
|
| 124 |
+
def test_view_limits_round_numbers_with_offset(self):
|
| 125 |
+
"""
|
| 126 |
+
Test that everything works properly with 'round_numbers' for auto
|
| 127 |
+
limit.
|
| 128 |
+
"""
|
| 129 |
+
with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}):
|
| 130 |
+
loc = mticker.MultipleLocator(base=3.147, offset=1.3)
|
| 131 |
+
assert_almost_equal(loc.view_limits(-4, 4), (-4.994, 4.447))
|
| 132 |
+
|
| 133 |
+
def test_view_limits_single_bin(self):
|
| 134 |
+
"""
|
| 135 |
+
Test that 'round_numbers' works properly with a single bin.
|
| 136 |
+
"""
|
| 137 |
+
with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}):
|
| 138 |
+
loc = mticker.MaxNLocator(nbins=1)
|
| 139 |
+
assert_almost_equal(loc.view_limits(-2.3, 2.3), (-4, 4))
|
| 140 |
+
|
| 141 |
+
def test_set_params(self):
|
| 142 |
+
"""
|
| 143 |
+
Create multiple locator with 0.7 base, and change it to something else.
|
| 144 |
+
See if change was successful.
|
| 145 |
+
"""
|
| 146 |
+
mult = mticker.MultipleLocator(base=0.7)
|
| 147 |
+
mult.set_params(base=1.7)
|
| 148 |
+
assert mult._edge.step == 1.7
|
| 149 |
+
mult.set_params(offset=3)
|
| 150 |
+
assert mult._offset == 3
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class TestAutoMinorLocator:
|
| 154 |
+
def test_basic(self):
|
| 155 |
+
fig, ax = plt.subplots()
|
| 156 |
+
ax.set_xlim(0, 1.39)
|
| 157 |
+
ax.minorticks_on()
|
| 158 |
+
test_value = np.array([0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45,
|
| 159 |
+
0.5, 0.55, 0.65, 0.7, 0.75, 0.85, 0.9,
|
| 160 |
+
0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35])
|
| 161 |
+
assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value)
|
| 162 |
+
|
| 163 |
+
# NB: the following values are assuming that *xlim* is [0, 5]
|
| 164 |
+
params = [
|
| 165 |
+
(0, 0), # no major tick => no minor tick either
|
| 166 |
+
(1, 0) # a single major tick => no minor tick
|
| 167 |
+
]
|
| 168 |
+
|
| 169 |
+
def test_first_and_last_minorticks(self):
|
| 170 |
+
"""
|
| 171 |
+
Test that first and last minor tick appear as expected.
|
| 172 |
+
"""
|
| 173 |
+
# This test is related to issue #22331
|
| 174 |
+
fig, ax = plt.subplots()
|
| 175 |
+
ax.set_xlim(-1.9, 1.9)
|
| 176 |
+
ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
|
| 177 |
+
test_value = np.array([-1.9, -1.8, -1.7, -1.6, -1.4, -1.3, -1.2, -1.1,
|
| 178 |
+
-0.9, -0.8, -0.7, -0.6, -0.4, -0.3, -0.2, -0.1,
|
| 179 |
+
0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9, 1.1,
|
| 180 |
+
1.2, 1.3, 1.4, 1.6, 1.7, 1.8, 1.9])
|
| 181 |
+
assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value)
|
| 182 |
+
|
| 183 |
+
ax.set_xlim(-5, 5)
|
| 184 |
+
test_value = np.array([-5.0, -4.5, -3.5, -3.0, -2.5, -1.5, -1.0, -0.5,
|
| 185 |
+
0.5, 1.0, 1.5, 2.5, 3.0, 3.5, 4.5, 5.0])
|
| 186 |
+
assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value)
|
| 187 |
+
|
| 188 |
+
@pytest.mark.parametrize('nb_majorticks, expected_nb_minorticks', params)
|
| 189 |
+
def test_low_number_of_majorticks(
|
| 190 |
+
self, nb_majorticks, expected_nb_minorticks):
|
| 191 |
+
# This test is related to issue #8804
|
| 192 |
+
fig, ax = plt.subplots()
|
| 193 |
+
xlims = (0, 5) # easier to test the different code paths
|
| 194 |
+
ax.set_xlim(*xlims)
|
| 195 |
+
ax.set_xticks(np.linspace(xlims[0], xlims[1], nb_majorticks))
|
| 196 |
+
ax.minorticks_on()
|
| 197 |
+
ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
|
| 198 |
+
assert len(ax.xaxis.get_minorticklocs()) == expected_nb_minorticks
|
| 199 |
+
|
| 200 |
+
majorstep_minordivisions = [(1, 5),
|
| 201 |
+
(2, 4),
|
| 202 |
+
(2.5, 5),
|
| 203 |
+
(5, 5),
|
| 204 |
+
(10, 5)]
|
| 205 |
+
|
| 206 |
+
# This test is meant to verify the parameterization for
|
| 207 |
+
# test_number_of_minor_ticks
|
| 208 |
+
def test_using_all_default_major_steps(self):
|
| 209 |
+
with mpl.rc_context({'_internal.classic_mode': False}):
|
| 210 |
+
majorsteps = [x[0] for x in self.majorstep_minordivisions]
|
| 211 |
+
np.testing.assert_allclose(majorsteps,
|
| 212 |
+
mticker.AutoLocator()._steps)
|
| 213 |
+
|
| 214 |
+
@pytest.mark.parametrize('major_step, expected_nb_minordivisions',
|
| 215 |
+
majorstep_minordivisions)
|
| 216 |
+
def test_number_of_minor_ticks(
|
| 217 |
+
self, major_step, expected_nb_minordivisions):
|
| 218 |
+
fig, ax = plt.subplots()
|
| 219 |
+
xlims = (0, major_step)
|
| 220 |
+
ax.set_xlim(*xlims)
|
| 221 |
+
ax.set_xticks(xlims)
|
| 222 |
+
ax.minorticks_on()
|
| 223 |
+
ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
|
| 224 |
+
nb_minor_divisions = len(ax.xaxis.get_minorticklocs()) + 1
|
| 225 |
+
assert nb_minor_divisions == expected_nb_minordivisions
|
| 226 |
+
|
| 227 |
+
limits = [(0, 1.39), (0, 0.139),
|
| 228 |
+
(0, 0.11e-19), (0, 0.112e-12),
|
| 229 |
+
(-2.0e-07, -3.3e-08), (1.20e-06, 1.42e-06),
|
| 230 |
+
(-1.34e-06, -1.44e-06), (-8.76e-07, -1.51e-06)]
|
| 231 |
+
|
| 232 |
+
reference = [
|
| 233 |
+
[0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7,
|
| 234 |
+
0.75, 0.85, 0.9, 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35],
|
| 235 |
+
[0.005, 0.01, 0.015, 0.025, 0.03, 0.035, 0.045, 0.05, 0.055, 0.065,
|
| 236 |
+
0.07, 0.075, 0.085, 0.09, 0.095, 0.105, 0.11, 0.115, 0.125, 0.13,
|
| 237 |
+
0.135],
|
| 238 |
+
[5.00e-22, 1.00e-21, 1.50e-21, 2.50e-21, 3.00e-21, 3.50e-21, 4.50e-21,
|
| 239 |
+
5.00e-21, 5.50e-21, 6.50e-21, 7.00e-21, 7.50e-21, 8.50e-21, 9.00e-21,
|
| 240 |
+
9.50e-21, 1.05e-20, 1.10e-20],
|
| 241 |
+
[5.00e-15, 1.00e-14, 1.50e-14, 2.50e-14, 3.00e-14, 3.50e-14, 4.50e-14,
|
| 242 |
+
5.00e-14, 5.50e-14, 6.50e-14, 7.00e-14, 7.50e-14, 8.50e-14, 9.00e-14,
|
| 243 |
+
9.50e-14, 1.05e-13, 1.10e-13],
|
| 244 |
+
[-1.95e-07, -1.90e-07, -1.85e-07, -1.75e-07, -1.70e-07, -1.65e-07,
|
| 245 |
+
-1.55e-07, -1.50e-07, -1.45e-07, -1.35e-07, -1.30e-07, -1.25e-07,
|
| 246 |
+
-1.15e-07, -1.10e-07, -1.05e-07, -9.50e-08, -9.00e-08, -8.50e-08,
|
| 247 |
+
-7.50e-08, -7.00e-08, -6.50e-08, -5.50e-08, -5.00e-08, -4.50e-08,
|
| 248 |
+
-3.50e-08],
|
| 249 |
+
[1.21e-06, 1.22e-06, 1.23e-06, 1.24e-06, 1.26e-06, 1.27e-06, 1.28e-06,
|
| 250 |
+
1.29e-06, 1.31e-06, 1.32e-06, 1.33e-06, 1.34e-06, 1.36e-06, 1.37e-06,
|
| 251 |
+
1.38e-06, 1.39e-06, 1.41e-06, 1.42e-06],
|
| 252 |
+
[-1.435e-06, -1.430e-06, -1.425e-06, -1.415e-06, -1.410e-06,
|
| 253 |
+
-1.405e-06, -1.395e-06, -1.390e-06, -1.385e-06, -1.375e-06,
|
| 254 |
+
-1.370e-06, -1.365e-06, -1.355e-06, -1.350e-06, -1.345e-06],
|
| 255 |
+
[-1.48e-06, -1.46e-06, -1.44e-06, -1.42e-06, -1.38e-06, -1.36e-06,
|
| 256 |
+
-1.34e-06, -1.32e-06, -1.28e-06, -1.26e-06, -1.24e-06, -1.22e-06,
|
| 257 |
+
-1.18e-06, -1.16e-06, -1.14e-06, -1.12e-06, -1.08e-06, -1.06e-06,
|
| 258 |
+
-1.04e-06, -1.02e-06, -9.80e-07, -9.60e-07, -9.40e-07, -9.20e-07,
|
| 259 |
+
-8.80e-07]]
|
| 260 |
+
|
| 261 |
+
additional_data = list(zip(limits, reference))
|
| 262 |
+
|
| 263 |
+
@pytest.mark.parametrize('lim, ref', additional_data)
|
| 264 |
+
def test_additional(self, lim, ref):
|
| 265 |
+
fig, ax = plt.subplots()
|
| 266 |
+
|
| 267 |
+
ax.minorticks_on()
|
| 268 |
+
ax.grid(True, 'minor', 'y', linewidth=1)
|
| 269 |
+
ax.grid(True, 'major', color='k', linewidth=1)
|
| 270 |
+
ax.set_ylim(lim)
|
| 271 |
+
|
| 272 |
+
assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref)
|
| 273 |
+
|
| 274 |
+
@pytest.mark.parametrize('use_rcparam', [False, True])
|
| 275 |
+
@pytest.mark.parametrize(
|
| 276 |
+
'lim, ref', [
|
| 277 |
+
((0, 1.39),
|
| 278 |
+
[0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7,
|
| 279 |
+
0.75, 0.85, 0.9, 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35]),
|
| 280 |
+
((0, 0.139),
|
| 281 |
+
[0.005, 0.01, 0.015, 0.025, 0.03, 0.035, 0.045, 0.05, 0.055,
|
| 282 |
+
0.065, 0.07, 0.075, 0.085, 0.09, 0.095, 0.105, 0.11, 0.115,
|
| 283 |
+
0.125, 0.13, 0.135]),
|
| 284 |
+
])
|
| 285 |
+
def test_number_of_minor_ticks_auto(self, lim, ref, use_rcparam):
|
| 286 |
+
if use_rcparam:
|
| 287 |
+
context = {'xtick.minor.ndivs': 'auto', 'ytick.minor.ndivs': 'auto'}
|
| 288 |
+
kwargs = {}
|
| 289 |
+
else:
|
| 290 |
+
context = {}
|
| 291 |
+
kwargs = {'n': 'auto'}
|
| 292 |
+
|
| 293 |
+
with mpl.rc_context(context):
|
| 294 |
+
fig, ax = plt.subplots()
|
| 295 |
+
ax.set_xlim(*lim)
|
| 296 |
+
ax.set_ylim(*lim)
|
| 297 |
+
ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))
|
| 298 |
+
ax.yaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))
|
| 299 |
+
assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), ref)
|
| 300 |
+
assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref)
|
| 301 |
+
|
| 302 |
+
@pytest.mark.parametrize('use_rcparam', [False, True])
|
| 303 |
+
@pytest.mark.parametrize(
|
| 304 |
+
'n, lim, ref', [
|
| 305 |
+
(2, (0, 4), [0.5, 1.5, 2.5, 3.5]),
|
| 306 |
+
(4, (0, 2), [0.25, 0.5, 0.75, 1.25, 1.5, 1.75]),
|
| 307 |
+
(10, (0, 1), [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]),
|
| 308 |
+
])
|
| 309 |
+
def test_number_of_minor_ticks_int(self, n, lim, ref, use_rcparam):
|
| 310 |
+
if use_rcparam:
|
| 311 |
+
context = {'xtick.minor.ndivs': n, 'ytick.minor.ndivs': n}
|
| 312 |
+
kwargs = {}
|
| 313 |
+
else:
|
| 314 |
+
context = {}
|
| 315 |
+
kwargs = {'n': n}
|
| 316 |
+
|
| 317 |
+
with mpl.rc_context(context):
|
| 318 |
+
fig, ax = plt.subplots()
|
| 319 |
+
ax.set_xlim(*lim)
|
| 320 |
+
ax.set_ylim(*lim)
|
| 321 |
+
ax.xaxis.set_major_locator(mticker.MultipleLocator(1))
|
| 322 |
+
ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))
|
| 323 |
+
ax.yaxis.set_major_locator(mticker.MultipleLocator(1))
|
| 324 |
+
ax.yaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))
|
| 325 |
+
assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), ref)
|
| 326 |
+
assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
class TestLogLocator:
|
| 330 |
+
def test_basic(self):
|
| 331 |
+
loc = mticker.LogLocator(numticks=5)
|
| 332 |
+
with pytest.raises(ValueError):
|
| 333 |
+
loc.tick_values(0, 1000)
|
| 334 |
+
|
| 335 |
+
test_value = np.array([1.00000000e-05, 1.00000000e-03, 1.00000000e-01,
|
| 336 |
+
1.00000000e+01, 1.00000000e+03, 1.00000000e+05,
|
| 337 |
+
1.00000000e+07, 1.000000000e+09])
|
| 338 |
+
assert_almost_equal(loc.tick_values(0.001, 1.1e5), test_value)
|
| 339 |
+
|
| 340 |
+
loc = mticker.LogLocator(base=2)
|
| 341 |
+
test_value = np.array([0.5, 1., 2., 4., 8., 16., 32., 64., 128., 256.])
|
| 342 |
+
assert_almost_equal(loc.tick_values(1, 100), test_value)
|
| 343 |
+
|
| 344 |
+
def test_polar_axes(self):
|
| 345 |
+
"""
|
| 346 |
+
Polar Axes have a different ticking logic.
|
| 347 |
+
"""
|
| 348 |
+
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
|
| 349 |
+
ax.set_yscale('log')
|
| 350 |
+
ax.set_ylim(1, 100)
|
| 351 |
+
assert_array_equal(ax.get_yticks(), [10, 100, 1000])
|
| 352 |
+
|
| 353 |
+
def test_switch_to_autolocator(self):
|
| 354 |
+
loc = mticker.LogLocator(subs="all")
|
| 355 |
+
assert_array_equal(loc.tick_values(0.45, 0.55),
|
| 356 |
+
[0.44, 0.46, 0.48, 0.5, 0.52, 0.54, 0.56])
|
| 357 |
+
# check that we *skip* 1.0, and 10, because this is a minor locator
|
| 358 |
+
loc = mticker.LogLocator(subs=np.arange(2, 10))
|
| 359 |
+
assert 1.0 not in loc.tick_values(0.9, 20.)
|
| 360 |
+
assert 10.0 not in loc.tick_values(0.9, 20.)
|
| 361 |
+
|
| 362 |
+
def test_set_params(self):
|
| 363 |
+
"""
|
| 364 |
+
Create log locator with default value, base=10.0, subs=[1.0],
|
| 365 |
+
numticks=15 and change it to something else.
|
| 366 |
+
See if change was successful. Should not raise exception.
|
| 367 |
+
"""
|
| 368 |
+
loc = mticker.LogLocator()
|
| 369 |
+
loc.set_params(numticks=7, subs=[2.0], base=4)
|
| 370 |
+
assert loc.numticks == 7
|
| 371 |
+
assert loc._base == 4
|
| 372 |
+
assert list(loc._subs) == [2.0]
|
| 373 |
+
|
| 374 |
+
def test_tick_values_correct(self):
|
| 375 |
+
ll = mticker.LogLocator(subs=(1, 2, 5))
|
| 376 |
+
test_value = np.array([1.e-01, 2.e-01, 5.e-01, 1.e+00, 2.e+00, 5.e+00,
|
| 377 |
+
1.e+01, 2.e+01, 5.e+01, 1.e+02, 2.e+02, 5.e+02,
|
| 378 |
+
1.e+03, 2.e+03, 5.e+03, 1.e+04, 2.e+04, 5.e+04,
|
| 379 |
+
1.e+05, 2.e+05, 5.e+05, 1.e+06, 2.e+06, 5.e+06,
|
| 380 |
+
1.e+07, 2.e+07, 5.e+07, 1.e+08, 2.e+08, 5.e+08])
|
| 381 |
+
assert_almost_equal(ll.tick_values(1, 1e7), test_value)
|
| 382 |
+
|
| 383 |
+
def test_tick_values_not_empty(self):
|
| 384 |
+
mpl.rcParams['_internal.classic_mode'] = False
|
| 385 |
+
ll = mticker.LogLocator(subs=(1, 2, 5))
|
| 386 |
+
test_value = np.array([1.e-01, 2.e-01, 5.e-01, 1.e+00, 2.e+00, 5.e+00,
|
| 387 |
+
1.e+01, 2.e+01, 5.e+01, 1.e+02, 2.e+02, 5.e+02,
|
| 388 |
+
1.e+03, 2.e+03, 5.e+03, 1.e+04, 2.e+04, 5.e+04,
|
| 389 |
+
1.e+05, 2.e+05, 5.e+05, 1.e+06, 2.e+06, 5.e+06,
|
| 390 |
+
1.e+07, 2.e+07, 5.e+07, 1.e+08, 2.e+08, 5.e+08,
|
| 391 |
+
1.e+09, 2.e+09, 5.e+09])
|
| 392 |
+
assert_almost_equal(ll.tick_values(1, 1e8), test_value)
|
| 393 |
+
|
| 394 |
+
def test_multiple_shared_axes(self):
|
| 395 |
+
rng = np.random.default_rng(19680801)
|
| 396 |
+
dummy_data = [rng.normal(size=100), [], []]
|
| 397 |
+
fig, axes = plt.subplots(len(dummy_data), sharex=True, sharey=True)
|
| 398 |
+
|
| 399 |
+
for ax, data in zip(axes.flatten(), dummy_data):
|
| 400 |
+
ax.hist(data, bins=10)
|
| 401 |
+
ax.set_yscale('log', nonpositive='clip')
|
| 402 |
+
|
| 403 |
+
for ax in axes.flatten():
|
| 404 |
+
assert all(ax.get_yticks() == axes[0].get_yticks())
|
| 405 |
+
assert ax.get_ylim() == axes[0].get_ylim()
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
class TestNullLocator:
|
| 409 |
+
def test_set_params(self):
|
| 410 |
+
"""
|
| 411 |
+
Create null locator, and attempt to call set_params() on it.
|
| 412 |
+
Should not exception, and should raise a warning.
|
| 413 |
+
"""
|
| 414 |
+
loc = mticker.NullLocator()
|
| 415 |
+
with pytest.warns(UserWarning):
|
| 416 |
+
loc.set_params()
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
class _LogitHelper:
|
| 420 |
+
@staticmethod
|
| 421 |
+
def isclose(x, y):
|
| 422 |
+
return (np.isclose(-np.log(1/x-1), -np.log(1/y-1))
|
| 423 |
+
if 0 < x < 1 and 0 < y < 1 else False)
|
| 424 |
+
|
| 425 |
+
@staticmethod
|
| 426 |
+
def assert_almost_equal(x, y):
|
| 427 |
+
ax = np.array(x)
|
| 428 |
+
ay = np.array(y)
|
| 429 |
+
assert np.all(ax > 0) and np.all(ax < 1)
|
| 430 |
+
assert np.all(ay > 0) and np.all(ay < 1)
|
| 431 |
+
lx = -np.log(1/ax-1)
|
| 432 |
+
ly = -np.log(1/ay-1)
|
| 433 |
+
assert_almost_equal(lx, ly)
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class TestLogitLocator:
|
| 437 |
+
ref_basic_limits = [
|
| 438 |
+
(5e-2, 1 - 5e-2),
|
| 439 |
+
(5e-3, 1 - 5e-3),
|
| 440 |
+
(5e-4, 1 - 5e-4),
|
| 441 |
+
(5e-5, 1 - 5e-5),
|
| 442 |
+
(5e-6, 1 - 5e-6),
|
| 443 |
+
(5e-7, 1 - 5e-7),
|
| 444 |
+
(5e-8, 1 - 5e-8),
|
| 445 |
+
(5e-9, 1 - 5e-9),
|
| 446 |
+
]
|
| 447 |
+
|
| 448 |
+
ref_basic_major_ticks = [
|
| 449 |
+
1 / (10 ** np.arange(1, 3)),
|
| 450 |
+
1 / (10 ** np.arange(1, 4)),
|
| 451 |
+
1 / (10 ** np.arange(1, 5)),
|
| 452 |
+
1 / (10 ** np.arange(1, 6)),
|
| 453 |
+
1 / (10 ** np.arange(1, 7)),
|
| 454 |
+
1 / (10 ** np.arange(1, 8)),
|
| 455 |
+
1 / (10 ** np.arange(1, 9)),
|
| 456 |
+
1 / (10 ** np.arange(1, 10)),
|
| 457 |
+
]
|
| 458 |
+
|
| 459 |
+
ref_maxn_limits = [(0.4, 0.6), (5e-2, 2e-1), (1 - 2e-1, 1 - 5e-2)]
|
| 460 |
+
|
| 461 |
+
@pytest.mark.parametrize(
|
| 462 |
+
"lims, expected_low_ticks",
|
| 463 |
+
zip(ref_basic_limits, ref_basic_major_ticks),
|
| 464 |
+
)
|
| 465 |
+
def test_basic_major(self, lims, expected_low_ticks):
|
| 466 |
+
"""
|
| 467 |
+
Create logit locator with huge number of major, and tests ticks.
|
| 468 |
+
"""
|
| 469 |
+
expected_ticks = sorted(
|
| 470 |
+
[*expected_low_ticks, 0.5, *(1 - expected_low_ticks)]
|
| 471 |
+
)
|
| 472 |
+
loc = mticker.LogitLocator(nbins=100)
|
| 473 |
+
_LogitHelper.assert_almost_equal(
|
| 474 |
+
loc.tick_values(*lims),
|
| 475 |
+
expected_ticks
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
@pytest.mark.parametrize("lims", ref_maxn_limits)
|
| 479 |
+
def test_maxn_major(self, lims):
|
| 480 |
+
"""
|
| 481 |
+
When the axis is zoomed, the locator must have the same behavior as
|
| 482 |
+
MaxNLocator.
|
| 483 |
+
"""
|
| 484 |
+
loc = mticker.LogitLocator(nbins=100)
|
| 485 |
+
maxn_loc = mticker.MaxNLocator(nbins=100, steps=[1, 2, 5, 10])
|
| 486 |
+
for nbins in (4, 8, 16):
|
| 487 |
+
loc.set_params(nbins=nbins)
|
| 488 |
+
maxn_loc.set_params(nbins=nbins)
|
| 489 |
+
ticks = loc.tick_values(*lims)
|
| 490 |
+
maxn_ticks = maxn_loc.tick_values(*lims)
|
| 491 |
+
assert ticks.shape == maxn_ticks.shape
|
| 492 |
+
assert (ticks == maxn_ticks).all()
|
| 493 |
+
|
| 494 |
+
@pytest.mark.parametrize("lims", ref_basic_limits + ref_maxn_limits)
|
| 495 |
+
def test_nbins_major(self, lims):
|
| 496 |
+
"""
|
| 497 |
+
Assert logit locator for respecting nbins param.
|
| 498 |
+
"""
|
| 499 |
+
|
| 500 |
+
basic_needed = int(-np.floor(np.log10(lims[0]))) * 2 + 1
|
| 501 |
+
loc = mticker.LogitLocator(nbins=100)
|
| 502 |
+
for nbins in range(basic_needed, 2, -1):
|
| 503 |
+
loc.set_params(nbins=nbins)
|
| 504 |
+
assert len(loc.tick_values(*lims)) <= nbins + 2
|
| 505 |
+
|
| 506 |
+
@pytest.mark.parametrize(
|
| 507 |
+
"lims, expected_low_ticks",
|
| 508 |
+
zip(ref_basic_limits, ref_basic_major_ticks),
|
| 509 |
+
)
|
| 510 |
+
def test_minor(self, lims, expected_low_ticks):
|
| 511 |
+
"""
|
| 512 |
+
In large scale, test the presence of minor,
|
| 513 |
+
and assert no minor when major are subsampled.
|
| 514 |
+
"""
|
| 515 |
+
|
| 516 |
+
expected_ticks = sorted(
|
| 517 |
+
[*expected_low_ticks, 0.5, *(1 - expected_low_ticks)]
|
| 518 |
+
)
|
| 519 |
+
basic_needed = len(expected_ticks)
|
| 520 |
+
loc = mticker.LogitLocator(nbins=100)
|
| 521 |
+
minor_loc = mticker.LogitLocator(nbins=100, minor=True)
|
| 522 |
+
for nbins in range(basic_needed, 2, -1):
|
| 523 |
+
loc.set_params(nbins=nbins)
|
| 524 |
+
minor_loc.set_params(nbins=nbins)
|
| 525 |
+
major_ticks = loc.tick_values(*lims)
|
| 526 |
+
minor_ticks = minor_loc.tick_values(*lims)
|
| 527 |
+
if len(major_ticks) >= len(expected_ticks):
|
| 528 |
+
# no subsample, we must have a lot of minors ticks
|
| 529 |
+
assert (len(major_ticks) - 1) * 5 < len(minor_ticks)
|
| 530 |
+
else:
|
| 531 |
+
# subsample
|
| 532 |
+
_LogitHelper.assert_almost_equal(
|
| 533 |
+
sorted([*major_ticks, *minor_ticks]), expected_ticks)
|
| 534 |
+
|
| 535 |
+
def test_minor_attr(self):
|
| 536 |
+
loc = mticker.LogitLocator(nbins=100)
|
| 537 |
+
assert not loc.minor
|
| 538 |
+
loc.minor = True
|
| 539 |
+
assert loc.minor
|
| 540 |
+
loc.set_params(minor=False)
|
| 541 |
+
assert not loc.minor
|
| 542 |
+
|
| 543 |
+
acceptable_vmin_vmax = [
|
| 544 |
+
*(2.5 ** np.arange(-3, 0)),
|
| 545 |
+
*(1 - 2.5 ** np.arange(-3, 0)),
|
| 546 |
+
]
|
| 547 |
+
|
| 548 |
+
@pytest.mark.parametrize(
|
| 549 |
+
"lims",
|
| 550 |
+
[
|
| 551 |
+
(a, b)
|
| 552 |
+
for (a, b) in itertools.product(acceptable_vmin_vmax, repeat=2)
|
| 553 |
+
if a != b
|
| 554 |
+
],
|
| 555 |
+
)
|
| 556 |
+
def test_nonsingular_ok(self, lims):
|
| 557 |
+
"""
|
| 558 |
+
Create logit locator, and test the nonsingular method for acceptable
|
| 559 |
+
value
|
| 560 |
+
"""
|
| 561 |
+
loc = mticker.LogitLocator()
|
| 562 |
+
lims2 = loc.nonsingular(*lims)
|
| 563 |
+
assert sorted(lims) == sorted(lims2)
|
| 564 |
+
|
| 565 |
+
@pytest.mark.parametrize("okval", acceptable_vmin_vmax)
|
| 566 |
+
def test_nonsingular_nok(self, okval):
|
| 567 |
+
"""
|
| 568 |
+
Create logit locator, and test the nonsingular method for non
|
| 569 |
+
acceptable value
|
| 570 |
+
"""
|
| 571 |
+
loc = mticker.LogitLocator()
|
| 572 |
+
vmin, vmax = (-1, okval)
|
| 573 |
+
vmin2, vmax2 = loc.nonsingular(vmin, vmax)
|
| 574 |
+
assert vmax2 == vmax
|
| 575 |
+
assert 0 < vmin2 < vmax2
|
| 576 |
+
vmin, vmax = (okval, 2)
|
| 577 |
+
vmin2, vmax2 = loc.nonsingular(vmin, vmax)
|
| 578 |
+
assert vmin2 == vmin
|
| 579 |
+
assert vmin2 < vmax2 < 1
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
class TestFixedLocator:
|
| 583 |
+
def test_set_params(self):
|
| 584 |
+
"""
|
| 585 |
+
Create fixed locator with 5 nbins, and change it to something else.
|
| 586 |
+
See if change was successful.
|
| 587 |
+
Should not exception.
|
| 588 |
+
"""
|
| 589 |
+
fixed = mticker.FixedLocator(range(0, 24), nbins=5)
|
| 590 |
+
fixed.set_params(nbins=7)
|
| 591 |
+
assert fixed.nbins == 7
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
class TestIndexLocator:
|
| 595 |
+
def test_set_params(self):
|
| 596 |
+
"""
|
| 597 |
+
Create index locator with 3 base, 4 offset. and change it to something
|
| 598 |
+
else. See if change was successful.
|
| 599 |
+
Should not exception.
|
| 600 |
+
"""
|
| 601 |
+
index = mticker.IndexLocator(base=3, offset=4)
|
| 602 |
+
index.set_params(base=7, offset=7)
|
| 603 |
+
assert index._base == 7
|
| 604 |
+
assert index.offset == 7
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
class TestSymmetricalLogLocator:
|
| 608 |
+
def test_set_params(self):
|
| 609 |
+
"""
|
| 610 |
+
Create symmetrical log locator with default subs =[1.0] numticks = 15,
|
| 611 |
+
and change it to something else.
|
| 612 |
+
See if change was successful.
|
| 613 |
+
Should not exception.
|
| 614 |
+
"""
|
| 615 |
+
sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)
|
| 616 |
+
sym.set_params(subs=[2.0], numticks=8)
|
| 617 |
+
assert sym._subs == [2.0]
|
| 618 |
+
assert sym.numticks == 8
|
| 619 |
+
|
| 620 |
+
@pytest.mark.parametrize(
|
| 621 |
+
'vmin, vmax, expected',
|
| 622 |
+
[
|
| 623 |
+
(0, 1, [0, 1]),
|
| 624 |
+
(-1, 1, [-1, 0, 1]),
|
| 625 |
+
],
|
| 626 |
+
)
|
| 627 |
+
def test_values(self, vmin, vmax, expected):
|
| 628 |
+
# https://github.com/matplotlib/matplotlib/issues/25945
|
| 629 |
+
sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)
|
| 630 |
+
ticks = sym.tick_values(vmin=vmin, vmax=vmax)
|
| 631 |
+
assert_array_equal(ticks, expected)
|
| 632 |
+
|
| 633 |
+
def test_subs(self):
|
| 634 |
+
sym = mticker.SymmetricalLogLocator(base=10, linthresh=1, subs=[2.0, 4.0])
|
| 635 |
+
sym.create_dummy_axis()
|
| 636 |
+
sym.axis.set_view_interval(-10, 10)
|
| 637 |
+
assert_array_equal(sym(), [-20, -40, -2, -4, 0, 2, 4, 20, 40])
|
| 638 |
+
|
| 639 |
+
def test_extending(self):
|
| 640 |
+
sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)
|
| 641 |
+
sym.create_dummy_axis()
|
| 642 |
+
sym.axis.set_view_interval(8, 9)
|
| 643 |
+
assert (sym() == [1.0]).all()
|
| 644 |
+
sym.axis.set_view_interval(8, 12)
|
| 645 |
+
assert (sym() == [1.0, 10.0]).all()
|
| 646 |
+
assert sym.view_limits(10, 10) == (1, 100)
|
| 647 |
+
assert sym.view_limits(-10, -10) == (-100, -1)
|
| 648 |
+
assert sym.view_limits(0, 0) == (-0.001, 0.001)
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
class TestAsinhLocator:
|
| 652 |
+
def test_init(self):
|
| 653 |
+
lctr = mticker.AsinhLocator(linear_width=2.718, numticks=19)
|
| 654 |
+
assert lctr.linear_width == 2.718
|
| 655 |
+
assert lctr.numticks == 19
|
| 656 |
+
assert lctr.base == 10
|
| 657 |
+
|
| 658 |
+
def test_set_params(self):
|
| 659 |
+
lctr = mticker.AsinhLocator(linear_width=5,
|
| 660 |
+
numticks=17, symthresh=0.125,
|
| 661 |
+
base=4, subs=(2.5, 3.25))
|
| 662 |
+
assert lctr.numticks == 17
|
| 663 |
+
assert lctr.symthresh == 0.125
|
| 664 |
+
assert lctr.base == 4
|
| 665 |
+
assert lctr.subs == (2.5, 3.25)
|
| 666 |
+
|
| 667 |
+
lctr.set_params(numticks=23)
|
| 668 |
+
assert lctr.numticks == 23
|
| 669 |
+
lctr.set_params(None)
|
| 670 |
+
assert lctr.numticks == 23
|
| 671 |
+
|
| 672 |
+
lctr.set_params(symthresh=0.5)
|
| 673 |
+
assert lctr.symthresh == 0.5
|
| 674 |
+
lctr.set_params(symthresh=None)
|
| 675 |
+
assert lctr.symthresh == 0.5
|
| 676 |
+
|
| 677 |
+
lctr.set_params(base=7)
|
| 678 |
+
assert lctr.base == 7
|
| 679 |
+
lctr.set_params(base=None)
|
| 680 |
+
assert lctr.base == 7
|
| 681 |
+
|
| 682 |
+
lctr.set_params(subs=(2, 4.125))
|
| 683 |
+
assert lctr.subs == (2, 4.125)
|
| 684 |
+
lctr.set_params(subs=None)
|
| 685 |
+
assert lctr.subs == (2, 4.125)
|
| 686 |
+
lctr.set_params(subs=[])
|
| 687 |
+
assert lctr.subs is None
|
| 688 |
+
|
| 689 |
+
def test_linear_values(self):
|
| 690 |
+
lctr = mticker.AsinhLocator(linear_width=100, numticks=11, base=0)
|
| 691 |
+
|
| 692 |
+
assert_almost_equal(lctr.tick_values(-1, 1),
|
| 693 |
+
np.arange(-1, 1.01, 0.2))
|
| 694 |
+
assert_almost_equal(lctr.tick_values(-0.1, 0.1),
|
| 695 |
+
np.arange(-0.1, 0.101, 0.02))
|
| 696 |
+
assert_almost_equal(lctr.tick_values(-0.01, 0.01),
|
| 697 |
+
np.arange(-0.01, 0.0101, 0.002))
|
| 698 |
+
|
| 699 |
+
def test_wide_values(self):
|
| 700 |
+
lctr = mticker.AsinhLocator(linear_width=0.1, numticks=11, base=0)
|
| 701 |
+
|
| 702 |
+
assert_almost_equal(lctr.tick_values(-100, 100),
|
| 703 |
+
[-100, -20, -5, -1, -0.2,
|
| 704 |
+
0, 0.2, 1, 5, 20, 100])
|
| 705 |
+
assert_almost_equal(lctr.tick_values(-1000, 1000),
|
| 706 |
+
[-1000, -100, -20, -3, -0.4,
|
| 707 |
+
0, 0.4, 3, 20, 100, 1000])
|
| 708 |
+
|
| 709 |
+
def test_near_zero(self):
|
| 710 |
+
"""Check that manually injected zero will supersede nearby tick"""
|
| 711 |
+
lctr = mticker.AsinhLocator(linear_width=100, numticks=3, base=0)
|
| 712 |
+
|
| 713 |
+
assert_almost_equal(lctr.tick_values(-1.1, 0.9), [-1.0, 0.0, 0.9])
|
| 714 |
+
|
| 715 |
+
def test_fallback(self):
|
| 716 |
+
lctr = mticker.AsinhLocator(1.0, numticks=11)
|
| 717 |
+
|
| 718 |
+
assert_almost_equal(lctr.tick_values(101, 102),
|
| 719 |
+
np.arange(101, 102.01, 0.1))
|
| 720 |
+
|
| 721 |
+
def test_symmetrizing(self):
|
| 722 |
+
lctr = mticker.AsinhLocator(linear_width=1, numticks=3,
|
| 723 |
+
symthresh=0.25, base=0)
|
| 724 |
+
lctr.create_dummy_axis()
|
| 725 |
+
|
| 726 |
+
lctr.axis.set_view_interval(-1, 2)
|
| 727 |
+
assert_almost_equal(lctr(), [-1, 0, 2])
|
| 728 |
+
|
| 729 |
+
lctr.axis.set_view_interval(-1, 0.9)
|
| 730 |
+
assert_almost_equal(lctr(), [-1, 0, 1])
|
| 731 |
+
|
| 732 |
+
lctr.axis.set_view_interval(-0.85, 1.05)
|
| 733 |
+
assert_almost_equal(lctr(), [-1, 0, 1])
|
| 734 |
+
|
| 735 |
+
lctr.axis.set_view_interval(1, 1.1)
|
| 736 |
+
assert_almost_equal(lctr(), [1, 1.05, 1.1])
|
| 737 |
+
|
| 738 |
+
def test_base_rounding(self):
|
| 739 |
+
lctr10 = mticker.AsinhLocator(linear_width=1, numticks=8,
|
| 740 |
+
base=10, subs=(1, 3, 5))
|
| 741 |
+
assert_almost_equal(lctr10.tick_values(-110, 110),
|
| 742 |
+
[-500, -300, -100, -50, -30, -10, -5, -3, -1,
|
| 743 |
+
-0.5, -0.3, -0.1, 0, 0.1, 0.3, 0.5,
|
| 744 |
+
1, 3, 5, 10, 30, 50, 100, 300, 500])
|
| 745 |
+
|
| 746 |
+
lctr5 = mticker.AsinhLocator(linear_width=1, numticks=20, base=5)
|
| 747 |
+
assert_almost_equal(lctr5.tick_values(-1050, 1050),
|
| 748 |
+
[-625, -125, -25, -5, -1, -0.2, 0,
|
| 749 |
+
0.2, 1, 5, 25, 125, 625])
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
class TestScalarFormatter:
|
| 753 |
+
offset_data = [
|
| 754 |
+
(123, 189, 0),
|
| 755 |
+
(-189, -123, 0),
|
| 756 |
+
(12341, 12349, 12340),
|
| 757 |
+
(-12349, -12341, -12340),
|
| 758 |
+
(99999.5, 100010.5, 100000),
|
| 759 |
+
(-100010.5, -99999.5, -100000),
|
| 760 |
+
(99990.5, 100000.5, 100000),
|
| 761 |
+
(-100000.5, -99990.5, -100000),
|
| 762 |
+
(1233999, 1234001, 1234000),
|
| 763 |
+
(-1234001, -1233999, -1234000),
|
| 764 |
+
(1, 1, 1),
|
| 765 |
+
(123, 123, 0),
|
| 766 |
+
# Test cases courtesy of @WeatherGod
|
| 767 |
+
(.4538, .4578, .45),
|
| 768 |
+
(3789.12, 3783.1, 3780),
|
| 769 |
+
(45124.3, 45831.75, 45000),
|
| 770 |
+
(0.000721, 0.0007243, 0.00072),
|
| 771 |
+
(12592.82, 12591.43, 12590),
|
| 772 |
+
(9., 12., 0),
|
| 773 |
+
(900., 1200., 0),
|
| 774 |
+
(1900., 1200., 0),
|
| 775 |
+
(0.99, 1.01, 1),
|
| 776 |
+
(9.99, 10.01, 10),
|
| 777 |
+
(99.99, 100.01, 100),
|
| 778 |
+
(5.99, 6.01, 6),
|
| 779 |
+
(15.99, 16.01, 16),
|
| 780 |
+
(-0.452, 0.492, 0),
|
| 781 |
+
(-0.492, 0.492, 0),
|
| 782 |
+
(12331.4, 12350.5, 12300),
|
| 783 |
+
(-12335.3, 12335.3, 0),
|
| 784 |
+
]
|
| 785 |
+
|
| 786 |
+
use_offset_data = [True, False]
|
| 787 |
+
|
| 788 |
+
useMathText_data = [True, False]
|
| 789 |
+
|
| 790 |
+
# (sci_type, scilimits, lim, orderOfMag, fewticks)
|
| 791 |
+
scilimits_data = [
|
| 792 |
+
(False, (0, 0), (10.0, 20.0), 0, False),
|
| 793 |
+
(True, (-2, 2), (-10, 20), 0, False),
|
| 794 |
+
(True, (-2, 2), (-20, 10), 0, False),
|
| 795 |
+
(True, (-2, 2), (-110, 120), 2, False),
|
| 796 |
+
(True, (-2, 2), (-120, 110), 2, False),
|
| 797 |
+
(True, (-2, 2), (-.001, 0.002), -3, False),
|
| 798 |
+
(True, (-7, 7), (0.18e10, 0.83e10), 9, True),
|
| 799 |
+
(True, (0, 0), (-1e5, 1e5), 5, False),
|
| 800 |
+
(True, (6, 6), (-1e5, 1e5), 6, False),
|
| 801 |
+
]
|
| 802 |
+
|
| 803 |
+
cursor_data = [
|
| 804 |
+
[0., "0.000"],
|
| 805 |
+
[0.0123, "0.012"],
|
| 806 |
+
[0.123, "0.123"],
|
| 807 |
+
[1.23, "1.230"],
|
| 808 |
+
[12.3, "12.300"],
|
| 809 |
+
]
|
| 810 |
+
|
| 811 |
+
format_data = [
|
| 812 |
+
(.1, "1e-1"),
|
| 813 |
+
(.11, "1.1e-1"),
|
| 814 |
+
(1e8, "1e8"),
|
| 815 |
+
(1.1e8, "1.1e8"),
|
| 816 |
+
]
|
| 817 |
+
|
| 818 |
+
@pytest.mark.parametrize('unicode_minus, result',
|
| 819 |
+
[(True, "\N{MINUS SIGN}1"), (False, "-1")])
|
| 820 |
+
def test_unicode_minus(self, unicode_minus, result):
|
| 821 |
+
mpl.rcParams['axes.unicode_minus'] = unicode_minus
|
| 822 |
+
assert (
|
| 823 |
+
plt.gca().xaxis.get_major_formatter().format_data_short(-1).strip()
|
| 824 |
+
== result)
|
| 825 |
+
|
| 826 |
+
@pytest.mark.parametrize('left, right, offset', offset_data)
|
| 827 |
+
def test_offset_value(self, left, right, offset):
|
| 828 |
+
fig, ax = plt.subplots()
|
| 829 |
+
formatter = ax.xaxis.get_major_formatter()
|
| 830 |
+
|
| 831 |
+
with (pytest.warns(UserWarning, match='Attempting to set identical')
|
| 832 |
+
if left == right else nullcontext()):
|
| 833 |
+
ax.set_xlim(left, right)
|
| 834 |
+
ax.xaxis._update_ticks()
|
| 835 |
+
assert formatter.offset == offset
|
| 836 |
+
|
| 837 |
+
with (pytest.warns(UserWarning, match='Attempting to set identical')
|
| 838 |
+
if left == right else nullcontext()):
|
| 839 |
+
ax.set_xlim(right, left)
|
| 840 |
+
ax.xaxis._update_ticks()
|
| 841 |
+
assert formatter.offset == offset
|
| 842 |
+
|
| 843 |
+
@pytest.mark.parametrize('use_offset', use_offset_data)
|
| 844 |
+
def test_use_offset(self, use_offset):
|
| 845 |
+
with mpl.rc_context({'axes.formatter.useoffset': use_offset}):
|
| 846 |
+
tmp_form = mticker.ScalarFormatter()
|
| 847 |
+
assert use_offset == tmp_form.get_useOffset()
|
| 848 |
+
assert tmp_form.offset == 0
|
| 849 |
+
|
| 850 |
+
@pytest.mark.parametrize('use_math_text', useMathText_data)
|
| 851 |
+
def test_useMathText(self, use_math_text):
|
| 852 |
+
with mpl.rc_context({'axes.formatter.use_mathtext': use_math_text}):
|
| 853 |
+
tmp_form = mticker.ScalarFormatter()
|
| 854 |
+
assert use_math_text == tmp_form.get_useMathText()
|
| 855 |
+
|
| 856 |
+
def test_set_use_offset_float(self):
|
| 857 |
+
tmp_form = mticker.ScalarFormatter()
|
| 858 |
+
tmp_form.set_useOffset(0.5)
|
| 859 |
+
assert not tmp_form.get_useOffset()
|
| 860 |
+
assert tmp_form.offset == 0.5
|
| 861 |
+
|
| 862 |
+
def test_use_locale(self):
|
| 863 |
+
conv = locale.localeconv()
|
| 864 |
+
sep = conv['thousands_sep']
|
| 865 |
+
if not sep or conv['grouping'][-1:] in ([], [locale.CHAR_MAX]):
|
| 866 |
+
pytest.skip('Locale does not apply grouping') # pragma: no cover
|
| 867 |
+
|
| 868 |
+
with mpl.rc_context({'axes.formatter.use_locale': True}):
|
| 869 |
+
tmp_form = mticker.ScalarFormatter()
|
| 870 |
+
assert tmp_form.get_useLocale()
|
| 871 |
+
|
| 872 |
+
tmp_form.create_dummy_axis()
|
| 873 |
+
tmp_form.axis.set_data_interval(0, 10)
|
| 874 |
+
tmp_form.set_locs([1, 2, 3])
|
| 875 |
+
assert sep in tmp_form(1e9)
|
| 876 |
+
|
| 877 |
+
@pytest.mark.parametrize(
|
| 878 |
+
'sci_type, scilimits, lim, orderOfMag, fewticks', scilimits_data)
|
| 879 |
+
def test_scilimits(self, sci_type, scilimits, lim, orderOfMag, fewticks):
|
| 880 |
+
tmp_form = mticker.ScalarFormatter()
|
| 881 |
+
tmp_form.set_scientific(sci_type)
|
| 882 |
+
tmp_form.set_powerlimits(scilimits)
|
| 883 |
+
fig, ax = plt.subplots()
|
| 884 |
+
ax.yaxis.set_major_formatter(tmp_form)
|
| 885 |
+
ax.set_ylim(*lim)
|
| 886 |
+
if fewticks:
|
| 887 |
+
ax.yaxis.set_major_locator(mticker.MaxNLocator(4))
|
| 888 |
+
|
| 889 |
+
tmp_form.set_locs(ax.yaxis.get_majorticklocs())
|
| 890 |
+
assert orderOfMag == tmp_form.orderOfMagnitude
|
| 891 |
+
|
| 892 |
+
@pytest.mark.parametrize('value, expected', format_data)
|
| 893 |
+
def test_format_data(self, value, expected):
|
| 894 |
+
mpl.rcParams['axes.unicode_minus'] = False
|
| 895 |
+
sf = mticker.ScalarFormatter()
|
| 896 |
+
assert sf.format_data(value) == expected
|
| 897 |
+
|
| 898 |
+
@pytest.mark.parametrize('data, expected', cursor_data)
|
| 899 |
+
def test_cursor_precision(self, data, expected):
|
| 900 |
+
fig, ax = plt.subplots()
|
| 901 |
+
ax.set_xlim(-1, 1) # Pointing precision of 0.001.
|
| 902 |
+
fmt = ax.xaxis.get_major_formatter().format_data_short
|
| 903 |
+
assert fmt(data) == expected
|
| 904 |
+
|
| 905 |
+
@pytest.mark.parametrize('data, expected', cursor_data)
|
| 906 |
+
def test_cursor_dummy_axis(self, data, expected):
|
| 907 |
+
# Issue #17624
|
| 908 |
+
sf = mticker.ScalarFormatter()
|
| 909 |
+
sf.create_dummy_axis()
|
| 910 |
+
sf.axis.set_view_interval(0, 10)
|
| 911 |
+
fmt = sf.format_data_short
|
| 912 |
+
assert fmt(data) == expected
|
| 913 |
+
assert sf.axis.get_tick_space() == 9
|
| 914 |
+
assert sf.axis.get_minpos() == 0
|
| 915 |
+
|
| 916 |
+
def test_mathtext_ticks(self):
|
| 917 |
+
mpl.rcParams.update({
|
| 918 |
+
'font.family': 'serif',
|
| 919 |
+
'font.serif': 'cmr10',
|
| 920 |
+
'axes.formatter.use_mathtext': False
|
| 921 |
+
})
|
| 922 |
+
|
| 923 |
+
if parse_version(pytest.__version__).major < 8:
|
| 924 |
+
with pytest.warns(UserWarning, match='cmr10 font should ideally'):
|
| 925 |
+
fig, ax = plt.subplots()
|
| 926 |
+
ax.set_xticks([-1, 0, 1])
|
| 927 |
+
fig.canvas.draw()
|
| 928 |
+
else:
|
| 929 |
+
with (pytest.warns(UserWarning, match="Glyph 8722"),
|
| 930 |
+
pytest.warns(UserWarning, match='cmr10 font should ideally')):
|
| 931 |
+
fig, ax = plt.subplots()
|
| 932 |
+
ax.set_xticks([-1, 0, 1])
|
| 933 |
+
fig.canvas.draw()
|
| 934 |
+
|
| 935 |
+
def test_cmr10_substitutions(self, caplog):
|
| 936 |
+
mpl.rcParams.update({
|
| 937 |
+
'font.family': 'cmr10',
|
| 938 |
+
'mathtext.fontset': 'cm',
|
| 939 |
+
'axes.formatter.use_mathtext': True,
|
| 940 |
+
})
|
| 941 |
+
|
| 942 |
+
# Test that it does not log a warning about missing glyphs.
|
| 943 |
+
with caplog.at_level(logging.WARNING, logger='matplotlib.mathtext'):
|
| 944 |
+
fig, ax = plt.subplots()
|
| 945 |
+
ax.plot([-0.03, 0.05], [40, 0.05])
|
| 946 |
+
ax.set_yscale('log')
|
| 947 |
+
yticks = [0.02, 0.3, 4, 50]
|
| 948 |
+
formatter = mticker.LogFormatterSciNotation()
|
| 949 |
+
ax.set_yticks(yticks, map(formatter, yticks))
|
| 950 |
+
fig.canvas.draw()
|
| 951 |
+
assert not caplog.text
|
| 952 |
+
|
| 953 |
+
def test_empty_locs(self):
|
| 954 |
+
sf = mticker.ScalarFormatter()
|
| 955 |
+
sf.set_locs([])
|
| 956 |
+
assert sf(0.5) == ''
|
| 957 |
+
|
| 958 |
+
|
| 959 |
+
class TestLogFormatterExponent:
|
| 960 |
+
param_data = [
|
| 961 |
+
(True, 4, np.arange(-3, 4.0), np.arange(-3, 4.0),
|
| 962 |
+
['-3', '-2', '-1', '0', '1', '2', '3']),
|
| 963 |
+
# With labelOnlyBase=False, non-integer powers should be nicely
|
| 964 |
+
# formatted.
|
| 965 |
+
(False, 10, np.array([0.1, 0.00001, np.pi, 0.2, -0.2, -0.00001]),
|
| 966 |
+
range(6), ['0.1', '1e-05', '3.14', '0.2', '-0.2', '-1e-05']),
|
| 967 |
+
(False, 50, np.array([3, 5, 12, 42], dtype=float), range(6),
|
| 968 |
+
['3', '5', '12', '42']),
|
| 969 |
+
]
|
| 970 |
+
|
| 971 |
+
base_data = [2.0, 5.0, 10.0, np.pi, np.e]
|
| 972 |
+
|
| 973 |
+
@pytest.mark.parametrize(
|
| 974 |
+
'labelOnlyBase, exponent, locs, positions, expected', param_data)
|
| 975 |
+
@pytest.mark.parametrize('base', base_data)
|
| 976 |
+
def test_basic(self, labelOnlyBase, base, exponent, locs, positions,
|
| 977 |
+
expected):
|
| 978 |
+
formatter = mticker.LogFormatterExponent(base=base,
|
| 979 |
+
labelOnlyBase=labelOnlyBase)
|
| 980 |
+
formatter.create_dummy_axis()
|
| 981 |
+
formatter.axis.set_view_interval(1, base**exponent)
|
| 982 |
+
vals = base**locs
|
| 983 |
+
labels = [formatter(x, pos) for (x, pos) in zip(vals, positions)]
|
| 984 |
+
expected = [label.replace('-', '\N{Minus Sign}') for label in expected]
|
| 985 |
+
assert labels == expected
|
| 986 |
+
|
| 987 |
+
def test_blank(self):
|
| 988 |
+
# Should be a blank string for non-integer powers if labelOnlyBase=True
|
| 989 |
+
formatter = mticker.LogFormatterExponent(base=10, labelOnlyBase=True)
|
| 990 |
+
formatter.create_dummy_axis()
|
| 991 |
+
formatter.axis.set_view_interval(1, 10)
|
| 992 |
+
assert formatter(10**0.1) == ''
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
class TestLogFormatterMathtext:
|
| 996 |
+
fmt = mticker.LogFormatterMathtext()
|
| 997 |
+
test_data = [
|
| 998 |
+
(0, 1, '$\\mathdefault{10^{0}}$'),
|
| 999 |
+
(0, 1e-2, '$\\mathdefault{10^{-2}}$'),
|
| 1000 |
+
(0, 1e2, '$\\mathdefault{10^{2}}$'),
|
| 1001 |
+
(3, 1, '$\\mathdefault{1}$'),
|
| 1002 |
+
(3, 1e-2, '$\\mathdefault{0.01}$'),
|
| 1003 |
+
(3, 1e2, '$\\mathdefault{100}$'),
|
| 1004 |
+
(3, 1e-3, '$\\mathdefault{10^{-3}}$'),
|
| 1005 |
+
(3, 1e3, '$\\mathdefault{10^{3}}$'),
|
| 1006 |
+
]
|
| 1007 |
+
|
| 1008 |
+
@pytest.mark.parametrize('min_exponent, value, expected', test_data)
|
| 1009 |
+
def test_min_exponent(self, min_exponent, value, expected):
|
| 1010 |
+
with mpl.rc_context({'axes.formatter.min_exponent': min_exponent}):
|
| 1011 |
+
assert self.fmt(value) == expected
|
| 1012 |
+
|
| 1013 |
+
|
| 1014 |
+
class TestLogFormatterSciNotation:
|
| 1015 |
+
test_data = [
|
| 1016 |
+
(2, 0.03125, '$\\mathdefault{2^{-5}}$'),
|
| 1017 |
+
(2, 1, '$\\mathdefault{2^{0}}$'),
|
| 1018 |
+
(2, 32, '$\\mathdefault{2^{5}}$'),
|
| 1019 |
+
(2, 0.0375, '$\\mathdefault{1.2\\times2^{-5}}$'),
|
| 1020 |
+
(2, 1.2, '$\\mathdefault{1.2\\times2^{0}}$'),
|
| 1021 |
+
(2, 38.4, '$\\mathdefault{1.2\\times2^{5}}$'),
|
| 1022 |
+
(10, -1, '$\\mathdefault{-10^{0}}$'),
|
| 1023 |
+
(10, 1e-05, '$\\mathdefault{10^{-5}}$'),
|
| 1024 |
+
(10, 1, '$\\mathdefault{10^{0}}$'),
|
| 1025 |
+
(10, 100000, '$\\mathdefault{10^{5}}$'),
|
| 1026 |
+
(10, 2e-05, '$\\mathdefault{2\\times10^{-5}}$'),
|
| 1027 |
+
(10, 2, '$\\mathdefault{2\\times10^{0}}$'),
|
| 1028 |
+
(10, 200000, '$\\mathdefault{2\\times10^{5}}$'),
|
| 1029 |
+
(10, 5e-05, '$\\mathdefault{5\\times10^{-5}}$'),
|
| 1030 |
+
(10, 5, '$\\mathdefault{5\\times10^{0}}$'),
|
| 1031 |
+
(10, 500000, '$\\mathdefault{5\\times10^{5}}$'),
|
| 1032 |
+
]
|
| 1033 |
+
|
| 1034 |
+
@mpl.style.context('default')
|
| 1035 |
+
@pytest.mark.parametrize('base, value, expected', test_data)
|
| 1036 |
+
def test_basic(self, base, value, expected):
|
| 1037 |
+
formatter = mticker.LogFormatterSciNotation(base=base)
|
| 1038 |
+
with mpl.rc_context({'text.usetex': False}):
|
| 1039 |
+
assert formatter(value) == expected
|
| 1040 |
+
|
| 1041 |
+
|
| 1042 |
+
class TestLogFormatter:
|
| 1043 |
+
pprint_data = [
|
| 1044 |
+
(3.141592654e-05, 0.001, '3.142e-5'),
|
| 1045 |
+
(0.0003141592654, 0.001, '3.142e-4'),
|
| 1046 |
+
(0.003141592654, 0.001, '3.142e-3'),
|
| 1047 |
+
(0.03141592654, 0.001, '3.142e-2'),
|
| 1048 |
+
(0.3141592654, 0.001, '3.142e-1'),
|
| 1049 |
+
(3.141592654, 0.001, '3.142'),
|
| 1050 |
+
(31.41592654, 0.001, '3.142e1'),
|
| 1051 |
+
(314.1592654, 0.001, '3.142e2'),
|
| 1052 |
+
(3141.592654, 0.001, '3.142e3'),
|
| 1053 |
+
(31415.92654, 0.001, '3.142e4'),
|
| 1054 |
+
(314159.2654, 0.001, '3.142e5'),
|
| 1055 |
+
(1e-05, 0.001, '1e-5'),
|
| 1056 |
+
(0.0001, 0.001, '1e-4'),
|
| 1057 |
+
(0.001, 0.001, '1e-3'),
|
| 1058 |
+
(0.01, 0.001, '1e-2'),
|
| 1059 |
+
(0.1, 0.001, '1e-1'),
|
| 1060 |
+
(1, 0.001, '1'),
|
| 1061 |
+
(10, 0.001, '10'),
|
| 1062 |
+
(100, 0.001, '100'),
|
| 1063 |
+
(1000, 0.001, '1000'),
|
| 1064 |
+
(10000, 0.001, '1e4'),
|
| 1065 |
+
(100000, 0.001, '1e5'),
|
| 1066 |
+
(3.141592654e-05, 0.015, '0'),
|
| 1067 |
+
(0.0003141592654, 0.015, '0'),
|
| 1068 |
+
(0.003141592654, 0.015, '0.003'),
|
| 1069 |
+
(0.03141592654, 0.015, '0.031'),
|
| 1070 |
+
(0.3141592654, 0.015, '0.314'),
|
| 1071 |
+
(3.141592654, 0.015, '3.142'),
|
| 1072 |
+
(31.41592654, 0.015, '31.416'),
|
| 1073 |
+
(314.1592654, 0.015, '314.159'),
|
| 1074 |
+
(3141.592654, 0.015, '3141.593'),
|
| 1075 |
+
(31415.92654, 0.015, '31415.927'),
|
| 1076 |
+
(314159.2654, 0.015, '314159.265'),
|
| 1077 |
+
(1e-05, 0.015, '0'),
|
| 1078 |
+
(0.0001, 0.015, '0'),
|
| 1079 |
+
(0.001, 0.015, '0.001'),
|
| 1080 |
+
(0.01, 0.015, '0.01'),
|
| 1081 |
+
(0.1, 0.015, '0.1'),
|
| 1082 |
+
(1, 0.015, '1'),
|
| 1083 |
+
(10, 0.015, '10'),
|
| 1084 |
+
(100, 0.015, '100'),
|
| 1085 |
+
(1000, 0.015, '1000'),
|
| 1086 |
+
(10000, 0.015, '10000'),
|
| 1087 |
+
(100000, 0.015, '100000'),
|
| 1088 |
+
(3.141592654e-05, 0.5, '0'),
|
| 1089 |
+
(0.0003141592654, 0.5, '0'),
|
| 1090 |
+
(0.003141592654, 0.5, '0.003'),
|
| 1091 |
+
(0.03141592654, 0.5, '0.031'),
|
| 1092 |
+
(0.3141592654, 0.5, '0.314'),
|
| 1093 |
+
(3.141592654, 0.5, '3.142'),
|
| 1094 |
+
(31.41592654, 0.5, '31.416'),
|
| 1095 |
+
(314.1592654, 0.5, '314.159'),
|
| 1096 |
+
(3141.592654, 0.5, '3141.593'),
|
| 1097 |
+
(31415.92654, 0.5, '31415.927'),
|
| 1098 |
+
(314159.2654, 0.5, '314159.265'),
|
| 1099 |
+
(1e-05, 0.5, '0'),
|
| 1100 |
+
(0.0001, 0.5, '0'),
|
| 1101 |
+
(0.001, 0.5, '0.001'),
|
| 1102 |
+
(0.01, 0.5, '0.01'),
|
| 1103 |
+
(0.1, 0.5, '0.1'),
|
| 1104 |
+
(1, 0.5, '1'),
|
| 1105 |
+
(10, 0.5, '10'),
|
| 1106 |
+
(100, 0.5, '100'),
|
| 1107 |
+
(1000, 0.5, '1000'),
|
| 1108 |
+
(10000, 0.5, '10000'),
|
| 1109 |
+
(100000, 0.5, '100000'),
|
| 1110 |
+
(3.141592654e-05, 5, '0'),
|
| 1111 |
+
(0.0003141592654, 5, '0'),
|
| 1112 |
+
(0.003141592654, 5, '0'),
|
| 1113 |
+
(0.03141592654, 5, '0.03'),
|
| 1114 |
+
(0.3141592654, 5, '0.31'),
|
| 1115 |
+
(3.141592654, 5, '3.14'),
|
| 1116 |
+
(31.41592654, 5, '31.42'),
|
| 1117 |
+
(314.1592654, 5, '314.16'),
|
| 1118 |
+
(3141.592654, 5, '3141.59'),
|
| 1119 |
+
(31415.92654, 5, '31415.93'),
|
| 1120 |
+
(314159.2654, 5, '314159.27'),
|
| 1121 |
+
(1e-05, 5, '0'),
|
| 1122 |
+
(0.0001, 5, '0'),
|
| 1123 |
+
(0.001, 5, '0'),
|
| 1124 |
+
(0.01, 5, '0.01'),
|
| 1125 |
+
(0.1, 5, '0.1'),
|
| 1126 |
+
(1, 5, '1'),
|
| 1127 |
+
(10, 5, '10'),
|
| 1128 |
+
(100, 5, '100'),
|
| 1129 |
+
(1000, 5, '1000'),
|
| 1130 |
+
(10000, 5, '10000'),
|
| 1131 |
+
(100000, 5, '100000'),
|
| 1132 |
+
(3.141592654e-05, 100, '0'),
|
| 1133 |
+
(0.0003141592654, 100, '0'),
|
| 1134 |
+
(0.003141592654, 100, '0'),
|
| 1135 |
+
(0.03141592654, 100, '0'),
|
| 1136 |
+
(0.3141592654, 100, '0.3'),
|
| 1137 |
+
(3.141592654, 100, '3.1'),
|
| 1138 |
+
(31.41592654, 100, '31.4'),
|
| 1139 |
+
(314.1592654, 100, '314.2'),
|
| 1140 |
+
(3141.592654, 100, '3141.6'),
|
| 1141 |
+
(31415.92654, 100, '31415.9'),
|
| 1142 |
+
(314159.2654, 100, '314159.3'),
|
| 1143 |
+
(1e-05, 100, '0'),
|
| 1144 |
+
(0.0001, 100, '0'),
|
| 1145 |
+
(0.001, 100, '0'),
|
| 1146 |
+
(0.01, 100, '0'),
|
| 1147 |
+
(0.1, 100, '0.1'),
|
| 1148 |
+
(1, 100, '1'),
|
| 1149 |
+
(10, 100, '10'),
|
| 1150 |
+
(100, 100, '100'),
|
| 1151 |
+
(1000, 100, '1000'),
|
| 1152 |
+
(10000, 100, '10000'),
|
| 1153 |
+
(100000, 100, '100000'),
|
| 1154 |
+
(3.141592654e-05, 1000000.0, '3.1e-5'),
|
| 1155 |
+
(0.0003141592654, 1000000.0, '3.1e-4'),
|
| 1156 |
+
(0.003141592654, 1000000.0, '3.1e-3'),
|
| 1157 |
+
(0.03141592654, 1000000.0, '3.1e-2'),
|
| 1158 |
+
(0.3141592654, 1000000.0, '3.1e-1'),
|
| 1159 |
+
(3.141592654, 1000000.0, '3.1'),
|
| 1160 |
+
(31.41592654, 1000000.0, '3.1e1'),
|
| 1161 |
+
(314.1592654, 1000000.0, '3.1e2'),
|
| 1162 |
+
(3141.592654, 1000000.0, '3.1e3'),
|
| 1163 |
+
(31415.92654, 1000000.0, '3.1e4'),
|
| 1164 |
+
(314159.2654, 1000000.0, '3.1e5'),
|
| 1165 |
+
(1e-05, 1000000.0, '1e-5'),
|
| 1166 |
+
(0.0001, 1000000.0, '1e-4'),
|
| 1167 |
+
(0.001, 1000000.0, '1e-3'),
|
| 1168 |
+
(0.01, 1000000.0, '1e-2'),
|
| 1169 |
+
(0.1, 1000000.0, '1e-1'),
|
| 1170 |
+
(1, 1000000.0, '1'),
|
| 1171 |
+
(10, 1000000.0, '10'),
|
| 1172 |
+
(100, 1000000.0, '100'),
|
| 1173 |
+
(1000, 1000000.0, '1000'),
|
| 1174 |
+
(10000, 1000000.0, '1e4'),
|
| 1175 |
+
(100000, 1000000.0, '1e5'),
|
| 1176 |
+
]
|
| 1177 |
+
|
| 1178 |
+
@pytest.mark.parametrize('value, domain, expected', pprint_data)
|
| 1179 |
+
def test_pprint(self, value, domain, expected):
|
| 1180 |
+
fmt = mticker.LogFormatter()
|
| 1181 |
+
label = fmt._pprint_val(value, domain)
|
| 1182 |
+
assert label == expected
|
| 1183 |
+
|
| 1184 |
+
@pytest.mark.parametrize('value, long, short', [
|
| 1185 |
+
(0.0, "0", "0"),
|
| 1186 |
+
(0, "0", "0"),
|
| 1187 |
+
(-1.0, "-10^0", "-1"),
|
| 1188 |
+
(2e-10, "2x10^-10", "2e-10"),
|
| 1189 |
+
(1e10, "10^10", "1e+10"),
|
| 1190 |
+
])
|
| 1191 |
+
def test_format_data(self, value, long, short):
|
| 1192 |
+
fig, ax = plt.subplots()
|
| 1193 |
+
ax.set_xscale('log')
|
| 1194 |
+
fmt = ax.xaxis.get_major_formatter()
|
| 1195 |
+
assert fmt.format_data(value) == long
|
| 1196 |
+
assert fmt.format_data_short(value) == short
|
| 1197 |
+
|
| 1198 |
+
def _sub_labels(self, axis, subs=()):
|
| 1199 |
+
"""Test whether locator marks subs to be labeled."""
|
| 1200 |
+
fmt = axis.get_minor_formatter()
|
| 1201 |
+
minor_tlocs = axis.get_minorticklocs()
|
| 1202 |
+
fmt.set_locs(minor_tlocs)
|
| 1203 |
+
coefs = minor_tlocs / 10**(np.floor(np.log10(minor_tlocs)))
|
| 1204 |
+
label_expected = [round(c) in subs for c in coefs]
|
| 1205 |
+
label_test = [fmt(x) != '' for x in minor_tlocs]
|
| 1206 |
+
assert label_test == label_expected
|
| 1207 |
+
|
| 1208 |
+
@mpl.style.context('default')
|
| 1209 |
+
def test_sublabel(self):
|
| 1210 |
+
# test label locator
|
| 1211 |
+
fig, ax = plt.subplots()
|
| 1212 |
+
ax.set_xscale('log')
|
| 1213 |
+
ax.xaxis.set_major_locator(mticker.LogLocator(base=10, subs=[]))
|
| 1214 |
+
ax.xaxis.set_minor_locator(mticker.LogLocator(base=10,
|
| 1215 |
+
subs=np.arange(2, 10)))
|
| 1216 |
+
ax.xaxis.set_major_formatter(mticker.LogFormatter(labelOnlyBase=True))
|
| 1217 |
+
ax.xaxis.set_minor_formatter(mticker.LogFormatter(labelOnlyBase=False))
|
| 1218 |
+
# axis range above 3 decades, only bases are labeled
|
| 1219 |
+
ax.set_xlim(1, 1e4)
|
| 1220 |
+
fmt = ax.xaxis.get_major_formatter()
|
| 1221 |
+
fmt.set_locs(ax.xaxis.get_majorticklocs())
|
| 1222 |
+
show_major_labels = [fmt(x) != ''
|
| 1223 |
+
for x in ax.xaxis.get_majorticklocs()]
|
| 1224 |
+
assert np.all(show_major_labels)
|
| 1225 |
+
self._sub_labels(ax.xaxis, subs=[])
|
| 1226 |
+
|
| 1227 |
+
# For the next two, if the numdec threshold in LogFormatter.set_locs
|
| 1228 |
+
# were 3, then the label sub would be 3 for 2-3 decades and (2, 5)
|
| 1229 |
+
# for 1-2 decades. With a threshold of 1, subs are not labeled.
|
| 1230 |
+
# axis range at 2 to 3 decades
|
| 1231 |
+
ax.set_xlim(1, 800)
|
| 1232 |
+
self._sub_labels(ax.xaxis, subs=[])
|
| 1233 |
+
|
| 1234 |
+
# axis range at 1 to 2 decades
|
| 1235 |
+
ax.set_xlim(1, 80)
|
| 1236 |
+
self._sub_labels(ax.xaxis, subs=[])
|
| 1237 |
+
|
| 1238 |
+
# axis range at 0.4 to 1 decades, label subs 2, 3, 4, 6
|
| 1239 |
+
ax.set_xlim(1, 8)
|
| 1240 |
+
self._sub_labels(ax.xaxis, subs=[2, 3, 4, 6])
|
| 1241 |
+
|
| 1242 |
+
# axis range at 0 to 0.4 decades, label all
|
| 1243 |
+
ax.set_xlim(0.5, 0.9)
|
| 1244 |
+
self._sub_labels(ax.xaxis, subs=np.arange(2, 10, dtype=int))
|
| 1245 |
+
|
| 1246 |
+
@pytest.mark.parametrize('val', [1, 10, 100, 1000])
|
| 1247 |
+
def test_LogFormatter_call(self, val):
|
| 1248 |
+
# test _num_to_string method used in __call__
|
| 1249 |
+
temp_lf = mticker.LogFormatter()
|
| 1250 |
+
temp_lf.create_dummy_axis()
|
| 1251 |
+
temp_lf.axis.set_view_interval(1, 10)
|
| 1252 |
+
assert temp_lf(val) == str(val)
|
| 1253 |
+
|
| 1254 |
+
@pytest.mark.parametrize('val', [1e-323, 2e-323, 10e-323, 11e-323])
|
| 1255 |
+
def test_LogFormatter_call_tiny(self, val):
|
| 1256 |
+
# test coeff computation in __call__
|
| 1257 |
+
temp_lf = mticker.LogFormatter()
|
| 1258 |
+
temp_lf.create_dummy_axis()
|
| 1259 |
+
temp_lf.axis.set_view_interval(1, 10)
|
| 1260 |
+
temp_lf(val)
|
| 1261 |
+
|
| 1262 |
+
|
| 1263 |
+
class TestLogitFormatter:
|
| 1264 |
+
@staticmethod
|
| 1265 |
+
def logit_deformatter(string):
|
| 1266 |
+
r"""
|
| 1267 |
+
Parser to convert string as r'$\mathdefault{1.41\cdot10^{-4}}$' in
|
| 1268 |
+
float 1.41e-4, as '0.5' or as r'$\mathdefault{\frac{1}{2}}$' in float
|
| 1269 |
+
0.5,
|
| 1270 |
+
"""
|
| 1271 |
+
match = re.match(
|
| 1272 |
+
r"[^\d]*"
|
| 1273 |
+
r"(?P<comp>1-)?"
|
| 1274 |
+
r"(?P<mant>\d*\.?\d*)?"
|
| 1275 |
+
r"(?:\\cdot)?"
|
| 1276 |
+
r"(?:10\^\{(?P<expo>-?\d*)})?"
|
| 1277 |
+
r"[^\d]*$",
|
| 1278 |
+
string,
|
| 1279 |
+
)
|
| 1280 |
+
if match:
|
| 1281 |
+
comp = match["comp"] is not None
|
| 1282 |
+
mantissa = float(match["mant"]) if match["mant"] else 1
|
| 1283 |
+
expo = int(match["expo"]) if match["expo"] is not None else 0
|
| 1284 |
+
value = mantissa * 10 ** expo
|
| 1285 |
+
if match["mant"] or match["expo"] is not None:
|
| 1286 |
+
if comp:
|
| 1287 |
+
return 1 - value
|
| 1288 |
+
return value
|
| 1289 |
+
match = re.match(
|
| 1290 |
+
r"[^\d]*\\frac\{(?P<num>\d+)\}\{(?P<deno>\d+)\}[^\d]*$", string
|
| 1291 |
+
)
|
| 1292 |
+
if match:
|
| 1293 |
+
num, deno = float(match["num"]), float(match["deno"])
|
| 1294 |
+
return num / deno
|
| 1295 |
+
raise ValueError("Not formatted by LogitFormatter")
|
| 1296 |
+
|
| 1297 |
+
@pytest.mark.parametrize(
|
| 1298 |
+
"fx, x",
|
| 1299 |
+
[
|
| 1300 |
+
(r"STUFF0.41OTHERSTUFF", 0.41),
|
| 1301 |
+
(r"STUFF1.41\cdot10^{-2}OTHERSTUFF", 1.41e-2),
|
| 1302 |
+
(r"STUFF1-0.41OTHERSTUFF", 1 - 0.41),
|
| 1303 |
+
(r"STUFF1-1.41\cdot10^{-2}OTHERSTUFF", 1 - 1.41e-2),
|
| 1304 |
+
(r"STUFF", None),
|
| 1305 |
+
(r"STUFF12.4e-3OTHERSTUFF", None),
|
| 1306 |
+
],
|
| 1307 |
+
)
|
| 1308 |
+
def test_logit_deformater(self, fx, x):
|
| 1309 |
+
if x is None:
|
| 1310 |
+
with pytest.raises(ValueError):
|
| 1311 |
+
TestLogitFormatter.logit_deformatter(fx)
|
| 1312 |
+
else:
|
| 1313 |
+
y = TestLogitFormatter.logit_deformatter(fx)
|
| 1314 |
+
assert _LogitHelper.isclose(x, y)
|
| 1315 |
+
|
| 1316 |
+
decade_test = sorted(
|
| 1317 |
+
[10 ** (-i) for i in range(1, 10)]
|
| 1318 |
+
+ [1 - 10 ** (-i) for i in range(1, 10)]
|
| 1319 |
+
+ [1 / 2]
|
| 1320 |
+
)
|
| 1321 |
+
|
| 1322 |
+
@pytest.mark.parametrize("x", decade_test)
|
| 1323 |
+
def test_basic(self, x):
|
| 1324 |
+
"""
|
| 1325 |
+
Test the formatted value correspond to the value for ideal ticks in
|
| 1326 |
+
logit space.
|
| 1327 |
+
"""
|
| 1328 |
+
formatter = mticker.LogitFormatter(use_overline=False)
|
| 1329 |
+
formatter.set_locs(self.decade_test)
|
| 1330 |
+
s = formatter(x)
|
| 1331 |
+
x2 = TestLogitFormatter.logit_deformatter(s)
|
| 1332 |
+
assert _LogitHelper.isclose(x, x2)
|
| 1333 |
+
|
| 1334 |
+
@pytest.mark.parametrize("x", (-1, -0.5, -0.1, 1.1, 1.5, 2))
|
| 1335 |
+
def test_invalid(self, x):
|
| 1336 |
+
"""
|
| 1337 |
+
Test that invalid value are formatted with empty string without
|
| 1338 |
+
raising exception.
|
| 1339 |
+
"""
|
| 1340 |
+
formatter = mticker.LogitFormatter(use_overline=False)
|
| 1341 |
+
formatter.set_locs(self.decade_test)
|
| 1342 |
+
s = formatter(x)
|
| 1343 |
+
assert s == ""
|
| 1344 |
+
|
| 1345 |
+
@pytest.mark.parametrize("x", 1 / (1 + np.exp(-np.linspace(-7, 7, 10))))
|
| 1346 |
+
def test_variablelength(self, x):
|
| 1347 |
+
"""
|
| 1348 |
+
The format length should change depending on the neighbor labels.
|
| 1349 |
+
"""
|
| 1350 |
+
formatter = mticker.LogitFormatter(use_overline=False)
|
| 1351 |
+
for N in (10, 20, 50, 100, 200, 1000, 2000, 5000, 10000):
|
| 1352 |
+
if x + 1 / N < 1:
|
| 1353 |
+
formatter.set_locs([x - 1 / N, x, x + 1 / N])
|
| 1354 |
+
sx = formatter(x)
|
| 1355 |
+
sx1 = formatter(x + 1 / N)
|
| 1356 |
+
d = (
|
| 1357 |
+
TestLogitFormatter.logit_deformatter(sx1)
|
| 1358 |
+
- TestLogitFormatter.logit_deformatter(sx)
|
| 1359 |
+
)
|
| 1360 |
+
assert 0 < d < 2 / N
|
| 1361 |
+
|
| 1362 |
+
lims_minor_major = [
|
| 1363 |
+
(True, (5e-8, 1 - 5e-8), ((25, False), (75, False))),
|
| 1364 |
+
(True, (5e-5, 1 - 5e-5), ((25, False), (75, True))),
|
| 1365 |
+
(True, (5e-2, 1 - 5e-2), ((25, True), (75, True))),
|
| 1366 |
+
(False, (0.75, 0.76, 0.77), ((7, True), (25, True), (75, True))),
|
| 1367 |
+
]
|
| 1368 |
+
|
| 1369 |
+
@pytest.mark.parametrize("method, lims, cases", lims_minor_major)
|
| 1370 |
+
def test_minor_vs_major(self, method, lims, cases):
|
| 1371 |
+
"""
|
| 1372 |
+
Test minor/major displays.
|
| 1373 |
+
"""
|
| 1374 |
+
|
| 1375 |
+
if method:
|
| 1376 |
+
min_loc = mticker.LogitLocator(minor=True)
|
| 1377 |
+
ticks = min_loc.tick_values(*lims)
|
| 1378 |
+
else:
|
| 1379 |
+
ticks = np.array(lims)
|
| 1380 |
+
min_form = mticker.LogitFormatter(minor=True)
|
| 1381 |
+
for threshold, has_minor in cases:
|
| 1382 |
+
min_form.set_minor_threshold(threshold)
|
| 1383 |
+
formatted = min_form.format_ticks(ticks)
|
| 1384 |
+
labelled = [f for f in formatted if len(f) > 0]
|
| 1385 |
+
if has_minor:
|
| 1386 |
+
assert len(labelled) > 0, (threshold, has_minor)
|
| 1387 |
+
else:
|
| 1388 |
+
assert len(labelled) == 0, (threshold, has_minor)
|
| 1389 |
+
|
| 1390 |
+
def test_minor_number(self):
|
| 1391 |
+
"""
|
| 1392 |
+
Test the parameter minor_number
|
| 1393 |
+
"""
|
| 1394 |
+
min_loc = mticker.LogitLocator(minor=True)
|
| 1395 |
+
min_form = mticker.LogitFormatter(minor=True)
|
| 1396 |
+
ticks = min_loc.tick_values(5e-2, 1 - 5e-2)
|
| 1397 |
+
for minor_number in (2, 4, 8, 16):
|
| 1398 |
+
min_form.set_minor_number(minor_number)
|
| 1399 |
+
formatted = min_form.format_ticks(ticks)
|
| 1400 |
+
labelled = [f for f in formatted if len(f) > 0]
|
| 1401 |
+
assert len(labelled) == minor_number
|
| 1402 |
+
|
| 1403 |
+
def test_use_overline(self):
|
| 1404 |
+
"""
|
| 1405 |
+
Test the parameter use_overline
|
| 1406 |
+
"""
|
| 1407 |
+
x = 1 - 1e-2
|
| 1408 |
+
fx1 = r"$\mathdefault{1-10^{-2}}$"
|
| 1409 |
+
fx2 = r"$\mathdefault{\overline{10^{-2}}}$"
|
| 1410 |
+
form = mticker.LogitFormatter(use_overline=False)
|
| 1411 |
+
assert form(x) == fx1
|
| 1412 |
+
form.use_overline(True)
|
| 1413 |
+
assert form(x) == fx2
|
| 1414 |
+
form.use_overline(False)
|
| 1415 |
+
assert form(x) == fx1
|
| 1416 |
+
|
| 1417 |
+
def test_one_half(self):
|
| 1418 |
+
"""
|
| 1419 |
+
Test the parameter one_half
|
| 1420 |
+
"""
|
| 1421 |
+
form = mticker.LogitFormatter()
|
| 1422 |
+
assert r"\frac{1}{2}" in form(1/2)
|
| 1423 |
+
form.set_one_half("1/2")
|
| 1424 |
+
assert "1/2" in form(1/2)
|
| 1425 |
+
form.set_one_half("one half")
|
| 1426 |
+
assert "one half" in form(1/2)
|
| 1427 |
+
|
| 1428 |
+
@pytest.mark.parametrize("N", (100, 253, 754))
|
| 1429 |
+
def test_format_data_short(self, N):
|
| 1430 |
+
locs = np.linspace(0, 1, N)[1:-1]
|
| 1431 |
+
form = mticker.LogitFormatter()
|
| 1432 |
+
for x in locs:
|
| 1433 |
+
fx = form.format_data_short(x)
|
| 1434 |
+
if fx.startswith("1-"):
|
| 1435 |
+
x2 = 1 - float(fx[2:])
|
| 1436 |
+
else:
|
| 1437 |
+
x2 = float(fx)
|
| 1438 |
+
assert abs(x - x2) < 1 / N
|
| 1439 |
+
|
| 1440 |
+
|
| 1441 |
+
class TestFormatStrFormatter:
|
| 1442 |
+
def test_basic(self):
|
| 1443 |
+
# test % style formatter
|
| 1444 |
+
tmp_form = mticker.FormatStrFormatter('%05d')
|
| 1445 |
+
assert '00002' == tmp_form(2)
|
| 1446 |
+
|
| 1447 |
+
|
| 1448 |
+
class TestStrMethodFormatter:
|
| 1449 |
+
test_data = [
|
| 1450 |
+
('{x:05d}', (2,), False, '00002'),
|
| 1451 |
+
('{x:05d}', (2,), True, '00002'),
|
| 1452 |
+
('{x:05d}', (-2,), False, '-0002'),
|
| 1453 |
+
('{x:05d}', (-2,), True, '\N{MINUS SIGN}0002'),
|
| 1454 |
+
('{x:03d}-{pos:02d}', (2, 1), False, '002-01'),
|
| 1455 |
+
('{x:03d}-{pos:02d}', (2, 1), True, '002-01'),
|
| 1456 |
+
('{x:03d}-{pos:02d}', (-2, 1), False, '-02-01'),
|
| 1457 |
+
('{x:03d}-{pos:02d}', (-2, 1), True, '\N{MINUS SIGN}02-01'),
|
| 1458 |
+
]
|
| 1459 |
+
|
| 1460 |
+
@pytest.mark.parametrize('format, input, unicode_minus, expected', test_data)
|
| 1461 |
+
def test_basic(self, format, input, unicode_minus, expected):
|
| 1462 |
+
with mpl.rc_context({"axes.unicode_minus": unicode_minus}):
|
| 1463 |
+
fmt = mticker.StrMethodFormatter(format)
|
| 1464 |
+
assert fmt(*input) == expected
|
| 1465 |
+
|
| 1466 |
+
|
| 1467 |
+
class TestEngFormatter:
|
| 1468 |
+
# (unicode_minus, input, expected) where ''expected'' corresponds to the
|
| 1469 |
+
# outputs respectively returned when (places=None, places=0, places=2)
|
| 1470 |
+
# unicode_minus is a boolean value for the rcParam['axes.unicode_minus']
|
| 1471 |
+
raw_format_data = [
|
| 1472 |
+
(False, -1234.56789, ('-1.23457 k', '-1 k', '-1.23 k')),
|
| 1473 |
+
(True, -1234.56789, ('\N{MINUS SIGN}1.23457 k', '\N{MINUS SIGN}1 k',
|
| 1474 |
+
'\N{MINUS SIGN}1.23 k')),
|
| 1475 |
+
(False, -1.23456789, ('-1.23457', '-1', '-1.23')),
|
| 1476 |
+
(True, -1.23456789, ('\N{MINUS SIGN}1.23457', '\N{MINUS SIGN}1',
|
| 1477 |
+
'\N{MINUS SIGN}1.23')),
|
| 1478 |
+
(False, -0.123456789, ('-123.457 m', '-123 m', '-123.46 m')),
|
| 1479 |
+
(True, -0.123456789, ('\N{MINUS SIGN}123.457 m', '\N{MINUS SIGN}123 m',
|
| 1480 |
+
'\N{MINUS SIGN}123.46 m')),
|
| 1481 |
+
(False, -0.00123456789, ('-1.23457 m', '-1 m', '-1.23 m')),
|
| 1482 |
+
(True, -0.00123456789, ('\N{MINUS SIGN}1.23457 m', '\N{MINUS SIGN}1 m',
|
| 1483 |
+
'\N{MINUS SIGN}1.23 m')),
|
| 1484 |
+
(True, -0.0, ('0', '0', '0.00')),
|
| 1485 |
+
(True, -0, ('0', '0', '0.00')),
|
| 1486 |
+
(True, 0, ('0', '0', '0.00')),
|
| 1487 |
+
(True, 1.23456789e-6, ('1.23457 µ', '1 µ', '1.23 µ')),
|
| 1488 |
+
(True, 0.123456789, ('123.457 m', '123 m', '123.46 m')),
|
| 1489 |
+
(True, 0.1, ('100 m', '100 m', '100.00 m')),
|
| 1490 |
+
(True, 1, ('1', '1', '1.00')),
|
| 1491 |
+
(True, 1.23456789, ('1.23457', '1', '1.23')),
|
| 1492 |
+
# places=0: corner-case rounding
|
| 1493 |
+
(True, 999.9, ('999.9', '1 k', '999.90')),
|
| 1494 |
+
# corner-case rounding for all
|
| 1495 |
+
(True, 999.9999, ('1 k', '1 k', '1.00 k')),
|
| 1496 |
+
# negative corner-case
|
| 1497 |
+
(False, -999.9999, ('-1 k', '-1 k', '-1.00 k')),
|
| 1498 |
+
(True, -999.9999, ('\N{MINUS SIGN}1 k', '\N{MINUS SIGN}1 k',
|
| 1499 |
+
'\N{MINUS SIGN}1.00 k')),
|
| 1500 |
+
(True, 1000, ('1 k', '1 k', '1.00 k')),
|
| 1501 |
+
(True, 1001, ('1.001 k', '1 k', '1.00 k')),
|
| 1502 |
+
(True, 100001, ('100.001 k', '100 k', '100.00 k')),
|
| 1503 |
+
(True, 987654.321, ('987.654 k', '988 k', '987.65 k')),
|
| 1504 |
+
# OoR value (> 1000 Q)
|
| 1505 |
+
(True, 1.23e33, ('1230 Q', '1230 Q', '1230.00 Q'))
|
| 1506 |
+
]
|
| 1507 |
+
|
| 1508 |
+
@pytest.mark.parametrize('unicode_minus, input, expected', raw_format_data)
|
| 1509 |
+
def test_params(self, unicode_minus, input, expected):
|
| 1510 |
+
"""
|
| 1511 |
+
Test the formatting of EngFormatter for various values of the 'places'
|
| 1512 |
+
argument, in several cases:
|
| 1513 |
+
|
| 1514 |
+
0. without a unit symbol but with a (default) space separator;
|
| 1515 |
+
1. with both a unit symbol and a (default) space separator;
|
| 1516 |
+
2. with both a unit symbol and some non default separators;
|
| 1517 |
+
3. without a unit symbol but with some non default separators.
|
| 1518 |
+
|
| 1519 |
+
Note that cases 2. and 3. are looped over several separator strings.
|
| 1520 |
+
"""
|
| 1521 |
+
|
| 1522 |
+
plt.rcParams['axes.unicode_minus'] = unicode_minus
|
| 1523 |
+
UNIT = 's' # seconds
|
| 1524 |
+
DIGITS = '0123456789' # %timeit showed 10-20% faster search than set
|
| 1525 |
+
|
| 1526 |
+
# Case 0: unit='' (default) and sep=' ' (default).
|
| 1527 |
+
# 'expected' already corresponds to this reference case.
|
| 1528 |
+
exp_outputs = expected
|
| 1529 |
+
formatters = (
|
| 1530 |
+
mticker.EngFormatter(), # places=None (default)
|
| 1531 |
+
mticker.EngFormatter(places=0),
|
| 1532 |
+
mticker.EngFormatter(places=2)
|
| 1533 |
+
)
|
| 1534 |
+
for _formatter, _exp_output in zip(formatters, exp_outputs):
|
| 1535 |
+
assert _formatter(input) == _exp_output
|
| 1536 |
+
|
| 1537 |
+
# Case 1: unit=UNIT and sep=' ' (default).
|
| 1538 |
+
# Append a unit symbol to the reference case.
|
| 1539 |
+
# Beware of the values in [1, 1000), where there is no prefix!
|
| 1540 |
+
exp_outputs = (_s + " " + UNIT if _s[-1] in DIGITS # case w/o prefix
|
| 1541 |
+
else _s + UNIT for _s in expected)
|
| 1542 |
+
formatters = (
|
| 1543 |
+
mticker.EngFormatter(unit=UNIT), # places=None (default)
|
| 1544 |
+
mticker.EngFormatter(unit=UNIT, places=0),
|
| 1545 |
+
mticker.EngFormatter(unit=UNIT, places=2)
|
| 1546 |
+
)
|
| 1547 |
+
for _formatter, _exp_output in zip(formatters, exp_outputs):
|
| 1548 |
+
assert _formatter(input) == _exp_output
|
| 1549 |
+
|
| 1550 |
+
# Test several non default separators: no separator, a narrow
|
| 1551 |
+
# no-break space (Unicode character) and an extravagant string.
|
| 1552 |
+
for _sep in ("", "\N{NARROW NO-BREAK SPACE}", "@_@"):
|
| 1553 |
+
# Case 2: unit=UNIT and sep=_sep.
|
| 1554 |
+
# Replace the default space separator from the reference case
|
| 1555 |
+
# with the tested one `_sep` and append a unit symbol to it.
|
| 1556 |
+
exp_outputs = (_s + _sep + UNIT if _s[-1] in DIGITS # no prefix
|
| 1557 |
+
else _s.replace(" ", _sep) + UNIT
|
| 1558 |
+
for _s in expected)
|
| 1559 |
+
formatters = (
|
| 1560 |
+
mticker.EngFormatter(unit=UNIT, sep=_sep), # places=None
|
| 1561 |
+
mticker.EngFormatter(unit=UNIT, places=0, sep=_sep),
|
| 1562 |
+
mticker.EngFormatter(unit=UNIT, places=2, sep=_sep)
|
| 1563 |
+
)
|
| 1564 |
+
for _formatter, _exp_output in zip(formatters, exp_outputs):
|
| 1565 |
+
assert _formatter(input) == _exp_output
|
| 1566 |
+
|
| 1567 |
+
# Case 3: unit='' (default) and sep=_sep.
|
| 1568 |
+
# Replace the default space separator from the reference case
|
| 1569 |
+
# with the tested one `_sep`. Reference case is already unitless.
|
| 1570 |
+
exp_outputs = (_s.replace(" ", _sep) for _s in expected)
|
| 1571 |
+
formatters = (
|
| 1572 |
+
mticker.EngFormatter(sep=_sep), # places=None (default)
|
| 1573 |
+
mticker.EngFormatter(places=0, sep=_sep),
|
| 1574 |
+
mticker.EngFormatter(places=2, sep=_sep)
|
| 1575 |
+
)
|
| 1576 |
+
for _formatter, _exp_output in zip(formatters, exp_outputs):
|
| 1577 |
+
assert _formatter(input) == _exp_output
|
| 1578 |
+
|
| 1579 |
+
|
| 1580 |
+
def test_engformatter_usetex_useMathText():
|
| 1581 |
+
fig, ax = plt.subplots()
|
| 1582 |
+
ax.plot([0, 500, 1000], [0, 500, 1000])
|
| 1583 |
+
ax.set_xticks([0, 500, 1000])
|
| 1584 |
+
for formatter in (mticker.EngFormatter(usetex=True),
|
| 1585 |
+
mticker.EngFormatter(useMathText=True)):
|
| 1586 |
+
ax.xaxis.set_major_formatter(formatter)
|
| 1587 |
+
fig.canvas.draw()
|
| 1588 |
+
x_tick_label_text = [labl.get_text() for labl in ax.get_xticklabels()]
|
| 1589 |
+
# Checking if the dollar `$` signs have been inserted around numbers
|
| 1590 |
+
# in tick labels.
|
| 1591 |
+
assert x_tick_label_text == ['$0$', '$500$', '$1$ k']
|
| 1592 |
+
|
| 1593 |
+
|
| 1594 |
+
@pytest.mark.parametrize(
|
| 1595 |
+
'data_offset, noise, oom_center_desired, oom_noise_desired', [
|
| 1596 |
+
(271_490_000_000.0, 10, 9, 0),
|
| 1597 |
+
(27_149_000_000_000.0, 10_000_000, 12, 6),
|
| 1598 |
+
(27.149, 0.01, 0, -3),
|
| 1599 |
+
(2_714.9, 0.01, 3, -3),
|
| 1600 |
+
(271_490.0, 0.001, 3, -3),
|
| 1601 |
+
(271.49, 0.001, 0, -3),
|
| 1602 |
+
# The following sets of parameters demonstrates that when
|
| 1603 |
+
# oom(data_offset)-1 and oom(noise)-2 equal a standard 3*N oom, we get
|
| 1604 |
+
# that oom_noise_desired < oom(noise)
|
| 1605 |
+
(27_149_000_000.0, 100, 9, +3),
|
| 1606 |
+
(27.149, 1e-07, 0, -6),
|
| 1607 |
+
(271.49, 0.0001, 0, -3),
|
| 1608 |
+
(27.149, 0.0001, 0, -3),
|
| 1609 |
+
# Tests where oom(data_offset) <= oom(noise), those are probably
|
| 1610 |
+
# covered by the part where formatter.offset != 0
|
| 1611 |
+
(27_149.0, 10_000, 0, 3),
|
| 1612 |
+
(27.149, 10_000, 0, 3),
|
| 1613 |
+
(27.149, 1_000, 0, 3),
|
| 1614 |
+
(27.149, 100, 0, 0),
|
| 1615 |
+
(27.149, 10, 0, 0),
|
| 1616 |
+
]
|
| 1617 |
+
)
|
| 1618 |
+
def test_engformatter_offset_oom(
|
| 1619 |
+
data_offset,
|
| 1620 |
+
noise,
|
| 1621 |
+
oom_center_desired,
|
| 1622 |
+
oom_noise_desired
|
| 1623 |
+
):
|
| 1624 |
+
UNIT = "eV"
|
| 1625 |
+
fig, ax = plt.subplots()
|
| 1626 |
+
ydata = data_offset + np.arange(-5, 7, dtype=float)*noise
|
| 1627 |
+
ax.plot(ydata)
|
| 1628 |
+
formatter = mticker.EngFormatter(useOffset=True, unit=UNIT)
|
| 1629 |
+
# So that offset strings will always have the same size
|
| 1630 |
+
formatter.ENG_PREFIXES[0] = "_"
|
| 1631 |
+
ax.yaxis.set_major_formatter(formatter)
|
| 1632 |
+
fig.canvas.draw()
|
| 1633 |
+
offset_got = formatter.get_offset()
|
| 1634 |
+
ticks_got = [labl.get_text() for labl in ax.get_yticklabels()]
|
| 1635 |
+
# Predicting whether offset should be 0 or not is essentially testing
|
| 1636 |
+
# ScalarFormatter._compute_offset . This function is pretty complex and it
|
| 1637 |
+
# would be nice to test it, but this is out of scope for this test which
|
| 1638 |
+
# only makes sure that offset text and the ticks gets the correct unit
|
| 1639 |
+
# prefixes and the ticks.
|
| 1640 |
+
if formatter.offset:
|
| 1641 |
+
prefix_noise_got = offset_got[2]
|
| 1642 |
+
prefix_noise_desired = formatter.ENG_PREFIXES[oom_noise_desired]
|
| 1643 |
+
prefix_center_got = offset_got[-1-len(UNIT)]
|
| 1644 |
+
prefix_center_desired = formatter.ENG_PREFIXES[oom_center_desired]
|
| 1645 |
+
assert prefix_noise_desired == prefix_noise_got
|
| 1646 |
+
assert prefix_center_desired == prefix_center_got
|
| 1647 |
+
# Make sure the ticks didn't get the UNIT
|
| 1648 |
+
for tick in ticks_got:
|
| 1649 |
+
assert UNIT not in tick
|
| 1650 |
+
else:
|
| 1651 |
+
assert oom_center_desired == 0
|
| 1652 |
+
assert offset_got == ""
|
| 1653 |
+
# Make sure the ticks contain now the prefixes
|
| 1654 |
+
for tick in ticks_got:
|
| 1655 |
+
# 0 is zero on all orders of magnitudes, no matter what is
|
| 1656 |
+
# oom_noise_desired
|
| 1657 |
+
prefix_idx = 0 if tick[0] == "0" else oom_noise_desired
|
| 1658 |
+
assert tick.endswith(formatter.ENG_PREFIXES[prefix_idx] + UNIT)
|
| 1659 |
+
|
| 1660 |
+
|
| 1661 |
+
class TestPercentFormatter:
|
| 1662 |
+
percent_data = [
|
| 1663 |
+
# Check explicitly set decimals over different intervals and values
|
| 1664 |
+
(100, 0, '%', 120, 100, '120%'),
|
| 1665 |
+
(100, 0, '%', 100, 90, '100%'),
|
| 1666 |
+
(100, 0, '%', 90, 50, '90%'),
|
| 1667 |
+
(100, 0, '%', -1.7, 40, '-2%'),
|
| 1668 |
+
(100, 1, '%', 90.0, 100, '90.0%'),
|
| 1669 |
+
(100, 1, '%', 80.1, 90, '80.1%'),
|
| 1670 |
+
(100, 1, '%', 70.23, 50, '70.2%'),
|
| 1671 |
+
# 60.554 instead of 60.55: see https://bugs.python.org/issue5118
|
| 1672 |
+
(100, 1, '%', -60.554, 40, '-60.6%'),
|
| 1673 |
+
# Check auto decimals over different intervals and values
|
| 1674 |
+
(100, None, '%', 95, 1, '95.00%'),
|
| 1675 |
+
(1.0, None, '%', 3, 6, '300%'),
|
| 1676 |
+
(17.0, None, '%', 1, 8.5, '6%'),
|
| 1677 |
+
(17.0, None, '%', 1, 8.4, '5.9%'),
|
| 1678 |
+
(5, None, '%', -100, 0.000001, '-2000.00000%'),
|
| 1679 |
+
# Check percent symbol
|
| 1680 |
+
(1.0, 2, None, 1.2, 100, '120.00'),
|
| 1681 |
+
(75, 3, '', 50, 100, '66.667'),
|
| 1682 |
+
(42, None, '^^Foobar$$', 21, 12, '50.0^^Foobar$$'),
|
| 1683 |
+
]
|
| 1684 |
+
|
| 1685 |
+
percent_ids = [
|
| 1686 |
+
# Check explicitly set decimals over different intervals and values
|
| 1687 |
+
'decimals=0, x>100%',
|
| 1688 |
+
'decimals=0, x=100%',
|
| 1689 |
+
'decimals=0, x<100%',
|
| 1690 |
+
'decimals=0, x<0%',
|
| 1691 |
+
'decimals=1, x>100%',
|
| 1692 |
+
'decimals=1, x=100%',
|
| 1693 |
+
'decimals=1, x<100%',
|
| 1694 |
+
'decimals=1, x<0%',
|
| 1695 |
+
# Check auto decimals over different intervals and values
|
| 1696 |
+
'autodecimal, x<100%, display_range=1',
|
| 1697 |
+
'autodecimal, x>100%, display_range=6 (custom xmax test)',
|
| 1698 |
+
'autodecimal, x<100%, display_range=8.5 (autodecimal test 1)',
|
| 1699 |
+
'autodecimal, x<100%, display_range=8.4 (autodecimal test 2)',
|
| 1700 |
+
'autodecimal, x<-100%, display_range=1e-6 (tiny display range)',
|
| 1701 |
+
# Check percent symbol
|
| 1702 |
+
'None as percent symbol',
|
| 1703 |
+
'Empty percent symbol',
|
| 1704 |
+
'Custom percent symbol',
|
| 1705 |
+
]
|
| 1706 |
+
|
| 1707 |
+
latex_data = [
|
| 1708 |
+
(False, False, r'50\{t}%'),
|
| 1709 |
+
(False, True, r'50\\\{t\}\%'),
|
| 1710 |
+
(True, False, r'50\{t}%'),
|
| 1711 |
+
(True, True, r'50\{t}%'),
|
| 1712 |
+
]
|
| 1713 |
+
|
| 1714 |
+
@pytest.mark.parametrize(
|
| 1715 |
+
'xmax, decimals, symbol, x, display_range, expected',
|
| 1716 |
+
percent_data, ids=percent_ids)
|
| 1717 |
+
def test_basic(self, xmax, decimals, symbol,
|
| 1718 |
+
x, display_range, expected):
|
| 1719 |
+
formatter = mticker.PercentFormatter(xmax, decimals, symbol)
|
| 1720 |
+
with mpl.rc_context(rc={'text.usetex': False}):
|
| 1721 |
+
assert formatter.format_pct(x, display_range) == expected
|
| 1722 |
+
|
| 1723 |
+
@pytest.mark.parametrize('is_latex, usetex, expected', latex_data)
|
| 1724 |
+
def test_latex(self, is_latex, usetex, expected):
|
| 1725 |
+
fmt = mticker.PercentFormatter(symbol='\\{t}%', is_latex=is_latex)
|
| 1726 |
+
with mpl.rc_context(rc={'text.usetex': usetex}):
|
| 1727 |
+
assert fmt.format_pct(50, 100) == expected
|
| 1728 |
+
|
| 1729 |
+
|
| 1730 |
+
def _impl_locale_comma():
|
| 1731 |
+
try:
|
| 1732 |
+
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
|
| 1733 |
+
except locale.Error:
|
| 1734 |
+
print('SKIP: Locale de_DE.UTF-8 is not supported on this machine')
|
| 1735 |
+
return
|
| 1736 |
+
ticks = mticker.ScalarFormatter(useMathText=True, useLocale=True)
|
| 1737 |
+
fmt = '$\\mathdefault{%1.1f}$'
|
| 1738 |
+
x = ticks._format_maybe_minus_and_locale(fmt, 0.5)
|
| 1739 |
+
assert x == '$\\mathdefault{0{,}5}$'
|
| 1740 |
+
# Do not change , in the format string
|
| 1741 |
+
fmt = ',$\\mathdefault{,%1.1f},$'
|
| 1742 |
+
x = ticks._format_maybe_minus_and_locale(fmt, 0.5)
|
| 1743 |
+
assert x == ',$\\mathdefault{,0{,}5},$'
|
| 1744 |
+
# Make sure no brackets are added if not using math text
|
| 1745 |
+
ticks = mticker.ScalarFormatter(useMathText=False, useLocale=True)
|
| 1746 |
+
fmt = '%1.1f'
|
| 1747 |
+
x = ticks._format_maybe_minus_and_locale(fmt, 0.5)
|
| 1748 |
+
assert x == '0,5'
|
| 1749 |
+
|
| 1750 |
+
|
| 1751 |
+
def test_locale_comma():
|
| 1752 |
+
# On some systems/pytest versions, `pytest.skip` in an exception handler
|
| 1753 |
+
# does not skip, but is treated as an exception, so directly running this
|
| 1754 |
+
# test can incorrectly fail instead of skip.
|
| 1755 |
+
# Instead, run this test in a subprocess, which avoids the problem, and the
|
| 1756 |
+
# need to fix the locale after.
|
| 1757 |
+
proc = mpl.testing.subprocess_run_helper(_impl_locale_comma, timeout=60,
|
| 1758 |
+
extra_env={'MPLBACKEND': 'Agg'})
|
| 1759 |
+
skip_msg = next((line[len('SKIP:'):].strip()
|
| 1760 |
+
for line in proc.stdout.splitlines()
|
| 1761 |
+
if line.startswith('SKIP:')),
|
| 1762 |
+
'')
|
| 1763 |
+
if skip_msg:
|
| 1764 |
+
pytest.skip(skip_msg)
|
| 1765 |
+
|
| 1766 |
+
|
| 1767 |
+
def test_majformatter_type():
|
| 1768 |
+
fig, ax = plt.subplots()
|
| 1769 |
+
with pytest.raises(TypeError):
|
| 1770 |
+
ax.xaxis.set_major_formatter(mticker.LogLocator())
|
| 1771 |
+
|
| 1772 |
+
|
| 1773 |
+
def test_minformatter_type():
|
| 1774 |
+
fig, ax = plt.subplots()
|
| 1775 |
+
with pytest.raises(TypeError):
|
| 1776 |
+
ax.xaxis.set_minor_formatter(mticker.LogLocator())
|
| 1777 |
+
|
| 1778 |
+
|
| 1779 |
+
def test_majlocator_type():
|
| 1780 |
+
fig, ax = plt.subplots()
|
| 1781 |
+
with pytest.raises(TypeError):
|
| 1782 |
+
ax.xaxis.set_major_locator(mticker.LogFormatter())
|
| 1783 |
+
|
| 1784 |
+
|
| 1785 |
+
def test_minlocator_type():
|
| 1786 |
+
fig, ax = plt.subplots()
|
| 1787 |
+
with pytest.raises(TypeError):
|
| 1788 |
+
ax.xaxis.set_minor_locator(mticker.LogFormatter())
|
| 1789 |
+
|
| 1790 |
+
|
| 1791 |
+
def test_minorticks_rc():
|
| 1792 |
+
fig = plt.figure()
|
| 1793 |
+
|
| 1794 |
+
def minorticksubplot(xminor, yminor, i):
|
| 1795 |
+
rc = {'xtick.minor.visible': xminor,
|
| 1796 |
+
'ytick.minor.visible': yminor}
|
| 1797 |
+
with plt.rc_context(rc=rc):
|
| 1798 |
+
ax = fig.add_subplot(2, 2, i)
|
| 1799 |
+
|
| 1800 |
+
assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor
|
| 1801 |
+
assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor
|
| 1802 |
+
|
| 1803 |
+
minorticksubplot(False, False, 1)
|
| 1804 |
+
minorticksubplot(True, False, 2)
|
| 1805 |
+
minorticksubplot(False, True, 3)
|
| 1806 |
+
minorticksubplot(True, True, 4)
|
| 1807 |
+
|
| 1808 |
+
|
| 1809 |
+
def test_minorticks_toggle():
|
| 1810 |
+
"""
|
| 1811 |
+
Test toggling minor ticks
|
| 1812 |
+
|
| 1813 |
+
Test `.Axis.minorticks_on()` and `.Axis.minorticks_off()`. Testing is
|
| 1814 |
+
limited to a subset of built-in scales - `'linear'`, `'log'`, `'asinh'`
|
| 1815 |
+
and `'logit'`. `symlog` scale does not seem to have a working minor
|
| 1816 |
+
locator and is omitted. In future, this test should cover all scales in
|
| 1817 |
+
`matplotlib.scale.get_scale_names()`.
|
| 1818 |
+
"""
|
| 1819 |
+
fig = plt.figure()
|
| 1820 |
+
def minortickstoggle(xminor, yminor, scale, i):
|
| 1821 |
+
ax = fig.add_subplot(2, 2, i)
|
| 1822 |
+
ax.set_xscale(scale)
|
| 1823 |
+
ax.set_yscale(scale)
|
| 1824 |
+
if not xminor and not yminor:
|
| 1825 |
+
ax.minorticks_off()
|
| 1826 |
+
if xminor and not yminor:
|
| 1827 |
+
ax.xaxis.minorticks_on()
|
| 1828 |
+
ax.yaxis.minorticks_off()
|
| 1829 |
+
if not xminor and yminor:
|
| 1830 |
+
ax.xaxis.minorticks_off()
|
| 1831 |
+
ax.yaxis.minorticks_on()
|
| 1832 |
+
if xminor and yminor:
|
| 1833 |
+
ax.minorticks_on()
|
| 1834 |
+
|
| 1835 |
+
assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor
|
| 1836 |
+
assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor
|
| 1837 |
+
|
| 1838 |
+
scales = ['linear', 'log', 'asinh', 'logit']
|
| 1839 |
+
for scale in scales:
|
| 1840 |
+
minortickstoggle(False, False, scale, 1)
|
| 1841 |
+
minortickstoggle(True, False, scale, 2)
|
| 1842 |
+
minortickstoggle(False, True, scale, 3)
|
| 1843 |
+
minortickstoggle(True, True, scale, 4)
|
| 1844 |
+
fig.clear()
|
| 1845 |
+
|
| 1846 |
+
plt.close(fig)
|
| 1847 |
+
|
| 1848 |
+
|
| 1849 |
+
@pytest.mark.parametrize('remove_overlapping_locs, expected_num',
|
| 1850 |
+
((True, 6),
|
| 1851 |
+
(None, 6), # this tests the default
|
| 1852 |
+
(False, 9)))
|
| 1853 |
+
def test_remove_overlap(remove_overlapping_locs, expected_num):
|
| 1854 |
+
t = np.arange("2018-11-03", "2018-11-06", dtype="datetime64")
|
| 1855 |
+
x = np.ones(len(t))
|
| 1856 |
+
|
| 1857 |
+
fig, ax = plt.subplots()
|
| 1858 |
+
ax.plot(t, x)
|
| 1859 |
+
|
| 1860 |
+
ax.xaxis.set_major_locator(mpl.dates.DayLocator())
|
| 1861 |
+
ax.xaxis.set_major_formatter(mpl.dates.DateFormatter('\n%a'))
|
| 1862 |
+
|
| 1863 |
+
ax.xaxis.set_minor_locator(mpl.dates.HourLocator((0, 6, 12, 18)))
|
| 1864 |
+
ax.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%H:%M'))
|
| 1865 |
+
# force there to be extra ticks
|
| 1866 |
+
ax.xaxis.get_minor_ticks(15)
|
| 1867 |
+
if remove_overlapping_locs is not None:
|
| 1868 |
+
ax.xaxis.remove_overlapping_locs = remove_overlapping_locs
|
| 1869 |
+
|
| 1870 |
+
# check that getter/setter exists
|
| 1871 |
+
current = ax.xaxis.remove_overlapping_locs
|
| 1872 |
+
assert (current == ax.xaxis.get_remove_overlapping_locs())
|
| 1873 |
+
plt.setp(ax.xaxis, remove_overlapping_locs=current)
|
| 1874 |
+
new = ax.xaxis.remove_overlapping_locs
|
| 1875 |
+
assert (new == ax.xaxis.remove_overlapping_locs)
|
| 1876 |
+
|
| 1877 |
+
# check that the accessors filter correctly
|
| 1878 |
+
# this is the method that does the actual filtering
|
| 1879 |
+
assert len(ax.xaxis.get_minorticklocs()) == expected_num
|
| 1880 |
+
# these three are derivative
|
| 1881 |
+
assert len(ax.xaxis.get_minor_ticks()) == expected_num
|
| 1882 |
+
assert len(ax.xaxis.get_minorticklabels()) == expected_num
|
| 1883 |
+
assert len(ax.xaxis.get_minorticklines()) == expected_num*2
|
| 1884 |
+
|
| 1885 |
+
|
| 1886 |
+
@pytest.mark.parametrize('sub', [
|
| 1887 |
+
['hi', 'aardvark'],
|
| 1888 |
+
np.zeros((2, 2))])
|
| 1889 |
+
def test_bad_locator_subs(sub):
|
| 1890 |
+
ll = mticker.LogLocator()
|
| 1891 |
+
with pytest.raises(ValueError):
|
| 1892 |
+
ll.set_params(subs=sub)
|
| 1893 |
+
|
| 1894 |
+
|
| 1895 |
+
@pytest.mark.parametrize('numticks', [1, 2, 3, 9])
|
| 1896 |
+
@mpl.style.context('default')
|
| 1897 |
+
def test_small_range_loglocator(numticks):
|
| 1898 |
+
ll = mticker.LogLocator()
|
| 1899 |
+
ll.set_params(numticks=numticks)
|
| 1900 |
+
for top in [5, 7, 9, 11, 15, 50, 100, 1000]:
|
| 1901 |
+
ticks = ll.tick_values(.5, top)
|
| 1902 |
+
assert (np.diff(np.log10(ll.tick_values(6, 150))) == 1).all()
|
| 1903 |
+
|
| 1904 |
+
|
| 1905 |
+
def test_NullFormatter():
|
| 1906 |
+
formatter = mticker.NullFormatter()
|
| 1907 |
+
assert formatter(1.0) == ''
|
| 1908 |
+
assert formatter.format_data(1.0) == ''
|
| 1909 |
+
assert formatter.format_data_short(1.0) == ''
|
| 1910 |
+
|
| 1911 |
+
|
| 1912 |
+
@pytest.mark.parametrize('formatter', (
|
| 1913 |
+
mticker.FuncFormatter(lambda a: f'val: {a}'),
|
| 1914 |
+
mticker.FixedFormatter(('foo', 'bar'))))
|
| 1915 |
+
def test_set_offset_string(formatter):
|
| 1916 |
+
assert formatter.get_offset() == ''
|
| 1917 |
+
formatter.set_offset_string('mpl')
|
| 1918 |
+
assert formatter.get_offset() == 'mpl'
|
| 1919 |
+
|
| 1920 |
+
|
| 1921 |
+
def test_minorticks_on_multi_fig():
|
| 1922 |
+
"""
|
| 1923 |
+
Turning on minor gridlines in a multi-Axes Figure
|
| 1924 |
+
that contains more than one boxplot and shares the x-axis
|
| 1925 |
+
should not raise an exception.
|
| 1926 |
+
"""
|
| 1927 |
+
fig, ax = plt.subplots()
|
| 1928 |
+
|
| 1929 |
+
ax.boxplot(np.arange(10), positions=[0])
|
| 1930 |
+
ax.boxplot(np.arange(10), positions=[0])
|
| 1931 |
+
ax.boxplot(np.arange(10), positions=[1])
|
| 1932 |
+
|
| 1933 |
+
ax.grid(which="major")
|
| 1934 |
+
ax.grid(which="minor")
|
| 1935 |
+
ax.minorticks_on()
|
| 1936 |
+
fig.draw_without_rendering()
|
| 1937 |
+
|
| 1938 |
+
assert ax.get_xgridlines()
|
| 1939 |
+
assert isinstance(ax.xaxis.get_minor_locator(), mpl.ticker.AutoMinorLocator)
|
shared/package-files/06/0642d38ff9e1addb42a845d6134f25a72d72b3a55c01e5022fdc234fe6329003/model.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
shared/package-files/06/06443070da247d3f658ce4042c0a69e5b785a902808279427f097122843658ce/special_digamma_native.h
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor special_digamma(const at::Tensor & self);
|
| 20 |
+
TORCH_API at::Tensor & special_digamma_out(const at::Tensor & self, at::Tensor & out);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
shared/package-files/06/0644947fedb1a228fe7977e9576b7bcb5245286d730f582d57a6808375e2ff01/matplotlib.pdf
ADDED
|
Binary file (22.9 kB). View file
|
|
|
shared/package-files/06/0645aef3d7df9a27e405d2c7fbe210ec3896d21bc3915122b9d531e0745599c2/_onenormest.py
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sparse block 1-norm estimator.
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from scipy.sparse.linalg import aslinearoperator
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = ['onenormest']
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def onenormest(A, t=2, itmax=5, compute_v=False, compute_w=False):
|
| 12 |
+
"""
|
| 13 |
+
Compute a lower bound of the 1-norm of a sparse array.
|
| 14 |
+
|
| 15 |
+
Parameters
|
| 16 |
+
----------
|
| 17 |
+
A : ndarray or other linear operator
|
| 18 |
+
A linear operator that can be transposed and that can
|
| 19 |
+
produce matrix products.
|
| 20 |
+
t : int, optional
|
| 21 |
+
A positive parameter controlling the tradeoff between
|
| 22 |
+
accuracy versus time and memory usage.
|
| 23 |
+
Larger values take longer and use more memory
|
| 24 |
+
but give more accurate output.
|
| 25 |
+
itmax : int, optional
|
| 26 |
+
Use at most this many iterations.
|
| 27 |
+
compute_v : bool, optional
|
| 28 |
+
Request a norm-maximizing linear operator input vector if True.
|
| 29 |
+
compute_w : bool, optional
|
| 30 |
+
Request a norm-maximizing linear operator output vector if True.
|
| 31 |
+
|
| 32 |
+
Returns
|
| 33 |
+
-------
|
| 34 |
+
est : float
|
| 35 |
+
An underestimate of the 1-norm of the sparse array.
|
| 36 |
+
v : ndarray, optional
|
| 37 |
+
The vector such that ||Av||_1 == est*||v||_1.
|
| 38 |
+
It can be thought of as an input to the linear operator
|
| 39 |
+
that gives an output with particularly large norm.
|
| 40 |
+
w : ndarray, optional
|
| 41 |
+
The vector Av which has relatively large 1-norm.
|
| 42 |
+
It can be thought of as an output of the linear operator
|
| 43 |
+
that is relatively large in norm compared to the input.
|
| 44 |
+
|
| 45 |
+
Notes
|
| 46 |
+
-----
|
| 47 |
+
This is algorithm 2.4 of [1].
|
| 48 |
+
|
| 49 |
+
In [2] it is described as follows.
|
| 50 |
+
"This algorithm typically requires the evaluation of
|
| 51 |
+
about 4t matrix-vector products and almost invariably
|
| 52 |
+
produces a norm estimate (which is, in fact, a lower
|
| 53 |
+
bound on the norm) correct to within a factor 3."
|
| 54 |
+
|
| 55 |
+
.. versionadded:: 0.13.0
|
| 56 |
+
|
| 57 |
+
References
|
| 58 |
+
----------
|
| 59 |
+
.. [1] Nicholas J. Higham and Francoise Tisseur (2000),
|
| 60 |
+
"A Block Algorithm for Matrix 1-Norm Estimation,
|
| 61 |
+
with an Application to 1-Norm Pseudospectra."
|
| 62 |
+
SIAM J. Matrix Anal. Appl. Vol. 21, No. 4, pp. 1185-1201.
|
| 63 |
+
|
| 64 |
+
.. [2] Awad H. Al-Mohy and Nicholas J. Higham (2009),
|
| 65 |
+
"A new scaling and squaring algorithm for the matrix exponential."
|
| 66 |
+
SIAM J. Matrix Anal. Appl. Vol. 31, No. 3, pp. 970-989.
|
| 67 |
+
|
| 68 |
+
Examples
|
| 69 |
+
--------
|
| 70 |
+
>>> import numpy as np
|
| 71 |
+
>>> from scipy.sparse import csc_array
|
| 72 |
+
>>> from scipy.sparse.linalg import onenormest
|
| 73 |
+
>>> A = csc_array([[1., 0., 0.], [5., 8., 2.], [0., -1., 0.]], dtype=float)
|
| 74 |
+
>>> A.toarray()
|
| 75 |
+
array([[ 1., 0., 0.],
|
| 76 |
+
[ 5., 8., 2.],
|
| 77 |
+
[ 0., -1., 0.]])
|
| 78 |
+
>>> onenormest(A)
|
| 79 |
+
9.0
|
| 80 |
+
>>> np.linalg.norm(A.toarray(), ord=1)
|
| 81 |
+
9.0
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
# Check the input.
|
| 85 |
+
A = aslinearoperator(A)
|
| 86 |
+
if A.shape[0] != A.shape[1]:
|
| 87 |
+
raise ValueError('expected the operator to act like a square matrix')
|
| 88 |
+
|
| 89 |
+
# If the operator size is small compared to t,
|
| 90 |
+
# then it is easier to compute the exact norm.
|
| 91 |
+
# Otherwise estimate the norm.
|
| 92 |
+
n = A.shape[1]
|
| 93 |
+
if t >= n:
|
| 94 |
+
A_explicit = np.asarray(aslinearoperator(A).matmat(np.identity(n)))
|
| 95 |
+
if A_explicit.shape != (n, n):
|
| 96 |
+
raise Exception('internal error: ',
|
| 97 |
+
'unexpected shape ' + str(A_explicit.shape))
|
| 98 |
+
col_abs_sums = abs(A_explicit).sum(axis=0)
|
| 99 |
+
if col_abs_sums.shape != (n, ):
|
| 100 |
+
raise Exception('internal error: ',
|
| 101 |
+
'unexpected shape ' + str(col_abs_sums.shape))
|
| 102 |
+
argmax_j = np.argmax(col_abs_sums)
|
| 103 |
+
v = elementary_vector(n, argmax_j)
|
| 104 |
+
w = A_explicit[:, argmax_j]
|
| 105 |
+
est = col_abs_sums[argmax_j]
|
| 106 |
+
else:
|
| 107 |
+
est, v, w, nmults, nresamples = _onenormest_core(A, A.H, t, itmax)
|
| 108 |
+
|
| 109 |
+
# Report the norm estimate along with some certificates of the estimate.
|
| 110 |
+
if compute_v or compute_w:
|
| 111 |
+
result = (est,)
|
| 112 |
+
if compute_v:
|
| 113 |
+
result += (v,)
|
| 114 |
+
if compute_w:
|
| 115 |
+
result += (w,)
|
| 116 |
+
return result
|
| 117 |
+
else:
|
| 118 |
+
return est
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _blocked_elementwise(func):
|
| 122 |
+
"""
|
| 123 |
+
Decorator for an elementwise function, to apply it blockwise along
|
| 124 |
+
first dimension, to avoid excessive memory usage in temporaries.
|
| 125 |
+
"""
|
| 126 |
+
block_size = 2**20
|
| 127 |
+
|
| 128 |
+
def wrapper(x):
|
| 129 |
+
if x.shape[0] < block_size:
|
| 130 |
+
return func(x)
|
| 131 |
+
else:
|
| 132 |
+
y0 = func(x[:block_size])
|
| 133 |
+
y = np.zeros((x.shape[0],) + y0.shape[1:], dtype=y0.dtype)
|
| 134 |
+
y[:block_size] = y0
|
| 135 |
+
del y0
|
| 136 |
+
for j in range(block_size, x.shape[0], block_size):
|
| 137 |
+
y[j:j+block_size] = func(x[j:j+block_size])
|
| 138 |
+
return y
|
| 139 |
+
return wrapper
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@_blocked_elementwise
|
| 143 |
+
def sign_round_up(X):
|
| 144 |
+
"""
|
| 145 |
+
This should do the right thing for both real and complex matrices.
|
| 146 |
+
|
| 147 |
+
From Higham and Tisseur:
|
| 148 |
+
"Everything in this section remains valid for complex matrices
|
| 149 |
+
provided that sign(A) is redefined as the matrix (aij / |aij|)
|
| 150 |
+
(and sign(0) = 1) transposes are replaced by conjugate transposes."
|
| 151 |
+
|
| 152 |
+
"""
|
| 153 |
+
Y = X.copy()
|
| 154 |
+
Y[Y == 0] = 1
|
| 155 |
+
Y /= np.abs(Y)
|
| 156 |
+
return Y
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@_blocked_elementwise
|
| 160 |
+
def _max_abs_axis1(X):
|
| 161 |
+
return np.max(np.abs(X), axis=1)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _sum_abs_axis0(X):
|
| 165 |
+
block_size = 2**20
|
| 166 |
+
r = None
|
| 167 |
+
for j in range(0, X.shape[0], block_size):
|
| 168 |
+
y = np.sum(np.abs(X[j:j+block_size]), axis=0)
|
| 169 |
+
if r is None:
|
| 170 |
+
r = y
|
| 171 |
+
else:
|
| 172 |
+
r += y
|
| 173 |
+
return r
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def elementary_vector(n, i):
|
| 177 |
+
v = np.zeros(n, dtype=float)
|
| 178 |
+
v[i] = 1
|
| 179 |
+
return v
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def vectors_are_parallel(v, w):
|
| 183 |
+
# Columns are considered parallel when they are equal or negative.
|
| 184 |
+
# Entries are required to be in {-1, 1},
|
| 185 |
+
# which guarantees that the magnitudes of the vectors are identical.
|
| 186 |
+
if v.ndim != 1 or v.shape != w.shape:
|
| 187 |
+
raise ValueError('expected conformant vectors with entries in {-1,1}')
|
| 188 |
+
n = v.shape[0]
|
| 189 |
+
return np.dot(v, w) == n
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def every_col_of_X_is_parallel_to_a_col_of_Y(X, Y):
|
| 193 |
+
for v in X.T:
|
| 194 |
+
if not any(vectors_are_parallel(v, w) for w in Y.T):
|
| 195 |
+
return False
|
| 196 |
+
return True
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def column_needs_resampling(i, X, Y=None):
|
| 200 |
+
# column i of X needs resampling if either
|
| 201 |
+
# it is parallel to a previous column of X or
|
| 202 |
+
# it is parallel to a column of Y
|
| 203 |
+
n, t = X.shape
|
| 204 |
+
v = X[:, i]
|
| 205 |
+
if any(vectors_are_parallel(v, X[:, j]) for j in range(i)):
|
| 206 |
+
return True
|
| 207 |
+
if Y is not None:
|
| 208 |
+
if any(vectors_are_parallel(v, w) for w in Y.T):
|
| 209 |
+
return True
|
| 210 |
+
return False
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def resample_column(i, X):
|
| 214 |
+
X[:, i] = np.random.randint(0, 2, size=X.shape[0])*2 - 1
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def less_than_or_close(a, b):
|
| 218 |
+
return np.allclose(a, b) or (a < b)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _algorithm_2_2(A, AT, t):
|
| 222 |
+
"""
|
| 223 |
+
This is Algorithm 2.2.
|
| 224 |
+
|
| 225 |
+
Parameters
|
| 226 |
+
----------
|
| 227 |
+
A : ndarray or other linear operator
|
| 228 |
+
A linear operator that can produce matrix products.
|
| 229 |
+
AT : ndarray or other linear operator
|
| 230 |
+
The transpose of A.
|
| 231 |
+
t : int, optional
|
| 232 |
+
A positive parameter controlling the tradeoff between
|
| 233 |
+
accuracy versus time and memory usage.
|
| 234 |
+
|
| 235 |
+
Returns
|
| 236 |
+
-------
|
| 237 |
+
g : sequence
|
| 238 |
+
A non-negative decreasing vector
|
| 239 |
+
such that g[j] is a lower bound for the 1-norm
|
| 240 |
+
of the column of A of jth largest 1-norm.
|
| 241 |
+
The first entry of this vector is therefore a lower bound
|
| 242 |
+
on the 1-norm of the linear operator A.
|
| 243 |
+
This sequence has length t.
|
| 244 |
+
ind : sequence
|
| 245 |
+
The ith entry of ind is the index of the column A whose 1-norm
|
| 246 |
+
is given by g[i].
|
| 247 |
+
This sequence of indices has length t, and its entries are
|
| 248 |
+
chosen from range(n), possibly with repetition,
|
| 249 |
+
where n is the order of the operator A.
|
| 250 |
+
|
| 251 |
+
Notes
|
| 252 |
+
-----
|
| 253 |
+
This algorithm is mainly for testing.
|
| 254 |
+
It uses the 'ind' array in a way that is similar to
|
| 255 |
+
its usage in algorithm 2.4. This algorithm 2.2 may be easier to test,
|
| 256 |
+
so it gives a chance of uncovering bugs related to indexing
|
| 257 |
+
which could have propagated less noticeably to algorithm 2.4.
|
| 258 |
+
|
| 259 |
+
"""
|
| 260 |
+
A_linear_operator = aslinearoperator(A)
|
| 261 |
+
AT_linear_operator = aslinearoperator(AT)
|
| 262 |
+
n = A_linear_operator.shape[0]
|
| 263 |
+
|
| 264 |
+
# Initialize the X block with columns of unit 1-norm.
|
| 265 |
+
X = np.ones((n, t))
|
| 266 |
+
if t > 1:
|
| 267 |
+
X[:, 1:] = np.random.randint(0, 2, size=(n, t-1))*2 - 1
|
| 268 |
+
X /= float(n)
|
| 269 |
+
|
| 270 |
+
# Iteratively improve the lower bounds.
|
| 271 |
+
# Track extra things, to assert invariants for debugging.
|
| 272 |
+
g_prev = None
|
| 273 |
+
h_prev = None
|
| 274 |
+
k = 1
|
| 275 |
+
ind = range(t)
|
| 276 |
+
while True:
|
| 277 |
+
Y = np.asarray(A_linear_operator.matmat(X))
|
| 278 |
+
g = _sum_abs_axis0(Y)
|
| 279 |
+
best_j = np.argmax(g)
|
| 280 |
+
g.sort()
|
| 281 |
+
g = g[::-1]
|
| 282 |
+
S = sign_round_up(Y)
|
| 283 |
+
Z = np.asarray(AT_linear_operator.matmat(S))
|
| 284 |
+
h = _max_abs_axis1(Z)
|
| 285 |
+
|
| 286 |
+
# If this algorithm runs for fewer than two iterations,
|
| 287 |
+
# then its return values do not have the properties indicated
|
| 288 |
+
# in the description of the algorithm.
|
| 289 |
+
# In particular, the entries of g are not 1-norms of any
|
| 290 |
+
# column of A until the second iteration.
|
| 291 |
+
# Therefore we will require the algorithm to run for at least
|
| 292 |
+
# two iterations, even though this requirement is not stated
|
| 293 |
+
# in the description of the algorithm.
|
| 294 |
+
if k >= 2:
|
| 295 |
+
if less_than_or_close(max(h), np.dot(Z[:, best_j], X[:, best_j])):
|
| 296 |
+
break
|
| 297 |
+
ind = np.argsort(h)[::-1][:t]
|
| 298 |
+
h = h[ind]
|
| 299 |
+
for j in range(t):
|
| 300 |
+
X[:, j] = elementary_vector(n, ind[j])
|
| 301 |
+
|
| 302 |
+
# Check invariant (2.2).
|
| 303 |
+
if k >= 2:
|
| 304 |
+
if not less_than_or_close(g_prev[0], h_prev[0]):
|
| 305 |
+
raise Exception('invariant (2.2) is violated')
|
| 306 |
+
if not less_than_or_close(h_prev[0], g[0]):
|
| 307 |
+
raise Exception('invariant (2.2) is violated')
|
| 308 |
+
|
| 309 |
+
# Check invariant (2.3).
|
| 310 |
+
if k >= 3:
|
| 311 |
+
for j in range(t):
|
| 312 |
+
if not less_than_or_close(g[j], g_prev[j]):
|
| 313 |
+
raise Exception('invariant (2.3) is violated')
|
| 314 |
+
|
| 315 |
+
# Update for the next iteration.
|
| 316 |
+
g_prev = g
|
| 317 |
+
h_prev = h
|
| 318 |
+
k += 1
|
| 319 |
+
|
| 320 |
+
# Return the lower bounds and the corresponding column indices.
|
| 321 |
+
return g, ind
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def _onenormest_core(A, AT, t, itmax):
|
| 325 |
+
"""
|
| 326 |
+
Compute a lower bound of the 1-norm of a sparse array.
|
| 327 |
+
|
| 328 |
+
Parameters
|
| 329 |
+
----------
|
| 330 |
+
A : ndarray or other linear operator
|
| 331 |
+
A linear operator that can produce matrix products.
|
| 332 |
+
AT : ndarray or other linear operator
|
| 333 |
+
The transpose of A.
|
| 334 |
+
t : int, optional
|
| 335 |
+
A positive parameter controlling the tradeoff between
|
| 336 |
+
accuracy versus time and memory usage.
|
| 337 |
+
itmax : int, optional
|
| 338 |
+
Use at most this many iterations.
|
| 339 |
+
|
| 340 |
+
Returns
|
| 341 |
+
-------
|
| 342 |
+
est : float
|
| 343 |
+
An underestimate of the 1-norm of the sparse array.
|
| 344 |
+
v : ndarray, optional
|
| 345 |
+
The vector such that ||Av||_1 == est*||v||_1.
|
| 346 |
+
It can be thought of as an input to the linear operator
|
| 347 |
+
that gives an output with particularly large norm.
|
| 348 |
+
w : ndarray, optional
|
| 349 |
+
The vector Av which has relatively large 1-norm.
|
| 350 |
+
It can be thought of as an output of the linear operator
|
| 351 |
+
that is relatively large in norm compared to the input.
|
| 352 |
+
nmults : int, optional
|
| 353 |
+
The number of matrix products that were computed.
|
| 354 |
+
nresamples : int, optional
|
| 355 |
+
The number of times a parallel column was observed,
|
| 356 |
+
necessitating a re-randomization of the column.
|
| 357 |
+
|
| 358 |
+
Notes
|
| 359 |
+
-----
|
| 360 |
+
This is algorithm 2.4.
|
| 361 |
+
|
| 362 |
+
"""
|
| 363 |
+
# This function is a more or less direct translation
|
| 364 |
+
# of Algorithm 2.4 from the Higham and Tisseur (2000) paper.
|
| 365 |
+
A_linear_operator = aslinearoperator(A)
|
| 366 |
+
AT_linear_operator = aslinearoperator(AT)
|
| 367 |
+
if itmax < 2:
|
| 368 |
+
raise ValueError('at least two iterations are required')
|
| 369 |
+
if t < 1:
|
| 370 |
+
raise ValueError('at least one column is required')
|
| 371 |
+
n = A.shape[0]
|
| 372 |
+
if t >= n:
|
| 373 |
+
raise ValueError('t should be smaller than the order of A')
|
| 374 |
+
# Track the number of big*small matrix multiplications
|
| 375 |
+
# and the number of resamplings.
|
| 376 |
+
nmults = 0
|
| 377 |
+
nresamples = 0
|
| 378 |
+
# "We now explain our choice of starting matrix. We take the first
|
| 379 |
+
# column of X to be the vector of 1s [...] This has the advantage that
|
| 380 |
+
# for a matrix with nonnegative elements the algorithm converges
|
| 381 |
+
# with an exact estimate on the second iteration, and such matrices
|
| 382 |
+
# arise in applications [...]"
|
| 383 |
+
X = np.ones((n, t), dtype=float)
|
| 384 |
+
# "The remaining columns are chosen as rand{-1,1},
|
| 385 |
+
# with a check for and correction of parallel columns,
|
| 386 |
+
# exactly as for S in the body of the algorithm."
|
| 387 |
+
if t > 1:
|
| 388 |
+
for i in range(1, t):
|
| 389 |
+
# These are technically initial samples, not resamples,
|
| 390 |
+
# so the resampling count is not incremented.
|
| 391 |
+
resample_column(i, X)
|
| 392 |
+
for i in range(t):
|
| 393 |
+
while column_needs_resampling(i, X):
|
| 394 |
+
resample_column(i, X)
|
| 395 |
+
nresamples += 1
|
| 396 |
+
# "Choose starting matrix X with columns of unit 1-norm."
|
| 397 |
+
X /= float(n)
|
| 398 |
+
# "indices of used unit vectors e_j"
|
| 399 |
+
ind_hist = np.zeros(0, dtype=np.intp)
|
| 400 |
+
est_old = 0
|
| 401 |
+
S = np.zeros((n, t), dtype=float)
|
| 402 |
+
k = 1
|
| 403 |
+
ind = None
|
| 404 |
+
while True:
|
| 405 |
+
Y = np.asarray(A_linear_operator.matmat(X))
|
| 406 |
+
nmults += 1
|
| 407 |
+
mags = _sum_abs_axis0(Y)
|
| 408 |
+
est = np.max(mags)
|
| 409 |
+
best_j = np.argmax(mags)
|
| 410 |
+
if est > est_old or k == 2:
|
| 411 |
+
if k >= 2:
|
| 412 |
+
ind_best = ind[best_j]
|
| 413 |
+
w = Y[:, best_j]
|
| 414 |
+
# (1)
|
| 415 |
+
if k >= 2 and est <= est_old:
|
| 416 |
+
est = est_old
|
| 417 |
+
break
|
| 418 |
+
est_old = est
|
| 419 |
+
S_old = S
|
| 420 |
+
if k > itmax:
|
| 421 |
+
break
|
| 422 |
+
S = sign_round_up(Y)
|
| 423 |
+
del Y
|
| 424 |
+
# (2)
|
| 425 |
+
if every_col_of_X_is_parallel_to_a_col_of_Y(S, S_old):
|
| 426 |
+
break
|
| 427 |
+
if t > 1:
|
| 428 |
+
# "Ensure that no column of S is parallel to another column of S
|
| 429 |
+
# or to a column of S_old by replacing columns of S by rand{-1,1}."
|
| 430 |
+
for i in range(t):
|
| 431 |
+
while column_needs_resampling(i, S, S_old):
|
| 432 |
+
resample_column(i, S)
|
| 433 |
+
nresamples += 1
|
| 434 |
+
del S_old
|
| 435 |
+
# (3)
|
| 436 |
+
Z = np.asarray(AT_linear_operator.matmat(S))
|
| 437 |
+
nmults += 1
|
| 438 |
+
h = _max_abs_axis1(Z)
|
| 439 |
+
del Z
|
| 440 |
+
# (4)
|
| 441 |
+
if k >= 2 and max(h) == h[ind_best]:
|
| 442 |
+
break
|
| 443 |
+
# "Sort h so that h_first >= ... >= h_last
|
| 444 |
+
# and re-order ind correspondingly."
|
| 445 |
+
#
|
| 446 |
+
# Later on, we will need at most t+len(ind_hist) largest
|
| 447 |
+
# entries, so drop the rest
|
| 448 |
+
ind = np.argsort(h)[::-1][:t+len(ind_hist)].copy()
|
| 449 |
+
del h
|
| 450 |
+
if t > 1:
|
| 451 |
+
# (5)
|
| 452 |
+
# Break if the most promising t vectors have been visited already.
|
| 453 |
+
if np.isin(ind[:t], ind_hist).all():
|
| 454 |
+
break
|
| 455 |
+
# Put the most promising unvisited vectors at the front of the list
|
| 456 |
+
# and put the visited vectors at the end of the list.
|
| 457 |
+
# Preserve the order of the indices induced by the ordering of h.
|
| 458 |
+
seen = np.isin(ind, ind_hist)
|
| 459 |
+
ind = np.concatenate((ind[~seen], ind[seen]))
|
| 460 |
+
for j in range(t):
|
| 461 |
+
X[:, j] = elementary_vector(n, ind[j])
|
| 462 |
+
|
| 463 |
+
new_ind = ind[:t][~np.isin(ind[:t], ind_hist)]
|
| 464 |
+
ind_hist = np.concatenate((ind_hist, new_ind))
|
| 465 |
+
k += 1
|
| 466 |
+
v = elementary_vector(n, ind_best)
|
| 467 |
+
return est, v, w, nmults, nresamples
|
shared/package-files/06/06474d45271bdfef20742bf0414eb87935942601969000a4be23fa345ba63f3a/native_layer_norm_backward_native.h
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> native_layer_norm_backward_out_symint(const at::Tensor & grad_out, const at::Tensor & input, c10::SymIntArrayRef normalized_shape, const at::Tensor & mean, const at::Tensor & rstd, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, ::std::array<bool,3> output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
|
| 20 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> layer_norm_backward_cpu(const at::Tensor & grad_out, const at::Tensor & input, at::IntArrayRef normalized_shape, const at::Tensor & mean, const at::Tensor & rstd, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, ::std::array<bool,3> output_mask);
|
| 21 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> layer_norm_backward_cuda(const at::Tensor & grad_out, const at::Tensor & input, at::IntArrayRef normalized_shape, const at::Tensor & mean, const at::Tensor & rstd, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, ::std::array<bool,3> output_mask);
|
| 22 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> layer_norm_backward_nested(const at::Tensor & grad_out, const at::Tensor & input, at::IntArrayRef normalized_shape, const at::Tensor & mean, const at::Tensor & rstd, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, ::std::array<bool,3> output_mask);
|
| 23 |
+
} // namespace native
|
| 24 |
+
} // namespace at
|
shared/package-files/06/064c0c5a812384deb8751898da757ca6696daa03c14cd3dcb303273e3879beec/ttkmenu.tcl
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ttkmenu.tcl --
|
| 2 |
+
#
|
| 3 |
+
# This demonstration script creates a toplevel window containing several Ttk
|
| 4 |
+
# menubutton widgets.
|
| 5 |
+
|
| 6 |
+
if {![info exists widgetDemo]} {
|
| 7 |
+
error "This script should be run from the \"widget\" demo."
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
package require Tk
|
| 11 |
+
|
| 12 |
+
set w .ttkmenu
|
| 13 |
+
catch {destroy $w}
|
| 14 |
+
toplevel $w
|
| 15 |
+
wm title $w "Ttk Menu Buttons"
|
| 16 |
+
wm iconname $w "ttkmenu"
|
| 17 |
+
positionWindow $w
|
| 18 |
+
|
| 19 |
+
ttk::label $w.msg -font $font -wraplength 4i -justify left -text "Ttk is the new Tk themed widget set, and one widget that is available in themed form is the menubutton. Below are some themed menu buttons that allow you to pick the current theme in use. Notice how picking a theme changes the way that the menu buttons themselves look, and that the central menu button is styled differently (in a way that is normally suitable for toolbars). However, there are no themed menus; the standard Tk menus were judged to have a sufficiently good look-and-feel on all platforms, especially as they are implemented as native controls in many places."
|
| 20 |
+
pack $w.msg [ttk::separator $w.msgSep] -side top -fill x
|
| 21 |
+
|
| 22 |
+
## See Code / Dismiss
|
| 23 |
+
pack [addSeeDismiss $w.seeDismiss $w] -side bottom -fill x
|
| 24 |
+
|
| 25 |
+
ttk::menubutton $w.m1 -menu $w.m1.menu -text "Select a theme" -direction above
|
| 26 |
+
ttk::menubutton $w.m2 -menu $w.m1.menu -text "Select a theme" -direction left
|
| 27 |
+
ttk::menubutton $w.m3 -menu $w.m1.menu -text "Select a theme" -direction right
|
| 28 |
+
ttk::menubutton $w.m4 -menu $w.m1.menu -text "Select a theme" \
|
| 29 |
+
-direction flush -style TMenubutton.Toolbutton
|
| 30 |
+
ttk::menubutton $w.m5 -menu $w.m1.menu -text "Select a theme" -direction below
|
| 31 |
+
|
| 32 |
+
menu $w.m1.menu -tearoff 0
|
| 33 |
+
menu $w.m2.menu -tearoff 0
|
| 34 |
+
menu $w.m3.menu -tearoff 0
|
| 35 |
+
menu $w.m4.menu -tearoff 0
|
| 36 |
+
menu $w.m5.menu -tearoff 0
|
| 37 |
+
|
| 38 |
+
foreach theme [ttk::themes] {
|
| 39 |
+
$w.m1.menu add command -label $theme -command [list ttk::setTheme $theme]
|
| 40 |
+
$w.m2.menu add command -label $theme -command [list ttk::setTheme $theme]
|
| 41 |
+
$w.m3.menu add command -label $theme -command [list ttk::setTheme $theme]
|
| 42 |
+
$w.m4.menu add command -label $theme -command [list ttk::setTheme $theme]
|
| 43 |
+
$w.m5.menu add command -label $theme -command [list ttk::setTheme $theme]
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
pack [ttk::frame $w.f] -fill x
|
| 47 |
+
pack [ttk::frame $w.f1] -fill both -expand yes
|
| 48 |
+
lower $w.f
|
| 49 |
+
|
| 50 |
+
grid anchor $w.f center
|
| 51 |
+
grid x $w.m1 x -in $w.f -padx 3 -pady 2
|
| 52 |
+
grid $w.m2 $w.m4 $w.m3 -in $w.f -padx 3 -pady 2
|
| 53 |
+
grid x $w.m5 x -in $w.f -padx 3 -pady 2
|
shared/package-files/06/064d6dd8bb636b3af33f338112552beb14d7c26d5b4914fdcaa5fcef1ac475e4/converters.pyi
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Optional, TypeVar, overload
|
| 2 |
+
|
| 3 |
+
from . import _ConverterType
|
| 4 |
+
|
| 5 |
+
_T = TypeVar("_T")
|
| 6 |
+
|
| 7 |
+
def optional(converter: _ConverterType[_T]) -> _ConverterType[Optional[_T]]: ...
|
| 8 |
+
@overload
|
| 9 |
+
def default_if_none(default: _T) -> _ConverterType[_T]: ...
|
| 10 |
+
@overload
|
| 11 |
+
def default_if_none(*, factory: Callable[[], _T]) -> _ConverterType[_T]: ...
|
shared/package-files/06/06512b22eb481311b9b644a58e810bbb239dda1854d815488c067748dd852ddb/_triton_multi_head_attention_native.h
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor & _triton_multi_head_attention_out(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const c10::optional<at::Tensor> & mask, at::Tensor & out);
|
| 20 |
+
TORCH_API at::Tensor triton_multi_head_attention(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const c10::optional<at::Tensor> & mask={});
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
shared/package-files/06/06517ec2f74f1c6562d0a1a500c48ba43f2e6e9d0c3d28356d747f274f1a4c8d/cp1254.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Python Character Mapping Codec cp1254 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1254.TXT' with gencodec.py.
|
| 2 |
+
|
| 3 |
+
"""#"
|
| 4 |
+
|
| 5 |
+
import codecs
|
| 6 |
+
|
| 7 |
+
### Codec APIs
|
| 8 |
+
|
| 9 |
+
class Codec(codecs.Codec):
|
| 10 |
+
|
| 11 |
+
def encode(self,input,errors='strict'):
|
| 12 |
+
return codecs.charmap_encode(input,errors,encoding_table)
|
| 13 |
+
|
| 14 |
+
def decode(self,input,errors='strict'):
|
| 15 |
+
return codecs.charmap_decode(input,errors,decoding_table)
|
| 16 |
+
|
| 17 |
+
class IncrementalEncoder(codecs.IncrementalEncoder):
|
| 18 |
+
def encode(self, input, final=False):
|
| 19 |
+
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
|
| 20 |
+
|
| 21 |
+
class IncrementalDecoder(codecs.IncrementalDecoder):
|
| 22 |
+
def decode(self, input, final=False):
|
| 23 |
+
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
|
| 24 |
+
|
| 25 |
+
class StreamWriter(Codec,codecs.StreamWriter):
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
class StreamReader(Codec,codecs.StreamReader):
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
### encodings module API
|
| 32 |
+
|
| 33 |
+
def getregentry():
|
| 34 |
+
return codecs.CodecInfo(
|
| 35 |
+
name='cp1254',
|
| 36 |
+
encode=Codec().encode,
|
| 37 |
+
decode=Codec().decode,
|
| 38 |
+
incrementalencoder=IncrementalEncoder,
|
| 39 |
+
incrementaldecoder=IncrementalDecoder,
|
| 40 |
+
streamreader=StreamReader,
|
| 41 |
+
streamwriter=StreamWriter,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
### Decoding Table
|
| 46 |
+
|
| 47 |
+
decoding_table = (
|
| 48 |
+
'\x00' # 0x00 -> NULL
|
| 49 |
+
'\x01' # 0x01 -> START OF HEADING
|
| 50 |
+
'\x02' # 0x02 -> START OF TEXT
|
| 51 |
+
'\x03' # 0x03 -> END OF TEXT
|
| 52 |
+
'\x04' # 0x04 -> END OF TRANSMISSION
|
| 53 |
+
'\x05' # 0x05 -> ENQUIRY
|
| 54 |
+
'\x06' # 0x06 -> ACKNOWLEDGE
|
| 55 |
+
'\x07' # 0x07 -> BELL
|
| 56 |
+
'\x08' # 0x08 -> BACKSPACE
|
| 57 |
+
'\t' # 0x09 -> HORIZONTAL TABULATION
|
| 58 |
+
'\n' # 0x0A -> LINE FEED
|
| 59 |
+
'\x0b' # 0x0B -> VERTICAL TABULATION
|
| 60 |
+
'\x0c' # 0x0C -> FORM FEED
|
| 61 |
+
'\r' # 0x0D -> CARRIAGE RETURN
|
| 62 |
+
'\x0e' # 0x0E -> SHIFT OUT
|
| 63 |
+
'\x0f' # 0x0F -> SHIFT IN
|
| 64 |
+
'\x10' # 0x10 -> DATA LINK ESCAPE
|
| 65 |
+
'\x11' # 0x11 -> DEVICE CONTROL ONE
|
| 66 |
+
'\x12' # 0x12 -> DEVICE CONTROL TWO
|
| 67 |
+
'\x13' # 0x13 -> DEVICE CONTROL THREE
|
| 68 |
+
'\x14' # 0x14 -> DEVICE CONTROL FOUR
|
| 69 |
+
'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE
|
| 70 |
+
'\x16' # 0x16 -> SYNCHRONOUS IDLE
|
| 71 |
+
'\x17' # 0x17 -> END OF TRANSMISSION BLOCK
|
| 72 |
+
'\x18' # 0x18 -> CANCEL
|
| 73 |
+
'\x19' # 0x19 -> END OF MEDIUM
|
| 74 |
+
'\x1a' # 0x1A -> SUBSTITUTE
|
| 75 |
+
'\x1b' # 0x1B -> ESCAPE
|
| 76 |
+
'\x1c' # 0x1C -> FILE SEPARATOR
|
| 77 |
+
'\x1d' # 0x1D -> GROUP SEPARATOR
|
| 78 |
+
'\x1e' # 0x1E -> RECORD SEPARATOR
|
| 79 |
+
'\x1f' # 0x1F -> UNIT SEPARATOR
|
| 80 |
+
' ' # 0x20 -> SPACE
|
| 81 |
+
'!' # 0x21 -> EXCLAMATION MARK
|
| 82 |
+
'"' # 0x22 -> QUOTATION MARK
|
| 83 |
+
'#' # 0x23 -> NUMBER SIGN
|
| 84 |
+
'$' # 0x24 -> DOLLAR SIGN
|
| 85 |
+
'%' # 0x25 -> PERCENT SIGN
|
| 86 |
+
'&' # 0x26 -> AMPERSAND
|
| 87 |
+
"'" # 0x27 -> APOSTROPHE
|
| 88 |
+
'(' # 0x28 -> LEFT PARENTHESIS
|
| 89 |
+
')' # 0x29 -> RIGHT PARENTHESIS
|
| 90 |
+
'*' # 0x2A -> ASTERISK
|
| 91 |
+
'+' # 0x2B -> PLUS SIGN
|
| 92 |
+
',' # 0x2C -> COMMA
|
| 93 |
+
'-' # 0x2D -> HYPHEN-MINUS
|
| 94 |
+
'.' # 0x2E -> FULL STOP
|
| 95 |
+
'/' # 0x2F -> SOLIDUS
|
| 96 |
+
'0' # 0x30 -> DIGIT ZERO
|
| 97 |
+
'1' # 0x31 -> DIGIT ONE
|
| 98 |
+
'2' # 0x32 -> DIGIT TWO
|
| 99 |
+
'3' # 0x33 -> DIGIT THREE
|
| 100 |
+
'4' # 0x34 -> DIGIT FOUR
|
| 101 |
+
'5' # 0x35 -> DIGIT FIVE
|
| 102 |
+
'6' # 0x36 -> DIGIT SIX
|
| 103 |
+
'7' # 0x37 -> DIGIT SEVEN
|
| 104 |
+
'8' # 0x38 -> DIGIT EIGHT
|
| 105 |
+
'9' # 0x39 -> DIGIT NINE
|
| 106 |
+
':' # 0x3A -> COLON
|
| 107 |
+
';' # 0x3B -> SEMICOLON
|
| 108 |
+
'<' # 0x3C -> LESS-THAN SIGN
|
| 109 |
+
'=' # 0x3D -> EQUALS SIGN
|
| 110 |
+
'>' # 0x3E -> GREATER-THAN SIGN
|
| 111 |
+
'?' # 0x3F -> QUESTION MARK
|
| 112 |
+
'@' # 0x40 -> COMMERCIAL AT
|
| 113 |
+
'A' # 0x41 -> LATIN CAPITAL LETTER A
|
| 114 |
+
'B' # 0x42 -> LATIN CAPITAL LETTER B
|
| 115 |
+
'C' # 0x43 -> LATIN CAPITAL LETTER C
|
| 116 |
+
'D' # 0x44 -> LATIN CAPITAL LETTER D
|
| 117 |
+
'E' # 0x45 -> LATIN CAPITAL LETTER E
|
| 118 |
+
'F' # 0x46 -> LATIN CAPITAL LETTER F
|
| 119 |
+
'G' # 0x47 -> LATIN CAPITAL LETTER G
|
| 120 |
+
'H' # 0x48 -> LATIN CAPITAL LETTER H
|
| 121 |
+
'I' # 0x49 -> LATIN CAPITAL LETTER I
|
| 122 |
+
'J' # 0x4A -> LATIN CAPITAL LETTER J
|
| 123 |
+
'K' # 0x4B -> LATIN CAPITAL LETTER K
|
| 124 |
+
'L' # 0x4C -> LATIN CAPITAL LETTER L
|
| 125 |
+
'M' # 0x4D -> LATIN CAPITAL LETTER M
|
| 126 |
+
'N' # 0x4E -> LATIN CAPITAL LETTER N
|
| 127 |
+
'O' # 0x4F -> LATIN CAPITAL LETTER O
|
| 128 |
+
'P' # 0x50 -> LATIN CAPITAL LETTER P
|
| 129 |
+
'Q' # 0x51 -> LATIN CAPITAL LETTER Q
|
| 130 |
+
'R' # 0x52 -> LATIN CAPITAL LETTER R
|
| 131 |
+
'S' # 0x53 -> LATIN CAPITAL LETTER S
|
| 132 |
+
'T' # 0x54 -> LATIN CAPITAL LETTER T
|
| 133 |
+
'U' # 0x55 -> LATIN CAPITAL LETTER U
|
| 134 |
+
'V' # 0x56 -> LATIN CAPITAL LETTER V
|
| 135 |
+
'W' # 0x57 -> LATIN CAPITAL LETTER W
|
| 136 |
+
'X' # 0x58 -> LATIN CAPITAL LETTER X
|
| 137 |
+
'Y' # 0x59 -> LATIN CAPITAL LETTER Y
|
| 138 |
+
'Z' # 0x5A -> LATIN CAPITAL LETTER Z
|
| 139 |
+
'[' # 0x5B -> LEFT SQUARE BRACKET
|
| 140 |
+
'\\' # 0x5C -> REVERSE SOLIDUS
|
| 141 |
+
']' # 0x5D -> RIGHT SQUARE BRACKET
|
| 142 |
+
'^' # 0x5E -> CIRCUMFLEX ACCENT
|
| 143 |
+
'_' # 0x5F -> LOW LINE
|
| 144 |
+
'`' # 0x60 -> GRAVE ACCENT
|
| 145 |
+
'a' # 0x61 -> LATIN SMALL LETTER A
|
| 146 |
+
'b' # 0x62 -> LATIN SMALL LETTER B
|
| 147 |
+
'c' # 0x63 -> LATIN SMALL LETTER C
|
| 148 |
+
'd' # 0x64 -> LATIN SMALL LETTER D
|
| 149 |
+
'e' # 0x65 -> LATIN SMALL LETTER E
|
| 150 |
+
'f' # 0x66 -> LATIN SMALL LETTER F
|
| 151 |
+
'g' # 0x67 -> LATIN SMALL LETTER G
|
| 152 |
+
'h' # 0x68 -> LATIN SMALL LETTER H
|
| 153 |
+
'i' # 0x69 -> LATIN SMALL LETTER I
|
| 154 |
+
'j' # 0x6A -> LATIN SMALL LETTER J
|
| 155 |
+
'k' # 0x6B -> LATIN SMALL LETTER K
|
| 156 |
+
'l' # 0x6C -> LATIN SMALL LETTER L
|
| 157 |
+
'm' # 0x6D -> LATIN SMALL LETTER M
|
| 158 |
+
'n' # 0x6E -> LATIN SMALL LETTER N
|
| 159 |
+
'o' # 0x6F -> LATIN SMALL LETTER O
|
| 160 |
+
'p' # 0x70 -> LATIN SMALL LETTER P
|
| 161 |
+
'q' # 0x71 -> LATIN SMALL LETTER Q
|
| 162 |
+
'r' # 0x72 -> LATIN SMALL LETTER R
|
| 163 |
+
's' # 0x73 -> LATIN SMALL LETTER S
|
| 164 |
+
't' # 0x74 -> LATIN SMALL LETTER T
|
| 165 |
+
'u' # 0x75 -> LATIN SMALL LETTER U
|
| 166 |
+
'v' # 0x76 -> LATIN SMALL LETTER V
|
| 167 |
+
'w' # 0x77 -> LATIN SMALL LETTER W
|
| 168 |
+
'x' # 0x78 -> LATIN SMALL LETTER X
|
| 169 |
+
'y' # 0x79 -> LATIN SMALL LETTER Y
|
| 170 |
+
'z' # 0x7A -> LATIN SMALL LETTER Z
|
| 171 |
+
'{' # 0x7B -> LEFT CURLY BRACKET
|
| 172 |
+
'|' # 0x7C -> VERTICAL LINE
|
| 173 |
+
'}' # 0x7D -> RIGHT CURLY BRACKET
|
| 174 |
+
'~' # 0x7E -> TILDE
|
| 175 |
+
'\x7f' # 0x7F -> DELETE
|
| 176 |
+
'\u20ac' # 0x80 -> EURO SIGN
|
| 177 |
+
'\ufffe' # 0x81 -> UNDEFINED
|
| 178 |
+
'\u201a' # 0x82 -> SINGLE LOW-9 QUOTATION MARK
|
| 179 |
+
'\u0192' # 0x83 -> LATIN SMALL LETTER F WITH HOOK
|
| 180 |
+
'\u201e' # 0x84 -> DOUBLE LOW-9 QUOTATION MARK
|
| 181 |
+
'\u2026' # 0x85 -> HORIZONTAL ELLIPSIS
|
| 182 |
+
'\u2020' # 0x86 -> DAGGER
|
| 183 |
+
'\u2021' # 0x87 -> DOUBLE DAGGER
|
| 184 |
+
'\u02c6' # 0x88 -> MODIFIER LETTER CIRCUMFLEX ACCENT
|
| 185 |
+
'\u2030' # 0x89 -> PER MILLE SIGN
|
| 186 |
+
'\u0160' # 0x8A -> LATIN CAPITAL LETTER S WITH CARON
|
| 187 |
+
'\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK
|
| 188 |
+
'\u0152' # 0x8C -> LATIN CAPITAL LIGATURE OE
|
| 189 |
+
'\ufffe' # 0x8D -> UNDEFINED
|
| 190 |
+
'\ufffe' # 0x8E -> UNDEFINED
|
| 191 |
+
'\ufffe' # 0x8F -> UNDEFINED
|
| 192 |
+
'\ufffe' # 0x90 -> UNDEFINED
|
| 193 |
+
'\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK
|
| 194 |
+
'\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK
|
| 195 |
+
'\u201c' # 0x93 -> LEFT DOUBLE QUOTATION MARK
|
| 196 |
+
'\u201d' # 0x94 -> RIGHT DOUBLE QUOTATION MARK
|
| 197 |
+
'\u2022' # 0x95 -> BULLET
|
| 198 |
+
'\u2013' # 0x96 -> EN DASH
|
| 199 |
+
'\u2014' # 0x97 -> EM DASH
|
| 200 |
+
'\u02dc' # 0x98 -> SMALL TILDE
|
| 201 |
+
'\u2122' # 0x99 -> TRADE MARK SIGN
|
| 202 |
+
'\u0161' # 0x9A -> LATIN SMALL LETTER S WITH CARON
|
| 203 |
+
'\u203a' # 0x9B -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
|
| 204 |
+
'\u0153' # 0x9C -> LATIN SMALL LIGATURE OE
|
| 205 |
+
'\ufffe' # 0x9D -> UNDEFINED
|
| 206 |
+
'\ufffe' # 0x9E -> UNDEFINED
|
| 207 |
+
'\u0178' # 0x9F -> LATIN CAPITAL LETTER Y WITH DIAERESIS
|
| 208 |
+
'\xa0' # 0xA0 -> NO-BREAK SPACE
|
| 209 |
+
'\xa1' # 0xA1 -> INVERTED EXCLAMATION MARK
|
| 210 |
+
'\xa2' # 0xA2 -> CENT SIGN
|
| 211 |
+
'\xa3' # 0xA3 -> POUND SIGN
|
| 212 |
+
'\xa4' # 0xA4 -> CURRENCY SIGN
|
| 213 |
+
'\xa5' # 0xA5 -> YEN SIGN
|
| 214 |
+
'\xa6' # 0xA6 -> BROKEN BAR
|
| 215 |
+
'\xa7' # 0xA7 -> SECTION SIGN
|
| 216 |
+
'\xa8' # 0xA8 -> DIAERESIS
|
| 217 |
+
'\xa9' # 0xA9 -> COPYRIGHT SIGN
|
| 218 |
+
'\xaa' # 0xAA -> FEMININE ORDINAL INDICATOR
|
| 219 |
+
'\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
|
| 220 |
+
'\xac' # 0xAC -> NOT SIGN
|
| 221 |
+
'\xad' # 0xAD -> SOFT HYPHEN
|
| 222 |
+
'\xae' # 0xAE -> REGISTERED SIGN
|
| 223 |
+
'\xaf' # 0xAF -> MACRON
|
| 224 |
+
'\xb0' # 0xB0 -> DEGREE SIGN
|
| 225 |
+
'\xb1' # 0xB1 -> PLUS-MINUS SIGN
|
| 226 |
+
'\xb2' # 0xB2 -> SUPERSCRIPT TWO
|
| 227 |
+
'\xb3' # 0xB3 -> SUPERSCRIPT THREE
|
| 228 |
+
'\xb4' # 0xB4 -> ACUTE ACCENT
|
| 229 |
+
'\xb5' # 0xB5 -> MICRO SIGN
|
| 230 |
+
'\xb6' # 0xB6 -> PILCROW SIGN
|
| 231 |
+
'\xb7' # 0xB7 -> MIDDLE DOT
|
| 232 |
+
'\xb8' # 0xB8 -> CEDILLA
|
| 233 |
+
'\xb9' # 0xB9 -> SUPERSCRIPT ONE
|
| 234 |
+
'\xba' # 0xBA -> MASCULINE ORDINAL INDICATOR
|
| 235 |
+
'\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
|
| 236 |
+
'\xbc' # 0xBC -> VULGAR FRACTION ONE QUARTER
|
| 237 |
+
'\xbd' # 0xBD -> VULGAR FRACTION ONE HALF
|
| 238 |
+
'\xbe' # 0xBE -> VULGAR FRACTION THREE QUARTERS
|
| 239 |
+
'\xbf' # 0xBF -> INVERTED QUESTION MARK
|
| 240 |
+
'\xc0' # 0xC0 -> LATIN CAPITAL LETTER A WITH GRAVE
|
| 241 |
+
'\xc1' # 0xC1 -> LATIN CAPITAL LETTER A WITH ACUTE
|
| 242 |
+
'\xc2' # 0xC2 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX
|
| 243 |
+
'\xc3' # 0xC3 -> LATIN CAPITAL LETTER A WITH TILDE
|
| 244 |
+
'\xc4' # 0xC4 -> LATIN CAPITAL LETTER A WITH DIAERESIS
|
| 245 |
+
'\xc5' # 0xC5 -> LATIN CAPITAL LETTER A WITH RING ABOVE
|
| 246 |
+
'\xc6' # 0xC6 -> LATIN CAPITAL LETTER AE
|
| 247 |
+
'\xc7' # 0xC7 -> LATIN CAPITAL LETTER C WITH CEDILLA
|
| 248 |
+
'\xc8' # 0xC8 -> LATIN CAPITAL LETTER E WITH GRAVE
|
| 249 |
+
'\xc9' # 0xC9 -> LATIN CAPITAL LETTER E WITH ACUTE
|
| 250 |
+
'\xca' # 0xCA -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX
|
| 251 |
+
'\xcb' # 0xCB -> LATIN CAPITAL LETTER E WITH DIAERESIS
|
| 252 |
+
'\xcc' # 0xCC -> LATIN CAPITAL LETTER I WITH GRAVE
|
| 253 |
+
'\xcd' # 0xCD -> LATIN CAPITAL LETTER I WITH ACUTE
|
| 254 |
+
'\xce' # 0xCE -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX
|
| 255 |
+
'\xcf' # 0xCF -> LATIN CAPITAL LETTER I WITH DIAERESIS
|
| 256 |
+
'\u011e' # 0xD0 -> LATIN CAPITAL LETTER G WITH BREVE
|
| 257 |
+
'\xd1' # 0xD1 -> LATIN CAPITAL LETTER N WITH TILDE
|
| 258 |
+
'\xd2' # 0xD2 -> LATIN CAPITAL LETTER O WITH GRAVE
|
| 259 |
+
'\xd3' # 0xD3 -> LATIN CAPITAL LETTER O WITH ACUTE
|
| 260 |
+
'\xd4' # 0xD4 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX
|
| 261 |
+
'\xd5' # 0xD5 -> LATIN CAPITAL LETTER O WITH TILDE
|
| 262 |
+
'\xd6' # 0xD6 -> LATIN CAPITAL LETTER O WITH DIAERESIS
|
| 263 |
+
'\xd7' # 0xD7 -> MULTIPLICATION SIGN
|
| 264 |
+
'\xd8' # 0xD8 -> LATIN CAPITAL LETTER O WITH STROKE
|
| 265 |
+
'\xd9' # 0xD9 -> LATIN CAPITAL LETTER U WITH GRAVE
|
| 266 |
+
'\xda' # 0xDA -> LATIN CAPITAL LETTER U WITH ACUTE
|
| 267 |
+
'\xdb' # 0xDB -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX
|
| 268 |
+
'\xdc' # 0xDC -> LATIN CAPITAL LETTER U WITH DIAERESIS
|
| 269 |
+
'\u0130' # 0xDD -> LATIN CAPITAL LETTER I WITH DOT ABOVE
|
| 270 |
+
'\u015e' # 0xDE -> LATIN CAPITAL LETTER S WITH CEDILLA
|
| 271 |
+
'\xdf' # 0xDF -> LATIN SMALL LETTER SHARP S
|
| 272 |
+
'\xe0' # 0xE0 -> LATIN SMALL LETTER A WITH GRAVE
|
| 273 |
+
'\xe1' # 0xE1 -> LATIN SMALL LETTER A WITH ACUTE
|
| 274 |
+
'\xe2' # 0xE2 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
|
| 275 |
+
'\xe3' # 0xE3 -> LATIN SMALL LETTER A WITH TILDE
|
| 276 |
+
'\xe4' # 0xE4 -> LATIN SMALL LETTER A WITH DIAERESIS
|
| 277 |
+
'\xe5' # 0xE5 -> LATIN SMALL LETTER A WITH RING ABOVE
|
| 278 |
+
'\xe6' # 0xE6 -> LATIN SMALL LETTER AE
|
| 279 |
+
'\xe7' # 0xE7 -> LATIN SMALL LETTER C WITH CEDILLA
|
| 280 |
+
'\xe8' # 0xE8 -> LATIN SMALL LETTER E WITH GRAVE
|
| 281 |
+
'\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE
|
| 282 |
+
'\xea' # 0xEA -> LATIN SMALL LETTER E WITH CIRCUMFLEX
|
| 283 |
+
'\xeb' # 0xEB -> LATIN SMALL LETTER E WITH DIAERESIS
|
| 284 |
+
'\xec' # 0xEC -> LATIN SMALL LETTER I WITH GRAVE
|
| 285 |
+
'\xed' # 0xED -> LATIN SMALL LETTER I WITH ACUTE
|
| 286 |
+
'\xee' # 0xEE -> LATIN SMALL LETTER I WITH CIRCUMFLEX
|
| 287 |
+
'\xef' # 0xEF -> LATIN SMALL LETTER I WITH DIAERESIS
|
| 288 |
+
'\u011f' # 0xF0 -> LATIN SMALL LETTER G WITH BREVE
|
| 289 |
+
'\xf1' # 0xF1 -> LATIN SMALL LETTER N WITH TILDE
|
| 290 |
+
'\xf2' # 0xF2 -> LATIN SMALL LETTER O WITH GRAVE
|
| 291 |
+
'\xf3' # 0xF3 -> LATIN SMALL LETTER O WITH ACUTE
|
| 292 |
+
'\xf4' # 0xF4 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
|
| 293 |
+
'\xf5' # 0xF5 -> LATIN SMALL LETTER O WITH TILDE
|
| 294 |
+
'\xf6' # 0xF6 -> LATIN SMALL LETTER O WITH DIAERESIS
|
| 295 |
+
'\xf7' # 0xF7 -> DIVISION SIGN
|
| 296 |
+
'\xf8' # 0xF8 -> LATIN SMALL LETTER O WITH STROKE
|
| 297 |
+
'\xf9' # 0xF9 -> LATIN SMALL LETTER U WITH GRAVE
|
| 298 |
+
'\xfa' # 0xFA -> LATIN SMALL LETTER U WITH ACUTE
|
| 299 |
+
'\xfb' # 0xFB -> LATIN SMALL LETTER U WITH CIRCUMFLEX
|
| 300 |
+
'\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS
|
| 301 |
+
'\u0131' # 0xFD -> LATIN SMALL LETTER DOTLESS I
|
| 302 |
+
'\u015f' # 0xFE -> LATIN SMALL LETTER S WITH CEDILLA
|
| 303 |
+
'\xff' # 0xFF -> LATIN SMALL LETTER Y WITH DIAERESIS
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
### Encoding table
|
| 307 |
+
encoding_table=codecs.charmap_build(decoding_table)
|
shared/package-files/06/065295d14dfa8ea9e5c4ce7e3f19fc388898e6424470b96ddd0668f86b0cce56/Dawson
ADDED
|
Binary file (1.03 kB). View file
|
|
|
shared/package-files/06/0652de1cead19b444d340db8c639054e7b1fb41dce25baab5633241d5c2107c2/linalg_norm_ops.h
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API linalg_norm {
|
| 18 |
+
using schema = at::Tensor (const at::Tensor &, const c10::optional<at::Scalar> &, at::OptionalIntArrayRef, bool, c10::optional<at::ScalarType>);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_norm")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_norm(Tensor self, Scalar? ord=None, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor")
|
| 24 |
+
static at::Tensor call(const at::Tensor & self, const c10::optional<at::Scalar> & ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional<at::ScalarType> dtype);
|
| 25 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const c10::optional<at::Scalar> & ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional<at::ScalarType> dtype);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API linalg_norm_ord_str {
|
| 29 |
+
using schema = at::Tensor (const at::Tensor &, c10::string_view, at::OptionalIntArrayRef, bool, c10::optional<at::ScalarType>);
|
| 30 |
+
using ptr_schema = schema*;
|
| 31 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 32 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_norm")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ord_str")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_norm.ord_str(Tensor self, str ord, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor")
|
| 35 |
+
static at::Tensor call(const at::Tensor & self, c10::string_view ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional<at::ScalarType> dtype);
|
| 36 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::string_view ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional<at::ScalarType> dtype);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
struct TORCH_API linalg_norm_out {
|
| 40 |
+
using schema = at::Tensor & (const at::Tensor &, const c10::optional<at::Scalar> &, at::OptionalIntArrayRef, bool, c10::optional<at::ScalarType>, at::Tensor &);
|
| 41 |
+
using ptr_schema = schema*;
|
| 42 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 43 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_norm")
|
| 44 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 45 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_norm.out(Tensor self, Scalar? ord=None, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)")
|
| 46 |
+
static at::Tensor & call(const at::Tensor & self, const c10::optional<at::Scalar> & ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional<at::ScalarType> dtype, at::Tensor & out);
|
| 47 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const c10::optional<at::Scalar> & ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional<at::ScalarType> dtype, at::Tensor & out);
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
struct TORCH_API linalg_norm_ord_str_out {
|
| 51 |
+
using schema = at::Tensor & (const at::Tensor &, c10::string_view, at::OptionalIntArrayRef, bool, c10::optional<at::ScalarType>, at::Tensor &);
|
| 52 |
+
using ptr_schema = schema*;
|
| 53 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 54 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::linalg_norm")
|
| 55 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ord_str_out")
|
| 56 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_norm.ord_str_out(Tensor self, str ord, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)")
|
| 57 |
+
static at::Tensor & call(const at::Tensor & self, c10::string_view ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional<at::ScalarType> dtype, at::Tensor & out);
|
| 58 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::string_view ord, at::OptionalIntArrayRef dim, bool keepdim, c10::optional<at::ScalarType> dtype, at::Tensor & out);
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
}} // namespace at::_ops
|
shared/package-files/06/06539aac034cde1ba42acc1401fd615f521c2874306ac54869e5fe1d71be92c9/ttkpane.tcl
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ttkpane.tcl --
|
| 2 |
+
#
|
| 3 |
+
# This demonstration script creates a Ttk pane with some content.
|
| 4 |
+
|
| 5 |
+
if {![info exists widgetDemo]} {
|
| 6 |
+
error "This script should be run from the \"widget\" demo."
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
package require Tk
|
| 10 |
+
|
| 11 |
+
set w .ttkpane
|
| 12 |
+
catch {destroy $w}
|
| 13 |
+
toplevel $w
|
| 14 |
+
wm title $w "Themed Nested Panes"
|
| 15 |
+
wm iconname $w "ttkpane"
|
| 16 |
+
positionWindow $w
|
| 17 |
+
|
| 18 |
+
ttk::label $w.msg -font $font -wraplength 4i -justify left -text "This demonstration shows off a nested set of themed paned windows. Their sizes can be changed by grabbing the area between each contained pane and dragging the divider."
|
| 19 |
+
pack $w.msg [ttk::separator $w.msgSep] -side top -fill x
|
| 20 |
+
|
| 21 |
+
## See Code / Dismiss
|
| 22 |
+
pack [addSeeDismiss $w.seeDismiss $w] -side bottom -fill x
|
| 23 |
+
|
| 24 |
+
ttk::frame $w.f
|
| 25 |
+
pack $w.f -fill both -expand 1
|
| 26 |
+
set w $w.f
|
| 27 |
+
ttk::panedwindow $w.outer -orient horizontal
|
| 28 |
+
$w.outer add [ttk::panedwindow $w.outer.inLeft -orient vertical]
|
| 29 |
+
$w.outer add [ttk::panedwindow $w.outer.inRight -orient vertical]
|
| 30 |
+
$w.outer.inLeft add [ttk::labelframe $w.outer.inLeft.top -text Button]
|
| 31 |
+
$w.outer.inLeft add [ttk::labelframe $w.outer.inLeft.bot -text Clocks]
|
| 32 |
+
$w.outer.inRight add [ttk::labelframe $w.outer.inRight.top -text Progress]
|
| 33 |
+
$w.outer.inRight add [ttk::labelframe $w.outer.inRight.bot -text Text]
|
| 34 |
+
if {[tk windowingsystem] eq "aqua"} {
|
| 35 |
+
foreach i [list inLeft.top inLeft.bot inRight.top inRight.bot] {
|
| 36 |
+
$w.outer.$i configure -padding 3
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
# Fill the button pane
|
| 41 |
+
ttk::button $w.outer.inLeft.top.b -text "Press Me" -command {
|
| 42 |
+
tk_messageBox -type ok -icon info -message "Ouch!" -detail "That hurt..." \
|
| 43 |
+
-parent .ttkpane -title "Button Pressed"
|
| 44 |
+
}
|
| 45 |
+
pack $w.outer.inLeft.top.b -padx 2 -pady 5
|
| 46 |
+
|
| 47 |
+
# Fill the clocks pane
|
| 48 |
+
set i 0
|
| 49 |
+
proc every {delay script} {
|
| 50 |
+
uplevel #0 $script
|
| 51 |
+
after $delay [list every $delay $script]
|
| 52 |
+
}
|
| 53 |
+
set testzones {
|
| 54 |
+
:Europe/Berlin
|
| 55 |
+
:America/Argentina/Buenos_Aires
|
| 56 |
+
:Africa/Johannesburg
|
| 57 |
+
:Europe/London
|
| 58 |
+
:America/Los_Angeles
|
| 59 |
+
:Europe/Moscow
|
| 60 |
+
:America/New_York
|
| 61 |
+
:Asia/Singapore
|
| 62 |
+
:Australia/Sydney
|
| 63 |
+
:Asia/Tokyo
|
| 64 |
+
}
|
| 65 |
+
# Force a pre-load of all the timezones needed; otherwise can end up
|
| 66 |
+
# poor-looking synch problems!
|
| 67 |
+
set zones {}
|
| 68 |
+
foreach zone $testzones {
|
| 69 |
+
if {![catch {clock format 0 -timezone $zone}]} {
|
| 70 |
+
lappend zones $zone
|
| 71 |
+
}
|
| 72 |
+
}
|
| 73 |
+
if {[llength $zones] < 2} { lappend zones -0200 :GMT :UTC +0200 }
|
| 74 |
+
foreach zone $zones {
|
| 75 |
+
set city [string map {_ " "} [regexp -inline {[^/]+$} $zone]]
|
| 76 |
+
if {$i} {
|
| 77 |
+
pack [ttk::separator $w.outer.inLeft.bot.s$i] -fill x
|
| 78 |
+
}
|
| 79 |
+
ttk::label $w.outer.inLeft.bot.l$i -text $city -anchor w
|
| 80 |
+
ttk::label $w.outer.inLeft.bot.t$i -textvariable time($zone) -anchor w
|
| 81 |
+
pack $w.outer.inLeft.bot.l$i $w.outer.inLeft.bot.t$i -fill x
|
| 82 |
+
every 1000 "set time($zone) \[clock format \[clock seconds\] -timezone $zone -format %T\]"
|
| 83 |
+
incr i
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
# Fill the progress pane
|
| 87 |
+
ttk::progressbar $w.outer.inRight.top.progress -mode indeterminate
|
| 88 |
+
pack $w.outer.inRight.top.progress -fill both -expand 1
|
| 89 |
+
$w.outer.inRight.top.progress start
|
| 90 |
+
|
| 91 |
+
# Fill the text pane
|
| 92 |
+
if {[tk windowingsystem] ne "aqua"} {
|
| 93 |
+
# The trick with the ttk::frame makes the text widget look like it fits with
|
| 94 |
+
# the current Ttk theme despite not being a themed widget itself. It is done
|
| 95 |
+
# by styling the frame like an entry, turning off the border in the text
|
| 96 |
+
# widget, and putting the text widget in the frame with enough space to allow
|
| 97 |
+
# the surrounding border to show through (2 pixels seems to be enough).
|
| 98 |
+
ttk::frame $w.outer.inRight.bot.f -style TEntry
|
| 99 |
+
text $w.txt -wrap word -yscroll "$w.sb set" -width 30 -borderwidth 0
|
| 100 |
+
pack $w.txt -fill both -expand 1 -in $w.outer.inRight.bot.f -pady 2 -padx 2
|
| 101 |
+
ttk::scrollbar $w.sb -orient vertical -command "$w.txt yview"
|
| 102 |
+
pack $w.sb -side right -fill y -in $w.outer.inRight.bot
|
| 103 |
+
pack $w.outer.inRight.bot.f -fill both -expand 1
|
| 104 |
+
pack $w.outer -fill both -expand 1
|
| 105 |
+
} else {
|
| 106 |
+
text $w.txt -wrap word -yscroll "$w.sb set" -width 30 -borderwidth 0
|
| 107 |
+
ttk::scrollbar $w.sb -orient vertical -command "$w.txt yview"
|
| 108 |
+
pack $w.sb -side right -fill y -in $w.outer.inRight.bot
|
| 109 |
+
pack $w.txt -fill both -expand 1 -in $w.outer.inRight.bot
|
| 110 |
+
pack $w.outer -fill both -expand 1 -padx 10 -pady {6 10}
|
| 111 |
+
}
|
| 112 |
+
|
shared/package-files/06/065a77e08b2cf3ba737881076f45f3fa301f3b3c694fe3629c6e8b8d73594979/METADATA
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: requests
|
| 3 |
+
Version: 2.31.0
|
| 4 |
+
Summary: Python HTTP for Humans.
|
| 5 |
+
Home-page: https://requests.readthedocs.io
|
| 6 |
+
Author: Kenneth Reitz
|
| 7 |
+
Author-email: me@kennethreitz.org
|
| 8 |
+
License: Apache 2.0
|
| 9 |
+
Project-URL: Documentation, https://requests.readthedocs.io
|
| 10 |
+
Project-URL: Source, https://github.com/psf/requests
|
| 11 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 12 |
+
Classifier: Environment :: Web Environment
|
| 13 |
+
Classifier: Intended Audience :: Developers
|
| 14 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
| 15 |
+
Classifier: Natural Language :: English
|
| 16 |
+
Classifier: Operating System :: OS Independent
|
| 17 |
+
Classifier: Programming Language :: Python
|
| 18 |
+
Classifier: Programming Language :: Python :: 3
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.7
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 24 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 25 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 26 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 27 |
+
Classifier: Topic :: Internet :: WWW/HTTP
|
| 28 |
+
Classifier: Topic :: Software Development :: Libraries
|
| 29 |
+
Requires-Python: >=3.7
|
| 30 |
+
Description-Content-Type: text/markdown
|
| 31 |
+
License-File: LICENSE
|
| 32 |
+
Requires-Dist: charset-normalizer <4,>=2
|
| 33 |
+
Requires-Dist: idna <4,>=2.5
|
| 34 |
+
Requires-Dist: urllib3 <3,>=1.21.1
|
| 35 |
+
Requires-Dist: certifi >=2017.4.17
|
| 36 |
+
Provides-Extra: security
|
| 37 |
+
Provides-Extra: socks
|
| 38 |
+
Requires-Dist: PySocks !=1.5.7,>=1.5.6 ; extra == 'socks'
|
| 39 |
+
Provides-Extra: use_chardet_on_py3
|
| 40 |
+
Requires-Dist: chardet <6,>=3.0.2 ; extra == 'use_chardet_on_py3'
|
| 41 |
+
|
| 42 |
+
# Requests
|
| 43 |
+
|
| 44 |
+
**Requests** is a simple, yet elegant, HTTP library.
|
| 45 |
+
|
| 46 |
+
```python
|
| 47 |
+
>>> import requests
|
| 48 |
+
>>> r = requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass'))
|
| 49 |
+
>>> r.status_code
|
| 50 |
+
200
|
| 51 |
+
>>> r.headers['content-type']
|
| 52 |
+
'application/json; charset=utf8'
|
| 53 |
+
>>> r.encoding
|
| 54 |
+
'utf-8'
|
| 55 |
+
>>> r.text
|
| 56 |
+
'{"authenticated": true, ...'
|
| 57 |
+
>>> r.json()
|
| 58 |
+
{'authenticated': True, ...}
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs, or to form-encode your `PUT` & `POST` data — but nowadays, just use the `json` method!
|
| 62 |
+
|
| 63 |
+
Requests is one of the most downloaded Python packages today, pulling in around `30M downloads / week`— according to GitHub, Requests is currently [depended upon](https://github.com/psf/requests/network/dependents?package_id=UGFja2FnZS01NzA4OTExNg%3D%3D) by `1,000,000+` repositories. You may certainly put your trust in this code.
|
| 64 |
+
|
| 65 |
+
[](https://pepy.tech/project/requests)
|
| 66 |
+
[](https://pypi.org/project/requests)
|
| 67 |
+
[](https://github.com/psf/requests/graphs/contributors)
|
| 68 |
+
|
| 69 |
+
## Installing Requests and Supported Versions
|
| 70 |
+
|
| 71 |
+
Requests is available on PyPI:
|
| 72 |
+
|
| 73 |
+
```console
|
| 74 |
+
$ python -m pip install requests
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
Requests officially supports Python 3.7+.
|
| 78 |
+
|
| 79 |
+
## Supported Features & Best–Practices
|
| 80 |
+
|
| 81 |
+
Requests is ready for the demands of building robust and reliable HTTP–speaking applications, for the needs of today.
|
| 82 |
+
|
| 83 |
+
- Keep-Alive & Connection Pooling
|
| 84 |
+
- International Domains and URLs
|
| 85 |
+
- Sessions with Cookie Persistence
|
| 86 |
+
- Browser-style TLS/SSL Verification
|
| 87 |
+
- Basic & Digest Authentication
|
| 88 |
+
- Familiar `dict`–like Cookies
|
| 89 |
+
- Automatic Content Decompression and Decoding
|
| 90 |
+
- Multi-part File Uploads
|
| 91 |
+
- SOCKS Proxy Support
|
| 92 |
+
- Connection Timeouts
|
| 93 |
+
- Streaming Downloads
|
| 94 |
+
- Automatic honoring of `.netrc`
|
| 95 |
+
- Chunked HTTP Requests
|
| 96 |
+
|
| 97 |
+
## API Reference and User Guide available on [Read the Docs](https://requests.readthedocs.io)
|
| 98 |
+
|
| 99 |
+
[](https://requests.readthedocs.io)
|
| 100 |
+
|
| 101 |
+
## Cloning the repository
|
| 102 |
+
|
| 103 |
+
When cloning the Requests repository, you may need to add the `-c
|
| 104 |
+
fetch.fsck.badTimezone=ignore` flag to avoid an error about a bad commit (see
|
| 105 |
+
[this issue](https://github.com/psf/requests/issues/2690) for more background):
|
| 106 |
+
|
| 107 |
+
```shell
|
| 108 |
+
git clone -c fetch.fsck.badTimezone=ignore https://github.com/psf/requests.git
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
You can also apply this setting to your global Git config:
|
| 112 |
+
|
| 113 |
+
```shell
|
| 114 |
+
git config --global fetch.fsck.badTimezone ignore
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
---
|
| 118 |
+
|
| 119 |
+
[](https://kennethreitz.org) [](https://www.python.org/psf)
|
shared/package-files/06/065c39bcfce917a75c4f2be1391b08c2c9ab2bf8c89311f78786172c4d1d5941/METADATA
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: jsonschema
|
| 3 |
+
Version: 4.19.2
|
| 4 |
+
Summary: An implementation of JSON Schema validation for Python
|
| 5 |
+
Project-URL: Documentation, https://python-jsonschema.readthedocs.io/
|
| 6 |
+
Project-URL: Homepage, https://github.com/python-jsonschema/jsonschema
|
| 7 |
+
Project-URL: Issues, https://github.com/python-jsonschema/jsonschema/issues/
|
| 8 |
+
Project-URL: Funding, https://github.com/sponsors/Julian
|
| 9 |
+
Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-jsonschema?utm_source=pypi-jsonschema&utm_medium=referral&utm_campaign=pypi-link
|
| 10 |
+
Project-URL: Changelog, https://github.com/python-jsonschema/jsonschema/blob/main/CHANGELOG.rst
|
| 11 |
+
Project-URL: Source, https://github.com/python-jsonschema/jsonschema
|
| 12 |
+
Author: Julian Berman
|
| 13 |
+
Author-email: Julian+jsonschema@GrayVines.com
|
| 14 |
+
License: MIT
|
| 15 |
+
License-File: COPYING
|
| 16 |
+
Keywords: data validation,json,jsonschema,validation
|
| 17 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 18 |
+
Classifier: Intended Audience :: Developers
|
| 19 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 20 |
+
Classifier: Operating System :: OS Independent
|
| 21 |
+
Classifier: Programming Language :: Python
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 26 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 27 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 28 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 29 |
+
Classifier: Topic :: File Formats :: JSON
|
| 30 |
+
Classifier: Topic :: File Formats :: JSON :: JSON Schema
|
| 31 |
+
Requires-Python: >=3.8
|
| 32 |
+
Requires-Dist: attrs>=22.2.0
|
| 33 |
+
Requires-Dist: importlib-resources>=1.4.0; python_version < '3.9'
|
| 34 |
+
Requires-Dist: jsonschema-specifications>=2023.03.6
|
| 35 |
+
Requires-Dist: pkgutil-resolve-name>=1.3.10; python_version < '3.9'
|
| 36 |
+
Requires-Dist: referencing>=0.28.4
|
| 37 |
+
Requires-Dist: rpds-py>=0.7.1
|
| 38 |
+
Provides-Extra: format
|
| 39 |
+
Requires-Dist: fqdn; extra == 'format'
|
| 40 |
+
Requires-Dist: idna; extra == 'format'
|
| 41 |
+
Requires-Dist: isoduration; extra == 'format'
|
| 42 |
+
Requires-Dist: jsonpointer>1.13; extra == 'format'
|
| 43 |
+
Requires-Dist: rfc3339-validator; extra == 'format'
|
| 44 |
+
Requires-Dist: rfc3987; extra == 'format'
|
| 45 |
+
Requires-Dist: uri-template; extra == 'format'
|
| 46 |
+
Requires-Dist: webcolors>=1.11; extra == 'format'
|
| 47 |
+
Provides-Extra: format-nongpl
|
| 48 |
+
Requires-Dist: fqdn; extra == 'format-nongpl'
|
| 49 |
+
Requires-Dist: idna; extra == 'format-nongpl'
|
| 50 |
+
Requires-Dist: isoduration; extra == 'format-nongpl'
|
| 51 |
+
Requires-Dist: jsonpointer>1.13; extra == 'format-nongpl'
|
| 52 |
+
Requires-Dist: rfc3339-validator; extra == 'format-nongpl'
|
| 53 |
+
Requires-Dist: rfc3986-validator>0.1.0; extra == 'format-nongpl'
|
| 54 |
+
Requires-Dist: uri-template; extra == 'format-nongpl'
|
| 55 |
+
Requires-Dist: webcolors>=1.11; extra == 'format-nongpl'
|
shared/package-files/06/065d481c6f109875b7d9e7686ef29f9440b857127e998896ebbe3961b4008abe/test_json_table_schema.py
ADDED
|
@@ -0,0 +1,873 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for Table Schema integration."""
|
| 2 |
+
from collections import OrderedDict
|
| 3 |
+
from io import StringIO
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from pandas.core.dtypes.dtypes import (
|
| 10 |
+
CategoricalDtype,
|
| 11 |
+
DatetimeTZDtype,
|
| 12 |
+
PeriodDtype,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
import pandas as pd
|
| 16 |
+
from pandas import DataFrame
|
| 17 |
+
import pandas._testing as tm
|
| 18 |
+
|
| 19 |
+
from pandas.io.json._table_schema import (
|
| 20 |
+
as_json_table_type,
|
| 21 |
+
build_table_schema,
|
| 22 |
+
convert_json_field_to_pandas_type,
|
| 23 |
+
convert_pandas_type_to_json_field,
|
| 24 |
+
set_default_names,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@pytest.fixture
|
| 29 |
+
def df_schema():
|
| 30 |
+
return DataFrame(
|
| 31 |
+
{
|
| 32 |
+
"A": [1, 2, 3, 4],
|
| 33 |
+
"B": ["a", "b", "c", "c"],
|
| 34 |
+
"C": pd.date_range("2016-01-01", freq="d", periods=4),
|
| 35 |
+
"D": pd.timedelta_range("1h", periods=4, freq="min"),
|
| 36 |
+
},
|
| 37 |
+
index=pd.Index(range(4), name="idx"),
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@pytest.fixture
|
| 42 |
+
def df_table():
|
| 43 |
+
return DataFrame(
|
| 44 |
+
{
|
| 45 |
+
"A": [1, 2, 3, 4],
|
| 46 |
+
"B": ["a", "b", "c", "c"],
|
| 47 |
+
"C": pd.date_range("2016-01-01", freq="d", periods=4),
|
| 48 |
+
"D": pd.timedelta_range("1h", periods=4, freq="min"),
|
| 49 |
+
"E": pd.Series(pd.Categorical(["a", "b", "c", "c"])),
|
| 50 |
+
"F": pd.Series(pd.Categorical(["a", "b", "c", "c"], ordered=True)),
|
| 51 |
+
"G": [1.0, 2.0, 3, 4.0],
|
| 52 |
+
"H": pd.date_range("2016-01-01", freq="d", periods=4, tz="US/Central"),
|
| 53 |
+
},
|
| 54 |
+
index=pd.Index(range(4), name="idx"),
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class TestBuildSchema:
|
| 59 |
+
def test_build_table_schema(self, df_schema, using_infer_string):
|
| 60 |
+
result = build_table_schema(df_schema, version=False)
|
| 61 |
+
expected = {
|
| 62 |
+
"fields": [
|
| 63 |
+
{"name": "idx", "type": "integer"},
|
| 64 |
+
{"name": "A", "type": "integer"},
|
| 65 |
+
{"name": "B", "type": "string"},
|
| 66 |
+
{"name": "C", "type": "datetime"},
|
| 67 |
+
{"name": "D", "type": "duration"},
|
| 68 |
+
],
|
| 69 |
+
"primaryKey": ["idx"],
|
| 70 |
+
}
|
| 71 |
+
if using_infer_string:
|
| 72 |
+
expected["fields"][2] = {"name": "B", "type": "string", "extDtype": "str"}
|
| 73 |
+
assert result == expected
|
| 74 |
+
result = build_table_schema(df_schema)
|
| 75 |
+
assert "pandas_version" in result
|
| 76 |
+
|
| 77 |
+
def test_series(self):
|
| 78 |
+
s = pd.Series([1, 2, 3], name="foo")
|
| 79 |
+
result = build_table_schema(s, version=False)
|
| 80 |
+
expected = {
|
| 81 |
+
"fields": [
|
| 82 |
+
{"name": "index", "type": "integer"},
|
| 83 |
+
{"name": "foo", "type": "integer"},
|
| 84 |
+
],
|
| 85 |
+
"primaryKey": ["index"],
|
| 86 |
+
}
|
| 87 |
+
assert result == expected
|
| 88 |
+
result = build_table_schema(s)
|
| 89 |
+
assert "pandas_version" in result
|
| 90 |
+
|
| 91 |
+
def test_series_unnamed(self):
|
| 92 |
+
result = build_table_schema(pd.Series([1, 2, 3]), version=False)
|
| 93 |
+
expected = {
|
| 94 |
+
"fields": [
|
| 95 |
+
{"name": "index", "type": "integer"},
|
| 96 |
+
{"name": "values", "type": "integer"},
|
| 97 |
+
],
|
| 98 |
+
"primaryKey": ["index"],
|
| 99 |
+
}
|
| 100 |
+
assert result == expected
|
| 101 |
+
|
| 102 |
+
def test_multiindex(self, df_schema, using_infer_string):
|
| 103 |
+
df = df_schema
|
| 104 |
+
idx = pd.MultiIndex.from_product([("a", "b"), (1, 2)])
|
| 105 |
+
df.index = idx
|
| 106 |
+
|
| 107 |
+
result = build_table_schema(df, version=False)
|
| 108 |
+
expected = {
|
| 109 |
+
"fields": [
|
| 110 |
+
{"name": "level_0", "type": "string"},
|
| 111 |
+
{"name": "level_1", "type": "integer"},
|
| 112 |
+
{"name": "A", "type": "integer"},
|
| 113 |
+
{"name": "B", "type": "string"},
|
| 114 |
+
{"name": "C", "type": "datetime"},
|
| 115 |
+
{"name": "D", "type": "duration"},
|
| 116 |
+
],
|
| 117 |
+
"primaryKey": ["level_0", "level_1"],
|
| 118 |
+
}
|
| 119 |
+
if using_infer_string:
|
| 120 |
+
expected["fields"][0] = {
|
| 121 |
+
"name": "level_0",
|
| 122 |
+
"type": "string",
|
| 123 |
+
"extDtype": "str",
|
| 124 |
+
}
|
| 125 |
+
expected["fields"][3] = {"name": "B", "type": "string", "extDtype": "str"}
|
| 126 |
+
assert result == expected
|
| 127 |
+
|
| 128 |
+
df.index.names = ["idx0", None]
|
| 129 |
+
expected["fields"][0]["name"] = "idx0"
|
| 130 |
+
expected["primaryKey"] = ["idx0", "level_1"]
|
| 131 |
+
result = build_table_schema(df, version=False)
|
| 132 |
+
assert result == expected
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class TestTableSchemaType:
|
| 136 |
+
@pytest.mark.parametrize("int_type", [int, np.int16, np.int32, np.int64])
|
| 137 |
+
def test_as_json_table_type_int_data(self, int_type):
|
| 138 |
+
int_data = [1, 2, 3]
|
| 139 |
+
assert as_json_table_type(np.array(int_data, dtype=int_type).dtype) == "integer"
|
| 140 |
+
|
| 141 |
+
@pytest.mark.parametrize("float_type", [float, np.float16, np.float32, np.float64])
|
| 142 |
+
def test_as_json_table_type_float_data(self, float_type):
|
| 143 |
+
float_data = [1.0, 2.0, 3.0]
|
| 144 |
+
assert (
|
| 145 |
+
as_json_table_type(np.array(float_data, dtype=float_type).dtype) == "number"
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
@pytest.mark.parametrize("bool_type", [bool, np.bool_])
|
| 149 |
+
def test_as_json_table_type_bool_data(self, bool_type):
|
| 150 |
+
bool_data = [True, False]
|
| 151 |
+
assert (
|
| 152 |
+
as_json_table_type(np.array(bool_data, dtype=bool_type).dtype) == "boolean"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
@pytest.mark.parametrize(
|
| 156 |
+
"date_data",
|
| 157 |
+
[
|
| 158 |
+
pd.to_datetime(["2016"]),
|
| 159 |
+
pd.to_datetime(["2016"], utc=True),
|
| 160 |
+
pd.Series(pd.to_datetime(["2016"])),
|
| 161 |
+
pd.Series(pd.to_datetime(["2016"], utc=True)),
|
| 162 |
+
pd.period_range("2016", freq="Y", periods=3),
|
| 163 |
+
],
|
| 164 |
+
)
|
| 165 |
+
def test_as_json_table_type_date_data(self, date_data):
|
| 166 |
+
assert as_json_table_type(date_data.dtype) == "datetime"
|
| 167 |
+
|
| 168 |
+
@pytest.mark.parametrize(
|
| 169 |
+
"str_data",
|
| 170 |
+
[pd.Series(["a", "b"], dtype=object), pd.Index(["a", "b"], dtype=object)],
|
| 171 |
+
)
|
| 172 |
+
def test_as_json_table_type_string_data(self, str_data):
|
| 173 |
+
assert as_json_table_type(str_data.dtype) == "string"
|
| 174 |
+
|
| 175 |
+
@pytest.mark.parametrize(
|
| 176 |
+
"cat_data",
|
| 177 |
+
[
|
| 178 |
+
pd.Categorical(["a"]),
|
| 179 |
+
pd.Categorical([1]),
|
| 180 |
+
pd.Series(pd.Categorical([1])),
|
| 181 |
+
pd.CategoricalIndex([1]),
|
| 182 |
+
pd.Categorical([1]),
|
| 183 |
+
],
|
| 184 |
+
)
|
| 185 |
+
def test_as_json_table_type_categorical_data(self, cat_data):
|
| 186 |
+
assert as_json_table_type(cat_data.dtype) == "any"
|
| 187 |
+
|
| 188 |
+
# ------
|
| 189 |
+
# dtypes
|
| 190 |
+
# ------
|
| 191 |
+
@pytest.mark.parametrize("int_dtype", [int, np.int16, np.int32, np.int64])
|
| 192 |
+
def test_as_json_table_type_int_dtypes(self, int_dtype):
|
| 193 |
+
assert as_json_table_type(int_dtype) == "integer"
|
| 194 |
+
|
| 195 |
+
@pytest.mark.parametrize("float_dtype", [float, np.float16, np.float32, np.float64])
|
| 196 |
+
def test_as_json_table_type_float_dtypes(self, float_dtype):
|
| 197 |
+
assert as_json_table_type(float_dtype) == "number"
|
| 198 |
+
|
| 199 |
+
@pytest.mark.parametrize("bool_dtype", [bool, np.bool_])
|
| 200 |
+
def test_as_json_table_type_bool_dtypes(self, bool_dtype):
|
| 201 |
+
assert as_json_table_type(bool_dtype) == "boolean"
|
| 202 |
+
|
| 203 |
+
@pytest.mark.parametrize(
|
| 204 |
+
"date_dtype",
|
| 205 |
+
[
|
| 206 |
+
np.dtype("<M8[ns]"),
|
| 207 |
+
PeriodDtype("D"),
|
| 208 |
+
DatetimeTZDtype("ns", "US/Central"),
|
| 209 |
+
],
|
| 210 |
+
)
|
| 211 |
+
def test_as_json_table_type_date_dtypes(self, date_dtype):
|
| 212 |
+
# TODO: datedate.date? datetime.time?
|
| 213 |
+
assert as_json_table_type(date_dtype) == "datetime"
|
| 214 |
+
|
| 215 |
+
@pytest.mark.parametrize("td_dtype", [np.dtype("<m8[ns]")])
|
| 216 |
+
def test_as_json_table_type_timedelta_dtypes(self, td_dtype):
|
| 217 |
+
assert as_json_table_type(td_dtype) == "duration"
|
| 218 |
+
|
| 219 |
+
@pytest.mark.parametrize("str_dtype", [object]) # TODO(GH#14904) flesh out dtypes?
|
| 220 |
+
def test_as_json_table_type_string_dtypes(self, str_dtype):
|
| 221 |
+
assert as_json_table_type(str_dtype) == "string"
|
| 222 |
+
|
| 223 |
+
def test_as_json_table_type_categorical_dtypes(self):
|
| 224 |
+
assert as_json_table_type(pd.Categorical(["a"]).dtype) == "any"
|
| 225 |
+
assert as_json_table_type(CategoricalDtype()) == "any"
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class TestTableOrient:
|
| 229 |
+
def test_build_series(self):
|
| 230 |
+
s = pd.Series([1, 2], name="a")
|
| 231 |
+
s.index.name = "id"
|
| 232 |
+
result = s.to_json(orient="table", date_format="iso")
|
| 233 |
+
result = json.loads(result, object_pairs_hook=OrderedDict)
|
| 234 |
+
|
| 235 |
+
assert "pandas_version" in result["schema"]
|
| 236 |
+
result["schema"].pop("pandas_version")
|
| 237 |
+
|
| 238 |
+
fields = [{"name": "id", "type": "integer"}, {"name": "a", "type": "integer"}]
|
| 239 |
+
|
| 240 |
+
schema = {"fields": fields, "primaryKey": ["id"]}
|
| 241 |
+
|
| 242 |
+
expected = OrderedDict(
|
| 243 |
+
[
|
| 244 |
+
("schema", schema),
|
| 245 |
+
(
|
| 246 |
+
"data",
|
| 247 |
+
[
|
| 248 |
+
OrderedDict([("id", 0), ("a", 1)]),
|
| 249 |
+
OrderedDict([("id", 1), ("a", 2)]),
|
| 250 |
+
],
|
| 251 |
+
),
|
| 252 |
+
]
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
assert result == expected
|
| 256 |
+
|
| 257 |
+
def test_read_json_from_to_json_results(self):
|
| 258 |
+
# GH32383
|
| 259 |
+
df = DataFrame(
|
| 260 |
+
{
|
| 261 |
+
"_id": {"row_0": 0},
|
| 262 |
+
"category": {"row_0": "Goods"},
|
| 263 |
+
"recommender_id": {"row_0": 3},
|
| 264 |
+
"recommender_name_jp": {"row_0": "浦田"},
|
| 265 |
+
"recommender_name_en": {"row_0": "Urata"},
|
| 266 |
+
"name_jp": {"row_0": "博多人形(松尾吉将まつお よしまさ)"},
|
| 267 |
+
"name_en": {"row_0": "Hakata Dolls Matsuo"},
|
| 268 |
+
}
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
result1 = pd.read_json(StringIO(df.to_json()))
|
| 272 |
+
result2 = DataFrame.from_dict(json.loads(df.to_json()))
|
| 273 |
+
tm.assert_frame_equal(result1, df)
|
| 274 |
+
tm.assert_frame_equal(result2, df)
|
| 275 |
+
|
| 276 |
+
def test_to_json(self, df_table, using_infer_string):
|
| 277 |
+
df = df_table
|
| 278 |
+
df.index.name = "idx"
|
| 279 |
+
result = df.to_json(orient="table", date_format="iso")
|
| 280 |
+
result = json.loads(result, object_pairs_hook=OrderedDict)
|
| 281 |
+
|
| 282 |
+
assert "pandas_version" in result["schema"]
|
| 283 |
+
result["schema"].pop("pandas_version")
|
| 284 |
+
|
| 285 |
+
fields = [
|
| 286 |
+
{"name": "idx", "type": "integer"},
|
| 287 |
+
{"name": "A", "type": "integer"},
|
| 288 |
+
{"name": "B", "type": "string"},
|
| 289 |
+
{"name": "C", "type": "datetime"},
|
| 290 |
+
{"name": "D", "type": "duration"},
|
| 291 |
+
{
|
| 292 |
+
"constraints": {"enum": ["a", "b", "c"]},
|
| 293 |
+
"name": "E",
|
| 294 |
+
"ordered": False,
|
| 295 |
+
"type": "any",
|
| 296 |
+
},
|
| 297 |
+
{
|
| 298 |
+
"constraints": {"enum": ["a", "b", "c"]},
|
| 299 |
+
"name": "F",
|
| 300 |
+
"ordered": True,
|
| 301 |
+
"type": "any",
|
| 302 |
+
},
|
| 303 |
+
{"name": "G", "type": "number"},
|
| 304 |
+
{"name": "H", "type": "datetime", "tz": "US/Central"},
|
| 305 |
+
]
|
| 306 |
+
|
| 307 |
+
if using_infer_string:
|
| 308 |
+
fields[2] = {"name": "B", "type": "string", "extDtype": "str"}
|
| 309 |
+
|
| 310 |
+
schema = {"fields": fields, "primaryKey": ["idx"]}
|
| 311 |
+
data = [
|
| 312 |
+
OrderedDict(
|
| 313 |
+
[
|
| 314 |
+
("idx", 0),
|
| 315 |
+
("A", 1),
|
| 316 |
+
("B", "a"),
|
| 317 |
+
("C", "2016-01-01T00:00:00.000"),
|
| 318 |
+
("D", "P0DT1H0M0S"),
|
| 319 |
+
("E", "a"),
|
| 320 |
+
("F", "a"),
|
| 321 |
+
("G", 1.0),
|
| 322 |
+
("H", "2016-01-01T06:00:00.000Z"),
|
| 323 |
+
]
|
| 324 |
+
),
|
| 325 |
+
OrderedDict(
|
| 326 |
+
[
|
| 327 |
+
("idx", 1),
|
| 328 |
+
("A", 2),
|
| 329 |
+
("B", "b"),
|
| 330 |
+
("C", "2016-01-02T00:00:00.000"),
|
| 331 |
+
("D", "P0DT1H1M0S"),
|
| 332 |
+
("E", "b"),
|
| 333 |
+
("F", "b"),
|
| 334 |
+
("G", 2.0),
|
| 335 |
+
("H", "2016-01-02T06:00:00.000Z"),
|
| 336 |
+
]
|
| 337 |
+
),
|
| 338 |
+
OrderedDict(
|
| 339 |
+
[
|
| 340 |
+
("idx", 2),
|
| 341 |
+
("A", 3),
|
| 342 |
+
("B", "c"),
|
| 343 |
+
("C", "2016-01-03T00:00:00.000"),
|
| 344 |
+
("D", "P0DT1H2M0S"),
|
| 345 |
+
("E", "c"),
|
| 346 |
+
("F", "c"),
|
| 347 |
+
("G", 3.0),
|
| 348 |
+
("H", "2016-01-03T06:00:00.000Z"),
|
| 349 |
+
]
|
| 350 |
+
),
|
| 351 |
+
OrderedDict(
|
| 352 |
+
[
|
| 353 |
+
("idx", 3),
|
| 354 |
+
("A", 4),
|
| 355 |
+
("B", "c"),
|
| 356 |
+
("C", "2016-01-04T00:00:00.000"),
|
| 357 |
+
("D", "P0DT1H3M0S"),
|
| 358 |
+
("E", "c"),
|
| 359 |
+
("F", "c"),
|
| 360 |
+
("G", 4.0),
|
| 361 |
+
("H", "2016-01-04T06:00:00.000Z"),
|
| 362 |
+
]
|
| 363 |
+
),
|
| 364 |
+
]
|
| 365 |
+
expected = OrderedDict([("schema", schema), ("data", data)])
|
| 366 |
+
|
| 367 |
+
assert result == expected
|
| 368 |
+
|
| 369 |
+
def test_to_json_float_index(self):
|
| 370 |
+
data = pd.Series(1, index=[1.0, 2.0])
|
| 371 |
+
result = data.to_json(orient="table", date_format="iso")
|
| 372 |
+
result = json.loads(result, object_pairs_hook=OrderedDict)
|
| 373 |
+
result["schema"].pop("pandas_version")
|
| 374 |
+
|
| 375 |
+
expected = OrderedDict(
|
| 376 |
+
[
|
| 377 |
+
(
|
| 378 |
+
"schema",
|
| 379 |
+
{
|
| 380 |
+
"fields": [
|
| 381 |
+
{"name": "index", "type": "number"},
|
| 382 |
+
{"name": "values", "type": "integer"},
|
| 383 |
+
],
|
| 384 |
+
"primaryKey": ["index"],
|
| 385 |
+
},
|
| 386 |
+
),
|
| 387 |
+
(
|
| 388 |
+
"data",
|
| 389 |
+
[
|
| 390 |
+
OrderedDict([("index", 1.0), ("values", 1)]),
|
| 391 |
+
OrderedDict([("index", 2.0), ("values", 1)]),
|
| 392 |
+
],
|
| 393 |
+
),
|
| 394 |
+
]
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
assert result == expected
|
| 398 |
+
|
| 399 |
+
def test_to_json_period_index(self):
|
| 400 |
+
idx = pd.period_range("2016", freq="Q-JAN", periods=2)
|
| 401 |
+
data = pd.Series(1, idx)
|
| 402 |
+
result = data.to_json(orient="table", date_format="iso")
|
| 403 |
+
result = json.loads(result, object_pairs_hook=OrderedDict)
|
| 404 |
+
result["schema"].pop("pandas_version")
|
| 405 |
+
|
| 406 |
+
fields = [
|
| 407 |
+
{"freq": "QE-JAN", "name": "index", "type": "datetime"},
|
| 408 |
+
{"name": "values", "type": "integer"},
|
| 409 |
+
]
|
| 410 |
+
|
| 411 |
+
schema = {"fields": fields, "primaryKey": ["index"]}
|
| 412 |
+
data = [
|
| 413 |
+
OrderedDict([("index", "2015-11-01T00:00:00.000"), ("values", 1)]),
|
| 414 |
+
OrderedDict([("index", "2016-02-01T00:00:00.000"), ("values", 1)]),
|
| 415 |
+
]
|
| 416 |
+
expected = OrderedDict([("schema", schema), ("data", data)])
|
| 417 |
+
|
| 418 |
+
assert result == expected
|
| 419 |
+
|
| 420 |
+
def test_to_json_categorical_index(self):
|
| 421 |
+
data = pd.Series(1, pd.CategoricalIndex(["a", "b"]))
|
| 422 |
+
result = data.to_json(orient="table", date_format="iso")
|
| 423 |
+
result = json.loads(result, object_pairs_hook=OrderedDict)
|
| 424 |
+
result["schema"].pop("pandas_version")
|
| 425 |
+
|
| 426 |
+
expected = OrderedDict(
|
| 427 |
+
[
|
| 428 |
+
(
|
| 429 |
+
"schema",
|
| 430 |
+
{
|
| 431 |
+
"fields": [
|
| 432 |
+
{
|
| 433 |
+
"name": "index",
|
| 434 |
+
"type": "any",
|
| 435 |
+
"constraints": {"enum": ["a", "b"]},
|
| 436 |
+
"ordered": False,
|
| 437 |
+
},
|
| 438 |
+
{"name": "values", "type": "integer"},
|
| 439 |
+
],
|
| 440 |
+
"primaryKey": ["index"],
|
| 441 |
+
},
|
| 442 |
+
),
|
| 443 |
+
(
|
| 444 |
+
"data",
|
| 445 |
+
[
|
| 446 |
+
OrderedDict([("index", "a"), ("values", 1)]),
|
| 447 |
+
OrderedDict([("index", "b"), ("values", 1)]),
|
| 448 |
+
],
|
| 449 |
+
),
|
| 450 |
+
]
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
assert result == expected
|
| 454 |
+
|
| 455 |
+
def test_date_format_raises(self, df_table):
|
| 456 |
+
msg = (
|
| 457 |
+
"Trying to write with `orient='table'` and `date_format='epoch'`. Table "
|
| 458 |
+
"Schema requires dates to be formatted with `date_format='iso'`"
|
| 459 |
+
)
|
| 460 |
+
with pytest.raises(ValueError, match=msg):
|
| 461 |
+
df_table.to_json(orient="table", date_format="epoch")
|
| 462 |
+
|
| 463 |
+
# others work
|
| 464 |
+
df_table.to_json(orient="table", date_format="iso")
|
| 465 |
+
df_table.to_json(orient="table")
|
| 466 |
+
|
| 467 |
+
def test_convert_pandas_type_to_json_field_int(self, index_or_series):
|
| 468 |
+
kind = index_or_series
|
| 469 |
+
data = [1, 2, 3]
|
| 470 |
+
result = convert_pandas_type_to_json_field(kind(data, name="name"))
|
| 471 |
+
expected = {"name": "name", "type": "integer"}
|
| 472 |
+
assert result == expected
|
| 473 |
+
|
| 474 |
+
def test_convert_pandas_type_to_json_field_float(self, index_or_series):
|
| 475 |
+
kind = index_or_series
|
| 476 |
+
data = [1.0, 2.0, 3.0]
|
| 477 |
+
result = convert_pandas_type_to_json_field(kind(data, name="name"))
|
| 478 |
+
expected = {"name": "name", "type": "number"}
|
| 479 |
+
assert result == expected
|
| 480 |
+
|
| 481 |
+
@pytest.mark.parametrize(
|
| 482 |
+
"dt_args,extra_exp", [({}, {}), ({"utc": True}, {"tz": "UTC"})]
|
| 483 |
+
)
|
| 484 |
+
@pytest.mark.parametrize("wrapper", [None, pd.Series])
|
| 485 |
+
def test_convert_pandas_type_to_json_field_datetime(
|
| 486 |
+
self, dt_args, extra_exp, wrapper
|
| 487 |
+
):
|
| 488 |
+
data = [1.0, 2.0, 3.0]
|
| 489 |
+
data = pd.to_datetime(data, **dt_args)
|
| 490 |
+
if wrapper is pd.Series:
|
| 491 |
+
data = pd.Series(data, name="values")
|
| 492 |
+
result = convert_pandas_type_to_json_field(data)
|
| 493 |
+
expected = {"name": "values", "type": "datetime"}
|
| 494 |
+
expected.update(extra_exp)
|
| 495 |
+
assert result == expected
|
| 496 |
+
|
| 497 |
+
def test_convert_pandas_type_to_json_period_range(self):
|
| 498 |
+
arr = pd.period_range("2016", freq="Y-DEC", periods=4)
|
| 499 |
+
result = convert_pandas_type_to_json_field(arr)
|
| 500 |
+
expected = {"name": "values", "type": "datetime", "freq": "YE-DEC"}
|
| 501 |
+
assert result == expected
|
| 502 |
+
|
| 503 |
+
@pytest.mark.parametrize("kind", [pd.Categorical, pd.CategoricalIndex])
|
| 504 |
+
@pytest.mark.parametrize("ordered", [True, False])
|
| 505 |
+
def test_convert_pandas_type_to_json_field_categorical(self, kind, ordered):
|
| 506 |
+
data = ["a", "b", "c"]
|
| 507 |
+
if kind is pd.Categorical:
|
| 508 |
+
arr = pd.Series(kind(data, ordered=ordered), name="cats")
|
| 509 |
+
elif kind is pd.CategoricalIndex:
|
| 510 |
+
arr = kind(data, ordered=ordered, name="cats")
|
| 511 |
+
|
| 512 |
+
result = convert_pandas_type_to_json_field(arr)
|
| 513 |
+
expected = {
|
| 514 |
+
"name": "cats",
|
| 515 |
+
"type": "any",
|
| 516 |
+
"constraints": {"enum": data},
|
| 517 |
+
"ordered": ordered,
|
| 518 |
+
}
|
| 519 |
+
assert result == expected
|
| 520 |
+
|
| 521 |
+
@pytest.mark.parametrize(
|
| 522 |
+
"inp,exp",
|
| 523 |
+
[
|
| 524 |
+
({"type": "integer"}, "int64"),
|
| 525 |
+
({"type": "number"}, "float64"),
|
| 526 |
+
({"type": "boolean"}, "bool"),
|
| 527 |
+
({"type": "duration"}, "timedelta64"),
|
| 528 |
+
({"type": "datetime"}, "datetime64[ns]"),
|
| 529 |
+
({"type": "datetime", "tz": "US/Hawaii"}, "datetime64[ns, US/Hawaii]"),
|
| 530 |
+
({"type": "any"}, "object"),
|
| 531 |
+
(
|
| 532 |
+
{
|
| 533 |
+
"type": "any",
|
| 534 |
+
"constraints": {"enum": ["a", "b", "c"]},
|
| 535 |
+
"ordered": False,
|
| 536 |
+
},
|
| 537 |
+
CategoricalDtype(categories=["a", "b", "c"], ordered=False),
|
| 538 |
+
),
|
| 539 |
+
(
|
| 540 |
+
{
|
| 541 |
+
"type": "any",
|
| 542 |
+
"constraints": {"enum": ["a", "b", "c"]},
|
| 543 |
+
"ordered": True,
|
| 544 |
+
},
|
| 545 |
+
CategoricalDtype(categories=["a", "b", "c"], ordered=True),
|
| 546 |
+
),
|
| 547 |
+
({"type": "string"}, None),
|
| 548 |
+
],
|
| 549 |
+
)
|
| 550 |
+
def test_convert_json_field_to_pandas_type(self, inp, exp):
|
| 551 |
+
field = {"name": "foo"}
|
| 552 |
+
field.update(inp)
|
| 553 |
+
assert convert_json_field_to_pandas_type(field) == exp
|
| 554 |
+
|
| 555 |
+
@pytest.mark.parametrize("inp", ["geopoint", "geojson", "fake_type"])
|
| 556 |
+
def test_convert_json_field_to_pandas_type_raises(self, inp):
|
| 557 |
+
field = {"type": inp}
|
| 558 |
+
with pytest.raises(
|
| 559 |
+
ValueError, match=f"Unsupported or invalid field type: {inp}"
|
| 560 |
+
):
|
| 561 |
+
convert_json_field_to_pandas_type(field)
|
| 562 |
+
|
| 563 |
+
def test_categorical(self):
|
| 564 |
+
s = pd.Series(pd.Categorical(["a", "b", "a"]))
|
| 565 |
+
s.index.name = "idx"
|
| 566 |
+
result = s.to_json(orient="table", date_format="iso")
|
| 567 |
+
result = json.loads(result, object_pairs_hook=OrderedDict)
|
| 568 |
+
result["schema"].pop("pandas_version")
|
| 569 |
+
|
| 570 |
+
fields = [
|
| 571 |
+
{"name": "idx", "type": "integer"},
|
| 572 |
+
{
|
| 573 |
+
"constraints": {"enum": ["a", "b"]},
|
| 574 |
+
"name": "values",
|
| 575 |
+
"ordered": False,
|
| 576 |
+
"type": "any",
|
| 577 |
+
},
|
| 578 |
+
]
|
| 579 |
+
|
| 580 |
+
expected = OrderedDict(
|
| 581 |
+
[
|
| 582 |
+
("schema", {"fields": fields, "primaryKey": ["idx"]}),
|
| 583 |
+
(
|
| 584 |
+
"data",
|
| 585 |
+
[
|
| 586 |
+
OrderedDict([("idx", 0), ("values", "a")]),
|
| 587 |
+
OrderedDict([("idx", 1), ("values", "b")]),
|
| 588 |
+
OrderedDict([("idx", 2), ("values", "a")]),
|
| 589 |
+
],
|
| 590 |
+
),
|
| 591 |
+
]
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
assert result == expected
|
| 595 |
+
|
| 596 |
+
@pytest.mark.parametrize(
|
| 597 |
+
"idx,nm,prop",
|
| 598 |
+
[
|
| 599 |
+
(pd.Index([1]), "index", "name"),
|
| 600 |
+
(pd.Index([1], name="myname"), "myname", "name"),
|
| 601 |
+
(
|
| 602 |
+
pd.MultiIndex.from_product([("a", "b"), ("c", "d")]),
|
| 603 |
+
["level_0", "level_1"],
|
| 604 |
+
"names",
|
| 605 |
+
),
|
| 606 |
+
(
|
| 607 |
+
pd.MultiIndex.from_product(
|
| 608 |
+
[("a", "b"), ("c", "d")], names=["n1", "n2"]
|
| 609 |
+
),
|
| 610 |
+
["n1", "n2"],
|
| 611 |
+
"names",
|
| 612 |
+
),
|
| 613 |
+
(
|
| 614 |
+
pd.MultiIndex.from_product(
|
| 615 |
+
[("a", "b"), ("c", "d")], names=["n1", None]
|
| 616 |
+
),
|
| 617 |
+
["n1", "level_1"],
|
| 618 |
+
"names",
|
| 619 |
+
),
|
| 620 |
+
],
|
| 621 |
+
)
|
| 622 |
+
def test_set_names_unset(self, idx, nm, prop):
|
| 623 |
+
data = pd.Series(1, idx)
|
| 624 |
+
result = set_default_names(data)
|
| 625 |
+
assert getattr(result.index, prop) == nm
|
| 626 |
+
|
| 627 |
+
@pytest.mark.parametrize(
|
| 628 |
+
"idx",
|
| 629 |
+
[
|
| 630 |
+
pd.Index([], name="index"),
|
| 631 |
+
pd.MultiIndex.from_arrays([["foo"], ["bar"]], names=("level_0", "level_1")),
|
| 632 |
+
pd.MultiIndex.from_arrays([["foo"], ["bar"]], names=("foo", "level_1")),
|
| 633 |
+
],
|
| 634 |
+
)
|
| 635 |
+
def test_warns_non_roundtrippable_names(self, idx):
|
| 636 |
+
# GH 19130
|
| 637 |
+
df = DataFrame(index=idx)
|
| 638 |
+
df.index.name = "index"
|
| 639 |
+
with tm.assert_produces_warning():
|
| 640 |
+
set_default_names(df)
|
| 641 |
+
|
| 642 |
+
def test_timestamp_in_columns(self):
|
| 643 |
+
df = DataFrame(
|
| 644 |
+
[[1, 2]], columns=[pd.Timestamp("2016"), pd.Timedelta(10, unit="s")]
|
| 645 |
+
)
|
| 646 |
+
result = df.to_json(orient="table")
|
| 647 |
+
js = json.loads(result)
|
| 648 |
+
assert js["schema"]["fields"][1]["name"] == "2016-01-01T00:00:00.000"
|
| 649 |
+
assert js["schema"]["fields"][2]["name"] == "P0DT0H0M10S"
|
| 650 |
+
|
| 651 |
+
@pytest.mark.parametrize(
|
| 652 |
+
"case",
|
| 653 |
+
[
|
| 654 |
+
pd.Series([1], index=pd.Index([1], name="a"), name="a"),
|
| 655 |
+
DataFrame({"A": [1]}, index=pd.Index([1], name="A")),
|
| 656 |
+
DataFrame(
|
| 657 |
+
{"A": [1]},
|
| 658 |
+
index=pd.MultiIndex.from_arrays([["a"], [1]], names=["A", "a"]),
|
| 659 |
+
),
|
| 660 |
+
],
|
| 661 |
+
)
|
| 662 |
+
def test_overlapping_names(self, case):
|
| 663 |
+
with pytest.raises(ValueError, match="Overlapping"):
|
| 664 |
+
case.to_json(orient="table")
|
| 665 |
+
|
| 666 |
+
def test_mi_falsey_name(self):
|
| 667 |
+
# GH 16203
|
| 668 |
+
df = DataFrame(
|
| 669 |
+
np.random.default_rng(2).standard_normal((4, 4)),
|
| 670 |
+
index=pd.MultiIndex.from_product([("A", "B"), ("a", "b")]),
|
| 671 |
+
)
|
| 672 |
+
result = [x["name"] for x in build_table_schema(df)["fields"]]
|
| 673 |
+
assert result == ["level_0", "level_1", 0, 1, 2, 3]
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
class TestTableOrientReader:
|
| 677 |
+
@pytest.mark.parametrize(
|
| 678 |
+
"index_nm",
|
| 679 |
+
[None, "idx", pytest.param("index", marks=pytest.mark.xfail), "level_0"],
|
| 680 |
+
)
|
| 681 |
+
@pytest.mark.parametrize(
|
| 682 |
+
"vals",
|
| 683 |
+
[
|
| 684 |
+
{"ints": [1, 2, 3, 4]},
|
| 685 |
+
{"objects": ["a", "b", "c", "d"]},
|
| 686 |
+
{"objects": ["1", "2", "3", "4"]},
|
| 687 |
+
{"date_ranges": pd.date_range("2016-01-01", freq="d", periods=4)},
|
| 688 |
+
{"categoricals": pd.Series(pd.Categorical(["a", "b", "c", "c"]))},
|
| 689 |
+
{
|
| 690 |
+
"ordered_cats": pd.Series(
|
| 691 |
+
pd.Categorical(["a", "b", "c", "c"], ordered=True)
|
| 692 |
+
)
|
| 693 |
+
},
|
| 694 |
+
{"floats": [1.0, 2.0, 3.0, 4.0]},
|
| 695 |
+
{"floats": [1.1, 2.2, 3.3, 4.4]},
|
| 696 |
+
{"bools": [True, False, False, True]},
|
| 697 |
+
{
|
| 698 |
+
"timezones": pd.date_range(
|
| 699 |
+
"2016-01-01", freq="d", periods=4, tz="US/Central"
|
| 700 |
+
) # added in # GH 35973
|
| 701 |
+
},
|
| 702 |
+
],
|
| 703 |
+
)
|
| 704 |
+
def test_read_json_table_orient(self, index_nm, vals, recwarn):
|
| 705 |
+
df = DataFrame(vals, index=pd.Index(range(4), name=index_nm))
|
| 706 |
+
out = df.to_json(orient="table")
|
| 707 |
+
result = pd.read_json(out, orient="table")
|
| 708 |
+
tm.assert_frame_equal(df, result)
|
| 709 |
+
|
| 710 |
+
@pytest.mark.parametrize("index_nm", [None, "idx", "index"])
|
| 711 |
+
@pytest.mark.parametrize(
|
| 712 |
+
"vals",
|
| 713 |
+
[{"timedeltas": pd.timedelta_range("1h", periods=4, freq="min")}],
|
| 714 |
+
)
|
| 715 |
+
def test_read_json_table_orient_raises(self, index_nm, vals, recwarn):
|
| 716 |
+
df = DataFrame(vals, index=pd.Index(range(4), name=index_nm))
|
| 717 |
+
out = df.to_json(orient="table")
|
| 718 |
+
with pytest.raises(NotImplementedError, match="can not yet read "):
|
| 719 |
+
pd.read_json(out, orient="table")
|
| 720 |
+
|
| 721 |
+
@pytest.mark.parametrize(
|
| 722 |
+
"index_nm",
|
| 723 |
+
[None, "idx", pytest.param("index", marks=pytest.mark.xfail), "level_0"],
|
| 724 |
+
)
|
| 725 |
+
@pytest.mark.parametrize(
|
| 726 |
+
"vals",
|
| 727 |
+
[
|
| 728 |
+
{"ints": [1, 2, 3, 4]},
|
| 729 |
+
{"objects": ["a", "b", "c", "d"]},
|
| 730 |
+
{"objects": ["1", "2", "3", "4"]},
|
| 731 |
+
{"date_ranges": pd.date_range("2016-01-01", freq="d", periods=4)},
|
| 732 |
+
{"categoricals": pd.Series(pd.Categorical(["a", "b", "c", "c"]))},
|
| 733 |
+
{
|
| 734 |
+
"ordered_cats": pd.Series(
|
| 735 |
+
pd.Categorical(["a", "b", "c", "c"], ordered=True)
|
| 736 |
+
)
|
| 737 |
+
},
|
| 738 |
+
{"floats": [1.0, 2.0, 3.0, 4.0]},
|
| 739 |
+
{"floats": [1.1, 2.2, 3.3, 4.4]},
|
| 740 |
+
{"bools": [True, False, False, True]},
|
| 741 |
+
{
|
| 742 |
+
"timezones": pd.date_range(
|
| 743 |
+
"2016-01-01", freq="d", periods=4, tz="US/Central"
|
| 744 |
+
) # added in # GH 35973
|
| 745 |
+
},
|
| 746 |
+
],
|
| 747 |
+
)
|
| 748 |
+
def test_read_json_table_period_orient(self, index_nm, vals, recwarn):
|
| 749 |
+
df = DataFrame(
|
| 750 |
+
vals,
|
| 751 |
+
index=pd.Index(
|
| 752 |
+
(pd.Period(f"2022Q{q}") for q in range(1, 5)), name=index_nm
|
| 753 |
+
),
|
| 754 |
+
)
|
| 755 |
+
out = df.to_json(orient="table")
|
| 756 |
+
result = pd.read_json(out, orient="table")
|
| 757 |
+
tm.assert_frame_equal(df, result)
|
| 758 |
+
|
| 759 |
+
@pytest.mark.parametrize(
|
| 760 |
+
"idx",
|
| 761 |
+
[
|
| 762 |
+
pd.Index(range(4)),
|
| 763 |
+
pd.date_range(
|
| 764 |
+
"2020-08-30",
|
| 765 |
+
freq="d",
|
| 766 |
+
periods=4,
|
| 767 |
+
)._with_freq(None),
|
| 768 |
+
pd.date_range(
|
| 769 |
+
"2020-08-30", freq="d", periods=4, tz="US/Central"
|
| 770 |
+
)._with_freq(None),
|
| 771 |
+
pd.MultiIndex.from_product(
|
| 772 |
+
[
|
| 773 |
+
pd.date_range("2020-08-30", freq="d", periods=2, tz="US/Central"),
|
| 774 |
+
["x", "y"],
|
| 775 |
+
],
|
| 776 |
+
),
|
| 777 |
+
],
|
| 778 |
+
)
|
| 779 |
+
@pytest.mark.parametrize(
|
| 780 |
+
"vals",
|
| 781 |
+
[
|
| 782 |
+
{"floats": [1.1, 2.2, 3.3, 4.4]},
|
| 783 |
+
{"dates": pd.date_range("2020-08-30", freq="d", periods=4)},
|
| 784 |
+
{
|
| 785 |
+
"timezones": pd.date_range(
|
| 786 |
+
"2020-08-30", freq="d", periods=4, tz="Europe/London"
|
| 787 |
+
)
|
| 788 |
+
},
|
| 789 |
+
],
|
| 790 |
+
)
|
| 791 |
+
def test_read_json_table_timezones_orient(self, idx, vals, recwarn):
|
| 792 |
+
# GH 35973
|
| 793 |
+
df = DataFrame(vals, index=idx)
|
| 794 |
+
out = df.to_json(orient="table")
|
| 795 |
+
result = pd.read_json(out, orient="table")
|
| 796 |
+
tm.assert_frame_equal(df, result)
|
| 797 |
+
|
| 798 |
+
def test_comprehensive(self):
|
| 799 |
+
df = DataFrame(
|
| 800 |
+
{
|
| 801 |
+
"A": [1, 2, 3, 4],
|
| 802 |
+
"B": ["a", "b", "c", "c"],
|
| 803 |
+
"C": pd.date_range("2016-01-01", freq="d", periods=4),
|
| 804 |
+
# 'D': pd.timedelta_range('1h', periods=4, freq='min'),
|
| 805 |
+
"E": pd.Series(pd.Categorical(["a", "b", "c", "c"])),
|
| 806 |
+
"F": pd.Series(pd.Categorical(["a", "b", "c", "c"], ordered=True)),
|
| 807 |
+
"G": [1.1, 2.2, 3.3, 4.4],
|
| 808 |
+
"H": pd.date_range("2016-01-01", freq="d", periods=4, tz="US/Central"),
|
| 809 |
+
"I": [True, False, False, True],
|
| 810 |
+
},
|
| 811 |
+
index=pd.Index(range(4), name="idx"),
|
| 812 |
+
)
|
| 813 |
+
|
| 814 |
+
out = StringIO(df.to_json(orient="table"))
|
| 815 |
+
result = pd.read_json(out, orient="table")
|
| 816 |
+
tm.assert_frame_equal(df, result)
|
| 817 |
+
|
| 818 |
+
@pytest.mark.parametrize(
|
| 819 |
+
"index_names",
|
| 820 |
+
[[None, None], ["foo", "bar"], ["foo", None], [None, "foo"], ["index", "foo"]],
|
| 821 |
+
)
|
| 822 |
+
def test_multiindex(self, index_names):
|
| 823 |
+
# GH 18912
|
| 824 |
+
df = DataFrame(
|
| 825 |
+
[["Arr", "alpha", [1, 2, 3, 4]], ["Bee", "Beta", [10, 20, 30, 40]]],
|
| 826 |
+
index=[["A", "B"], ["Null", "Eins"]],
|
| 827 |
+
columns=["Aussprache", "Griechisch", "Args"],
|
| 828 |
+
)
|
| 829 |
+
df.index.names = index_names
|
| 830 |
+
out = StringIO(df.to_json(orient="table"))
|
| 831 |
+
result = pd.read_json(out, orient="table")
|
| 832 |
+
tm.assert_frame_equal(df, result)
|
| 833 |
+
|
| 834 |
+
def test_empty_frame_roundtrip(self):
|
| 835 |
+
# GH 21287
|
| 836 |
+
df = DataFrame(columns=["a", "b", "c"])
|
| 837 |
+
expected = df.copy()
|
| 838 |
+
out = StringIO(df.to_json(orient="table"))
|
| 839 |
+
result = pd.read_json(out, orient="table")
|
| 840 |
+
tm.assert_frame_equal(expected, result)
|
| 841 |
+
|
| 842 |
+
def test_read_json_orient_table_old_schema_version(self):
|
| 843 |
+
df_json = """
|
| 844 |
+
{
|
| 845 |
+
"schema":{
|
| 846 |
+
"fields":[
|
| 847 |
+
{"name":"index","type":"integer"},
|
| 848 |
+
{"name":"a","type":"string"}
|
| 849 |
+
],
|
| 850 |
+
"primaryKey":["index"],
|
| 851 |
+
"pandas_version":"0.20.0"
|
| 852 |
+
},
|
| 853 |
+
"data":[
|
| 854 |
+
{"index":0,"a":1},
|
| 855 |
+
{"index":1,"a":2.0},
|
| 856 |
+
{"index":2,"a":"s"}
|
| 857 |
+
]
|
| 858 |
+
}
|
| 859 |
+
"""
|
| 860 |
+
expected = DataFrame({"a": [1, 2.0, "s"]})
|
| 861 |
+
result = pd.read_json(StringIO(df_json), orient="table")
|
| 862 |
+
tm.assert_frame_equal(expected, result)
|
| 863 |
+
|
| 864 |
+
@pytest.mark.parametrize("freq", ["M", "2M", "Q", "2Q", "Y", "2Y"])
|
| 865 |
+
def test_read_json_table_orient_period_depr_freq(self, freq, recwarn):
|
| 866 |
+
# GH#9586
|
| 867 |
+
df = DataFrame(
|
| 868 |
+
{"ints": [1, 2]},
|
| 869 |
+
index=pd.PeriodIndex(["2020-01", "2021-06"], freq=freq),
|
| 870 |
+
)
|
| 871 |
+
out = df.to_json(orient="table")
|
| 872 |
+
result = pd.read_json(out, orient="table")
|
| 873 |
+
tm.assert_frame_equal(df, result)
|
shared/package-files/06/065e6597af214f795d16c018fdfe60ec93ab1d2703bdb159e0576173a19a72f8/_strptime.py
ADDED
|
@@ -0,0 +1,579 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Strptime-related classes and functions.
|
| 2 |
+
|
| 3 |
+
CLASSES:
|
| 4 |
+
LocaleTime -- Discovers and stores locale-specific time information
|
| 5 |
+
TimeRE -- Creates regexes for pattern matching a string of text containing
|
| 6 |
+
time information
|
| 7 |
+
|
| 8 |
+
FUNCTIONS:
|
| 9 |
+
_getlang -- Figure out what language is being used for the locale
|
| 10 |
+
strptime -- Calculates the time struct represented by the passed-in string
|
| 11 |
+
|
| 12 |
+
"""
|
| 13 |
+
import time
|
| 14 |
+
import locale
|
| 15 |
+
import calendar
|
| 16 |
+
from re import compile as re_compile
|
| 17 |
+
from re import IGNORECASE
|
| 18 |
+
from re import escape as re_escape
|
| 19 |
+
from datetime import (date as datetime_date,
|
| 20 |
+
timedelta as datetime_timedelta,
|
| 21 |
+
timezone as datetime_timezone)
|
| 22 |
+
from _thread import allocate_lock as _thread_allocate_lock
|
| 23 |
+
|
| 24 |
+
__all__ = []
|
| 25 |
+
|
| 26 |
+
def _getlang():
|
| 27 |
+
# Figure out what the current language is set to.
|
| 28 |
+
return locale.getlocale(locale.LC_TIME)
|
| 29 |
+
|
| 30 |
+
class LocaleTime(object):
|
| 31 |
+
"""Stores and handles locale-specific information related to time.
|
| 32 |
+
|
| 33 |
+
ATTRIBUTES:
|
| 34 |
+
f_weekday -- full weekday names (7-item list)
|
| 35 |
+
a_weekday -- abbreviated weekday names (7-item list)
|
| 36 |
+
f_month -- full month names (13-item list; dummy value in [0], which
|
| 37 |
+
is added by code)
|
| 38 |
+
a_month -- abbreviated month names (13-item list, dummy value in
|
| 39 |
+
[0], which is added by code)
|
| 40 |
+
am_pm -- AM/PM representation (2-item list)
|
| 41 |
+
LC_date_time -- format string for date/time representation (string)
|
| 42 |
+
LC_date -- format string for date representation (string)
|
| 43 |
+
LC_time -- format string for time representation (string)
|
| 44 |
+
timezone -- daylight- and non-daylight-savings timezone representation
|
| 45 |
+
(2-item list of sets)
|
| 46 |
+
lang -- Language used by instance (2-item tuple)
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
def __init__(self):
|
| 50 |
+
"""Set all attributes.
|
| 51 |
+
|
| 52 |
+
Order of methods called matters for dependency reasons.
|
| 53 |
+
|
| 54 |
+
The locale language is set at the offset and then checked again before
|
| 55 |
+
exiting. This is to make sure that the attributes were not set with a
|
| 56 |
+
mix of information from more than one locale. This would most likely
|
| 57 |
+
happen when using threads where one thread calls a locale-dependent
|
| 58 |
+
function while another thread changes the locale while the function in
|
| 59 |
+
the other thread is still running. Proper coding would call for
|
| 60 |
+
locks to prevent changing the locale while locale-dependent code is
|
| 61 |
+
running. The check here is done in case someone does not think about
|
| 62 |
+
doing this.
|
| 63 |
+
|
| 64 |
+
Only other possible issue is if someone changed the timezone and did
|
| 65 |
+
not call tz.tzset . That is an issue for the programmer, though,
|
| 66 |
+
since changing the timezone is worthless without that call.
|
| 67 |
+
|
| 68 |
+
"""
|
| 69 |
+
self.lang = _getlang()
|
| 70 |
+
self.__calc_weekday()
|
| 71 |
+
self.__calc_month()
|
| 72 |
+
self.__calc_am_pm()
|
| 73 |
+
self.__calc_timezone()
|
| 74 |
+
self.__calc_date_time()
|
| 75 |
+
if _getlang() != self.lang:
|
| 76 |
+
raise ValueError("locale changed during initialization")
|
| 77 |
+
if time.tzname != self.tzname or time.daylight != self.daylight:
|
| 78 |
+
raise ValueError("timezone changed during initialization")
|
| 79 |
+
|
| 80 |
+
def __calc_weekday(self):
|
| 81 |
+
# Set self.a_weekday and self.f_weekday using the calendar
|
| 82 |
+
# module.
|
| 83 |
+
a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
|
| 84 |
+
f_weekday = [calendar.day_name[i].lower() for i in range(7)]
|
| 85 |
+
self.a_weekday = a_weekday
|
| 86 |
+
self.f_weekday = f_weekday
|
| 87 |
+
|
| 88 |
+
def __calc_month(self):
|
| 89 |
+
# Set self.f_month and self.a_month using the calendar module.
|
| 90 |
+
a_month = [calendar.month_abbr[i].lower() for i in range(13)]
|
| 91 |
+
f_month = [calendar.month_name[i].lower() for i in range(13)]
|
| 92 |
+
self.a_month = a_month
|
| 93 |
+
self.f_month = f_month
|
| 94 |
+
|
| 95 |
+
def __calc_am_pm(self):
|
| 96 |
+
# Set self.am_pm by using time.strftime().
|
| 97 |
+
|
| 98 |
+
# The magic date (1999,3,17,hour,44,55,2,76,0) is not really that
|
| 99 |
+
# magical; just happened to have used it everywhere else where a
|
| 100 |
+
# static date was needed.
|
| 101 |
+
am_pm = []
|
| 102 |
+
for hour in (1, 22):
|
| 103 |
+
time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))
|
| 104 |
+
am_pm.append(time.strftime("%p", time_tuple).lower())
|
| 105 |
+
self.am_pm = am_pm
|
| 106 |
+
|
| 107 |
+
def __calc_date_time(self):
|
| 108 |
+
# Set self.date_time, self.date, & self.time by using
|
| 109 |
+
# time.strftime().
|
| 110 |
+
|
| 111 |
+
# Use (1999,3,17,22,44,55,2,76,0) for magic date because the amount of
|
| 112 |
+
# overloaded numbers is minimized. The order in which searches for
|
| 113 |
+
# values within the format string is very important; it eliminates
|
| 114 |
+
# possible ambiguity for what something represents.
|
| 115 |
+
time_tuple = time.struct_time((1999,3,17,22,44,55,2,76,0))
|
| 116 |
+
date_time = [None, None, None]
|
| 117 |
+
date_time[0] = time.strftime("%c", time_tuple).lower()
|
| 118 |
+
date_time[1] = time.strftime("%x", time_tuple).lower()
|
| 119 |
+
date_time[2] = time.strftime("%X", time_tuple).lower()
|
| 120 |
+
replacement_pairs = [('%', '%%'), (self.f_weekday[2], '%A'),
|
| 121 |
+
(self.f_month[3], '%B'), (self.a_weekday[2], '%a'),
|
| 122 |
+
(self.a_month[3], '%b'), (self.am_pm[1], '%p'),
|
| 123 |
+
('1999', '%Y'), ('99', '%y'), ('22', '%H'),
|
| 124 |
+
('44', '%M'), ('55', '%S'), ('76', '%j'),
|
| 125 |
+
('17', '%d'), ('03', '%m'), ('3', '%m'),
|
| 126 |
+
# '3' needed for when no leading zero.
|
| 127 |
+
('2', '%w'), ('10', '%I')]
|
| 128 |
+
replacement_pairs.extend([(tz, "%Z") for tz_values in self.timezone
|
| 129 |
+
for tz in tz_values])
|
| 130 |
+
for offset,directive in ((0,'%c'), (1,'%x'), (2,'%X')):
|
| 131 |
+
current_format = date_time[offset]
|
| 132 |
+
for old, new in replacement_pairs:
|
| 133 |
+
# Must deal with possible lack of locale info
|
| 134 |
+
# manifesting itself as the empty string (e.g., Swedish's
|
| 135 |
+
# lack of AM/PM info) or a platform returning a tuple of empty
|
| 136 |
+
# strings (e.g., MacOS 9 having timezone as ('','')).
|
| 137 |
+
if old:
|
| 138 |
+
current_format = current_format.replace(old, new)
|
| 139 |
+
# If %W is used, then Sunday, 2005-01-03 will fall on week 0 since
|
| 140 |
+
# 2005-01-03 occurs before the first Monday of the year. Otherwise
|
| 141 |
+
# %U is used.
|
| 142 |
+
time_tuple = time.struct_time((1999,1,3,1,1,1,6,3,0))
|
| 143 |
+
if '00' in time.strftime(directive, time_tuple):
|
| 144 |
+
U_W = '%W'
|
| 145 |
+
else:
|
| 146 |
+
U_W = '%U'
|
| 147 |
+
date_time[offset] = current_format.replace('11', U_W)
|
| 148 |
+
self.LC_date_time = date_time[0]
|
| 149 |
+
self.LC_date = date_time[1]
|
| 150 |
+
self.LC_time = date_time[2]
|
| 151 |
+
|
| 152 |
+
def __calc_timezone(self):
|
| 153 |
+
# Set self.timezone by using time.tzname.
|
| 154 |
+
# Do not worry about possibility of time.tzname[0] == time.tzname[1]
|
| 155 |
+
# and time.daylight; handle that in strptime.
|
| 156 |
+
try:
|
| 157 |
+
time.tzset()
|
| 158 |
+
except AttributeError:
|
| 159 |
+
pass
|
| 160 |
+
self.tzname = time.tzname
|
| 161 |
+
self.daylight = time.daylight
|
| 162 |
+
no_saving = frozenset({"utc", "gmt", self.tzname[0].lower()})
|
| 163 |
+
if self.daylight:
|
| 164 |
+
has_saving = frozenset({self.tzname[1].lower()})
|
| 165 |
+
else:
|
| 166 |
+
has_saving = frozenset()
|
| 167 |
+
self.timezone = (no_saving, has_saving)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class TimeRE(dict):
|
| 171 |
+
"""Handle conversion from format directives to regexes."""
|
| 172 |
+
|
| 173 |
+
def __init__(self, locale_time=None):
|
| 174 |
+
"""Create keys/values.
|
| 175 |
+
|
| 176 |
+
Order of execution is important for dependency reasons.
|
| 177 |
+
|
| 178 |
+
"""
|
| 179 |
+
if locale_time:
|
| 180 |
+
self.locale_time = locale_time
|
| 181 |
+
else:
|
| 182 |
+
self.locale_time = LocaleTime()
|
| 183 |
+
base = super()
|
| 184 |
+
base.__init__({
|
| 185 |
+
# The " [1-9]" part of the regex is to make %c from ANSI C work
|
| 186 |
+
'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",
|
| 187 |
+
'f': r"(?P<f>[0-9]{1,6})",
|
| 188 |
+
'H': r"(?P<H>2[0-3]|[0-1]\d|\d)",
|
| 189 |
+
'I': r"(?P<I>1[0-2]|0[1-9]|[1-9])",
|
| 190 |
+
'G': r"(?P<G>\d\d\d\d)",
|
| 191 |
+
'j': r"(?P<j>36[0-6]|3[0-5]\d|[1-2]\d\d|0[1-9]\d|00[1-9]|[1-9]\d|0[1-9]|[1-9])",
|
| 192 |
+
'm': r"(?P<m>1[0-2]|0[1-9]|[1-9])",
|
| 193 |
+
'M': r"(?P<M>[0-5]\d|\d)",
|
| 194 |
+
'S': r"(?P<S>6[0-1]|[0-5]\d|\d)",
|
| 195 |
+
'U': r"(?P<U>5[0-3]|[0-4]\d|\d)",
|
| 196 |
+
'w': r"(?P<w>[0-6])",
|
| 197 |
+
'u': r"(?P<u>[1-7])",
|
| 198 |
+
'V': r"(?P<V>5[0-3]|0[1-9]|[1-4]\d|\d)",
|
| 199 |
+
# W is set below by using 'U'
|
| 200 |
+
'y': r"(?P<y>\d\d)",
|
| 201 |
+
#XXX: Does 'Y' need to worry about having less or more than
|
| 202 |
+
# 4 digits?
|
| 203 |
+
'Y': r"(?P<Y>\d\d\d\d)",
|
| 204 |
+
'z': r"(?P<z>[+-]\d\d:?[0-5]\d(:?[0-5]\d(\.\d{1,6})?)?|(?-i:Z))",
|
| 205 |
+
'A': self.__seqToRE(self.locale_time.f_weekday, 'A'),
|
| 206 |
+
'a': self.__seqToRE(self.locale_time.a_weekday, 'a'),
|
| 207 |
+
'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'),
|
| 208 |
+
'b': self.__seqToRE(self.locale_time.a_month[1:], 'b'),
|
| 209 |
+
'p': self.__seqToRE(self.locale_time.am_pm, 'p'),
|
| 210 |
+
'Z': self.__seqToRE((tz for tz_names in self.locale_time.timezone
|
| 211 |
+
for tz in tz_names),
|
| 212 |
+
'Z'),
|
| 213 |
+
'%': '%'})
|
| 214 |
+
base.__setitem__('W', base.__getitem__('U').replace('U', 'W'))
|
| 215 |
+
base.__setitem__('c', self.pattern(self.locale_time.LC_date_time))
|
| 216 |
+
base.__setitem__('x', self.pattern(self.locale_time.LC_date))
|
| 217 |
+
base.__setitem__('X', self.pattern(self.locale_time.LC_time))
|
| 218 |
+
|
| 219 |
+
def __seqToRE(self, to_convert, directive):
|
| 220 |
+
"""Convert a list to a regex string for matching a directive.
|
| 221 |
+
|
| 222 |
+
Want possible matching values to be from longest to shortest. This
|
| 223 |
+
prevents the possibility of a match occurring for a value that also
|
| 224 |
+
a substring of a larger value that should have matched (e.g., 'abc'
|
| 225 |
+
matching when 'abcdef' should have been the match).
|
| 226 |
+
|
| 227 |
+
"""
|
| 228 |
+
to_convert = sorted(to_convert, key=len, reverse=True)
|
| 229 |
+
for value in to_convert:
|
| 230 |
+
if value != '':
|
| 231 |
+
break
|
| 232 |
+
else:
|
| 233 |
+
return ''
|
| 234 |
+
regex = '|'.join(re_escape(stuff) for stuff in to_convert)
|
| 235 |
+
regex = '(?P<%s>%s' % (directive, regex)
|
| 236 |
+
return '%s)' % regex
|
| 237 |
+
|
| 238 |
+
def pattern(self, format):
|
| 239 |
+
"""Return regex pattern for the format string.
|
| 240 |
+
|
| 241 |
+
Need to make sure that any characters that might be interpreted as
|
| 242 |
+
regex syntax are escaped.
|
| 243 |
+
|
| 244 |
+
"""
|
| 245 |
+
processed_format = ''
|
| 246 |
+
# The sub() call escapes all characters that might be misconstrued
|
| 247 |
+
# as regex syntax. Cannot use re.escape since we have to deal with
|
| 248 |
+
# format directives (%m, etc.).
|
| 249 |
+
regex_chars = re_compile(r"([\\.^$*+?\(\){}\[\]|])")
|
| 250 |
+
format = regex_chars.sub(r"\\\1", format)
|
| 251 |
+
whitespace_replacement = re_compile(r'\s+')
|
| 252 |
+
format = whitespace_replacement.sub(r'\\s+', format)
|
| 253 |
+
while '%' in format:
|
| 254 |
+
directive_index = format.index('%')+1
|
| 255 |
+
processed_format = "%s%s%s" % (processed_format,
|
| 256 |
+
format[:directive_index-1],
|
| 257 |
+
self[format[directive_index]])
|
| 258 |
+
format = format[directive_index+1:]
|
| 259 |
+
return "%s%s" % (processed_format, format)
|
| 260 |
+
|
| 261 |
+
def compile(self, format):
|
| 262 |
+
"""Return a compiled re object for the format string."""
|
| 263 |
+
return re_compile(self.pattern(format), IGNORECASE)
|
| 264 |
+
|
| 265 |
+
_cache_lock = _thread_allocate_lock()
|
| 266 |
+
# DO NOT modify _TimeRE_cache or _regex_cache without acquiring the cache lock
|
| 267 |
+
# first!
|
| 268 |
+
_TimeRE_cache = TimeRE()
|
| 269 |
+
_CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache
|
| 270 |
+
_regex_cache = {}
|
| 271 |
+
|
| 272 |
+
def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon):
|
| 273 |
+
"""Calculate the Julian day based on the year, week of the year, and day of
|
| 274 |
+
the week, with week_start_day representing whether the week of the year
|
| 275 |
+
assumes the week starts on Sunday or Monday (6 or 0)."""
|
| 276 |
+
first_weekday = datetime_date(year, 1, 1).weekday()
|
| 277 |
+
# If we are dealing with the %U directive (week starts on Sunday), it's
|
| 278 |
+
# easier to just shift the view to Sunday being the first day of the
|
| 279 |
+
# week.
|
| 280 |
+
if not week_starts_Mon:
|
| 281 |
+
first_weekday = (first_weekday + 1) % 7
|
| 282 |
+
day_of_week = (day_of_week + 1) % 7
|
| 283 |
+
# Need to watch out for a week 0 (when the first day of the year is not
|
| 284 |
+
# the same as that specified by %U or %W).
|
| 285 |
+
week_0_length = (7 - first_weekday) % 7
|
| 286 |
+
if week_of_year == 0:
|
| 287 |
+
return 1 + day_of_week - first_weekday
|
| 288 |
+
else:
|
| 289 |
+
days_to_week = week_0_length + (7 * (week_of_year - 1))
|
| 290 |
+
return 1 + days_to_week + day_of_week
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def _calc_julian_from_V(iso_year, iso_week, iso_weekday):
|
| 294 |
+
"""Calculate the Julian day based on the ISO 8601 year, week, and weekday.
|
| 295 |
+
ISO weeks start on Mondays, with week 01 being the week containing 4 Jan.
|
| 296 |
+
ISO week days range from 1 (Monday) to 7 (Sunday).
|
| 297 |
+
"""
|
| 298 |
+
correction = datetime_date(iso_year, 1, 4).isoweekday() + 3
|
| 299 |
+
ordinal = (iso_week * 7) + iso_weekday - correction
|
| 300 |
+
# ordinal may be negative or 0 now, which means the date is in the previous
|
| 301 |
+
# calendar year
|
| 302 |
+
if ordinal < 1:
|
| 303 |
+
ordinal += datetime_date(iso_year, 1, 1).toordinal()
|
| 304 |
+
iso_year -= 1
|
| 305 |
+
ordinal -= datetime_date(iso_year, 1, 1).toordinal()
|
| 306 |
+
return iso_year, ordinal
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
|
| 310 |
+
"""Return a 2-tuple consisting of a time struct and an int containing
|
| 311 |
+
the number of microseconds based on the input string and the
|
| 312 |
+
format string."""
|
| 313 |
+
|
| 314 |
+
for index, arg in enumerate([data_string, format]):
|
| 315 |
+
if not isinstance(arg, str):
|
| 316 |
+
msg = "strptime() argument {} must be str, not {}"
|
| 317 |
+
raise TypeError(msg.format(index, type(arg)))
|
| 318 |
+
|
| 319 |
+
global _TimeRE_cache, _regex_cache
|
| 320 |
+
with _cache_lock:
|
| 321 |
+
locale_time = _TimeRE_cache.locale_time
|
| 322 |
+
if (_getlang() != locale_time.lang or
|
| 323 |
+
time.tzname != locale_time.tzname or
|
| 324 |
+
time.daylight != locale_time.daylight):
|
| 325 |
+
_TimeRE_cache = TimeRE()
|
| 326 |
+
_regex_cache.clear()
|
| 327 |
+
locale_time = _TimeRE_cache.locale_time
|
| 328 |
+
if len(_regex_cache) > _CACHE_MAX_SIZE:
|
| 329 |
+
_regex_cache.clear()
|
| 330 |
+
format_regex = _regex_cache.get(format)
|
| 331 |
+
if not format_regex:
|
| 332 |
+
try:
|
| 333 |
+
format_regex = _TimeRE_cache.compile(format)
|
| 334 |
+
# KeyError raised when a bad format is found; can be specified as
|
| 335 |
+
# \\, in which case it was a stray % but with a space after it
|
| 336 |
+
except KeyError as err:
|
| 337 |
+
bad_directive = err.args[0]
|
| 338 |
+
if bad_directive == "\\":
|
| 339 |
+
bad_directive = "%"
|
| 340 |
+
del err
|
| 341 |
+
raise ValueError("'%s' is a bad directive in format '%s'" %
|
| 342 |
+
(bad_directive, format)) from None
|
| 343 |
+
# IndexError only occurs when the format string is "%"
|
| 344 |
+
except IndexError:
|
| 345 |
+
raise ValueError("stray %% in format '%s'" % format) from None
|
| 346 |
+
_regex_cache[format] = format_regex
|
| 347 |
+
found = format_regex.match(data_string)
|
| 348 |
+
if not found:
|
| 349 |
+
raise ValueError("time data %r does not match format %r" %
|
| 350 |
+
(data_string, format))
|
| 351 |
+
if len(data_string) != found.end():
|
| 352 |
+
raise ValueError("unconverted data remains: %s" %
|
| 353 |
+
data_string[found.end():])
|
| 354 |
+
|
| 355 |
+
iso_year = year = None
|
| 356 |
+
month = day = 1
|
| 357 |
+
hour = minute = second = fraction = 0
|
| 358 |
+
tz = -1
|
| 359 |
+
gmtoff = None
|
| 360 |
+
gmtoff_fraction = 0
|
| 361 |
+
# Default to -1 to signify that values not known; not critical to have,
|
| 362 |
+
# though
|
| 363 |
+
iso_week = week_of_year = None
|
| 364 |
+
week_of_year_start = None
|
| 365 |
+
# weekday and julian defaulted to None so as to signal need to calculate
|
| 366 |
+
# values
|
| 367 |
+
weekday = julian = None
|
| 368 |
+
found_dict = found.groupdict()
|
| 369 |
+
for group_key in found_dict.keys():
|
| 370 |
+
# Directives not explicitly handled below:
|
| 371 |
+
# c, x, X
|
| 372 |
+
# handled by making out of other directives
|
| 373 |
+
# U, W
|
| 374 |
+
# worthless without day of the week
|
| 375 |
+
if group_key == 'y':
|
| 376 |
+
year = int(found_dict['y'])
|
| 377 |
+
# Open Group specification for strptime() states that a %y
|
| 378 |
+
#value in the range of [00, 68] is in the century 2000, while
|
| 379 |
+
#[69,99] is in the century 1900
|
| 380 |
+
if year <= 68:
|
| 381 |
+
year += 2000
|
| 382 |
+
else:
|
| 383 |
+
year += 1900
|
| 384 |
+
elif group_key == 'Y':
|
| 385 |
+
year = int(found_dict['Y'])
|
| 386 |
+
elif group_key == 'G':
|
| 387 |
+
iso_year = int(found_dict['G'])
|
| 388 |
+
elif group_key == 'm':
|
| 389 |
+
month = int(found_dict['m'])
|
| 390 |
+
elif group_key == 'B':
|
| 391 |
+
month = locale_time.f_month.index(found_dict['B'].lower())
|
| 392 |
+
elif group_key == 'b':
|
| 393 |
+
month = locale_time.a_month.index(found_dict['b'].lower())
|
| 394 |
+
elif group_key == 'd':
|
| 395 |
+
day = int(found_dict['d'])
|
| 396 |
+
elif group_key == 'H':
|
| 397 |
+
hour = int(found_dict['H'])
|
| 398 |
+
elif group_key == 'I':
|
| 399 |
+
hour = int(found_dict['I'])
|
| 400 |
+
ampm = found_dict.get('p', '').lower()
|
| 401 |
+
# If there was no AM/PM indicator, we'll treat this like AM
|
| 402 |
+
if ampm in ('', locale_time.am_pm[0]):
|
| 403 |
+
# We're in AM so the hour is correct unless we're
|
| 404 |
+
# looking at 12 midnight.
|
| 405 |
+
# 12 midnight == 12 AM == hour 0
|
| 406 |
+
if hour == 12:
|
| 407 |
+
hour = 0
|
| 408 |
+
elif ampm == locale_time.am_pm[1]:
|
| 409 |
+
# We're in PM so we need to add 12 to the hour unless
|
| 410 |
+
# we're looking at 12 noon.
|
| 411 |
+
# 12 noon == 12 PM == hour 12
|
| 412 |
+
if hour != 12:
|
| 413 |
+
hour += 12
|
| 414 |
+
elif group_key == 'M':
|
| 415 |
+
minute = int(found_dict['M'])
|
| 416 |
+
elif group_key == 'S':
|
| 417 |
+
second = int(found_dict['S'])
|
| 418 |
+
elif group_key == 'f':
|
| 419 |
+
s = found_dict['f']
|
| 420 |
+
# Pad to always return microseconds.
|
| 421 |
+
s += "0" * (6 - len(s))
|
| 422 |
+
fraction = int(s)
|
| 423 |
+
elif group_key == 'A':
|
| 424 |
+
weekday = locale_time.f_weekday.index(found_dict['A'].lower())
|
| 425 |
+
elif group_key == 'a':
|
| 426 |
+
weekday = locale_time.a_weekday.index(found_dict['a'].lower())
|
| 427 |
+
elif group_key == 'w':
|
| 428 |
+
weekday = int(found_dict['w'])
|
| 429 |
+
if weekday == 0:
|
| 430 |
+
weekday = 6
|
| 431 |
+
else:
|
| 432 |
+
weekday -= 1
|
| 433 |
+
elif group_key == 'u':
|
| 434 |
+
weekday = int(found_dict['u'])
|
| 435 |
+
weekday -= 1
|
| 436 |
+
elif group_key == 'j':
|
| 437 |
+
julian = int(found_dict['j'])
|
| 438 |
+
elif group_key in ('U', 'W'):
|
| 439 |
+
week_of_year = int(found_dict[group_key])
|
| 440 |
+
if group_key == 'U':
|
| 441 |
+
# U starts week on Sunday.
|
| 442 |
+
week_of_year_start = 6
|
| 443 |
+
else:
|
| 444 |
+
# W starts week on Monday.
|
| 445 |
+
week_of_year_start = 0
|
| 446 |
+
elif group_key == 'V':
|
| 447 |
+
iso_week = int(found_dict['V'])
|
| 448 |
+
elif group_key == 'z':
|
| 449 |
+
z = found_dict['z']
|
| 450 |
+
if z == 'Z':
|
| 451 |
+
gmtoff = 0
|
| 452 |
+
else:
|
| 453 |
+
if z[3] == ':':
|
| 454 |
+
z = z[:3] + z[4:]
|
| 455 |
+
if len(z) > 5:
|
| 456 |
+
if z[5] != ':':
|
| 457 |
+
msg = f"Inconsistent use of : in {found_dict['z']}"
|
| 458 |
+
raise ValueError(msg)
|
| 459 |
+
z = z[:5] + z[6:]
|
| 460 |
+
hours = int(z[1:3])
|
| 461 |
+
minutes = int(z[3:5])
|
| 462 |
+
seconds = int(z[5:7] or 0)
|
| 463 |
+
gmtoff = (hours * 60 * 60) + (minutes * 60) + seconds
|
| 464 |
+
gmtoff_remainder = z[8:]
|
| 465 |
+
# Pad to always return microseconds.
|
| 466 |
+
gmtoff_remainder_padding = "0" * (6 - len(gmtoff_remainder))
|
| 467 |
+
gmtoff_fraction = int(gmtoff_remainder + gmtoff_remainder_padding)
|
| 468 |
+
if z.startswith("-"):
|
| 469 |
+
gmtoff = -gmtoff
|
| 470 |
+
gmtoff_fraction = -gmtoff_fraction
|
| 471 |
+
elif group_key == 'Z':
|
| 472 |
+
# Since -1 is default value only need to worry about setting tz if
|
| 473 |
+
# it can be something other than -1.
|
| 474 |
+
found_zone = found_dict['Z'].lower()
|
| 475 |
+
for value, tz_values in enumerate(locale_time.timezone):
|
| 476 |
+
if found_zone in tz_values:
|
| 477 |
+
# Deal with bad locale setup where timezone names are the
|
| 478 |
+
# same and yet time.daylight is true; too ambiguous to
|
| 479 |
+
# be able to tell what timezone has daylight savings
|
| 480 |
+
if (time.tzname[0] == time.tzname[1] and
|
| 481 |
+
time.daylight and found_zone not in ("utc", "gmt")):
|
| 482 |
+
break
|
| 483 |
+
else:
|
| 484 |
+
tz = value
|
| 485 |
+
break
|
| 486 |
+
# Deal with the cases where ambiguities arize
|
| 487 |
+
# don't assume default values for ISO week/year
|
| 488 |
+
if year is None and iso_year is not None:
|
| 489 |
+
if iso_week is None or weekday is None:
|
| 490 |
+
raise ValueError("ISO year directive '%G' must be used with "
|
| 491 |
+
"the ISO week directive '%V' and a weekday "
|
| 492 |
+
"directive ('%A', '%a', '%w', or '%u').")
|
| 493 |
+
if julian is not None:
|
| 494 |
+
raise ValueError("Day of the year directive '%j' is not "
|
| 495 |
+
"compatible with ISO year directive '%G'. "
|
| 496 |
+
"Use '%Y' instead.")
|
| 497 |
+
elif week_of_year is None and iso_week is not None:
|
| 498 |
+
if weekday is None:
|
| 499 |
+
raise ValueError("ISO week directive '%V' must be used with "
|
| 500 |
+
"the ISO year directive '%G' and a weekday "
|
| 501 |
+
"directive ('%A', '%a', '%w', or '%u').")
|
| 502 |
+
else:
|
| 503 |
+
raise ValueError("ISO week directive '%V' is incompatible with "
|
| 504 |
+
"the year directive '%Y'. Use the ISO year '%G' "
|
| 505 |
+
"instead.")
|
| 506 |
+
|
| 507 |
+
leap_year_fix = False
|
| 508 |
+
if year is None and month == 2 and day == 29:
|
| 509 |
+
year = 1904 # 1904 is first leap year of 20th century
|
| 510 |
+
leap_year_fix = True
|
| 511 |
+
elif year is None:
|
| 512 |
+
year = 1900
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
# If we know the week of the year and what day of that week, we can figure
|
| 516 |
+
# out the Julian day of the year.
|
| 517 |
+
if julian is None and weekday is not None:
|
| 518 |
+
if week_of_year is not None:
|
| 519 |
+
week_starts_Mon = True if week_of_year_start == 0 else False
|
| 520 |
+
julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,
|
| 521 |
+
week_starts_Mon)
|
| 522 |
+
elif iso_year is not None and iso_week is not None:
|
| 523 |
+
year, julian = _calc_julian_from_V(iso_year, iso_week, weekday + 1)
|
| 524 |
+
if julian is not None and julian <= 0:
|
| 525 |
+
year -= 1
|
| 526 |
+
yday = 366 if calendar.isleap(year) else 365
|
| 527 |
+
julian += yday
|
| 528 |
+
|
| 529 |
+
if julian is None:
|
| 530 |
+
# Cannot pre-calculate datetime_date() since can change in Julian
|
| 531 |
+
# calculation and thus could have different value for the day of
|
| 532 |
+
# the week calculation.
|
| 533 |
+
# Need to add 1 to result since first day of the year is 1, not 0.
|
| 534 |
+
julian = datetime_date(year, month, day).toordinal() - \
|
| 535 |
+
datetime_date(year, 1, 1).toordinal() + 1
|
| 536 |
+
else: # Assume that if they bothered to include Julian day (or if it was
|
| 537 |
+
# calculated above with year/week/weekday) it will be accurate.
|
| 538 |
+
datetime_result = datetime_date.fromordinal(
|
| 539 |
+
(julian - 1) +
|
| 540 |
+
datetime_date(year, 1, 1).toordinal())
|
| 541 |
+
year = datetime_result.year
|
| 542 |
+
month = datetime_result.month
|
| 543 |
+
day = datetime_result.day
|
| 544 |
+
if weekday is None:
|
| 545 |
+
weekday = datetime_date(year, month, day).weekday()
|
| 546 |
+
# Add timezone info
|
| 547 |
+
tzname = found_dict.get("Z")
|
| 548 |
+
|
| 549 |
+
if leap_year_fix:
|
| 550 |
+
# the caller didn't supply a year but asked for Feb 29th. We couldn't
|
| 551 |
+
# use the default of 1900 for computations. We set it back to ensure
|
| 552 |
+
# that February 29th is smaller than March 1st.
|
| 553 |
+
year = 1900
|
| 554 |
+
|
| 555 |
+
return (year, month, day,
|
| 556 |
+
hour, minute, second,
|
| 557 |
+
weekday, julian, tz, tzname, gmtoff), fraction, gmtoff_fraction
|
| 558 |
+
|
| 559 |
+
def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"):
|
| 560 |
+
"""Return a time struct based on the input string and the
|
| 561 |
+
format string."""
|
| 562 |
+
tt = _strptime(data_string, format)[0]
|
| 563 |
+
return time.struct_time(tt[:time._STRUCT_TM_ITEMS])
|
| 564 |
+
|
| 565 |
+
def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):
|
| 566 |
+
"""Return a class cls instance based on the input string and the
|
| 567 |
+
format string."""
|
| 568 |
+
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
|
| 569 |
+
tzname, gmtoff = tt[-2:]
|
| 570 |
+
args = tt[:6] + (fraction,)
|
| 571 |
+
if gmtoff is not None:
|
| 572 |
+
tzdelta = datetime_timedelta(seconds=gmtoff, microseconds=gmtoff_fraction)
|
| 573 |
+
if tzname:
|
| 574 |
+
tz = datetime_timezone(tzdelta, tzname)
|
| 575 |
+
else:
|
| 576 |
+
tz = datetime_timezone(tzdelta)
|
| 577 |
+
args += (tz,)
|
| 578 |
+
|
| 579 |
+
return cls(*args)
|
shared/package-files/06/06619670ff86b58913d1659471b92ef6f1c259f095e95f299e2ba52ac6f2aef5/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Authors: The scikit-learn developers
|
| 2 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 3 |
+
|
| 4 |
+
from .glm import (
|
| 5 |
+
GammaRegressor,
|
| 6 |
+
PoissonRegressor,
|
| 7 |
+
TweedieRegressor,
|
| 8 |
+
_GeneralizedLinearRegressor,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"GammaRegressor",
|
| 13 |
+
"PoissonRegressor",
|
| 14 |
+
"TweedieRegressor",
|
| 15 |
+
"_GeneralizedLinearRegressor",
|
| 16 |
+
]
|
shared/package-files/06/0663c5c7805e9b2f331ecb92aae1ad8b59913f2ff047be8a2a77c8f62c4716d2/_prelu_kernel_backward_cpu_dispatch.h
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cpu {
|
| 19 |
+
|
| 20 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor> _prelu_kernel_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight);
|
| 21 |
+
|
| 22 |
+
} // namespace cpu
|
| 23 |
+
} // namespace at
|
shared/package-files/06/0669132a68939389b6723fa2b9e9626adc33deeb7ff52b000415b9d6f9d09d95/scripts.py
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C) 2013-2015 Vinay Sajip.
|
| 4 |
+
# Licensed to the Python Software Foundation under a contributor agreement.
|
| 5 |
+
# See LICENSE.txt and CONTRIBUTORS.txt.
|
| 6 |
+
#
|
| 7 |
+
from io import BytesIO
|
| 8 |
+
import logging
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import struct
|
| 12 |
+
import sys
|
| 13 |
+
import time
|
| 14 |
+
from zipfile import ZipInfo
|
| 15 |
+
|
| 16 |
+
from .compat import sysconfig, detect_encoding, ZipFile
|
| 17 |
+
from .resources import finder
|
| 18 |
+
from .util import (FileOperator, get_export_entry, convert_path,
|
| 19 |
+
get_executable, get_platform, in_venv)
|
| 20 |
+
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
_DEFAULT_MANIFEST = '''
|
| 24 |
+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
| 25 |
+
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
|
| 26 |
+
<assemblyIdentity version="1.0.0.0"
|
| 27 |
+
processorArchitecture="X86"
|
| 28 |
+
name="%s"
|
| 29 |
+
type="win32"/>
|
| 30 |
+
|
| 31 |
+
<!-- Identify the application security requirements. -->
|
| 32 |
+
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
|
| 33 |
+
<security>
|
| 34 |
+
<requestedPrivileges>
|
| 35 |
+
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
|
| 36 |
+
</requestedPrivileges>
|
| 37 |
+
</security>
|
| 38 |
+
</trustInfo>
|
| 39 |
+
</assembly>'''.strip()
|
| 40 |
+
|
| 41 |
+
# check if Python is called on the first line with this expression
|
| 42 |
+
FIRST_LINE_RE = re.compile(b'^#!.*pythonw?[0-9.]*([ \t].*)?$')
|
| 43 |
+
SCRIPT_TEMPLATE = r'''# -*- coding: utf-8 -*-
|
| 44 |
+
import re
|
| 45 |
+
import sys
|
| 46 |
+
from %(module)s import %(import_name)s
|
| 47 |
+
if __name__ == '__main__':
|
| 48 |
+
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
| 49 |
+
sys.exit(%(func)s())
|
| 50 |
+
'''
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def enquote_executable(executable):
|
| 54 |
+
if ' ' in executable:
|
| 55 |
+
# make sure we quote only the executable in case of env
|
| 56 |
+
# for example /usr/bin/env "/dir with spaces/bin/jython"
|
| 57 |
+
# instead of "/usr/bin/env /dir with spaces/bin/jython"
|
| 58 |
+
# otherwise whole
|
| 59 |
+
if executable.startswith('/usr/bin/env '):
|
| 60 |
+
env, _executable = executable.split(' ', 1)
|
| 61 |
+
if ' ' in _executable and not _executable.startswith('"'):
|
| 62 |
+
executable = '%s "%s"' % (env, _executable)
|
| 63 |
+
else:
|
| 64 |
+
if not executable.startswith('"'):
|
| 65 |
+
executable = '"%s"' % executable
|
| 66 |
+
return executable
|
| 67 |
+
|
| 68 |
+
# Keep the old name around (for now), as there is at least one project using it!
|
| 69 |
+
_enquote_executable = enquote_executable
|
| 70 |
+
|
| 71 |
+
class ScriptMaker(object):
|
| 72 |
+
"""
|
| 73 |
+
A class to copy or create scripts from source scripts or callable
|
| 74 |
+
specifications.
|
| 75 |
+
"""
|
| 76 |
+
script_template = SCRIPT_TEMPLATE
|
| 77 |
+
|
| 78 |
+
executable = None # for shebangs
|
| 79 |
+
|
| 80 |
+
def __init__(self, source_dir, target_dir, add_launchers=True,
|
| 81 |
+
dry_run=False, fileop=None):
|
| 82 |
+
self.source_dir = source_dir
|
| 83 |
+
self.target_dir = target_dir
|
| 84 |
+
self.add_launchers = add_launchers
|
| 85 |
+
self.force = False
|
| 86 |
+
self.clobber = False
|
| 87 |
+
# It only makes sense to set mode bits on POSIX.
|
| 88 |
+
self.set_mode = (os.name == 'posix') or (os.name == 'java' and
|
| 89 |
+
os._name == 'posix')
|
| 90 |
+
self.variants = set(('', 'X.Y'))
|
| 91 |
+
self._fileop = fileop or FileOperator(dry_run)
|
| 92 |
+
|
| 93 |
+
self._is_nt = os.name == 'nt' or (
|
| 94 |
+
os.name == 'java' and os._name == 'nt')
|
| 95 |
+
self.version_info = sys.version_info
|
| 96 |
+
|
| 97 |
+
def _get_alternate_executable(self, executable, options):
|
| 98 |
+
if options.get('gui', False) and self._is_nt: # pragma: no cover
|
| 99 |
+
dn, fn = os.path.split(executable)
|
| 100 |
+
fn = fn.replace('python', 'pythonw')
|
| 101 |
+
executable = os.path.join(dn, fn)
|
| 102 |
+
return executable
|
| 103 |
+
|
| 104 |
+
if sys.platform.startswith('java'): # pragma: no cover
|
| 105 |
+
def _is_shell(self, executable):
|
| 106 |
+
"""
|
| 107 |
+
Determine if the specified executable is a script
|
| 108 |
+
(contains a #! line)
|
| 109 |
+
"""
|
| 110 |
+
try:
|
| 111 |
+
with open(executable) as fp:
|
| 112 |
+
return fp.read(2) == '#!'
|
| 113 |
+
except (OSError, IOError):
|
| 114 |
+
logger.warning('Failed to open %s', executable)
|
| 115 |
+
return False
|
| 116 |
+
|
| 117 |
+
def _fix_jython_executable(self, executable):
|
| 118 |
+
if self._is_shell(executable):
|
| 119 |
+
# Workaround for Jython is not needed on Linux systems.
|
| 120 |
+
import java
|
| 121 |
+
|
| 122 |
+
if java.lang.System.getProperty('os.name') == 'Linux':
|
| 123 |
+
return executable
|
| 124 |
+
elif executable.lower().endswith('jython.exe'):
|
| 125 |
+
# Use wrapper exe for Jython on Windows
|
| 126 |
+
return executable
|
| 127 |
+
return '/usr/bin/env %s' % executable
|
| 128 |
+
|
| 129 |
+
def _build_shebang(self, executable, post_interp):
|
| 130 |
+
"""
|
| 131 |
+
Build a shebang line. In the simple case (on Windows, or a shebang line
|
| 132 |
+
which is not too long or contains spaces) use a simple formulation for
|
| 133 |
+
the shebang. Otherwise, use /bin/sh as the executable, with a contrived
|
| 134 |
+
shebang which allows the script to run either under Python or sh, using
|
| 135 |
+
suitable quoting. Thanks to Harald Nordgren for his input.
|
| 136 |
+
|
| 137 |
+
See also: http://www.in-ulm.de/~mascheck/various/shebang/#length
|
| 138 |
+
https://hg.mozilla.org/mozilla-central/file/tip/mach
|
| 139 |
+
"""
|
| 140 |
+
if os.name != 'posix':
|
| 141 |
+
simple_shebang = True
|
| 142 |
+
else:
|
| 143 |
+
# Add 3 for '#!' prefix and newline suffix.
|
| 144 |
+
shebang_length = len(executable) + len(post_interp) + 3
|
| 145 |
+
if sys.platform == 'darwin':
|
| 146 |
+
max_shebang_length = 512
|
| 147 |
+
else:
|
| 148 |
+
max_shebang_length = 127
|
| 149 |
+
simple_shebang = ((b' ' not in executable) and
|
| 150 |
+
(shebang_length <= max_shebang_length))
|
| 151 |
+
|
| 152 |
+
if simple_shebang:
|
| 153 |
+
result = b'#!' + executable + post_interp + b'\n'
|
| 154 |
+
else:
|
| 155 |
+
result = b'#!/bin/sh\n'
|
| 156 |
+
result += b"'''exec' " + executable + post_interp + b' "$0" "$@"\n'
|
| 157 |
+
result += b"' '''"
|
| 158 |
+
return result
|
| 159 |
+
|
| 160 |
+
def _get_shebang(self, encoding, post_interp=b'', options=None):
|
| 161 |
+
enquote = True
|
| 162 |
+
if self.executable:
|
| 163 |
+
executable = self.executable
|
| 164 |
+
enquote = False # assume this will be taken care of
|
| 165 |
+
elif not sysconfig.is_python_build():
|
| 166 |
+
executable = get_executable()
|
| 167 |
+
elif in_venv(): # pragma: no cover
|
| 168 |
+
executable = os.path.join(sysconfig.get_path('scripts'),
|
| 169 |
+
'python%s' % sysconfig.get_config_var('EXE'))
|
| 170 |
+
else: # pragma: no cover
|
| 171 |
+
executable = os.path.join(
|
| 172 |
+
sysconfig.get_config_var('BINDIR'),
|
| 173 |
+
'python%s%s' % (sysconfig.get_config_var('VERSION'),
|
| 174 |
+
sysconfig.get_config_var('EXE')))
|
| 175 |
+
if not os.path.isfile(executable):
|
| 176 |
+
# for Python builds from source on Windows, no Python executables with
|
| 177 |
+
# a version suffix are created, so we use python.exe
|
| 178 |
+
executable = os.path.join(sysconfig.get_config_var('BINDIR'),
|
| 179 |
+
'python%s' % (sysconfig.get_config_var('EXE')))
|
| 180 |
+
if options:
|
| 181 |
+
executable = self._get_alternate_executable(executable, options)
|
| 182 |
+
|
| 183 |
+
if sys.platform.startswith('java'): # pragma: no cover
|
| 184 |
+
executable = self._fix_jython_executable(executable)
|
| 185 |
+
|
| 186 |
+
# Normalise case for Windows - COMMENTED OUT
|
| 187 |
+
# executable = os.path.normcase(executable)
|
| 188 |
+
# N.B. The normalising operation above has been commented out: See
|
| 189 |
+
# issue #124. Although paths in Windows are generally case-insensitive,
|
| 190 |
+
# they aren't always. For example, a path containing a ẞ (which is a
|
| 191 |
+
# LATIN CAPITAL LETTER SHARP S - U+1E9E) is normcased to ß (which is a
|
| 192 |
+
# LATIN SMALL LETTER SHARP S' - U+00DF). The two are not considered by
|
| 193 |
+
# Windows as equivalent in path names.
|
| 194 |
+
|
| 195 |
+
# If the user didn't specify an executable, it may be necessary to
|
| 196 |
+
# cater for executable paths with spaces (not uncommon on Windows)
|
| 197 |
+
if enquote:
|
| 198 |
+
executable = enquote_executable(executable)
|
| 199 |
+
# Issue #51: don't use fsencode, since we later try to
|
| 200 |
+
# check that the shebang is decodable using utf-8.
|
| 201 |
+
executable = executable.encode('utf-8')
|
| 202 |
+
# in case of IronPython, play safe and enable frames support
|
| 203 |
+
if (sys.platform == 'cli' and '-X:Frames' not in post_interp
|
| 204 |
+
and '-X:FullFrames' not in post_interp): # pragma: no cover
|
| 205 |
+
post_interp += b' -X:Frames'
|
| 206 |
+
shebang = self._build_shebang(executable, post_interp)
|
| 207 |
+
# Python parser starts to read a script using UTF-8 until
|
| 208 |
+
# it gets a #coding:xxx cookie. The shebang has to be the
|
| 209 |
+
# first line of a file, the #coding:xxx cookie cannot be
|
| 210 |
+
# written before. So the shebang has to be decodable from
|
| 211 |
+
# UTF-8.
|
| 212 |
+
try:
|
| 213 |
+
shebang.decode('utf-8')
|
| 214 |
+
except UnicodeDecodeError: # pragma: no cover
|
| 215 |
+
raise ValueError(
|
| 216 |
+
'The shebang (%r) is not decodable from utf-8' % shebang)
|
| 217 |
+
# If the script is encoded to a custom encoding (use a
|
| 218 |
+
# #coding:xxx cookie), the shebang has to be decodable from
|
| 219 |
+
# the script encoding too.
|
| 220 |
+
if encoding != 'utf-8':
|
| 221 |
+
try:
|
| 222 |
+
shebang.decode(encoding)
|
| 223 |
+
except UnicodeDecodeError: # pragma: no cover
|
| 224 |
+
raise ValueError(
|
| 225 |
+
'The shebang (%r) is not decodable '
|
| 226 |
+
'from the script encoding (%r)' % (shebang, encoding))
|
| 227 |
+
return shebang
|
| 228 |
+
|
| 229 |
+
def _get_script_text(self, entry):
|
| 230 |
+
return self.script_template % dict(module=entry.prefix,
|
| 231 |
+
import_name=entry.suffix.split('.')[0],
|
| 232 |
+
func=entry.suffix)
|
| 233 |
+
|
| 234 |
+
manifest = _DEFAULT_MANIFEST
|
| 235 |
+
|
| 236 |
+
def get_manifest(self, exename):
|
| 237 |
+
base = os.path.basename(exename)
|
| 238 |
+
return self.manifest % base
|
| 239 |
+
|
| 240 |
+
def _write_script(self, names, shebang, script_bytes, filenames, ext):
|
| 241 |
+
use_launcher = self.add_launchers and self._is_nt
|
| 242 |
+
linesep = os.linesep.encode('utf-8')
|
| 243 |
+
if not shebang.endswith(linesep):
|
| 244 |
+
shebang += linesep
|
| 245 |
+
if not use_launcher:
|
| 246 |
+
script_bytes = shebang + script_bytes
|
| 247 |
+
else: # pragma: no cover
|
| 248 |
+
if ext == 'py':
|
| 249 |
+
launcher = self._get_launcher('t')
|
| 250 |
+
else:
|
| 251 |
+
launcher = self._get_launcher('w')
|
| 252 |
+
stream = BytesIO()
|
| 253 |
+
with ZipFile(stream, 'w') as zf:
|
| 254 |
+
source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH')
|
| 255 |
+
if source_date_epoch:
|
| 256 |
+
date_time = time.gmtime(int(source_date_epoch))[:6]
|
| 257 |
+
zinfo = ZipInfo(filename='__main__.py', date_time=date_time)
|
| 258 |
+
zf.writestr(zinfo, script_bytes)
|
| 259 |
+
else:
|
| 260 |
+
zf.writestr('__main__.py', script_bytes)
|
| 261 |
+
zip_data = stream.getvalue()
|
| 262 |
+
script_bytes = launcher + shebang + zip_data
|
| 263 |
+
for name in names:
|
| 264 |
+
outname = os.path.join(self.target_dir, name)
|
| 265 |
+
if use_launcher: # pragma: no cover
|
| 266 |
+
n, e = os.path.splitext(outname)
|
| 267 |
+
if e.startswith('.py'):
|
| 268 |
+
outname = n
|
| 269 |
+
outname = '%s.exe' % outname
|
| 270 |
+
try:
|
| 271 |
+
self._fileop.write_binary_file(outname, script_bytes)
|
| 272 |
+
except Exception:
|
| 273 |
+
# Failed writing an executable - it might be in use.
|
| 274 |
+
logger.warning('Failed to write executable - trying to '
|
| 275 |
+
'use .deleteme logic')
|
| 276 |
+
dfname = '%s.deleteme' % outname
|
| 277 |
+
if os.path.exists(dfname):
|
| 278 |
+
os.remove(dfname) # Not allowed to fail here
|
| 279 |
+
os.rename(outname, dfname) # nor here
|
| 280 |
+
self._fileop.write_binary_file(outname, script_bytes)
|
| 281 |
+
logger.debug('Able to replace executable using '
|
| 282 |
+
'.deleteme logic')
|
| 283 |
+
try:
|
| 284 |
+
os.remove(dfname)
|
| 285 |
+
except Exception:
|
| 286 |
+
pass # still in use - ignore error
|
| 287 |
+
else:
|
| 288 |
+
if self._is_nt and not outname.endswith('.' + ext): # pragma: no cover
|
| 289 |
+
outname = '%s.%s' % (outname, ext)
|
| 290 |
+
if os.path.exists(outname) and not self.clobber:
|
| 291 |
+
logger.warning('Skipping existing file %s', outname)
|
| 292 |
+
continue
|
| 293 |
+
self._fileop.write_binary_file(outname, script_bytes)
|
| 294 |
+
if self.set_mode:
|
| 295 |
+
self._fileop.set_executable_mode([outname])
|
| 296 |
+
filenames.append(outname)
|
| 297 |
+
|
| 298 |
+
variant_separator = '-'
|
| 299 |
+
|
| 300 |
+
def get_script_filenames(self, name):
|
| 301 |
+
result = set()
|
| 302 |
+
if '' in self.variants:
|
| 303 |
+
result.add(name)
|
| 304 |
+
if 'X' in self.variants:
|
| 305 |
+
result.add('%s%s' % (name, self.version_info[0]))
|
| 306 |
+
if 'X.Y' in self.variants:
|
| 307 |
+
result.add('%s%s%s.%s' % (name, self.variant_separator,
|
| 308 |
+
self.version_info[0], self.version_info[1]))
|
| 309 |
+
return result
|
| 310 |
+
|
| 311 |
+
def _make_script(self, entry, filenames, options=None):
|
| 312 |
+
post_interp = b''
|
| 313 |
+
if options:
|
| 314 |
+
args = options.get('interpreter_args', [])
|
| 315 |
+
if args:
|
| 316 |
+
args = ' %s' % ' '.join(args)
|
| 317 |
+
post_interp = args.encode('utf-8')
|
| 318 |
+
shebang = self._get_shebang('utf-8', post_interp, options=options)
|
| 319 |
+
script = self._get_script_text(entry).encode('utf-8')
|
| 320 |
+
scriptnames = self.get_script_filenames(entry.name)
|
| 321 |
+
if options and options.get('gui', False):
|
| 322 |
+
ext = 'pyw'
|
| 323 |
+
else:
|
| 324 |
+
ext = 'py'
|
| 325 |
+
self._write_script(scriptnames, shebang, script, filenames, ext)
|
| 326 |
+
|
| 327 |
+
def _copy_script(self, script, filenames):
|
| 328 |
+
adjust = False
|
| 329 |
+
script = os.path.join(self.source_dir, convert_path(script))
|
| 330 |
+
outname = os.path.join(self.target_dir, os.path.basename(script))
|
| 331 |
+
if not self.force and not self._fileop.newer(script, outname):
|
| 332 |
+
logger.debug('not copying %s (up-to-date)', script)
|
| 333 |
+
return
|
| 334 |
+
|
| 335 |
+
# Always open the file, but ignore failures in dry-run mode --
|
| 336 |
+
# that way, we'll get accurate feedback if we can read the
|
| 337 |
+
# script.
|
| 338 |
+
try:
|
| 339 |
+
f = open(script, 'rb')
|
| 340 |
+
except IOError: # pragma: no cover
|
| 341 |
+
if not self.dry_run:
|
| 342 |
+
raise
|
| 343 |
+
f = None
|
| 344 |
+
else:
|
| 345 |
+
first_line = f.readline()
|
| 346 |
+
if not first_line: # pragma: no cover
|
| 347 |
+
logger.warning('%s is an empty file (skipping)', script)
|
| 348 |
+
return
|
| 349 |
+
|
| 350 |
+
match = FIRST_LINE_RE.match(first_line.replace(b'\r\n', b'\n'))
|
| 351 |
+
if match:
|
| 352 |
+
adjust = True
|
| 353 |
+
post_interp = match.group(1) or b''
|
| 354 |
+
|
| 355 |
+
if not adjust:
|
| 356 |
+
if f:
|
| 357 |
+
f.close()
|
| 358 |
+
self._fileop.copy_file(script, outname)
|
| 359 |
+
if self.set_mode:
|
| 360 |
+
self._fileop.set_executable_mode([outname])
|
| 361 |
+
filenames.append(outname)
|
| 362 |
+
else:
|
| 363 |
+
logger.info('copying and adjusting %s -> %s', script,
|
| 364 |
+
self.target_dir)
|
| 365 |
+
if not self._fileop.dry_run:
|
| 366 |
+
encoding, lines = detect_encoding(f.readline)
|
| 367 |
+
f.seek(0)
|
| 368 |
+
shebang = self._get_shebang(encoding, post_interp)
|
| 369 |
+
if b'pythonw' in first_line: # pragma: no cover
|
| 370 |
+
ext = 'pyw'
|
| 371 |
+
else:
|
| 372 |
+
ext = 'py'
|
| 373 |
+
n = os.path.basename(outname)
|
| 374 |
+
self._write_script([n], shebang, f.read(), filenames, ext)
|
| 375 |
+
if f:
|
| 376 |
+
f.close()
|
| 377 |
+
|
| 378 |
+
@property
|
| 379 |
+
def dry_run(self):
|
| 380 |
+
return self._fileop.dry_run
|
| 381 |
+
|
| 382 |
+
@dry_run.setter
|
| 383 |
+
def dry_run(self, value):
|
| 384 |
+
self._fileop.dry_run = value
|
| 385 |
+
|
| 386 |
+
if os.name == 'nt' or (os.name == 'java' and os._name == 'nt'): # pragma: no cover
|
| 387 |
+
# Executable launcher support.
|
| 388 |
+
# Launchers are from https://bitbucket.org/vinay.sajip/simple_launcher/
|
| 389 |
+
|
| 390 |
+
def _get_launcher(self, kind):
|
| 391 |
+
if struct.calcsize('P') == 8: # 64-bit
|
| 392 |
+
bits = '64'
|
| 393 |
+
else:
|
| 394 |
+
bits = '32'
|
| 395 |
+
platform_suffix = '-arm' if get_platform() == 'win-arm64' else ''
|
| 396 |
+
name = '%s%s%s.exe' % (kind, bits, platform_suffix)
|
| 397 |
+
# Issue 31: don't hardcode an absolute package name, but
|
| 398 |
+
# determine it relative to the current package
|
| 399 |
+
distlib_package = __name__.rsplit('.', 1)[0]
|
| 400 |
+
resource = finder(distlib_package).find(name)
|
| 401 |
+
if not resource:
|
| 402 |
+
msg = ('Unable to find resource %s in package %s' % (name,
|
| 403 |
+
distlib_package))
|
| 404 |
+
raise ValueError(msg)
|
| 405 |
+
return resource.bytes
|
| 406 |
+
|
| 407 |
+
# Public API follows
|
| 408 |
+
|
| 409 |
+
def make(self, specification, options=None):
|
| 410 |
+
"""
|
| 411 |
+
Make a script.
|
| 412 |
+
|
| 413 |
+
:param specification: The specification, which is either a valid export
|
| 414 |
+
entry specification (to make a script from a
|
| 415 |
+
callable) or a filename (to make a script by
|
| 416 |
+
copying from a source location).
|
| 417 |
+
:param options: A dictionary of options controlling script generation.
|
| 418 |
+
:return: A list of all absolute pathnames written to.
|
| 419 |
+
"""
|
| 420 |
+
filenames = []
|
| 421 |
+
entry = get_export_entry(specification)
|
| 422 |
+
if entry is None:
|
| 423 |
+
self._copy_script(specification, filenames)
|
| 424 |
+
else:
|
| 425 |
+
self._make_script(entry, filenames, options=options)
|
| 426 |
+
return filenames
|
| 427 |
+
|
| 428 |
+
def make_multiple(self, specifications, options=None):
|
| 429 |
+
"""
|
| 430 |
+
Take a list of specifications and make scripts from them,
|
| 431 |
+
:param specifications: A list of specifications.
|
| 432 |
+
:return: A list of all absolute pathnames written to,
|
| 433 |
+
"""
|
| 434 |
+
filenames = []
|
| 435 |
+
for specification in specifications:
|
| 436 |
+
filenames.extend(self.make(specification, options))
|
| 437 |
+
return filenames
|
shared/package-files/06/0669a58a817af3261c88ad611491ae32a55c708efbb5c3b694e2edb845859729/bitwise_and_ops.h
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API bitwise_and_Tensor_out {
|
| 18 |
+
using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_and")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)")
|
| 24 |
+
static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
|
| 25 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API bitwise_and_Scalar_out {
|
| 29 |
+
using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, at::Tensor &);
|
| 30 |
+
using ptr_schema = schema*;
|
| 31 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 32 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_and")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)")
|
| 35 |
+
static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, at::Tensor & out);
|
| 36 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, at::Tensor & out);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
struct TORCH_API bitwise_and_Scalar {
|
| 40 |
+
using schema = at::Tensor (const at::Tensor &, const at::Scalar &);
|
| 41 |
+
using ptr_schema = schema*;
|
| 42 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 43 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_and")
|
| 44 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar")
|
| 45 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and.Scalar(Tensor self, Scalar other) -> Tensor")
|
| 46 |
+
static at::Tensor call(const at::Tensor & self, const at::Scalar & other);
|
| 47 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other);
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
struct TORCH_API bitwise_and_Scalar_Tensor {
|
| 51 |
+
using schema = at::Tensor (const at::Scalar &, const at::Tensor &);
|
| 52 |
+
using ptr_schema = schema*;
|
| 53 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 54 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_and")
|
| 55 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Tensor")
|
| 56 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and.Scalar_Tensor(Scalar self, Tensor other) -> Tensor")
|
| 57 |
+
static at::Tensor call(const at::Scalar & self, const at::Tensor & other);
|
| 58 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & other);
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
struct TORCH_API bitwise_and_Tensor {
|
| 62 |
+
using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
|
| 63 |
+
using ptr_schema = schema*;
|
| 64 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 65 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_and")
|
| 66 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
|
| 67 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and.Tensor(Tensor self, Tensor other) -> Tensor")
|
| 68 |
+
static at::Tensor call(const at::Tensor & self, const at::Tensor & other);
|
| 69 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other);
|
| 70 |
+
};
|
| 71 |
+
|
| 72 |
+
struct TORCH_API bitwise_and__Scalar {
|
| 73 |
+
using schema = at::Tensor & (at::Tensor &, const at::Scalar &);
|
| 74 |
+
using ptr_schema = schema*;
|
| 75 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 76 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_and_")
|
| 77 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar")
|
| 78 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)")
|
| 79 |
+
static at::Tensor & call(at::Tensor & self, const at::Scalar & other);
|
| 80 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other);
|
| 81 |
+
};
|
| 82 |
+
|
| 83 |
+
struct TORCH_API bitwise_and__Tensor {
|
| 84 |
+
using schema = at::Tensor & (at::Tensor &, const at::Tensor &);
|
| 85 |
+
using ptr_schema = schema*;
|
| 86 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 87 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_and_")
|
| 88 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
|
| 89 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)")
|
| 90 |
+
static at::Tensor & call(at::Tensor & self, const at::Tensor & other);
|
| 91 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other);
|
| 92 |
+
};
|
| 93 |
+
|
| 94 |
+
struct TORCH_API bitwise_and_Scalar_Tensor_out {
|
| 95 |
+
using schema = at::Tensor & (const at::Scalar &, const at::Tensor &, at::Tensor &);
|
| 96 |
+
using ptr_schema = schema*;
|
| 97 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 98 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bitwise_and")
|
| 99 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_Tensor_out")
|
| 100 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bitwise_and.Scalar_Tensor_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)")
|
| 101 |
+
static at::Tensor & call(const at::Scalar & self, const at::Tensor & other, at::Tensor & out);
|
| 102 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & other, at::Tensor & out);
|
| 103 |
+
};
|
| 104 |
+
|
| 105 |
+
}} // namespace at::_ops
|
shared/package-files/06/0669c432544417b1b4079cdd68946c773a8845d87c7628938ac05b09523a169d/common.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
from pandas import (
|
| 6 |
+
DataFrame,
|
| 7 |
+
concat,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from pandas._typing import AxisInt
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _check_mixed_float(df, dtype=None):
|
| 15 |
+
# float16 are most likely to be upcasted to float32
|
| 16 |
+
dtypes = {"A": "float32", "B": "float32", "C": "float16", "D": "float64"}
|
| 17 |
+
if isinstance(dtype, str):
|
| 18 |
+
dtypes = {k: dtype for k, v in dtypes.items()}
|
| 19 |
+
elif isinstance(dtype, dict):
|
| 20 |
+
dtypes.update(dtype)
|
| 21 |
+
if dtypes.get("A"):
|
| 22 |
+
assert df.dtypes["A"] == dtypes["A"]
|
| 23 |
+
if dtypes.get("B"):
|
| 24 |
+
assert df.dtypes["B"] == dtypes["B"]
|
| 25 |
+
if dtypes.get("C"):
|
| 26 |
+
assert df.dtypes["C"] == dtypes["C"]
|
| 27 |
+
if dtypes.get("D"):
|
| 28 |
+
assert df.dtypes["D"] == dtypes["D"]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _check_mixed_int(df, dtype=None):
|
| 32 |
+
dtypes = {"A": "int32", "B": "uint64", "C": "uint8", "D": "int64"}
|
| 33 |
+
if isinstance(dtype, str):
|
| 34 |
+
dtypes = {k: dtype for k, v in dtypes.items()}
|
| 35 |
+
elif isinstance(dtype, dict):
|
| 36 |
+
dtypes.update(dtype)
|
| 37 |
+
if dtypes.get("A"):
|
| 38 |
+
assert df.dtypes["A"] == dtypes["A"]
|
| 39 |
+
if dtypes.get("B"):
|
| 40 |
+
assert df.dtypes["B"] == dtypes["B"]
|
| 41 |
+
if dtypes.get("C"):
|
| 42 |
+
assert df.dtypes["C"] == dtypes["C"]
|
| 43 |
+
if dtypes.get("D"):
|
| 44 |
+
assert df.dtypes["D"] == dtypes["D"]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def zip_frames(frames: list[DataFrame], axis: AxisInt = 1) -> DataFrame:
|
| 48 |
+
"""
|
| 49 |
+
take a list of frames, zip them together under the
|
| 50 |
+
assumption that these all have the first frames' index/columns.
|
| 51 |
+
|
| 52 |
+
Returns
|
| 53 |
+
-------
|
| 54 |
+
new_frame : DataFrame
|
| 55 |
+
"""
|
| 56 |
+
if axis == 1:
|
| 57 |
+
columns = frames[0].columns
|
| 58 |
+
zipped = [f.loc[:, c] for c in columns for f in frames]
|
| 59 |
+
return concat(zipped, axis=1)
|
| 60 |
+
else:
|
| 61 |
+
index = frames[0].index
|
| 62 |
+
zipped = [f.loc[i, :] for i in index for f in frames]
|
| 63 |
+
return DataFrame(zipped)
|
shared/package-files/06/066a541e6d38ead952d63cc32afbac51a33acf354799f235c582eab17488105d/tty.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Terminal utilities."""
|
| 2 |
+
|
| 3 |
+
# Author: Steen Lumholt.
|
| 4 |
+
|
| 5 |
+
from termios import *
|
| 6 |
+
|
| 7 |
+
__all__ = ["setraw", "setcbreak"]
|
| 8 |
+
|
| 9 |
+
# Indexes for termios list.
|
| 10 |
+
IFLAG = 0
|
| 11 |
+
OFLAG = 1
|
| 12 |
+
CFLAG = 2
|
| 13 |
+
LFLAG = 3
|
| 14 |
+
ISPEED = 4
|
| 15 |
+
OSPEED = 5
|
| 16 |
+
CC = 6
|
| 17 |
+
|
| 18 |
+
def setraw(fd, when=TCSAFLUSH):
|
| 19 |
+
"""Put terminal into a raw mode."""
|
| 20 |
+
mode = tcgetattr(fd)
|
| 21 |
+
mode[IFLAG] = mode[IFLAG] & ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON)
|
| 22 |
+
mode[OFLAG] = mode[OFLAG] & ~(OPOST)
|
| 23 |
+
mode[CFLAG] = mode[CFLAG] & ~(CSIZE | PARENB)
|
| 24 |
+
mode[CFLAG] = mode[CFLAG] | CS8
|
| 25 |
+
mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON | IEXTEN | ISIG)
|
| 26 |
+
mode[CC][VMIN] = 1
|
| 27 |
+
mode[CC][VTIME] = 0
|
| 28 |
+
tcsetattr(fd, when, mode)
|
| 29 |
+
|
| 30 |
+
def setcbreak(fd, when=TCSAFLUSH):
|
| 31 |
+
"""Put terminal into a cbreak mode."""
|
| 32 |
+
mode = tcgetattr(fd)
|
| 33 |
+
mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON)
|
| 34 |
+
mode[CC][VMIN] = 1
|
| 35 |
+
mode[CC][VTIME] = 0
|
| 36 |
+
tcsetattr(fd, when, mode)
|
shared/package-files/06/066ec787f6844f1e8c4cddd6bbb4a28f2e2b60647fd6168d1ac8b7c5fceb00a3/test_digamma.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from numpy import pi, log, sqrt
|
| 3 |
+
from numpy.testing import assert_, assert_equal
|
| 4 |
+
|
| 5 |
+
from scipy.special._testutils import FuncData
|
| 6 |
+
import scipy.special as sc
|
| 7 |
+
|
| 8 |
+
# Euler-Mascheroni constant
|
| 9 |
+
euler = 0.57721566490153286
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_consistency():
|
| 13 |
+
# Make sure the implementation of digamma for real arguments
|
| 14 |
+
# agrees with the implementation of digamma for complex arguments.
|
| 15 |
+
|
| 16 |
+
# It's all poles after -1e16
|
| 17 |
+
x = np.r_[-np.logspace(15, -30, 200), np.logspace(-30, 300, 200)]
|
| 18 |
+
dataset = np.vstack((x + 0j, sc.digamma(x))).T
|
| 19 |
+
FuncData(sc.digamma, dataset, 0, 1, rtol=5e-14, nan_ok=True).check()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_special_values():
|
| 23 |
+
# Test special values from Gauss's digamma theorem. See
|
| 24 |
+
#
|
| 25 |
+
# https://en.wikipedia.org/wiki/Digamma_function
|
| 26 |
+
|
| 27 |
+
dataset = [
|
| 28 |
+
(1, -euler),
|
| 29 |
+
(0.5, -2*log(2) - euler),
|
| 30 |
+
(1/3, -pi/(2*sqrt(3)) - 3*log(3)/2 - euler),
|
| 31 |
+
(1/4, -pi/2 - 3*log(2) - euler),
|
| 32 |
+
(1/6, -pi*sqrt(3)/2 - 2*log(2) - 3*log(3)/2 - euler),
|
| 33 |
+
(1/8,
|
| 34 |
+
-pi/2 - 4*log(2) - (pi + log(2 + sqrt(2)) - log(2 - sqrt(2)))/sqrt(2) - euler)
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
dataset = np.asarray(dataset)
|
| 38 |
+
FuncData(sc.digamma, dataset, 0, 1, rtol=1e-14).check()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_nonfinite():
|
| 42 |
+
pts = [0.0, -0.0, np.inf]
|
| 43 |
+
std = [-np.inf, np.inf, np.inf]
|
| 44 |
+
assert_equal(sc.digamma(pts), std)
|
| 45 |
+
assert_(all(np.isnan(sc.digamma([-np.inf, -1]))))
|
shared/package-files/06/0670145a35bbb055059594c037004fc42d9a35eeef98e1324eceaa53915fba22/__init__.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Wrapt is a library for decorators, wrappers and monkey patching.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def _format_version(parts):
|
| 7 |
+
base = ".".join(parts[:3])
|
| 8 |
+
if len(parts) == 3:
|
| 9 |
+
return base
|
| 10 |
+
suffix = parts[3]
|
| 11 |
+
return (
|
| 12 |
+
f"{base}.{suffix}" if suffix.startswith(("dev", "post")) else f"{base}{suffix}"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
__version_info__ = ("2", "5", "1")
|
| 17 |
+
__version__ = _format_version(__version_info__)
|
| 18 |
+
|
| 19 |
+
from .__wrapt__ import (
|
| 20 |
+
BaseObjectProxy,
|
| 21 |
+
BoundFunctionWrapper,
|
| 22 |
+
CallableObjectProxy,
|
| 23 |
+
FunctionWrapper,
|
| 24 |
+
PartialCallableObjectProxy,
|
| 25 |
+
partial,
|
| 26 |
+
)
|
| 27 |
+
from .caching import lru_cache
|
| 28 |
+
from .decorators import (
|
| 29 |
+
AdapterFactory,
|
| 30 |
+
adapter_factory,
|
| 31 |
+
bind_state_to_wrapper,
|
| 32 |
+
decorator,
|
| 33 |
+
)
|
| 34 |
+
from .doc import with_doc
|
| 35 |
+
from .exceptions import (
|
| 36 |
+
PathResolutionError,
|
| 37 |
+
TargetModuleNotFoundError,
|
| 38 |
+
WrapperChainTooDeepError,
|
| 39 |
+
WrapperNotFoundError,
|
| 40 |
+
WrapperNotInitializedError,
|
| 41 |
+
WrapperNotOutermostError,
|
| 42 |
+
)
|
| 43 |
+
from .importer import (
|
| 44 |
+
discover_post_import_hooks,
|
| 45 |
+
notify_module_loaded,
|
| 46 |
+
register_post_import_hook,
|
| 47 |
+
when_imported,
|
| 48 |
+
)
|
| 49 |
+
from .patches import (
|
| 50 |
+
MISSING,
|
| 51 |
+
AttributeWrapper,
|
| 52 |
+
apply_patch,
|
| 53 |
+
find_wrapper,
|
| 54 |
+
function_wrapper,
|
| 55 |
+
is_wrapped_by,
|
| 56 |
+
patch_function_wrapper,
|
| 57 |
+
resolve_owner,
|
| 58 |
+
resolve_path,
|
| 59 |
+
scoped_function_wrapper,
|
| 60 |
+
transient_function_wrapper,
|
| 61 |
+
unwrap_object,
|
| 62 |
+
unwrapped,
|
| 63 |
+
wrap_function_wrapper,
|
| 64 |
+
wrap_object,
|
| 65 |
+
wrap_object_attribute,
|
| 66 |
+
wrapper_chain,
|
| 67 |
+
)
|
| 68 |
+
from .proxies import AutoObjectProxy, LazyObjectProxy, ObjectProxy, lazy_import
|
| 69 |
+
from .signature import with_signature
|
| 70 |
+
from .synchronization import (
|
| 71 |
+
async_to_sync,
|
| 72 |
+
mark_as_async,
|
| 73 |
+
mark_as_sync,
|
| 74 |
+
sync_to_async,
|
| 75 |
+
synchronized,
|
| 76 |
+
)
|
| 77 |
+
from .weakrefs import WeakFunctionProxy
|
| 78 |
+
|
| 79 |
+
__all__ = (
|
| 80 |
+
"AutoObjectProxy",
|
| 81 |
+
"BaseObjectProxy",
|
| 82 |
+
"BoundFunctionWrapper",
|
| 83 |
+
"CallableObjectProxy",
|
| 84 |
+
"FunctionWrapper",
|
| 85 |
+
"LazyObjectProxy",
|
| 86 |
+
"ObjectProxy",
|
| 87 |
+
"PartialCallableObjectProxy",
|
| 88 |
+
"PathResolutionError",
|
| 89 |
+
"TargetModuleNotFoundError",
|
| 90 |
+
"WrapperChainTooDeepError",
|
| 91 |
+
"WrapperNotFoundError",
|
| 92 |
+
"WrapperNotInitializedError",
|
| 93 |
+
"WrapperNotOutermostError",
|
| 94 |
+
"partial",
|
| 95 |
+
"AdapterFactory",
|
| 96 |
+
"adapter_factory",
|
| 97 |
+
"bind_state_to_wrapper",
|
| 98 |
+
"async_to_sync",
|
| 99 |
+
"decorator",
|
| 100 |
+
"lru_cache",
|
| 101 |
+
"mark_as_async",
|
| 102 |
+
"mark_as_sync",
|
| 103 |
+
"sync_to_async",
|
| 104 |
+
"synchronized",
|
| 105 |
+
"with_doc",
|
| 106 |
+
"with_signature",
|
| 107 |
+
"discover_post_import_hooks",
|
| 108 |
+
"notify_module_loaded",
|
| 109 |
+
"register_post_import_hook",
|
| 110 |
+
"when_imported",
|
| 111 |
+
"MISSING",
|
| 112 |
+
"AttributeWrapper",
|
| 113 |
+
"apply_patch",
|
| 114 |
+
"find_wrapper",
|
| 115 |
+
"function_wrapper",
|
| 116 |
+
"is_wrapped_by",
|
| 117 |
+
"lazy_import",
|
| 118 |
+
"patch_function_wrapper",
|
| 119 |
+
"resolve_owner",
|
| 120 |
+
"resolve_path",
|
| 121 |
+
"scoped_function_wrapper",
|
| 122 |
+
"transient_function_wrapper",
|
| 123 |
+
"unwrap_object",
|
| 124 |
+
"unwrapped",
|
| 125 |
+
"wrap_function_wrapper",
|
| 126 |
+
"wrap_object",
|
| 127 |
+
"wrap_object_attribute",
|
| 128 |
+
"wrapper_chain",
|
| 129 |
+
"WeakFunctionProxy",
|
| 130 |
+
)
|
shared/package-files/06/06705a8a4257644a5ad1df45722647238d0f0c97b88355af9f934bda6ca815fc/graphmatrix.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Adjacency matrix and incidence matrix of graphs.
|
| 3 |
+
"""
|
| 4 |
+
import networkx as nx
|
| 5 |
+
|
| 6 |
+
__all__ = ["incidence_matrix", "adjacency_matrix"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def incidence_matrix(G, nodelist=None, edgelist=None, oriented=False, weight=None):
|
| 10 |
+
"""Returns incidence matrix of G.
|
| 11 |
+
|
| 12 |
+
The incidence matrix assigns each row to a node and each column to an edge.
|
| 13 |
+
For a standard incidence matrix a 1 appears wherever a row's node is
|
| 14 |
+
incident on the column's edge. For an oriented incidence matrix each
|
| 15 |
+
edge is assigned an orientation (arbitrarily for undirected and aligning to
|
| 16 |
+
direction for directed). A -1 appears for the source (tail) of an edge and
|
| 17 |
+
1 for the destination (head) of the edge. The elements are zero otherwise.
|
| 18 |
+
|
| 19 |
+
Parameters
|
| 20 |
+
----------
|
| 21 |
+
G : graph
|
| 22 |
+
A NetworkX graph
|
| 23 |
+
|
| 24 |
+
nodelist : list, optional (default= all nodes in G)
|
| 25 |
+
The rows are ordered according to the nodes in nodelist.
|
| 26 |
+
If nodelist is None, then the ordering is produced by G.nodes().
|
| 27 |
+
|
| 28 |
+
edgelist : list, optional (default= all edges in G)
|
| 29 |
+
The columns are ordered according to the edges in edgelist.
|
| 30 |
+
If edgelist is None, then the ordering is produced by G.edges().
|
| 31 |
+
|
| 32 |
+
oriented: bool, optional (default=False)
|
| 33 |
+
If True, matrix elements are +1 or -1 for the head or tail node
|
| 34 |
+
respectively of each edge. If False, +1 occurs at both nodes.
|
| 35 |
+
|
| 36 |
+
weight : string or None, optional (default=None)
|
| 37 |
+
The edge data key used to provide each value in the matrix.
|
| 38 |
+
If None, then each edge has weight 1. Edge weights, if used,
|
| 39 |
+
should be positive so that the orientation can provide the sign.
|
| 40 |
+
|
| 41 |
+
Returns
|
| 42 |
+
-------
|
| 43 |
+
A : SciPy sparse array
|
| 44 |
+
The incidence matrix of G.
|
| 45 |
+
|
| 46 |
+
Notes
|
| 47 |
+
-----
|
| 48 |
+
For MultiGraph/MultiDiGraph, the edges in edgelist should be
|
| 49 |
+
(u,v,key) 3-tuples.
|
| 50 |
+
|
| 51 |
+
"Networks are the best discrete model for so many problems in
|
| 52 |
+
applied mathematics" [1]_.
|
| 53 |
+
|
| 54 |
+
References
|
| 55 |
+
----------
|
| 56 |
+
.. [1] Gil Strang, Network applications: A = incidence matrix,
|
| 57 |
+
http://videolectures.net/mit18085f07_strang_lec03/
|
| 58 |
+
"""
|
| 59 |
+
import scipy as sp
|
| 60 |
+
import scipy.sparse # call as sp.sparse
|
| 61 |
+
|
| 62 |
+
if nodelist is None:
|
| 63 |
+
nodelist = list(G)
|
| 64 |
+
if edgelist is None:
|
| 65 |
+
if G.is_multigraph():
|
| 66 |
+
edgelist = list(G.edges(keys=True))
|
| 67 |
+
else:
|
| 68 |
+
edgelist = list(G.edges())
|
| 69 |
+
A = sp.sparse.lil_array((len(nodelist), len(edgelist)))
|
| 70 |
+
node_index = {node: i for i, node in enumerate(nodelist)}
|
| 71 |
+
for ei, e in enumerate(edgelist):
|
| 72 |
+
(u, v) = e[:2]
|
| 73 |
+
if u == v:
|
| 74 |
+
continue # self loops give zero column
|
| 75 |
+
try:
|
| 76 |
+
ui = node_index[u]
|
| 77 |
+
vi = node_index[v]
|
| 78 |
+
except KeyError as err:
|
| 79 |
+
raise nx.NetworkXError(
|
| 80 |
+
f"node {u} or {v} in edgelist but not in nodelist"
|
| 81 |
+
) from err
|
| 82 |
+
if weight is None:
|
| 83 |
+
wt = 1
|
| 84 |
+
else:
|
| 85 |
+
if G.is_multigraph():
|
| 86 |
+
ekey = e[2]
|
| 87 |
+
wt = G[u][v][ekey].get(weight, 1)
|
| 88 |
+
else:
|
| 89 |
+
wt = G[u][v].get(weight, 1)
|
| 90 |
+
if oriented:
|
| 91 |
+
A[ui, ei] = -wt
|
| 92 |
+
A[vi, ei] = wt
|
| 93 |
+
else:
|
| 94 |
+
A[ui, ei] = wt
|
| 95 |
+
A[vi, ei] = wt
|
| 96 |
+
return A.asformat("csc")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def adjacency_matrix(G, nodelist=None, dtype=None, weight="weight"):
|
| 100 |
+
"""Returns adjacency matrix of G.
|
| 101 |
+
|
| 102 |
+
Parameters
|
| 103 |
+
----------
|
| 104 |
+
G : graph
|
| 105 |
+
A NetworkX graph
|
| 106 |
+
|
| 107 |
+
nodelist : list, optional
|
| 108 |
+
The rows and columns are ordered according to the nodes in nodelist.
|
| 109 |
+
If nodelist is None, then the ordering is produced by G.nodes().
|
| 110 |
+
|
| 111 |
+
dtype : NumPy data-type, optional
|
| 112 |
+
The desired data-type for the array.
|
| 113 |
+
If None, then the NumPy default is used.
|
| 114 |
+
|
| 115 |
+
weight : string or None, optional (default='weight')
|
| 116 |
+
The edge data key used to provide each value in the matrix.
|
| 117 |
+
If None, then each edge has weight 1.
|
| 118 |
+
|
| 119 |
+
Returns
|
| 120 |
+
-------
|
| 121 |
+
A : SciPy sparse array
|
| 122 |
+
Adjacency matrix representation of G.
|
| 123 |
+
|
| 124 |
+
Notes
|
| 125 |
+
-----
|
| 126 |
+
For directed graphs, entry i,j corresponds to an edge from i to j.
|
| 127 |
+
|
| 128 |
+
If you want a pure Python adjacency matrix representation try
|
| 129 |
+
networkx.convert.to_dict_of_dicts which will return a
|
| 130 |
+
dictionary-of-dictionaries format that can be addressed as a
|
| 131 |
+
sparse matrix.
|
| 132 |
+
|
| 133 |
+
For MultiGraph/MultiDiGraph with parallel edges the weights are summed.
|
| 134 |
+
See `to_numpy_array` for other options.
|
| 135 |
+
|
| 136 |
+
The convention used for self-loop edges in graphs is to assign the
|
| 137 |
+
diagonal matrix entry value to the edge weight attribute
|
| 138 |
+
(or the number 1 if the edge has no weight attribute). If the
|
| 139 |
+
alternate convention of doubling the edge weight is desired the
|
| 140 |
+
resulting SciPy sparse array can be modified as follows:
|
| 141 |
+
|
| 142 |
+
>>> G = nx.Graph([(1, 1)])
|
| 143 |
+
>>> A = nx.adjacency_matrix(G)
|
| 144 |
+
>>> print(A.todense())
|
| 145 |
+
[[1]]
|
| 146 |
+
>>> A.setdiag(A.diagonal() * 2)
|
| 147 |
+
>>> print(A.todense())
|
| 148 |
+
[[2]]
|
| 149 |
+
|
| 150 |
+
See Also
|
| 151 |
+
--------
|
| 152 |
+
to_numpy_array
|
| 153 |
+
to_scipy_sparse_array
|
| 154 |
+
to_dict_of_dicts
|
| 155 |
+
adjacency_spectrum
|
| 156 |
+
"""
|
| 157 |
+
return nx.to_scipy_sparse_array(G, nodelist=nodelist, dtype=dtype, weight=weight)
|
shared/package-files/06/067298ce39044746278cb1c81360130a8b514f0e97fdea9ad28210836ce6ed26/vi200
ADDED
|
Binary file (704 Bytes). View file
|
|
|