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/03/030007203a04811b5b5b26ea82c6cd0d1e7b884a27ce1b7aaadbb86402b1619c/arcsinh_ops.h +50 -0
- shared/package-files/03/0300e16c77d396a47280154331dad99fa750de58a4adf37d1a71b6eec118167d/isposinf_meta_dispatch.h +25 -0
- shared/package-files/03/0309af5e66929870cd20176054218d0fba2d3f23c4af325578d1c2d2d2a815ee/conv_depthwise3d_compositeexplicitautograd_dispatch.h +26 -0
- shared/package-files/03/0309d55e361c206c202e3526ddbf065ac68b71d724a9a8b05ec57c437aef0c40/c100-1p +0 -0
- shared/package-files/03/0309d55e361c206c202e3526ddbf065ac68b71d724a9a8b05ec57c437aef0c40/oc100 +0 -0
- shared/package-files/03/0309d55e361c206c202e3526ddbf065ac68b71d724a9a8b05ec57c437aef0c40/oconcept +0 -0
- shared/package-files/03/030a6e0a41e1d087b705b1a44c0dcffa204e76a10655e443a9ffba1a0971f57d/apple-uterm-vb +0 -0
- shared/package-files/03/030ab00fc6f6815d5fe47111b731ba52d388b2114669f508ffd0903952cf9e1a/test_interchange_spec.py +294 -0
- shared/package-files/03/030ece7cf591b8383569b012c413d11d0170a2561e19eb638b9bde5c0603b0e4/minitel1b +0 -0
- shared/package-files/03/031033d205350b1b879352fdd81cf3895b39dc1d25d67951b43266e04559cf0e/ge_meta.h +32 -0
- shared/package-files/03/0314c417a99dc9b016d650bf0dc8df2a5c6f4ae895ba99ea6c926ba92e71e257/_meta.py +279 -0
- shared/package-files/03/031643f594ecae7d8fd57fab3eb0ca3ef5be1d1bb2d37231980b050bb60c9ebe/ger.h +39 -0
- shared/package-files/03/03183173734448b7ce55383b69b1a6f5933efe3df2bfe75c3e866c3b8892100a/unique_dim_consecutive_ops.h +39 -0
- shared/package-files/03/031ace958cbed534d359e432a4329e5eb0c2add1c6a2bd042821387f1cd2406a/AAAA.py +51 -0
- shared/package-files/03/031b2634b8ae567c2c371e6ad2a5b5e554eee6a6f9951c5e35d2c7d4b233156a/softplus_compositeexplicitautogradnonfunctional_dispatch.h +23 -0
- shared/package-files/03/031c14693c4b798295b344469fa56ed3fba46991e605949b39babb3dca9370e4/new_empty_native.h +22 -0
- shared/package-files/03/0320c34b6f70b510cecbcd728603b2eee19abb8258434e68fc347e8acba1cded/_dedup_tensors.py +59 -0
- shared/package-files/03/0321bb9206a7c95d23571f9a34111416882a44b1d0aaa167f315376527c9a1a3/cache.py +210 -0
- shared/package-files/03/0324c87cf5dbfe64812b08fbac549ebf9444c0f074499c549145bba37ae2c259/_softmax_backward_data_compositeexplicitautogradnonfunctional_dispatch.h +23 -0
- shared/package-files/03/03251d9f4fc8b1aeb609b087ab0098ee1192b6e790b73100407a717f58a54506/convolution_ops.h +39 -0
- shared/package-files/03/0325c1dc539efa12931bc6f28e6465ed7a6ef45ff407dc466c873823aa0cc11e/native_batch_norm_backward.h +39 -0
- shared/package-files/03/032863b05f89846c07759a3f0473d99c0a90839a7a238cab43e180cdb2208821/__init__.pyi +7 -0
- shared/package-files/03/033099246f5f08faa159aa6b542aa2189859b6a4a50934c89abb4f3b07b3b801/katz.py +334 -0
- shared/package-files/03/0333d6dcb876478b139be454522e0e7776926daf73a0b712ff31c1c73b6fe332/process.h +46 -0
- shared/package-files/03/0334201b81a04b5e76fdcaa61abfcecf63085ec09a97ec5fb22b3b7c0ee7994d/xmlrpc.py +60 -0
- shared/package-files/03/03357aaf07136b86f8b5c7a7a0a87de68e9517ecfbc3be65f3564e761862eb21/test_trophic.py +302 -0
- shared/package-files/03/0336f7c5cf56be0c41bd044d0b99bcdd2269aabef788bac6489549e6ce3fccd2/linux-ubuntu18.04-broadwell +26 -0
- shared/package-files/03/03396305249fef000efc6f56f29920fa8dc87651f331da7926e9613067283913/_optimize.py +0 -0
- shared/package-files/03/033fa0a1a0e2fdb48f6c7bdb2ad38311971f28276f8b0dd72da94faad2e2db8a/MiscUtils.h +32 -0
- shared/package-files/03/0340993c4015c58ae9cad8d750640909375dc06f0aaef5156ed05edc0d4caa02/_m_e_t_a.py +112 -0
- shared/package-files/03/03416510aea384836f168c4978ca1fd9167c4c41562e4369ccb335d08b2e046a/_fixed.py +26 -0
- shared/package-files/03/034494ddbb8e506853f8d23fe8b43aa7bd1f152214de22c5760cefceb291e921/data_x_x2_x3.csv +11 -0
- shared/package-files/03/0346d975de368cfa7d65a971d91b47f3c5b4dbd7cbd3913cf4fb416e5bc39141/mgterm +0 -0
- shared/package-files/03/034812a748714b21037ee80956263709e59a945faf2bbd3561fb73ae3490cd0e/calculus.py +6 -0
- shared/package-files/03/034870dc0a84357793169d5171bff86b212c2d82ee315173f6ced4ae095ab4b4/test_ivp.py +1287 -0
- shared/package-files/03/034b10af10c15474b243ef2bbb72f5d613177f7abd815b81f71fd88076f847d3/__init__.py +5 -0
- shared/package-files/03/034b861abd5808226ebe75c2ac69282fc3f7c48135e403636e17c53d7a7f9e6a/_cudnn_init_dropout_state.h +43 -0
- shared/package-files/03/034e916d6a62449e09e22e7f4a60e7f23f2659d3dd1a2a0a6521f540d623d9f0/is_floating_point_compositeimplicitautograd_dispatch.h +23 -0
- shared/package-files/03/0351667ed3afd3310ebd353526824d6f6f34d641ef0a785552c6893b7f95fdf3/heapq.py +601 -0
- shared/package-files/03/0353721b70c5f97f936acb7c0eafc7c6878e2bdf770b0bb3a7e00e7ab1199451/distributions.py +680 -0
- shared/package-files/03/035415e61eb105ad5c4c87a38ec73535f8c6d0ca8c6f1a85a9789c0b638b36b3/idl.py +17 -0
- shared/package-files/03/0356e6f80e58762b36899255236fabdda14a52e7d6478d8d67c62db6ba7c9b38/testutils.py +9 -0
- shared/package-files/03/03587701f3e110c6c6e4f2dd0ebd606e7c2dfc395a40e06016ec7942c2290a93/test_backend_tk.py +280 -0
- shared/package-files/03/035a2ecc772fbc43c641b0fa2dcecd147f0e44d61a88d4f22fc0d17a0c5cb40d/native_functions.py +64 -0
- shared/package-files/03/035d95e258d6c6f5da48527bde61d214ad9834efa4f1ac7a31ee321164ec238b/test_sparsifiers.py +137 -0
- shared/package-files/03/03606ac3664f19fc2472f2e633fdbad766d6f1b4e2414f21c1234692ff91dc55/multilabel_margin_loss_backward_native.h +24 -0
- shared/package-files/03/036238ba9b78a8da259571a9c33aea83b334a0a1c9859c750543080678d1228c/dispatcher.py +413 -0
- shared/package-files/03/0367001befa2ee94d5a2520af7a9b136e093b4bbe16cb551a89e0c01f5940444/test_coloring.py +865 -0
- shared/package-files/03/036de769e968aa7fb534a5400013ac26d1d4f55cfc95fbeb0080ae2e4fbba813/chrono.h +225 -0
- shared/package-files/03/036e6516c4ec6bd5d4ead3eea8578e587d7880e8c8e3484f7c9eb6e8119e08e6/test_ir.py +0 -0
shared/package-files/03/030007203a04811b5b5b26ea82c6cd0d1e7b884a27ce1b7aaadbb86402b1619c/arcsinh_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 arcsinh {
|
| 18 |
+
using schema = at::Tensor (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::arcsinh")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "arcsinh(Tensor self) -> Tensor")
|
| 24 |
+
static at::Tensor call(const at::Tensor & self);
|
| 25 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API arcsinh_ {
|
| 29 |
+
using schema = 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::arcsinh_")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "arcsinh_(Tensor(a!) self) -> Tensor(a!)")
|
| 35 |
+
static at::Tensor & call(at::Tensor & self);
|
| 36 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
struct TORCH_API arcsinh_out {
|
| 40 |
+
using schema = at::Tensor & (const at::Tensor &, 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::arcsinh")
|
| 44 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 45 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "arcsinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)")
|
| 46 |
+
static at::Tensor & call(const at::Tensor & self, at::Tensor & out);
|
| 47 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out);
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
}} // namespace at::_ops
|
shared/package-files/03/0300e16c77d396a47280154331dad99fa750de58a4adf37d1a71b6eec118167d/isposinf_meta_dispatch.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 meta {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor isposinf(const at::Tensor & self);
|
| 21 |
+
TORCH_API at::Tensor & isposinf_out(at::Tensor & out, const at::Tensor & self);
|
| 22 |
+
TORCH_API at::Tensor & isposinf_outf(const at::Tensor & self, at::Tensor & out);
|
| 23 |
+
|
| 24 |
+
} // namespace meta
|
| 25 |
+
} // namespace at
|
shared/package-files/03/0309af5e66929870cd20176054218d0fba2d3f23c4af325578d1c2d2d2a815ee/conv_depthwise3d_compositeexplicitautograd_dispatch.h
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 compositeexplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor & conv_depthwise3d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional<at::Tensor> & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation);
|
| 21 |
+
TORCH_API at::Tensor & conv_depthwise3d_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional<at::Tensor> & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, at::Tensor & out);
|
| 22 |
+
TORCH_API at::Tensor & conv_depthwise3d_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation);
|
| 23 |
+
TORCH_API at::Tensor & conv_depthwise3d_symint_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, at::Tensor & out);
|
| 24 |
+
|
| 25 |
+
} // namespace compositeexplicitautograd
|
| 26 |
+
} // namespace at
|
shared/package-files/03/0309d55e361c206c202e3526ddbf065ac68b71d724a9a8b05ec57c437aef0c40/c100-1p
ADDED
|
Binary file (810 Bytes). View file
|
|
|
shared/package-files/03/0309d55e361c206c202e3526ddbf065ac68b71d724a9a8b05ec57c437aef0c40/oc100
ADDED
|
Binary file (810 Bytes). View file
|
|
|
shared/package-files/03/0309d55e361c206c202e3526ddbf065ac68b71d724a9a8b05ec57c437aef0c40/oconcept
ADDED
|
Binary file (810 Bytes). View file
|
|
|
shared/package-files/03/030a6e0a41e1d087b705b1a44c0dcffa204e76a10655e443a9ffba1a0971f57d/apple-uterm-vb
ADDED
|
Binary file (498 Bytes). View file
|
|
|
shared/package-files/03/030ab00fc6f6815d5fe47111b731ba52d388b2114669f508ffd0903952cf9e1a/test_interchange_spec.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
import ctypes
|
| 19 |
+
import hypothesis as h
|
| 20 |
+
import hypothesis.strategies as st
|
| 21 |
+
|
| 22 |
+
import pytest
|
| 23 |
+
try:
|
| 24 |
+
import numpy as np
|
| 25 |
+
except ImportError:
|
| 26 |
+
np = None
|
| 27 |
+
import pyarrow as pa
|
| 28 |
+
import pyarrow.tests.strategies as past
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
all_types = st.deferred(
|
| 32 |
+
lambda: (
|
| 33 |
+
past.signed_integer_types |
|
| 34 |
+
past.unsigned_integer_types |
|
| 35 |
+
past.floating_types |
|
| 36 |
+
past.bool_type |
|
| 37 |
+
past.string_type |
|
| 38 |
+
past.large_string_type
|
| 39 |
+
)
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# datetime is tested in test_extra.py
|
| 44 |
+
# dictionary is tested in test_categorical()
|
| 45 |
+
@pytest.mark.numpy
|
| 46 |
+
@h.settings(suppress_health_check=(h.HealthCheck.too_slow,))
|
| 47 |
+
@h.given(past.arrays(all_types, size=3))
|
| 48 |
+
def test_dtypes(arr):
|
| 49 |
+
table = pa.table([arr], names=["a"])
|
| 50 |
+
df = table.__dataframe__()
|
| 51 |
+
|
| 52 |
+
null_count = df.get_column(0).null_count
|
| 53 |
+
assert null_count == arr.null_count
|
| 54 |
+
assert isinstance(null_count, int)
|
| 55 |
+
assert df.get_column(0).size() == 3
|
| 56 |
+
assert df.get_column(0).offset == 0
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@pytest.mark.numpy
|
| 60 |
+
@pytest.mark.parametrize(
|
| 61 |
+
"uint, uint_bw",
|
| 62 |
+
[
|
| 63 |
+
(pa.uint8(), 8),
|
| 64 |
+
(pa.uint16(), 16),
|
| 65 |
+
(pa.uint32(), 32)
|
| 66 |
+
]
|
| 67 |
+
)
|
| 68 |
+
@pytest.mark.parametrize(
|
| 69 |
+
"int, int_bw", [
|
| 70 |
+
(pa.int8(), 8),
|
| 71 |
+
(pa.int16(), 16),
|
| 72 |
+
(pa.int32(), 32),
|
| 73 |
+
(pa.int64(), 64)
|
| 74 |
+
]
|
| 75 |
+
)
|
| 76 |
+
@pytest.mark.parametrize(
|
| 77 |
+
"float, float_bw, np_float_str", [
|
| 78 |
+
(pa.float16(), 16, "float16"),
|
| 79 |
+
(pa.float32(), 32, "float32"),
|
| 80 |
+
(pa.float64(), 64, "float64")
|
| 81 |
+
]
|
| 82 |
+
)
|
| 83 |
+
@pytest.mark.parametrize("unit", ['s', 'ms', 'us', 'ns'])
|
| 84 |
+
@pytest.mark.parametrize("tz", ['', 'America/New_York', '+07:30', '-04:30'])
|
| 85 |
+
@pytest.mark.parametrize("use_batch", [False, True])
|
| 86 |
+
def test_mixed_dtypes(uint, uint_bw, int, int_bw,
|
| 87 |
+
float, float_bw, np_float_str, unit, tz,
|
| 88 |
+
use_batch):
|
| 89 |
+
from datetime import datetime as dt
|
| 90 |
+
arr = [1, 2, 3]
|
| 91 |
+
dt_arr = [dt(2007, 7, 13), dt(2007, 7, 14), dt(2007, 7, 15)]
|
| 92 |
+
table = pa.table(
|
| 93 |
+
{
|
| 94 |
+
"a": pa.array(arr, type=uint),
|
| 95 |
+
"b": pa.array(arr, type=int),
|
| 96 |
+
"c": pa.array(np.array(arr, dtype=np.dtype(np_float_str)), type=float),
|
| 97 |
+
"d": [True, False, True],
|
| 98 |
+
"e": ["a", "", "c"],
|
| 99 |
+
"f": pa.array(dt_arr, type=pa.timestamp(unit, tz=tz))
|
| 100 |
+
}
|
| 101 |
+
)
|
| 102 |
+
if use_batch:
|
| 103 |
+
table = table.to_batches()[0]
|
| 104 |
+
df = table.__dataframe__()
|
| 105 |
+
# 0 = DtypeKind.INT, 1 = DtypeKind.UINT, 2 = DtypeKind.FLOAT,
|
| 106 |
+
# 20 = DtypeKind.BOOL, 21 = DtypeKind.STRING, 22 = DtypeKind.DATETIME
|
| 107 |
+
# see DtypeKind class in column.py
|
| 108 |
+
columns = {"a": 1, "b": 0, "c": 2, "d": 20, "e": 21, "f": 22}
|
| 109 |
+
|
| 110 |
+
for column, kind in columns.items():
|
| 111 |
+
col = df.get_column_by_name(column)
|
| 112 |
+
|
| 113 |
+
assert col.null_count == 0
|
| 114 |
+
assert col.size() == 3
|
| 115 |
+
assert col.offset == 0
|
| 116 |
+
assert col.dtype[0] == kind
|
| 117 |
+
|
| 118 |
+
assert df.get_column_by_name("a").dtype[1] == uint_bw
|
| 119 |
+
assert df.get_column_by_name("b").dtype[1] == int_bw
|
| 120 |
+
assert df.get_column_by_name("c").dtype[1] == float_bw
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_na_float():
|
| 124 |
+
table = pa.table({"a": [1.0, None, 2.0]})
|
| 125 |
+
df = table.__dataframe__()
|
| 126 |
+
col = df.get_column_by_name("a")
|
| 127 |
+
assert col.null_count == 1
|
| 128 |
+
assert isinstance(col.null_count, int)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def test_noncategorical():
|
| 132 |
+
table = pa.table({"a": [1, 2, 3]})
|
| 133 |
+
df = table.__dataframe__()
|
| 134 |
+
col = df.get_column_by_name("a")
|
| 135 |
+
with pytest.raises(TypeError, match=".*categorical.*"):
|
| 136 |
+
col.describe_categorical
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@pytest.mark.parametrize("use_batch", [False, True])
|
| 140 |
+
def test_categorical(use_batch):
|
| 141 |
+
import pyarrow as pa
|
| 142 |
+
arr = ["Mon", "Tue", "Mon", "Wed", "Mon", "Thu", "Fri", "Sat", None]
|
| 143 |
+
table = pa.table(
|
| 144 |
+
{"weekday": pa.array(arr).dictionary_encode()}
|
| 145 |
+
)
|
| 146 |
+
if use_batch:
|
| 147 |
+
table = table.to_batches()[0]
|
| 148 |
+
|
| 149 |
+
col = table.__dataframe__().get_column_by_name("weekday")
|
| 150 |
+
categorical = col.describe_categorical
|
| 151 |
+
assert isinstance(categorical["is_ordered"], bool)
|
| 152 |
+
assert isinstance(categorical["is_dictionary"], bool)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@pytest.mark.parametrize("use_batch", [False, True])
|
| 156 |
+
def test_dataframe(use_batch):
|
| 157 |
+
n = pa.chunked_array([[2, 2, 4], [4, 5, 100]])
|
| 158 |
+
a = pa.chunked_array([["Flamingo", "Parrot", "Cow"],
|
| 159 |
+
["Horse", "Brittle stars", "Centipede"]])
|
| 160 |
+
table = pa.table([n, a], names=['n_legs', 'animals'])
|
| 161 |
+
if use_batch:
|
| 162 |
+
table = table.combine_chunks().to_batches()[0]
|
| 163 |
+
df = table.__dataframe__()
|
| 164 |
+
|
| 165 |
+
assert df.num_columns() == 2
|
| 166 |
+
assert df.num_rows() == 6
|
| 167 |
+
if use_batch:
|
| 168 |
+
assert df.num_chunks() == 1
|
| 169 |
+
else:
|
| 170 |
+
assert df.num_chunks() == 2
|
| 171 |
+
assert list(df.column_names()) == ['n_legs', 'animals']
|
| 172 |
+
assert list(df.select_columns((1,)).column_names()) == list(
|
| 173 |
+
df.select_columns_by_name(("animals",)).column_names()
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@pytest.mark.parametrize("use_batch", [False, True])
|
| 178 |
+
@pytest.mark.parametrize(["size", "n_chunks"], [(10, 3), (12, 3), (12, 5)])
|
| 179 |
+
def test_df_get_chunks(use_batch, size, n_chunks):
|
| 180 |
+
table = pa.table({"x": list(range(size))})
|
| 181 |
+
if use_batch:
|
| 182 |
+
table = table.to_batches()[0]
|
| 183 |
+
df = table.__dataframe__()
|
| 184 |
+
chunks = list(df.get_chunks(n_chunks))
|
| 185 |
+
assert len(chunks) == n_chunks
|
| 186 |
+
assert sum(chunk.num_rows() for chunk in chunks) == size
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@pytest.mark.parametrize("use_batch", [False, True])
|
| 190 |
+
@pytest.mark.parametrize(["size", "n_chunks"], [(10, 3), (12, 3), (12, 5)])
|
| 191 |
+
def test_column_get_chunks(use_batch, size, n_chunks):
|
| 192 |
+
table = pa.table({"x": list(range(size))})
|
| 193 |
+
if use_batch:
|
| 194 |
+
table = table.to_batches()[0]
|
| 195 |
+
df = table.__dataframe__()
|
| 196 |
+
chunks = list(df.get_column(0).get_chunks(n_chunks))
|
| 197 |
+
assert len(chunks) == n_chunks
|
| 198 |
+
assert sum(chunk.size() for chunk in chunks) == size
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@pytest.mark.pandas
|
| 202 |
+
@pytest.mark.parametrize(
|
| 203 |
+
"uint", [pa.uint8(), pa.uint16(), pa.uint32()]
|
| 204 |
+
)
|
| 205 |
+
@pytest.mark.parametrize(
|
| 206 |
+
"int", [pa.int8(), pa.int16(), pa.int32(), pa.int64()]
|
| 207 |
+
)
|
| 208 |
+
@pytest.mark.parametrize(
|
| 209 |
+
"float, np_float_str", [
|
| 210 |
+
(pa.float16(), "float16"),
|
| 211 |
+
(pa.float32(), "float32"),
|
| 212 |
+
(pa.float64(), "float64")
|
| 213 |
+
]
|
| 214 |
+
)
|
| 215 |
+
@pytest.mark.parametrize("use_batch", [False, True])
|
| 216 |
+
def test_get_columns(uint, int, float, np_float_str, use_batch):
|
| 217 |
+
arr = [[1, 2, 3], [4, 5]]
|
| 218 |
+
arr_float = np.array([1, 2, 3, 4, 5], dtype=np.dtype(np_float_str))
|
| 219 |
+
table = pa.table(
|
| 220 |
+
{
|
| 221 |
+
"a": pa.chunked_array(arr, type=uint),
|
| 222 |
+
"b": pa.chunked_array(arr, type=int),
|
| 223 |
+
"c": pa.array(arr_float, type=float)
|
| 224 |
+
}
|
| 225 |
+
)
|
| 226 |
+
if use_batch:
|
| 227 |
+
table = table.combine_chunks().to_batches()[0]
|
| 228 |
+
df = table.__dataframe__()
|
| 229 |
+
for col in df.get_columns():
|
| 230 |
+
assert col.size() == 5
|
| 231 |
+
assert col.num_chunks() == 1
|
| 232 |
+
|
| 233 |
+
# 0 = DtypeKind.INT, 1 = DtypeKind.UINT, 2 = DtypeKind.FLOAT,
|
| 234 |
+
# see DtypeKind class in column.py
|
| 235 |
+
assert df.get_column(0).dtype[0] == 1 # UINT
|
| 236 |
+
assert df.get_column(1).dtype[0] == 0 # INT
|
| 237 |
+
assert df.get_column(2).dtype[0] == 2 # FLOAT
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
@pytest.mark.parametrize(
|
| 241 |
+
"int", [pa.int8(), pa.int16(), pa.int32(), pa.int64()]
|
| 242 |
+
)
|
| 243 |
+
@pytest.mark.parametrize("use_batch", [False, True])
|
| 244 |
+
def test_buffer(int, use_batch):
|
| 245 |
+
arr = [0, 1, -1]
|
| 246 |
+
table = pa.table({"a": pa.array(arr, type=int)})
|
| 247 |
+
if use_batch:
|
| 248 |
+
table = table.to_batches()[0]
|
| 249 |
+
df = table.__dataframe__()
|
| 250 |
+
col = df.get_column(0)
|
| 251 |
+
buf = col.get_buffers()
|
| 252 |
+
|
| 253 |
+
dataBuf, dataDtype = buf["data"]
|
| 254 |
+
|
| 255 |
+
assert dataBuf.bufsize > 0
|
| 256 |
+
assert dataBuf.ptr != 0
|
| 257 |
+
device, _ = dataBuf.__dlpack_device__()
|
| 258 |
+
|
| 259 |
+
# 0 = DtypeKind.INT
|
| 260 |
+
# see DtypeKind class in column.py
|
| 261 |
+
assert dataDtype[0] == 0
|
| 262 |
+
|
| 263 |
+
if device == 1: # CPU-only as we're going to directly read memory here
|
| 264 |
+
bitwidth = dataDtype[1]
|
| 265 |
+
ctype = {
|
| 266 |
+
8: ctypes.c_int8,
|
| 267 |
+
16: ctypes.c_int16,
|
| 268 |
+
32: ctypes.c_int32,
|
| 269 |
+
64: ctypes.c_int64,
|
| 270 |
+
}[bitwidth]
|
| 271 |
+
|
| 272 |
+
for idx, truth in enumerate(arr):
|
| 273 |
+
val = ctype.from_address(dataBuf.ptr + idx * (bitwidth // 8)).value
|
| 274 |
+
assert val == truth, f"Buffer at index {idx} mismatch"
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@pytest.mark.parametrize(
|
| 278 |
+
"indices_type, bitwidth, f_string", [
|
| 279 |
+
(pa.int8(), 8, "c"),
|
| 280 |
+
(pa.int16(), 16, "s"),
|
| 281 |
+
(pa.int32(), 32, "i"),
|
| 282 |
+
(pa.int64(), 64, "l")
|
| 283 |
+
]
|
| 284 |
+
)
|
| 285 |
+
def test_categorical_dtype(indices_type, bitwidth, f_string):
|
| 286 |
+
type = pa.dictionary(indices_type, pa.string())
|
| 287 |
+
arr = pa.array(["a", "b", None, "d"], type)
|
| 288 |
+
table = pa.table({'a': arr})
|
| 289 |
+
|
| 290 |
+
df = table.__dataframe__()
|
| 291 |
+
col = df.get_column(0)
|
| 292 |
+
assert col.dtype[0] == 23 # <DtypeKind.CATEGORICAL: 23>
|
| 293 |
+
assert col.dtype[1] == bitwidth
|
| 294 |
+
assert col.dtype[2] == f_string
|
shared/package-files/03/030ece7cf591b8383569b012c413d11d0170a2561e19eb638b9bde5c0603b0e4/minitel1b
ADDED
|
Binary file (1.98 kB). View file
|
|
|
shared/package-files/03/031033d205350b1b879352fdd81cf3895b39dc1d25d67951b43266e04559cf0e/ge_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_ge_Scalar : public TensorIteratorBase {
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
void meta(const at::Tensor & self, const at::Scalar & other);
|
| 24 |
+
};
|
| 25 |
+
struct TORCH_API structured_ge_Tensor : public TensorIteratorBase {
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
void meta(const at::Tensor & self, const at::Tensor & other);
|
| 29 |
+
};
|
| 30 |
+
|
| 31 |
+
} // namespace native
|
| 32 |
+
} // namespace at
|
shared/package-files/03/0314c417a99dc9b016d650bf0dc8df2a5c6f4ae895ba99ea6c926ba92e71e257/_meta.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Optional, Tuple
|
| 2 |
+
|
| 3 |
+
import PIL.Image
|
| 4 |
+
import torch
|
| 5 |
+
from torchvision import tv_tensors
|
| 6 |
+
from torchvision.transforms import _functional_pil as _FP
|
| 7 |
+
from torchvision.tv_tensors import BoundingBoxFormat
|
| 8 |
+
|
| 9 |
+
from torchvision.utils import _log_api_usage_once
|
| 10 |
+
|
| 11 |
+
from ._utils import _get_kernel, _register_kernel_internal, is_pure_tensor
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def get_dimensions(inpt: torch.Tensor) -> List[int]:
|
| 15 |
+
if torch.jit.is_scripting():
|
| 16 |
+
return get_dimensions_image(inpt)
|
| 17 |
+
|
| 18 |
+
_log_api_usage_once(get_dimensions)
|
| 19 |
+
|
| 20 |
+
kernel = _get_kernel(get_dimensions, type(inpt))
|
| 21 |
+
return kernel(inpt)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@_register_kernel_internal(get_dimensions, torch.Tensor)
|
| 25 |
+
@_register_kernel_internal(get_dimensions, tv_tensors.Image, tv_tensor_wrapper=False)
|
| 26 |
+
def get_dimensions_image(image: torch.Tensor) -> List[int]:
|
| 27 |
+
chw = list(image.shape[-3:])
|
| 28 |
+
ndims = len(chw)
|
| 29 |
+
if ndims == 3:
|
| 30 |
+
return chw
|
| 31 |
+
elif ndims == 2:
|
| 32 |
+
chw.insert(0, 1)
|
| 33 |
+
return chw
|
| 34 |
+
else:
|
| 35 |
+
raise TypeError(f"Input tensor should have at least two dimensions, but got {ndims}")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
_get_dimensions_image_pil = _register_kernel_internal(get_dimensions, PIL.Image.Image)(_FP.get_dimensions)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@_register_kernel_internal(get_dimensions, tv_tensors.Video, tv_tensor_wrapper=False)
|
| 42 |
+
def get_dimensions_video(video: torch.Tensor) -> List[int]:
|
| 43 |
+
return get_dimensions_image(video)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def get_num_channels(inpt: torch.Tensor) -> int:
|
| 47 |
+
if torch.jit.is_scripting():
|
| 48 |
+
return get_num_channels_image(inpt)
|
| 49 |
+
|
| 50 |
+
_log_api_usage_once(get_num_channels)
|
| 51 |
+
|
| 52 |
+
kernel = _get_kernel(get_num_channels, type(inpt))
|
| 53 |
+
return kernel(inpt)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@_register_kernel_internal(get_num_channels, torch.Tensor)
|
| 57 |
+
@_register_kernel_internal(get_num_channels, tv_tensors.Image, tv_tensor_wrapper=False)
|
| 58 |
+
def get_num_channels_image(image: torch.Tensor) -> int:
|
| 59 |
+
chw = image.shape[-3:]
|
| 60 |
+
ndims = len(chw)
|
| 61 |
+
if ndims == 3:
|
| 62 |
+
return chw[0]
|
| 63 |
+
elif ndims == 2:
|
| 64 |
+
return 1
|
| 65 |
+
else:
|
| 66 |
+
raise TypeError(f"Input tensor should have at least two dimensions, but got {ndims}")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
_get_num_channels_image_pil = _register_kernel_internal(get_num_channels, PIL.Image.Image)(_FP.get_image_num_channels)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@_register_kernel_internal(get_num_channels, tv_tensors.Video, tv_tensor_wrapper=False)
|
| 73 |
+
def get_num_channels_video(video: torch.Tensor) -> int:
|
| 74 |
+
return get_num_channels_image(video)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# We changed the names to ensure it can be used not only for images but also videos. Thus, we just alias it without
|
| 78 |
+
# deprecating the old names.
|
| 79 |
+
get_image_num_channels = get_num_channels
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def get_size(inpt: torch.Tensor) -> List[int]:
|
| 83 |
+
if torch.jit.is_scripting():
|
| 84 |
+
return get_size_image(inpt)
|
| 85 |
+
|
| 86 |
+
_log_api_usage_once(get_size)
|
| 87 |
+
|
| 88 |
+
kernel = _get_kernel(get_size, type(inpt))
|
| 89 |
+
return kernel(inpt)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@_register_kernel_internal(get_size, torch.Tensor)
|
| 93 |
+
@_register_kernel_internal(get_size, tv_tensors.Image, tv_tensor_wrapper=False)
|
| 94 |
+
def get_size_image(image: torch.Tensor) -> List[int]:
|
| 95 |
+
hw = list(image.shape[-2:])
|
| 96 |
+
ndims = len(hw)
|
| 97 |
+
if ndims == 2:
|
| 98 |
+
return hw
|
| 99 |
+
else:
|
| 100 |
+
raise TypeError(f"Input tensor should have at least two dimensions, but got {ndims}")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@_register_kernel_internal(get_size, PIL.Image.Image)
|
| 104 |
+
def _get_size_image_pil(image: PIL.Image.Image) -> List[int]:
|
| 105 |
+
width, height = _FP.get_image_size(image)
|
| 106 |
+
return [height, width]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@_register_kernel_internal(get_size, tv_tensors.Video, tv_tensor_wrapper=False)
|
| 110 |
+
def get_size_video(video: torch.Tensor) -> List[int]:
|
| 111 |
+
return get_size_image(video)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@_register_kernel_internal(get_size, tv_tensors.Mask, tv_tensor_wrapper=False)
|
| 115 |
+
def get_size_mask(mask: torch.Tensor) -> List[int]:
|
| 116 |
+
return get_size_image(mask)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@_register_kernel_internal(get_size, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False)
|
| 120 |
+
def get_size_bounding_boxes(bounding_box: tv_tensors.BoundingBoxes) -> List[int]:
|
| 121 |
+
return list(bounding_box.canvas_size)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def get_num_frames(inpt: torch.Tensor) -> int:
|
| 125 |
+
if torch.jit.is_scripting():
|
| 126 |
+
return get_num_frames_video(inpt)
|
| 127 |
+
|
| 128 |
+
_log_api_usage_once(get_num_frames)
|
| 129 |
+
|
| 130 |
+
kernel = _get_kernel(get_num_frames, type(inpt))
|
| 131 |
+
return kernel(inpt)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@_register_kernel_internal(get_num_frames, torch.Tensor)
|
| 135 |
+
@_register_kernel_internal(get_num_frames, tv_tensors.Video, tv_tensor_wrapper=False)
|
| 136 |
+
def get_num_frames_video(video: torch.Tensor) -> int:
|
| 137 |
+
return video.shape[-4]
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _xywh_to_xyxy(xywh: torch.Tensor, inplace: bool) -> torch.Tensor:
|
| 141 |
+
xyxy = xywh if inplace else xywh.clone()
|
| 142 |
+
xyxy[..., 2:] += xyxy[..., :2]
|
| 143 |
+
return xyxy
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _xyxy_to_xywh(xyxy: torch.Tensor, inplace: bool) -> torch.Tensor:
|
| 147 |
+
xywh = xyxy if inplace else xyxy.clone()
|
| 148 |
+
xywh[..., 2:] -= xywh[..., :2]
|
| 149 |
+
return xywh
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _cxcywh_to_xyxy(cxcywh: torch.Tensor, inplace: bool) -> torch.Tensor:
|
| 153 |
+
if not inplace:
|
| 154 |
+
cxcywh = cxcywh.clone()
|
| 155 |
+
|
| 156 |
+
# Trick to do fast division by 2 and ceil, without casting. It produces the same result as
|
| 157 |
+
# `torchvision.ops._box_convert._box_cxcywh_to_xyxy`.
|
| 158 |
+
half_wh = cxcywh[..., 2:].div(-2, rounding_mode=None if cxcywh.is_floating_point() else "floor").abs_()
|
| 159 |
+
# (cx - width / 2) = x1, same for y1
|
| 160 |
+
cxcywh[..., :2].sub_(half_wh)
|
| 161 |
+
# (x1 + width) = x2, same for y2
|
| 162 |
+
cxcywh[..., 2:].add_(cxcywh[..., :2])
|
| 163 |
+
|
| 164 |
+
return cxcywh
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _xyxy_to_cxcywh(xyxy: torch.Tensor, inplace: bool) -> torch.Tensor:
|
| 168 |
+
if not inplace:
|
| 169 |
+
xyxy = xyxy.clone()
|
| 170 |
+
|
| 171 |
+
# (x2 - x1) = width, same for height
|
| 172 |
+
xyxy[..., 2:].sub_(xyxy[..., :2])
|
| 173 |
+
# (x1 * 2 + width) / 2 = x1 + width / 2 = x1 + (x2-x1)/2 = (x1 + x2)/2 = cx, same for cy
|
| 174 |
+
xyxy[..., :2].mul_(2).add_(xyxy[..., 2:]).div_(2, rounding_mode=None if xyxy.is_floating_point() else "floor")
|
| 175 |
+
|
| 176 |
+
return xyxy
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _convert_bounding_box_format(
|
| 180 |
+
bounding_boxes: torch.Tensor, old_format: BoundingBoxFormat, new_format: BoundingBoxFormat, inplace: bool = False
|
| 181 |
+
) -> torch.Tensor:
|
| 182 |
+
|
| 183 |
+
if new_format == old_format:
|
| 184 |
+
return bounding_boxes
|
| 185 |
+
|
| 186 |
+
# TODO: Add _xywh_to_cxcywh and _cxcywh_to_xywh to improve performance
|
| 187 |
+
if old_format == BoundingBoxFormat.XYWH:
|
| 188 |
+
bounding_boxes = _xywh_to_xyxy(bounding_boxes, inplace)
|
| 189 |
+
elif old_format == BoundingBoxFormat.CXCYWH:
|
| 190 |
+
bounding_boxes = _cxcywh_to_xyxy(bounding_boxes, inplace)
|
| 191 |
+
|
| 192 |
+
if new_format == BoundingBoxFormat.XYWH:
|
| 193 |
+
bounding_boxes = _xyxy_to_xywh(bounding_boxes, inplace)
|
| 194 |
+
elif new_format == BoundingBoxFormat.CXCYWH:
|
| 195 |
+
bounding_boxes = _xyxy_to_cxcywh(bounding_boxes, inplace)
|
| 196 |
+
|
| 197 |
+
return bounding_boxes
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def convert_bounding_box_format(
|
| 201 |
+
inpt: torch.Tensor,
|
| 202 |
+
old_format: Optional[BoundingBoxFormat] = None,
|
| 203 |
+
new_format: Optional[BoundingBoxFormat] = None,
|
| 204 |
+
inplace: bool = False,
|
| 205 |
+
) -> torch.Tensor:
|
| 206 |
+
"""See :func:`~torchvision.transforms.v2.ConvertBoundingBoxFormat` for details."""
|
| 207 |
+
# This being a kernel / functional hybrid, we need an option to pass `old_format` explicitly for pure tensor
|
| 208 |
+
# inputs as well as extract it from `tv_tensors.BoundingBoxes` inputs. However, putting a default value on
|
| 209 |
+
# `old_format` means we also need to put one on `new_format` to have syntactically correct Python. Here we mimic the
|
| 210 |
+
# default error that would be thrown if `new_format` had no default value.
|
| 211 |
+
if new_format is None:
|
| 212 |
+
raise TypeError("convert_bounding_box_format() missing 1 required argument: 'new_format'")
|
| 213 |
+
|
| 214 |
+
if not torch.jit.is_scripting():
|
| 215 |
+
_log_api_usage_once(convert_bounding_box_format)
|
| 216 |
+
|
| 217 |
+
if isinstance(old_format, str):
|
| 218 |
+
old_format = BoundingBoxFormat[old_format.upper()]
|
| 219 |
+
if isinstance(new_format, str):
|
| 220 |
+
new_format = BoundingBoxFormat[new_format.upper()]
|
| 221 |
+
|
| 222 |
+
if torch.jit.is_scripting() or is_pure_tensor(inpt):
|
| 223 |
+
if old_format is None:
|
| 224 |
+
raise ValueError("For pure tensor inputs, `old_format` has to be passed.")
|
| 225 |
+
return _convert_bounding_box_format(inpt, old_format=old_format, new_format=new_format, inplace=inplace)
|
| 226 |
+
elif isinstance(inpt, tv_tensors.BoundingBoxes):
|
| 227 |
+
if old_format is not None:
|
| 228 |
+
raise ValueError("For bounding box tv_tensor inputs, `old_format` must not be passed.")
|
| 229 |
+
output = _convert_bounding_box_format(
|
| 230 |
+
inpt.as_subclass(torch.Tensor), old_format=inpt.format, new_format=new_format, inplace=inplace
|
| 231 |
+
)
|
| 232 |
+
return tv_tensors.wrap(output, like=inpt, format=new_format)
|
| 233 |
+
else:
|
| 234 |
+
raise TypeError(
|
| 235 |
+
f"Input can either be a plain tensor or a bounding box tv_tensor, but got {type(inpt)} instead."
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _clamp_bounding_boxes(
|
| 240 |
+
bounding_boxes: torch.Tensor, format: BoundingBoxFormat, canvas_size: Tuple[int, int]
|
| 241 |
+
) -> torch.Tensor:
|
| 242 |
+
# TODO: Investigate if it makes sense from a performance perspective to have an implementation for every
|
| 243 |
+
# BoundingBoxFormat instead of converting back and forth
|
| 244 |
+
in_dtype = bounding_boxes.dtype
|
| 245 |
+
bounding_boxes = bounding_boxes.clone() if bounding_boxes.is_floating_point() else bounding_boxes.float()
|
| 246 |
+
xyxy_boxes = convert_bounding_box_format(
|
| 247 |
+
bounding_boxes, old_format=format, new_format=tv_tensors.BoundingBoxFormat.XYXY, inplace=True
|
| 248 |
+
)
|
| 249 |
+
xyxy_boxes[..., 0::2].clamp_(min=0, max=canvas_size[1])
|
| 250 |
+
xyxy_boxes[..., 1::2].clamp_(min=0, max=canvas_size[0])
|
| 251 |
+
out_boxes = convert_bounding_box_format(
|
| 252 |
+
xyxy_boxes, old_format=BoundingBoxFormat.XYXY, new_format=format, inplace=True
|
| 253 |
+
)
|
| 254 |
+
return out_boxes.to(in_dtype)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def clamp_bounding_boxes(
|
| 258 |
+
inpt: torch.Tensor,
|
| 259 |
+
format: Optional[BoundingBoxFormat] = None,
|
| 260 |
+
canvas_size: Optional[Tuple[int, int]] = None,
|
| 261 |
+
) -> torch.Tensor:
|
| 262 |
+
"""See :func:`~torchvision.transforms.v2.ClampBoundingBoxes` for details."""
|
| 263 |
+
if not torch.jit.is_scripting():
|
| 264 |
+
_log_api_usage_once(clamp_bounding_boxes)
|
| 265 |
+
|
| 266 |
+
if torch.jit.is_scripting() or is_pure_tensor(inpt):
|
| 267 |
+
|
| 268 |
+
if format is None or canvas_size is None:
|
| 269 |
+
raise ValueError("For pure tensor inputs, `format` and `canvas_size` have to be passed.")
|
| 270 |
+
return _clamp_bounding_boxes(inpt, format=format, canvas_size=canvas_size)
|
| 271 |
+
elif isinstance(inpt, tv_tensors.BoundingBoxes):
|
| 272 |
+
if format is not None or canvas_size is not None:
|
| 273 |
+
raise ValueError("For bounding box tv_tensor inputs, `format` and `canvas_size` must not be passed.")
|
| 274 |
+
output = _clamp_bounding_boxes(inpt.as_subclass(torch.Tensor), format=inpt.format, canvas_size=inpt.canvas_size)
|
| 275 |
+
return tv_tensors.wrap(output, like=inpt)
|
| 276 |
+
else:
|
| 277 |
+
raise TypeError(
|
| 278 |
+
f"Input can either be a plain tensor or a bounding box tv_tensor, but got {type(inpt)} instead."
|
| 279 |
+
)
|
shared/package-files/03/031643f594ecae7d8fd57fab3eb0ca3ef5be1d1bb2d37231980b050bb60c9ebe/ger.h
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/ger_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::ger(Tensor self, Tensor vec2) -> Tensor
|
| 26 |
+
inline at::Tensor ger(const at::Tensor & self, const at::Tensor & vec2) {
|
| 27 |
+
return at::_ops::ger::call(self, vec2);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// aten::ger.out(Tensor self, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!)
|
| 31 |
+
inline at::Tensor & ger_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & vec2) {
|
| 32 |
+
return at::_ops::ger_out::call(self, vec2, out);
|
| 33 |
+
}
|
| 34 |
+
// aten::ger.out(Tensor self, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!)
|
| 35 |
+
inline at::Tensor & ger_outf(const at::Tensor & self, const at::Tensor & vec2, at::Tensor & out) {
|
| 36 |
+
return at::_ops::ger_out::call(self, vec2, out);
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
}
|
shared/package-files/03/03183173734448b7ce55383b69b1a6f5933efe3df2bfe75c3e866c3b8892100a/unique_dim_consecutive_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 unique_dim_consecutive {
|
| 18 |
+
using schema = ::std::tuple<at::Tensor,at::Tensor,at::Tensor> (const at::Tensor &, int64_t, bool, bool);
|
| 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::unique_dim_consecutive")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "unique_dim_consecutive(Tensor self, int dim, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor)")
|
| 24 |
+
static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> call(const at::Tensor & self, int64_t dim, bool return_inverse, bool return_counts);
|
| 25 |
+
static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool return_inverse, bool return_counts);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API unique_dim_consecutive_out {
|
| 29 |
+
using schema = ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> (const at::Tensor &, int64_t, bool, bool, at::Tensor &, 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::unique_dim_consecutive")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "unique_dim_consecutive.out(Tensor self, int dim, bool return_inverse=False, bool return_counts=False, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))")
|
| 35 |
+
static ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> call(const at::Tensor & self, int64_t dim, bool return_inverse, bool return_counts, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
|
| 36 |
+
static ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool return_inverse, bool return_counts, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
}} // namespace at::_ops
|
shared/package-files/03/031ace958cbed534d359e432a4329e5eb0c2add1c6a2bd042821387f1cd2406a/AAAA.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
|
| 2 |
+
|
| 3 |
+
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
|
| 4 |
+
#
|
| 5 |
+
# Permission to use, copy, modify, and distribute this software and its
|
| 6 |
+
# documentation for any purpose with or without fee is hereby granted,
|
| 7 |
+
# provided that the above copyright notice and this permission notice
|
| 8 |
+
# appear in all copies.
|
| 9 |
+
#
|
| 10 |
+
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
|
| 11 |
+
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
| 12 |
+
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
|
| 13 |
+
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
| 14 |
+
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
| 15 |
+
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
| 16 |
+
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
| 17 |
+
|
| 18 |
+
import dns.exception
|
| 19 |
+
import dns.immutable
|
| 20 |
+
import dns.ipv6
|
| 21 |
+
import dns.rdata
|
| 22 |
+
import dns.tokenizer
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dns.immutable.immutable
|
| 26 |
+
class AAAA(dns.rdata.Rdata):
|
| 27 |
+
"""AAAA record."""
|
| 28 |
+
|
| 29 |
+
__slots__ = ["address"]
|
| 30 |
+
|
| 31 |
+
def __init__(self, rdclass, rdtype, address):
|
| 32 |
+
super().__init__(rdclass, rdtype)
|
| 33 |
+
self.address = self._as_ipv6_address(address)
|
| 34 |
+
|
| 35 |
+
def to_text(self, origin=None, relativize=True, **kw):
|
| 36 |
+
return self.address
|
| 37 |
+
|
| 38 |
+
@classmethod
|
| 39 |
+
def from_text(
|
| 40 |
+
cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None
|
| 41 |
+
):
|
| 42 |
+
address = tok.get_identifier()
|
| 43 |
+
return cls(rdclass, rdtype, address)
|
| 44 |
+
|
| 45 |
+
def _to_wire(self, file, compress=None, origin=None, canonicalize=False):
|
| 46 |
+
file.write(dns.ipv6.inet_aton(self.address))
|
| 47 |
+
|
| 48 |
+
@classmethod
|
| 49 |
+
def from_wire_parser(cls, rdclass, rdtype, parser, origin=None):
|
| 50 |
+
address = parser.get_remaining()
|
| 51 |
+
return cls(rdclass, rdtype, address)
|
shared/package-files/03/031b2634b8ae567c2c371e6ad2a5b5e554eee6a6f9951c5e35d2c7d4b233156a/softplus_compositeexplicitautogradnonfunctional_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 compositeexplicitautogradnonfunctional {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor softplus(const at::Tensor & self, const at::Scalar & beta=1, const at::Scalar & threshold=20);
|
| 21 |
+
|
| 22 |
+
} // namespace compositeexplicitautogradnonfunctional
|
| 23 |
+
} // namespace at
|
shared/package-files/03/031c14693c4b798295b344469fa56ed3fba46991e605949b39babb3dca9370e4/new_empty_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 new_empty_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::optional<at::ScalarType> dtype={}, c10::optional<at::Layout> layout={}, c10::optional<at::Device> device={}, c10::optional<bool> pin_memory={});
|
| 20 |
+
TORCH_API at::Tensor & new_empty_out_symint(const at::Tensor & self, c10::SymIntArrayRef size, at::Tensor & out);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
shared/package-files/03/0320c34b6f70b510cecbcd728603b2eee19abb8258434e68fc347e8acba1cded/_dedup_tensors.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates
|
| 2 |
+
import dataclasses
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Dict, List
|
| 5 |
+
|
| 6 |
+
from torch.distributed.checkpoint.metadata import MetadataIndex
|
| 7 |
+
from torch.distributed.checkpoint.planner import SavePlan
|
| 8 |
+
|
| 9 |
+
__all__ = ["dedup_tensors"]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def init_logger() -> logging.Logger:
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
level = logging.INFO
|
| 15 |
+
logger.setLevel(level)
|
| 16 |
+
console = logging.StreamHandler()
|
| 17 |
+
formatter = logging.Formatter(
|
| 18 |
+
"%(asctime)s %(filename)s:%(lineno)s %(levelname)s p:%(processName)s t:%(threadName)s: %(message)s"
|
| 19 |
+
)
|
| 20 |
+
console.setFormatter(formatter)
|
| 21 |
+
console.setLevel(level)
|
| 22 |
+
logger.addHandler(console)
|
| 23 |
+
logger.propagate = False
|
| 24 |
+
return logger
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = init_logger()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# TODO add docstring for dedup_tensors
|
| 31 |
+
def dedup_tensors(all_plans: List[SavePlan]) -> List[SavePlan]:
|
| 32 |
+
all_plans = list(all_plans)
|
| 33 |
+
key_to_plan: Dict[MetadataIndex, List[int]] = {}
|
| 34 |
+
for plan_idx, plan in enumerate(all_plans):
|
| 35 |
+
for write_item in plan.items:
|
| 36 |
+
key_to_plan.setdefault(write_item.index, []).append(plan_idx)
|
| 37 |
+
|
| 38 |
+
replicated_items = {k: v for k, v in key_to_plan.items() if len(v) > 1}
|
| 39 |
+
|
| 40 |
+
# Remove duplicates by always keeping the first entry.
|
| 41 |
+
# Compute the per-rank remove set.
|
| 42 |
+
plan_to_keys: Dict[int, List[MetadataIndex]] = {}
|
| 43 |
+
for key, plans in replicated_items.items():
|
| 44 |
+
for plan_idx in plans[1:]:
|
| 45 |
+
plan_to_keys.setdefault(plan_idx, []).append(key)
|
| 46 |
+
if len(plan_to_keys) > 0:
|
| 47 |
+
logger.info("Duplicate keys to remove: %s", plan_to_keys)
|
| 48 |
+
|
| 49 |
+
for plan_idx, keys in plan_to_keys.items():
|
| 50 |
+
key_set = set(keys)
|
| 51 |
+
# rewrite items and remove elements
|
| 52 |
+
new_items = [
|
| 53 |
+
write_item
|
| 54 |
+
for write_item in all_plans[plan_idx].items
|
| 55 |
+
if write_item.index not in key_set
|
| 56 |
+
]
|
| 57 |
+
all_plans[plan_idx] = dataclasses.replace(all_plans[plan_idx], items=new_items)
|
| 58 |
+
|
| 59 |
+
return all_plans
|
shared/package-files/03/0321bb9206a7c95d23571f9a34111416882a44b1d0aaa167f315376527c9a1a3/cache.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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(list):
|
| 6 |
+
""" List of cached functions """
|
| 7 |
+
|
| 8 |
+
def print_cache(self):
|
| 9 |
+
"""print cache info"""
|
| 10 |
+
|
| 11 |
+
for item in self:
|
| 12 |
+
name = item.__name__
|
| 13 |
+
myfunc = item
|
| 14 |
+
while hasattr(myfunc, '__wrapped__'):
|
| 15 |
+
if hasattr(myfunc, 'cache_info'):
|
| 16 |
+
info = myfunc.cache_info()
|
| 17 |
+
break
|
| 18 |
+
else:
|
| 19 |
+
myfunc = myfunc.__wrapped__
|
| 20 |
+
else:
|
| 21 |
+
info = None
|
| 22 |
+
|
| 23 |
+
print(name, info)
|
| 24 |
+
|
| 25 |
+
def clear_cache(self):
|
| 26 |
+
"""clear cache content"""
|
| 27 |
+
for item in self:
|
| 28 |
+
myfunc = item
|
| 29 |
+
while hasattr(myfunc, '__wrapped__'):
|
| 30 |
+
if hasattr(myfunc, 'cache_clear'):
|
| 31 |
+
myfunc.cache_clear()
|
| 32 |
+
break
|
| 33 |
+
else:
|
| 34 |
+
myfunc = myfunc.__wrapped__
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# global cache registry:
|
| 38 |
+
CACHE = _cache()
|
| 39 |
+
# make clear and print methods available
|
| 40 |
+
print_cache = CACHE.print_cache
|
| 41 |
+
clear_cache = CACHE.clear_cache
|
| 42 |
+
|
| 43 |
+
from functools import lru_cache, wraps
|
| 44 |
+
|
| 45 |
+
def __cacheit(maxsize):
|
| 46 |
+
"""caching decorator.
|
| 47 |
+
|
| 48 |
+
important: the result of cached function must be *immutable*
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
Examples
|
| 52 |
+
========
|
| 53 |
+
|
| 54 |
+
>>> from sympy import cacheit
|
| 55 |
+
>>> @cacheit
|
| 56 |
+
... def f(a, b):
|
| 57 |
+
... return a+b
|
| 58 |
+
|
| 59 |
+
>>> @cacheit
|
| 60 |
+
... def f(a, b): # noqa: F811
|
| 61 |
+
... return [a, b] # <-- WRONG, returns mutable object
|
| 62 |
+
|
| 63 |
+
to force cacheit to check returned results mutability and consistency,
|
| 64 |
+
set environment variable SYMPY_USE_CACHE to 'debug'
|
| 65 |
+
"""
|
| 66 |
+
def func_wrapper(func):
|
| 67 |
+
cfunc = lru_cache(maxsize, typed=True)(func)
|
| 68 |
+
|
| 69 |
+
@wraps(func)
|
| 70 |
+
def wrapper(*args, **kwargs):
|
| 71 |
+
try:
|
| 72 |
+
retval = cfunc(*args, **kwargs)
|
| 73 |
+
except TypeError as e:
|
| 74 |
+
if not e.args or not e.args[0].startswith('unhashable type:'):
|
| 75 |
+
raise
|
| 76 |
+
retval = func(*args, **kwargs)
|
| 77 |
+
return retval
|
| 78 |
+
|
| 79 |
+
wrapper.cache_info = cfunc.cache_info
|
| 80 |
+
wrapper.cache_clear = cfunc.cache_clear
|
| 81 |
+
|
| 82 |
+
CACHE.append(wrapper)
|
| 83 |
+
return wrapper
|
| 84 |
+
|
| 85 |
+
return func_wrapper
|
| 86 |
+
########################################
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def __cacheit_nocache(func):
|
| 90 |
+
return func
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def __cacheit_debug(maxsize):
|
| 94 |
+
"""cacheit + code to check cache consistency"""
|
| 95 |
+
def func_wrapper(func):
|
| 96 |
+
cfunc = __cacheit(maxsize)(func)
|
| 97 |
+
|
| 98 |
+
@wraps(func)
|
| 99 |
+
def wrapper(*args, **kw_args):
|
| 100 |
+
# always call function itself and compare it with cached version
|
| 101 |
+
r1 = func(*args, **kw_args)
|
| 102 |
+
r2 = cfunc(*args, **kw_args)
|
| 103 |
+
|
| 104 |
+
# try to see if the result is immutable
|
| 105 |
+
#
|
| 106 |
+
# this works because:
|
| 107 |
+
#
|
| 108 |
+
# hash([1,2,3]) -> raise TypeError
|
| 109 |
+
# hash({'a':1, 'b':2}) -> raise TypeError
|
| 110 |
+
# hash((1,[2,3])) -> raise TypeError
|
| 111 |
+
#
|
| 112 |
+
# hash((1,2,3)) -> just computes the hash
|
| 113 |
+
hash(r1), hash(r2)
|
| 114 |
+
|
| 115 |
+
# also see if returned values are the same
|
| 116 |
+
if r1 != r2:
|
| 117 |
+
raise RuntimeError("Returned values are not the same")
|
| 118 |
+
return r1
|
| 119 |
+
return wrapper
|
| 120 |
+
return func_wrapper
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _getenv(key, default=None):
|
| 124 |
+
from os import getenv
|
| 125 |
+
return getenv(key, default)
|
| 126 |
+
|
| 127 |
+
# SYMPY_USE_CACHE=yes/no/debug
|
| 128 |
+
USE_CACHE = _getenv('SYMPY_USE_CACHE', 'yes').lower()
|
| 129 |
+
# SYMPY_CACHE_SIZE=some_integer/None
|
| 130 |
+
# special cases :
|
| 131 |
+
# SYMPY_CACHE_SIZE=0 -> No caching
|
| 132 |
+
# SYMPY_CACHE_SIZE=None -> Unbounded caching
|
| 133 |
+
scs = _getenv('SYMPY_CACHE_SIZE', '1000')
|
| 134 |
+
if scs.lower() == 'none':
|
| 135 |
+
SYMPY_CACHE_SIZE = None
|
| 136 |
+
else:
|
| 137 |
+
try:
|
| 138 |
+
SYMPY_CACHE_SIZE = int(scs)
|
| 139 |
+
except ValueError:
|
| 140 |
+
raise RuntimeError(
|
| 141 |
+
'SYMPY_CACHE_SIZE must be a valid integer or None. ' + \
|
| 142 |
+
'Got: %s' % SYMPY_CACHE_SIZE)
|
| 143 |
+
|
| 144 |
+
if USE_CACHE == 'no':
|
| 145 |
+
cacheit = __cacheit_nocache
|
| 146 |
+
elif USE_CACHE == 'yes':
|
| 147 |
+
cacheit = __cacheit(SYMPY_CACHE_SIZE)
|
| 148 |
+
elif USE_CACHE == 'debug':
|
| 149 |
+
cacheit = __cacheit_debug(SYMPY_CACHE_SIZE) # a lot slower
|
| 150 |
+
else:
|
| 151 |
+
raise RuntimeError(
|
| 152 |
+
'unrecognized value for SYMPY_USE_CACHE: %s' % USE_CACHE)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def cached_property(func):
|
| 156 |
+
'''Decorator to cache property method'''
|
| 157 |
+
attrname = '__' + func.__name__
|
| 158 |
+
_cached_property_sentinel = object()
|
| 159 |
+
def propfunc(self):
|
| 160 |
+
val = getattr(self, attrname, _cached_property_sentinel)
|
| 161 |
+
if val is _cached_property_sentinel:
|
| 162 |
+
val = func(self)
|
| 163 |
+
setattr(self, attrname, val)
|
| 164 |
+
return val
|
| 165 |
+
return property(propfunc)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def lazy_function(module : str, name : str) -> Callable:
|
| 169 |
+
"""Create a lazy proxy for a function in a module.
|
| 170 |
+
|
| 171 |
+
The module containing the function is not imported until the function is used.
|
| 172 |
+
|
| 173 |
+
"""
|
| 174 |
+
func = None
|
| 175 |
+
|
| 176 |
+
def _get_function():
|
| 177 |
+
nonlocal func
|
| 178 |
+
if func is None:
|
| 179 |
+
func = getattr(import_module(module), name)
|
| 180 |
+
return func
|
| 181 |
+
|
| 182 |
+
# The metaclass is needed so that help() shows the docstring
|
| 183 |
+
class LazyFunctionMeta(type):
|
| 184 |
+
@property
|
| 185 |
+
def __doc__(self):
|
| 186 |
+
docstring = _get_function().__doc__
|
| 187 |
+
docstring += f"\n\nNote: this is a {self.__class__.__name__} wrapper of '{module}.{name}'"
|
| 188 |
+
return docstring
|
| 189 |
+
|
| 190 |
+
class LazyFunction(metaclass=LazyFunctionMeta):
|
| 191 |
+
def __call__(self, *args, **kwargs):
|
| 192 |
+
# inline get of function for performance gh-23832
|
| 193 |
+
nonlocal func
|
| 194 |
+
if func is None:
|
| 195 |
+
func = getattr(import_module(module), name)
|
| 196 |
+
return func(*args, **kwargs)
|
| 197 |
+
|
| 198 |
+
@property
|
| 199 |
+
def __doc__(self):
|
| 200 |
+
docstring = _get_function().__doc__
|
| 201 |
+
docstring += f"\n\nNote: this is a {self.__class__.__name__} wrapper of '{module}.{name}'"
|
| 202 |
+
return docstring
|
| 203 |
+
|
| 204 |
+
def __str__(self):
|
| 205 |
+
return _get_function().__str__()
|
| 206 |
+
|
| 207 |
+
def __repr__(self):
|
| 208 |
+
return f"<{__class__.__name__} object at 0x{id(self):x}>: wrapping '{module}.{name}'"
|
| 209 |
+
|
| 210 |
+
return LazyFunction()
|
shared/package-files/03/0324c87cf5dbfe64812b08fbac549ebf9444c0f074499c549145bba37ae2c259/_softmax_backward_data_compositeexplicitautogradnonfunctional_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 compositeexplicitautogradnonfunctional {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor _softmax_backward_data(const at::Tensor & grad_output, const at::Tensor & output, int64_t dim, at::ScalarType input_dtype);
|
| 21 |
+
|
| 22 |
+
} // namespace compositeexplicitautogradnonfunctional
|
| 23 |
+
} // namespace at
|
shared/package-files/03/03251d9f4fc8b1aeb609b087ab0098ee1192b6e790b73100407a717f58a54506/convolution_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 convolution {
|
| 18 |
+
using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const c10::optional<at::Tensor> &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, bool, c10::SymIntArrayRef, c10::SymInt);
|
| 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::convolution")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups) -> Tensor")
|
| 24 |
+
static at::Tensor call(const at::Tensor & input, const at::Tensor & weight, const c10::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups);
|
| 25 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & weight, const c10::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API convolution_out {
|
| 29 |
+
using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const c10::optional<at::Tensor> &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, bool, c10::SymIntArrayRef, c10::SymInt, 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::convolution")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "convolution.out(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, *, Tensor(a!) out) -> Tensor(a!)")
|
| 35 |
+
static at::Tensor & call(const at::Tensor & input, const at::Tensor & weight, const c10::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, at::Tensor & out);
|
| 36 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & weight, const c10::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, at::Tensor & out);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
}} // namespace at::_ops
|
shared/package-files/03/0325c1dc539efa12931bc6f28e6465ed7a6ef45ff407dc466c873823aa0cc11e/native_batch_norm_backward.h
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/native_batch_norm_backward_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::native_batch_norm_backward(Tensor grad_out, Tensor input, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_invstd, bool train, float eps, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
|
| 26 |
+
inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor> native_batch_norm_backward(const at::Tensor & grad_out, const at::Tensor & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & running_mean, const c10::optional<at::Tensor> & running_var, const c10::optional<at::Tensor> & save_mean, const c10::optional<at::Tensor> & save_invstd, bool train, double eps, ::std::array<bool,3> output_mask) {
|
| 27 |
+
return at::_ops::native_batch_norm_backward::call(grad_out, input, weight, running_mean, running_var, save_mean, save_invstd, train, eps, output_mask);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// aten::native_batch_norm_backward.out(Tensor grad_out, Tensor input, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_invstd, bool train, float eps, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
|
| 31 |
+
inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> native_batch_norm_backward_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & grad_out, const at::Tensor & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & running_mean, const c10::optional<at::Tensor> & running_var, const c10::optional<at::Tensor> & save_mean, const c10::optional<at::Tensor> & save_invstd, bool train, double eps, ::std::array<bool,3> output_mask) {
|
| 32 |
+
return at::_ops::native_batch_norm_backward_out::call(grad_out, input, weight, running_mean, running_var, save_mean, save_invstd, train, eps, output_mask, out0, out1, out2);
|
| 33 |
+
}
|
| 34 |
+
// aten::native_batch_norm_backward.out(Tensor grad_out, Tensor input, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_invstd, bool train, float eps, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
|
| 35 |
+
inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> native_batch_norm_backward_outf(const at::Tensor & grad_out, const at::Tensor & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & running_mean, const c10::optional<at::Tensor> & running_var, const c10::optional<at::Tensor> & save_mean, const c10::optional<at::Tensor> & save_invstd, bool train, double eps, ::std::array<bool,3> output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) {
|
| 36 |
+
return at::_ops::native_batch_norm_backward_out::call(grad_out, input, weight, running_mean, running_var, save_mean, save_invstd, train, eps, output_mask, out0, out1, out2);
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
}
|
shared/package-files/03/032863b05f89846c07759a3f0473d99c0a90839a7a238cab43e180cdb2208821/__init__.pyi
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Tuple
|
| 2 |
+
|
| 3 |
+
from waitress.server import create_server as create_server
|
| 4 |
+
|
| 5 |
+
def serve(app: Any, **kw: Any) -> None: ...
|
| 6 |
+
def serve_paste(app: Any, global_conf: Any, **kw: Any) -> int: ...
|
| 7 |
+
def profile(cmd: Any, globals: Any, locals: Any, sort_order: Tuple[str, ...], callers: bool) -> None: ...
|
shared/package-files/03/033099246f5f08faa159aa6b542aa2189859b6a4a50934c89abb4f3b07b3b801/katz.py
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Katz centrality."""
|
| 2 |
+
import math
|
| 3 |
+
|
| 4 |
+
import networkx as nx
|
| 5 |
+
from networkx.utils import not_implemented_for
|
| 6 |
+
|
| 7 |
+
__all__ = ["katz_centrality", "katz_centrality_numpy"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@nx._dispatch
|
| 11 |
+
@not_implemented_for("multigraph")
|
| 12 |
+
def katz_centrality(
|
| 13 |
+
G,
|
| 14 |
+
alpha=0.1,
|
| 15 |
+
beta=1.0,
|
| 16 |
+
max_iter=1000,
|
| 17 |
+
tol=1.0e-6,
|
| 18 |
+
nstart=None,
|
| 19 |
+
normalized=True,
|
| 20 |
+
weight=None,
|
| 21 |
+
):
|
| 22 |
+
r"""Compute the Katz centrality for the nodes of the graph G.
|
| 23 |
+
|
| 24 |
+
Katz centrality computes the centrality for a node based on the centrality
|
| 25 |
+
of its neighbors. It is a generalization of the eigenvector centrality. The
|
| 26 |
+
Katz centrality for node $i$ is
|
| 27 |
+
|
| 28 |
+
.. math::
|
| 29 |
+
|
| 30 |
+
x_i = \alpha \sum_{j} A_{ij} x_j + \beta,
|
| 31 |
+
|
| 32 |
+
where $A$ is the adjacency matrix of graph G with eigenvalues $\lambda$.
|
| 33 |
+
|
| 34 |
+
The parameter $\beta$ controls the initial centrality and
|
| 35 |
+
|
| 36 |
+
.. math::
|
| 37 |
+
|
| 38 |
+
\alpha < \frac{1}{\lambda_{\max}}.
|
| 39 |
+
|
| 40 |
+
Katz centrality computes the relative influence of a node within a
|
| 41 |
+
network by measuring the number of the immediate neighbors (first
|
| 42 |
+
degree nodes) and also all other nodes in the network that connect
|
| 43 |
+
to the node under consideration through these immediate neighbors.
|
| 44 |
+
|
| 45 |
+
Extra weight can be provided to immediate neighbors through the
|
| 46 |
+
parameter $\beta$. Connections made with distant neighbors
|
| 47 |
+
are, however, penalized by an attenuation factor $\alpha$ which
|
| 48 |
+
should be strictly less than the inverse largest eigenvalue of the
|
| 49 |
+
adjacency matrix in order for the Katz centrality to be computed
|
| 50 |
+
correctly. More information is provided in [1]_.
|
| 51 |
+
|
| 52 |
+
Parameters
|
| 53 |
+
----------
|
| 54 |
+
G : graph
|
| 55 |
+
A NetworkX graph.
|
| 56 |
+
|
| 57 |
+
alpha : float
|
| 58 |
+
Attenuation factor
|
| 59 |
+
|
| 60 |
+
beta : scalar or dictionary, optional (default=1.0)
|
| 61 |
+
Weight attributed to the immediate neighborhood. If not a scalar, the
|
| 62 |
+
dictionary must have an value for every node.
|
| 63 |
+
|
| 64 |
+
max_iter : integer, optional (default=1000)
|
| 65 |
+
Maximum number of iterations in power method.
|
| 66 |
+
|
| 67 |
+
tol : float, optional (default=1.0e-6)
|
| 68 |
+
Error tolerance used to check convergence in power method iteration.
|
| 69 |
+
|
| 70 |
+
nstart : dictionary, optional
|
| 71 |
+
Starting value of Katz iteration for each node.
|
| 72 |
+
|
| 73 |
+
normalized : bool, optional (default=True)
|
| 74 |
+
If True normalize the resulting values.
|
| 75 |
+
|
| 76 |
+
weight : None or string, optional (default=None)
|
| 77 |
+
If None, all edge weights are considered equal.
|
| 78 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 79 |
+
In this measure the weight is interpreted as the connection strength.
|
| 80 |
+
|
| 81 |
+
Returns
|
| 82 |
+
-------
|
| 83 |
+
nodes : dictionary
|
| 84 |
+
Dictionary of nodes with Katz centrality as the value.
|
| 85 |
+
|
| 86 |
+
Raises
|
| 87 |
+
------
|
| 88 |
+
NetworkXError
|
| 89 |
+
If the parameter `beta` is not a scalar but lacks a value for at least
|
| 90 |
+
one node
|
| 91 |
+
|
| 92 |
+
PowerIterationFailedConvergence
|
| 93 |
+
If the algorithm fails to converge to the specified tolerance
|
| 94 |
+
within the specified number of iterations of the power iteration
|
| 95 |
+
method.
|
| 96 |
+
|
| 97 |
+
Examples
|
| 98 |
+
--------
|
| 99 |
+
>>> import math
|
| 100 |
+
>>> G = nx.path_graph(4)
|
| 101 |
+
>>> phi = (1 + math.sqrt(5)) / 2.0 # largest eigenvalue of adj matrix
|
| 102 |
+
>>> centrality = nx.katz_centrality(G, 1 / phi - 0.01)
|
| 103 |
+
>>> for n, c in sorted(centrality.items()):
|
| 104 |
+
... print(f"{n} {c:.2f}")
|
| 105 |
+
0 0.37
|
| 106 |
+
1 0.60
|
| 107 |
+
2 0.60
|
| 108 |
+
3 0.37
|
| 109 |
+
|
| 110 |
+
See Also
|
| 111 |
+
--------
|
| 112 |
+
katz_centrality_numpy
|
| 113 |
+
eigenvector_centrality
|
| 114 |
+
eigenvector_centrality_numpy
|
| 115 |
+
pagerank
|
| 116 |
+
hits
|
| 117 |
+
|
| 118 |
+
Notes
|
| 119 |
+
-----
|
| 120 |
+
Katz centrality was introduced by [2]_.
|
| 121 |
+
|
| 122 |
+
This algorithm it uses the power method to find the eigenvector
|
| 123 |
+
corresponding to the largest eigenvalue of the adjacency matrix of ``G``.
|
| 124 |
+
The parameter ``alpha`` should be strictly less than the inverse of largest
|
| 125 |
+
eigenvalue of the adjacency matrix for the algorithm to converge.
|
| 126 |
+
You can use ``max(nx.adjacency_spectrum(G))`` to get $\lambda_{\max}$ the largest
|
| 127 |
+
eigenvalue of the adjacency matrix.
|
| 128 |
+
The iteration will stop after ``max_iter`` iterations or an error tolerance of
|
| 129 |
+
``number_of_nodes(G) * tol`` has been reached.
|
| 130 |
+
|
| 131 |
+
When $\alpha = 1/\lambda_{\max}$ and $\beta=0$, Katz centrality is the same
|
| 132 |
+
as eigenvector centrality.
|
| 133 |
+
|
| 134 |
+
For directed graphs this finds "left" eigenvectors which corresponds
|
| 135 |
+
to the in-edges in the graph. For out-edges Katz centrality
|
| 136 |
+
first reverse the graph with ``G.reverse()``.
|
| 137 |
+
|
| 138 |
+
References
|
| 139 |
+
----------
|
| 140 |
+
.. [1] Mark E. J. Newman:
|
| 141 |
+
Networks: An Introduction.
|
| 142 |
+
Oxford University Press, USA, 2010, p. 720.
|
| 143 |
+
.. [2] Leo Katz:
|
| 144 |
+
A New Status Index Derived from Sociometric Index.
|
| 145 |
+
Psychometrika 18(1):39–43, 1953
|
| 146 |
+
https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
|
| 147 |
+
"""
|
| 148 |
+
if len(G) == 0:
|
| 149 |
+
return {}
|
| 150 |
+
|
| 151 |
+
nnodes = G.number_of_nodes()
|
| 152 |
+
|
| 153 |
+
if nstart is None:
|
| 154 |
+
# choose starting vector with entries of 0
|
| 155 |
+
x = {n: 0 for n in G}
|
| 156 |
+
else:
|
| 157 |
+
x = nstart
|
| 158 |
+
|
| 159 |
+
try:
|
| 160 |
+
b = dict.fromkeys(G, float(beta))
|
| 161 |
+
except (TypeError, ValueError, AttributeError) as err:
|
| 162 |
+
b = beta
|
| 163 |
+
if set(beta) != set(G):
|
| 164 |
+
raise nx.NetworkXError(
|
| 165 |
+
"beta dictionary " "must have a value for every node"
|
| 166 |
+
) from err
|
| 167 |
+
|
| 168 |
+
# make up to max_iter iterations
|
| 169 |
+
for _ in range(max_iter):
|
| 170 |
+
xlast = x
|
| 171 |
+
x = dict.fromkeys(xlast, 0)
|
| 172 |
+
# do the multiplication y^T = Alpha * x^T A + Beta
|
| 173 |
+
for n in x:
|
| 174 |
+
for nbr in G[n]:
|
| 175 |
+
x[nbr] += xlast[n] * G[n][nbr].get(weight, 1)
|
| 176 |
+
for n in x:
|
| 177 |
+
x[n] = alpha * x[n] + b[n]
|
| 178 |
+
|
| 179 |
+
# check convergence
|
| 180 |
+
error = sum(abs(x[n] - xlast[n]) for n in x)
|
| 181 |
+
if error < nnodes * tol:
|
| 182 |
+
if normalized:
|
| 183 |
+
# normalize vector
|
| 184 |
+
try:
|
| 185 |
+
s = 1.0 / math.hypot(*x.values())
|
| 186 |
+
# this should never be zero?
|
| 187 |
+
except ZeroDivisionError:
|
| 188 |
+
s = 1.0
|
| 189 |
+
else:
|
| 190 |
+
s = 1
|
| 191 |
+
for n in x:
|
| 192 |
+
x[n] *= s
|
| 193 |
+
return x
|
| 194 |
+
raise nx.PowerIterationFailedConvergence(max_iter)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
@not_implemented_for("multigraph")
|
| 198 |
+
def katz_centrality_numpy(G, alpha=0.1, beta=1.0, normalized=True, weight=None):
|
| 199 |
+
r"""Compute the Katz centrality for the graph G.
|
| 200 |
+
|
| 201 |
+
Katz centrality computes the centrality for a node based on the centrality
|
| 202 |
+
of its neighbors. It is a generalization of the eigenvector centrality. The
|
| 203 |
+
Katz centrality for node $i$ is
|
| 204 |
+
|
| 205 |
+
.. math::
|
| 206 |
+
|
| 207 |
+
x_i = \alpha \sum_{j} A_{ij} x_j + \beta,
|
| 208 |
+
|
| 209 |
+
where $A$ is the adjacency matrix of graph G with eigenvalues $\lambda$.
|
| 210 |
+
|
| 211 |
+
The parameter $\beta$ controls the initial centrality and
|
| 212 |
+
|
| 213 |
+
.. math::
|
| 214 |
+
|
| 215 |
+
\alpha < \frac{1}{\lambda_{\max}}.
|
| 216 |
+
|
| 217 |
+
Katz centrality computes the relative influence of a node within a
|
| 218 |
+
network by measuring the number of the immediate neighbors (first
|
| 219 |
+
degree nodes) and also all other nodes in the network that connect
|
| 220 |
+
to the node under consideration through these immediate neighbors.
|
| 221 |
+
|
| 222 |
+
Extra weight can be provided to immediate neighbors through the
|
| 223 |
+
parameter $\beta$. Connections made with distant neighbors
|
| 224 |
+
are, however, penalized by an attenuation factor $\alpha$ which
|
| 225 |
+
should be strictly less than the inverse largest eigenvalue of the
|
| 226 |
+
adjacency matrix in order for the Katz centrality to be computed
|
| 227 |
+
correctly. More information is provided in [1]_.
|
| 228 |
+
|
| 229 |
+
Parameters
|
| 230 |
+
----------
|
| 231 |
+
G : graph
|
| 232 |
+
A NetworkX graph
|
| 233 |
+
|
| 234 |
+
alpha : float
|
| 235 |
+
Attenuation factor
|
| 236 |
+
|
| 237 |
+
beta : scalar or dictionary, optional (default=1.0)
|
| 238 |
+
Weight attributed to the immediate neighborhood. If not a scalar the
|
| 239 |
+
dictionary must have an value for every node.
|
| 240 |
+
|
| 241 |
+
normalized : bool
|
| 242 |
+
If True normalize the resulting values.
|
| 243 |
+
|
| 244 |
+
weight : None or string, optional
|
| 245 |
+
If None, all edge weights are considered equal.
|
| 246 |
+
Otherwise holds the name of the edge attribute used as weight.
|
| 247 |
+
In this measure the weight is interpreted as the connection strength.
|
| 248 |
+
|
| 249 |
+
Returns
|
| 250 |
+
-------
|
| 251 |
+
nodes : dictionary
|
| 252 |
+
Dictionary of nodes with Katz centrality as the value.
|
| 253 |
+
|
| 254 |
+
Raises
|
| 255 |
+
------
|
| 256 |
+
NetworkXError
|
| 257 |
+
If the parameter `beta` is not a scalar but lacks a value for at least
|
| 258 |
+
one node
|
| 259 |
+
|
| 260 |
+
Examples
|
| 261 |
+
--------
|
| 262 |
+
>>> import math
|
| 263 |
+
>>> G = nx.path_graph(4)
|
| 264 |
+
>>> phi = (1 + math.sqrt(5)) / 2.0 # largest eigenvalue of adj matrix
|
| 265 |
+
>>> centrality = nx.katz_centrality_numpy(G, 1 / phi)
|
| 266 |
+
>>> for n, c in sorted(centrality.items()):
|
| 267 |
+
... print(f"{n} {c:.2f}")
|
| 268 |
+
0 0.37
|
| 269 |
+
1 0.60
|
| 270 |
+
2 0.60
|
| 271 |
+
3 0.37
|
| 272 |
+
|
| 273 |
+
See Also
|
| 274 |
+
--------
|
| 275 |
+
katz_centrality
|
| 276 |
+
eigenvector_centrality_numpy
|
| 277 |
+
eigenvector_centrality
|
| 278 |
+
pagerank
|
| 279 |
+
hits
|
| 280 |
+
|
| 281 |
+
Notes
|
| 282 |
+
-----
|
| 283 |
+
Katz centrality was introduced by [2]_.
|
| 284 |
+
|
| 285 |
+
This algorithm uses a direct linear solver to solve the above equation.
|
| 286 |
+
The parameter ``alpha`` should be strictly less than the inverse of largest
|
| 287 |
+
eigenvalue of the adjacency matrix for there to be a solution.
|
| 288 |
+
You can use ``max(nx.adjacency_spectrum(G))`` to get $\lambda_{\max}$ the largest
|
| 289 |
+
eigenvalue of the adjacency matrix.
|
| 290 |
+
|
| 291 |
+
When $\alpha = 1/\lambda_{\max}$ and $\beta=0$, Katz centrality is the same
|
| 292 |
+
as eigenvector centrality.
|
| 293 |
+
|
| 294 |
+
For directed graphs this finds "left" eigenvectors which corresponds
|
| 295 |
+
to the in-edges in the graph. For out-edges Katz centrality
|
| 296 |
+
first reverse the graph with ``G.reverse()``.
|
| 297 |
+
|
| 298 |
+
References
|
| 299 |
+
----------
|
| 300 |
+
.. [1] Mark E. J. Newman:
|
| 301 |
+
Networks: An Introduction.
|
| 302 |
+
Oxford University Press, USA, 2010, p. 173.
|
| 303 |
+
.. [2] Leo Katz:
|
| 304 |
+
A New Status Index Derived from Sociometric Index.
|
| 305 |
+
Psychometrika 18(1):39–43, 1953
|
| 306 |
+
https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
|
| 307 |
+
"""
|
| 308 |
+
import numpy as np
|
| 309 |
+
|
| 310 |
+
if len(G) == 0:
|
| 311 |
+
return {}
|
| 312 |
+
try:
|
| 313 |
+
nodelist = beta.keys()
|
| 314 |
+
if set(nodelist) != set(G):
|
| 315 |
+
raise nx.NetworkXError(
|
| 316 |
+
"beta dictionary " "must have a value for every node"
|
| 317 |
+
)
|
| 318 |
+
b = np.array(list(beta.values()), dtype=float)
|
| 319 |
+
except AttributeError:
|
| 320 |
+
nodelist = list(G)
|
| 321 |
+
try:
|
| 322 |
+
b = np.ones((len(nodelist), 1)) * beta
|
| 323 |
+
except (TypeError, ValueError, AttributeError) as err:
|
| 324 |
+
raise nx.NetworkXError("beta must be a number") from err
|
| 325 |
+
|
| 326 |
+
A = nx.adjacency_matrix(G, nodelist=nodelist, weight=weight).todense().T
|
| 327 |
+
n = A.shape[0]
|
| 328 |
+
centrality = np.linalg.solve(np.eye(n, n) - (alpha * A), b)
|
| 329 |
+
if normalized:
|
| 330 |
+
norm = np.sign(sum(centrality)) * np.linalg.norm(centrality)
|
| 331 |
+
else:
|
| 332 |
+
norm = 1.0
|
| 333 |
+
centrality = dict(zip(nodelist, map(float, centrality / norm)))
|
| 334 |
+
return centrality
|
shared/package-files/03/0333d6dcb876478b139be454522e0e7776926daf73a0b712ff31c1c73b6fe332/process.h
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
// or more contributor license agreements. See the NOTICE file
|
| 3 |
+
// distributed with this work for additional information
|
| 4 |
+
// regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
// to you under the Apache License, Version 2.0 (the
|
| 6 |
+
// "License"); you may not use this file except in compliance
|
| 7 |
+
// with the License. You may obtain a copy of the License at
|
| 8 |
+
//
|
| 9 |
+
// http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
//
|
| 11 |
+
// Unless required by applicable law or agreed to in writing,
|
| 12 |
+
// software distributed under the License is distributed on an
|
| 13 |
+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
// KIND, either express or implied. See the License for the
|
| 15 |
+
// specific language governing permissions and limitations
|
| 16 |
+
// under the License.
|
| 17 |
+
|
| 18 |
+
#pragma once
|
| 19 |
+
|
| 20 |
+
#include <memory>
|
| 21 |
+
#include <string>
|
| 22 |
+
#include <vector>
|
| 23 |
+
|
| 24 |
+
#include "arrow/status.h"
|
| 25 |
+
#include "arrow/testing/visibility.h"
|
| 26 |
+
|
| 27 |
+
namespace arrow::util {
|
| 28 |
+
|
| 29 |
+
class ARROW_TESTING_EXPORT Process {
|
| 30 |
+
public:
|
| 31 |
+
Process();
|
| 32 |
+
~Process();
|
| 33 |
+
|
| 34 |
+
Status SetExecutable(const std::string& path);
|
| 35 |
+
void SetArgs(const std::vector<std::string>& args);
|
| 36 |
+
void SetEnv(const std::string& name, const std::string& value);
|
| 37 |
+
void IgnoreStderr();
|
| 38 |
+
Status Execute();
|
| 39 |
+
bool IsRunning();
|
| 40 |
+
uint64_t pid();
|
| 41 |
+
|
| 42 |
+
private:
|
| 43 |
+
class Impl;
|
| 44 |
+
std::unique_ptr<Impl> impl_;
|
| 45 |
+
};
|
| 46 |
+
} // namespace arrow::util
|
shared/package-files/03/0334201b81a04b5e76fdcaa61abfcecf63085ec09a97ec5fb22b3b7c0ee7994d/xmlrpc.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""xmlrpclib.Transport implementation
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
import urllib.parse
|
| 6 |
+
import xmlrpc.client
|
| 7 |
+
from typing import TYPE_CHECKING, Tuple
|
| 8 |
+
|
| 9 |
+
from pip._internal.exceptions import NetworkConnectionError
|
| 10 |
+
from pip._internal.network.session import PipSession
|
| 11 |
+
from pip._internal.network.utils import raise_for_status
|
| 12 |
+
|
| 13 |
+
if TYPE_CHECKING:
|
| 14 |
+
from xmlrpc.client import _HostType, _Marshallable
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class PipXmlrpcTransport(xmlrpc.client.Transport):
|
| 20 |
+
"""Provide a `xmlrpclib.Transport` implementation via a `PipSession`
|
| 21 |
+
object.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(
|
| 25 |
+
self, index_url: str, session: PipSession, use_datetime: bool = False
|
| 26 |
+
) -> None:
|
| 27 |
+
super().__init__(use_datetime)
|
| 28 |
+
index_parts = urllib.parse.urlparse(index_url)
|
| 29 |
+
self._scheme = index_parts.scheme
|
| 30 |
+
self._session = session
|
| 31 |
+
|
| 32 |
+
def request(
|
| 33 |
+
self,
|
| 34 |
+
host: "_HostType",
|
| 35 |
+
handler: str,
|
| 36 |
+
request_body: bytes,
|
| 37 |
+
verbose: bool = False,
|
| 38 |
+
) -> Tuple["_Marshallable", ...]:
|
| 39 |
+
assert isinstance(host, str)
|
| 40 |
+
parts = (self._scheme, host, handler, None, None, None)
|
| 41 |
+
url = urllib.parse.urlunparse(parts)
|
| 42 |
+
try:
|
| 43 |
+
headers = {"Content-Type": "text/xml"}
|
| 44 |
+
response = self._session.post(
|
| 45 |
+
url,
|
| 46 |
+
data=request_body,
|
| 47 |
+
headers=headers,
|
| 48 |
+
stream=True,
|
| 49 |
+
)
|
| 50 |
+
raise_for_status(response)
|
| 51 |
+
self.verbose = verbose
|
| 52 |
+
return self.parse_response(response.raw)
|
| 53 |
+
except NetworkConnectionError as exc:
|
| 54 |
+
assert exc.response
|
| 55 |
+
logger.critical(
|
| 56 |
+
"HTTP error %s while getting %s",
|
| 57 |
+
exc.response.status_code,
|
| 58 |
+
url,
|
| 59 |
+
)
|
| 60 |
+
raise
|
shared/package-files/03/03357aaf07136b86f8b5c7a7a0a87de68e9517ecfbc3be65f3564e761862eb21/test_trophic.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test trophic levels, trophic differences and trophic coherence
|
| 2 |
+
"""
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
np = pytest.importorskip("numpy")
|
| 6 |
+
pytest.importorskip("scipy")
|
| 7 |
+
|
| 8 |
+
import networkx as nx
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_trophic_levels():
|
| 12 |
+
"""Trivial example"""
|
| 13 |
+
G = nx.DiGraph()
|
| 14 |
+
G.add_edge("a", "b")
|
| 15 |
+
G.add_edge("b", "c")
|
| 16 |
+
|
| 17 |
+
d = nx.trophic_levels(G)
|
| 18 |
+
assert d == {"a": 1, "b": 2, "c": 3}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_trophic_levels_levine():
|
| 22 |
+
"""Example from Figure 5 in Stephen Levine (1980) J. theor. Biol. 83,
|
| 23 |
+
195-207
|
| 24 |
+
"""
|
| 25 |
+
S = nx.DiGraph()
|
| 26 |
+
S.add_edge(1, 2, weight=1.0)
|
| 27 |
+
S.add_edge(1, 3, weight=0.2)
|
| 28 |
+
S.add_edge(1, 4, weight=0.8)
|
| 29 |
+
S.add_edge(2, 3, weight=0.2)
|
| 30 |
+
S.add_edge(2, 5, weight=0.3)
|
| 31 |
+
S.add_edge(4, 3, weight=0.6)
|
| 32 |
+
S.add_edge(4, 5, weight=0.7)
|
| 33 |
+
S.add_edge(5, 4, weight=0.2)
|
| 34 |
+
|
| 35 |
+
# save copy for later, test intermediate implementation details first
|
| 36 |
+
S2 = S.copy()
|
| 37 |
+
|
| 38 |
+
# drop nodes of in-degree zero
|
| 39 |
+
z = [nid for nid, d in S.in_degree if d == 0]
|
| 40 |
+
for nid in z:
|
| 41 |
+
S.remove_node(nid)
|
| 42 |
+
|
| 43 |
+
# find adjacency matrix
|
| 44 |
+
q = nx.linalg.graphmatrix.adjacency_matrix(S).T
|
| 45 |
+
|
| 46 |
+
# fmt: off
|
| 47 |
+
expected_q = np.array([
|
| 48 |
+
[0, 0, 0., 0],
|
| 49 |
+
[0.2, 0, 0.6, 0],
|
| 50 |
+
[0, 0, 0, 0.2],
|
| 51 |
+
[0.3, 0, 0.7, 0]
|
| 52 |
+
])
|
| 53 |
+
# fmt: on
|
| 54 |
+
assert np.array_equal(q.todense(), expected_q)
|
| 55 |
+
|
| 56 |
+
# must be square, size of number of nodes
|
| 57 |
+
assert len(q.shape) == 2
|
| 58 |
+
assert q.shape[0] == q.shape[1]
|
| 59 |
+
assert q.shape[0] == len(S)
|
| 60 |
+
|
| 61 |
+
nn = q.shape[0]
|
| 62 |
+
|
| 63 |
+
i = np.eye(nn)
|
| 64 |
+
n = np.linalg.inv(i - q)
|
| 65 |
+
y = np.asarray(n) @ np.ones(nn)
|
| 66 |
+
|
| 67 |
+
expected_y = np.array([1, 2.07906977, 1.46511628, 2.3255814])
|
| 68 |
+
assert np.allclose(y, expected_y)
|
| 69 |
+
|
| 70 |
+
expected_d = {1: 1, 2: 2, 3: 3.07906977, 4: 2.46511628, 5: 3.3255814}
|
| 71 |
+
|
| 72 |
+
d = nx.trophic_levels(S2)
|
| 73 |
+
|
| 74 |
+
for nid, level in d.items():
|
| 75 |
+
expected_level = expected_d[nid]
|
| 76 |
+
assert expected_level == pytest.approx(level, abs=1e-7)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_trophic_levels_simple():
|
| 80 |
+
matrix_a = np.array([[0, 0], [1, 0]])
|
| 81 |
+
G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
|
| 82 |
+
d = nx.trophic_levels(G)
|
| 83 |
+
assert d[0] == pytest.approx(2, abs=1e-7)
|
| 84 |
+
assert d[1] == pytest.approx(1, abs=1e-7)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_trophic_levels_more_complex():
|
| 88 |
+
# fmt: off
|
| 89 |
+
matrix = np.array([
|
| 90 |
+
[0, 1, 0, 0],
|
| 91 |
+
[0, 0, 1, 0],
|
| 92 |
+
[0, 0, 0, 1],
|
| 93 |
+
[0, 0, 0, 0]
|
| 94 |
+
])
|
| 95 |
+
# fmt: on
|
| 96 |
+
G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
|
| 97 |
+
d = nx.trophic_levels(G)
|
| 98 |
+
expected_result = [1, 2, 3, 4]
|
| 99 |
+
for ind in range(4):
|
| 100 |
+
assert d[ind] == pytest.approx(expected_result[ind], abs=1e-7)
|
| 101 |
+
|
| 102 |
+
# fmt: off
|
| 103 |
+
matrix = np.array([
|
| 104 |
+
[0, 1, 1, 0],
|
| 105 |
+
[0, 0, 1, 1],
|
| 106 |
+
[0, 0, 0, 1],
|
| 107 |
+
[0, 0, 0, 0]
|
| 108 |
+
])
|
| 109 |
+
# fmt: on
|
| 110 |
+
G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
|
| 111 |
+
d = nx.trophic_levels(G)
|
| 112 |
+
|
| 113 |
+
expected_result = [1, 2, 2.5, 3.25]
|
| 114 |
+
print("Calculated result: ", d)
|
| 115 |
+
print("Expected Result: ", expected_result)
|
| 116 |
+
|
| 117 |
+
for ind in range(4):
|
| 118 |
+
assert d[ind] == pytest.approx(expected_result[ind], abs=1e-7)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def test_trophic_levels_even_more_complex():
|
| 122 |
+
# fmt: off
|
| 123 |
+
# Another, bigger matrix
|
| 124 |
+
matrix = np.array([
|
| 125 |
+
[0, 0, 0, 0, 0],
|
| 126 |
+
[0, 1, 0, 1, 0],
|
| 127 |
+
[1, 0, 0, 0, 0],
|
| 128 |
+
[0, 1, 0, 0, 0],
|
| 129 |
+
[0, 0, 0, 1, 0]
|
| 130 |
+
])
|
| 131 |
+
# Generated this linear system using pen and paper:
|
| 132 |
+
K = np.array([
|
| 133 |
+
[1, 0, -1, 0, 0],
|
| 134 |
+
[0, 0.5, 0, -0.5, 0],
|
| 135 |
+
[0, 0, 1, 0, 0],
|
| 136 |
+
[0, -0.5, 0, 1, -0.5],
|
| 137 |
+
[0, 0, 0, 0, 1],
|
| 138 |
+
])
|
| 139 |
+
# fmt: on
|
| 140 |
+
result_1 = np.ravel(np.linalg.inv(K) @ np.ones(5))
|
| 141 |
+
G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
|
| 142 |
+
result_2 = nx.trophic_levels(G)
|
| 143 |
+
|
| 144 |
+
for ind in range(5):
|
| 145 |
+
assert result_1[ind] == pytest.approx(result_2[ind], abs=1e-7)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def test_trophic_levels_singular_matrix():
|
| 149 |
+
"""Should raise an error with graphs with only non-basal nodes"""
|
| 150 |
+
matrix = np.identity(4)
|
| 151 |
+
G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
|
| 152 |
+
with pytest.raises(nx.NetworkXError) as e:
|
| 153 |
+
nx.trophic_levels(G)
|
| 154 |
+
msg = (
|
| 155 |
+
"Trophic levels are only defined for graphs where every node "
|
| 156 |
+
+ "has a path from a basal node (basal nodes are nodes with no "
|
| 157 |
+
+ "incoming edges)."
|
| 158 |
+
)
|
| 159 |
+
assert msg in str(e.value)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def test_trophic_levels_singular_with_basal():
|
| 163 |
+
"""Should fail to compute if there are any parts of the graph which are not
|
| 164 |
+
reachable from any basal node (with in-degree zero).
|
| 165 |
+
"""
|
| 166 |
+
G = nx.DiGraph()
|
| 167 |
+
# a has in-degree zero
|
| 168 |
+
G.add_edge("a", "b")
|
| 169 |
+
|
| 170 |
+
# b is one level above a, c and d
|
| 171 |
+
G.add_edge("c", "b")
|
| 172 |
+
G.add_edge("d", "b")
|
| 173 |
+
|
| 174 |
+
# c and d form a loop, neither are reachable from a
|
| 175 |
+
G.add_edge("c", "d")
|
| 176 |
+
G.add_edge("d", "c")
|
| 177 |
+
|
| 178 |
+
with pytest.raises(nx.NetworkXError) as e:
|
| 179 |
+
nx.trophic_levels(G)
|
| 180 |
+
msg = (
|
| 181 |
+
"Trophic levels are only defined for graphs where every node "
|
| 182 |
+
+ "has a path from a basal node (basal nodes are nodes with no "
|
| 183 |
+
+ "incoming edges)."
|
| 184 |
+
)
|
| 185 |
+
assert msg in str(e.value)
|
| 186 |
+
|
| 187 |
+
# if self-loops are allowed, smaller example:
|
| 188 |
+
G = nx.DiGraph()
|
| 189 |
+
G.add_edge("a", "b") # a has in-degree zero
|
| 190 |
+
G.add_edge("c", "b") # b is one level above a and c
|
| 191 |
+
G.add_edge("c", "c") # c has a self-loop
|
| 192 |
+
with pytest.raises(nx.NetworkXError) as e:
|
| 193 |
+
nx.trophic_levels(G)
|
| 194 |
+
msg = (
|
| 195 |
+
"Trophic levels are only defined for graphs where every node "
|
| 196 |
+
+ "has a path from a basal node (basal nodes are nodes with no "
|
| 197 |
+
+ "incoming edges)."
|
| 198 |
+
)
|
| 199 |
+
assert msg in str(e.value)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def test_trophic_differences():
|
| 203 |
+
matrix_a = np.array([[0, 1], [0, 0]])
|
| 204 |
+
G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
|
| 205 |
+
diffs = nx.trophic_differences(G)
|
| 206 |
+
assert diffs[(0, 1)] == pytest.approx(1, abs=1e-7)
|
| 207 |
+
|
| 208 |
+
# fmt: off
|
| 209 |
+
matrix_b = np.array([
|
| 210 |
+
[0, 1, 1, 0],
|
| 211 |
+
[0, 0, 1, 1],
|
| 212 |
+
[0, 0, 0, 1],
|
| 213 |
+
[0, 0, 0, 0]
|
| 214 |
+
])
|
| 215 |
+
# fmt: on
|
| 216 |
+
G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph)
|
| 217 |
+
diffs = nx.trophic_differences(G)
|
| 218 |
+
|
| 219 |
+
assert diffs[(0, 1)] == pytest.approx(1, abs=1e-7)
|
| 220 |
+
assert diffs[(0, 2)] == pytest.approx(1.5, abs=1e-7)
|
| 221 |
+
assert diffs[(1, 2)] == pytest.approx(0.5, abs=1e-7)
|
| 222 |
+
assert diffs[(1, 3)] == pytest.approx(1.25, abs=1e-7)
|
| 223 |
+
assert diffs[(2, 3)] == pytest.approx(0.75, abs=1e-7)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def test_trophic_incoherence_parameter_no_cannibalism():
|
| 227 |
+
matrix_a = np.array([[0, 1], [0, 0]])
|
| 228 |
+
G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
|
| 229 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=False)
|
| 230 |
+
assert q == pytest.approx(0, abs=1e-7)
|
| 231 |
+
|
| 232 |
+
# fmt: off
|
| 233 |
+
matrix_b = np.array([
|
| 234 |
+
[0, 1, 1, 0],
|
| 235 |
+
[0, 0, 1, 1],
|
| 236 |
+
[0, 0, 0, 1],
|
| 237 |
+
[0, 0, 0, 0]
|
| 238 |
+
])
|
| 239 |
+
# fmt: on
|
| 240 |
+
G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph)
|
| 241 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=False)
|
| 242 |
+
assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
|
| 243 |
+
|
| 244 |
+
# fmt: off
|
| 245 |
+
matrix_c = np.array([
|
| 246 |
+
[0, 1, 1, 0],
|
| 247 |
+
[0, 1, 1, 1],
|
| 248 |
+
[0, 0, 0, 1],
|
| 249 |
+
[0, 0, 0, 1]
|
| 250 |
+
])
|
| 251 |
+
# fmt: on
|
| 252 |
+
G = nx.from_numpy_array(matrix_c, create_using=nx.DiGraph)
|
| 253 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=False)
|
| 254 |
+
# Ignore the -link
|
| 255 |
+
assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
|
| 256 |
+
|
| 257 |
+
# no self-loops case
|
| 258 |
+
# fmt: off
|
| 259 |
+
matrix_d = np.array([
|
| 260 |
+
[0, 1, 1, 0],
|
| 261 |
+
[0, 0, 1, 1],
|
| 262 |
+
[0, 0, 0, 1],
|
| 263 |
+
[0, 0, 0, 0]
|
| 264 |
+
])
|
| 265 |
+
# fmt: on
|
| 266 |
+
G = nx.from_numpy_array(matrix_d, create_using=nx.DiGraph)
|
| 267 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=False)
|
| 268 |
+
# Ignore the -link
|
| 269 |
+
assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def test_trophic_incoherence_parameter_cannibalism():
|
| 273 |
+
matrix_a = np.array([[0, 1], [0, 0]])
|
| 274 |
+
G = nx.from_numpy_array(matrix_a, create_using=nx.DiGraph)
|
| 275 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=True)
|
| 276 |
+
assert q == pytest.approx(0, abs=1e-7)
|
| 277 |
+
|
| 278 |
+
# fmt: off
|
| 279 |
+
matrix_b = np.array([
|
| 280 |
+
[0, 0, 0, 0, 0],
|
| 281 |
+
[0, 1, 0, 1, 0],
|
| 282 |
+
[1, 0, 0, 0, 0],
|
| 283 |
+
[0, 1, 0, 0, 0],
|
| 284 |
+
[0, 0, 0, 1, 0]
|
| 285 |
+
])
|
| 286 |
+
# fmt: on
|
| 287 |
+
G = nx.from_numpy_array(matrix_b, create_using=nx.DiGraph)
|
| 288 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=True)
|
| 289 |
+
assert q == pytest.approx(2, abs=1e-7)
|
| 290 |
+
|
| 291 |
+
# fmt: off
|
| 292 |
+
matrix_c = np.array([
|
| 293 |
+
[0, 1, 1, 0],
|
| 294 |
+
[0, 0, 1, 1],
|
| 295 |
+
[0, 0, 0, 1],
|
| 296 |
+
[0, 0, 0, 0]
|
| 297 |
+
])
|
| 298 |
+
# fmt: on
|
| 299 |
+
G = nx.from_numpy_array(matrix_c, create_using=nx.DiGraph)
|
| 300 |
+
q = nx.trophic_incoherence_parameter(G, cannibalism=True)
|
| 301 |
+
# Ignore the -link
|
| 302 |
+
assert q == pytest.approx(np.std([1, 1.5, 0.5, 0.75, 1.25]), abs=1e-7)
|
shared/package-files/03/0336f7c5cf56be0c41bd044d0b99bcdd2269aabef788bac6489549e6ce3fccd2/linux-ubuntu18.04-broadwell
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
processor : 0
|
| 2 |
+
vendor_id : GenuineIntel
|
| 3 |
+
cpu family : 6
|
| 4 |
+
model : 61
|
| 5 |
+
model name : Intel(R) Core(TM) i5-5200U CPU @ 2.20GHz
|
| 6 |
+
stepping : 4
|
| 7 |
+
microcode : 0x2d
|
| 8 |
+
cpu MHz : 1944.124
|
| 9 |
+
cache size : 3072 KB
|
| 10 |
+
physical id : 0
|
| 11 |
+
siblings : 4
|
| 12 |
+
core id : 0
|
| 13 |
+
cpu cores : 2
|
| 14 |
+
apicid : 0
|
| 15 |
+
initial apicid : 0
|
| 16 |
+
fpu : yes
|
| 17 |
+
fpu_exception : yes
|
| 18 |
+
cpuid level : 20
|
| 19 |
+
wp : yes
|
| 20 |
+
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap intel_pt xsaveopt dtherm ida arat pln pts md_clear flush_l1d
|
| 21 |
+
bugs : cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds
|
| 22 |
+
bogomips : 4389.80
|
| 23 |
+
clflush size : 64
|
| 24 |
+
cache_alignment : 64
|
| 25 |
+
address sizes : 39 bits physical, 48 bits virtual
|
| 26 |
+
power management:
|
shared/package-files/03/03396305249fef000efc6f56f29920fa8dc87651f331da7926e9613067283913/_optimize.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
shared/package-files/03/033fa0a1a0e2fdb48f6c7bdb2ad38311971f28276f8b0dd72da94faad2e2db8a/MiscUtils.h
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
#include <ATen/cuda/Exceptions.h>
|
| 3 |
+
#include <ATen/cuda/CUDAContext.h>
|
| 4 |
+
#include <ATen/cuda/CUDAConfig.h>
|
| 5 |
+
#include <ATen/cuda/PinnedMemoryAllocator.h>
|
| 6 |
+
|
| 7 |
+
namespace at {
|
| 8 |
+
namespace native {
|
| 9 |
+
|
| 10 |
+
static inline int cuda_int_cast(int64_t value, const char* varname) {
|
| 11 |
+
auto result = static_cast<int>(value);
|
| 12 |
+
TORCH_CHECK(static_cast<int64_t>(result) == value,
|
| 13 |
+
"cuda_int_cast: The value of ", varname, "(", (long long)value,
|
| 14 |
+
") is too large to fit into a int (", sizeof(int), " bytes)");
|
| 15 |
+
return result;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
// Creates an array of size elements of type T, backed by pinned memory
|
| 19 |
+
// wrapped in a Storage
|
| 20 |
+
template<class T>
|
| 21 |
+
static inline Storage pin_memory(int64_t size) {
|
| 22 |
+
auto* allocator = cuda::getPinnedMemoryAllocator();
|
| 23 |
+
int64_t adjusted_size = size * sizeof(T);
|
| 24 |
+
return Storage(
|
| 25 |
+
Storage::use_byte_size_t(),
|
| 26 |
+
adjusted_size,
|
| 27 |
+
allocator,
|
| 28 |
+
/*resizable=*/false);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
} // namespace native
|
| 32 |
+
} // namespace at
|
shared/package-files/03/0340993c4015c58ae9cad8d750640909375dc06f0aaef5156ed05edc0d4caa02/_m_e_t_a.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.misc import sstruct
|
| 2 |
+
from fontTools.misc.textTools import bytesjoin, strjoin, readHex
|
| 3 |
+
from fontTools.ttLib import TTLibError
|
| 4 |
+
from . import DefaultTable
|
| 5 |
+
|
| 6 |
+
# Apple's documentation of 'meta':
|
| 7 |
+
# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html
|
| 8 |
+
|
| 9 |
+
META_HEADER_FORMAT = """
|
| 10 |
+
> # big endian
|
| 11 |
+
version: L
|
| 12 |
+
flags: L
|
| 13 |
+
dataOffset: L
|
| 14 |
+
numDataMaps: L
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
DATA_MAP_FORMAT = """
|
| 19 |
+
> # big endian
|
| 20 |
+
tag: 4s
|
| 21 |
+
dataOffset: L
|
| 22 |
+
dataLength: L
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class table__m_e_t_a(DefaultTable.DefaultTable):
|
| 27 |
+
"""Metadata table
|
| 28 |
+
|
| 29 |
+
The ``meta`` table contains various metadata values for the font. Each
|
| 30 |
+
category of metadata in the table is identified by a four-character tag.
|
| 31 |
+
|
| 32 |
+
See also https://learn.microsoft.com/en-us/typography/opentype/spec/meta
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(self, tag=None):
|
| 36 |
+
DefaultTable.DefaultTable.__init__(self, tag)
|
| 37 |
+
self.data = {}
|
| 38 |
+
|
| 39 |
+
def decompile(self, data, ttFont):
|
| 40 |
+
headerSize = sstruct.calcsize(META_HEADER_FORMAT)
|
| 41 |
+
header = sstruct.unpack(META_HEADER_FORMAT, data[0:headerSize])
|
| 42 |
+
if header["version"] != 1:
|
| 43 |
+
raise TTLibError("unsupported 'meta' version %d" % header["version"])
|
| 44 |
+
dataMapSize = sstruct.calcsize(DATA_MAP_FORMAT)
|
| 45 |
+
for i in range(header["numDataMaps"]):
|
| 46 |
+
dataMapOffset = headerSize + i * dataMapSize
|
| 47 |
+
dataMap = sstruct.unpack(
|
| 48 |
+
DATA_MAP_FORMAT, data[dataMapOffset : dataMapOffset + dataMapSize]
|
| 49 |
+
)
|
| 50 |
+
tag = dataMap["tag"]
|
| 51 |
+
offset = dataMap["dataOffset"]
|
| 52 |
+
self.data[tag] = data[offset : offset + dataMap["dataLength"]]
|
| 53 |
+
if tag in ["dlng", "slng"]:
|
| 54 |
+
self.data[tag] = self.data[tag].decode("utf-8")
|
| 55 |
+
|
| 56 |
+
def compile(self, ttFont):
|
| 57 |
+
keys = sorted(self.data.keys())
|
| 58 |
+
headerSize = sstruct.calcsize(META_HEADER_FORMAT)
|
| 59 |
+
dataOffset = headerSize + len(keys) * sstruct.calcsize(DATA_MAP_FORMAT)
|
| 60 |
+
header = sstruct.pack(
|
| 61 |
+
META_HEADER_FORMAT,
|
| 62 |
+
{
|
| 63 |
+
"version": 1,
|
| 64 |
+
"flags": 0,
|
| 65 |
+
"dataOffset": dataOffset,
|
| 66 |
+
"numDataMaps": len(keys),
|
| 67 |
+
},
|
| 68 |
+
)
|
| 69 |
+
dataMaps = []
|
| 70 |
+
dataBlocks = []
|
| 71 |
+
for tag in keys:
|
| 72 |
+
if tag in ["dlng", "slng"]:
|
| 73 |
+
data = self.data[tag].encode("utf-8")
|
| 74 |
+
else:
|
| 75 |
+
data = self.data[tag]
|
| 76 |
+
dataMaps.append(
|
| 77 |
+
sstruct.pack(
|
| 78 |
+
DATA_MAP_FORMAT,
|
| 79 |
+
{"tag": tag, "dataOffset": dataOffset, "dataLength": len(data)},
|
| 80 |
+
)
|
| 81 |
+
)
|
| 82 |
+
dataBlocks.append(data)
|
| 83 |
+
dataOffset += len(data)
|
| 84 |
+
return bytesjoin([header] + dataMaps + dataBlocks)
|
| 85 |
+
|
| 86 |
+
def toXML(self, writer, ttFont):
|
| 87 |
+
for tag in sorted(self.data.keys()):
|
| 88 |
+
if tag in ["dlng", "slng"]:
|
| 89 |
+
writer.begintag("text", tag=tag)
|
| 90 |
+
writer.newline()
|
| 91 |
+
writer.write(self.data[tag])
|
| 92 |
+
writer.newline()
|
| 93 |
+
writer.endtag("text")
|
| 94 |
+
writer.newline()
|
| 95 |
+
else:
|
| 96 |
+
writer.begintag("hexdata", tag=tag)
|
| 97 |
+
writer.newline()
|
| 98 |
+
data = self.data[tag]
|
| 99 |
+
if min(data) >= 0x20 and max(data) <= 0x7E:
|
| 100 |
+
writer.comment("ascii: " + data.decode("ascii"))
|
| 101 |
+
writer.newline()
|
| 102 |
+
writer.dumphex(data)
|
| 103 |
+
writer.endtag("hexdata")
|
| 104 |
+
writer.newline()
|
| 105 |
+
|
| 106 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 107 |
+
if name == "hexdata":
|
| 108 |
+
self.data[attrs["tag"]] = readHex(content)
|
| 109 |
+
elif name == "text" and attrs["tag"] in ["dlng", "slng"]:
|
| 110 |
+
self.data[attrs["tag"]] = strjoin(content).strip()
|
| 111 |
+
else:
|
| 112 |
+
raise TTLibError("can't handle '%s' element" % name)
|
shared/package-files/03/03416510aea384836f168c4978ca1fd9167c4c41562e4369ccb335d08b2e046a/_fixed.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from ._masker import Masker
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Fixed(Masker):
|
| 7 |
+
"""This leaves the input unchanged during masking, and is used for things like scoring labels.
|
| 8 |
+
|
| 9 |
+
Sometimes there are inputs to the model that we do not want to explain, but rather we want to
|
| 10 |
+
consider them fixed. The primary example of this is when we explain the loss of the model using
|
| 11 |
+
the labels. These "true" labels are inputs to the function we are explaining, but we don't want
|
| 12 |
+
to attribute credit to them, instead we want to consider them fixed and assign all the credit to
|
| 13 |
+
the model's input features. This is where the Fixed masker can help, since we can apply it to the
|
| 14 |
+
label inputs.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self):
|
| 18 |
+
self.shape = (None, 0)
|
| 19 |
+
self.clustering = np.zeros((0, 4))
|
| 20 |
+
|
| 21 |
+
def __call__(self, mask, x):
|
| 22 |
+
return ([x],)
|
| 23 |
+
|
| 24 |
+
def mask_shapes(self, x):
|
| 25 |
+
"""The shape of the masks we expect."""
|
| 26 |
+
return [(0,)]
|
shared/package-files/03/034494ddbb8e506853f8d23fe8b43aa7bd1f152214de22c5760cefceb291e921/data_x_x2_x3.csv
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
0 0 0
|
| 2 |
+
1 1 1
|
| 3 |
+
2 4 8
|
| 4 |
+
3 9 27
|
| 5 |
+
4 16 64
|
| 6 |
+
5 25 125
|
| 7 |
+
6 36 216
|
| 8 |
+
7 49 343
|
| 9 |
+
8 64 512
|
| 10 |
+
9 81 729
|
| 11 |
+
10 100 1000
|
shared/package-files/03/0346d975de368cfa7d65a971d91b47f3c5b4dbd7cbd3913cf4fb416e5bc39141/mgterm
ADDED
|
Binary file (1.14 kB). View file
|
|
|
shared/package-files/03/034812a748714b21037ee80956263709e59a945faf2bbd3561fb73ae3490cd0e/calculus.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class CalculusMethods(object):
|
| 2 |
+
pass
|
| 3 |
+
|
| 4 |
+
def defun(f):
|
| 5 |
+
setattr(CalculusMethods, f.__name__, f)
|
| 6 |
+
return f
|
shared/package-files/03/034870dc0a84357793169d5171bff86b212c2d82ee315173f6ced4ae095ab4b4/test_ivp.py
ADDED
|
@@ -0,0 +1,1287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import product
|
| 2 |
+
from numpy.testing import (assert_, assert_allclose, assert_array_less,
|
| 3 |
+
assert_equal, assert_no_warnings, suppress_warnings)
|
| 4 |
+
import pytest
|
| 5 |
+
from pytest import raises as assert_raises
|
| 6 |
+
import numpy as np
|
| 7 |
+
from scipy.optimize._numdiff import group_columns
|
| 8 |
+
from scipy.integrate import solve_ivp, RK23, RK45, DOP853, Radau, BDF, LSODA
|
| 9 |
+
from scipy.integrate import OdeSolution
|
| 10 |
+
from scipy.integrate._ivp.common import num_jac, select_initial_step
|
| 11 |
+
from scipy.integrate._ivp.base import ConstantDenseOutput
|
| 12 |
+
from scipy.sparse import coo_matrix, csc_matrix
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def fun_zero(t, y):
|
| 16 |
+
return np.zeros_like(y)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def fun_linear(t, y):
|
| 20 |
+
return np.array([-y[0] - 5 * y[1], y[0] + y[1]])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def jac_linear():
|
| 24 |
+
return np.array([[-1, -5], [1, 1]])
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def sol_linear(t):
|
| 28 |
+
return np.vstack((-5 * np.sin(2 * t),
|
| 29 |
+
2 * np.cos(2 * t) + np.sin(2 * t)))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def fun_rational(t, y):
|
| 33 |
+
return np.array([y[1] / t,
|
| 34 |
+
y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))])
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def fun_rational_vectorized(t, y):
|
| 38 |
+
return np.vstack((y[1] / t,
|
| 39 |
+
y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def jac_rational(t, y):
|
| 43 |
+
return np.array([
|
| 44 |
+
[0, 1 / t],
|
| 45 |
+
[-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
|
| 46 |
+
(y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
|
| 47 |
+
])
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def jac_rational_sparse(t, y):
|
| 51 |
+
return csc_matrix([
|
| 52 |
+
[0, 1 / t],
|
| 53 |
+
[-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
|
| 54 |
+
(y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
|
| 55 |
+
])
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def sol_rational(t):
|
| 59 |
+
return np.asarray((t / (t + 10), 10 * t / (t + 10) ** 2))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def fun_medazko(t, y):
|
| 63 |
+
n = y.shape[0] // 2
|
| 64 |
+
k = 100
|
| 65 |
+
c = 4
|
| 66 |
+
|
| 67 |
+
phi = 2 if t <= 5 else 0
|
| 68 |
+
y = np.hstack((phi, 0, y, y[-2]))
|
| 69 |
+
|
| 70 |
+
d = 1 / n
|
| 71 |
+
j = np.arange(n) + 1
|
| 72 |
+
alpha = 2 * (j * d - 1) ** 3 / c ** 2
|
| 73 |
+
beta = (j * d - 1) ** 4 / c ** 2
|
| 74 |
+
|
| 75 |
+
j_2_p1 = 2 * j + 2
|
| 76 |
+
j_2_m3 = 2 * j - 2
|
| 77 |
+
j_2_m1 = 2 * j
|
| 78 |
+
j_2 = 2 * j + 1
|
| 79 |
+
|
| 80 |
+
f = np.empty(2 * n)
|
| 81 |
+
f[::2] = (alpha * (y[j_2_p1] - y[j_2_m3]) / (2 * d) +
|
| 82 |
+
beta * (y[j_2_m3] - 2 * y[j_2_m1] + y[j_2_p1]) / d ** 2 -
|
| 83 |
+
k * y[j_2_m1] * y[j_2])
|
| 84 |
+
f[1::2] = -k * y[j_2] * y[j_2_m1]
|
| 85 |
+
|
| 86 |
+
return f
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def medazko_sparsity(n):
|
| 90 |
+
cols = []
|
| 91 |
+
rows = []
|
| 92 |
+
|
| 93 |
+
i = np.arange(n) * 2
|
| 94 |
+
|
| 95 |
+
cols.append(i[1:])
|
| 96 |
+
rows.append(i[1:] - 2)
|
| 97 |
+
|
| 98 |
+
cols.append(i)
|
| 99 |
+
rows.append(i)
|
| 100 |
+
|
| 101 |
+
cols.append(i)
|
| 102 |
+
rows.append(i + 1)
|
| 103 |
+
|
| 104 |
+
cols.append(i[:-1])
|
| 105 |
+
rows.append(i[:-1] + 2)
|
| 106 |
+
|
| 107 |
+
i = np.arange(n) * 2 + 1
|
| 108 |
+
|
| 109 |
+
cols.append(i)
|
| 110 |
+
rows.append(i)
|
| 111 |
+
|
| 112 |
+
cols.append(i)
|
| 113 |
+
rows.append(i - 1)
|
| 114 |
+
|
| 115 |
+
cols = np.hstack(cols)
|
| 116 |
+
rows = np.hstack(rows)
|
| 117 |
+
|
| 118 |
+
return coo_matrix((np.ones_like(cols), (cols, rows)))
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def fun_complex(t, y):
|
| 122 |
+
return -y
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def jac_complex(t, y):
|
| 126 |
+
return -np.eye(y.shape[0])
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def jac_complex_sparse(t, y):
|
| 130 |
+
return csc_matrix(jac_complex(t, y))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def sol_complex(t):
|
| 134 |
+
y = (0.5 + 1j) * np.exp(-t)
|
| 135 |
+
return y.reshape((1, -1))
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def fun_event_dense_output_LSODA(t, y):
|
| 139 |
+
return y * (t - 2)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def jac_event_dense_output_LSODA(t, y):
|
| 143 |
+
return t - 2
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def sol_event_dense_output_LSODA(t):
|
| 147 |
+
return np.exp(t ** 2 / 2 - 2 * t + np.log(0.05) - 6)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def compute_error(y, y_true, rtol, atol):
|
| 151 |
+
e = (y - y_true) / (atol + rtol * np.abs(y_true))
|
| 152 |
+
return np.linalg.norm(e, axis=0) / np.sqrt(e.shape[0])
|
| 153 |
+
|
| 154 |
+
def test_duplicate_timestamps():
|
| 155 |
+
def upward_cannon(t, y):
|
| 156 |
+
return [y[1], -9.80665]
|
| 157 |
+
|
| 158 |
+
def hit_ground(t, y):
|
| 159 |
+
return y[0]
|
| 160 |
+
|
| 161 |
+
hit_ground.terminal = True
|
| 162 |
+
hit_ground.direction = -1
|
| 163 |
+
|
| 164 |
+
sol = solve_ivp(upward_cannon, [0, np.inf], [0, 0.01],
|
| 165 |
+
max_step=0.05 * 0.001 / 9.80665,
|
| 166 |
+
events=hit_ground, dense_output=True)
|
| 167 |
+
assert_allclose(sol.sol(0.01), np.asarray([-0.00039033, -0.08806632]),
|
| 168 |
+
rtol=1e-5, atol=1e-8)
|
| 169 |
+
assert_allclose(sol.t_events, np.asarray([[0.00203943]]), rtol=1e-5, atol=1e-8)
|
| 170 |
+
assert_allclose(sol.y_events, [np.asarray([[ 0.0, -0.01 ]])], atol=1e-9)
|
| 171 |
+
assert sol.success
|
| 172 |
+
assert_equal(sol.status, 1)
|
| 173 |
+
|
| 174 |
+
@pytest.mark.thread_unsafe
|
| 175 |
+
def test_integration():
|
| 176 |
+
rtol = 1e-3
|
| 177 |
+
atol = 1e-6
|
| 178 |
+
y0 = [1/3, 2/9]
|
| 179 |
+
|
| 180 |
+
for vectorized, method, t_span, jac in product(
|
| 181 |
+
[False, True],
|
| 182 |
+
['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'],
|
| 183 |
+
[[5, 9], [5, 1]],
|
| 184 |
+
[None, jac_rational, jac_rational_sparse]):
|
| 185 |
+
|
| 186 |
+
if vectorized:
|
| 187 |
+
fun = fun_rational_vectorized
|
| 188 |
+
else:
|
| 189 |
+
fun = fun_rational
|
| 190 |
+
|
| 191 |
+
with suppress_warnings() as sup:
|
| 192 |
+
sup.filter(UserWarning,
|
| 193 |
+
"The following arguments have no effect for a chosen "
|
| 194 |
+
"solver: `jac`")
|
| 195 |
+
res = solve_ivp(fun, t_span, y0, rtol=rtol,
|
| 196 |
+
atol=atol, method=method, dense_output=True,
|
| 197 |
+
jac=jac, vectorized=vectorized)
|
| 198 |
+
assert_equal(res.t[0], t_span[0])
|
| 199 |
+
assert_(res.t_events is None)
|
| 200 |
+
assert_(res.y_events is None)
|
| 201 |
+
assert_(res.success)
|
| 202 |
+
assert_equal(res.status, 0)
|
| 203 |
+
|
| 204 |
+
if method == 'DOP853':
|
| 205 |
+
# DOP853 spends more functions evaluation because it doesn't
|
| 206 |
+
# have enough time to develop big enough step size.
|
| 207 |
+
assert_(res.nfev < 50)
|
| 208 |
+
else:
|
| 209 |
+
assert_(res.nfev < 40)
|
| 210 |
+
|
| 211 |
+
if method in ['RK23', 'RK45', 'DOP853', 'LSODA']:
|
| 212 |
+
assert_equal(res.njev, 0)
|
| 213 |
+
assert_equal(res.nlu, 0)
|
| 214 |
+
else:
|
| 215 |
+
assert_(0 < res.njev < 3)
|
| 216 |
+
assert_(0 < res.nlu < 10)
|
| 217 |
+
|
| 218 |
+
y_true = sol_rational(res.t)
|
| 219 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 220 |
+
assert_(np.all(e < 5))
|
| 221 |
+
|
| 222 |
+
tc = np.linspace(*t_span)
|
| 223 |
+
yc_true = sol_rational(tc)
|
| 224 |
+
yc = res.sol(tc)
|
| 225 |
+
|
| 226 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 227 |
+
assert_(np.all(e < 5))
|
| 228 |
+
|
| 229 |
+
tc = (t_span[0] + t_span[-1]) / 2
|
| 230 |
+
yc_true = sol_rational(tc)
|
| 231 |
+
yc = res.sol(tc)
|
| 232 |
+
|
| 233 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 234 |
+
assert_(np.all(e < 5))
|
| 235 |
+
|
| 236 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@pytest.mark.thread_unsafe
|
| 240 |
+
def test_integration_complex():
|
| 241 |
+
rtol = 1e-3
|
| 242 |
+
atol = 1e-6
|
| 243 |
+
y0 = [0.5 + 1j]
|
| 244 |
+
t_span = [0, 1]
|
| 245 |
+
tc = np.linspace(t_span[0], t_span[1])
|
| 246 |
+
for method, jac in product(['RK23', 'RK45', 'DOP853', 'BDF'],
|
| 247 |
+
[None, jac_complex, jac_complex_sparse]):
|
| 248 |
+
with suppress_warnings() as sup:
|
| 249 |
+
sup.filter(UserWarning,
|
| 250 |
+
"The following arguments have no effect for a chosen "
|
| 251 |
+
"solver: `jac`")
|
| 252 |
+
res = solve_ivp(fun_complex, t_span, y0, method=method,
|
| 253 |
+
dense_output=True, rtol=rtol, atol=atol, jac=jac)
|
| 254 |
+
|
| 255 |
+
assert_equal(res.t[0], t_span[0])
|
| 256 |
+
assert_(res.t_events is None)
|
| 257 |
+
assert_(res.y_events is None)
|
| 258 |
+
assert_(res.success)
|
| 259 |
+
assert_equal(res.status, 0)
|
| 260 |
+
|
| 261 |
+
if method == 'DOP853':
|
| 262 |
+
assert res.nfev < 35
|
| 263 |
+
else:
|
| 264 |
+
assert res.nfev < 25
|
| 265 |
+
|
| 266 |
+
if method == 'BDF':
|
| 267 |
+
assert_equal(res.njev, 1)
|
| 268 |
+
assert res.nlu < 6
|
| 269 |
+
else:
|
| 270 |
+
assert res.njev == 0
|
| 271 |
+
assert res.nlu == 0
|
| 272 |
+
|
| 273 |
+
y_true = sol_complex(res.t)
|
| 274 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 275 |
+
assert np.all(e < 5)
|
| 276 |
+
|
| 277 |
+
yc_true = sol_complex(tc)
|
| 278 |
+
yc = res.sol(tc)
|
| 279 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 280 |
+
|
| 281 |
+
assert np.all(e < 5)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
@pytest.mark.fail_slow(5)
|
| 285 |
+
def test_integration_sparse_difference():
|
| 286 |
+
n = 200
|
| 287 |
+
t_span = [0, 20]
|
| 288 |
+
y0 = np.zeros(2 * n)
|
| 289 |
+
y0[1::2] = 1
|
| 290 |
+
sparsity = medazko_sparsity(n)
|
| 291 |
+
|
| 292 |
+
for method in ['BDF', 'Radau']:
|
| 293 |
+
res = solve_ivp(fun_medazko, t_span, y0, method=method,
|
| 294 |
+
jac_sparsity=sparsity)
|
| 295 |
+
|
| 296 |
+
assert_equal(res.t[0], t_span[0])
|
| 297 |
+
assert_(res.t_events is None)
|
| 298 |
+
assert_(res.y_events is None)
|
| 299 |
+
assert_(res.success)
|
| 300 |
+
assert_equal(res.status, 0)
|
| 301 |
+
|
| 302 |
+
assert_allclose(res.y[78, -1], 0.233994e-3, rtol=1e-2)
|
| 303 |
+
assert_allclose(res.y[79, -1], 0, atol=1e-3)
|
| 304 |
+
assert_allclose(res.y[148, -1], 0.359561e-3, rtol=1e-2)
|
| 305 |
+
assert_allclose(res.y[149, -1], 0, atol=1e-3)
|
| 306 |
+
assert_allclose(res.y[198, -1], 0.117374129e-3, rtol=1e-2)
|
| 307 |
+
assert_allclose(res.y[199, -1], 0.6190807e-5, atol=1e-3)
|
| 308 |
+
assert_allclose(res.y[238, -1], 0, atol=1e-3)
|
| 309 |
+
assert_allclose(res.y[239, -1], 0.9999997, rtol=1e-2)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def test_integration_const_jac():
|
| 313 |
+
rtol = 1e-3
|
| 314 |
+
atol = 1e-6
|
| 315 |
+
y0 = [0, 2]
|
| 316 |
+
t_span = [0, 2]
|
| 317 |
+
J = jac_linear()
|
| 318 |
+
J_sparse = csc_matrix(J)
|
| 319 |
+
|
| 320 |
+
for method, jac in product(['Radau', 'BDF'], [J, J_sparse]):
|
| 321 |
+
res = solve_ivp(fun_linear, t_span, y0, rtol=rtol, atol=atol,
|
| 322 |
+
method=method, dense_output=True, jac=jac)
|
| 323 |
+
assert_equal(res.t[0], t_span[0])
|
| 324 |
+
assert_(res.t_events is None)
|
| 325 |
+
assert_(res.y_events is None)
|
| 326 |
+
assert_(res.success)
|
| 327 |
+
assert_equal(res.status, 0)
|
| 328 |
+
|
| 329 |
+
assert_(res.nfev < 100)
|
| 330 |
+
assert_equal(res.njev, 0)
|
| 331 |
+
assert_(0 < res.nlu < 15)
|
| 332 |
+
|
| 333 |
+
y_true = sol_linear(res.t)
|
| 334 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 335 |
+
assert_(np.all(e < 10))
|
| 336 |
+
|
| 337 |
+
tc = np.linspace(*t_span)
|
| 338 |
+
yc_true = sol_linear(tc)
|
| 339 |
+
yc = res.sol(tc)
|
| 340 |
+
|
| 341 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 342 |
+
assert_(np.all(e < 15))
|
| 343 |
+
|
| 344 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-14, atol=1e-14)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
@pytest.mark.slow
|
| 348 |
+
@pytest.mark.parametrize('method', ['Radau', 'BDF', 'LSODA'])
|
| 349 |
+
def test_integration_stiff(method, num_parallel_threads):
|
| 350 |
+
rtol = 1e-6
|
| 351 |
+
atol = 1e-6
|
| 352 |
+
y0 = [1e4, 0, 0]
|
| 353 |
+
tspan = [0, 1e8]
|
| 354 |
+
|
| 355 |
+
if method == 'LSODA' and num_parallel_threads > 1:
|
| 356 |
+
pytest.skip(reason='LSODA does not allow for concurrent calls')
|
| 357 |
+
|
| 358 |
+
def fun_robertson(t, state):
|
| 359 |
+
x, y, z = state
|
| 360 |
+
return [
|
| 361 |
+
-0.04 * x + 1e4 * y * z,
|
| 362 |
+
0.04 * x - 1e4 * y * z - 3e7 * y * y,
|
| 363 |
+
3e7 * y * y,
|
| 364 |
+
]
|
| 365 |
+
|
| 366 |
+
res = solve_ivp(fun_robertson, tspan, y0, rtol=rtol,
|
| 367 |
+
atol=atol, method=method)
|
| 368 |
+
|
| 369 |
+
# If the stiff mode is not activated correctly, these numbers will be much bigger
|
| 370 |
+
assert res.nfev < 5000
|
| 371 |
+
assert res.njev < 200
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def test_events(num_parallel_threads):
|
| 375 |
+
def event_rational_1(t, y):
|
| 376 |
+
return y[0] - y[1] ** 0.7
|
| 377 |
+
|
| 378 |
+
def event_rational_2(t, y):
|
| 379 |
+
return y[1] ** 0.6 - y[0]
|
| 380 |
+
|
| 381 |
+
def event_rational_3(t, y):
|
| 382 |
+
return t - 7.4
|
| 383 |
+
|
| 384 |
+
event_rational_3.terminal = True
|
| 385 |
+
|
| 386 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
| 387 |
+
if method == 'LSODA' and num_parallel_threads > 1:
|
| 388 |
+
continue
|
| 389 |
+
|
| 390 |
+
res = solve_ivp(fun_rational, [5, 8], [1/3, 2/9], method=method,
|
| 391 |
+
events=(event_rational_1, event_rational_2))
|
| 392 |
+
assert_equal(res.status, 0)
|
| 393 |
+
assert_equal(res.t_events[0].size, 1)
|
| 394 |
+
assert_equal(res.t_events[1].size, 1)
|
| 395 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
| 396 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
| 397 |
+
|
| 398 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
| 399 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
| 400 |
+
assert np.isclose(
|
| 401 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
| 402 |
+
assert np.isclose(
|
| 403 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
| 404 |
+
|
| 405 |
+
event_rational_1.direction = 1
|
| 406 |
+
event_rational_2.direction = 1
|
| 407 |
+
res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
|
| 408 |
+
events=(event_rational_1, event_rational_2))
|
| 409 |
+
assert_equal(res.status, 0)
|
| 410 |
+
assert_equal(res.t_events[0].size, 1)
|
| 411 |
+
assert_equal(res.t_events[1].size, 0)
|
| 412 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
| 413 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
| 414 |
+
assert_equal(res.y_events[1].shape, (0,))
|
| 415 |
+
assert np.isclose(
|
| 416 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
| 417 |
+
|
| 418 |
+
event_rational_1.direction = -1
|
| 419 |
+
event_rational_2.direction = -1
|
| 420 |
+
res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
|
| 421 |
+
events=(event_rational_1, event_rational_2))
|
| 422 |
+
assert_equal(res.status, 0)
|
| 423 |
+
assert_equal(res.t_events[0].size, 0)
|
| 424 |
+
assert_equal(res.t_events[1].size, 1)
|
| 425 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
| 426 |
+
assert_equal(res.y_events[0].shape, (0,))
|
| 427 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
| 428 |
+
assert np.isclose(
|
| 429 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
| 430 |
+
|
| 431 |
+
event_rational_1.direction = 0
|
| 432 |
+
event_rational_2.direction = 0
|
| 433 |
+
|
| 434 |
+
res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
|
| 435 |
+
events=(event_rational_1, event_rational_2,
|
| 436 |
+
event_rational_3), dense_output=True)
|
| 437 |
+
assert_equal(res.status, 1)
|
| 438 |
+
assert_equal(res.t_events[0].size, 1)
|
| 439 |
+
assert_equal(res.t_events[1].size, 0)
|
| 440 |
+
assert_equal(res.t_events[2].size, 1)
|
| 441 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
| 442 |
+
assert_(7.3 < res.t_events[2][0] < 7.5)
|
| 443 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
| 444 |
+
assert_equal(res.y_events[1].shape, (0,))
|
| 445 |
+
assert_equal(res.y_events[2].shape, (1, 2))
|
| 446 |
+
assert np.isclose(
|
| 447 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
| 448 |
+
assert np.isclose(
|
| 449 |
+
event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
|
| 450 |
+
|
| 451 |
+
res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
|
| 452 |
+
events=event_rational_1, dense_output=True)
|
| 453 |
+
assert_equal(res.status, 0)
|
| 454 |
+
assert_equal(res.t_events[0].size, 1)
|
| 455 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
| 456 |
+
|
| 457 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
| 458 |
+
assert np.isclose(
|
| 459 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
| 460 |
+
|
| 461 |
+
# Also test that termination by event doesn't break interpolants.
|
| 462 |
+
tc = np.linspace(res.t[0], res.t[-1])
|
| 463 |
+
yc_true = sol_rational(tc)
|
| 464 |
+
yc = res.sol(tc)
|
| 465 |
+
e = compute_error(yc, yc_true, 1e-3, 1e-6)
|
| 466 |
+
assert_(np.all(e < 5))
|
| 467 |
+
|
| 468 |
+
# Test that the y_event matches solution
|
| 469 |
+
assert np.allclose(sol_rational(res.t_events[0][0]), res.y_events[0][0],
|
| 470 |
+
rtol=1e-3, atol=1e-6)
|
| 471 |
+
|
| 472 |
+
# Test in backward direction.
|
| 473 |
+
event_rational_1.direction = 0
|
| 474 |
+
event_rational_2.direction = 0
|
| 475 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
| 476 |
+
if method == 'LSODA' and num_parallel_threads > 1:
|
| 477 |
+
continue
|
| 478 |
+
|
| 479 |
+
res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
|
| 480 |
+
events=(event_rational_1, event_rational_2))
|
| 481 |
+
assert_equal(res.status, 0)
|
| 482 |
+
assert_equal(res.t_events[0].size, 1)
|
| 483 |
+
assert_equal(res.t_events[1].size, 1)
|
| 484 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
| 485 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
| 486 |
+
|
| 487 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
| 488 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
| 489 |
+
assert np.isclose(
|
| 490 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
| 491 |
+
assert np.isclose(
|
| 492 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
| 493 |
+
|
| 494 |
+
event_rational_1.direction = -1
|
| 495 |
+
event_rational_2.direction = -1
|
| 496 |
+
res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
|
| 497 |
+
events=(event_rational_1, event_rational_2))
|
| 498 |
+
assert_equal(res.status, 0)
|
| 499 |
+
assert_equal(res.t_events[0].size, 1)
|
| 500 |
+
assert_equal(res.t_events[1].size, 0)
|
| 501 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
| 502 |
+
|
| 503 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
| 504 |
+
assert_equal(res.y_events[1].shape, (0,))
|
| 505 |
+
assert np.isclose(
|
| 506 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
| 507 |
+
|
| 508 |
+
event_rational_1.direction = 1
|
| 509 |
+
event_rational_2.direction = 1
|
| 510 |
+
res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
|
| 511 |
+
events=(event_rational_1, event_rational_2))
|
| 512 |
+
assert_equal(res.status, 0)
|
| 513 |
+
assert_equal(res.t_events[0].size, 0)
|
| 514 |
+
assert_equal(res.t_events[1].size, 1)
|
| 515 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
| 516 |
+
|
| 517 |
+
assert_equal(res.y_events[0].shape, (0,))
|
| 518 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
| 519 |
+
assert np.isclose(
|
| 520 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
| 521 |
+
|
| 522 |
+
event_rational_1.direction = 0
|
| 523 |
+
event_rational_2.direction = 0
|
| 524 |
+
|
| 525 |
+
res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
|
| 526 |
+
events=(event_rational_1, event_rational_2,
|
| 527 |
+
event_rational_3), dense_output=True)
|
| 528 |
+
assert_equal(res.status, 1)
|
| 529 |
+
assert_equal(res.t_events[0].size, 0)
|
| 530 |
+
assert_equal(res.t_events[1].size, 1)
|
| 531 |
+
assert_equal(res.t_events[2].size, 1)
|
| 532 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
| 533 |
+
assert_(7.3 < res.t_events[2][0] < 7.5)
|
| 534 |
+
|
| 535 |
+
assert_equal(res.y_events[0].shape, (0,))
|
| 536 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
| 537 |
+
assert_equal(res.y_events[2].shape, (1, 2))
|
| 538 |
+
assert np.isclose(
|
| 539 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
| 540 |
+
assert np.isclose(
|
| 541 |
+
event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
|
| 542 |
+
|
| 543 |
+
# Also test that termination by event doesn't break interpolants.
|
| 544 |
+
tc = np.linspace(res.t[-1], res.t[0])
|
| 545 |
+
yc_true = sol_rational(tc)
|
| 546 |
+
yc = res.sol(tc)
|
| 547 |
+
e = compute_error(yc, yc_true, 1e-3, 1e-6)
|
| 548 |
+
assert_(np.all(e < 5))
|
| 549 |
+
|
| 550 |
+
assert np.allclose(sol_rational(res.t_events[1][0]), res.y_events[1][0],
|
| 551 |
+
rtol=1e-3, atol=1e-6)
|
| 552 |
+
assert np.allclose(sol_rational(res.t_events[2][0]), res.y_events[2][0],
|
| 553 |
+
rtol=1e-3, atol=1e-6)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def _get_harmonic_oscillator():
|
| 557 |
+
def f(t, y):
|
| 558 |
+
return [y[1], -y[0]]
|
| 559 |
+
|
| 560 |
+
def event(t, y):
|
| 561 |
+
return y[0]
|
| 562 |
+
|
| 563 |
+
return f, event
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
@pytest.mark.parametrize('n_events', [3, 4])
|
| 567 |
+
def test_event_terminal_integer(n_events):
|
| 568 |
+
f, event = _get_harmonic_oscillator()
|
| 569 |
+
event.terminal = n_events
|
| 570 |
+
res = solve_ivp(f, (0, 100), [1, 0], events=event)
|
| 571 |
+
assert len(res.t_events[0]) == n_events
|
| 572 |
+
assert len(res.y_events[0]) == n_events
|
| 573 |
+
assert_allclose(res.y_events[0][:, 0], 0, atol=1e-14)
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def test_event_terminal_iv():
|
| 577 |
+
f, event = _get_harmonic_oscillator()
|
| 578 |
+
args = (f, (0, 100), [1, 0])
|
| 579 |
+
|
| 580 |
+
event.terminal = None
|
| 581 |
+
res = solve_ivp(*args, events=event)
|
| 582 |
+
event.terminal = 0
|
| 583 |
+
ref = solve_ivp(*args, events=event)
|
| 584 |
+
assert_allclose(res.t_events, ref.t_events)
|
| 585 |
+
|
| 586 |
+
message = "The `terminal` attribute..."
|
| 587 |
+
event.terminal = -1
|
| 588 |
+
with pytest.raises(ValueError, match=message):
|
| 589 |
+
solve_ivp(*args, events=event)
|
| 590 |
+
event.terminal = 3.5
|
| 591 |
+
with pytest.raises(ValueError, match=message):
|
| 592 |
+
solve_ivp(*args, events=event)
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def test_max_step(num_parallel_threads):
|
| 596 |
+
rtol = 1e-3
|
| 597 |
+
atol = 1e-6
|
| 598 |
+
y0 = [1/3, 2/9]
|
| 599 |
+
for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
|
| 600 |
+
if method is LSODA and num_parallel_threads > 1:
|
| 601 |
+
continue
|
| 602 |
+
for t_span in ([5, 9], [5, 1]):
|
| 603 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
|
| 604 |
+
max_step=0.5, atol=atol, method=method,
|
| 605 |
+
dense_output=True)
|
| 606 |
+
assert_equal(res.t[0], t_span[0])
|
| 607 |
+
assert_equal(res.t[-1], t_span[-1])
|
| 608 |
+
assert_(np.all(np.abs(np.diff(res.t)) <= 0.5 + 1e-15))
|
| 609 |
+
assert_(res.t_events is None)
|
| 610 |
+
assert_(res.success)
|
| 611 |
+
assert_equal(res.status, 0)
|
| 612 |
+
|
| 613 |
+
y_true = sol_rational(res.t)
|
| 614 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 615 |
+
assert_(np.all(e < 5))
|
| 616 |
+
|
| 617 |
+
tc = np.linspace(*t_span)
|
| 618 |
+
yc_true = sol_rational(tc)
|
| 619 |
+
yc = res.sol(tc)
|
| 620 |
+
|
| 621 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 622 |
+
assert_(np.all(e < 5))
|
| 623 |
+
|
| 624 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
|
| 625 |
+
|
| 626 |
+
assert_raises(ValueError, method, fun_rational, t_span[0], y0,
|
| 627 |
+
t_span[1], max_step=-1)
|
| 628 |
+
|
| 629 |
+
if method is not LSODA:
|
| 630 |
+
solver = method(fun_rational, t_span[0], y0, t_span[1],
|
| 631 |
+
rtol=rtol, atol=atol, max_step=1e-20)
|
| 632 |
+
message = solver.step()
|
| 633 |
+
message = solver.step() # First step succeeds but second step fails.
|
| 634 |
+
assert_equal(solver.status, 'failed')
|
| 635 |
+
assert_("step size is less" in message)
|
| 636 |
+
assert_raises(RuntimeError, solver.step)
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def test_first_step(num_parallel_threads):
|
| 640 |
+
rtol = 1e-3
|
| 641 |
+
atol = 1e-6
|
| 642 |
+
y0 = [1/3, 2/9]
|
| 643 |
+
first_step = 0.1
|
| 644 |
+
for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
|
| 645 |
+
if method is LSODA and num_parallel_threads > 1:
|
| 646 |
+
continue
|
| 647 |
+
for t_span in ([5, 9], [5, 1]):
|
| 648 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
|
| 649 |
+
max_step=0.5, atol=atol, method=method,
|
| 650 |
+
dense_output=True, first_step=first_step)
|
| 651 |
+
|
| 652 |
+
assert_equal(res.t[0], t_span[0])
|
| 653 |
+
assert_equal(res.t[-1], t_span[-1])
|
| 654 |
+
assert_allclose(first_step, np.abs(res.t[1] - 5))
|
| 655 |
+
assert_(res.t_events is None)
|
| 656 |
+
assert_(res.success)
|
| 657 |
+
assert_equal(res.status, 0)
|
| 658 |
+
|
| 659 |
+
y_true = sol_rational(res.t)
|
| 660 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 661 |
+
assert_(np.all(e < 5))
|
| 662 |
+
|
| 663 |
+
tc = np.linspace(*t_span)
|
| 664 |
+
yc_true = sol_rational(tc)
|
| 665 |
+
yc = res.sol(tc)
|
| 666 |
+
|
| 667 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 668 |
+
assert_(np.all(e < 5))
|
| 669 |
+
|
| 670 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
|
| 671 |
+
|
| 672 |
+
assert_raises(ValueError, method, fun_rational, t_span[0], y0,
|
| 673 |
+
t_span[1], first_step=-1)
|
| 674 |
+
assert_raises(ValueError, method, fun_rational, t_span[0], y0,
|
| 675 |
+
t_span[1], first_step=5)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def test_t_eval():
|
| 679 |
+
rtol = 1e-3
|
| 680 |
+
atol = 1e-6
|
| 681 |
+
y0 = [1/3, 2/9]
|
| 682 |
+
for t_span in ([5, 9], [5, 1]):
|
| 683 |
+
t_eval = np.linspace(t_span[0], t_span[1], 10)
|
| 684 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
|
| 685 |
+
t_eval=t_eval)
|
| 686 |
+
assert_equal(res.t, t_eval)
|
| 687 |
+
assert_(res.t_events is None)
|
| 688 |
+
assert_(res.success)
|
| 689 |
+
assert_equal(res.status, 0)
|
| 690 |
+
|
| 691 |
+
y_true = sol_rational(res.t)
|
| 692 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 693 |
+
assert_(np.all(e < 5))
|
| 694 |
+
|
| 695 |
+
t_eval = [5, 5.01, 7, 8, 8.01, 9]
|
| 696 |
+
res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
|
| 697 |
+
t_eval=t_eval)
|
| 698 |
+
assert_equal(res.t, t_eval)
|
| 699 |
+
assert_(res.t_events is None)
|
| 700 |
+
assert_(res.success)
|
| 701 |
+
assert_equal(res.status, 0)
|
| 702 |
+
|
| 703 |
+
y_true = sol_rational(res.t)
|
| 704 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 705 |
+
assert_(np.all(e < 5))
|
| 706 |
+
|
| 707 |
+
t_eval = [5, 4.99, 3, 1.5, 1.1, 1.01, 1]
|
| 708 |
+
res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
|
| 709 |
+
t_eval=t_eval)
|
| 710 |
+
assert_equal(res.t, t_eval)
|
| 711 |
+
assert_(res.t_events is None)
|
| 712 |
+
assert_(res.success)
|
| 713 |
+
assert_equal(res.status, 0)
|
| 714 |
+
|
| 715 |
+
t_eval = [5.01, 7, 8, 8.01]
|
| 716 |
+
res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
|
| 717 |
+
t_eval=t_eval)
|
| 718 |
+
assert_equal(res.t, t_eval)
|
| 719 |
+
assert_(res.t_events is None)
|
| 720 |
+
assert_(res.success)
|
| 721 |
+
assert_equal(res.status, 0)
|
| 722 |
+
|
| 723 |
+
y_true = sol_rational(res.t)
|
| 724 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 725 |
+
assert_(np.all(e < 5))
|
| 726 |
+
|
| 727 |
+
t_eval = [4.99, 3, 1.5, 1.1, 1.01]
|
| 728 |
+
res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
|
| 729 |
+
t_eval=t_eval)
|
| 730 |
+
assert_equal(res.t, t_eval)
|
| 731 |
+
assert_(res.t_events is None)
|
| 732 |
+
assert_(res.success)
|
| 733 |
+
assert_equal(res.status, 0)
|
| 734 |
+
|
| 735 |
+
t_eval = [4, 6]
|
| 736 |
+
assert_raises(ValueError, solve_ivp, fun_rational, [5, 9], y0,
|
| 737 |
+
rtol=rtol, atol=atol, t_eval=t_eval)
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
def test_t_eval_dense_output():
|
| 741 |
+
rtol = 1e-3
|
| 742 |
+
atol = 1e-6
|
| 743 |
+
y0 = [1/3, 2/9]
|
| 744 |
+
t_span = [5, 9]
|
| 745 |
+
t_eval = np.linspace(t_span[0], t_span[1], 10)
|
| 746 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
|
| 747 |
+
t_eval=t_eval)
|
| 748 |
+
res_d = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
|
| 749 |
+
t_eval=t_eval, dense_output=True)
|
| 750 |
+
assert_equal(res.t, t_eval)
|
| 751 |
+
assert_(res.t_events is None)
|
| 752 |
+
assert_(res.success)
|
| 753 |
+
assert_equal(res.status, 0)
|
| 754 |
+
|
| 755 |
+
assert_equal(res.t, res_d.t)
|
| 756 |
+
assert_equal(res.y, res_d.y)
|
| 757 |
+
assert_(res_d.t_events is None)
|
| 758 |
+
assert_(res_d.success)
|
| 759 |
+
assert_equal(res_d.status, 0)
|
| 760 |
+
|
| 761 |
+
# if t and y are equal only test values for one case
|
| 762 |
+
y_true = sol_rational(res.t)
|
| 763 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 764 |
+
assert_(np.all(e < 5))
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
@pytest.mark.thread_unsafe
|
| 768 |
+
def test_t_eval_early_event():
|
| 769 |
+
def early_event(t, y):
|
| 770 |
+
return t - 7
|
| 771 |
+
|
| 772 |
+
early_event.terminal = True
|
| 773 |
+
|
| 774 |
+
rtol = 1e-3
|
| 775 |
+
atol = 1e-6
|
| 776 |
+
y0 = [1/3, 2/9]
|
| 777 |
+
t_span = [5, 9]
|
| 778 |
+
t_eval = np.linspace(7.5, 9, 16)
|
| 779 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
| 780 |
+
with suppress_warnings() as sup:
|
| 781 |
+
sup.filter(UserWarning,
|
| 782 |
+
"The following arguments have no effect for a chosen "
|
| 783 |
+
"solver: `jac`")
|
| 784 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
|
| 785 |
+
method=method, t_eval=t_eval, events=early_event,
|
| 786 |
+
jac=jac_rational)
|
| 787 |
+
assert res.success
|
| 788 |
+
assert res.message == 'A termination event occurred.'
|
| 789 |
+
assert res.status == 1
|
| 790 |
+
assert not res.t and not res.y
|
| 791 |
+
assert len(res.t_events) == 1
|
| 792 |
+
assert res.t_events[0].size == 1
|
| 793 |
+
assert res.t_events[0][0] == 7
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
def test_event_dense_output_LSODA(num_parallel_threads):
|
| 797 |
+
if num_parallel_threads > 1:
|
| 798 |
+
pytest.skip('LSODA does not allow for concurrent execution')
|
| 799 |
+
|
| 800 |
+
def event_lsoda(t, y):
|
| 801 |
+
return y[0] - 2.02e-5
|
| 802 |
+
|
| 803 |
+
rtol = 1e-3
|
| 804 |
+
atol = 1e-6
|
| 805 |
+
y0 = [0.05]
|
| 806 |
+
t_span = [-2, 2]
|
| 807 |
+
first_step = 1e-3
|
| 808 |
+
res = solve_ivp(
|
| 809 |
+
fun_event_dense_output_LSODA,
|
| 810 |
+
t_span,
|
| 811 |
+
y0,
|
| 812 |
+
method="LSODA",
|
| 813 |
+
dense_output=True,
|
| 814 |
+
events=event_lsoda,
|
| 815 |
+
first_step=first_step,
|
| 816 |
+
max_step=1,
|
| 817 |
+
rtol=rtol,
|
| 818 |
+
atol=atol,
|
| 819 |
+
jac=jac_event_dense_output_LSODA,
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
assert_equal(res.t[0], t_span[0])
|
| 823 |
+
assert_equal(res.t[-1], t_span[-1])
|
| 824 |
+
assert_allclose(first_step, np.abs(res.t[1] - t_span[0]))
|
| 825 |
+
assert res.success
|
| 826 |
+
assert_equal(res.status, 0)
|
| 827 |
+
|
| 828 |
+
y_true = sol_event_dense_output_LSODA(res.t)
|
| 829 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 830 |
+
assert_array_less(e, 5)
|
| 831 |
+
|
| 832 |
+
tc = np.linspace(*t_span)
|
| 833 |
+
yc_true = sol_event_dense_output_LSODA(tc)
|
| 834 |
+
yc = res.sol(tc)
|
| 835 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 836 |
+
assert_array_less(e, 5)
|
| 837 |
+
|
| 838 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
|
| 839 |
+
|
| 840 |
+
|
| 841 |
+
def test_no_integration():
|
| 842 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
| 843 |
+
sol = solve_ivp(lambda t, y: -y, [4, 4], [2, 3],
|
| 844 |
+
method=method, dense_output=True)
|
| 845 |
+
assert_equal(sol.sol(4), [2, 3])
|
| 846 |
+
assert_equal(sol.sol([4, 5, 6]), [[2, 2, 2], [3, 3, 3]])
|
| 847 |
+
|
| 848 |
+
|
| 849 |
+
def test_no_integration_class():
|
| 850 |
+
for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
|
| 851 |
+
solver = method(lambda t, y: -y, 0.0, [10.0, 0.0], 0.0)
|
| 852 |
+
solver.step()
|
| 853 |
+
assert_equal(solver.status, 'finished')
|
| 854 |
+
sol = solver.dense_output()
|
| 855 |
+
assert_equal(sol(0.0), [10.0, 0.0])
|
| 856 |
+
assert_equal(sol([0, 1, 2]), [[10, 10, 10], [0, 0, 0]])
|
| 857 |
+
|
| 858 |
+
solver = method(lambda t, y: -y, 0.0, [], np.inf)
|
| 859 |
+
solver.step()
|
| 860 |
+
assert_equal(solver.status, 'finished')
|
| 861 |
+
sol = solver.dense_output()
|
| 862 |
+
assert_equal(sol(100.0), [])
|
| 863 |
+
assert_equal(sol([0, 1, 2]), np.empty((0, 3)))
|
| 864 |
+
|
| 865 |
+
|
| 866 |
+
def test_empty():
|
| 867 |
+
def fun(t, y):
|
| 868 |
+
return np.zeros((0,))
|
| 869 |
+
|
| 870 |
+
y0 = np.zeros((0,))
|
| 871 |
+
|
| 872 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
| 873 |
+
sol = assert_no_warnings(solve_ivp, fun, [0, 10], y0,
|
| 874 |
+
method=method, dense_output=True)
|
| 875 |
+
assert_equal(sol.sol(10), np.zeros((0,)))
|
| 876 |
+
assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
|
| 877 |
+
|
| 878 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
| 879 |
+
sol = assert_no_warnings(solve_ivp, fun, [0, np.inf], y0,
|
| 880 |
+
method=method, dense_output=True)
|
| 881 |
+
assert_equal(sol.sol(10), np.zeros((0,)))
|
| 882 |
+
assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
|
| 883 |
+
|
| 884 |
+
|
| 885 |
+
def test_ConstantDenseOutput():
|
| 886 |
+
sol = ConstantDenseOutput(0, 1, np.array([1, 2]))
|
| 887 |
+
assert_allclose(sol(1.5), [1, 2])
|
| 888 |
+
assert_allclose(sol([1, 1.5, 2]), [[1, 1, 1], [2, 2, 2]])
|
| 889 |
+
|
| 890 |
+
sol = ConstantDenseOutput(0, 1, np.array([]))
|
| 891 |
+
assert_allclose(sol(1.5), np.empty(0))
|
| 892 |
+
assert_allclose(sol([1, 1.5, 2]), np.empty((0, 3)))
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
def test_classes():
|
| 896 |
+
y0 = [1 / 3, 2 / 9]
|
| 897 |
+
for cls in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
|
| 898 |
+
solver = cls(fun_rational, 5, y0, np.inf)
|
| 899 |
+
assert_equal(solver.n, 2)
|
| 900 |
+
assert_equal(solver.status, 'running')
|
| 901 |
+
assert_equal(solver.t_bound, np.inf)
|
| 902 |
+
assert_equal(solver.direction, 1)
|
| 903 |
+
assert_equal(solver.t, 5)
|
| 904 |
+
assert_equal(solver.y, y0)
|
| 905 |
+
assert_(solver.step_size is None)
|
| 906 |
+
if cls is not LSODA:
|
| 907 |
+
assert_(solver.nfev > 0)
|
| 908 |
+
assert_(solver.njev >= 0)
|
| 909 |
+
assert_equal(solver.nlu, 0)
|
| 910 |
+
else:
|
| 911 |
+
assert_equal(solver.nfev, 0)
|
| 912 |
+
assert_equal(solver.njev, 0)
|
| 913 |
+
assert_equal(solver.nlu, 0)
|
| 914 |
+
|
| 915 |
+
assert_raises(RuntimeError, solver.dense_output)
|
| 916 |
+
|
| 917 |
+
message = solver.step()
|
| 918 |
+
assert_equal(solver.status, 'running')
|
| 919 |
+
assert_equal(message, None)
|
| 920 |
+
assert_equal(solver.n, 2)
|
| 921 |
+
assert_equal(solver.t_bound, np.inf)
|
| 922 |
+
assert_equal(solver.direction, 1)
|
| 923 |
+
assert_(solver.t > 5)
|
| 924 |
+
assert_(not np.all(np.equal(solver.y, y0)))
|
| 925 |
+
assert_(solver.step_size > 0)
|
| 926 |
+
assert_(solver.nfev > 0)
|
| 927 |
+
assert_(solver.njev >= 0)
|
| 928 |
+
assert_(solver.nlu >= 0)
|
| 929 |
+
sol = solver.dense_output()
|
| 930 |
+
assert_allclose(sol(5), y0, rtol=1e-15, atol=0)
|
| 931 |
+
|
| 932 |
+
|
| 933 |
+
def test_OdeSolution():
|
| 934 |
+
ts = np.array([0, 2, 5], dtype=float)
|
| 935 |
+
s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
|
| 936 |
+
s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
|
| 937 |
+
|
| 938 |
+
sol = OdeSolution(ts, [s1, s2])
|
| 939 |
+
|
| 940 |
+
assert_equal(sol(-1), [-1])
|
| 941 |
+
assert_equal(sol(1), [-1])
|
| 942 |
+
assert_equal(sol(2), [-1])
|
| 943 |
+
assert_equal(sol(3), [1])
|
| 944 |
+
assert_equal(sol(5), [1])
|
| 945 |
+
assert_equal(sol(6), [1])
|
| 946 |
+
|
| 947 |
+
assert_equal(sol([0, 6, -2, 1.5, 4.5, 2.5, 5, 5.5, 2]),
|
| 948 |
+
np.array([[-1, 1, -1, -1, 1, 1, 1, 1, -1]]))
|
| 949 |
+
|
| 950 |
+
ts = np.array([10, 4, -3])
|
| 951 |
+
s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
|
| 952 |
+
s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
|
| 953 |
+
|
| 954 |
+
sol = OdeSolution(ts, [s1, s2])
|
| 955 |
+
assert_equal(sol(11), [-1])
|
| 956 |
+
assert_equal(sol(10), [-1])
|
| 957 |
+
assert_equal(sol(5), [-1])
|
| 958 |
+
assert_equal(sol(4), [-1])
|
| 959 |
+
assert_equal(sol(0), [1])
|
| 960 |
+
assert_equal(sol(-3), [1])
|
| 961 |
+
assert_equal(sol(-4), [1])
|
| 962 |
+
|
| 963 |
+
assert_equal(sol([12, -5, 10, -3, 6, 1, 4]),
|
| 964 |
+
np.array([[-1, 1, -1, 1, -1, 1, -1]]))
|
| 965 |
+
|
| 966 |
+
ts = np.array([1, 1])
|
| 967 |
+
s = ConstantDenseOutput(1, 1, np.array([10]))
|
| 968 |
+
sol = OdeSolution(ts, [s])
|
| 969 |
+
assert_equal(sol(0), [10])
|
| 970 |
+
assert_equal(sol(1), [10])
|
| 971 |
+
assert_equal(sol(2), [10])
|
| 972 |
+
|
| 973 |
+
assert_equal(sol([2, 1, 0]), np.array([[10, 10, 10]]))
|
| 974 |
+
|
| 975 |
+
|
| 976 |
+
def test_num_jac():
|
| 977 |
+
def fun(t, y):
|
| 978 |
+
return np.vstack([
|
| 979 |
+
-0.04 * y[0] + 1e4 * y[1] * y[2],
|
| 980 |
+
0.04 * y[0] - 1e4 * y[1] * y[2] - 3e7 * y[1] ** 2,
|
| 981 |
+
3e7 * y[1] ** 2
|
| 982 |
+
])
|
| 983 |
+
|
| 984 |
+
def jac(t, y):
|
| 985 |
+
return np.array([
|
| 986 |
+
[-0.04, 1e4 * y[2], 1e4 * y[1]],
|
| 987 |
+
[0.04, -1e4 * y[2] - 6e7 * y[1], -1e4 * y[1]],
|
| 988 |
+
[0, 6e7 * y[1], 0]
|
| 989 |
+
])
|
| 990 |
+
|
| 991 |
+
t = 1
|
| 992 |
+
y = np.array([1, 0, 0])
|
| 993 |
+
J_true = jac(t, y)
|
| 994 |
+
threshold = 1e-5
|
| 995 |
+
f = fun(t, y).ravel()
|
| 996 |
+
|
| 997 |
+
J_num, factor = num_jac(fun, t, y, f, threshold, None)
|
| 998 |
+
assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
|
| 999 |
+
|
| 1000 |
+
J_num, factor = num_jac(fun, t, y, f, threshold, factor)
|
| 1001 |
+
assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
def test_num_jac_sparse():
|
| 1005 |
+
def fun(t, y):
|
| 1006 |
+
e = y[1:]**3 - y[:-1]**2
|
| 1007 |
+
z = np.zeros(y.shape[1])
|
| 1008 |
+
return np.vstack((z, 3 * e)) + np.vstack((2 * e, z))
|
| 1009 |
+
|
| 1010 |
+
def structure(n):
|
| 1011 |
+
A = np.zeros((n, n), dtype=int)
|
| 1012 |
+
A[0, 0] = 1
|
| 1013 |
+
A[0, 1] = 1
|
| 1014 |
+
for i in range(1, n - 1):
|
| 1015 |
+
A[i, i - 1: i + 2] = 1
|
| 1016 |
+
A[-1, -1] = 1
|
| 1017 |
+
A[-1, -2] = 1
|
| 1018 |
+
|
| 1019 |
+
return A
|
| 1020 |
+
|
| 1021 |
+
np.random.seed(0)
|
| 1022 |
+
n = 20
|
| 1023 |
+
y = np.random.randn(n)
|
| 1024 |
+
A = structure(n)
|
| 1025 |
+
groups = group_columns(A)
|
| 1026 |
+
|
| 1027 |
+
f = fun(0, y[:, None]).ravel()
|
| 1028 |
+
|
| 1029 |
+
# Compare dense and sparse results, assuming that dense implementation
|
| 1030 |
+
# is correct (as it is straightforward).
|
| 1031 |
+
J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, None,
|
| 1032 |
+
sparsity=(A, groups))
|
| 1033 |
+
J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, None)
|
| 1034 |
+
assert_allclose(J_num_dense, J_num_sparse.toarray(),
|
| 1035 |
+
rtol=1e-12, atol=1e-14)
|
| 1036 |
+
assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
|
| 1037 |
+
|
| 1038 |
+
# Take small factors to trigger their recomputing inside.
|
| 1039 |
+
factor = np.random.uniform(0, 1e-12, size=n)
|
| 1040 |
+
J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, factor,
|
| 1041 |
+
sparsity=(A, groups))
|
| 1042 |
+
J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, factor)
|
| 1043 |
+
|
| 1044 |
+
assert_allclose(J_num_dense, J_num_sparse.toarray(),
|
| 1045 |
+
rtol=1e-12, atol=1e-14)
|
| 1046 |
+
assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
|
| 1047 |
+
|
| 1048 |
+
|
| 1049 |
+
def test_args():
|
| 1050 |
+
|
| 1051 |
+
# sys3 is actually two decoupled systems. (x, y) form a
|
| 1052 |
+
# linear oscillator, while z is a nonlinear first order
|
| 1053 |
+
# system with equilibria at z=0 and z=1. If k > 0, z=1
|
| 1054 |
+
# is stable and z=0 is unstable.
|
| 1055 |
+
|
| 1056 |
+
def sys3(t, w, omega, k, zfinal):
|
| 1057 |
+
x, y, z = w
|
| 1058 |
+
return [-omega*y, omega*x, k*z*(1 - z)]
|
| 1059 |
+
|
| 1060 |
+
def sys3_jac(t, w, omega, k, zfinal):
|
| 1061 |
+
x, y, z = w
|
| 1062 |
+
J = np.array([[0, -omega, 0],
|
| 1063 |
+
[omega, 0, 0],
|
| 1064 |
+
[0, 0, k*(1 - 2*z)]])
|
| 1065 |
+
return J
|
| 1066 |
+
|
| 1067 |
+
def sys3_x0decreasing(t, w, omega, k, zfinal):
|
| 1068 |
+
x, y, z = w
|
| 1069 |
+
return x
|
| 1070 |
+
|
| 1071 |
+
def sys3_y0increasing(t, w, omega, k, zfinal):
|
| 1072 |
+
x, y, z = w
|
| 1073 |
+
return y
|
| 1074 |
+
|
| 1075 |
+
def sys3_zfinal(t, w, omega, k, zfinal):
|
| 1076 |
+
x, y, z = w
|
| 1077 |
+
return z - zfinal
|
| 1078 |
+
|
| 1079 |
+
# Set the event flags for the event functions.
|
| 1080 |
+
sys3_x0decreasing.direction = -1
|
| 1081 |
+
sys3_y0increasing.direction = 1
|
| 1082 |
+
sys3_zfinal.terminal = True
|
| 1083 |
+
|
| 1084 |
+
omega = 2
|
| 1085 |
+
k = 4
|
| 1086 |
+
|
| 1087 |
+
tfinal = 5
|
| 1088 |
+
zfinal = 0.99
|
| 1089 |
+
# Find z0 such that when z(0) = z0, z(tfinal) = zfinal.
|
| 1090 |
+
# The condition z(tfinal) = zfinal is the terminal event.
|
| 1091 |
+
z0 = np.exp(-k*tfinal)/((1 - zfinal)/zfinal + np.exp(-k*tfinal))
|
| 1092 |
+
|
| 1093 |
+
w0 = [0, -1, z0]
|
| 1094 |
+
|
| 1095 |
+
# Provide the jac argument and use the Radau method to ensure that the use
|
| 1096 |
+
# of the Jacobian function is exercised.
|
| 1097 |
+
# If event handling is working, the solution will stop at tfinal, not tend.
|
| 1098 |
+
tend = 2*tfinal
|
| 1099 |
+
sol = solve_ivp(sys3, [0, tend], w0,
|
| 1100 |
+
events=[sys3_x0decreasing, sys3_y0increasing, sys3_zfinal],
|
| 1101 |
+
dense_output=True, args=(omega, k, zfinal),
|
| 1102 |
+
method='Radau', jac=sys3_jac,
|
| 1103 |
+
rtol=1e-10, atol=1e-13)
|
| 1104 |
+
|
| 1105 |
+
# Check that we got the expected events at the expected times.
|
| 1106 |
+
x0events_t = sol.t_events[0]
|
| 1107 |
+
y0events_t = sol.t_events[1]
|
| 1108 |
+
zfinalevents_t = sol.t_events[2]
|
| 1109 |
+
assert_allclose(x0events_t, [0.5*np.pi, 1.5*np.pi])
|
| 1110 |
+
assert_allclose(y0events_t, [0.25*np.pi, 1.25*np.pi])
|
| 1111 |
+
assert_allclose(zfinalevents_t, [tfinal])
|
| 1112 |
+
|
| 1113 |
+
# Check that the solution agrees with the known exact solution.
|
| 1114 |
+
t = np.linspace(0, zfinalevents_t[0], 250)
|
| 1115 |
+
w = sol.sol(t)
|
| 1116 |
+
assert_allclose(w[0], np.sin(omega*t), rtol=1e-9, atol=1e-12)
|
| 1117 |
+
assert_allclose(w[1], -np.cos(omega*t), rtol=1e-9, atol=1e-12)
|
| 1118 |
+
assert_allclose(w[2], 1/(((1 - z0)/z0)*np.exp(-k*t) + 1),
|
| 1119 |
+
rtol=1e-9, atol=1e-12)
|
| 1120 |
+
|
| 1121 |
+
# Check that the state variables have the expected values at the events.
|
| 1122 |
+
x0events = sol.sol(x0events_t)
|
| 1123 |
+
y0events = sol.sol(y0events_t)
|
| 1124 |
+
zfinalevents = sol.sol(zfinalevents_t)
|
| 1125 |
+
assert_allclose(x0events[0], np.zeros_like(x0events[0]), atol=5e-14)
|
| 1126 |
+
assert_allclose(x0events[1], np.ones_like(x0events[1]))
|
| 1127 |
+
assert_allclose(y0events[0], np.ones_like(y0events[0]))
|
| 1128 |
+
assert_allclose(y0events[1], np.zeros_like(y0events[1]), atol=5e-14)
|
| 1129 |
+
assert_allclose(zfinalevents[2], [zfinal])
|
| 1130 |
+
|
| 1131 |
+
|
| 1132 |
+
@pytest.mark.thread_unsafe
|
| 1133 |
+
def test_array_rtol():
|
| 1134 |
+
# solve_ivp had a bug with array_like `rtol`; see gh-15482
|
| 1135 |
+
# check that it's fixed
|
| 1136 |
+
def f(t, y):
|
| 1137 |
+
return y[0], y[1]
|
| 1138 |
+
|
| 1139 |
+
# no warning (or error) when `rtol` is array_like
|
| 1140 |
+
sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-1])
|
| 1141 |
+
err1 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
|
| 1142 |
+
|
| 1143 |
+
# warning when an element of `rtol` is too small
|
| 1144 |
+
with pytest.warns(UserWarning, match="At least one element..."):
|
| 1145 |
+
sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-16])
|
| 1146 |
+
err2 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
|
| 1147 |
+
|
| 1148 |
+
# tighter rtol improves the error
|
| 1149 |
+
assert err2 < err1
|
| 1150 |
+
|
| 1151 |
+
|
| 1152 |
+
@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'])
|
| 1153 |
+
def test_integration_zero_rhs(method, num_parallel_threads):
|
| 1154 |
+
if method == 'LSODA' and num_parallel_threads > 1:
|
| 1155 |
+
pytest.skip(reason='LSODA does not allow for concurrent execution')
|
| 1156 |
+
|
| 1157 |
+
result = solve_ivp(fun_zero, [0, 10], np.ones(3), method=method)
|
| 1158 |
+
assert_(result.success)
|
| 1159 |
+
assert_equal(result.status, 0)
|
| 1160 |
+
assert_allclose(result.y, 1.0, rtol=1e-15)
|
| 1161 |
+
|
| 1162 |
+
|
| 1163 |
+
def test_args_single_value():
|
| 1164 |
+
def fun_with_arg(t, y, a):
|
| 1165 |
+
return a*y
|
| 1166 |
+
|
| 1167 |
+
message = "Supplied 'args' cannot be unpacked."
|
| 1168 |
+
with pytest.raises(TypeError, match=message):
|
| 1169 |
+
solve_ivp(fun_with_arg, (0, 0.1), [1], args=-1)
|
| 1170 |
+
|
| 1171 |
+
sol = solve_ivp(fun_with_arg, (0, 0.1), [1], args=(-1,))
|
| 1172 |
+
assert_allclose(sol.y[0, -1], np.exp(-0.1))
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
@pytest.mark.parametrize("f0_fill", [np.nan, np.inf])
|
| 1176 |
+
def test_initial_state_finiteness(f0_fill):
|
| 1177 |
+
# regression test for gh-17846
|
| 1178 |
+
msg = "All components of the initial state `y0` must be finite."
|
| 1179 |
+
with pytest.raises(ValueError, match=msg):
|
| 1180 |
+
solve_ivp(fun_zero, [0, 10], np.full(3, f0_fill))
|
| 1181 |
+
|
| 1182 |
+
|
| 1183 |
+
@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
|
| 1184 |
+
def test_zero_interval(method):
|
| 1185 |
+
# Case where upper and lower limits of integration are the same
|
| 1186 |
+
# Result of integration should match initial state.
|
| 1187 |
+
# f[y(t)] = 2y(t)
|
| 1188 |
+
def f(t, y):
|
| 1189 |
+
return 2 * y
|
| 1190 |
+
res = solve_ivp(f, (0.0, 0.0), np.array([1.0]), method=method)
|
| 1191 |
+
assert res.success
|
| 1192 |
+
assert_allclose(res.y[0, -1], 1.0)
|
| 1193 |
+
|
| 1194 |
+
|
| 1195 |
+
@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
|
| 1196 |
+
def test_tbound_respected_small_interval(method):
|
| 1197 |
+
"""Regression test for gh-17341"""
|
| 1198 |
+
SMALL = 1e-4
|
| 1199 |
+
|
| 1200 |
+
# f[y(t)] = 2y(t) on t in [0,SMALL]
|
| 1201 |
+
# undefined otherwise
|
| 1202 |
+
def f(t, y):
|
| 1203 |
+
if t > SMALL:
|
| 1204 |
+
raise ValueError("Function was evaluated outside interval")
|
| 1205 |
+
return 2 * y
|
| 1206 |
+
res = solve_ivp(f, (0.0, SMALL), np.array([1]), method=method)
|
| 1207 |
+
assert res.success
|
| 1208 |
+
|
| 1209 |
+
|
| 1210 |
+
@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
|
| 1211 |
+
def test_tbound_respected_larger_interval(method):
|
| 1212 |
+
"""Regression test for gh-8848"""
|
| 1213 |
+
def V(r):
|
| 1214 |
+
return -11/r + 10 * r / (0.05 + r**2)
|
| 1215 |
+
|
| 1216 |
+
def func(t, p):
|
| 1217 |
+
if t < -17 or t > 2:
|
| 1218 |
+
raise ValueError("Function was evaluated outside interval")
|
| 1219 |
+
P = p[0]
|
| 1220 |
+
Q = p[1]
|
| 1221 |
+
r = np.exp(t)
|
| 1222 |
+
dPdr = r * Q
|
| 1223 |
+
dQdr = -2.0 * r * ((-0.2 - V(r)) * P + 1 / r * Q)
|
| 1224 |
+
return np.array([dPdr, dQdr])
|
| 1225 |
+
|
| 1226 |
+
result = solve_ivp(func,
|
| 1227 |
+
(-17, 2),
|
| 1228 |
+
y0=np.array([1, -11]),
|
| 1229 |
+
max_step=0.03,
|
| 1230 |
+
vectorized=False,
|
| 1231 |
+
t_eval=None,
|
| 1232 |
+
atol=1e-8,
|
| 1233 |
+
rtol=1e-5)
|
| 1234 |
+
assert result.success
|
| 1235 |
+
|
| 1236 |
+
|
| 1237 |
+
@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
|
| 1238 |
+
def test_tbound_respected_oscillator(method):
|
| 1239 |
+
"Regression test for gh-9198"
|
| 1240 |
+
def reactions_func(t, y):
|
| 1241 |
+
if (t > 205):
|
| 1242 |
+
raise ValueError("Called outside interval")
|
| 1243 |
+
yprime = np.array([1.73307544e-02,
|
| 1244 |
+
6.49376470e-06,
|
| 1245 |
+
0.00000000e+00,
|
| 1246 |
+
0.00000000e+00])
|
| 1247 |
+
return yprime
|
| 1248 |
+
|
| 1249 |
+
def run_sim2(t_end, n_timepoints=10, shortest_delay_line=10000000):
|
| 1250 |
+
init_state = np.array([134.08298555, 138.82348612, 100., 0.])
|
| 1251 |
+
t0 = 100.0
|
| 1252 |
+
t1 = 200.0
|
| 1253 |
+
return solve_ivp(reactions_func,
|
| 1254 |
+
(t0, t1),
|
| 1255 |
+
init_state.copy(),
|
| 1256 |
+
dense_output=True,
|
| 1257 |
+
max_step=t1 - t0)
|
| 1258 |
+
result = run_sim2(1000, 100, 100)
|
| 1259 |
+
assert result.success
|
| 1260 |
+
|
| 1261 |
+
|
| 1262 |
+
def test_inital_maxstep():
|
| 1263 |
+
"""Verify that select_inital_step respects max_step"""
|
| 1264 |
+
rtol = 1e-3
|
| 1265 |
+
atol = 1e-6
|
| 1266 |
+
y0 = np.array([1/3, 2/9])
|
| 1267 |
+
for (t0, t_bound) in ((5, 9), (5, 1)):
|
| 1268 |
+
for method_order in [RK23.error_estimator_order,
|
| 1269 |
+
RK45.error_estimator_order,
|
| 1270 |
+
DOP853.error_estimator_order,
|
| 1271 |
+
3, #RADAU
|
| 1272 |
+
1 #BDF
|
| 1273 |
+
]:
|
| 1274 |
+
step_no_max = select_initial_step(fun_rational, t0, y0, t_bound,
|
| 1275 |
+
np.inf,
|
| 1276 |
+
fun_rational(t0,y0),
|
| 1277 |
+
np.sign(t_bound - t0),
|
| 1278 |
+
method_order,
|
| 1279 |
+
rtol, atol)
|
| 1280 |
+
max_step = step_no_max/2
|
| 1281 |
+
step_with_max = select_initial_step(fun_rational, t0, y0, t_bound,
|
| 1282 |
+
max_step,
|
| 1283 |
+
fun_rational(t0, y0),
|
| 1284 |
+
np.sign(t_bound - t0),
|
| 1285 |
+
method_order,
|
| 1286 |
+
rtol, atol)
|
| 1287 |
+
assert_equal(max_step, step_with_max)
|
shared/package-files/03/034b10af10c15474b243ef2bbb72f5d613177f7abd815b81f71fd88076f847d3/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Benchmarks for validation.
|
| 3 |
+
|
| 4 |
+
This package is *not* public API.
|
| 5 |
+
"""
|
shared/package-files/03/034b861abd5808226ebe75c2ac69282fc3f7c48135e403636e17c53d7a7f9e6a/_cudnn_init_dropout_state.h
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/_cudnn_init_dropout_state_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::_cudnn_init_dropout_state(float dropout, bool train, int dropout_seed, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
|
| 26 |
+
inline at::Tensor _cudnn_init_dropout_state(double dropout, bool train, int64_t dropout_seed, at::TensorOptions options) {
|
| 27 |
+
return at::_ops::_cudnn_init_dropout_state::call(dropout, train, dropout_seed, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt());
|
| 28 |
+
}
|
| 29 |
+
// aten::_cudnn_init_dropout_state(float dropout, bool train, int dropout_seed, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
|
| 30 |
+
inline at::Tensor _cudnn_init_dropout_state(double dropout, bool train, int64_t dropout_seed, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory) {
|
| 31 |
+
return at::_ops::_cudnn_init_dropout_state::call(dropout, train, dropout_seed, dtype, layout, device, pin_memory);
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
// aten::_cudnn_init_dropout_state.out(float dropout, bool train, int dropout_seed, *, Tensor(a!) out) -> Tensor(a!)
|
| 35 |
+
inline at::Tensor & _cudnn_init_dropout_state_out(at::Tensor & out, double dropout, bool train, int64_t dropout_seed) {
|
| 36 |
+
return at::_ops::_cudnn_init_dropout_state_out::call(dropout, train, dropout_seed, out);
|
| 37 |
+
}
|
| 38 |
+
// aten::_cudnn_init_dropout_state.out(float dropout, bool train, int dropout_seed, *, Tensor(a!) out) -> Tensor(a!)
|
| 39 |
+
inline at::Tensor & _cudnn_init_dropout_state_outf(double dropout, bool train, int64_t dropout_seed, at::Tensor & out) {
|
| 40 |
+
return at::_ops::_cudnn_init_dropout_state_out::call(dropout, train, dropout_seed, out);
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
}
|
shared/package-files/03/034e916d6a62449e09e22e7f4a60e7f23f2659d3dd1a2a0a6521f540d623d9f0/is_floating_point_compositeimplicitautograd_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 compositeimplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API bool is_floating_point(const at::Tensor & self);
|
| 21 |
+
|
| 22 |
+
} // namespace compositeimplicitautograd
|
| 23 |
+
} // namespace at
|
shared/package-files/03/0351667ed3afd3310ebd353526824d6f6f34d641ef0a785552c6893b7f95fdf3/heapq.py
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Heap queue algorithm (a.k.a. priority queue).
|
| 2 |
+
|
| 3 |
+
Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
|
| 4 |
+
all k, counting elements from 0. For the sake of comparison,
|
| 5 |
+
non-existing elements are considered to be infinite. The interesting
|
| 6 |
+
property of a heap is that a[0] is always its smallest element.
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
|
| 10 |
+
heap = [] # creates an empty heap
|
| 11 |
+
heappush(heap, item) # pushes a new item on the heap
|
| 12 |
+
item = heappop(heap) # pops the smallest item from the heap
|
| 13 |
+
item = heap[0] # smallest item on the heap without popping it
|
| 14 |
+
heapify(x) # transforms list into a heap, in-place, in linear time
|
| 15 |
+
item = heapreplace(heap, item) # pops and returns smallest item, and adds
|
| 16 |
+
# new item; the heap size is unchanged
|
| 17 |
+
|
| 18 |
+
Our API differs from textbook heap algorithms as follows:
|
| 19 |
+
|
| 20 |
+
- We use 0-based indexing. This makes the relationship between the
|
| 21 |
+
index for a node and the indexes for its children slightly less
|
| 22 |
+
obvious, but is more suitable since Python uses 0-based indexing.
|
| 23 |
+
|
| 24 |
+
- Our heappop() method returns the smallest item, not the largest.
|
| 25 |
+
|
| 26 |
+
These two make it possible to view the heap as a regular Python list
|
| 27 |
+
without surprises: heap[0] is the smallest item, and heap.sort()
|
| 28 |
+
maintains the heap invariant!
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
# Original code by Kevin O'Connor, augmented by Tim Peters and Raymond Hettinger
|
| 32 |
+
|
| 33 |
+
__about__ = """Heap queues
|
| 34 |
+
|
| 35 |
+
[explanation by François Pinard]
|
| 36 |
+
|
| 37 |
+
Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
|
| 38 |
+
all k, counting elements from 0. For the sake of comparison,
|
| 39 |
+
non-existing elements are considered to be infinite. The interesting
|
| 40 |
+
property of a heap is that a[0] is always its smallest element.
|
| 41 |
+
|
| 42 |
+
The strange invariant above is meant to be an efficient memory
|
| 43 |
+
representation for a tournament. The numbers below are `k', not a[k]:
|
| 44 |
+
|
| 45 |
+
0
|
| 46 |
+
|
| 47 |
+
1 2
|
| 48 |
+
|
| 49 |
+
3 4 5 6
|
| 50 |
+
|
| 51 |
+
7 8 9 10 11 12 13 14
|
| 52 |
+
|
| 53 |
+
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In
|
| 57 |
+
a usual binary tournament we see in sports, each cell is the winner
|
| 58 |
+
over the two cells it tops, and we can trace the winner down the tree
|
| 59 |
+
to see all opponents s/he had. However, in many computer applications
|
| 60 |
+
of such tournaments, we do not need to trace the history of a winner.
|
| 61 |
+
To be more memory efficient, when a winner is promoted, we try to
|
| 62 |
+
replace it by something else at a lower level, and the rule becomes
|
| 63 |
+
that a cell and the two cells it tops contain three different items,
|
| 64 |
+
but the top cell "wins" over the two topped cells.
|
| 65 |
+
|
| 66 |
+
If this heap invariant is protected at all time, index 0 is clearly
|
| 67 |
+
the overall winner. The simplest algorithmic way to remove it and
|
| 68 |
+
find the "next" winner is to move some loser (let's say cell 30 in the
|
| 69 |
+
diagram above) into the 0 position, and then percolate this new 0 down
|
| 70 |
+
the tree, exchanging values, until the invariant is re-established.
|
| 71 |
+
This is clearly logarithmic on the total number of items in the tree.
|
| 72 |
+
By iterating over all items, you get an O(n ln n) sort.
|
| 73 |
+
|
| 74 |
+
A nice feature of this sort is that you can efficiently insert new
|
| 75 |
+
items while the sort is going on, provided that the inserted items are
|
| 76 |
+
not "better" than the last 0'th element you extracted. This is
|
| 77 |
+
especially useful in simulation contexts, where the tree holds all
|
| 78 |
+
incoming events, and the "win" condition means the smallest scheduled
|
| 79 |
+
time. When an event schedule other events for execution, they are
|
| 80 |
+
scheduled into the future, so they can easily go into the heap. So, a
|
| 81 |
+
heap is a good structure for implementing schedulers (this is what I
|
| 82 |
+
used for my MIDI sequencer :-).
|
| 83 |
+
|
| 84 |
+
Various structures for implementing schedulers have been extensively
|
| 85 |
+
studied, and heaps are good for this, as they are reasonably speedy,
|
| 86 |
+
the speed is almost constant, and the worst case is not much different
|
| 87 |
+
than the average case. However, there are other representations which
|
| 88 |
+
are more efficient overall, yet the worst cases might be terrible.
|
| 89 |
+
|
| 90 |
+
Heaps are also very useful in big disk sorts. You most probably all
|
| 91 |
+
know that a big sort implies producing "runs" (which are pre-sorted
|
| 92 |
+
sequences, which size is usually related to the amount of CPU memory),
|
| 93 |
+
followed by a merging passes for these runs, which merging is often
|
| 94 |
+
very cleverly organised[1]. It is very important that the initial
|
| 95 |
+
sort produces the longest runs possible. Tournaments are a good way
|
| 96 |
+
to that. If, using all the memory available to hold a tournament, you
|
| 97 |
+
replace and percolate items that happen to fit the current run, you'll
|
| 98 |
+
produce runs which are twice the size of the memory for random input,
|
| 99 |
+
and much better for input fuzzily ordered.
|
| 100 |
+
|
| 101 |
+
Moreover, if you output the 0'th item on disk and get an input which
|
| 102 |
+
may not fit in the current tournament (because the value "wins" over
|
| 103 |
+
the last output value), it cannot fit in the heap, so the size of the
|
| 104 |
+
heap decreases. The freed memory could be cleverly reused immediately
|
| 105 |
+
for progressively building a second heap, which grows at exactly the
|
| 106 |
+
same rate the first heap is melting. When the first heap completely
|
| 107 |
+
vanishes, you switch heaps and start a new run. Clever and quite
|
| 108 |
+
effective!
|
| 109 |
+
|
| 110 |
+
In a word, heaps are useful memory structures to know. I use them in
|
| 111 |
+
a few applications, and I think it is good to keep a `heap' module
|
| 112 |
+
around. :-)
|
| 113 |
+
|
| 114 |
+
--------------------
|
| 115 |
+
[1] The disk balancing algorithms which are current, nowadays, are
|
| 116 |
+
more annoying than clever, and this is a consequence of the seeking
|
| 117 |
+
capabilities of the disks. On devices which cannot seek, like big
|
| 118 |
+
tape drives, the story was quite different, and one had to be very
|
| 119 |
+
clever to ensure (far in advance) that each tape movement will be the
|
| 120 |
+
most effective possible (that is, will best participate at
|
| 121 |
+
"progressing" the merge). Some tapes were even able to read
|
| 122 |
+
backwards, and this was also used to avoid the rewinding time.
|
| 123 |
+
Believe me, real good tape sorts were quite spectacular to watch!
|
| 124 |
+
From all times, sorting has always been a Great Art! :-)
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge',
|
| 128 |
+
'nlargest', 'nsmallest', 'heappushpop']
|
| 129 |
+
|
| 130 |
+
def heappush(heap, item):
|
| 131 |
+
"""Push item onto heap, maintaining the heap invariant."""
|
| 132 |
+
heap.append(item)
|
| 133 |
+
_siftdown(heap, 0, len(heap)-1)
|
| 134 |
+
|
| 135 |
+
def heappop(heap):
|
| 136 |
+
"""Pop the smallest item off the heap, maintaining the heap invariant."""
|
| 137 |
+
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
|
| 138 |
+
if heap:
|
| 139 |
+
returnitem = heap[0]
|
| 140 |
+
heap[0] = lastelt
|
| 141 |
+
_siftup(heap, 0)
|
| 142 |
+
return returnitem
|
| 143 |
+
return lastelt
|
| 144 |
+
|
| 145 |
+
def heapreplace(heap, item):
|
| 146 |
+
"""Pop and return the current smallest value, and add the new item.
|
| 147 |
+
|
| 148 |
+
This is more efficient than heappop() followed by heappush(), and can be
|
| 149 |
+
more appropriate when using a fixed-size heap. Note that the value
|
| 150 |
+
returned may be larger than item! That constrains reasonable uses of
|
| 151 |
+
this routine unless written as part of a conditional replacement:
|
| 152 |
+
|
| 153 |
+
if item > heap[0]:
|
| 154 |
+
item = heapreplace(heap, item)
|
| 155 |
+
"""
|
| 156 |
+
returnitem = heap[0] # raises appropriate IndexError if heap is empty
|
| 157 |
+
heap[0] = item
|
| 158 |
+
_siftup(heap, 0)
|
| 159 |
+
return returnitem
|
| 160 |
+
|
| 161 |
+
def heappushpop(heap, item):
|
| 162 |
+
"""Fast version of a heappush followed by a heappop."""
|
| 163 |
+
if heap and heap[0] < item:
|
| 164 |
+
item, heap[0] = heap[0], item
|
| 165 |
+
_siftup(heap, 0)
|
| 166 |
+
return item
|
| 167 |
+
|
| 168 |
+
def heapify(x):
|
| 169 |
+
"""Transform list into a heap, in-place, in O(len(x)) time."""
|
| 170 |
+
n = len(x)
|
| 171 |
+
# Transform bottom-up. The largest index there's any point to looking at
|
| 172 |
+
# is the largest with a child index in-range, so must have 2*i + 1 < n,
|
| 173 |
+
# or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so
|
| 174 |
+
# j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is
|
| 175 |
+
# (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.
|
| 176 |
+
for i in reversed(range(n//2)):
|
| 177 |
+
_siftup(x, i)
|
| 178 |
+
|
| 179 |
+
def _heappop_max(heap):
|
| 180 |
+
"""Maxheap version of a heappop."""
|
| 181 |
+
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
|
| 182 |
+
if heap:
|
| 183 |
+
returnitem = heap[0]
|
| 184 |
+
heap[0] = lastelt
|
| 185 |
+
_siftup_max(heap, 0)
|
| 186 |
+
return returnitem
|
| 187 |
+
return lastelt
|
| 188 |
+
|
| 189 |
+
def _heapreplace_max(heap, item):
|
| 190 |
+
"""Maxheap version of a heappop followed by a heappush."""
|
| 191 |
+
returnitem = heap[0] # raises appropriate IndexError if heap is empty
|
| 192 |
+
heap[0] = item
|
| 193 |
+
_siftup_max(heap, 0)
|
| 194 |
+
return returnitem
|
| 195 |
+
|
| 196 |
+
def _heapify_max(x):
|
| 197 |
+
"""Transform list into a maxheap, in-place, in O(len(x)) time."""
|
| 198 |
+
n = len(x)
|
| 199 |
+
for i in reversed(range(n//2)):
|
| 200 |
+
_siftup_max(x, i)
|
| 201 |
+
|
| 202 |
+
# 'heap' is a heap at all indices >= startpos, except possibly for pos. pos
|
| 203 |
+
# is the index of a leaf with a possibly out-of-order value. Restore the
|
| 204 |
+
# heap invariant.
|
| 205 |
+
def _siftdown(heap, startpos, pos):
|
| 206 |
+
newitem = heap[pos]
|
| 207 |
+
# Follow the path to the root, moving parents down until finding a place
|
| 208 |
+
# newitem fits.
|
| 209 |
+
while pos > startpos:
|
| 210 |
+
parentpos = (pos - 1) >> 1
|
| 211 |
+
parent = heap[parentpos]
|
| 212 |
+
if newitem < parent:
|
| 213 |
+
heap[pos] = parent
|
| 214 |
+
pos = parentpos
|
| 215 |
+
continue
|
| 216 |
+
break
|
| 217 |
+
heap[pos] = newitem
|
| 218 |
+
|
| 219 |
+
# The child indices of heap index pos are already heaps, and we want to make
|
| 220 |
+
# a heap at index pos too. We do this by bubbling the smaller child of
|
| 221 |
+
# pos up (and so on with that child's children, etc) until hitting a leaf,
|
| 222 |
+
# then using _siftdown to move the oddball originally at index pos into place.
|
| 223 |
+
#
|
| 224 |
+
# We *could* break out of the loop as soon as we find a pos where newitem <=
|
| 225 |
+
# both its children, but turns out that's not a good idea, and despite that
|
| 226 |
+
# many books write the algorithm that way. During a heap pop, the last array
|
| 227 |
+
# element is sifted in, and that tends to be large, so that comparing it
|
| 228 |
+
# against values starting from the root usually doesn't pay (= usually doesn't
|
| 229 |
+
# get us out of the loop early). See Knuth, Volume 3, where this is
|
| 230 |
+
# explained and quantified in an exercise.
|
| 231 |
+
#
|
| 232 |
+
# Cutting the # of comparisons is important, since these routines have no
|
| 233 |
+
# way to extract "the priority" from an array element, so that intelligence
|
| 234 |
+
# is likely to be hiding in custom comparison methods, or in array elements
|
| 235 |
+
# storing (priority, record) tuples. Comparisons are thus potentially
|
| 236 |
+
# expensive.
|
| 237 |
+
#
|
| 238 |
+
# On random arrays of length 1000, making this change cut the number of
|
| 239 |
+
# comparisons made by heapify() a little, and those made by exhaustive
|
| 240 |
+
# heappop() a lot, in accord with theory. Here are typical results from 3
|
| 241 |
+
# runs (3 just to demonstrate how small the variance is):
|
| 242 |
+
#
|
| 243 |
+
# Compares needed by heapify Compares needed by 1000 heappops
|
| 244 |
+
# -------------------------- --------------------------------
|
| 245 |
+
# 1837 cut to 1663 14996 cut to 8680
|
| 246 |
+
# 1855 cut to 1659 14966 cut to 8678
|
| 247 |
+
# 1847 cut to 1660 15024 cut to 8703
|
| 248 |
+
#
|
| 249 |
+
# Building the heap by using heappush() 1000 times instead required
|
| 250 |
+
# 2198, 2148, and 2219 compares: heapify() is more efficient, when
|
| 251 |
+
# you can use it.
|
| 252 |
+
#
|
| 253 |
+
# The total compares needed by list.sort() on the same lists were 8627,
|
| 254 |
+
# 8627, and 8632 (this should be compared to the sum of heapify() and
|
| 255 |
+
# heappop() compares): list.sort() is (unsurprisingly!) more efficient
|
| 256 |
+
# for sorting.
|
| 257 |
+
|
| 258 |
+
def _siftup(heap, pos):
|
| 259 |
+
endpos = len(heap)
|
| 260 |
+
startpos = pos
|
| 261 |
+
newitem = heap[pos]
|
| 262 |
+
# Bubble up the smaller child until hitting a leaf.
|
| 263 |
+
childpos = 2*pos + 1 # leftmost child position
|
| 264 |
+
while childpos < endpos:
|
| 265 |
+
# Set childpos to index of smaller child.
|
| 266 |
+
rightpos = childpos + 1
|
| 267 |
+
if rightpos < endpos and not heap[childpos] < heap[rightpos]:
|
| 268 |
+
childpos = rightpos
|
| 269 |
+
# Move the smaller child up.
|
| 270 |
+
heap[pos] = heap[childpos]
|
| 271 |
+
pos = childpos
|
| 272 |
+
childpos = 2*pos + 1
|
| 273 |
+
# The leaf at pos is empty now. Put newitem there, and bubble it up
|
| 274 |
+
# to its final resting place (by sifting its parents down).
|
| 275 |
+
heap[pos] = newitem
|
| 276 |
+
_siftdown(heap, startpos, pos)
|
| 277 |
+
|
| 278 |
+
def _siftdown_max(heap, startpos, pos):
|
| 279 |
+
'Maxheap variant of _siftdown'
|
| 280 |
+
newitem = heap[pos]
|
| 281 |
+
# Follow the path to the root, moving parents down until finding a place
|
| 282 |
+
# newitem fits.
|
| 283 |
+
while pos > startpos:
|
| 284 |
+
parentpos = (pos - 1) >> 1
|
| 285 |
+
parent = heap[parentpos]
|
| 286 |
+
if parent < newitem:
|
| 287 |
+
heap[pos] = parent
|
| 288 |
+
pos = parentpos
|
| 289 |
+
continue
|
| 290 |
+
break
|
| 291 |
+
heap[pos] = newitem
|
| 292 |
+
|
| 293 |
+
def _siftup_max(heap, pos):
|
| 294 |
+
'Maxheap variant of _siftup'
|
| 295 |
+
endpos = len(heap)
|
| 296 |
+
startpos = pos
|
| 297 |
+
newitem = heap[pos]
|
| 298 |
+
# Bubble up the larger child until hitting a leaf.
|
| 299 |
+
childpos = 2*pos + 1 # leftmost child position
|
| 300 |
+
while childpos < endpos:
|
| 301 |
+
# Set childpos to index of larger child.
|
| 302 |
+
rightpos = childpos + 1
|
| 303 |
+
if rightpos < endpos and not heap[rightpos] < heap[childpos]:
|
| 304 |
+
childpos = rightpos
|
| 305 |
+
# Move the larger child up.
|
| 306 |
+
heap[pos] = heap[childpos]
|
| 307 |
+
pos = childpos
|
| 308 |
+
childpos = 2*pos + 1
|
| 309 |
+
# The leaf at pos is empty now. Put newitem there, and bubble it up
|
| 310 |
+
# to its final resting place (by sifting its parents down).
|
| 311 |
+
heap[pos] = newitem
|
| 312 |
+
_siftdown_max(heap, startpos, pos)
|
| 313 |
+
|
| 314 |
+
def merge(*iterables, key=None, reverse=False):
|
| 315 |
+
'''Merge multiple sorted inputs into a single sorted output.
|
| 316 |
+
|
| 317 |
+
Similar to sorted(itertools.chain(*iterables)) but returns a generator,
|
| 318 |
+
does not pull the data into memory all at once, and assumes that each of
|
| 319 |
+
the input streams is already sorted (smallest to largest).
|
| 320 |
+
|
| 321 |
+
>>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
|
| 322 |
+
[0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
|
| 323 |
+
|
| 324 |
+
If *key* is not None, applies a key function to each element to determine
|
| 325 |
+
its sort order.
|
| 326 |
+
|
| 327 |
+
>>> list(merge(['dog', 'horse'], ['cat', 'fish', 'kangaroo'], key=len))
|
| 328 |
+
['dog', 'cat', 'fish', 'horse', 'kangaroo']
|
| 329 |
+
|
| 330 |
+
'''
|
| 331 |
+
|
| 332 |
+
h = []
|
| 333 |
+
h_append = h.append
|
| 334 |
+
|
| 335 |
+
if reverse:
|
| 336 |
+
_heapify = _heapify_max
|
| 337 |
+
_heappop = _heappop_max
|
| 338 |
+
_heapreplace = _heapreplace_max
|
| 339 |
+
direction = -1
|
| 340 |
+
else:
|
| 341 |
+
_heapify = heapify
|
| 342 |
+
_heappop = heappop
|
| 343 |
+
_heapreplace = heapreplace
|
| 344 |
+
direction = 1
|
| 345 |
+
|
| 346 |
+
if key is None:
|
| 347 |
+
for order, it in enumerate(map(iter, iterables)):
|
| 348 |
+
try:
|
| 349 |
+
next = it.__next__
|
| 350 |
+
h_append([next(), order * direction, next])
|
| 351 |
+
except StopIteration:
|
| 352 |
+
pass
|
| 353 |
+
_heapify(h)
|
| 354 |
+
while len(h) > 1:
|
| 355 |
+
try:
|
| 356 |
+
while True:
|
| 357 |
+
value, order, next = s = h[0]
|
| 358 |
+
yield value
|
| 359 |
+
s[0] = next() # raises StopIteration when exhausted
|
| 360 |
+
_heapreplace(h, s) # restore heap condition
|
| 361 |
+
except StopIteration:
|
| 362 |
+
_heappop(h) # remove empty iterator
|
| 363 |
+
if h:
|
| 364 |
+
# fast case when only a single iterator remains
|
| 365 |
+
value, order, next = h[0]
|
| 366 |
+
yield value
|
| 367 |
+
yield from next.__self__
|
| 368 |
+
return
|
| 369 |
+
|
| 370 |
+
for order, it in enumerate(map(iter, iterables)):
|
| 371 |
+
try:
|
| 372 |
+
next = it.__next__
|
| 373 |
+
value = next()
|
| 374 |
+
h_append([key(value), order * direction, value, next])
|
| 375 |
+
except StopIteration:
|
| 376 |
+
pass
|
| 377 |
+
_heapify(h)
|
| 378 |
+
while len(h) > 1:
|
| 379 |
+
try:
|
| 380 |
+
while True:
|
| 381 |
+
key_value, order, value, next = s = h[0]
|
| 382 |
+
yield value
|
| 383 |
+
value = next()
|
| 384 |
+
s[0] = key(value)
|
| 385 |
+
s[2] = value
|
| 386 |
+
_heapreplace(h, s)
|
| 387 |
+
except StopIteration:
|
| 388 |
+
_heappop(h)
|
| 389 |
+
if h:
|
| 390 |
+
key_value, order, value, next = h[0]
|
| 391 |
+
yield value
|
| 392 |
+
yield from next.__self__
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
# Algorithm notes for nlargest() and nsmallest()
|
| 396 |
+
# ==============================================
|
| 397 |
+
#
|
| 398 |
+
# Make a single pass over the data while keeping the k most extreme values
|
| 399 |
+
# in a heap. Memory consumption is limited to keeping k values in a list.
|
| 400 |
+
#
|
| 401 |
+
# Measured performance for random inputs:
|
| 402 |
+
#
|
| 403 |
+
# number of comparisons
|
| 404 |
+
# n inputs k-extreme values (average of 5 trials) % more than min()
|
| 405 |
+
# ------------- ---------------- --------------------- -----------------
|
| 406 |
+
# 1,000 100 3,317 231.7%
|
| 407 |
+
# 10,000 100 14,046 40.5%
|
| 408 |
+
# 100,000 100 105,749 5.7%
|
| 409 |
+
# 1,000,000 100 1,007,751 0.8%
|
| 410 |
+
# 10,000,000 100 10,009,401 0.1%
|
| 411 |
+
#
|
| 412 |
+
# Theoretical number of comparisons for k smallest of n random inputs:
|
| 413 |
+
#
|
| 414 |
+
# Step Comparisons Action
|
| 415 |
+
# ---- -------------------------- ---------------------------
|
| 416 |
+
# 1 1.66 * k heapify the first k-inputs
|
| 417 |
+
# 2 n - k compare remaining elements to top of heap
|
| 418 |
+
# 3 k * (1 + lg2(k)) * ln(n/k) replace the topmost value on the heap
|
| 419 |
+
# 4 k * lg2(k) - (k/2) final sort of the k most extreme values
|
| 420 |
+
#
|
| 421 |
+
# Combining and simplifying for a rough estimate gives:
|
| 422 |
+
#
|
| 423 |
+
# comparisons = n + k * (log(k, 2) * log(n/k) + log(k, 2) + log(n/k))
|
| 424 |
+
#
|
| 425 |
+
# Computing the number of comparisons for step 3:
|
| 426 |
+
# -----------------------------------------------
|
| 427 |
+
# * For the i-th new value from the iterable, the probability of being in the
|
| 428 |
+
# k most extreme values is k/i. For example, the probability of the 101st
|
| 429 |
+
# value seen being in the 100 most extreme values is 100/101.
|
| 430 |
+
# * If the value is a new extreme value, the cost of inserting it into the
|
| 431 |
+
# heap is 1 + log(k, 2).
|
| 432 |
+
# * The probability times the cost gives:
|
| 433 |
+
# (k/i) * (1 + log(k, 2))
|
| 434 |
+
# * Summing across the remaining n-k elements gives:
|
| 435 |
+
# sum((k/i) * (1 + log(k, 2)) for i in range(k+1, n+1))
|
| 436 |
+
# * This reduces to:
|
| 437 |
+
# (H(n) - H(k)) * k * (1 + log(k, 2))
|
| 438 |
+
# * Where H(n) is the n-th harmonic number estimated by:
|
| 439 |
+
# gamma = 0.5772156649
|
| 440 |
+
# H(n) = log(n, e) + gamma + 1 / (2 * n)
|
| 441 |
+
# http://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#Rate_of_divergence
|
| 442 |
+
# * Substituting the H(n) formula:
|
| 443 |
+
# comparisons = k * (1 + log(k, 2)) * (log(n/k, e) + (1/n - 1/k) / 2)
|
| 444 |
+
#
|
| 445 |
+
# Worst-case for step 3:
|
| 446 |
+
# ----------------------
|
| 447 |
+
# In the worst case, the input data is reversed sorted so that every new element
|
| 448 |
+
# must be inserted in the heap:
|
| 449 |
+
#
|
| 450 |
+
# comparisons = 1.66 * k + log(k, 2) * (n - k)
|
| 451 |
+
#
|
| 452 |
+
# Alternative Algorithms
|
| 453 |
+
# ----------------------
|
| 454 |
+
# Other algorithms were not used because they:
|
| 455 |
+
# 1) Took much more auxiliary memory,
|
| 456 |
+
# 2) Made multiple passes over the data.
|
| 457 |
+
# 3) Made more comparisons in common cases (small k, large n, semi-random input).
|
| 458 |
+
# See the more detailed comparison of approach at:
|
| 459 |
+
# http://code.activestate.com/recipes/577573-compare-algorithms-for-heapqsmallest
|
| 460 |
+
|
| 461 |
+
def nsmallest(n, iterable, key=None):
|
| 462 |
+
"""Find the n smallest elements in a dataset.
|
| 463 |
+
|
| 464 |
+
Equivalent to: sorted(iterable, key=key)[:n]
|
| 465 |
+
"""
|
| 466 |
+
|
| 467 |
+
# Short-cut for n==1 is to use min()
|
| 468 |
+
if n == 1:
|
| 469 |
+
it = iter(iterable)
|
| 470 |
+
sentinel = object()
|
| 471 |
+
result = min(it, default=sentinel, key=key)
|
| 472 |
+
return [] if result is sentinel else [result]
|
| 473 |
+
|
| 474 |
+
# When n>=size, it's faster to use sorted()
|
| 475 |
+
try:
|
| 476 |
+
size = len(iterable)
|
| 477 |
+
except (TypeError, AttributeError):
|
| 478 |
+
pass
|
| 479 |
+
else:
|
| 480 |
+
if n >= size:
|
| 481 |
+
return sorted(iterable, key=key)[:n]
|
| 482 |
+
|
| 483 |
+
# When key is none, use simpler decoration
|
| 484 |
+
if key is None:
|
| 485 |
+
it = iter(iterable)
|
| 486 |
+
# put the range(n) first so that zip() doesn't
|
| 487 |
+
# consume one too many elements from the iterator
|
| 488 |
+
result = [(elem, i) for i, elem in zip(range(n), it)]
|
| 489 |
+
if not result:
|
| 490 |
+
return result
|
| 491 |
+
_heapify_max(result)
|
| 492 |
+
top = result[0][0]
|
| 493 |
+
order = n
|
| 494 |
+
_heapreplace = _heapreplace_max
|
| 495 |
+
for elem in it:
|
| 496 |
+
if elem < top:
|
| 497 |
+
_heapreplace(result, (elem, order))
|
| 498 |
+
top, _order = result[0]
|
| 499 |
+
order += 1
|
| 500 |
+
result.sort()
|
| 501 |
+
return [elem for (elem, order) in result]
|
| 502 |
+
|
| 503 |
+
# General case, slowest method
|
| 504 |
+
it = iter(iterable)
|
| 505 |
+
result = [(key(elem), i, elem) for i, elem in zip(range(n), it)]
|
| 506 |
+
if not result:
|
| 507 |
+
return result
|
| 508 |
+
_heapify_max(result)
|
| 509 |
+
top = result[0][0]
|
| 510 |
+
order = n
|
| 511 |
+
_heapreplace = _heapreplace_max
|
| 512 |
+
for elem in it:
|
| 513 |
+
k = key(elem)
|
| 514 |
+
if k < top:
|
| 515 |
+
_heapreplace(result, (k, order, elem))
|
| 516 |
+
top, _order, _elem = result[0]
|
| 517 |
+
order += 1
|
| 518 |
+
result.sort()
|
| 519 |
+
return [elem for (k, order, elem) in result]
|
| 520 |
+
|
| 521 |
+
def nlargest(n, iterable, key=None):
|
| 522 |
+
"""Find the n largest elements in a dataset.
|
| 523 |
+
|
| 524 |
+
Equivalent to: sorted(iterable, key=key, reverse=True)[:n]
|
| 525 |
+
"""
|
| 526 |
+
|
| 527 |
+
# Short-cut for n==1 is to use max()
|
| 528 |
+
if n == 1:
|
| 529 |
+
it = iter(iterable)
|
| 530 |
+
sentinel = object()
|
| 531 |
+
result = max(it, default=sentinel, key=key)
|
| 532 |
+
return [] if result is sentinel else [result]
|
| 533 |
+
|
| 534 |
+
# When n>=size, it's faster to use sorted()
|
| 535 |
+
try:
|
| 536 |
+
size = len(iterable)
|
| 537 |
+
except (TypeError, AttributeError):
|
| 538 |
+
pass
|
| 539 |
+
else:
|
| 540 |
+
if n >= size:
|
| 541 |
+
return sorted(iterable, key=key, reverse=True)[:n]
|
| 542 |
+
|
| 543 |
+
# When key is none, use simpler decoration
|
| 544 |
+
if key is None:
|
| 545 |
+
it = iter(iterable)
|
| 546 |
+
result = [(elem, i) for i, elem in zip(range(0, -n, -1), it)]
|
| 547 |
+
if not result:
|
| 548 |
+
return result
|
| 549 |
+
heapify(result)
|
| 550 |
+
top = result[0][0]
|
| 551 |
+
order = -n
|
| 552 |
+
_heapreplace = heapreplace
|
| 553 |
+
for elem in it:
|
| 554 |
+
if top < elem:
|
| 555 |
+
_heapreplace(result, (elem, order))
|
| 556 |
+
top, _order = result[0]
|
| 557 |
+
order -= 1
|
| 558 |
+
result.sort(reverse=True)
|
| 559 |
+
return [elem for (elem, order) in result]
|
| 560 |
+
|
| 561 |
+
# General case, slowest method
|
| 562 |
+
it = iter(iterable)
|
| 563 |
+
result = [(key(elem), i, elem) for i, elem in zip(range(0, -n, -1), it)]
|
| 564 |
+
if not result:
|
| 565 |
+
return result
|
| 566 |
+
heapify(result)
|
| 567 |
+
top = result[0][0]
|
| 568 |
+
order = -n
|
| 569 |
+
_heapreplace = heapreplace
|
| 570 |
+
for elem in it:
|
| 571 |
+
k = key(elem)
|
| 572 |
+
if top < k:
|
| 573 |
+
_heapreplace(result, (k, order, elem))
|
| 574 |
+
top, _order, _elem = result[0]
|
| 575 |
+
order -= 1
|
| 576 |
+
result.sort(reverse=True)
|
| 577 |
+
return [elem for (k, order, elem) in result]
|
| 578 |
+
|
| 579 |
+
# If available, use C implementation
|
| 580 |
+
try:
|
| 581 |
+
from _heapq import *
|
| 582 |
+
except ImportError:
|
| 583 |
+
pass
|
| 584 |
+
try:
|
| 585 |
+
from _heapq import _heapreplace_max
|
| 586 |
+
except ImportError:
|
| 587 |
+
pass
|
| 588 |
+
try:
|
| 589 |
+
from _heapq import _heapify_max
|
| 590 |
+
except ImportError:
|
| 591 |
+
pass
|
| 592 |
+
try:
|
| 593 |
+
from _heapq import _heappop_max
|
| 594 |
+
except ImportError:
|
| 595 |
+
pass
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
if __name__ == "__main__":
|
| 599 |
+
|
| 600 |
+
import doctest # pragma: no cover
|
| 601 |
+
print(doctest.testmod()) # pragma: no cover
|
shared/package-files/03/0353721b70c5f97f936acb7c0eafc7c6878e2bdf770b0bb3a7e00e7ab1199451/distributions.py
AD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
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Algorithmic implementations for generating different types
|
| 3 |
+
of random distributions.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
from numba.core.extending import register_jitable
|
| 9 |
+
from numba.np.random._constants import (wi_double, ki_double,
|
| 10 |
+
ziggurat_nor_r, fi_double,
|
| 11 |
+
wi_float, ki_float,
|
| 12 |
+
ziggurat_nor_inv_r_f,
|
| 13 |
+
ziggurat_nor_r_f, fi_float,
|
| 14 |
+
we_double, ke_double,
|
| 15 |
+
ziggurat_exp_r, fe_double,
|
| 16 |
+
we_float, ke_float,
|
| 17 |
+
ziggurat_exp_r_f, fe_float,
|
| 18 |
+
INT64_MAX, ziggurat_nor_inv_r)
|
| 19 |
+
from numba.cpython._binomial import make_binomial_btpe
|
| 20 |
+
from numba.np.random.generator_core import (next_double, next_float,
|
| 21 |
+
next_uint32, next_uint64)
|
| 22 |
+
from numba import float32, int64
|
| 23 |
+
from numba.np.numpy_support import numpy_version
|
| 24 |
+
# All of the following implementations are direct translations from:
|
| 25 |
+
# https://github.com/numpy/numpy/blob/7cfef93c77599bd387ecc6a15d186c5a46024dac/numpy/random/src/distributions/distributions.c
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@register_jitable
|
| 29 |
+
def np_log1p(x):
|
| 30 |
+
return np.log1p(x)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@register_jitable
|
| 34 |
+
def np_log1pf(x):
|
| 35 |
+
return np.log1p(float32(x))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@register_jitable
|
| 39 |
+
def random_rayleigh(bitgen, mode):
|
| 40 |
+
return mode * np.sqrt(2.0 * random_standard_exponential(bitgen))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@register_jitable
|
| 44 |
+
def np_expm1(x):
|
| 45 |
+
return np.expm1(x)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@register_jitable
|
| 49 |
+
def random_standard_normal(bitgen):
|
| 50 |
+
while 1:
|
| 51 |
+
r = next_uint64(bitgen)
|
| 52 |
+
idx = r & 0xff
|
| 53 |
+
r >>= 8
|
| 54 |
+
sign = r & 0x1
|
| 55 |
+
rabs = (r >> 1) & 0x000fffffffffffff
|
| 56 |
+
x = rabs * wi_double[idx]
|
| 57 |
+
if (sign & 0x1):
|
| 58 |
+
x = -x
|
| 59 |
+
if rabs < ki_double[idx]:
|
| 60 |
+
return x
|
| 61 |
+
if idx == 0:
|
| 62 |
+
while 1:
|
| 63 |
+
xx = -ziggurat_nor_inv_r * np.log1p(-next_double(bitgen))
|
| 64 |
+
yy = -np.log1p(-next_double(bitgen))
|
| 65 |
+
if (yy + yy > xx * xx):
|
| 66 |
+
if ((rabs >> 8) & 0x1):
|
| 67 |
+
return -(ziggurat_nor_r + xx)
|
| 68 |
+
else:
|
| 69 |
+
return ziggurat_nor_r + xx
|
| 70 |
+
else:
|
| 71 |
+
if (((fi_double[idx - 1] - fi_double[idx]) *
|
| 72 |
+
next_double(bitgen) + fi_double[idx]) <
|
| 73 |
+
np.exp(-0.5 * x * x)):
|
| 74 |
+
return x
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@register_jitable
|
| 78 |
+
def random_standard_normal_f(bitgen):
|
| 79 |
+
while 1:
|
| 80 |
+
r = next_uint32(bitgen)
|
| 81 |
+
idx = r & 0xff
|
| 82 |
+
sign = (r >> 8) & 0x1
|
| 83 |
+
rabs = (r >> 9) & 0x0007fffff
|
| 84 |
+
x = float32(float32(rabs) * wi_float[idx])
|
| 85 |
+
if (sign & 0x1):
|
| 86 |
+
x = -x
|
| 87 |
+
if (rabs < ki_float[idx]):
|
| 88 |
+
return x
|
| 89 |
+
if (idx == 0):
|
| 90 |
+
while 1:
|
| 91 |
+
xx = float32(-ziggurat_nor_inv_r_f *
|
| 92 |
+
np_log1pf(-next_float(bitgen)))
|
| 93 |
+
yy = float32(-np_log1pf(-next_float(bitgen)))
|
| 94 |
+
if (float32(yy + yy) > float32(xx * xx)):
|
| 95 |
+
if ((rabs >> 8) & 0x1):
|
| 96 |
+
return -float32(ziggurat_nor_r_f + xx)
|
| 97 |
+
else:
|
| 98 |
+
return float32(ziggurat_nor_r_f + xx)
|
| 99 |
+
else:
|
| 100 |
+
if (((fi_float[idx - 1] - fi_float[idx]) * next_float(bitgen) +
|
| 101 |
+
fi_float[idx]) < float32(np.exp(-float32(0.5) * x * x))):
|
| 102 |
+
return x
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@register_jitable
|
| 106 |
+
def random_standard_exponential(bitgen):
|
| 107 |
+
while 1:
|
| 108 |
+
ri = next_uint64(bitgen)
|
| 109 |
+
ri >>= 3
|
| 110 |
+
idx = ri & 0xFF
|
| 111 |
+
ri >>= 8
|
| 112 |
+
x = ri * we_double[idx]
|
| 113 |
+
if (ri < ke_double[idx]):
|
| 114 |
+
return x
|
| 115 |
+
else:
|
| 116 |
+
if idx == 0:
|
| 117 |
+
return ziggurat_exp_r - np_log1p(-next_double(bitgen))
|
| 118 |
+
elif ((fe_double[idx - 1] - fe_double[idx]) * next_double(bitgen) +
|
| 119 |
+
fe_double[idx] < np.exp(-x)):
|
| 120 |
+
return x
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@register_jitable
|
| 124 |
+
def random_standard_exponential_f(bitgen):
|
| 125 |
+
while 1:
|
| 126 |
+
ri = next_uint32(bitgen)
|
| 127 |
+
ri >>= 1
|
| 128 |
+
idx = ri & 0xFF
|
| 129 |
+
ri >>= 8
|
| 130 |
+
x = float32(float32(ri) * we_float[idx])
|
| 131 |
+
if (ri < ke_float[idx]):
|
| 132 |
+
return x
|
| 133 |
+
else:
|
| 134 |
+
if (idx == 0):
|
| 135 |
+
return float32(ziggurat_exp_r_f -
|
| 136 |
+
float32(np_log1pf(-next_float(bitgen))))
|
| 137 |
+
elif ((fe_float[idx - 1] - fe_float[idx]) * next_float(bitgen) +
|
| 138 |
+
fe_float[idx] < float32(np.exp(float32(-x)))):
|
| 139 |
+
return x
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@register_jitable
|
| 143 |
+
def random_standard_exponential_inv(bitgen):
|
| 144 |
+
return -np_log1p(-next_double(bitgen))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@register_jitable
|
| 148 |
+
def random_standard_exponential_inv_f(bitgen):
|
| 149 |
+
return -np.log(float32(1.0) - next_float(bitgen))
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@register_jitable
|
| 153 |
+
def random_standard_gamma(bitgen, shape):
|
| 154 |
+
if (shape == 1.0):
|
| 155 |
+
return random_standard_exponential(bitgen)
|
| 156 |
+
elif (shape == 0.0):
|
| 157 |
+
return 0.0
|
| 158 |
+
elif (shape < 1.0):
|
| 159 |
+
while 1:
|
| 160 |
+
U = next_double(bitgen)
|
| 161 |
+
V = random_standard_exponential(bitgen)
|
| 162 |
+
if (U <= 1.0 - shape):
|
| 163 |
+
X = pow(U, 1. / shape)
|
| 164 |
+
if (X <= V):
|
| 165 |
+
return X
|
| 166 |
+
else:
|
| 167 |
+
Y = -np.log((1 - U) / shape)
|
| 168 |
+
X = pow(1.0 - shape + shape * Y, 1. / shape)
|
| 169 |
+
if (X <= (V + Y)):
|
| 170 |
+
return X
|
| 171 |
+
else:
|
| 172 |
+
b = shape - 1. / 3.
|
| 173 |
+
c = 1. / np.sqrt(9 * b)
|
| 174 |
+
while 1:
|
| 175 |
+
while 1:
|
| 176 |
+
X = random_standard_normal(bitgen)
|
| 177 |
+
V = 1.0 + c * X
|
| 178 |
+
if (V > 0.0):
|
| 179 |
+
break
|
| 180 |
+
|
| 181 |
+
V = V * V * V
|
| 182 |
+
U = next_double(bitgen)
|
| 183 |
+
if (U < 1.0 - 0.0331 * (X * X) * (X * X)):
|
| 184 |
+
return (b * V)
|
| 185 |
+
|
| 186 |
+
if (np.log(U) < 0.5 * X * X + b * (1. - V + np.log(V))):
|
| 187 |
+
return (b * V)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@register_jitable
|
| 191 |
+
def random_standard_gamma_f(bitgen, shape):
|
| 192 |
+
f32_one = float32(1.0)
|
| 193 |
+
shape = float32(shape)
|
| 194 |
+
if (shape == f32_one):
|
| 195 |
+
return random_standard_exponential_f(bitgen)
|
| 196 |
+
elif (shape == float32(0.0)):
|
| 197 |
+
return float32(0.0)
|
| 198 |
+
elif (shape < f32_one):
|
| 199 |
+
while 1:
|
| 200 |
+
U = next_float(bitgen)
|
| 201 |
+
V = random_standard_exponential_f(bitgen)
|
| 202 |
+
if (U <= f32_one - shape):
|
| 203 |
+
X = float32(pow(U, float32(f32_one / shape)))
|
| 204 |
+
if (X <= V):
|
| 205 |
+
return X
|
| 206 |
+
else:
|
| 207 |
+
Y = float32(-np.log(float32((f32_one - U) / shape)))
|
| 208 |
+
X = float32(pow(f32_one - shape + float32(shape * Y),
|
| 209 |
+
float32(f32_one / shape)))
|
| 210 |
+
if (X <= (V + Y)):
|
| 211 |
+
return X
|
| 212 |
+
else:
|
| 213 |
+
b = shape - f32_one / float32(3.0)
|
| 214 |
+
c = float32(f32_one / float32(np.sqrt(float32(9.0) * b)))
|
| 215 |
+
while 1:
|
| 216 |
+
while 1:
|
| 217 |
+
X = float32(random_standard_normal_f(bitgen))
|
| 218 |
+
V = float32(f32_one + c * X)
|
| 219 |
+
if (V > float32(0.0)):
|
| 220 |
+
break
|
| 221 |
+
|
| 222 |
+
V = float32(V * V * V)
|
| 223 |
+
U = next_float(bitgen)
|
| 224 |
+
if (U < f32_one - float32(0.0331) * (X * X) * (X * X)):
|
| 225 |
+
return float32(b * V)
|
| 226 |
+
|
| 227 |
+
if (np.log(U) < float32(0.5) * X * X + b *
|
| 228 |
+
(f32_one - V + np.log(V))):
|
| 229 |
+
return float32(b * V)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
@register_jitable
|
| 233 |
+
def random_normal(bitgen, loc, scale):
|
| 234 |
+
scaled_normal = scale * random_standard_normal(bitgen)
|
| 235 |
+
return loc + scaled_normal
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
@register_jitable
|
| 239 |
+
def random_normal_f(bitgen, loc, scale):
|
| 240 |
+
scaled_normal = float32(scale * random_standard_normal_f(bitgen))
|
| 241 |
+
return float32(loc + scaled_normal)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
@register_jitable
|
| 245 |
+
def random_exponential(bitgen, scale):
|
| 246 |
+
return scale * random_standard_exponential(bitgen)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
@register_jitable
|
| 250 |
+
def random_uniform(bitgen, lower, range):
|
| 251 |
+
scaled_uniform = range * next_double(bitgen)
|
| 252 |
+
return lower + scaled_uniform
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
@register_jitable
|
| 256 |
+
def random_gamma(bitgen, shape, scale):
|
| 257 |
+
return scale * random_standard_gamma(bitgen, shape)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
@register_jitable
|
| 261 |
+
def random_gamma_f(bitgen, shape, scale):
|
| 262 |
+
return float32(scale * random_standard_gamma_f(bitgen, shape))
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@register_jitable
|
| 266 |
+
def random_beta(bitgen, a, b):
|
| 267 |
+
if a <= 1.0 and b <= 1.0:
|
| 268 |
+
while 1:
|
| 269 |
+
U = next_double(bitgen)
|
| 270 |
+
V = next_double(bitgen)
|
| 271 |
+
X = pow(U, 1.0 / a)
|
| 272 |
+
Y = pow(V, 1.0 / b)
|
| 273 |
+
XpY = X + Y
|
| 274 |
+
if XpY <= 1.0 and XpY > 0.0:
|
| 275 |
+
if (X + Y > 0):
|
| 276 |
+
return X / XpY
|
| 277 |
+
else:
|
| 278 |
+
logX = np.log(U) / a
|
| 279 |
+
logY = np.log(V) / b
|
| 280 |
+
logM = min(logX, logY)
|
| 281 |
+
logX -= logM
|
| 282 |
+
logY -= logM
|
| 283 |
+
|
| 284 |
+
return np.exp(logX - np.log(np.exp(logX) + np.exp(logY)))
|
| 285 |
+
else:
|
| 286 |
+
Ga = random_standard_gamma(bitgen, a)
|
| 287 |
+
Gb = random_standard_gamma(bitgen, b)
|
| 288 |
+
return Ga / (Ga + Gb)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
@register_jitable
|
| 292 |
+
def random_chisquare(bitgen, df):
|
| 293 |
+
return 2.0 * random_standard_gamma(bitgen, df / 2.0)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
@register_jitable
|
| 297 |
+
def random_f(bitgen, dfnum, dfden):
|
| 298 |
+
return ((random_chisquare(bitgen, dfnum) * dfden) /
|
| 299 |
+
(random_chisquare(bitgen, dfden) * dfnum))
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
@register_jitable
|
| 303 |
+
def random_standard_cauchy(bitgen):
|
| 304 |
+
return random_standard_normal(bitgen) / random_standard_normal(bitgen)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
@register_jitable
|
| 308 |
+
def random_pareto(bitgen, a):
|
| 309 |
+
return np_expm1(random_standard_exponential(bitgen) / a)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
@register_jitable
|
| 313 |
+
def random_weibull(bitgen, a):
|
| 314 |
+
if (a == 0.0):
|
| 315 |
+
return 0.0
|
| 316 |
+
return pow(random_standard_exponential(bitgen), 1. / a)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@register_jitable
|
| 320 |
+
def random_power(bitgen, a):
|
| 321 |
+
return pow(-np_expm1(-random_standard_exponential(bitgen)), 1. / a)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
@register_jitable
|
| 325 |
+
def random_laplace(bitgen, loc, scale):
|
| 326 |
+
U = next_double(bitgen)
|
| 327 |
+
while U <= 0:
|
| 328 |
+
U = next_double(bitgen)
|
| 329 |
+
if (U >= 0.5):
|
| 330 |
+
U = loc - scale * np.log(2.0 - U - U)
|
| 331 |
+
elif (U > 0.0):
|
| 332 |
+
U = loc + scale * np.log(U + U)
|
| 333 |
+
return U
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
@register_jitable
|
| 337 |
+
def random_logistic(bitgen, loc, scale):
|
| 338 |
+
U = next_double(bitgen)
|
| 339 |
+
while U <= 0.0:
|
| 340 |
+
U = next_double(bitgen)
|
| 341 |
+
return loc + scale * np.log(U / (1.0 - U))
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
@register_jitable
|
| 345 |
+
def random_lognormal(bitgen, mean, sigma):
|
| 346 |
+
return np.exp(random_normal(bitgen, mean, sigma))
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
@register_jitable
|
| 350 |
+
def random_standard_t(bitgen, df):
|
| 351 |
+
num = random_standard_normal(bitgen)
|
| 352 |
+
denom = random_standard_gamma(bitgen, df / 2)
|
| 353 |
+
return np.sqrt(df / 2) * num / np.sqrt(denom)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
@register_jitable
|
| 357 |
+
def random_wald(bitgen, mean, scale):
|
| 358 |
+
mu_2l = mean / (2 * scale)
|
| 359 |
+
Y = random_standard_normal(bitgen)
|
| 360 |
+
Y = mean * Y * Y
|
| 361 |
+
X = mean + mu_2l * (Y - np.sqrt(4 * scale * Y + Y * Y))
|
| 362 |
+
U = next_double(bitgen)
|
| 363 |
+
if (U <= mean / (mean + X)):
|
| 364 |
+
return X
|
| 365 |
+
else:
|
| 366 |
+
return mean * mean / X
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
@register_jitable
|
| 370 |
+
def random_geometric_search(bitgen, p):
|
| 371 |
+
X = 1
|
| 372 |
+
sum = prod = p
|
| 373 |
+
q = 1.0 - p
|
| 374 |
+
U = next_double(bitgen)
|
| 375 |
+
while (U > sum):
|
| 376 |
+
prod *= q
|
| 377 |
+
sum += prod
|
| 378 |
+
X = X + 1
|
| 379 |
+
return X
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
@register_jitable
|
| 383 |
+
def random_geometric_inversion(bitgen, p):
|
| 384 |
+
return np.ceil(-random_standard_exponential(bitgen) / np.log1p(-p))
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
@register_jitable
|
| 388 |
+
def random_geometric(bitgen, p):
|
| 389 |
+
if (p >= 0.333333333333333333333333):
|
| 390 |
+
return random_geometric_search(bitgen, p)
|
| 391 |
+
else:
|
| 392 |
+
return random_geometric_inversion(bitgen, p)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
if numpy_version < (2, 1):
|
| 396 |
+
@register_jitable
|
| 397 |
+
def random_zipf(bitgen, a):
|
| 398 |
+
am1 = a - 1.0
|
| 399 |
+
b = pow(2.0, am1)
|
| 400 |
+
while 1:
|
| 401 |
+
U = 1.0 - next_double(bitgen)
|
| 402 |
+
V = next_double(bitgen)
|
| 403 |
+
X = np.floor(pow(U, -1.0 / am1))
|
| 404 |
+
if (X > INT64_MAX or X < 1.0):
|
| 405 |
+
continue
|
| 406 |
+
T = pow(1.0 + 1.0 / X, am1)
|
| 407 |
+
if (V * X * (T - 1.0) / (b - 1.0) <= T / b):
|
| 408 |
+
return X
|
| 409 |
+
else:
|
| 410 |
+
@register_jitable
|
| 411 |
+
def random_zipf(bitgen, a):
|
| 412 |
+
am1 = a - 1.0
|
| 413 |
+
b = pow(2.0, am1)
|
| 414 |
+
Umin = pow(INT64_MAX, -am1)
|
| 415 |
+
while 1:
|
| 416 |
+
U01 = next_double(bitgen)
|
| 417 |
+
U = U01 * Umin + (1 - U01)
|
| 418 |
+
V = next_double(bitgen)
|
| 419 |
+
X = np.floor(pow(U, -1.0 / am1))
|
| 420 |
+
if (X > INT64_MAX or X < 1.0):
|
| 421 |
+
continue
|
| 422 |
+
|
| 423 |
+
T = pow(1.0 + 1.0 / X, am1)
|
| 424 |
+
if (V * X * (T - 1.0) / (b - 1.0) <= T / b):
|
| 425 |
+
return X
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
@register_jitable
|
| 429 |
+
def random_triangular(bitgen, left, mode,
|
| 430 |
+
right):
|
| 431 |
+
base = right - left
|
| 432 |
+
leftbase = mode - left
|
| 433 |
+
ratio = leftbase / base
|
| 434 |
+
leftprod = leftbase * base
|
| 435 |
+
rightprod = (right - mode) * base
|
| 436 |
+
|
| 437 |
+
U = next_double(bitgen)
|
| 438 |
+
if (U <= ratio):
|
| 439 |
+
return left + np.sqrt(U * leftprod)
|
| 440 |
+
else:
|
| 441 |
+
return right - np.sqrt((1.0 - U) * rightprod)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
@register_jitable
|
| 445 |
+
def random_loggam(x):
|
| 446 |
+
a = [8.333333333333333e-02, -2.777777777777778e-03,
|
| 447 |
+
7.936507936507937e-04, -5.952380952380952e-04,
|
| 448 |
+
8.417508417508418e-04, -1.917526917526918e-03,
|
| 449 |
+
6.410256410256410e-03, -2.955065359477124e-02,
|
| 450 |
+
1.796443723688307e-01, -1.39243221690590e+00]
|
| 451 |
+
|
| 452 |
+
if ((x == 1.0) or (x == 2.0)):
|
| 453 |
+
return 0.0
|
| 454 |
+
elif (x < 7.0):
|
| 455 |
+
n = int(7 - x)
|
| 456 |
+
else:
|
| 457 |
+
n = 0
|
| 458 |
+
|
| 459 |
+
x0 = x + n
|
| 460 |
+
x2 = (1.0 / x0) * (1.0 / x0)
|
| 461 |
+
# /* log(2 * M_PI) */
|
| 462 |
+
lg2pi = 1.8378770664093453e+00
|
| 463 |
+
gl0 = a[9]
|
| 464 |
+
|
| 465 |
+
for k in range(0, 9):
|
| 466 |
+
gl0 *= x2
|
| 467 |
+
gl0 += a[8 - k]
|
| 468 |
+
|
| 469 |
+
gl = gl0 / x0 + 0.5 * lg2pi + (x0 - 0.5) * np.log(x0) - x0
|
| 470 |
+
if (x < 7.0):
|
| 471 |
+
for k in range(1, n + 1):
|
| 472 |
+
gl = gl - np.log(x0 - 1.0)
|
| 473 |
+
x0 = x0 - 1.0
|
| 474 |
+
|
| 475 |
+
return gl
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
@register_jitable
|
| 479 |
+
def random_poisson_mult(bitgen, lam):
|
| 480 |
+
enlam = np.exp(-lam)
|
| 481 |
+
X = 0
|
| 482 |
+
prod = 1.0
|
| 483 |
+
while (1):
|
| 484 |
+
U = next_double(bitgen)
|
| 485 |
+
prod *= U
|
| 486 |
+
if (prod > enlam):
|
| 487 |
+
X += 1
|
| 488 |
+
else:
|
| 489 |
+
return X
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
@register_jitable
|
| 493 |
+
def random_poisson_ptrs(bitgen, lam):
|
| 494 |
+
|
| 495 |
+
slam = np.sqrt(lam)
|
| 496 |
+
loglam = np.log(lam)
|
| 497 |
+
b = 0.931 + 2.53 * slam
|
| 498 |
+
a = -0.059 + 0.02483 * b
|
| 499 |
+
invalpha = 1.1239 + 1.1328 / (b - 3.4)
|
| 500 |
+
vr = 0.9277 - 3.6224 / (b - 2)
|
| 501 |
+
|
| 502 |
+
while (1):
|
| 503 |
+
U = next_double(bitgen) - 0.5
|
| 504 |
+
V = next_double(bitgen)
|
| 505 |
+
us = 0.5 - np.fabs(U)
|
| 506 |
+
k = int((2 * a / us + b) * U + lam + 0.43)
|
| 507 |
+
if ((us >= 0.07) and (V <= vr)):
|
| 508 |
+
return k
|
| 509 |
+
|
| 510 |
+
if ((k < 0) or ((us < 0.013) and (V > us))):
|
| 511 |
+
continue
|
| 512 |
+
|
| 513 |
+
# /* log(V) == log(0.0) ok here */
|
| 514 |
+
# /* if U==0.0 so that us==0.0, log is ok since always returns */
|
| 515 |
+
if ((np.log(V) + np.log(invalpha) - np.log(a / (us * us) + b)) <=
|
| 516 |
+
(-lam + k * loglam - random_loggam(k + 1))):
|
| 517 |
+
return k
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
@register_jitable
|
| 521 |
+
def random_poisson(bitgen, lam):
|
| 522 |
+
if (lam >= 10):
|
| 523 |
+
return random_poisson_ptrs(bitgen, lam)
|
| 524 |
+
elif (lam == 0):
|
| 525 |
+
return 0
|
| 526 |
+
else:
|
| 527 |
+
return random_poisson_mult(bitgen, lam)
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
@register_jitable
|
| 531 |
+
def random_negative_binomial(bitgen, n, p):
|
| 532 |
+
Y = random_gamma(bitgen, n, (1 - p) / p)
|
| 533 |
+
return random_poisson(bitgen, Y)
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
@register_jitable
|
| 537 |
+
def random_noncentral_chisquare(bitgen, df, nonc):
|
| 538 |
+
if np.isnan(nonc):
|
| 539 |
+
return np.nan
|
| 540 |
+
|
| 541 |
+
if nonc == 0:
|
| 542 |
+
return random_chisquare(bitgen, df)
|
| 543 |
+
|
| 544 |
+
if 1 < df:
|
| 545 |
+
Chi2 = random_chisquare(bitgen, df - 1)
|
| 546 |
+
n = random_standard_normal(bitgen) + np.sqrt(nonc)
|
| 547 |
+
return Chi2 + n * n
|
| 548 |
+
else:
|
| 549 |
+
i = random_poisson(bitgen, nonc / 2.0)
|
| 550 |
+
return random_chisquare(bitgen, df + 2 * i)
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
@register_jitable
|
| 554 |
+
def random_noncentral_f(bitgen, dfnum, dfden, nonc):
|
| 555 |
+
t = random_noncentral_chisquare(bitgen, dfnum, nonc) * dfden
|
| 556 |
+
return t / (random_chisquare(bitgen, dfden) * dfnum)
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
@register_jitable
|
| 560 |
+
def random_logseries(bitgen, p):
|
| 561 |
+
r = np_log1p(-p)
|
| 562 |
+
|
| 563 |
+
while 1:
|
| 564 |
+
V = next_double(bitgen)
|
| 565 |
+
if (V >= p):
|
| 566 |
+
return 1
|
| 567 |
+
U = next_double(bitgen)
|
| 568 |
+
q = -np.expm1(r * U)
|
| 569 |
+
if (V <= q * q):
|
| 570 |
+
result = int64(np.floor(1 + np.log(V) / np.log(q)))
|
| 571 |
+
if result < 1 or V == 0.0:
|
| 572 |
+
continue
|
| 573 |
+
else:
|
| 574 |
+
return result
|
| 575 |
+
if (V >= q):
|
| 576 |
+
return 1
|
| 577 |
+
else:
|
| 578 |
+
return 2
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
if numpy_version < (2, 5):
|
| 582 |
+
@register_jitable
|
| 583 |
+
def _binomial_btpe_squeeze(A, xm, m, n, y, r, q):
|
| 584 |
+
# Generator path's case-52 Stirling squeeze, pre-2.5 form: all terms
|
| 585 |
+
# added, constant 13680. Deliberately matches NumPy < 2.5's
|
| 586 |
+
# random_binomial_btpe. Do not fix here.
|
| 587 |
+
x1 = y + 1
|
| 588 |
+
f1 = m + 1
|
| 589 |
+
z = n + 1 - m
|
| 590 |
+
w = n - y + 1
|
| 591 |
+
x2 = x1 * x1
|
| 592 |
+
f2 = f1 * f1
|
| 593 |
+
z2 = z * z
|
| 594 |
+
w2 = w * w
|
| 595 |
+
return A > (xm * np.log(f1 / x1) + (n - m + 0.5) * np.log(z / w) +
|
| 596 |
+
(y - m) * np.log(w * r / (x1 * q)) +
|
| 597 |
+
(13680. - (462. - (132. - (99. - 140. / f2) / f2) / f2)
|
| 598 |
+
/ f2) / f1 / 166320. +
|
| 599 |
+
(13680. - (462. - (132. - (99. - 140. / z2) / z2) / z2)
|
| 600 |
+
/ z2) / z / 166320. +
|
| 601 |
+
(13680. - (462. - (132. - (99. - 140. / x2) / x2) / x2)
|
| 602 |
+
/ x2) / x1 / 166320. +
|
| 603 |
+
(13680. - (462. - (132. - (99. - 140. / w2) / w2) / w2)
|
| 604 |
+
/ w2) / w / 166320.)
|
| 605 |
+
else:
|
| 606 |
+
@register_jitable
|
| 607 |
+
def _binomial_btpe_squeeze(A, xm, m, n, y, r, q):
|
| 608 |
+
# Generator path's case-52 Stirling squeeze, NumPy >= 2.5 form. Keep in
|
| 609 |
+
# sync with NumPy's random_binomial_btpe, which fixed the Stirling
|
| 610 |
+
# constant (13680 -> 13860) and subtracts the x1 and w terms.
|
| 611 |
+
# https://github.com/numpy/numpy/pull/31238
|
| 612 |
+
x1 = y + 1
|
| 613 |
+
f1 = m + 1
|
| 614 |
+
z = n + 1 - m
|
| 615 |
+
w = n - y + 1
|
| 616 |
+
x2 = x1 * x1
|
| 617 |
+
f2 = f1 * f1
|
| 618 |
+
z2 = z * z
|
| 619 |
+
w2 = w * w
|
| 620 |
+
return A > (xm * np.log(f1 / x1) + (n - m + 0.5) * np.log(z / w) +
|
| 621 |
+
(y - m) * np.log(w * r / (x1 * q)) +
|
| 622 |
+
(13860. - (462. - (132. - (99. - 140. / f2) / f2) / f2)
|
| 623 |
+
/ f2) / f1 / 166320. +
|
| 624 |
+
(13860. - (462. - (132. - (99. - 140. / z2) / z2) / z2)
|
| 625 |
+
/ z2) / z / 166320. -
|
| 626 |
+
(13860. - (462. - (132. - (99. - 140. / x2) / x2) / x2)
|
| 627 |
+
/ x2) / x1 / 166320. -
|
| 628 |
+
(13860. - (462. - (132. - (99. - 140. / w2) / w2) / w2)
|
| 629 |
+
/ w2) / w / 166320.)
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
_binomial_btpe_impl = make_binomial_btpe(next_double, _binomial_btpe_squeeze)
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
@register_jitable
|
| 636 |
+
def random_binomial_btpe(bitgen, n, p):
|
| 637 |
+
r = min(p, 1.0 - p)
|
| 638 |
+
y = _binomial_btpe_impl(bitgen, n, r)
|
| 639 |
+
return n - y if p > 0.5 else y
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
@register_jitable
|
| 643 |
+
def random_binomial_inversion(bitgen, n, p):
|
| 644 |
+
q = 1.0 - p
|
| 645 |
+
qn = np.exp(n * np.log(q))
|
| 646 |
+
_np = n * p
|
| 647 |
+
bound = min(n, _np + 10.0 * np.sqrt(_np * q + 1))
|
| 648 |
+
|
| 649 |
+
X = 0
|
| 650 |
+
px = qn
|
| 651 |
+
U = next_double(bitgen)
|
| 652 |
+
while (U > px):
|
| 653 |
+
X = X + 1
|
| 654 |
+
if (X > bound):
|
| 655 |
+
X = 0
|
| 656 |
+
px = qn
|
| 657 |
+
U = next_double(bitgen)
|
| 658 |
+
else:
|
| 659 |
+
U -= px
|
| 660 |
+
px = ((n - X + 1) * p * px) / (X * q)
|
| 661 |
+
|
| 662 |
+
return X
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
@register_jitable
|
| 666 |
+
def random_binomial(bitgen, n, p):
|
| 667 |
+
if ((n == 0) or (p == 0.0)):
|
| 668 |
+
return 0
|
| 669 |
+
|
| 670 |
+
if (p <= 0.5):
|
| 671 |
+
if (p * n <= 30.0):
|
| 672 |
+
return random_binomial_inversion(bitgen, n, p)
|
| 673 |
+
else:
|
| 674 |
+
return random_binomial_btpe(bitgen, n, p)
|
| 675 |
+
else:
|
| 676 |
+
q = 1.0 - p
|
| 677 |
+
if (q * n <= 30.0):
|
| 678 |
+
return n - random_binomial_inversion(bitgen, n, q)
|
| 679 |
+
else:
|
| 680 |
+
return n - random_binomial_btpe(bitgen, n, q)
|
shared/package-files/03/035415e61eb105ad5c4c87a38ec73535f8c6d0ca8c6f1a85a9789c0b638b36b3/idl.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.io` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = ["readsav"] # noqa: F822
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __dir__():
|
| 11 |
+
return __all__
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __getattr__(name):
|
| 15 |
+
return _sub_module_deprecation(sub_package="io", module="idl",
|
| 16 |
+
private_modules=["_idl"], all=__all__,
|
| 17 |
+
attribute=name)
|
shared/package-files/03/0356e6f80e58762b36899255236fabdda14a52e7d6478d8d67c62db6ba7c9b38/testutils.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def return_slice_of_data(arr, start_idx, end_idx):
|
| 2 |
+
return arr[start_idx:end_idx]
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def print_filename_and_raise(arr):
|
| 6 |
+
from joblib._memmapping_reducer import _get_backing_memmap
|
| 7 |
+
|
| 8 |
+
print(_get_backing_memmap(arr).filename)
|
| 9 |
+
raise ValueError
|
shared/package-files/03/03587701f3e110c6c6e4f2dd0ebd606e7c2dfc395a40e06016ec7942c2290a93/test_backend_tk.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 2 |
+
import importlib
|
| 3 |
+
import os
|
| 4 |
+
import platform
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
from matplotlib import _c_internal_utils
|
| 11 |
+
from matplotlib.testing import subprocess_run_helper
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
_test_timeout = 60 # A reasonably safe value for slower architectures.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _isolated_tk_test(success_count, func=None):
|
| 18 |
+
"""
|
| 19 |
+
A decorator to run *func* in a subprocess and assert that it prints
|
| 20 |
+
"success" *success_count* times and nothing on stderr.
|
| 21 |
+
|
| 22 |
+
TkAgg tests seem to have interactions between tests, so isolate each test
|
| 23 |
+
in a subprocess. See GH#18261
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
if func is None:
|
| 27 |
+
return functools.partial(_isolated_tk_test, success_count)
|
| 28 |
+
|
| 29 |
+
if "MPL_TEST_ESCAPE_HATCH" in os.environ:
|
| 30 |
+
# set in subprocess_run_helper() below
|
| 31 |
+
return func
|
| 32 |
+
|
| 33 |
+
@pytest.mark.skipif(
|
| 34 |
+
not importlib.util.find_spec('tkinter'),
|
| 35 |
+
reason="missing tkinter"
|
| 36 |
+
)
|
| 37 |
+
@pytest.mark.skipif(
|
| 38 |
+
sys.platform == "linux" and not _c_internal_utils.xdisplay_is_valid(),
|
| 39 |
+
reason="$DISPLAY is unset"
|
| 40 |
+
)
|
| 41 |
+
@pytest.mark.xfail( # https://github.com/actions/setup-python/issues/649
|
| 42 |
+
('TF_BUILD' in os.environ or 'GITHUB_ACTION' in os.environ) and
|
| 43 |
+
sys.platform == 'darwin' and sys.version_info[:2] < (3, 11),
|
| 44 |
+
reason='Tk version mismatch on Azure macOS CI'
|
| 45 |
+
)
|
| 46 |
+
@functools.wraps(func)
|
| 47 |
+
def test_func():
|
| 48 |
+
# even if the package exists, may not actually be importable this can
|
| 49 |
+
# be the case on some CI systems.
|
| 50 |
+
pytest.importorskip('tkinter')
|
| 51 |
+
try:
|
| 52 |
+
proc = subprocess_run_helper(
|
| 53 |
+
func, timeout=_test_timeout, extra_env=dict(
|
| 54 |
+
MPLBACKEND="TkAgg", MPL_TEST_ESCAPE_HATCH="1"))
|
| 55 |
+
except subprocess.TimeoutExpired:
|
| 56 |
+
pytest.fail("Subprocess timed out")
|
| 57 |
+
except subprocess.CalledProcessError as e:
|
| 58 |
+
pytest.fail("Subprocess failed to test intended behavior\n"
|
| 59 |
+
+ str(e.stderr))
|
| 60 |
+
else:
|
| 61 |
+
# macOS may actually emit irrelevant errors about Accelerated
|
| 62 |
+
# OpenGL vs. software OpenGL, or some permission error on Azure, so
|
| 63 |
+
# suppress them.
|
| 64 |
+
# Asserting stderr first (and printing it on failure) should be
|
| 65 |
+
# more helpful for debugging that printing a failed success count.
|
| 66 |
+
ignored_lines = ["OpenGL", "CFMessagePort: bootstrap_register",
|
| 67 |
+
"/usr/include/servers/bootstrap_defs.h"]
|
| 68 |
+
assert not [line for line in proc.stderr.splitlines()
|
| 69 |
+
if all(msg not in line for msg in ignored_lines)]
|
| 70 |
+
assert proc.stdout.count("success") == success_count
|
| 71 |
+
|
| 72 |
+
return test_func
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@_isolated_tk_test(success_count=6) # len(bad_boxes)
|
| 76 |
+
def test_blit():
|
| 77 |
+
import matplotlib.pyplot as plt
|
| 78 |
+
import numpy as np
|
| 79 |
+
import matplotlib.backends.backend_tkagg # noqa
|
| 80 |
+
from matplotlib.backends import _backend_tk, _tkagg
|
| 81 |
+
|
| 82 |
+
fig, ax = plt.subplots()
|
| 83 |
+
photoimage = fig.canvas._tkphoto
|
| 84 |
+
data = np.ones((4, 4, 4), dtype=np.uint8)
|
| 85 |
+
# Test out of bounds blitting.
|
| 86 |
+
bad_boxes = ((-1, 2, 0, 2),
|
| 87 |
+
(2, 0, 0, 2),
|
| 88 |
+
(1, 6, 0, 2),
|
| 89 |
+
(0, 2, -1, 2),
|
| 90 |
+
(0, 2, 2, 0),
|
| 91 |
+
(0, 2, 1, 6))
|
| 92 |
+
for bad_box in bad_boxes:
|
| 93 |
+
try:
|
| 94 |
+
_tkagg.blit(
|
| 95 |
+
photoimage.tk.interpaddr(), str(photoimage), data,
|
| 96 |
+
_tkagg.TK_PHOTO_COMPOSITE_OVERLAY, (0, 1, 2, 3), bad_box)
|
| 97 |
+
except ValueError:
|
| 98 |
+
print("success")
|
| 99 |
+
|
| 100 |
+
# Test blitting to a destroyed canvas.
|
| 101 |
+
plt.close(fig)
|
| 102 |
+
_backend_tk.blit(photoimage, data, (0, 1, 2, 3))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@_isolated_tk_test(success_count=1)
|
| 106 |
+
def test_figuremanager_preserves_host_mainloop():
|
| 107 |
+
import tkinter
|
| 108 |
+
import matplotlib.pyplot as plt
|
| 109 |
+
success = []
|
| 110 |
+
|
| 111 |
+
def do_plot():
|
| 112 |
+
plt.figure()
|
| 113 |
+
plt.plot([1, 2], [3, 5])
|
| 114 |
+
plt.close()
|
| 115 |
+
root.after(0, legitimate_quit)
|
| 116 |
+
|
| 117 |
+
def legitimate_quit():
|
| 118 |
+
root.quit()
|
| 119 |
+
success.append(True)
|
| 120 |
+
|
| 121 |
+
root = tkinter.Tk()
|
| 122 |
+
root.after(0, do_plot)
|
| 123 |
+
root.mainloop()
|
| 124 |
+
|
| 125 |
+
if success:
|
| 126 |
+
print("success")
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@pytest.mark.skipif(platform.python_implementation() != 'CPython',
|
| 130 |
+
reason='PyPy does not support Tkinter threading: '
|
| 131 |
+
'https://foss.heptapod.net/pypy/pypy/-/issues/1929')
|
| 132 |
+
@pytest.mark.flaky(reruns=3)
|
| 133 |
+
@_isolated_tk_test(success_count=1)
|
| 134 |
+
def test_figuremanager_cleans_own_mainloop():
|
| 135 |
+
import tkinter
|
| 136 |
+
import time
|
| 137 |
+
import matplotlib.pyplot as plt
|
| 138 |
+
import threading
|
| 139 |
+
from matplotlib.cbook import _get_running_interactive_framework
|
| 140 |
+
|
| 141 |
+
root = tkinter.Tk()
|
| 142 |
+
plt.plot([1, 2, 3], [1, 2, 5])
|
| 143 |
+
|
| 144 |
+
def target():
|
| 145 |
+
while not 'tk' == _get_running_interactive_framework():
|
| 146 |
+
time.sleep(.01)
|
| 147 |
+
plt.close()
|
| 148 |
+
if show_finished_event.wait():
|
| 149 |
+
print('success')
|
| 150 |
+
|
| 151 |
+
show_finished_event = threading.Event()
|
| 152 |
+
thread = threading.Thread(target=target, daemon=True)
|
| 153 |
+
thread.start()
|
| 154 |
+
plt.show(block=True) # Testing if this function hangs.
|
| 155 |
+
show_finished_event.set()
|
| 156 |
+
thread.join()
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@pytest.mark.flaky(reruns=3)
|
| 160 |
+
@_isolated_tk_test(success_count=0)
|
| 161 |
+
def test_never_update():
|
| 162 |
+
import tkinter
|
| 163 |
+
del tkinter.Misc.update
|
| 164 |
+
del tkinter.Misc.update_idletasks
|
| 165 |
+
|
| 166 |
+
import matplotlib.pyplot as plt
|
| 167 |
+
fig = plt.figure()
|
| 168 |
+
plt.show(block=False)
|
| 169 |
+
|
| 170 |
+
plt.draw() # Test FigureCanvasTkAgg.
|
| 171 |
+
fig.canvas.toolbar.configure_subplots() # Test NavigationToolbar2Tk.
|
| 172 |
+
# Test FigureCanvasTk filter_destroy callback
|
| 173 |
+
fig.canvas.get_tk_widget().after(100, plt.close, fig)
|
| 174 |
+
|
| 175 |
+
# Check for update() or update_idletasks() in the event queue, functionally
|
| 176 |
+
# equivalent to tkinter.Misc.update.
|
| 177 |
+
plt.show(block=True)
|
| 178 |
+
|
| 179 |
+
# Note that exceptions would be printed to stderr; _isolated_tk_test
|
| 180 |
+
# checks them.
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
@_isolated_tk_test(success_count=2)
|
| 184 |
+
def test_missing_back_button():
|
| 185 |
+
import matplotlib.pyplot as plt
|
| 186 |
+
from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk
|
| 187 |
+
|
| 188 |
+
class Toolbar(NavigationToolbar2Tk):
|
| 189 |
+
# Only display the buttons we need.
|
| 190 |
+
toolitems = [t for t in NavigationToolbar2Tk.toolitems if
|
| 191 |
+
t[0] in ('Home', 'Pan', 'Zoom')]
|
| 192 |
+
|
| 193 |
+
fig = plt.figure()
|
| 194 |
+
print("success")
|
| 195 |
+
Toolbar(fig.canvas, fig.canvas.manager.window) # This should not raise.
|
| 196 |
+
print("success")
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
@_isolated_tk_test(success_count=2)
|
| 200 |
+
def test_save_figure_return():
|
| 201 |
+
import matplotlib.pyplot as plt
|
| 202 |
+
from unittest import mock
|
| 203 |
+
fig = plt.figure()
|
| 204 |
+
prop = "tkinter.filedialog.asksaveasfilename"
|
| 205 |
+
with mock.patch(prop, return_value="foobar.png"):
|
| 206 |
+
fname = fig.canvas.manager.toolbar.save_figure()
|
| 207 |
+
os.remove("foobar.png")
|
| 208 |
+
assert fname == "foobar.png"
|
| 209 |
+
print("success")
|
| 210 |
+
with mock.patch(prop, return_value=""):
|
| 211 |
+
fname = fig.canvas.manager.toolbar.save_figure()
|
| 212 |
+
assert fname is None
|
| 213 |
+
print("success")
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@_isolated_tk_test(success_count=1)
|
| 217 |
+
def test_canvas_focus():
|
| 218 |
+
import tkinter as tk
|
| 219 |
+
import matplotlib.pyplot as plt
|
| 220 |
+
success = []
|
| 221 |
+
|
| 222 |
+
def check_focus():
|
| 223 |
+
tkcanvas = fig.canvas.get_tk_widget()
|
| 224 |
+
# Give the plot window time to appear
|
| 225 |
+
if not tkcanvas.winfo_viewable():
|
| 226 |
+
tkcanvas.wait_visibility()
|
| 227 |
+
# Make sure the canvas has the focus, so that it's able to receive
|
| 228 |
+
# keyboard events.
|
| 229 |
+
if tkcanvas.focus_lastfor() == tkcanvas:
|
| 230 |
+
success.append(True)
|
| 231 |
+
plt.close()
|
| 232 |
+
root.destroy()
|
| 233 |
+
|
| 234 |
+
root = tk.Tk()
|
| 235 |
+
fig = plt.figure()
|
| 236 |
+
plt.plot([1, 2, 3])
|
| 237 |
+
root.after(0, plt.show)
|
| 238 |
+
root.after(100, check_focus)
|
| 239 |
+
root.mainloop()
|
| 240 |
+
|
| 241 |
+
if success:
|
| 242 |
+
print("success")
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@_isolated_tk_test(success_count=2)
|
| 246 |
+
def test_embedding():
|
| 247 |
+
import tkinter as tk
|
| 248 |
+
from matplotlib.backends.backend_tkagg import (
|
| 249 |
+
FigureCanvasTkAgg, NavigationToolbar2Tk)
|
| 250 |
+
from matplotlib.backend_bases import key_press_handler
|
| 251 |
+
from matplotlib.figure import Figure
|
| 252 |
+
|
| 253 |
+
root = tk.Tk()
|
| 254 |
+
|
| 255 |
+
def test_figure(master):
|
| 256 |
+
fig = Figure()
|
| 257 |
+
ax = fig.add_subplot()
|
| 258 |
+
ax.plot([1, 2, 3])
|
| 259 |
+
|
| 260 |
+
canvas = FigureCanvasTkAgg(fig, master=master)
|
| 261 |
+
canvas.draw()
|
| 262 |
+
canvas.mpl_connect("key_press_event", key_press_handler)
|
| 263 |
+
canvas.get_tk_widget().pack(expand=True, fill="both")
|
| 264 |
+
|
| 265 |
+
toolbar = NavigationToolbar2Tk(canvas, master, pack_toolbar=False)
|
| 266 |
+
toolbar.pack(expand=True, fill="x")
|
| 267 |
+
|
| 268 |
+
canvas.get_tk_widget().forget()
|
| 269 |
+
toolbar.forget()
|
| 270 |
+
|
| 271 |
+
test_figure(root)
|
| 272 |
+
print("success")
|
| 273 |
+
|
| 274 |
+
# Test with a dark button color. Doesn't actually check whether the icon
|
| 275 |
+
# color becomes lighter, just that the code doesn't break.
|
| 276 |
+
|
| 277 |
+
root.tk_setPalette(background="sky blue", selectColor="midnight blue",
|
| 278 |
+
foreground="white")
|
| 279 |
+
test_figure(root)
|
| 280 |
+
print("success")
|
shared/package-files/03/035a2ecc772fbc43c641b0fa2dcecd147f0e44d61a88d4f22fc0d17a0c5cb40d/native_functions.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Optional, Union
|
| 2 |
+
|
| 3 |
+
import torchgen.api.meta as meta
|
| 4 |
+
import torchgen.api.structured as structured
|
| 5 |
+
from torchgen.api.types import kernel_signature
|
| 6 |
+
|
| 7 |
+
from torchgen.context import with_native_function_and_index
|
| 8 |
+
from torchgen.model import BackendIndex, NativeFunction, NativeFunctionsGroup
|
| 9 |
+
from torchgen.utils import mapMaybe
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@with_native_function_and_index
|
| 13 |
+
def gen_unstructured(f: NativeFunction, backend_index: BackendIndex) -> Optional[str]:
|
| 14 |
+
sig = kernel_signature(f, backend_index)
|
| 15 |
+
metadata = backend_index.get_kernel(f)
|
| 16 |
+
if metadata is None:
|
| 17 |
+
return None
|
| 18 |
+
if "legacy::" in metadata.kernel:
|
| 19 |
+
return None
|
| 20 |
+
else:
|
| 21 |
+
prefix = "static" if backend_index.external else "TORCH_API"
|
| 22 |
+
return f"{prefix} {sig.decl(name=metadata.kernel)};"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@with_native_function_and_index
|
| 26 |
+
def gen_structured(g: NativeFunctionsGroup, backend_index: BackendIndex) -> List[str]:
|
| 27 |
+
meta_name = meta.name(g)
|
| 28 |
+
out_args = structured.impl_arguments(g)
|
| 29 |
+
metadata = backend_index.get_kernel(g)
|
| 30 |
+
if metadata is None:
|
| 31 |
+
return []
|
| 32 |
+
prefix = "" if backend_index.external else "TORCH_API "
|
| 33 |
+
return [
|
| 34 |
+
f"""\
|
| 35 |
+
struct {prefix}structured_{metadata.kernel} : public at::meta::structured_{meta_name} {{
|
| 36 |
+
void impl({', '.join(a.decl() for a in out_args)});
|
| 37 |
+
}};
|
| 38 |
+
"""
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# Generates NativeFunctions.h, a list of forward declarations of all
|
| 43 |
+
# actual kernel definitions we keep in aten/src/ATen/native/
|
| 44 |
+
@with_native_function_and_index
|
| 45 |
+
def compute_native_function_declaration(
|
| 46 |
+
g: Union[NativeFunctionsGroup, NativeFunction], backend_index: BackendIndex
|
| 47 |
+
) -> List[str]:
|
| 48 |
+
metadata = backend_index.get_kernel(g)
|
| 49 |
+
if isinstance(g, NativeFunctionsGroup):
|
| 50 |
+
if metadata is not None and metadata.structured:
|
| 51 |
+
if backend_index.external:
|
| 52 |
+
# Structured hasn't been tested with external backends yet.
|
| 53 |
+
raise AssertionError(
|
| 54 |
+
"Structured external backend functions are not implemented yet."
|
| 55 |
+
)
|
| 56 |
+
else:
|
| 57 |
+
return gen_structured(g, backend_index)
|
| 58 |
+
else:
|
| 59 |
+
return list(
|
| 60 |
+
mapMaybe(lambda f: gen_unstructured(f, backend_index), g.functions())
|
| 61 |
+
)
|
| 62 |
+
else:
|
| 63 |
+
x = gen_unstructured(g, backend_index)
|
| 64 |
+
return [] if x is None else [x]
|
shared/package-files/03/035d95e258d6c6f5da48527bde61d214ad9834efa4f1ac7a31ee321164ec238b/test_sparsifiers.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for the sparsifier computation functions."""
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import networkx as nx
|
| 5 |
+
from networkx.utils import py_random_state
|
| 6 |
+
|
| 7 |
+
_seed = 2
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _test_spanner(G, spanner, stretch, weight=None):
|
| 11 |
+
"""Test whether a spanner is valid.
|
| 12 |
+
|
| 13 |
+
This function tests whether the given spanner is a subgraph of the
|
| 14 |
+
given graph G with the same node set. It also tests for all shortest
|
| 15 |
+
paths whether they adhere to the given stretch.
|
| 16 |
+
|
| 17 |
+
Parameters
|
| 18 |
+
----------
|
| 19 |
+
G : NetworkX graph
|
| 20 |
+
The original graph for which the spanner was constructed.
|
| 21 |
+
|
| 22 |
+
spanner : NetworkX graph
|
| 23 |
+
The spanner to be tested.
|
| 24 |
+
|
| 25 |
+
stretch : float
|
| 26 |
+
The proclaimed stretch of the spanner.
|
| 27 |
+
|
| 28 |
+
weight : object
|
| 29 |
+
The edge attribute to use as distance.
|
| 30 |
+
"""
|
| 31 |
+
# check node set
|
| 32 |
+
assert set(G.nodes()) == set(spanner.nodes())
|
| 33 |
+
|
| 34 |
+
# check edge set and weights
|
| 35 |
+
for u, v in spanner.edges():
|
| 36 |
+
assert G.has_edge(u, v)
|
| 37 |
+
if weight:
|
| 38 |
+
assert spanner[u][v][weight] == G[u][v][weight]
|
| 39 |
+
|
| 40 |
+
# check connectivity and stretch
|
| 41 |
+
original_length = dict(nx.shortest_path_length(G, weight=weight))
|
| 42 |
+
spanner_length = dict(nx.shortest_path_length(spanner, weight=weight))
|
| 43 |
+
for u in G.nodes():
|
| 44 |
+
for v in G.nodes():
|
| 45 |
+
if u in original_length and v in original_length[u]:
|
| 46 |
+
assert spanner_length[u][v] <= stretch * original_length[u][v]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@py_random_state(1)
|
| 50 |
+
def _assign_random_weights(G, seed=None):
|
| 51 |
+
"""Assigns random weights to the edges of a graph.
|
| 52 |
+
|
| 53 |
+
Parameters
|
| 54 |
+
----------
|
| 55 |
+
|
| 56 |
+
G : NetworkX graph
|
| 57 |
+
The original graph for which the spanner was constructed.
|
| 58 |
+
|
| 59 |
+
seed : integer, random_state, or None (default)
|
| 60 |
+
Indicator of random number generation state.
|
| 61 |
+
See :ref:`Randomness<randomness>`.
|
| 62 |
+
"""
|
| 63 |
+
for u, v in G.edges():
|
| 64 |
+
G[u][v]["weight"] = seed.random()
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_spanner_trivial():
|
| 68 |
+
"""Test a trivial spanner with stretch 1."""
|
| 69 |
+
G = nx.complete_graph(20)
|
| 70 |
+
spanner = nx.spanner(G, 1, seed=_seed)
|
| 71 |
+
|
| 72 |
+
for u, v in G.edges:
|
| 73 |
+
assert spanner.has_edge(u, v)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def test_spanner_unweighted_complete_graph():
|
| 77 |
+
"""Test spanner construction on a complete unweighted graph."""
|
| 78 |
+
G = nx.complete_graph(20)
|
| 79 |
+
|
| 80 |
+
spanner = nx.spanner(G, 4, seed=_seed)
|
| 81 |
+
_test_spanner(G, spanner, 4)
|
| 82 |
+
|
| 83 |
+
spanner = nx.spanner(G, 10, seed=_seed)
|
| 84 |
+
_test_spanner(G, spanner, 10)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_spanner_weighted_complete_graph():
|
| 88 |
+
"""Test spanner construction on a complete weighted graph."""
|
| 89 |
+
G = nx.complete_graph(20)
|
| 90 |
+
_assign_random_weights(G, seed=_seed)
|
| 91 |
+
|
| 92 |
+
spanner = nx.spanner(G, 4, weight="weight", seed=_seed)
|
| 93 |
+
_test_spanner(G, spanner, 4, weight="weight")
|
| 94 |
+
|
| 95 |
+
spanner = nx.spanner(G, 10, weight="weight", seed=_seed)
|
| 96 |
+
_test_spanner(G, spanner, 10, weight="weight")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_spanner_unweighted_gnp_graph():
|
| 100 |
+
"""Test spanner construction on an unweighted gnp graph."""
|
| 101 |
+
G = nx.gnp_random_graph(20, 0.4, seed=_seed)
|
| 102 |
+
|
| 103 |
+
spanner = nx.spanner(G, 4, seed=_seed)
|
| 104 |
+
_test_spanner(G, spanner, 4)
|
| 105 |
+
|
| 106 |
+
spanner = nx.spanner(G, 10, seed=_seed)
|
| 107 |
+
_test_spanner(G, spanner, 10)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_spanner_weighted_gnp_graph():
|
| 111 |
+
"""Test spanner construction on an weighted gnp graph."""
|
| 112 |
+
G = nx.gnp_random_graph(20, 0.4, seed=_seed)
|
| 113 |
+
_assign_random_weights(G, seed=_seed)
|
| 114 |
+
|
| 115 |
+
spanner = nx.spanner(G, 4, weight="weight", seed=_seed)
|
| 116 |
+
_test_spanner(G, spanner, 4, weight="weight")
|
| 117 |
+
|
| 118 |
+
spanner = nx.spanner(G, 10, weight="weight", seed=_seed)
|
| 119 |
+
_test_spanner(G, spanner, 10, weight="weight")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_spanner_unweighted_disconnected_graph():
|
| 123 |
+
"""Test spanner construction on a disconnected graph."""
|
| 124 |
+
G = nx.disjoint_union(nx.complete_graph(10), nx.complete_graph(10))
|
| 125 |
+
|
| 126 |
+
spanner = nx.spanner(G, 4, seed=_seed)
|
| 127 |
+
_test_spanner(G, spanner, 4)
|
| 128 |
+
|
| 129 |
+
spanner = nx.spanner(G, 10, seed=_seed)
|
| 130 |
+
_test_spanner(G, spanner, 10)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_spanner_invalid_stretch():
|
| 134 |
+
"""Check whether an invalid stretch is caught."""
|
| 135 |
+
with pytest.raises(ValueError):
|
| 136 |
+
G = nx.empty_graph()
|
| 137 |
+
nx.spanner(G, 0)
|
shared/package-files/03/03606ac3664f19fc2472f2e633fdbad766d6f1b4e2414f21c1234692ff91dc55/multilabel_margin_loss_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 at::Tensor multilabel_margin_loss_backward_cpu(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, const at::Tensor & is_target);
|
| 20 |
+
TORCH_API at::Tensor & multilabel_margin_loss_backward_cpu_out(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, const at::Tensor & is_target, at::Tensor & grad_input);
|
| 21 |
+
TORCH_API at::Tensor multilabel_margin_loss_backward_cuda(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, const at::Tensor & is_target);
|
| 22 |
+
TORCH_API at::Tensor & multilabel_margin_loss_backward_cuda_out(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, const at::Tensor & is_target, at::Tensor & grad_input);
|
| 23 |
+
} // namespace native
|
| 24 |
+
} // namespace at
|
shared/package-files/03/036238ba9b78a8da259571a9c33aea83b334a0a1c9859c750543080678d1228c/dispatcher.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from warnings import warn
|
| 4 |
+
import inspect
|
| 5 |
+
from .conflict import ordering, ambiguities, super_signature, AmbiguityWarning
|
| 6 |
+
from .utils import expand_tuples
|
| 7 |
+
import itertools as itl
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class MDNotImplementedError(NotImplementedError):
|
| 11 |
+
""" A NotImplementedError for multiple dispatch """
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
### Functions for on_ambiguity
|
| 15 |
+
|
| 16 |
+
def ambiguity_warn(dispatcher, ambiguities):
|
| 17 |
+
""" Raise warning when ambiguity is detected
|
| 18 |
+
|
| 19 |
+
Parameters
|
| 20 |
+
----------
|
| 21 |
+
dispatcher : Dispatcher
|
| 22 |
+
The dispatcher on which the ambiguity was detected
|
| 23 |
+
ambiguities : set
|
| 24 |
+
Set of type signature pairs that are ambiguous within this dispatcher
|
| 25 |
+
|
| 26 |
+
See Also:
|
| 27 |
+
Dispatcher.add
|
| 28 |
+
warning_text
|
| 29 |
+
"""
|
| 30 |
+
warn(warning_text(dispatcher.name, ambiguities), AmbiguityWarning)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class RaiseNotImplementedError:
|
| 34 |
+
"""Raise ``NotImplementedError`` when called."""
|
| 35 |
+
|
| 36 |
+
def __init__(self, dispatcher):
|
| 37 |
+
self.dispatcher = dispatcher
|
| 38 |
+
|
| 39 |
+
def __call__(self, *args, **kwargs):
|
| 40 |
+
types = tuple(type(a) for a in args)
|
| 41 |
+
raise NotImplementedError(
|
| 42 |
+
"Ambiguous signature for %s: <%s>" % (
|
| 43 |
+
self.dispatcher.name, str_signature(types)
|
| 44 |
+
))
|
| 45 |
+
|
| 46 |
+
def ambiguity_register_error_ignore_dup(dispatcher, ambiguities):
|
| 47 |
+
"""
|
| 48 |
+
If super signature for ambiguous types is duplicate types, ignore it.
|
| 49 |
+
Else, register instance of ``RaiseNotImplementedError`` for ambiguous types.
|
| 50 |
+
|
| 51 |
+
Parameters
|
| 52 |
+
----------
|
| 53 |
+
dispatcher : Dispatcher
|
| 54 |
+
The dispatcher on which the ambiguity was detected
|
| 55 |
+
ambiguities : set
|
| 56 |
+
Set of type signature pairs that are ambiguous within this dispatcher
|
| 57 |
+
|
| 58 |
+
See Also:
|
| 59 |
+
Dispatcher.add
|
| 60 |
+
ambiguity_warn
|
| 61 |
+
"""
|
| 62 |
+
for amb in ambiguities:
|
| 63 |
+
signature = tuple(super_signature(amb))
|
| 64 |
+
if len(set(signature)) == 1:
|
| 65 |
+
continue
|
| 66 |
+
dispatcher.add(
|
| 67 |
+
signature, RaiseNotImplementedError(dispatcher),
|
| 68 |
+
on_ambiguity=ambiguity_register_error_ignore_dup
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
###
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
_unresolved_dispatchers: set[Dispatcher] = set()
|
| 75 |
+
_resolve = [True]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def halt_ordering():
|
| 79 |
+
_resolve[0] = False
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def restart_ordering(on_ambiguity=ambiguity_warn):
|
| 83 |
+
_resolve[0] = True
|
| 84 |
+
while _unresolved_dispatchers:
|
| 85 |
+
dispatcher = _unresolved_dispatchers.pop()
|
| 86 |
+
dispatcher.reorder(on_ambiguity=on_ambiguity)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class Dispatcher:
|
| 90 |
+
""" Dispatch methods based on type signature
|
| 91 |
+
|
| 92 |
+
Use ``dispatch`` to add implementations
|
| 93 |
+
|
| 94 |
+
Examples
|
| 95 |
+
--------
|
| 96 |
+
|
| 97 |
+
>>> from sympy.multipledispatch import dispatch
|
| 98 |
+
>>> @dispatch(int)
|
| 99 |
+
... def f(x):
|
| 100 |
+
... return x + 1
|
| 101 |
+
|
| 102 |
+
>>> @dispatch(float)
|
| 103 |
+
... def f(x): # noqa: F811
|
| 104 |
+
... return x - 1
|
| 105 |
+
|
| 106 |
+
>>> f(3)
|
| 107 |
+
4
|
| 108 |
+
>>> f(3.0)
|
| 109 |
+
2.0
|
| 110 |
+
"""
|
| 111 |
+
__slots__ = '__name__', 'name', 'funcs', 'ordering', '_cache', 'doc'
|
| 112 |
+
|
| 113 |
+
def __init__(self, name, doc=None):
|
| 114 |
+
self.name = self.__name__ = name
|
| 115 |
+
self.funcs = {}
|
| 116 |
+
self._cache = {}
|
| 117 |
+
self.ordering = []
|
| 118 |
+
self.doc = doc
|
| 119 |
+
|
| 120 |
+
def register(self, *types, **kwargs):
|
| 121 |
+
""" Register dispatcher with new implementation
|
| 122 |
+
|
| 123 |
+
>>> from sympy.multipledispatch.dispatcher import Dispatcher
|
| 124 |
+
>>> f = Dispatcher('f')
|
| 125 |
+
>>> @f.register(int)
|
| 126 |
+
... def inc(x):
|
| 127 |
+
... return x + 1
|
| 128 |
+
|
| 129 |
+
>>> @f.register(float)
|
| 130 |
+
... def dec(x):
|
| 131 |
+
... return x - 1
|
| 132 |
+
|
| 133 |
+
>>> @f.register(list)
|
| 134 |
+
... @f.register(tuple)
|
| 135 |
+
... def reverse(x):
|
| 136 |
+
... return x[::-1]
|
| 137 |
+
|
| 138 |
+
>>> f(1)
|
| 139 |
+
2
|
| 140 |
+
|
| 141 |
+
>>> f(1.0)
|
| 142 |
+
0.0
|
| 143 |
+
|
| 144 |
+
>>> f([1, 2, 3])
|
| 145 |
+
[3, 2, 1]
|
| 146 |
+
"""
|
| 147 |
+
def _(func):
|
| 148 |
+
self.add(types, func, **kwargs)
|
| 149 |
+
return func
|
| 150 |
+
return _
|
| 151 |
+
|
| 152 |
+
@classmethod
|
| 153 |
+
def get_func_params(cls, func):
|
| 154 |
+
if hasattr(inspect, "signature"):
|
| 155 |
+
sig = inspect.signature(func)
|
| 156 |
+
return sig.parameters.values()
|
| 157 |
+
|
| 158 |
+
@classmethod
|
| 159 |
+
def get_func_annotations(cls, func):
|
| 160 |
+
""" Get annotations of function positional parameters
|
| 161 |
+
"""
|
| 162 |
+
params = cls.get_func_params(func)
|
| 163 |
+
if params:
|
| 164 |
+
Parameter = inspect.Parameter
|
| 165 |
+
|
| 166 |
+
params = (param for param in params
|
| 167 |
+
if param.kind in
|
| 168 |
+
(Parameter.POSITIONAL_ONLY,
|
| 169 |
+
Parameter.POSITIONAL_OR_KEYWORD))
|
| 170 |
+
|
| 171 |
+
annotations = tuple(
|
| 172 |
+
param.annotation
|
| 173 |
+
for param in params)
|
| 174 |
+
|
| 175 |
+
if not any(ann is Parameter.empty for ann in annotations):
|
| 176 |
+
return annotations
|
| 177 |
+
|
| 178 |
+
def add(self, signature, func, on_ambiguity=ambiguity_warn):
|
| 179 |
+
""" Add new types/method pair to dispatcher
|
| 180 |
+
|
| 181 |
+
>>> from sympy.multipledispatch import Dispatcher
|
| 182 |
+
>>> D = Dispatcher('add')
|
| 183 |
+
>>> D.add((int, int), lambda x, y: x + y)
|
| 184 |
+
>>> D.add((float, float), lambda x, y: x + y)
|
| 185 |
+
|
| 186 |
+
>>> D(1, 2)
|
| 187 |
+
3
|
| 188 |
+
>>> D(1, 2.0)
|
| 189 |
+
Traceback (most recent call last):
|
| 190 |
+
...
|
| 191 |
+
NotImplementedError: Could not find signature for add: <int, float>
|
| 192 |
+
|
| 193 |
+
When ``add`` detects a warning it calls the ``on_ambiguity`` callback
|
| 194 |
+
with a dispatcher/itself, and a set of ambiguous type signature pairs
|
| 195 |
+
as inputs. See ``ambiguity_warn`` for an example.
|
| 196 |
+
"""
|
| 197 |
+
# Handle annotations
|
| 198 |
+
if not signature:
|
| 199 |
+
annotations = self.get_func_annotations(func)
|
| 200 |
+
if annotations:
|
| 201 |
+
signature = annotations
|
| 202 |
+
|
| 203 |
+
# Handle union types
|
| 204 |
+
if any(isinstance(typ, tuple) for typ in signature):
|
| 205 |
+
for typs in expand_tuples(signature):
|
| 206 |
+
self.add(typs, func, on_ambiguity)
|
| 207 |
+
return
|
| 208 |
+
|
| 209 |
+
for typ in signature:
|
| 210 |
+
if not isinstance(typ, type):
|
| 211 |
+
str_sig = ', '.join(c.__name__ if isinstance(c, type)
|
| 212 |
+
else str(c) for c in signature)
|
| 213 |
+
raise TypeError("Tried to dispatch on non-type: %s\n"
|
| 214 |
+
"In signature: <%s>\n"
|
| 215 |
+
"In function: %s" %
|
| 216 |
+
(typ, str_sig, self.name))
|
| 217 |
+
|
| 218 |
+
self.funcs[signature] = func
|
| 219 |
+
self.reorder(on_ambiguity=on_ambiguity)
|
| 220 |
+
self._cache.clear()
|
| 221 |
+
|
| 222 |
+
def reorder(self, on_ambiguity=ambiguity_warn):
|
| 223 |
+
if _resolve[0]:
|
| 224 |
+
self.ordering = ordering(self.funcs)
|
| 225 |
+
amb = ambiguities(self.funcs)
|
| 226 |
+
if amb:
|
| 227 |
+
on_ambiguity(self, amb)
|
| 228 |
+
else:
|
| 229 |
+
_unresolved_dispatchers.add(self)
|
| 230 |
+
|
| 231 |
+
def __call__(self, *args, **kwargs):
|
| 232 |
+
types = tuple([type(arg) for arg in args])
|
| 233 |
+
try:
|
| 234 |
+
func = self._cache[types]
|
| 235 |
+
except KeyError:
|
| 236 |
+
func = self.dispatch(*types)
|
| 237 |
+
if not func:
|
| 238 |
+
raise NotImplementedError(
|
| 239 |
+
'Could not find signature for %s: <%s>' %
|
| 240 |
+
(self.name, str_signature(types)))
|
| 241 |
+
self._cache[types] = func
|
| 242 |
+
try:
|
| 243 |
+
return func(*args, **kwargs)
|
| 244 |
+
|
| 245 |
+
except MDNotImplementedError:
|
| 246 |
+
funcs = self.dispatch_iter(*types)
|
| 247 |
+
next(funcs) # burn first
|
| 248 |
+
for func in funcs:
|
| 249 |
+
try:
|
| 250 |
+
return func(*args, **kwargs)
|
| 251 |
+
except MDNotImplementedError:
|
| 252 |
+
pass
|
| 253 |
+
raise NotImplementedError("Matching functions for "
|
| 254 |
+
"%s: <%s> found, but none completed successfully"
|
| 255 |
+
% (self.name, str_signature(types)))
|
| 256 |
+
|
| 257 |
+
def __str__(self):
|
| 258 |
+
return "<dispatched %s>" % self.name
|
| 259 |
+
__repr__ = __str__
|
| 260 |
+
|
| 261 |
+
def dispatch(self, *types):
|
| 262 |
+
""" Deterimine appropriate implementation for this type signature
|
| 263 |
+
|
| 264 |
+
This method is internal. Users should call this object as a function.
|
| 265 |
+
Implementation resolution occurs within the ``__call__`` method.
|
| 266 |
+
|
| 267 |
+
>>> from sympy.multipledispatch import dispatch
|
| 268 |
+
>>> @dispatch(int)
|
| 269 |
+
... def inc(x):
|
| 270 |
+
... return x + 1
|
| 271 |
+
|
| 272 |
+
>>> implementation = inc.dispatch(int)
|
| 273 |
+
>>> implementation(3)
|
| 274 |
+
4
|
| 275 |
+
|
| 276 |
+
>>> print(inc.dispatch(float))
|
| 277 |
+
None
|
| 278 |
+
|
| 279 |
+
See Also:
|
| 280 |
+
``sympy.multipledispatch.conflict`` - module to determine resolution order
|
| 281 |
+
"""
|
| 282 |
+
|
| 283 |
+
if types in self.funcs:
|
| 284 |
+
return self.funcs[types]
|
| 285 |
+
|
| 286 |
+
try:
|
| 287 |
+
return next(self.dispatch_iter(*types))
|
| 288 |
+
except StopIteration:
|
| 289 |
+
return None
|
| 290 |
+
|
| 291 |
+
def dispatch_iter(self, *types):
|
| 292 |
+
n = len(types)
|
| 293 |
+
for signature in self.ordering:
|
| 294 |
+
if len(signature) == n and all(map(issubclass, types, signature)):
|
| 295 |
+
result = self.funcs[signature]
|
| 296 |
+
yield result
|
| 297 |
+
|
| 298 |
+
def resolve(self, types):
|
| 299 |
+
""" Deterimine appropriate implementation for this type signature
|
| 300 |
+
|
| 301 |
+
.. deprecated:: 0.4.4
|
| 302 |
+
Use ``dispatch(*types)`` instead
|
| 303 |
+
"""
|
| 304 |
+
warn("resolve() is deprecated, use dispatch(*types)",
|
| 305 |
+
DeprecationWarning)
|
| 306 |
+
|
| 307 |
+
return self.dispatch(*types)
|
| 308 |
+
|
| 309 |
+
def __getstate__(self):
|
| 310 |
+
return {'name': self.name,
|
| 311 |
+
'funcs': self.funcs}
|
| 312 |
+
|
| 313 |
+
def __setstate__(self, d):
|
| 314 |
+
self.name = d['name']
|
| 315 |
+
self.funcs = d['funcs']
|
| 316 |
+
self.ordering = ordering(self.funcs)
|
| 317 |
+
self._cache = {}
|
| 318 |
+
|
| 319 |
+
@property
|
| 320 |
+
def __doc__(self):
|
| 321 |
+
docs = ["Multiply dispatched method: %s" % self.name]
|
| 322 |
+
|
| 323 |
+
if self.doc:
|
| 324 |
+
docs.append(self.doc)
|
| 325 |
+
|
| 326 |
+
other = []
|
| 327 |
+
for sig in self.ordering[::-1]:
|
| 328 |
+
func = self.funcs[sig]
|
| 329 |
+
if func.__doc__:
|
| 330 |
+
s = 'Inputs: <%s>\n' % str_signature(sig)
|
| 331 |
+
s += '-' * len(s) + '\n'
|
| 332 |
+
s += func.__doc__.strip()
|
| 333 |
+
docs.append(s)
|
| 334 |
+
else:
|
| 335 |
+
other.append(str_signature(sig))
|
| 336 |
+
|
| 337 |
+
if other:
|
| 338 |
+
docs.append('Other signatures:\n ' + '\n '.join(other))
|
| 339 |
+
|
| 340 |
+
return '\n\n'.join(docs)
|
| 341 |
+
|
| 342 |
+
def _help(self, *args):
|
| 343 |
+
return self.dispatch(*map(type, args)).__doc__
|
| 344 |
+
|
| 345 |
+
def help(self, *args, **kwargs):
|
| 346 |
+
""" Print docstring for the function corresponding to inputs """
|
| 347 |
+
print(self._help(*args))
|
| 348 |
+
|
| 349 |
+
def _source(self, *args):
|
| 350 |
+
func = self.dispatch(*map(type, args))
|
| 351 |
+
if not func:
|
| 352 |
+
raise TypeError("No function found")
|
| 353 |
+
return source(func)
|
| 354 |
+
|
| 355 |
+
def source(self, *args, **kwargs):
|
| 356 |
+
""" Print source code for the function corresponding to inputs """
|
| 357 |
+
print(self._source(*args))
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def source(func):
|
| 361 |
+
s = 'File: %s\n\n' % inspect.getsourcefile(func)
|
| 362 |
+
s = s + inspect.getsource(func)
|
| 363 |
+
return s
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
class MethodDispatcher(Dispatcher):
|
| 367 |
+
""" Dispatch methods based on type signature
|
| 368 |
+
|
| 369 |
+
See Also:
|
| 370 |
+
Dispatcher
|
| 371 |
+
"""
|
| 372 |
+
|
| 373 |
+
@classmethod
|
| 374 |
+
def get_func_params(cls, func):
|
| 375 |
+
if hasattr(inspect, "signature"):
|
| 376 |
+
sig = inspect.signature(func)
|
| 377 |
+
return itl.islice(sig.parameters.values(), 1, None)
|
| 378 |
+
|
| 379 |
+
def __get__(self, instance, owner):
|
| 380 |
+
self.obj = instance
|
| 381 |
+
self.cls = owner
|
| 382 |
+
return self
|
| 383 |
+
|
| 384 |
+
def __call__(self, *args, **kwargs):
|
| 385 |
+
types = tuple([type(arg) for arg in args])
|
| 386 |
+
func = self.dispatch(*types)
|
| 387 |
+
if not func:
|
| 388 |
+
raise NotImplementedError('Could not find signature for %s: <%s>' %
|
| 389 |
+
(self.name, str_signature(types)))
|
| 390 |
+
return func(self.obj, *args, **kwargs)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def str_signature(sig):
|
| 394 |
+
""" String representation of type signature
|
| 395 |
+
|
| 396 |
+
>>> from sympy.multipledispatch.dispatcher import str_signature
|
| 397 |
+
>>> str_signature((int, float))
|
| 398 |
+
'int, float'
|
| 399 |
+
"""
|
| 400 |
+
return ', '.join(cls.__name__ for cls in sig)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def warning_text(name, amb):
|
| 404 |
+
""" The text for ambiguity warnings """
|
| 405 |
+
text = "\nAmbiguities exist in dispatched function %s\n\n" % (name)
|
| 406 |
+
text += "The following signatures may result in ambiguous behavior:\n"
|
| 407 |
+
for pair in amb:
|
| 408 |
+
text += "\t" + \
|
| 409 |
+
', '.join('[' + str_signature(s) + ']' for s in pair) + "\n"
|
| 410 |
+
text += "\n\nConsider making the following additions:\n\n"
|
| 411 |
+
text += '\n\n'.join(['@dispatch(' + str_signature(super_signature(s))
|
| 412 |
+
+ ')\ndef %s(...)' % name for s in amb])
|
| 413 |
+
return text
|
shared/package-files/03/0367001befa2ee94d5a2520af7a9b136e093b4bbe16cb551a89e0c01f5940444/test_coloring.py
ADDED
|
@@ -0,0 +1,865 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Greedy coloring test suite.
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import itertools
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
import networkx as nx
|
| 10 |
+
|
| 11 |
+
is_coloring = nx.algorithms.coloring.equitable_coloring.is_coloring
|
| 12 |
+
is_equitable = nx.algorithms.coloring.equitable_coloring.is_equitable
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
ALL_STRATEGIES = [
|
| 16 |
+
"largest_first",
|
| 17 |
+
"random_sequential",
|
| 18 |
+
"smallest_last",
|
| 19 |
+
"independent_set",
|
| 20 |
+
"connected_sequential_bfs",
|
| 21 |
+
"connected_sequential_dfs",
|
| 22 |
+
"connected_sequential",
|
| 23 |
+
"saturation_largest_first",
|
| 24 |
+
"DSATUR",
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
# List of strategies where interchange=True results in an error
|
| 28 |
+
INTERCHANGE_INVALID = ["independent_set", "saturation_largest_first", "DSATUR"]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class TestColoring:
|
| 32 |
+
def test_basic_cases(self):
|
| 33 |
+
def check_basic_case(graph_func, n_nodes, strategy, interchange):
|
| 34 |
+
graph = graph_func()
|
| 35 |
+
coloring = nx.coloring.greedy_color(
|
| 36 |
+
graph, strategy=strategy, interchange=interchange
|
| 37 |
+
)
|
| 38 |
+
assert verify_length(coloring, n_nodes)
|
| 39 |
+
assert verify_coloring(graph, coloring)
|
| 40 |
+
|
| 41 |
+
for graph_func, n_nodes in BASIC_TEST_CASES.items():
|
| 42 |
+
for interchange in [True, False]:
|
| 43 |
+
for strategy in ALL_STRATEGIES:
|
| 44 |
+
check_basic_case(graph_func, n_nodes, strategy, False)
|
| 45 |
+
if strategy not in INTERCHANGE_INVALID:
|
| 46 |
+
check_basic_case(graph_func, n_nodes, strategy, True)
|
| 47 |
+
|
| 48 |
+
def test_special_cases(self):
|
| 49 |
+
def check_special_case(strategy, graph_func, interchange, colors):
|
| 50 |
+
graph = graph_func()
|
| 51 |
+
coloring = nx.coloring.greedy_color(
|
| 52 |
+
graph, strategy=strategy, interchange=interchange
|
| 53 |
+
)
|
| 54 |
+
if not hasattr(colors, "__len__"):
|
| 55 |
+
colors = [colors]
|
| 56 |
+
assert any(verify_length(coloring, n_colors) for n_colors in colors)
|
| 57 |
+
assert verify_coloring(graph, coloring)
|
| 58 |
+
|
| 59 |
+
for strategy, arglist in SPECIAL_TEST_CASES.items():
|
| 60 |
+
for args in arglist:
|
| 61 |
+
check_special_case(strategy, args[0], args[1], args[2])
|
| 62 |
+
|
| 63 |
+
def test_interchange_invalid(self):
|
| 64 |
+
graph = one_node_graph()
|
| 65 |
+
for strategy in INTERCHANGE_INVALID:
|
| 66 |
+
pytest.raises(
|
| 67 |
+
nx.NetworkXPointlessConcept,
|
| 68 |
+
nx.coloring.greedy_color,
|
| 69 |
+
graph,
|
| 70 |
+
strategy=strategy,
|
| 71 |
+
interchange=True,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def test_bad_inputs(self):
|
| 75 |
+
graph = one_node_graph()
|
| 76 |
+
pytest.raises(
|
| 77 |
+
nx.NetworkXError,
|
| 78 |
+
nx.coloring.greedy_color,
|
| 79 |
+
graph,
|
| 80 |
+
strategy="invalid strategy",
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
def test_strategy_as_function(self):
|
| 84 |
+
graph = lf_shc()
|
| 85 |
+
colors_1 = nx.coloring.greedy_color(graph, "largest_first")
|
| 86 |
+
colors_2 = nx.coloring.greedy_color(graph, nx.coloring.strategy_largest_first)
|
| 87 |
+
assert colors_1 == colors_2
|
| 88 |
+
|
| 89 |
+
def test_seed_argument(self):
|
| 90 |
+
graph = lf_shc()
|
| 91 |
+
rs = nx.coloring.strategy_random_sequential
|
| 92 |
+
c1 = nx.coloring.greedy_color(graph, lambda g, c: rs(g, c, seed=1))
|
| 93 |
+
for u, v in graph.edges:
|
| 94 |
+
assert c1[u] != c1[v]
|
| 95 |
+
|
| 96 |
+
def test_is_coloring(self):
|
| 97 |
+
G = nx.Graph()
|
| 98 |
+
G.add_edges_from([(0, 1), (1, 2)])
|
| 99 |
+
coloring = {0: 0, 1: 1, 2: 0}
|
| 100 |
+
assert is_coloring(G, coloring)
|
| 101 |
+
|
| 102 |
+
coloring[0] = 1
|
| 103 |
+
assert not is_coloring(G, coloring)
|
| 104 |
+
assert not is_equitable(G, coloring)
|
| 105 |
+
|
| 106 |
+
def test_is_equitable(self):
|
| 107 |
+
G = nx.Graph()
|
| 108 |
+
G.add_edges_from([(0, 1), (1, 2)])
|
| 109 |
+
coloring = {0: 0, 1: 1, 2: 0}
|
| 110 |
+
assert is_equitable(G, coloring)
|
| 111 |
+
|
| 112 |
+
G.add_edges_from([(2, 3), (2, 4), (2, 5)])
|
| 113 |
+
coloring[3] = 1
|
| 114 |
+
coloring[4] = 1
|
| 115 |
+
coloring[5] = 1
|
| 116 |
+
assert is_coloring(G, coloring)
|
| 117 |
+
assert not is_equitable(G, coloring)
|
| 118 |
+
|
| 119 |
+
def test_num_colors(self):
|
| 120 |
+
G = nx.Graph()
|
| 121 |
+
G.add_edges_from([(0, 1), (0, 2), (0, 3)])
|
| 122 |
+
pytest.raises(nx.NetworkXAlgorithmError, nx.coloring.equitable_color, G, 2)
|
| 123 |
+
|
| 124 |
+
def test_equitable_color(self):
|
| 125 |
+
G = nx.fast_gnp_random_graph(n=10, p=0.2, seed=42)
|
| 126 |
+
coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
|
| 127 |
+
assert is_equitable(G, coloring)
|
| 128 |
+
|
| 129 |
+
def test_equitable_color_empty(self):
|
| 130 |
+
G = nx.empty_graph()
|
| 131 |
+
coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
|
| 132 |
+
assert is_equitable(G, coloring)
|
| 133 |
+
|
| 134 |
+
def test_equitable_color_large(self):
|
| 135 |
+
G = nx.fast_gnp_random_graph(100, 0.1, seed=42)
|
| 136 |
+
coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
|
| 137 |
+
assert is_equitable(G, coloring, num_colors=max_degree(G) + 1)
|
| 138 |
+
|
| 139 |
+
def test_case_V_plus_not_in_A_cal(self):
|
| 140 |
+
# Hand crafted case to avoid the easy case.
|
| 141 |
+
L = {
|
| 142 |
+
0: [2, 5],
|
| 143 |
+
1: [3, 4],
|
| 144 |
+
2: [0, 8],
|
| 145 |
+
3: [1, 7],
|
| 146 |
+
4: [1, 6],
|
| 147 |
+
5: [0, 6],
|
| 148 |
+
6: [4, 5],
|
| 149 |
+
7: [3],
|
| 150 |
+
8: [2],
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
F = {
|
| 154 |
+
# Color 0
|
| 155 |
+
0: 0,
|
| 156 |
+
1: 0,
|
| 157 |
+
# Color 1
|
| 158 |
+
2: 1,
|
| 159 |
+
3: 1,
|
| 160 |
+
4: 1,
|
| 161 |
+
5: 1,
|
| 162 |
+
# Color 2
|
| 163 |
+
6: 2,
|
| 164 |
+
7: 2,
|
| 165 |
+
8: 2,
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
|
| 169 |
+
N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
|
| 170 |
+
H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
|
| 171 |
+
|
| 172 |
+
nx.algorithms.coloring.equitable_coloring.procedure_P(
|
| 173 |
+
V_minus=0, V_plus=1, N=N, H=H, F=F, C=C, L=L
|
| 174 |
+
)
|
| 175 |
+
check_state(L=L, N=N, H=H, F=F, C=C)
|
| 176 |
+
|
| 177 |
+
def test_cast_no_solo(self):
|
| 178 |
+
L = {
|
| 179 |
+
0: [8, 9],
|
| 180 |
+
1: [10, 11],
|
| 181 |
+
2: [8],
|
| 182 |
+
3: [9],
|
| 183 |
+
4: [10, 11],
|
| 184 |
+
5: [8],
|
| 185 |
+
6: [9],
|
| 186 |
+
7: [10, 11],
|
| 187 |
+
8: [0, 2, 5],
|
| 188 |
+
9: [0, 3, 6],
|
| 189 |
+
10: [1, 4, 7],
|
| 190 |
+
11: [1, 4, 7],
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
F = {0: 0, 1: 0, 2: 2, 3: 2, 4: 2, 5: 3, 6: 3, 7: 3, 8: 1, 9: 1, 10: 1, 11: 1}
|
| 194 |
+
|
| 195 |
+
C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
|
| 196 |
+
N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
|
| 197 |
+
H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
|
| 198 |
+
|
| 199 |
+
nx.algorithms.coloring.equitable_coloring.procedure_P(
|
| 200 |
+
V_minus=0, V_plus=1, N=N, H=H, F=F, C=C, L=L
|
| 201 |
+
)
|
| 202 |
+
check_state(L=L, N=N, H=H, F=F, C=C)
|
| 203 |
+
|
| 204 |
+
def test_hard_prob(self):
|
| 205 |
+
# Tests for two levels of recursion.
|
| 206 |
+
num_colors, s = 5, 5
|
| 207 |
+
|
| 208 |
+
G = nx.Graph()
|
| 209 |
+
G.add_edges_from(
|
| 210 |
+
[
|
| 211 |
+
(0, 10),
|
| 212 |
+
(0, 11),
|
| 213 |
+
(0, 12),
|
| 214 |
+
(0, 23),
|
| 215 |
+
(10, 4),
|
| 216 |
+
(10, 9),
|
| 217 |
+
(10, 20),
|
| 218 |
+
(11, 4),
|
| 219 |
+
(11, 8),
|
| 220 |
+
(11, 16),
|
| 221 |
+
(12, 9),
|
| 222 |
+
(12, 22),
|
| 223 |
+
(12, 23),
|
| 224 |
+
(23, 7),
|
| 225 |
+
(1, 17),
|
| 226 |
+
(1, 18),
|
| 227 |
+
(1, 19),
|
| 228 |
+
(1, 24),
|
| 229 |
+
(17, 5),
|
| 230 |
+
(17, 13),
|
| 231 |
+
(17, 22),
|
| 232 |
+
(18, 5),
|
| 233 |
+
(19, 5),
|
| 234 |
+
(19, 6),
|
| 235 |
+
(19, 8),
|
| 236 |
+
(24, 7),
|
| 237 |
+
(24, 16),
|
| 238 |
+
(2, 4),
|
| 239 |
+
(2, 13),
|
| 240 |
+
(2, 14),
|
| 241 |
+
(2, 15),
|
| 242 |
+
(4, 6),
|
| 243 |
+
(13, 5),
|
| 244 |
+
(13, 21),
|
| 245 |
+
(14, 6),
|
| 246 |
+
(14, 15),
|
| 247 |
+
(15, 6),
|
| 248 |
+
(15, 21),
|
| 249 |
+
(3, 16),
|
| 250 |
+
(3, 20),
|
| 251 |
+
(3, 21),
|
| 252 |
+
(3, 22),
|
| 253 |
+
(16, 8),
|
| 254 |
+
(20, 8),
|
| 255 |
+
(21, 9),
|
| 256 |
+
(22, 7),
|
| 257 |
+
]
|
| 258 |
+
)
|
| 259 |
+
F = {node: node // s for node in range(num_colors * s)}
|
| 260 |
+
F[s - 1] = num_colors - 1
|
| 261 |
+
|
| 262 |
+
params = make_params_from_graph(G=G, F=F)
|
| 263 |
+
|
| 264 |
+
nx.algorithms.coloring.equitable_coloring.procedure_P(
|
| 265 |
+
V_minus=0, V_plus=num_colors - 1, **params
|
| 266 |
+
)
|
| 267 |
+
check_state(**params)
|
| 268 |
+
|
| 269 |
+
def test_hardest_prob(self):
|
| 270 |
+
# Tests for two levels of recursion.
|
| 271 |
+
num_colors, s = 10, 4
|
| 272 |
+
|
| 273 |
+
G = nx.Graph()
|
| 274 |
+
G.add_edges_from(
|
| 275 |
+
[
|
| 276 |
+
(0, 19),
|
| 277 |
+
(0, 24),
|
| 278 |
+
(0, 29),
|
| 279 |
+
(0, 30),
|
| 280 |
+
(0, 35),
|
| 281 |
+
(19, 3),
|
| 282 |
+
(19, 7),
|
| 283 |
+
(19, 9),
|
| 284 |
+
(19, 15),
|
| 285 |
+
(19, 21),
|
| 286 |
+
(19, 24),
|
| 287 |
+
(19, 30),
|
| 288 |
+
(19, 38),
|
| 289 |
+
(24, 5),
|
| 290 |
+
(24, 11),
|
| 291 |
+
(24, 13),
|
| 292 |
+
(24, 20),
|
| 293 |
+
(24, 30),
|
| 294 |
+
(24, 37),
|
| 295 |
+
(24, 38),
|
| 296 |
+
(29, 6),
|
| 297 |
+
(29, 10),
|
| 298 |
+
(29, 13),
|
| 299 |
+
(29, 15),
|
| 300 |
+
(29, 16),
|
| 301 |
+
(29, 17),
|
| 302 |
+
(29, 20),
|
| 303 |
+
(29, 26),
|
| 304 |
+
(30, 6),
|
| 305 |
+
(30, 10),
|
| 306 |
+
(30, 15),
|
| 307 |
+
(30, 22),
|
| 308 |
+
(30, 23),
|
| 309 |
+
(30, 39),
|
| 310 |
+
(35, 6),
|
| 311 |
+
(35, 9),
|
| 312 |
+
(35, 14),
|
| 313 |
+
(35, 18),
|
| 314 |
+
(35, 22),
|
| 315 |
+
(35, 23),
|
| 316 |
+
(35, 25),
|
| 317 |
+
(35, 27),
|
| 318 |
+
(1, 20),
|
| 319 |
+
(1, 26),
|
| 320 |
+
(1, 31),
|
| 321 |
+
(1, 34),
|
| 322 |
+
(1, 38),
|
| 323 |
+
(20, 4),
|
| 324 |
+
(20, 8),
|
| 325 |
+
(20, 14),
|
| 326 |
+
(20, 18),
|
| 327 |
+
(20, 28),
|
| 328 |
+
(20, 33),
|
| 329 |
+
(26, 7),
|
| 330 |
+
(26, 10),
|
| 331 |
+
(26, 14),
|
| 332 |
+
(26, 18),
|
| 333 |
+
(26, 21),
|
| 334 |
+
(26, 32),
|
| 335 |
+
(26, 39),
|
| 336 |
+
(31, 5),
|
| 337 |
+
(31, 8),
|
| 338 |
+
(31, 13),
|
| 339 |
+
(31, 16),
|
| 340 |
+
(31, 17),
|
| 341 |
+
(31, 21),
|
| 342 |
+
(31, 25),
|
| 343 |
+
(31, 27),
|
| 344 |
+
(34, 7),
|
| 345 |
+
(34, 8),
|
| 346 |
+
(34, 13),
|
| 347 |
+
(34, 18),
|
| 348 |
+
(34, 22),
|
| 349 |
+
(34, 23),
|
| 350 |
+
(34, 25),
|
| 351 |
+
(34, 27),
|
| 352 |
+
(38, 4),
|
| 353 |
+
(38, 9),
|
| 354 |
+
(38, 12),
|
| 355 |
+
(38, 14),
|
| 356 |
+
(38, 21),
|
| 357 |
+
(38, 27),
|
| 358 |
+
(2, 3),
|
| 359 |
+
(2, 18),
|
| 360 |
+
(2, 21),
|
| 361 |
+
(2, 28),
|
| 362 |
+
(2, 32),
|
| 363 |
+
(2, 33),
|
| 364 |
+
(2, 36),
|
| 365 |
+
(2, 37),
|
| 366 |
+
(2, 39),
|
| 367 |
+
(3, 5),
|
| 368 |
+
(3, 9),
|
| 369 |
+
(3, 13),
|
| 370 |
+
(3, 22),
|
| 371 |
+
(3, 23),
|
| 372 |
+
(3, 25),
|
| 373 |
+
(3, 27),
|
| 374 |
+
(18, 6),
|
| 375 |
+
(18, 11),
|
| 376 |
+
(18, 15),
|
| 377 |
+
(18, 39),
|
| 378 |
+
(21, 4),
|
| 379 |
+
(21, 10),
|
| 380 |
+
(21, 14),
|
| 381 |
+
(21, 36),
|
| 382 |
+
(28, 6),
|
| 383 |
+
(28, 10),
|
| 384 |
+
(28, 14),
|
| 385 |
+
(28, 16),
|
| 386 |
+
(28, 17),
|
| 387 |
+
(28, 25),
|
| 388 |
+
(28, 27),
|
| 389 |
+
(32, 5),
|
| 390 |
+
(32, 10),
|
| 391 |
+
(32, 12),
|
| 392 |
+
(32, 16),
|
| 393 |
+
(32, 17),
|
| 394 |
+
(32, 22),
|
| 395 |
+
(32, 23),
|
| 396 |
+
(33, 7),
|
| 397 |
+
(33, 10),
|
| 398 |
+
(33, 12),
|
| 399 |
+
(33, 16),
|
| 400 |
+
(33, 17),
|
| 401 |
+
(33, 25),
|
| 402 |
+
(33, 27),
|
| 403 |
+
(36, 5),
|
| 404 |
+
(36, 8),
|
| 405 |
+
(36, 15),
|
| 406 |
+
(36, 16),
|
| 407 |
+
(36, 17),
|
| 408 |
+
(36, 25),
|
| 409 |
+
(36, 27),
|
| 410 |
+
(37, 5),
|
| 411 |
+
(37, 11),
|
| 412 |
+
(37, 15),
|
| 413 |
+
(37, 16),
|
| 414 |
+
(37, 17),
|
| 415 |
+
(37, 22),
|
| 416 |
+
(37, 23),
|
| 417 |
+
(39, 7),
|
| 418 |
+
(39, 8),
|
| 419 |
+
(39, 15),
|
| 420 |
+
(39, 22),
|
| 421 |
+
(39, 23),
|
| 422 |
+
]
|
| 423 |
+
)
|
| 424 |
+
F = {node: node // s for node in range(num_colors * s)}
|
| 425 |
+
F[s - 1] = num_colors - 1 # V- = 0, V+ = num_colors - 1
|
| 426 |
+
|
| 427 |
+
params = make_params_from_graph(G=G, F=F)
|
| 428 |
+
|
| 429 |
+
nx.algorithms.coloring.equitable_coloring.procedure_P(
|
| 430 |
+
V_minus=0, V_plus=num_colors - 1, **params
|
| 431 |
+
)
|
| 432 |
+
check_state(**params)
|
| 433 |
+
|
| 434 |
+
def test_strategy_saturation_largest_first(self):
|
| 435 |
+
def color_remaining_nodes(
|
| 436 |
+
G,
|
| 437 |
+
colored_nodes,
|
| 438 |
+
full_color_assignment=None,
|
| 439 |
+
nodes_to_add_between_calls=1,
|
| 440 |
+
):
|
| 441 |
+
color_assignments = []
|
| 442 |
+
aux_colored_nodes = colored_nodes.copy()
|
| 443 |
+
|
| 444 |
+
node_iterator = nx.algorithms.coloring.greedy_coloring.strategy_saturation_largest_first(
|
| 445 |
+
G, aux_colored_nodes
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
for u in node_iterator:
|
| 449 |
+
# Set to keep track of colors of neighbours
|
| 450 |
+
neighbour_colors = {
|
| 451 |
+
aux_colored_nodes[v] for v in G[u] if v in aux_colored_nodes
|
| 452 |
+
}
|
| 453 |
+
# Find the first unused color.
|
| 454 |
+
for color in itertools.count():
|
| 455 |
+
if color not in neighbour_colors:
|
| 456 |
+
break
|
| 457 |
+
aux_colored_nodes[u] = color
|
| 458 |
+
color_assignments.append((u, color))
|
| 459 |
+
|
| 460 |
+
# Color nodes between iterations
|
| 461 |
+
for i in range(nodes_to_add_between_calls - 1):
|
| 462 |
+
if not len(color_assignments) + len(colored_nodes) >= len(
|
| 463 |
+
full_color_assignment
|
| 464 |
+
):
|
| 465 |
+
full_color_assignment_node, color = full_color_assignment[
|
| 466 |
+
len(color_assignments) + len(colored_nodes)
|
| 467 |
+
]
|
| 468 |
+
|
| 469 |
+
# Assign the new color to the current node.
|
| 470 |
+
aux_colored_nodes[full_color_assignment_node] = color
|
| 471 |
+
color_assignments.append((full_color_assignment_node, color))
|
| 472 |
+
|
| 473 |
+
return color_assignments, aux_colored_nodes
|
| 474 |
+
|
| 475 |
+
for G, _, _ in SPECIAL_TEST_CASES["saturation_largest_first"]:
|
| 476 |
+
G = G()
|
| 477 |
+
|
| 478 |
+
# Check that function still works when nodes are colored between iterations
|
| 479 |
+
for nodes_to_add_between_calls in range(1, 5):
|
| 480 |
+
# Get a full color assignment, (including the order in which nodes were colored)
|
| 481 |
+
colored_nodes = {}
|
| 482 |
+
full_color_assignment, full_colored_nodes = color_remaining_nodes(
|
| 483 |
+
G, colored_nodes
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
# For each node in the color assignment, add it to colored_nodes and re-run the function
|
| 487 |
+
for ind, (node, color) in enumerate(full_color_assignment):
|
| 488 |
+
colored_nodes[node] = color
|
| 489 |
+
|
| 490 |
+
(
|
| 491 |
+
partial_color_assignment,
|
| 492 |
+
partial_colored_nodes,
|
| 493 |
+
) = color_remaining_nodes(
|
| 494 |
+
G,
|
| 495 |
+
colored_nodes,
|
| 496 |
+
full_color_assignment=full_color_assignment,
|
| 497 |
+
nodes_to_add_between_calls=nodes_to_add_between_calls,
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
# Check that the color assignment and order of remaining nodes are the same
|
| 501 |
+
assert full_color_assignment[ind + 1 :] == partial_color_assignment
|
| 502 |
+
assert full_colored_nodes == partial_colored_nodes
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
# ############################ Utility functions ############################
|
| 506 |
+
def verify_coloring(graph, coloring):
|
| 507 |
+
for node in graph.nodes():
|
| 508 |
+
if node not in coloring:
|
| 509 |
+
return False
|
| 510 |
+
|
| 511 |
+
color = coloring[node]
|
| 512 |
+
for neighbor in graph.neighbors(node):
|
| 513 |
+
if coloring[neighbor] == color:
|
| 514 |
+
return False
|
| 515 |
+
|
| 516 |
+
return True
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def verify_length(coloring, expected):
|
| 520 |
+
coloring = dict_to_sets(coloring)
|
| 521 |
+
return len(coloring) == expected
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def dict_to_sets(colors):
|
| 525 |
+
if len(colors) == 0:
|
| 526 |
+
return []
|
| 527 |
+
|
| 528 |
+
k = max(colors.values()) + 1
|
| 529 |
+
sets = [set() for _ in range(k)]
|
| 530 |
+
|
| 531 |
+
for node, color in colors.items():
|
| 532 |
+
sets[color].add(node)
|
| 533 |
+
|
| 534 |
+
return sets
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
# ############################ Graph Generation ############################
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
def empty_graph():
|
| 541 |
+
return nx.Graph()
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def one_node_graph():
|
| 545 |
+
graph = nx.Graph()
|
| 546 |
+
graph.add_nodes_from([1])
|
| 547 |
+
return graph
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def two_node_graph():
|
| 551 |
+
graph = nx.Graph()
|
| 552 |
+
graph.add_nodes_from([1, 2])
|
| 553 |
+
graph.add_edges_from([(1, 2)])
|
| 554 |
+
return graph
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def three_node_clique():
|
| 558 |
+
graph = nx.Graph()
|
| 559 |
+
graph.add_nodes_from([1, 2, 3])
|
| 560 |
+
graph.add_edges_from([(1, 2), (1, 3), (2, 3)])
|
| 561 |
+
return graph
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
def disconnected():
|
| 565 |
+
graph = nx.Graph()
|
| 566 |
+
graph.add_edges_from([(1, 2), (2, 3), (4, 5), (5, 6)])
|
| 567 |
+
return graph
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def rs_shc():
|
| 571 |
+
graph = nx.Graph()
|
| 572 |
+
graph.add_nodes_from([1, 2, 3, 4])
|
| 573 |
+
graph.add_edges_from([(1, 2), (2, 3), (3, 4)])
|
| 574 |
+
return graph
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def slf_shc():
|
| 578 |
+
graph = nx.Graph()
|
| 579 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
|
| 580 |
+
graph.add_edges_from(
|
| 581 |
+
[(1, 2), (1, 5), (1, 6), (2, 3), (2, 7), (3, 4), (3, 7), (4, 5), (4, 6), (5, 6)]
|
| 582 |
+
)
|
| 583 |
+
return graph
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def slf_hc():
|
| 587 |
+
graph = nx.Graph()
|
| 588 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8])
|
| 589 |
+
graph.add_edges_from(
|
| 590 |
+
[
|
| 591 |
+
(1, 2),
|
| 592 |
+
(1, 3),
|
| 593 |
+
(1, 4),
|
| 594 |
+
(1, 5),
|
| 595 |
+
(2, 3),
|
| 596 |
+
(2, 4),
|
| 597 |
+
(2, 6),
|
| 598 |
+
(5, 7),
|
| 599 |
+
(5, 8),
|
| 600 |
+
(6, 7),
|
| 601 |
+
(6, 8),
|
| 602 |
+
(7, 8),
|
| 603 |
+
]
|
| 604 |
+
)
|
| 605 |
+
return graph
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def lf_shc():
|
| 609 |
+
graph = nx.Graph()
|
| 610 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
|
| 611 |
+
graph.add_edges_from([(6, 1), (1, 4), (4, 3), (3, 2), (2, 5)])
|
| 612 |
+
return graph
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def lf_hc():
|
| 616 |
+
graph = nx.Graph()
|
| 617 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
|
| 618 |
+
graph.add_edges_from(
|
| 619 |
+
[
|
| 620 |
+
(1, 7),
|
| 621 |
+
(1, 6),
|
| 622 |
+
(1, 3),
|
| 623 |
+
(1, 4),
|
| 624 |
+
(7, 2),
|
| 625 |
+
(2, 6),
|
| 626 |
+
(2, 3),
|
| 627 |
+
(2, 5),
|
| 628 |
+
(5, 3),
|
| 629 |
+
(5, 4),
|
| 630 |
+
(4, 3),
|
| 631 |
+
]
|
| 632 |
+
)
|
| 633 |
+
return graph
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
def sl_shc():
|
| 637 |
+
graph = nx.Graph()
|
| 638 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
|
| 639 |
+
graph.add_edges_from(
|
| 640 |
+
[(1, 2), (1, 3), (2, 3), (1, 4), (2, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
|
| 641 |
+
)
|
| 642 |
+
return graph
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
def sl_hc():
|
| 646 |
+
graph = nx.Graph()
|
| 647 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8])
|
| 648 |
+
graph.add_edges_from(
|
| 649 |
+
[
|
| 650 |
+
(1, 2),
|
| 651 |
+
(1, 3),
|
| 652 |
+
(1, 5),
|
| 653 |
+
(1, 7),
|
| 654 |
+
(2, 3),
|
| 655 |
+
(2, 4),
|
| 656 |
+
(2, 8),
|
| 657 |
+
(8, 4),
|
| 658 |
+
(8, 6),
|
| 659 |
+
(8, 7),
|
| 660 |
+
(7, 5),
|
| 661 |
+
(7, 6),
|
| 662 |
+
(3, 4),
|
| 663 |
+
(4, 6),
|
| 664 |
+
(6, 5),
|
| 665 |
+
(5, 3),
|
| 666 |
+
]
|
| 667 |
+
)
|
| 668 |
+
return graph
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
def gis_shc():
|
| 672 |
+
graph = nx.Graph()
|
| 673 |
+
graph.add_nodes_from([1, 2, 3, 4])
|
| 674 |
+
graph.add_edges_from([(1, 2), (2, 3), (3, 4)])
|
| 675 |
+
return graph
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def gis_hc():
|
| 679 |
+
graph = nx.Graph()
|
| 680 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
|
| 681 |
+
graph.add_edges_from([(1, 5), (2, 5), (3, 6), (4, 6), (5, 6)])
|
| 682 |
+
return graph
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
def cs_shc():
|
| 686 |
+
graph = nx.Graph()
|
| 687 |
+
graph.add_nodes_from([1, 2, 3, 4, 5])
|
| 688 |
+
graph.add_edges_from([(1, 2), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (4, 5)])
|
| 689 |
+
return graph
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
def rsi_shc():
|
| 693 |
+
graph = nx.Graph()
|
| 694 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6])
|
| 695 |
+
graph.add_edges_from(
|
| 696 |
+
[(1, 2), (1, 5), (1, 6), (2, 3), (3, 4), (4, 5), (4, 6), (5, 6)]
|
| 697 |
+
)
|
| 698 |
+
return graph
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
def lfi_shc():
|
| 702 |
+
graph = nx.Graph()
|
| 703 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
|
| 704 |
+
graph.add_edges_from(
|
| 705 |
+
[(1, 2), (1, 5), (1, 6), (2, 3), (2, 7), (3, 4), (3, 7), (4, 5), (4, 6), (5, 6)]
|
| 706 |
+
)
|
| 707 |
+
return graph
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def lfi_hc():
|
| 711 |
+
graph = nx.Graph()
|
| 712 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
|
| 713 |
+
graph.add_edges_from(
|
| 714 |
+
[
|
| 715 |
+
(1, 2),
|
| 716 |
+
(1, 5),
|
| 717 |
+
(1, 6),
|
| 718 |
+
(1, 7),
|
| 719 |
+
(2, 3),
|
| 720 |
+
(2, 8),
|
| 721 |
+
(2, 9),
|
| 722 |
+
(3, 4),
|
| 723 |
+
(3, 8),
|
| 724 |
+
(3, 9),
|
| 725 |
+
(4, 5),
|
| 726 |
+
(4, 6),
|
| 727 |
+
(4, 7),
|
| 728 |
+
(5, 6),
|
| 729 |
+
]
|
| 730 |
+
)
|
| 731 |
+
return graph
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
def sli_shc():
|
| 735 |
+
graph = nx.Graph()
|
| 736 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
|
| 737 |
+
graph.add_edges_from(
|
| 738 |
+
[
|
| 739 |
+
(1, 2),
|
| 740 |
+
(1, 3),
|
| 741 |
+
(1, 5),
|
| 742 |
+
(1, 7),
|
| 743 |
+
(2, 3),
|
| 744 |
+
(2, 6),
|
| 745 |
+
(3, 4),
|
| 746 |
+
(4, 5),
|
| 747 |
+
(4, 6),
|
| 748 |
+
(5, 7),
|
| 749 |
+
(6, 7),
|
| 750 |
+
]
|
| 751 |
+
)
|
| 752 |
+
return graph
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
def sli_hc():
|
| 756 |
+
graph = nx.Graph()
|
| 757 |
+
graph.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9])
|
| 758 |
+
graph.add_edges_from(
|
| 759 |
+
[
|
| 760 |
+
(1, 2),
|
| 761 |
+
(1, 3),
|
| 762 |
+
(1, 4),
|
| 763 |
+
(1, 5),
|
| 764 |
+
(2, 3),
|
| 765 |
+
(2, 7),
|
| 766 |
+
(2, 8),
|
| 767 |
+
(2, 9),
|
| 768 |
+
(3, 6),
|
| 769 |
+
(3, 7),
|
| 770 |
+
(3, 9),
|
| 771 |
+
(4, 5),
|
| 772 |
+
(4, 6),
|
| 773 |
+
(4, 8),
|
| 774 |
+
(4, 9),
|
| 775 |
+
(5, 6),
|
| 776 |
+
(5, 7),
|
| 777 |
+
(5, 8),
|
| 778 |
+
(6, 7),
|
| 779 |
+
(6, 9),
|
| 780 |
+
(7, 8),
|
| 781 |
+
(8, 9),
|
| 782 |
+
]
|
| 783 |
+
)
|
| 784 |
+
return graph
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
# --------------------------------------------------------------------------
|
| 788 |
+
# Basic tests for all strategies
|
| 789 |
+
# For each basic graph function, specify the number of expected colors.
|
| 790 |
+
BASIC_TEST_CASES = {
|
| 791 |
+
empty_graph: 0,
|
| 792 |
+
one_node_graph: 1,
|
| 793 |
+
two_node_graph: 2,
|
| 794 |
+
disconnected: 2,
|
| 795 |
+
three_node_clique: 3,
|
| 796 |
+
}
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
# --------------------------------------------------------------------------
|
| 800 |
+
# Special test cases. Each strategy has a list of tuples of the form
|
| 801 |
+
# (graph function, interchange, valid # of colors)
|
| 802 |
+
SPECIAL_TEST_CASES = {
|
| 803 |
+
"random_sequential": [
|
| 804 |
+
(rs_shc, False, (2, 3)),
|
| 805 |
+
(rs_shc, True, 2),
|
| 806 |
+
(rsi_shc, True, (3, 4)),
|
| 807 |
+
],
|
| 808 |
+
"saturation_largest_first": [(slf_shc, False, (3, 4)), (slf_hc, False, 4)],
|
| 809 |
+
"largest_first": [
|
| 810 |
+
(lf_shc, False, (2, 3)),
|
| 811 |
+
(lf_hc, False, 4),
|
| 812 |
+
(lf_shc, True, 2),
|
| 813 |
+
(lf_hc, True, 3),
|
| 814 |
+
(lfi_shc, True, (3, 4)),
|
| 815 |
+
(lfi_hc, True, 4),
|
| 816 |
+
],
|
| 817 |
+
"smallest_last": [
|
| 818 |
+
(sl_shc, False, (3, 4)),
|
| 819 |
+
(sl_hc, False, 5),
|
| 820 |
+
(sl_shc, True, 3),
|
| 821 |
+
(sl_hc, True, 4),
|
| 822 |
+
(sli_shc, True, (3, 4)),
|
| 823 |
+
(sli_hc, True, 5),
|
| 824 |
+
],
|
| 825 |
+
"independent_set": [(gis_shc, False, (2, 3)), (gis_hc, False, 3)],
|
| 826 |
+
"connected_sequential": [(cs_shc, False, (3, 4)), (cs_shc, True, 3)],
|
| 827 |
+
"connected_sequential_dfs": [(cs_shc, False, (3, 4))],
|
| 828 |
+
}
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
# --------------------------------------------------------------------------
|
| 832 |
+
# Helper functions to test
|
| 833 |
+
# (graph function, interchange, valid # of colors)
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
def check_state(L, N, H, F, C):
|
| 837 |
+
s = len(C[0])
|
| 838 |
+
num_colors = len(C.keys())
|
| 839 |
+
|
| 840 |
+
assert all(u in L[v] for u in L for v in L[u])
|
| 841 |
+
assert all(F[u] != F[v] for u in L for v in L[u])
|
| 842 |
+
assert all(len(L[u]) < num_colors for u in L)
|
| 843 |
+
assert all(len(C[x]) == s for x in C)
|
| 844 |
+
assert all(H[(c1, c2)] >= 0 for c1 in C for c2 in C)
|
| 845 |
+
assert all(N[(u, F[u])] == 0 for u in F)
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
def max_degree(G):
|
| 849 |
+
"""Get the maximum degree of any node in G."""
|
| 850 |
+
return max(G.degree(node) for node in G.nodes) if len(G.nodes) > 0 else 0
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
def make_params_from_graph(G, F):
|
| 854 |
+
"""Returns {N, L, H, C} from the given graph."""
|
| 855 |
+
num_nodes = len(G)
|
| 856 |
+
L = {u: [] for u in range(num_nodes)}
|
| 857 |
+
for u, v in G.edges:
|
| 858 |
+
L[u].append(v)
|
| 859 |
+
L[v].append(u)
|
| 860 |
+
|
| 861 |
+
C = nx.algorithms.coloring.equitable_coloring.make_C_from_F(F)
|
| 862 |
+
N = nx.algorithms.coloring.equitable_coloring.make_N_from_L_C(L, C)
|
| 863 |
+
H = nx.algorithms.coloring.equitable_coloring.make_H_from_C_N(C, N)
|
| 864 |
+
|
| 865 |
+
return {"N": N, "F": F, "C": C, "H": H, "L": L}
|
shared/package-files/03/036de769e968aa7fb534a5400013ac26d1d4f55cfc95fbeb0080ae2e4fbba813/chrono.h
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
Wenzel Jakob <wenzel.jakob@epfl.ch>
|
| 6 |
+
|
| 7 |
+
All rights reserved. Use of this source code is governed by a
|
| 8 |
+
BSD-style license that can be found in the LICENSE file.
|
| 9 |
+
*/
|
| 10 |
+
|
| 11 |
+
#pragma once
|
| 12 |
+
|
| 13 |
+
#include "pybind11.h"
|
| 14 |
+
|
| 15 |
+
#include <chrono>
|
| 16 |
+
#include <cmath>
|
| 17 |
+
#include <ctime>
|
| 18 |
+
#include <datetime.h>
|
| 19 |
+
#include <mutex>
|
| 20 |
+
|
| 21 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
| 22 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
| 23 |
+
|
| 24 |
+
template <typename type>
|
| 25 |
+
class duration_caster {
|
| 26 |
+
public:
|
| 27 |
+
using rep = typename type::rep;
|
| 28 |
+
using period = typename type::period;
|
| 29 |
+
|
| 30 |
+
// signed 25 bits required by the standard.
|
| 31 |
+
using days = std::chrono::duration<int_least32_t, std::ratio<86400>>;
|
| 32 |
+
|
| 33 |
+
bool load(handle src, bool) {
|
| 34 |
+
using namespace std::chrono;
|
| 35 |
+
|
| 36 |
+
// Lazy initialise the PyDateTime import
|
| 37 |
+
if (!PyDateTimeAPI) {
|
| 38 |
+
PyDateTime_IMPORT;
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
if (!src) {
|
| 42 |
+
return false;
|
| 43 |
+
}
|
| 44 |
+
// If invoked with datetime.delta object
|
| 45 |
+
if (PyDelta_Check(src.ptr())) {
|
| 46 |
+
value = type(duration_cast<duration<rep, period>>(
|
| 47 |
+
days(PyDateTime_DELTA_GET_DAYS(src.ptr()))
|
| 48 |
+
+ seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr()))
|
| 49 |
+
+ microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr()))));
|
| 50 |
+
return true;
|
| 51 |
+
}
|
| 52 |
+
// If invoked with a float we assume it is seconds and convert
|
| 53 |
+
if (PyFloat_Check(src.ptr())) {
|
| 54 |
+
value = type(duration_cast<duration<rep, period>>(
|
| 55 |
+
duration<double>(PyFloat_AsDouble(src.ptr()))));
|
| 56 |
+
return true;
|
| 57 |
+
}
|
| 58 |
+
return false;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
// If this is a duration just return it back
|
| 62 |
+
static const std::chrono::duration<rep, period> &
|
| 63 |
+
get_duration(const std::chrono::duration<rep, period> &src) {
|
| 64 |
+
return src;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
// If this is a time_point get the time_since_epoch
|
| 68 |
+
template <typename Clock>
|
| 69 |
+
static std::chrono::duration<rep, period>
|
| 70 |
+
get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
|
| 71 |
+
return src.time_since_epoch();
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) {
|
| 75 |
+
using namespace std::chrono;
|
| 76 |
+
|
| 77 |
+
// Use overloaded function to get our duration from our source
|
| 78 |
+
// Works out if it is a duration or time_point and get the duration
|
| 79 |
+
auto d = get_duration(src);
|
| 80 |
+
|
| 81 |
+
// Lazy initialise the PyDateTime import
|
| 82 |
+
if (!PyDateTimeAPI) {
|
| 83 |
+
PyDateTime_IMPORT;
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
// Declare these special duration types so the conversions happen with the correct
|
| 87 |
+
// primitive types (int)
|
| 88 |
+
using dd_t = duration<int, std::ratio<86400>>;
|
| 89 |
+
using ss_t = duration<int, std::ratio<1>>;
|
| 90 |
+
using us_t = duration<int, std::micro>;
|
| 91 |
+
|
| 92 |
+
auto dd = duration_cast<dd_t>(d);
|
| 93 |
+
auto subd = d - dd;
|
| 94 |
+
auto ss = duration_cast<ss_t>(subd);
|
| 95 |
+
auto us = duration_cast<us_t>(subd - ss);
|
| 96 |
+
return PyDelta_FromDSU(dd.count(), ss.count(), us.count());
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
PYBIND11_TYPE_CASTER(type, const_name("datetime.timedelta"));
|
| 100 |
+
};
|
| 101 |
+
|
| 102 |
+
inline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) {
|
| 103 |
+
#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER)
|
| 104 |
+
if (localtime_s(buf, time))
|
| 105 |
+
return nullptr;
|
| 106 |
+
return buf;
|
| 107 |
+
#else
|
| 108 |
+
static std::mutex mtx;
|
| 109 |
+
std::lock_guard<std::mutex> lock(mtx);
|
| 110 |
+
std::tm *tm_ptr = std::localtime(time);
|
| 111 |
+
if (tm_ptr != nullptr) {
|
| 112 |
+
*buf = *tm_ptr;
|
| 113 |
+
}
|
| 114 |
+
return tm_ptr;
|
| 115 |
+
#endif
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
// This is for casting times on the system clock into datetime.datetime instances
|
| 119 |
+
template <typename Duration>
|
| 120 |
+
class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {
|
| 121 |
+
public:
|
| 122 |
+
using type = std::chrono::time_point<std::chrono::system_clock, Duration>;
|
| 123 |
+
bool load(handle src, bool) {
|
| 124 |
+
using namespace std::chrono;
|
| 125 |
+
|
| 126 |
+
// Lazy initialise the PyDateTime import
|
| 127 |
+
if (!PyDateTimeAPI) {
|
| 128 |
+
PyDateTime_IMPORT;
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
if (!src) {
|
| 132 |
+
return false;
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
std::tm cal;
|
| 136 |
+
microseconds msecs;
|
| 137 |
+
|
| 138 |
+
if (PyDateTime_Check(src.ptr())) {
|
| 139 |
+
cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
|
| 140 |
+
cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
|
| 141 |
+
cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
|
| 142 |
+
cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
|
| 143 |
+
cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
|
| 144 |
+
cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
|
| 145 |
+
cal.tm_isdst = -1;
|
| 146 |
+
msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
|
| 147 |
+
} else if (PyDate_Check(src.ptr())) {
|
| 148 |
+
cal.tm_sec = 0;
|
| 149 |
+
cal.tm_min = 0;
|
| 150 |
+
cal.tm_hour = 0;
|
| 151 |
+
cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
|
| 152 |
+
cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
|
| 153 |
+
cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
|
| 154 |
+
cal.tm_isdst = -1;
|
| 155 |
+
msecs = microseconds(0);
|
| 156 |
+
} else if (PyTime_Check(src.ptr())) {
|
| 157 |
+
cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());
|
| 158 |
+
cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());
|
| 159 |
+
cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());
|
| 160 |
+
cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70)
|
| 161 |
+
cal.tm_mon = 0; // represents 1-Jan-1970, which is the first
|
| 162 |
+
cal.tm_year = 70; // earliest available date for Python's datetime
|
| 163 |
+
cal.tm_isdst = -1;
|
| 164 |
+
msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));
|
| 165 |
+
} else {
|
| 166 |
+
return false;
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs);
|
| 170 |
+
return true;
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src,
|
| 174 |
+
return_value_policy /* policy */,
|
| 175 |
+
handle /* parent */) {
|
| 176 |
+
using namespace std::chrono;
|
| 177 |
+
|
| 178 |
+
// Lazy initialise the PyDateTime import
|
| 179 |
+
if (!PyDateTimeAPI) {
|
| 180 |
+
PyDateTime_IMPORT;
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
// Get out microseconds, and make sure they are positive, to avoid bug in eastern
|
| 184 |
+
// hemisphere time zones (cfr. https://github.com/pybind/pybind11/issues/2417)
|
| 185 |
+
using us_t = duration<int, std::micro>;
|
| 186 |
+
auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
|
| 187 |
+
if (us.count() < 0) {
|
| 188 |
+
us += seconds(1);
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
// Subtract microseconds BEFORE `system_clock::to_time_t`, because:
|
| 192 |
+
// > If std::time_t has lower precision, it is implementation-defined whether the value is
|
| 193 |
+
// rounded or truncated. (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
|
| 194 |
+
std::time_t tt
|
| 195 |
+
= system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
|
| 196 |
+
|
| 197 |
+
std::tm localtime;
|
| 198 |
+
std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime);
|
| 199 |
+
if (!localtime_ptr) {
|
| 200 |
+
throw cast_error("Unable to represent system_clock in local time");
|
| 201 |
+
}
|
| 202 |
+
return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
|
| 203 |
+
localtime.tm_mon + 1,
|
| 204 |
+
localtime.tm_mday,
|
| 205 |
+
localtime.tm_hour,
|
| 206 |
+
localtime.tm_min,
|
| 207 |
+
localtime.tm_sec,
|
| 208 |
+
us.count());
|
| 209 |
+
}
|
| 210 |
+
PYBIND11_TYPE_CASTER(type, const_name("datetime.datetime"));
|
| 211 |
+
};
|
| 212 |
+
|
| 213 |
+
// Other clocks that are not the system clock are not measured as datetime.datetime objects
|
| 214 |
+
// since they are not measured on calendar time. So instead we just make them timedeltas
|
| 215 |
+
// Or if they have passed us a time as a float we convert that
|
| 216 |
+
template <typename Clock, typename Duration>
|
| 217 |
+
class type_caster<std::chrono::time_point<Clock, Duration>>
|
| 218 |
+
: public duration_caster<std::chrono::time_point<Clock, Duration>> {};
|
| 219 |
+
|
| 220 |
+
template <typename Rep, typename Period>
|
| 221 |
+
class type_caster<std::chrono::duration<Rep, Period>>
|
| 222 |
+
: public duration_caster<std::chrono::duration<Rep, Period>> {};
|
| 223 |
+
|
| 224 |
+
PYBIND11_NAMESPACE_END(detail)
|
| 225 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
shared/package-files/03/036e6516c4ec6bd5d4ead3eea8578e587d7880e8c8e3484f7c9eb6e8119e08e6/test_ir.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|