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/00/003a32bd1889775f1c7405d2d01cdef524ebe07e4347fcd5dd8ba009920ea628/igammac_meta.h +27 -0
- shared/package-files/00/006fc7f4bc50db6692f9823d09a03031dc6f3881feb24da82d3ee690ea645382/sqrt_cuda_dispatch.h +26 -0
- shared/package-files/00/007b4b4429d075e6397d074c248b6780debb3c1565c569f612aff4b9ae159492/graph.py +105 -0
- shared/package-files/00/008df3db96fee0e246fb7c3856aadccc29fd22e8cc53be2808d92ea2ad1862e5/_foreach_tanh_native.h +25 -0
- shared/package-files/00/00ab61d75f635c60e1766c4d11000f19df89b27f39ccafcf9ba9cde119042c7e/rad2deg_ops.h +50 -0
- shared/package-files/00/00b2b32c07023c8313af7242e91247b8e61deb3d1a155685e7e7b8f3589c61ef/test_generate.py +250 -0
- shared/package-files/00/00bd32de69cbd0a8143a0c48833de605c7d710b04465a7e373a808c3a5988d55/darwin-100x37 +0 -0
- shared/package-files/00/00bd32de69cbd0a8143a0c48833de605c7d710b04465a7e373a808c3a5988d55/xnuppc-100x37 +0 -0
- shared/package-files/00/00da7f094f47725cbdf8d0719279bb83eb96c658ecb539ab8aadd2f1fe643ec3/masked_shared.py +154 -0
- shared/package-files/00/00e743ca2baee2dda2b691e115c05dbd8f93833ce2d47c10367bb695adf2697c/__init__.py +46 -0
- shared/package-files/4b/4b0063276c1c66181a36591cbb41f28afcf01f91e6115f1fb733b8c0072353ca/_sparse_csc_tensor_unsafe_native.h +21 -0
- shared/package-files/4b/4b00fa42c7d296b11da43d9d6e470deb608f54844fe5269d8c2a652eb300a1af/test_baseclasses.py +209 -0
- shared/package-files/4b/4b0361a3789666efe526f71d4a8980e5c41d70353c82870a6e64679ba05ff7ed/__init__.py +22 -0
- shared/package-files/4b/4b0b3db9869b94cf6b589eea31e71e171a5f523b19334f9cad5c3a5729187a67/exponential_smoothing_params.csv +15 -0
- shared/package-files/4b/4b0be99729c93d746824518a627a1cad2e0afe37a5c151b47029a207cc1df4ec/output-archive.h +82 -0
- shared/package-files/4b/4b0fd07726244c98a5cc3690328e628c22155de2396c370dcd466b07b7b6534a/diff.py +294 -0
- shared/package-files/4b/4b120db5de236321f4616773b29afc251d2cc997cede7323ec2eb4196054afa9/_validation.py +66 -0
- shared/package-files/4b/4b126d0a83e4d7aef97e0df0dc3205847d1f3e2124dc8d309ec724c0e114a3f5/inv_gaussian.csv +0 -0
- shared/package-files/4b/4b12f6235acaa9eef75998243b9d753d6271db43f5eb457886bc2cd531b42539/byteswap.pyi +5 -0
- shared/package-files/4b/4b131f22fd01af8f7a5622fc3221715d64dbf19caac6d67c2fb364113b7cfa77/upsample_nearest1d_backward_cuda_dispatch.h +28 -0
- shared/package-files/4b/4b1a1753c20901a95af2e052c43d5fe6d49629fcc24afc5d470b5be2d111be12/sugared_value.h +857 -0
- shared/package-files/4b/4b1b478b7c4d9aa7e859160e464f841c8d64db243918547d47ac5956c81a1c0e/_unpack_dual_native.h +21 -0
- shared/package-files/4b/4b1dd6bfcdc0ce85d83c444411f29098ccaf86851d9e48122bf26c491c8aa0b2/native_group_norm_ops.h +39 -0
- shared/package-files/4b/4b24155cadc107580466570ad6ae4bb9e5afa72a3e53ad34b5d9e957ff3b41b1/nonhomogeneous.py +499 -0
- shared/package-files/4b/4b28b46981bbb78cbd2b22060e2dd018c66fcff1cee52755425ad4900a90d6c3/es_ni.msg +6 -0
- shared/package-files/4b/4b2b96775cdb43b50a6795957718f0519abace8a637e7f3d0b2d453395dd57ac/pastes.csv +61 -0
- shared/package-files/4b/4b2bc899cc5ebf58fa4db91310f3dfa85aa131c99cb579d067526582aefce8e5/kron_native.h +22 -0
- shared/package-files/4b/4b2c1587fa23eee028d6d98c8f2b4869f70b08931f02d3051597bd437bc0e988/cmd.pyi +67 -0
- shared/package-files/4b/4b324fa058f2204be2492bcf46f2fcd68d638d025c33e55ea9be76bc553ae894/selectors.py +31 -0
- shared/package-files/4b/4b37ecbb4f68a464be2b80e999987c75351d1782ced6671603468036ead2c338/new_empty_strided_compositeexplicitautogradnonfunctional_dispatch.h +26 -0
- shared/package-files/4b/4b3aa1d7d213d9806e9617e51608e8be626a5f89b907b856b5ee49057463b828/softshrink_backward_native.h +23 -0
- shared/package-files/4b/4b3dfeb7d4f1d254acbb217b7a010b3240936cea015d4554340b76429176ed12/compat.py +366 -0
- shared/package-files/4b/4b3ea073c802fc2f8fdcbb8c2dc6527ccc71081153b643bf49071509ff43a3aa/weight_utils.py +275 -0
- shared/package-files/4b/4b45b4ec49e90135a8e6ccb557e140a0fa728514f50c73af79bf4fc976bb89b4/test_mocking.py +205 -0
- shared/package-files/4b/4b479d20416e47fcc964ba77d97bb446eaf9b6325d0c4ccd513512645a609f24/citoh-6lpi +0 -0
- shared/package-files/4b/4b4a2ba49a08e73193559c825067eb9b3da3837be0ef936b42aae1e81fea18a7/conda.bat +26 -0
- shared/package-files/4b/4b4b0115c341185d2b33fcfa6be0c23479b0acaab811bf0d6535b3c59508316e/cuda_codegen.h +295 -0
- shared/package-files/4b/4b4b84fbd86a6b8114d7493ff064ab950e1b3f1ec82e4ff36abee60aa9869a0c/_location.py +50 -0
- shared/package-files/4b/4b505195f5d20f6e3c38537302e6793bdc3d5ba7ebd8d527d17f3060518c364d/error.py +111 -0
- shared/package-files/4b/4b53466cc8ba93760059fb11e2007cded9d7402087320a979b2ef86e710758da/test_indexing.py +60 -0
- shared/package-files/4b/4b559c391b73696eafd9524ea9caee1872a8afc042fd6218c8ffbeb16d9562e7/aaa-22 +0 -0
- shared/package-files/4b/4b597f52c1cb35ae8ed540d1db2dab52276c7874febd7a659ee50f26be26f61e/lindenmayer.py +119 -0
- shared/package-files/4b/4b5cdce106e003b746944b5c8b1299f16ad3d8e93ceb5cb2fb353c0cbb6f6697/hostkeys.pyi +47 -0
- shared/package-files/4b/4b6228391845937f451053a54855ad815c9b4623fa87b0652e574755c94d914f/latin1prober.py +145 -0
- shared/package-files/4b/4b622a5c23858a4977ff25240ae88e36dd26be6bf15bf39c2b9661956bf7f1c4/base_futures.pyi +22 -0
- shared/package-files/4b/4b6291086e765ed3cd2c4df4535cfd344afe960ec624d0a67b5f729e5e621804/TensorProperties.h +12 -0
- shared/package-files/4b/4b62cd165422d03b6f5fcce2e8788a24006657841f898f190edbee1faa03fb7f/index_select_backward.h +47 -0
- shared/package-files/4b/4b63b0ba2c4df0d0a6d4fef0d7152b6eed81f6757e073cfb812bb5ab307fea42/cummax_ops.h +61 -0
- shared/package-files/4b/4b6c5fb6ffc8dc10a47953000052c232df42bcd8707f5e9e428a3f3fef47c2db/_foreach_erfc_ops.h +50 -0
- shared/package-files/4b/4b6cb7a82b3b00ed4491096d37f398901e0fb1a990a9c22370fbbfd7cd7016a6/stochastic_process_types.py +2382 -0
shared/package-files/00/003a32bd1889775f1c7405d2d01cdef524ebe07e4347fcd5dd8ba009920ea628/igammac_meta.h
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeMetaFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/TensorIterator.h>
|
| 13 |
+
#include <ATen/TensorMeta.h>
|
| 14 |
+
#include <tuple>
|
| 15 |
+
#include <vector>
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace meta {
|
| 19 |
+
|
| 20 |
+
struct TORCH_API structured_igammac : public TensorIteratorBase {
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
void meta(const at::Tensor & self, const at::Tensor & other);
|
| 24 |
+
};
|
| 25 |
+
|
| 26 |
+
} // namespace native
|
| 27 |
+
} // namespace at
|
shared/package-files/00/006fc7f4bc50db6692f9823d09a03031dc6f3881feb24da82d3ee690ea645382/sqrt_cuda_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 cuda {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor sqrt(const at::Tensor & self);
|
| 21 |
+
TORCH_API at::Tensor & sqrt_out(at::Tensor & out, const at::Tensor & self);
|
| 22 |
+
TORCH_API at::Tensor & sqrt_outf(const at::Tensor & self, at::Tensor & out);
|
| 23 |
+
TORCH_API at::Tensor & sqrt_(at::Tensor & self);
|
| 24 |
+
|
| 25 |
+
} // namespace cuda
|
| 26 |
+
} // namespace at
|
shared/package-files/00/007b4b4429d075e6397d074c248b6780debb3c1565c569f612aff4b9ae159492/graph.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.lexers.graph
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
Lexers for graph query languages.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import re
|
| 12 |
+
|
| 13 |
+
from pygments.lexer import RegexLexer, include, bygroups, using, this, words
|
| 14 |
+
from pygments.token import Keyword, Punctuation, Comment, Operator, Name,\
|
| 15 |
+
String, Number, Whitespace
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = ['CypherLexer']
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class CypherLexer(RegexLexer):
|
| 22 |
+
"""
|
| 23 |
+
For Cypher Query Language
|
| 24 |
+
|
| 25 |
+
For the Cypher version in Neo4j 3.3
|
| 26 |
+
|
| 27 |
+
.. versionadded:: 2.0
|
| 28 |
+
"""
|
| 29 |
+
name = 'Cypher'
|
| 30 |
+
url = 'https://neo4j.com/docs/developer-manual/3.3/cypher/'
|
| 31 |
+
aliases = ['cypher']
|
| 32 |
+
filenames = ['*.cyp', '*.cypher']
|
| 33 |
+
|
| 34 |
+
flags = re.MULTILINE | re.IGNORECASE
|
| 35 |
+
|
| 36 |
+
tokens = {
|
| 37 |
+
'root': [
|
| 38 |
+
include('comment'),
|
| 39 |
+
include('clauses'),
|
| 40 |
+
include('keywords'),
|
| 41 |
+
include('relations'),
|
| 42 |
+
include('strings'),
|
| 43 |
+
include('whitespace'),
|
| 44 |
+
include('barewords'),
|
| 45 |
+
],
|
| 46 |
+
'comment': [
|
| 47 |
+
(r'^.*//.*$', Comment.Single),
|
| 48 |
+
],
|
| 49 |
+
'keywords': [
|
| 50 |
+
(r'(create|order|match|limit|set|skip|start|return|with|where|'
|
| 51 |
+
r'delete|foreach|not|by|true|false)\b', Keyword),
|
| 52 |
+
],
|
| 53 |
+
'clauses': [
|
| 54 |
+
# based on https://neo4j.com/docs/cypher-refcard/3.3/
|
| 55 |
+
(r'(create)(\s+)(index|unique)\b',
|
| 56 |
+
bygroups(Keyword, Whitespace, Keyword)),
|
| 57 |
+
(r'(drop)(\s+)(contraint|index)(\s+)(on)\b',
|
| 58 |
+
bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)),
|
| 59 |
+
(r'(ends)(\s+)(with)\b',
|
| 60 |
+
bygroups(Keyword, Whitespace, Keyword)),
|
| 61 |
+
(r'(is)(\s+)(node)(\s+)(key)\b',
|
| 62 |
+
bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)),
|
| 63 |
+
(r'(is)(\s+)(null|unique)\b',
|
| 64 |
+
bygroups(Keyword, Whitespace, Keyword)),
|
| 65 |
+
(r'(load)(\s+)(csv)(\s+)(from)\b',
|
| 66 |
+
bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)),
|
| 67 |
+
(r'(on)(\s+)(match|create)\b',
|
| 68 |
+
bygroups(Keyword, Whitespace, Keyword)),
|
| 69 |
+
(r'(optional)(\s+)(match)\b',
|
| 70 |
+
bygroups(Keyword, Whitespace, Keyword)),
|
| 71 |
+
(r'(order)(\s+)(by)\b',
|
| 72 |
+
bygroups(Keyword, Whitespace, Keyword)),
|
| 73 |
+
(r'(starts)(\s+)(with)\b',
|
| 74 |
+
bygroups(Keyword, Whitespace, Keyword)),
|
| 75 |
+
(r'(union)(\s+)(all)\b',
|
| 76 |
+
bygroups(Keyword, Whitespace, Keyword)),
|
| 77 |
+
(r'(using)(\s+)(periodic)(\s+)(commit)\b',
|
| 78 |
+
bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)),
|
| 79 |
+
(words((
|
| 80 |
+
'all', 'any', 'as', 'asc', 'ascending', 'assert', 'call', 'case', 'create',
|
| 81 |
+
'delete', 'desc', 'descending', 'distinct', 'end', 'fieldterminator',
|
| 82 |
+
'foreach', 'in', 'limit', 'match', 'merge', 'none', 'not', 'null',
|
| 83 |
+
'remove', 'return', 'set', 'skip', 'single', 'start', 'then', 'union',
|
| 84 |
+
'unwind', 'yield', 'where', 'when', 'with'), suffix=r'\b'), Keyword),
|
| 85 |
+
],
|
| 86 |
+
'relations': [
|
| 87 |
+
(r'(-\[)(.*?)(\]->)', bygroups(Operator, using(this), Operator)),
|
| 88 |
+
(r'(<-\[)(.*?)(\]-)', bygroups(Operator, using(this), Operator)),
|
| 89 |
+
(r'(-\[)(.*?)(\]-)', bygroups(Operator, using(this), Operator)),
|
| 90 |
+
(r'-->|<--|\[|\]', Operator),
|
| 91 |
+
(r'<|>|<>|=|<=|=>|\(|\)|\||:|,|;', Punctuation),
|
| 92 |
+
(r'[.*{}]', Punctuation),
|
| 93 |
+
],
|
| 94 |
+
'strings': [
|
| 95 |
+
(r'"(?:\\[tbnrf\'"\\]|[^\\"])*"', String),
|
| 96 |
+
(r'`(?:``|[^`])+`', Name.Variable),
|
| 97 |
+
],
|
| 98 |
+
'whitespace': [
|
| 99 |
+
(r'\s+', Whitespace),
|
| 100 |
+
],
|
| 101 |
+
'barewords': [
|
| 102 |
+
(r'[a-z]\w*', Name),
|
| 103 |
+
(r'\d+', Number),
|
| 104 |
+
],
|
| 105 |
+
}
|
shared/package-files/00/008df3db96fee0e246fb7c3856aadccc29fd22e8cc53be2808d92ea2ad1862e5/_foreach_tanh_native.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 void _foreach_tanh_out(at::TensorList self, at::TensorList out);
|
| 20 |
+
TORCH_API ::std::vector<at::Tensor> foreach_tensor_tanh_slow(at::TensorList self);
|
| 21 |
+
TORCH_API void foreach_tensor_tanh_slow_(at::TensorList self);
|
| 22 |
+
TORCH_API ::std::vector<at::Tensor> foreach_tensor_tanh_cuda(at::TensorList self);
|
| 23 |
+
TORCH_API void foreach_tensor_tanh_cuda_(at::TensorList self);
|
| 24 |
+
} // namespace native
|
| 25 |
+
} // namespace at
|
shared/package-files/00/00ab61d75f635c60e1766c4d11000f19df89b27f39ccafcf9ba9cde119042c7e/rad2deg_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 rad2deg {
|
| 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::rad2deg")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rad2deg(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 rad2deg_ {
|
| 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::rad2deg_")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rad2deg_(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 rad2deg_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::rad2deg")
|
| 44 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 45 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rad2deg.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/00/00b2b32c07023c8313af7242e91247b8e61deb3d1a155685e7e7b8f3589c61ef/test_generate.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.numbers import (I, Rational, nan, zoo)
|
| 2 |
+
from sympy.core.singleton import S
|
| 3 |
+
from sympy.core.symbol import Symbol
|
| 4 |
+
from sympy.ntheory.generate import (sieve, Sieve)
|
| 5 |
+
from sympy.series.limits import limit
|
| 6 |
+
|
| 7 |
+
from sympy.ntheory import isprime, totient, mobius, randprime, nextprime, prevprime, \
|
| 8 |
+
primerange, primepi, prime, primorial, composite, compositepi, reduced_totient
|
| 9 |
+
from sympy.ntheory.generate import cycle_length
|
| 10 |
+
from sympy.ntheory.primetest import mr
|
| 11 |
+
from sympy.testing.pytest import raises
|
| 12 |
+
|
| 13 |
+
def test_prime():
|
| 14 |
+
assert prime(1) == 2
|
| 15 |
+
assert prime(2) == 3
|
| 16 |
+
assert prime(5) == 11
|
| 17 |
+
assert prime(11) == 31
|
| 18 |
+
assert prime(57) == 269
|
| 19 |
+
assert prime(296) == 1949
|
| 20 |
+
assert prime(559) == 4051
|
| 21 |
+
assert prime(3000) == 27449
|
| 22 |
+
assert prime(4096) == 38873
|
| 23 |
+
assert prime(9096) == 94321
|
| 24 |
+
assert prime(25023) == 287341
|
| 25 |
+
assert prime(10000000) == 179424673 # issue #20951
|
| 26 |
+
assert prime(99999999) == 2038074739
|
| 27 |
+
raises(ValueError, lambda: prime(0))
|
| 28 |
+
sieve.extend(3000)
|
| 29 |
+
assert prime(401) == 2749
|
| 30 |
+
raises(ValueError, lambda: prime(-1))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_primepi():
|
| 34 |
+
assert primepi(-1) == 0
|
| 35 |
+
assert primepi(1) == 0
|
| 36 |
+
assert primepi(2) == 1
|
| 37 |
+
assert primepi(Rational(7, 2)) == 2
|
| 38 |
+
assert primepi(3.5) == 2
|
| 39 |
+
assert primepi(5) == 3
|
| 40 |
+
assert primepi(11) == 5
|
| 41 |
+
assert primepi(57) == 16
|
| 42 |
+
assert primepi(296) == 62
|
| 43 |
+
assert primepi(559) == 102
|
| 44 |
+
assert primepi(3000) == 430
|
| 45 |
+
assert primepi(4096) == 564
|
| 46 |
+
assert primepi(9096) == 1128
|
| 47 |
+
assert primepi(25023) == 2763
|
| 48 |
+
assert primepi(10**8) == 5761455
|
| 49 |
+
assert primepi(253425253) == 13856396
|
| 50 |
+
assert primepi(8769575643) == 401464322
|
| 51 |
+
sieve.extend(3000)
|
| 52 |
+
assert primepi(2000) == 303
|
| 53 |
+
|
| 54 |
+
n = Symbol('n')
|
| 55 |
+
assert primepi(n).subs(n, 2) == 1
|
| 56 |
+
|
| 57 |
+
r = Symbol('r', real=True)
|
| 58 |
+
assert primepi(r).subs(r, 2) == 1
|
| 59 |
+
|
| 60 |
+
assert primepi(S.Infinity) is S.Infinity
|
| 61 |
+
assert primepi(S.NegativeInfinity) == 0
|
| 62 |
+
|
| 63 |
+
assert limit(primepi(n), n, 100) == 25
|
| 64 |
+
|
| 65 |
+
raises(ValueError, lambda: primepi(I))
|
| 66 |
+
raises(ValueError, lambda: primepi(1 + I))
|
| 67 |
+
raises(ValueError, lambda: primepi(zoo))
|
| 68 |
+
raises(ValueError, lambda: primepi(nan))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_composite():
|
| 72 |
+
from sympy.ntheory.generate import sieve
|
| 73 |
+
sieve._reset()
|
| 74 |
+
assert composite(1) == 4
|
| 75 |
+
assert composite(2) == 6
|
| 76 |
+
assert composite(5) == 10
|
| 77 |
+
assert composite(11) == 20
|
| 78 |
+
assert composite(41) == 58
|
| 79 |
+
assert composite(57) == 80
|
| 80 |
+
assert composite(296) == 370
|
| 81 |
+
assert composite(559) == 684
|
| 82 |
+
assert composite(3000) == 3488
|
| 83 |
+
assert composite(4096) == 4736
|
| 84 |
+
assert composite(9096) == 10368
|
| 85 |
+
assert composite(25023) == 28088
|
| 86 |
+
sieve.extend(3000)
|
| 87 |
+
assert composite(1957) == 2300
|
| 88 |
+
assert composite(2568) == 2998
|
| 89 |
+
raises(ValueError, lambda: composite(0))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_compositepi():
|
| 93 |
+
assert compositepi(1) == 0
|
| 94 |
+
assert compositepi(2) == 0
|
| 95 |
+
assert compositepi(5) == 1
|
| 96 |
+
assert compositepi(11) == 5
|
| 97 |
+
assert compositepi(57) == 40
|
| 98 |
+
assert compositepi(296) == 233
|
| 99 |
+
assert compositepi(559) == 456
|
| 100 |
+
assert compositepi(3000) == 2569
|
| 101 |
+
assert compositepi(4096) == 3531
|
| 102 |
+
assert compositepi(9096) == 7967
|
| 103 |
+
assert compositepi(25023) == 22259
|
| 104 |
+
assert compositepi(10**8) == 94238544
|
| 105 |
+
assert compositepi(253425253) == 239568856
|
| 106 |
+
assert compositepi(8769575643) == 8368111320
|
| 107 |
+
sieve.extend(3000)
|
| 108 |
+
assert compositepi(2321) == 1976
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def test_generate():
|
| 112 |
+
from sympy.ntheory.generate import sieve
|
| 113 |
+
sieve._reset()
|
| 114 |
+
assert nextprime(-4) == 2
|
| 115 |
+
assert nextprime(2) == 3
|
| 116 |
+
assert nextprime(5) == 7
|
| 117 |
+
assert nextprime(12) == 13
|
| 118 |
+
assert prevprime(3) == 2
|
| 119 |
+
assert prevprime(7) == 5
|
| 120 |
+
assert prevprime(13) == 11
|
| 121 |
+
assert prevprime(19) == 17
|
| 122 |
+
assert prevprime(20) == 19
|
| 123 |
+
|
| 124 |
+
sieve.extend_to_no(9)
|
| 125 |
+
assert sieve._list[-1] == 23
|
| 126 |
+
|
| 127 |
+
assert sieve._list[-1] < 31
|
| 128 |
+
assert 31 in sieve
|
| 129 |
+
|
| 130 |
+
assert nextprime(90) == 97
|
| 131 |
+
assert nextprime(10**40) == (10**40 + 121)
|
| 132 |
+
assert prevprime(97) == 89
|
| 133 |
+
assert prevprime(10**40) == (10**40 - 17)
|
| 134 |
+
|
| 135 |
+
assert list(sieve.primerange(10, 1)) == []
|
| 136 |
+
assert list(sieve.primerange(5, 9)) == [5, 7]
|
| 137 |
+
sieve._reset(prime=True)
|
| 138 |
+
assert list(sieve.primerange(2, 13)) == [2, 3, 5, 7, 11]
|
| 139 |
+
assert list(sieve.primerange(13)) == [2, 3, 5, 7, 11]
|
| 140 |
+
assert list(sieve.primerange(8)) == [2, 3, 5, 7]
|
| 141 |
+
assert list(sieve.primerange(-2)) == []
|
| 142 |
+
assert list(sieve.primerange(29)) == [2, 3, 5, 7, 11, 13, 17, 19, 23]
|
| 143 |
+
assert list(sieve.primerange(34)) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
|
| 144 |
+
|
| 145 |
+
assert list(sieve.totientrange(5, 15)) == [4, 2, 6, 4, 6, 4, 10, 4, 12, 6]
|
| 146 |
+
sieve._reset(totient=True)
|
| 147 |
+
assert list(sieve.totientrange(3, 13)) == [2, 2, 4, 2, 6, 4, 6, 4, 10, 4]
|
| 148 |
+
assert list(sieve.totientrange(900, 1000)) == [totient(x) for x in range(900, 1000)]
|
| 149 |
+
assert list(sieve.totientrange(0, 1)) == []
|
| 150 |
+
assert list(sieve.totientrange(1, 2)) == [1]
|
| 151 |
+
|
| 152 |
+
assert list(sieve.mobiusrange(5, 15)) == [-1, 1, -1, 0, 0, 1, -1, 0, -1, 1]
|
| 153 |
+
sieve._reset(mobius=True)
|
| 154 |
+
assert list(sieve.mobiusrange(3, 13)) == [-1, 0, -1, 1, -1, 0, 0, 1, -1, 0]
|
| 155 |
+
assert list(sieve.mobiusrange(1050, 1100)) == [mobius(x) for x in range(1050, 1100)]
|
| 156 |
+
assert list(sieve.mobiusrange(0, 1)) == []
|
| 157 |
+
assert list(sieve.mobiusrange(1, 2)) == [1]
|
| 158 |
+
|
| 159 |
+
assert list(primerange(10, 1)) == []
|
| 160 |
+
assert list(primerange(2, 7)) == [2, 3, 5]
|
| 161 |
+
assert list(primerange(2, 10)) == [2, 3, 5, 7]
|
| 162 |
+
assert list(primerange(1050, 1100)) == [1051, 1061,
|
| 163 |
+
1063, 1069, 1087, 1091, 1093, 1097]
|
| 164 |
+
s = Sieve()
|
| 165 |
+
for i in range(30, 2350, 376):
|
| 166 |
+
for j in range(2, 5096, 1139):
|
| 167 |
+
A = list(s.primerange(i, i + j))
|
| 168 |
+
B = list(primerange(i, i + j))
|
| 169 |
+
assert A == B
|
| 170 |
+
s = Sieve()
|
| 171 |
+
assert s[10] == 29
|
| 172 |
+
|
| 173 |
+
assert nextprime(2, 2) == 5
|
| 174 |
+
|
| 175 |
+
raises(ValueError, lambda: totient(0))
|
| 176 |
+
|
| 177 |
+
raises(ValueError, lambda: reduced_totient(0))
|
| 178 |
+
|
| 179 |
+
raises(ValueError, lambda: primorial(0))
|
| 180 |
+
|
| 181 |
+
assert mr(1, [2]) is False
|
| 182 |
+
|
| 183 |
+
func = lambda i: (i**2 + 1) % 51
|
| 184 |
+
assert next(cycle_length(func, 4)) == (6, 2)
|
| 185 |
+
assert list(cycle_length(func, 4, values=True)) == \
|
| 186 |
+
[17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
|
| 187 |
+
assert next(cycle_length(func, 4, nmax=5)) == (5, None)
|
| 188 |
+
assert list(cycle_length(func, 4, nmax=5, values=True)) == \
|
| 189 |
+
[17, 35, 2, 5, 26]
|
| 190 |
+
sieve.extend(3000)
|
| 191 |
+
assert nextprime(2968) == 2969
|
| 192 |
+
assert prevprime(2930) == 2927
|
| 193 |
+
raises(ValueError, lambda: prevprime(1))
|
| 194 |
+
raises(ValueError, lambda: prevprime(-4))
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def test_randprime():
|
| 198 |
+
assert randprime(10, 1) is None
|
| 199 |
+
assert randprime(3, -3) is None
|
| 200 |
+
assert randprime(2, 3) == 2
|
| 201 |
+
assert randprime(1, 3) == 2
|
| 202 |
+
assert randprime(3, 5) == 3
|
| 203 |
+
raises(ValueError, lambda: randprime(-12, -2))
|
| 204 |
+
raises(ValueError, lambda: randprime(-10, 0))
|
| 205 |
+
raises(ValueError, lambda: randprime(20, 22))
|
| 206 |
+
raises(ValueError, lambda: randprime(0, 2))
|
| 207 |
+
raises(ValueError, lambda: randprime(1, 2))
|
| 208 |
+
for a in [100, 300, 500, 250000]:
|
| 209 |
+
for b in [100, 300, 500, 250000]:
|
| 210 |
+
p = randprime(a, a + b)
|
| 211 |
+
assert a <= p < (a + b) and isprime(p)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def test_primorial():
|
| 215 |
+
assert primorial(1) == 2
|
| 216 |
+
assert primorial(1, nth=0) == 1
|
| 217 |
+
assert primorial(2) == 6
|
| 218 |
+
assert primorial(2, nth=0) == 2
|
| 219 |
+
assert primorial(4, nth=0) == 6
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def test_search():
|
| 223 |
+
assert 2 in sieve
|
| 224 |
+
assert 2.1 not in sieve
|
| 225 |
+
assert 1 not in sieve
|
| 226 |
+
assert 2**1000 not in sieve
|
| 227 |
+
raises(ValueError, lambda: sieve.search(1))
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def test_sieve_slice():
|
| 231 |
+
assert sieve[5] == 11
|
| 232 |
+
assert list(sieve[5:10]) == [sieve[x] for x in range(5, 10)]
|
| 233 |
+
assert list(sieve[5:10:2]) == [sieve[x] for x in range(5, 10, 2)]
|
| 234 |
+
assert list(sieve[1:5]) == [2, 3, 5, 7]
|
| 235 |
+
raises(IndexError, lambda: sieve[:5])
|
| 236 |
+
raises(IndexError, lambda: sieve[0])
|
| 237 |
+
raises(IndexError, lambda: sieve[0:5])
|
| 238 |
+
|
| 239 |
+
def test_sieve_iter():
|
| 240 |
+
values = []
|
| 241 |
+
for value in sieve:
|
| 242 |
+
if value > 7:
|
| 243 |
+
break
|
| 244 |
+
values.append(value)
|
| 245 |
+
assert values == list(sieve[1:5])
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def test_sieve_repr():
|
| 249 |
+
assert "sieve" in repr(sieve)
|
| 250 |
+
assert "prime" in repr(sieve)
|
shared/package-files/00/00bd32de69cbd0a8143a0c48833de605c7d710b04465a7e373a808c3a5988d55/darwin-100x37
ADDED
|
Binary file (1.22 kB). View file
|
|
|
shared/package-files/00/00bd32de69cbd0a8143a0c48833de605c7d710b04465a7e373a808c3a5988d55/xnuppc-100x37
ADDED
|
Binary file (1.22 kB). View file
|
|
|
shared/package-files/00/00da7f094f47725cbdf8d0719279bb83eb96c658ecb539ab8aadd2f1fe643ec3/masked_shared.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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as tm
|
| 9 |
+
from pandas.tests.extension.base import BaseOpsUtil
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ComparisonOps(BaseOpsUtil):
|
| 13 |
+
def _compare_other(self, data, op, other):
|
| 14 |
+
# array
|
| 15 |
+
result = pd.Series(op(data, other))
|
| 16 |
+
expected = pd.Series(op(data._data, other), dtype="boolean")
|
| 17 |
+
|
| 18 |
+
# fill the nan locations
|
| 19 |
+
expected[data._mask] = pd.NA
|
| 20 |
+
|
| 21 |
+
tm.assert_series_equal(result, expected)
|
| 22 |
+
|
| 23 |
+
# series
|
| 24 |
+
ser = pd.Series(data)
|
| 25 |
+
result = op(ser, other)
|
| 26 |
+
|
| 27 |
+
# Set nullable dtype here to avoid upcasting when setting to pd.NA below
|
| 28 |
+
expected = op(pd.Series(data._data), other).astype("boolean")
|
| 29 |
+
|
| 30 |
+
# fill the nan locations
|
| 31 |
+
expected[data._mask] = pd.NA
|
| 32 |
+
|
| 33 |
+
tm.assert_series_equal(result, expected)
|
| 34 |
+
|
| 35 |
+
# subclass will override to parametrize 'other'
|
| 36 |
+
def test_scalar(self, other, comparison_op, dtype):
|
| 37 |
+
op = comparison_op
|
| 38 |
+
left = pd.array([1, 0, None], dtype=dtype)
|
| 39 |
+
|
| 40 |
+
result = op(left, other)
|
| 41 |
+
|
| 42 |
+
if other is pd.NA:
|
| 43 |
+
expected = pd.array([None, None, None], dtype="boolean")
|
| 44 |
+
else:
|
| 45 |
+
values = op(left._data, other)
|
| 46 |
+
expected = pd.arrays.BooleanArray(values, left._mask, copy=True)
|
| 47 |
+
tm.assert_extension_array_equal(result, expected)
|
| 48 |
+
|
| 49 |
+
# ensure we haven't mutated anything inplace
|
| 50 |
+
result[0] = pd.NA
|
| 51 |
+
tm.assert_extension_array_equal(left, pd.array([1, 0, None], dtype=dtype))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class NumericOps:
|
| 55 |
+
# Shared by IntegerArray and FloatingArray, not BooleanArray
|
| 56 |
+
|
| 57 |
+
def test_searchsorted_nan(self, dtype):
|
| 58 |
+
# The base class casts to object dtype, for which searchsorted returns
|
| 59 |
+
# 0 from the left and 10 from the right.
|
| 60 |
+
arr = pd.array(range(10), dtype=dtype)
|
| 61 |
+
|
| 62 |
+
assert arr.searchsorted(np.nan, side="left") == 10
|
| 63 |
+
assert arr.searchsorted(np.nan, side="right") == 10
|
| 64 |
+
|
| 65 |
+
def test_no_shared_mask(self, data):
|
| 66 |
+
result = data + 1
|
| 67 |
+
assert not tm.shares_memory(result, data)
|
| 68 |
+
|
| 69 |
+
def test_array(self, comparison_op, dtype):
|
| 70 |
+
op = comparison_op
|
| 71 |
+
|
| 72 |
+
left = pd.array([0, 1, 2, None, None, None], dtype=dtype)
|
| 73 |
+
right = pd.array([0, 1, None, 0, 1, None], dtype=dtype)
|
| 74 |
+
|
| 75 |
+
result = op(left, right)
|
| 76 |
+
values = op(left._data, right._data)
|
| 77 |
+
mask = left._mask | right._mask
|
| 78 |
+
|
| 79 |
+
expected = pd.arrays.BooleanArray(values, mask)
|
| 80 |
+
tm.assert_extension_array_equal(result, expected)
|
| 81 |
+
|
| 82 |
+
# ensure we haven't mutated anything inplace
|
| 83 |
+
result[0] = pd.NA
|
| 84 |
+
tm.assert_extension_array_equal(
|
| 85 |
+
left, pd.array([0, 1, 2, None, None, None], dtype=dtype)
|
| 86 |
+
)
|
| 87 |
+
tm.assert_extension_array_equal(
|
| 88 |
+
right, pd.array([0, 1, None, 0, 1, None], dtype=dtype)
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
def test_compare_with_booleanarray(self, comparison_op, dtype):
|
| 92 |
+
op = comparison_op
|
| 93 |
+
|
| 94 |
+
left = pd.array([True, False, None] * 3, dtype="boolean")
|
| 95 |
+
right = pd.array([0] * 3 + [1] * 3 + [None] * 3, dtype=dtype)
|
| 96 |
+
other = pd.array([False] * 3 + [True] * 3 + [None] * 3, dtype="boolean")
|
| 97 |
+
|
| 98 |
+
expected = op(left, other)
|
| 99 |
+
result = op(left, right)
|
| 100 |
+
tm.assert_extension_array_equal(result, expected)
|
| 101 |
+
|
| 102 |
+
# reversed op
|
| 103 |
+
expected = op(other, left)
|
| 104 |
+
result = op(right, left)
|
| 105 |
+
tm.assert_extension_array_equal(result, expected)
|
| 106 |
+
|
| 107 |
+
def test_compare_to_string(self, dtype):
|
| 108 |
+
# GH#28930
|
| 109 |
+
ser = pd.Series([1, None], dtype=dtype)
|
| 110 |
+
result = ser == "a"
|
| 111 |
+
expected = pd.Series([False, pd.NA], dtype="boolean")
|
| 112 |
+
|
| 113 |
+
tm.assert_series_equal(result, expected)
|
| 114 |
+
|
| 115 |
+
def test_ufunc_with_out(self, dtype):
|
| 116 |
+
arr = pd.array([1, 2, 3], dtype=dtype)
|
| 117 |
+
arr2 = pd.array([1, 2, pd.NA], dtype=dtype)
|
| 118 |
+
|
| 119 |
+
mask = arr == arr
|
| 120 |
+
mask2 = arr2 == arr2
|
| 121 |
+
|
| 122 |
+
result = np.zeros(3, dtype=bool)
|
| 123 |
+
result |= mask
|
| 124 |
+
# If MaskedArray.__array_ufunc__ handled "out" appropriately,
|
| 125 |
+
# `result` should still be an ndarray.
|
| 126 |
+
assert isinstance(result, np.ndarray)
|
| 127 |
+
assert result.all()
|
| 128 |
+
|
| 129 |
+
# result |= mask worked because mask could be cast losslessly to
|
| 130 |
+
# boolean ndarray. mask2 can't, so this raises
|
| 131 |
+
result = np.zeros(3, dtype=bool)
|
| 132 |
+
msg = "Specify an appropriate 'na_value' for this dtype"
|
| 133 |
+
with pytest.raises(ValueError, match=msg):
|
| 134 |
+
result |= mask2
|
| 135 |
+
|
| 136 |
+
# addition
|
| 137 |
+
res = np.add(arr, arr2)
|
| 138 |
+
expected = pd.array([2, 4, pd.NA], dtype=dtype)
|
| 139 |
+
tm.assert_extension_array_equal(res, expected)
|
| 140 |
+
|
| 141 |
+
# when passing out=arr, we will modify 'arr' inplace.
|
| 142 |
+
res = np.add(arr, arr2, out=arr)
|
| 143 |
+
assert res is arr
|
| 144 |
+
tm.assert_extension_array_equal(res, expected)
|
| 145 |
+
tm.assert_extension_array_equal(arr, expected)
|
| 146 |
+
|
| 147 |
+
def test_mul_td64_array(self, dtype):
|
| 148 |
+
# GH#45622
|
| 149 |
+
arr = pd.array([1, 2, pd.NA], dtype=dtype)
|
| 150 |
+
other = np.arange(3, dtype=np.int64).view("m8[ns]")
|
| 151 |
+
|
| 152 |
+
result = arr * other
|
| 153 |
+
expected = pd.array([pd.Timedelta(0), pd.Timedelta(2), pd.NaT])
|
| 154 |
+
tm.assert_extension_array_equal(result, expected)
|
shared/package-files/00/00e743ca2baee2dda2b691e115c05dbd8f93833ce2d47c10367bb695adf2697c/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from .dialogs import (
|
| 4 |
+
button_dialog,
|
| 5 |
+
checkboxlist_dialog,
|
| 6 |
+
input_dialog,
|
| 7 |
+
message_dialog,
|
| 8 |
+
progress_dialog,
|
| 9 |
+
radiolist_dialog,
|
| 10 |
+
yes_no_dialog,
|
| 11 |
+
)
|
| 12 |
+
from .progress_bar import ProgressBar, ProgressBarCounter
|
| 13 |
+
from .prompt import (
|
| 14 |
+
CompleteStyle,
|
| 15 |
+
PromptSession,
|
| 16 |
+
confirm,
|
| 17 |
+
create_confirm_session,
|
| 18 |
+
prompt,
|
| 19 |
+
)
|
| 20 |
+
from .utils import clear, clear_title, print_container, print_formatted_text, set_title
|
| 21 |
+
|
| 22 |
+
__all__ = [
|
| 23 |
+
# Dialogs.
|
| 24 |
+
"input_dialog",
|
| 25 |
+
"message_dialog",
|
| 26 |
+
"progress_dialog",
|
| 27 |
+
"checkboxlist_dialog",
|
| 28 |
+
"radiolist_dialog",
|
| 29 |
+
"yes_no_dialog",
|
| 30 |
+
"button_dialog",
|
| 31 |
+
# Prompts.
|
| 32 |
+
"PromptSession",
|
| 33 |
+
"prompt",
|
| 34 |
+
"confirm",
|
| 35 |
+
"create_confirm_session",
|
| 36 |
+
"CompleteStyle",
|
| 37 |
+
# Progress bars.
|
| 38 |
+
"ProgressBar",
|
| 39 |
+
"ProgressBarCounter",
|
| 40 |
+
# Utils.
|
| 41 |
+
"clear",
|
| 42 |
+
"clear_title",
|
| 43 |
+
"print_container",
|
| 44 |
+
"print_formatted_text",
|
| 45 |
+
"set_title",
|
| 46 |
+
]
|
shared/package-files/4b/4b0063276c1c66181a36591cbb41f28afcf01f91e6115f1fb733b8c0072353ca/_sparse_csc_tensor_unsafe_native.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 _sparse_csc_tensor_unsafe(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, c10::optional<at::ScalarType> dtype={}, c10::optional<at::Layout> layout={}, c10::optional<at::Device> device={}, c10::optional<bool> pin_memory={});
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
shared/package-files/4b/4b00fa42c7d296b11da43d9d6e470deb608f54844fe5269d8c2a652eb300a1af/test_baseclasses.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.categories import (Object, Morphism, IdentityMorphism,
|
| 2 |
+
NamedMorphism, CompositeMorphism,
|
| 3 |
+
Diagram, Category)
|
| 4 |
+
from sympy.categories.baseclasses import Class
|
| 5 |
+
from sympy.testing.pytest import raises
|
| 6 |
+
from sympy.core.containers import (Dict, Tuple)
|
| 7 |
+
from sympy.sets import EmptySet
|
| 8 |
+
from sympy.sets.sets import FiniteSet
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_morphisms():
|
| 12 |
+
A = Object("A")
|
| 13 |
+
B = Object("B")
|
| 14 |
+
C = Object("C")
|
| 15 |
+
D = Object("D")
|
| 16 |
+
|
| 17 |
+
# Test the base morphism.
|
| 18 |
+
f = NamedMorphism(A, B, "f")
|
| 19 |
+
assert f.domain == A
|
| 20 |
+
assert f.codomain == B
|
| 21 |
+
assert f == NamedMorphism(A, B, "f")
|
| 22 |
+
|
| 23 |
+
# Test identities.
|
| 24 |
+
id_A = IdentityMorphism(A)
|
| 25 |
+
id_B = IdentityMorphism(B)
|
| 26 |
+
assert id_A.domain == A
|
| 27 |
+
assert id_A.codomain == A
|
| 28 |
+
assert id_A == IdentityMorphism(A)
|
| 29 |
+
assert id_A != id_B
|
| 30 |
+
|
| 31 |
+
# Test named morphisms.
|
| 32 |
+
g = NamedMorphism(B, C, "g")
|
| 33 |
+
assert g.name == "g"
|
| 34 |
+
assert g != f
|
| 35 |
+
assert g == NamedMorphism(B, C, "g")
|
| 36 |
+
assert g != NamedMorphism(B, C, "f")
|
| 37 |
+
|
| 38 |
+
# Test composite morphisms.
|
| 39 |
+
assert f == CompositeMorphism(f)
|
| 40 |
+
|
| 41 |
+
k = g.compose(f)
|
| 42 |
+
assert k.domain == A
|
| 43 |
+
assert k.codomain == C
|
| 44 |
+
assert k.components == Tuple(f, g)
|
| 45 |
+
assert g * f == k
|
| 46 |
+
assert CompositeMorphism(f, g) == k
|
| 47 |
+
|
| 48 |
+
assert CompositeMorphism(g * f) == g * f
|
| 49 |
+
|
| 50 |
+
# Test the associativity of composition.
|
| 51 |
+
h = NamedMorphism(C, D, "h")
|
| 52 |
+
|
| 53 |
+
p = h * g
|
| 54 |
+
u = h * g * f
|
| 55 |
+
|
| 56 |
+
assert h * k == u
|
| 57 |
+
assert p * f == u
|
| 58 |
+
assert CompositeMorphism(f, g, h) == u
|
| 59 |
+
|
| 60 |
+
# Test flattening.
|
| 61 |
+
u2 = u.flatten("u")
|
| 62 |
+
assert isinstance(u2, NamedMorphism)
|
| 63 |
+
assert u2.name == "u"
|
| 64 |
+
assert u2.domain == A
|
| 65 |
+
assert u2.codomain == D
|
| 66 |
+
|
| 67 |
+
# Test identities.
|
| 68 |
+
assert f * id_A == f
|
| 69 |
+
assert id_B * f == f
|
| 70 |
+
assert id_A * id_A == id_A
|
| 71 |
+
assert CompositeMorphism(id_A) == id_A
|
| 72 |
+
|
| 73 |
+
# Test bad compositions.
|
| 74 |
+
raises(ValueError, lambda: f * g)
|
| 75 |
+
|
| 76 |
+
raises(TypeError, lambda: f.compose(None))
|
| 77 |
+
raises(TypeError, lambda: id_A.compose(None))
|
| 78 |
+
raises(TypeError, lambda: f * None)
|
| 79 |
+
raises(TypeError, lambda: id_A * None)
|
| 80 |
+
|
| 81 |
+
raises(TypeError, lambda: CompositeMorphism(f, None, 1))
|
| 82 |
+
|
| 83 |
+
raises(ValueError, lambda: NamedMorphism(A, B, ""))
|
| 84 |
+
raises(NotImplementedError, lambda: Morphism(A, B))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_diagram():
|
| 88 |
+
A = Object("A")
|
| 89 |
+
B = Object("B")
|
| 90 |
+
C = Object("C")
|
| 91 |
+
|
| 92 |
+
f = NamedMorphism(A, B, "f")
|
| 93 |
+
g = NamedMorphism(B, C, "g")
|
| 94 |
+
id_A = IdentityMorphism(A)
|
| 95 |
+
id_B = IdentityMorphism(B)
|
| 96 |
+
|
| 97 |
+
empty = EmptySet
|
| 98 |
+
|
| 99 |
+
# Test the addition of identities.
|
| 100 |
+
d1 = Diagram([f])
|
| 101 |
+
|
| 102 |
+
assert d1.objects == FiniteSet(A, B)
|
| 103 |
+
assert d1.hom(A, B) == (FiniteSet(f), empty)
|
| 104 |
+
assert d1.hom(A, A) == (FiniteSet(id_A), empty)
|
| 105 |
+
assert d1.hom(B, B) == (FiniteSet(id_B), empty)
|
| 106 |
+
|
| 107 |
+
assert d1 == Diagram([id_A, f])
|
| 108 |
+
assert d1 == Diagram([f, f])
|
| 109 |
+
|
| 110 |
+
# Test the addition of composites.
|
| 111 |
+
d2 = Diagram([f, g])
|
| 112 |
+
homAC = d2.hom(A, C)[0]
|
| 113 |
+
|
| 114 |
+
assert d2.objects == FiniteSet(A, B, C)
|
| 115 |
+
assert g * f in d2.premises.keys()
|
| 116 |
+
assert homAC == FiniteSet(g * f)
|
| 117 |
+
|
| 118 |
+
# Test equality, inequality and hash.
|
| 119 |
+
d11 = Diagram([f])
|
| 120 |
+
|
| 121 |
+
assert d1 == d11
|
| 122 |
+
assert d1 != d2
|
| 123 |
+
assert hash(d1) == hash(d11)
|
| 124 |
+
|
| 125 |
+
d11 = Diagram({f: "unique"})
|
| 126 |
+
assert d1 != d11
|
| 127 |
+
|
| 128 |
+
# Make sure that (re-)adding composites (with new properties)
|
| 129 |
+
# works as expected.
|
| 130 |
+
d = Diagram([f, g], {g * f: "unique"})
|
| 131 |
+
assert d.conclusions == Dict({g * f: FiniteSet("unique")})
|
| 132 |
+
|
| 133 |
+
# Check the hom-sets when there are premises and conclusions.
|
| 134 |
+
assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f))
|
| 135 |
+
d = Diagram([f, g], [g * f])
|
| 136 |
+
assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f))
|
| 137 |
+
|
| 138 |
+
# Check how the properties of composite morphisms are computed.
|
| 139 |
+
d = Diagram({f: ["unique", "isomorphism"], g: "unique"})
|
| 140 |
+
assert d.premises[g * f] == FiniteSet("unique")
|
| 141 |
+
|
| 142 |
+
# Check that conclusion morphisms with new objects are not allowed.
|
| 143 |
+
d = Diagram([f], [g])
|
| 144 |
+
assert d.conclusions == Dict({})
|
| 145 |
+
|
| 146 |
+
# Test an empty diagram.
|
| 147 |
+
d = Diagram()
|
| 148 |
+
assert d.premises == Dict({})
|
| 149 |
+
assert d.conclusions == Dict({})
|
| 150 |
+
assert d.objects == empty
|
| 151 |
+
|
| 152 |
+
# Check a SymPy Dict object.
|
| 153 |
+
d = Diagram(Dict({f: FiniteSet("unique", "isomorphism"), g: "unique"}))
|
| 154 |
+
assert d.premises[g * f] == FiniteSet("unique")
|
| 155 |
+
|
| 156 |
+
# Check the addition of components of composite morphisms.
|
| 157 |
+
d = Diagram([g * f])
|
| 158 |
+
assert f in d.premises
|
| 159 |
+
assert g in d.premises
|
| 160 |
+
|
| 161 |
+
# Check subdiagrams.
|
| 162 |
+
d = Diagram([f, g], {g * f: "unique"})
|
| 163 |
+
|
| 164 |
+
d1 = Diagram([f])
|
| 165 |
+
assert d.is_subdiagram(d1)
|
| 166 |
+
assert not d1.is_subdiagram(d)
|
| 167 |
+
|
| 168 |
+
d = Diagram([NamedMorphism(B, A, "f'")])
|
| 169 |
+
assert not d.is_subdiagram(d1)
|
| 170 |
+
assert not d1.is_subdiagram(d)
|
| 171 |
+
|
| 172 |
+
d1 = Diagram([f, g], {g * f: ["unique", "something"]})
|
| 173 |
+
assert not d.is_subdiagram(d1)
|
| 174 |
+
assert not d1.is_subdiagram(d)
|
| 175 |
+
|
| 176 |
+
d = Diagram({f: "blooh"})
|
| 177 |
+
d1 = Diagram({f: "bleeh"})
|
| 178 |
+
assert not d.is_subdiagram(d1)
|
| 179 |
+
assert not d1.is_subdiagram(d)
|
| 180 |
+
|
| 181 |
+
d = Diagram([f, g], {f: "unique", g * f: "veryunique"})
|
| 182 |
+
d1 = d.subdiagram_from_objects(FiniteSet(A, B))
|
| 183 |
+
assert d1 == Diagram([f], {f: "unique"})
|
| 184 |
+
raises(ValueError, lambda: d.subdiagram_from_objects(FiniteSet(A,
|
| 185 |
+
Object("D"))))
|
| 186 |
+
|
| 187 |
+
raises(ValueError, lambda: Diagram({IdentityMorphism(A): "unique"}))
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_category():
|
| 191 |
+
A = Object("A")
|
| 192 |
+
B = Object("B")
|
| 193 |
+
C = Object("C")
|
| 194 |
+
|
| 195 |
+
f = NamedMorphism(A, B, "f")
|
| 196 |
+
g = NamedMorphism(B, C, "g")
|
| 197 |
+
|
| 198 |
+
d1 = Diagram([f, g])
|
| 199 |
+
d2 = Diagram([f])
|
| 200 |
+
|
| 201 |
+
objects = d1.objects | d2.objects
|
| 202 |
+
|
| 203 |
+
K = Category("K", objects, commutative_diagrams=[d1, d2])
|
| 204 |
+
|
| 205 |
+
assert K.name == "K"
|
| 206 |
+
assert K.objects == Class(objects)
|
| 207 |
+
assert K.commutative_diagrams == FiniteSet(d1, d2)
|
| 208 |
+
|
| 209 |
+
raises(ValueError, lambda: Category(""))
|
shared/package-files/4b/4b0361a3789666efe526f71d4a8980e5c41d70353c82870a6e64679ba05ff7ed/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Sparse Eigenvalue Solvers
|
| 3 |
+
-------------------------
|
| 4 |
+
|
| 5 |
+
The submodules of sparse.linalg._eigen:
|
| 6 |
+
1. lobpcg: Locally Optimal Block Preconditioned Conjugate Gradient Method
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
from .arpack import *
|
| 10 |
+
from .lobpcg import *
|
| 11 |
+
from ._svds import svds
|
| 12 |
+
|
| 13 |
+
from . import arpack
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
'ArpackError', 'ArpackNoConvergence',
|
| 17 |
+
'eigs', 'eigsh', 'lobpcg', 'svds'
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
from scipy._lib._testutils import PytestTester
|
| 21 |
+
test = PytestTester(__name__)
|
| 22 |
+
del PytestTester
|
shared/package-files/4b/4b0b3db9869b94cf6b589eea31e71e171a5f523b19334f9cad5c3a5729187a67/exponential_smoothing_params.csv
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"","oil_fpp1","oil_fpp2","oil_fpp3","oil_ets","air_fpp1","air_fpp2","air_ets","aust_fpp1","aust_ets1","aust_ets2","aust_ets3"
|
| 2 |
+
"alpha",0.2,0.6,0.891956021483951,0.892109662581714,0.8,0.8,0.99591248359386,0.362500481843614,0.362426132365822,0.280488397086475,0.533839350626543
|
| 3 |
+
"beta_star",NA,NA,NA,NA,0.2,NA,NA,NA,NA,NA,NA
|
| 4 |
+
"beta",NA,NA,NA,NA,NA,0.2,0.000100000177749125,0.0754341632786649,0.0754190455497834,0.000107909350046852,NA
|
| 5 |
+
"gamma",NA,NA,NA,NA,NA,NA,NA,0.63749564203014,0.637569422468331,0.70817204866374,0.466160630654508
|
| 6 |
+
"phi",NA,NA,NA,NA,NA,0.850219271948577,0.975837884841967,NA,NA,0.934556132735162,NA
|
| 7 |
+
"l0",446.6565229,446.6565229,447.483644169658,447.4765151319,17.5534,13.9648223911759,16.6430315594723,31.6429376250105,31.6432606420664,30.8411433051289,32.6308030872576
|
| 8 |
+
"b0",NA,NA,NA,NA,4.3067,4.50545211897653,2.29728622390832,1.00282356207448,1.00279733904072,1.42536708194344,NA
|
| 9 |
+
"s0_0",NA,NA,NA,NA,NA,NA,NA,2.0685005855211,2.06807190359294,1.36918887747184,2.31737355127666
|
| 10 |
+
"s0_1",NA,NA,NA,NA,NA,NA,NA,-2.02739592581295,-2.02733922834511,-1.87117054599654,-1.97439136441432
|
| 11 |
+
"s0_2",NA,NA,NA,NA,NA,NA,NA,-9.46755384381316,-9.46732416254387,-9.63885827145074,-9.31769673439368
|
| 12 |
+
"sigma2",1032.64559793583,674.879573349505,757.342045162521,757.342048406917,4.85263034249838,4.10324314559494,3.86535913444311,3.75145949470755,3.75145957477554,3.4698670407518,4.44162514270279
|
| 13 |
+
"sse",12391.7471752299,8098.55488019406,NA,NA,72.7894551374757,NA,NA,NA,NA,NA,NA
|
| 14 |
+
"llf",NA,NA,-53.5944005243784,-53.5944005500819,NA,-27.8577207385546,-27.409797677742,-49.1368042211119,-49.1368044772298,-47.4259977304878,-52.5767050860172
|
| 15 |
+
"mse",NA,NA,631.118370968767,631.11837367243,NA,2.73549543039663,2.57690608962874,2.5009729964717,2.50097304985036,2.16866690046988,3.33121885702709
|
shared/package-files/4b/4b0be99729c93d746824518a627a1cad2e0afe37a5c151b47029a207cc1df4ec/output-archive.h
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/csrc/Export.h>
|
| 4 |
+
#include <torch/csrc/jit/api/module.h>
|
| 5 |
+
|
| 6 |
+
#include <iosfwd>
|
| 7 |
+
#include <memory>
|
| 8 |
+
#include <string>
|
| 9 |
+
#include <utility>
|
| 10 |
+
|
| 11 |
+
namespace at {
|
| 12 |
+
class Tensor;
|
| 13 |
+
} // namespace at
|
| 14 |
+
|
| 15 |
+
namespace torch {
|
| 16 |
+
using at::Tensor;
|
| 17 |
+
namespace jit {
|
| 18 |
+
struct Module;
|
| 19 |
+
} // namespace jit
|
| 20 |
+
} // namespace torch
|
| 21 |
+
|
| 22 |
+
namespace torch {
|
| 23 |
+
namespace serialize {
|
| 24 |
+
class TORCH_API OutputArchive final {
|
| 25 |
+
public:
|
| 26 |
+
explicit OutputArchive(std::shared_ptr<jit::CompilationUnit> cu);
|
| 27 |
+
explicit OutputArchive()
|
| 28 |
+
: cu_(std::make_shared<jit::CompilationUnit>()),
|
| 29 |
+
module_("__torch__.Module", cu_) {}
|
| 30 |
+
|
| 31 |
+
// Move is allowed.
|
| 32 |
+
OutputArchive(OutputArchive&&) = default;
|
| 33 |
+
OutputArchive& operator=(OutputArchive&&) = default;
|
| 34 |
+
|
| 35 |
+
// Copy is disallowed.
|
| 36 |
+
OutputArchive(OutputArchive&) = delete;
|
| 37 |
+
OutputArchive& operator=(OutputArchive&) = delete;
|
| 38 |
+
|
| 39 |
+
std::shared_ptr<jit::CompilationUnit> compilation_unit() const {
|
| 40 |
+
return cu_;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
/// Writes an `IValue` to the `OutputArchive`.
|
| 44 |
+
void write(const std::string& key, const c10::IValue& ivalue);
|
| 45 |
+
|
| 46 |
+
/// Writes a `(key, tensor)` pair to the `OutputArchive`, and marks it as
|
| 47 |
+
/// being or not being a buffer (non-differentiable tensor).
|
| 48 |
+
void write(
|
| 49 |
+
const std::string& key,
|
| 50 |
+
const Tensor& tensor,
|
| 51 |
+
bool is_buffer = false);
|
| 52 |
+
|
| 53 |
+
/// Writes a nested `OutputArchive` under the given `key` to this
|
| 54 |
+
/// `OutputArchive`.
|
| 55 |
+
void write(const std::string& key, OutputArchive& nested_archive);
|
| 56 |
+
|
| 57 |
+
/// Saves the `OutputArchive` into a serialized representation in a file at
|
| 58 |
+
/// `filename`.
|
| 59 |
+
void save_to(const std::string& filename);
|
| 60 |
+
|
| 61 |
+
/// Saves the `OutputArchive` into a serialized representation into the given
|
| 62 |
+
/// `stream`.
|
| 63 |
+
void save_to(std::ostream& stream);
|
| 64 |
+
|
| 65 |
+
/// Saves the `OutputArchive` into a serialized representation using the
|
| 66 |
+
/// given writer function.
|
| 67 |
+
void save_to(const std::function<size_t(const void*, size_t)>& func);
|
| 68 |
+
|
| 69 |
+
/// Forwards all arguments to `write()`.
|
| 70 |
+
/// Useful for generic code that can be re-used for both `OutputArchive` and
|
| 71 |
+
/// `InputArchive` (where `operator()` forwards to `read()`).
|
| 72 |
+
template <typename... Ts>
|
| 73 |
+
void operator()(Ts&&... ts) {
|
| 74 |
+
write(std::forward<Ts>(ts)...);
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
private:
|
| 78 |
+
std::shared_ptr<jit::CompilationUnit> cu_;
|
| 79 |
+
jit::Module module_;
|
| 80 |
+
};
|
| 81 |
+
} // namespace serialize
|
| 82 |
+
} // namespace torch
|
shared/package-files/4b/4b0fd07726244c98a5cc3690328e628c22155de2396c370dcd466b07b7b6534a/diff.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import subprocess
|
| 3 |
+
import tempfile
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
from difflib import unified_diff
|
| 6 |
+
from multiprocessing import Pool, cpu_count
|
| 7 |
+
from typing import Any, Callable, Iterable, Iterator, List, Optional, Text, Tuple
|
| 8 |
+
|
| 9 |
+
from fontTools.ttLib import TTFont # type: ignore
|
| 10 |
+
|
| 11 |
+
from .utils import get_file_modtime
|
| 12 |
+
|
| 13 |
+
#
|
| 14 |
+
#
|
| 15 |
+
# Private functions
|
| 16 |
+
#
|
| 17 |
+
#
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _get_fonts_and_save_xml(
|
| 21 |
+
filepath_a: Text,
|
| 22 |
+
filepath_b: Text,
|
| 23 |
+
tmpdirpath: Text,
|
| 24 |
+
include_tables: Optional[List[Text]],
|
| 25 |
+
exclude_tables: Optional[List[Text]],
|
| 26 |
+
font_number_a: int,
|
| 27 |
+
font_number_b: int,
|
| 28 |
+
use_multiprocess: bool,
|
| 29 |
+
) -> Tuple[Text, Text, Text, Text, Text, Text]:
|
| 30 |
+
post_pathname, postpath, pre_pathname, prepath = _get_pre_post_paths(
|
| 31 |
+
filepath_a, filepath_b
|
| 32 |
+
)
|
| 33 |
+
# instantiate left and right fontTools.ttLib.TTFont objects
|
| 34 |
+
tt_left = TTFont(prepath, fontNumber=font_number_a)
|
| 35 |
+
tt_right = TTFont(postpath, fontNumber=font_number_b)
|
| 36 |
+
left_ttxpath = os.path.join(tmpdirpath, "left.ttx")
|
| 37 |
+
right_ttxpath = os.path.join(tmpdirpath, "right.ttx")
|
| 38 |
+
_mp_save_ttx_xml(
|
| 39 |
+
tt_left,
|
| 40 |
+
tt_right,
|
| 41 |
+
left_ttxpath,
|
| 42 |
+
right_ttxpath,
|
| 43 |
+
exclude_tables,
|
| 44 |
+
include_tables,
|
| 45 |
+
use_multiprocess,
|
| 46 |
+
)
|
| 47 |
+
return left_ttxpath, right_ttxpath, pre_pathname, prepath, post_pathname, postpath
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _get_pre_post_paths(
|
| 51 |
+
filepath_a: Text,
|
| 52 |
+
filepath_b: Text,
|
| 53 |
+
) -> Tuple[Text, Text, Text, Text]:
|
| 54 |
+
prepath = filepath_a
|
| 55 |
+
postpath = filepath_b
|
| 56 |
+
pre_pathname = filepath_a
|
| 57 |
+
post_pathname = filepath_b
|
| 58 |
+
return post_pathname, postpath, pre_pathname, prepath
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _mp_save_ttx_xml(
|
| 62 |
+
tt_left: Any,
|
| 63 |
+
tt_right: Any,
|
| 64 |
+
left_ttxpath: Text,
|
| 65 |
+
right_ttxpath: Text,
|
| 66 |
+
exclude_tables: Optional[List[Text]],
|
| 67 |
+
include_tables: Optional[List[Text]],
|
| 68 |
+
use_multiprocess: bool,
|
| 69 |
+
) -> None:
|
| 70 |
+
if use_multiprocess and cpu_count() > 1:
|
| 71 |
+
# Use parallel fontTools.ttLib.TTFont.saveXML dump
|
| 72 |
+
# by default on multi CPU systems. This is a performance
|
| 73 |
+
# optimization. Profiling demonstrates that this can reduce
|
| 74 |
+
# execution time by up to 30% for some fonts
|
| 75 |
+
mp_args_list = [
|
| 76 |
+
(tt_left, left_ttxpath, include_tables, exclude_tables),
|
| 77 |
+
(tt_right, right_ttxpath, include_tables, exclude_tables),
|
| 78 |
+
]
|
| 79 |
+
with Pool(processes=2) as pool:
|
| 80 |
+
pool.starmap(_ttfont_save_xml, mp_args_list)
|
| 81 |
+
else:
|
| 82 |
+
# use sequential fontTools.ttLib.TTFont.saveXML dumps
|
| 83 |
+
# when use_multiprocess is False or single CPU system
|
| 84 |
+
# detected
|
| 85 |
+
_ttfont_save_xml(tt_left, left_ttxpath, include_tables, exclude_tables)
|
| 86 |
+
_ttfont_save_xml(tt_right, right_ttxpath, include_tables, exclude_tables)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _ttfont_save_xml(
|
| 90 |
+
ttf: Any,
|
| 91 |
+
filepath: Text,
|
| 92 |
+
include_tables: Optional[List[Text]],
|
| 93 |
+
exclude_tables: Optional[List[Text]],
|
| 94 |
+
) -> bool:
|
| 95 |
+
"""Writes TTX specification formatted XML to disk on filepath."""
|
| 96 |
+
ttf.saveXML(filepath, tables=include_tables, skipTables=exclude_tables)
|
| 97 |
+
return True
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@contextmanager
|
| 101 |
+
def _saved_ttx_files(
|
| 102 |
+
filepath_a: Text,
|
| 103 |
+
filepath_b: Text,
|
| 104 |
+
include_tables: Optional[List[Text]],
|
| 105 |
+
exclude_tables: Optional[List[Text]],
|
| 106 |
+
font_number_a: int,
|
| 107 |
+
font_number_b: int,
|
| 108 |
+
use_multiprocess: bool,
|
| 109 |
+
) -> Iterator[Tuple[Text, Text, Text, Text, Text, Text]]:
|
| 110 |
+
with tempfile.TemporaryDirectory() as tmpdirpath:
|
| 111 |
+
yield _get_fonts_and_save_xml(
|
| 112 |
+
filepath_a,
|
| 113 |
+
filepath_b,
|
| 114 |
+
tmpdirpath,
|
| 115 |
+
include_tables,
|
| 116 |
+
exclude_tables,
|
| 117 |
+
font_number_a,
|
| 118 |
+
font_number_b,
|
| 119 |
+
use_multiprocess,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _diff_with_saved_ttx_files(
|
| 124 |
+
filepath_a: Text,
|
| 125 |
+
filepath_b: Text,
|
| 126 |
+
include_tables: Optional[List[Text]],
|
| 127 |
+
exclude_tables: Optional[List[Text]],
|
| 128 |
+
font_number_a: int,
|
| 129 |
+
font_number_b: int,
|
| 130 |
+
use_multiprocess: bool,
|
| 131 |
+
create_differ: Callable[[Text, Text, Text, Text, Text, Text], Iterable[Text]],
|
| 132 |
+
) -> Iterator[Text]:
|
| 133 |
+
with _saved_ttx_files(
|
| 134 |
+
filepath_a,
|
| 135 |
+
filepath_b,
|
| 136 |
+
include_tables,
|
| 137 |
+
exclude_tables,
|
| 138 |
+
font_number_a,
|
| 139 |
+
font_number_b,
|
| 140 |
+
use_multiprocess,
|
| 141 |
+
) as (
|
| 142 |
+
left_ttxpath,
|
| 143 |
+
right_ttxpath,
|
| 144 |
+
pre_pathname,
|
| 145 |
+
prepath,
|
| 146 |
+
post_pathname,
|
| 147 |
+
postpath,
|
| 148 |
+
):
|
| 149 |
+
yield from create_differ(
|
| 150 |
+
left_ttxpath,
|
| 151 |
+
right_ttxpath,
|
| 152 |
+
pre_pathname,
|
| 153 |
+
prepath,
|
| 154 |
+
post_pathname,
|
| 155 |
+
postpath,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
#
|
| 160 |
+
#
|
| 161 |
+
# Public functions
|
| 162 |
+
#
|
| 163 |
+
#
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def u_diff(
|
| 167 |
+
filepath_a: Text,
|
| 168 |
+
filepath_b: Text,
|
| 169 |
+
context_lines: int = 3,
|
| 170 |
+
include_tables: Optional[List[Text]] = None,
|
| 171 |
+
exclude_tables: Optional[List[Text]] = None,
|
| 172 |
+
font_number_a: int = -1,
|
| 173 |
+
font_number_b: int = -1,
|
| 174 |
+
use_multiprocess: bool = True,
|
| 175 |
+
) -> Iterator[Text]:
|
| 176 |
+
"""Performs a unified diff on a TTX serialized data format dump of font binary data using
|
| 177 |
+
a modified version of the Python standard libary difflib module.
|
| 178 |
+
|
| 179 |
+
filepath_a: (string) pre-file local file path
|
| 180 |
+
filepath_b: (string) post-file local file path
|
| 181 |
+
context_lines: (int) number of context lines to include in the diff (default=3)
|
| 182 |
+
include_tables: (list of str) Python list of OpenType tables to include in the diff
|
| 183 |
+
exclude_tables: (list of str) Python list of OpentType tables to exclude from the diff
|
| 184 |
+
use_multiprocess: (bool) use multi-processor optimizations (default=True)
|
| 185 |
+
|
| 186 |
+
include_tables and exclude_tables are mutually exclusive arguments. Only one should
|
| 187 |
+
be defined
|
| 188 |
+
|
| 189 |
+
:returns: Generator of ordered diff line strings that include newline line endings
|
| 190 |
+
:raises: KeyError if include_tables or exclude_tables includes a mis-specified table
|
| 191 |
+
that is not included in filepath_a OR filepath_b
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
def _create_unified_diff(
|
| 195 |
+
left_ttxpath: Text,
|
| 196 |
+
right_ttxpath: Text,
|
| 197 |
+
pre_pathname: Text,
|
| 198 |
+
prepath: Text,
|
| 199 |
+
post_pathname: Text,
|
| 200 |
+
postpath: Text,
|
| 201 |
+
) -> Iterable[Text]:
|
| 202 |
+
with open(left_ttxpath) as ff:
|
| 203 |
+
fromlines = ff.readlines()
|
| 204 |
+
with open(right_ttxpath) as tf:
|
| 205 |
+
tolines = tf.readlines()
|
| 206 |
+
|
| 207 |
+
fromdate = get_file_modtime(prepath)
|
| 208 |
+
todate = get_file_modtime(postpath)
|
| 209 |
+
|
| 210 |
+
yield from unified_diff(
|
| 211 |
+
fromlines,
|
| 212 |
+
tolines,
|
| 213 |
+
pre_pathname,
|
| 214 |
+
post_pathname,
|
| 215 |
+
fromdate,
|
| 216 |
+
todate,
|
| 217 |
+
n=context_lines,
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
yield from _diff_with_saved_ttx_files(
|
| 221 |
+
filepath_a,
|
| 222 |
+
filepath_b,
|
| 223 |
+
include_tables,
|
| 224 |
+
exclude_tables,
|
| 225 |
+
font_number_a,
|
| 226 |
+
font_number_b,
|
| 227 |
+
use_multiprocess,
|
| 228 |
+
_create_unified_diff,
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def run_external_diff(
|
| 233 |
+
diff_tool: Text,
|
| 234 |
+
diff_args: List[Text],
|
| 235 |
+
filepath_a: Text,
|
| 236 |
+
filepath_b: Text,
|
| 237 |
+
include_tables: Optional[List[Text]] = None,
|
| 238 |
+
exclude_tables: Optional[List[Text]] = None,
|
| 239 |
+
font_number_a: int = -1,
|
| 240 |
+
font_number_b: int = -1,
|
| 241 |
+
use_multiprocess: bool = True,
|
| 242 |
+
) -> Iterator[Text]:
|
| 243 |
+
"""Performs a unified diff on a TTX serialized data format dump of font binary data using
|
| 244 |
+
an external diff executable that is requested by the caller via `command`
|
| 245 |
+
|
| 246 |
+
diff_tool: (string) command line executable string
|
| 247 |
+
diff_args: (list of strings) arguments for the diff tool
|
| 248 |
+
filepath_a: (string) pre-file local file path
|
| 249 |
+
filepath_b: (string) post-file local file path
|
| 250 |
+
include_tables: (list of str) Python list of OpenType tables to include in the diff
|
| 251 |
+
exclude_tables: (list of str) Python list of OpentType tables to exclude from the diff
|
| 252 |
+
use_multiprocess: (bool) use multi-processor optimizations (default=True)
|
| 253 |
+
|
| 254 |
+
include_tables and exclude_tables are mutually exclusive arguments. Only one should
|
| 255 |
+
be defined
|
| 256 |
+
|
| 257 |
+
:returns: Generator of ordered diff line strings that include newline line endings
|
| 258 |
+
:raises: KeyError if include_tables or exclude_tables includes a mis-specified table
|
| 259 |
+
that is not included in filepath_a OR filepath_b
|
| 260 |
+
:raises: IOError if exception raised during execution of `command` on TTX files
|
| 261 |
+
"""
|
| 262 |
+
|
| 263 |
+
def _create_external_diff(
|
| 264 |
+
left_ttxpath: Text,
|
| 265 |
+
right_ttxpath: Text,
|
| 266 |
+
_pre_pathname: Text,
|
| 267 |
+
_prepath: Text,
|
| 268 |
+
_post_pathname: Text,
|
| 269 |
+
_postpath: Text,
|
| 270 |
+
) -> Iterable[Text]:
|
| 271 |
+
command = [diff_tool] + diff_args + [left_ttxpath, right_ttxpath]
|
| 272 |
+
process = subprocess.Popen(
|
| 273 |
+
command,
|
| 274 |
+
stdout=subprocess.PIPE,
|
| 275 |
+
stderr=subprocess.PIPE,
|
| 276 |
+
encoding="utf8",
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
for line in process.stdout:
|
| 280 |
+
yield line
|
| 281 |
+
err = process.stderr.read()
|
| 282 |
+
if err:
|
| 283 |
+
raise IOError(err)
|
| 284 |
+
|
| 285 |
+
yield from _diff_with_saved_ttx_files(
|
| 286 |
+
filepath_a,
|
| 287 |
+
filepath_b,
|
| 288 |
+
include_tables,
|
| 289 |
+
exclude_tables,
|
| 290 |
+
font_number_a,
|
| 291 |
+
font_number_b,
|
| 292 |
+
use_multiprocess,
|
| 293 |
+
_create_external_diff,
|
| 294 |
+
)
|
shared/package-files/4b/4b120db5de236321f4616773b29afc251d2cc997cede7323ec2eb4196054afa9/_validation.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from scipy.sparse import issparse
|
| 3 |
+
from scipy.sparse._sputils import convert_pydata_sparse_to_scipy
|
| 4 |
+
from scipy.sparse.csgraph._tools import (
|
| 5 |
+
csgraph_to_dense, csgraph_from_dense,
|
| 6 |
+
csgraph_masked_from_dense, csgraph_from_masked
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
DTYPE = np.float64
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def validate_graph(csgraph, directed, dtype=DTYPE,
|
| 13 |
+
csr_output=True, dense_output=True,
|
| 14 |
+
copy_if_dense=False, copy_if_sparse=False,
|
| 15 |
+
null_value_in=0, null_value_out=np.inf,
|
| 16 |
+
infinity_null=True, nan_null=True):
|
| 17 |
+
"""Routine for validation and conversion of csgraph inputs"""
|
| 18 |
+
if not (csr_output or dense_output):
|
| 19 |
+
raise ValueError("Internal: dense or csr output must be true")
|
| 20 |
+
|
| 21 |
+
accept_fv = [null_value_in]
|
| 22 |
+
if infinity_null:
|
| 23 |
+
accept_fv.append(np.inf)
|
| 24 |
+
if nan_null:
|
| 25 |
+
accept_fv.append(np.nan)
|
| 26 |
+
csgraph = convert_pydata_sparse_to_scipy(csgraph, accept_fv=accept_fv)
|
| 27 |
+
|
| 28 |
+
# if undirected and csc storage, then transposing in-place
|
| 29 |
+
# is quicker than later converting to csr.
|
| 30 |
+
if (not directed) and issparse(csgraph) and csgraph.format == "csc":
|
| 31 |
+
csgraph = csgraph.T
|
| 32 |
+
|
| 33 |
+
if issparse(csgraph):
|
| 34 |
+
if csr_output:
|
| 35 |
+
csgraph = csgraph.tocsr(copy=copy_if_sparse).astype(DTYPE, copy=False)
|
| 36 |
+
else:
|
| 37 |
+
csgraph = csgraph_to_dense(csgraph, null_value=null_value_out)
|
| 38 |
+
elif np.ma.isMaskedArray(csgraph):
|
| 39 |
+
if dense_output:
|
| 40 |
+
mask = csgraph.mask
|
| 41 |
+
csgraph = np.array(csgraph.data, dtype=DTYPE, copy=copy_if_dense)
|
| 42 |
+
csgraph[mask] = null_value_out
|
| 43 |
+
else:
|
| 44 |
+
csgraph = csgraph_from_masked(csgraph)
|
| 45 |
+
else:
|
| 46 |
+
if dense_output:
|
| 47 |
+
csgraph = csgraph_masked_from_dense(csgraph,
|
| 48 |
+
copy=copy_if_dense,
|
| 49 |
+
null_value=null_value_in,
|
| 50 |
+
nan_null=nan_null,
|
| 51 |
+
infinity_null=infinity_null)
|
| 52 |
+
mask = csgraph.mask
|
| 53 |
+
csgraph = np.asarray(csgraph.data, dtype=DTYPE)
|
| 54 |
+
csgraph[mask] = null_value_out
|
| 55 |
+
else:
|
| 56 |
+
csgraph = csgraph_from_dense(csgraph, null_value=null_value_in,
|
| 57 |
+
infinity_null=infinity_null,
|
| 58 |
+
nan_null=nan_null)
|
| 59 |
+
|
| 60 |
+
if csgraph.ndim != 2:
|
| 61 |
+
raise ValueError("compressed-sparse graph must be 2-D")
|
| 62 |
+
|
| 63 |
+
if csgraph.shape[0] != csgraph.shape[1]:
|
| 64 |
+
raise ValueError("compressed-sparse graph must be shape (N, N)")
|
| 65 |
+
|
| 66 |
+
return csgraph
|
shared/package-files/4b/4b126d0a83e4d7aef97e0df0dc3205847d1f3e2124dc8d309ec724c0e114a3f5/inv_gaussian.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
shared/package-files/4b/4b12f6235acaa9eef75998243b9d753d6271db43f5eb457886bc2cd531b42539/byteswap.pyi
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def read_float_with_byteswap(data: bytes, offset: int, byteswap: bool) -> float: ...
|
| 2 |
+
def read_double_with_byteswap(data: bytes, offset: int, byteswap: bool) -> float: ...
|
| 3 |
+
def read_uint16_with_byteswap(data: bytes, offset: int, byteswap: bool) -> int: ...
|
| 4 |
+
def read_uint32_with_byteswap(data: bytes, offset: int, byteswap: bool) -> int: ...
|
| 5 |
+
def read_uint64_with_byteswap(data: bytes, offset: int, byteswap: bool) -> int: ...
|
shared/package-files/4b/4b131f22fd01af8f7a5622fc3221715d64dbf19caac6d67c2fb364113b7cfa77/upsample_nearest1d_backward_cuda_dispatch.h
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 cuda {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor upsample_nearest1d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional<double> scales=c10::nullopt);
|
| 21 |
+
TORCH_API at::Tensor upsample_nearest1d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional<double> scales=c10::nullopt);
|
| 22 |
+
TORCH_API at::Tensor & upsample_nearest1d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional<double> scales=c10::nullopt);
|
| 23 |
+
TORCH_API at::Tensor & upsample_nearest1d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional<double> scales, at::Tensor & grad_input);
|
| 24 |
+
TORCH_API at::Tensor & upsample_nearest1d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional<double> scales=c10::nullopt);
|
| 25 |
+
TORCH_API at::Tensor & upsample_nearest1d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional<double> scales, at::Tensor & grad_input);
|
| 26 |
+
|
| 27 |
+
} // namespace cuda
|
| 28 |
+
} // namespace at
|
shared/package-files/4b/4b1a1753c20901a95af2e052c43d5fe6d49629fcc24afc5d470b5be2d111be12/sugared_value.h
ADDED
|
@@ -0,0 +1,857 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
#include <c10/util/Optional.h>
|
| 3 |
+
#include <functional>
|
| 4 |
+
#include <memory>
|
| 5 |
+
#include <string>
|
| 6 |
+
#include <utility>
|
| 7 |
+
|
| 8 |
+
#include <ATen/core/symbol.h>
|
| 9 |
+
#include <caffe2/serialize/versions.h>
|
| 10 |
+
#include <torch/csrc/jit/api/module.h>
|
| 11 |
+
#include <torch/csrc/jit/frontend/error_report.h>
|
| 12 |
+
#include <torch/csrc/jit/frontend/schema_matching.h>
|
| 13 |
+
#include <torch/csrc/jit/frontend/versioned_symbols.h>
|
| 14 |
+
#include <torch/csrc/jit/ir/ir.h>
|
| 15 |
+
|
| 16 |
+
namespace torch {
|
| 17 |
+
namespace jit {
|
| 18 |
+
|
| 19 |
+
using SugaredValuePtr = std::shared_ptr<SugaredValue>;
|
| 20 |
+
|
| 21 |
+
// The AST can contain nodes like `self`, `self.b` or `python_fn` that
|
| 22 |
+
// are not first-class values in the graph representation, but instead
|
| 23 |
+
// will be desugared based on how they are used in the AST.
|
| 24 |
+
|
| 25 |
+
// SugaredValue is used to temporarily represent these values in a way
|
| 26 |
+
// that separates their behavior from the AST -> IR converter itself.
|
| 27 |
+
// This allows us to keep dependencies on python minimal.
|
| 28 |
+
|
| 29 |
+
struct TORCH_API SugaredValue
|
| 30 |
+
: public std::enable_shared_from_this<SugaredValue> {
|
| 31 |
+
// what is this node? for error reporting (e.g. Module, python function)
|
| 32 |
+
virtual std::string kind() const = 0;
|
| 33 |
+
|
| 34 |
+
// what can we do with this thing?
|
| 35 |
+
// use it as a value e.g. `this + 4`
|
| 36 |
+
virtual Value* asValue(const SourceRange& loc, GraphFunction& m) {
|
| 37 |
+
throw ErrorReport(loc) << kind() << " cannot be used as a value";
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
// select an attribute on it, e.g. `this.field`
|
| 41 |
+
virtual std::shared_ptr<SugaredValue> attr(
|
| 42 |
+
const SourceRange& loc,
|
| 43 |
+
GraphFunction& m,
|
| 44 |
+
const std::string& field) {
|
| 45 |
+
throw ErrorReport(loc) << "attribute lookup is not defined on " << kind();
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
virtual bool hasAttr(
|
| 49 |
+
const SourceRange& loc,
|
| 50 |
+
GraphFunction& m,
|
| 51 |
+
const std::string& field) {
|
| 52 |
+
throw ErrorReport(loc) << "attribute lookup is not defined on " << kind();
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
// assign an attribute on it, e.g. `this.field = newValue`
|
| 56 |
+
virtual void setAttr(
|
| 57 |
+
const SourceRange& loc,
|
| 58 |
+
GraphFunction& m,
|
| 59 |
+
const std::string& field,
|
| 60 |
+
Value* newValue) {
|
| 61 |
+
throw ErrorReport(loc) << "attribute assignment is not defined on "
|
| 62 |
+
<< kind();
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
// use it as a vector of values, e.g. a tuple of values as return value from
|
| 66 |
+
// a method invocation
|
| 67 |
+
virtual std::vector<std::shared_ptr<SugaredValue>> asTuple(
|
| 68 |
+
const SourceRange& loc,
|
| 69 |
+
GraphFunction& m,
|
| 70 |
+
const c10::optional<size_t>& size_hint = {}) {
|
| 71 |
+
throw ErrorReport(loc) << kind() << " cannot be used as a tuple";
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
// TODO @wconstab refactor to use ModuleValue::asTuple instead of new API
|
| 75 |
+
virtual SugaredValuePtr asTupleValue(
|
| 76 |
+
const SourceRange& loc,
|
| 77 |
+
GraphFunction& m) {
|
| 78 |
+
throw ErrorReport(loc) << kind() << " cannot be used as a tuplevalue";
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
virtual std::vector<std::shared_ptr<SugaredValue>> asType(
|
| 82 |
+
const SourceRange& loc,
|
| 83 |
+
Method& m) {
|
| 84 |
+
throw ErrorReport(loc) << kind() << " cannot be used as a type";
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
// call it like a function, e.g. `outputs = this(inputs)`
|
| 88 |
+
virtual std::shared_ptr<SugaredValue> call(
|
| 89 |
+
const SourceRange& loc,
|
| 90 |
+
GraphFunction& m,
|
| 91 |
+
// note: names for args will be 'argument 0', 'argument 1', etc..
|
| 92 |
+
at::ArrayRef<NamedValue> args,
|
| 93 |
+
at::ArrayRef<NamedValue> kwargs,
|
| 94 |
+
size_t n_binders) {
|
| 95 |
+
// n_binders is always set to the number of variables an expression is
|
| 96 |
+
// syntactically bound to:
|
| 97 |
+
// a = foo() # 1 binder (note in this case the single binder might be a
|
| 98 |
+
// tuple) a, * b = foo() # 1 binder a, b = foo() # 2 binders foo() # 0
|
| 99 |
+
// binders
|
| 100 |
+
//
|
| 101 |
+
// In subexpressions, like bar() in foo(bar()), n_binders is always set to
|
| 102 |
+
// 1. n_binders is used as a hint to subexpressions to determine how many
|
| 103 |
+
// values they should return when that number is ambiguous statically. In
|
| 104 |
+
// particular it is currently used to decide how many tensors a call to a
|
| 105 |
+
// python function will return. It is only a hint, functions do not have to
|
| 106 |
+
// check that n_binders match the number of things they are returning, the
|
| 107 |
+
// assignment logic will do that anyway.
|
| 108 |
+
|
| 109 |
+
throw ErrorReport(loc) << "cannot call a " << kind();
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
// This function is called when to convert a SugaredValue to its iterator.
|
| 113 |
+
// For example, when iterating through a Dict we iterate over its keys
|
| 114 |
+
virtual std::shared_ptr<SugaredValue> iter(
|
| 115 |
+
const SourceRange& loc,
|
| 116 |
+
GraphFunction& m) {
|
| 117 |
+
throw ErrorReport(loc) << kind() << " cannot be used as an iterable";
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
// If we are iterating over a Sugared Value and it returns a value from this
|
| 121 |
+
// function, then we emit an unrolled loop over the variable. This allows us
|
| 122 |
+
// to support containers of Heterogenous types, like Module Containers &
|
| 123 |
+
// Tuples
|
| 124 |
+
virtual c10::optional<int64_t> staticLen() {
|
| 125 |
+
return c10::nullopt;
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
// When iterating over this SugaredValue, should we emit the for loop as an
|
| 129 |
+
// unrolled loop.
|
| 130 |
+
bool shouldEmitUnrolled() {
|
| 131 |
+
return staticLen() != c10::nullopt;
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
// return length of this thing, if not then it can't be iterated.
|
| 135 |
+
// If it does not have a statically-determinable length, then it cannot
|
| 136 |
+
// be iterated over with a modulelist. If it does it must return a constant
|
| 137 |
+
// Value *
|
| 138 |
+
virtual Value* len(const SourceRange& loc, GraphFunction& m) {
|
| 139 |
+
throw ErrorReport(loc) << "'" << kind() << "'"
|
| 140 |
+
<< " object is not iterable";
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
// expression for ith elemement for iterable value
|
| 144 |
+
virtual std::shared_ptr<SugaredValue> getitem(
|
| 145 |
+
const SourceRange& loc,
|
| 146 |
+
GraphFunction& m,
|
| 147 |
+
Value* idx,
|
| 148 |
+
TypePtr type_hint = nullptr) {
|
| 149 |
+
throw ErrorReport(loc) << "'" << kind() << "'"
|
| 150 |
+
<< " object is not subscriptable";
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
virtual ~SugaredValue() = default;
|
| 154 |
+
};
|
| 155 |
+
|
| 156 |
+
// most things in the environment are just simple value types
|
| 157 |
+
// and not special python syntax sugar types
|
| 158 |
+
struct TORCH_API SimpleValue : public SugaredValue {
|
| 159 |
+
SimpleValue(Value* value) : value_(value) {}
|
| 160 |
+
std::string kind() const override {
|
| 161 |
+
std::stringstream ss;
|
| 162 |
+
// NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage)
|
| 163 |
+
ss << "value of type '" << value_->type()->annotation_str() << "'";
|
| 164 |
+
return ss.str();
|
| 165 |
+
}
|
| 166 |
+
Value* asValue(const SourceRange& range, GraphFunction& m) override {
|
| 167 |
+
return value_;
|
| 168 |
+
}
|
| 169 |
+
std::vector<std::shared_ptr<SugaredValue>> asTuple(
|
| 170 |
+
const SourceRange& loc,
|
| 171 |
+
GraphFunction& m,
|
| 172 |
+
const c10::optional<size_t>& size_hint = {}) override;
|
| 173 |
+
std::shared_ptr<SugaredValue> attr(
|
| 174 |
+
const SourceRange& loc,
|
| 175 |
+
GraphFunction& m,
|
| 176 |
+
const std::string& field) override;
|
| 177 |
+
|
| 178 |
+
bool hasAttr(
|
| 179 |
+
const SourceRange& loc,
|
| 180 |
+
GraphFunction& m,
|
| 181 |
+
const std::string& field) override;
|
| 182 |
+
|
| 183 |
+
void setAttr(
|
| 184 |
+
const SourceRange& loc,
|
| 185 |
+
GraphFunction& m,
|
| 186 |
+
const std::string& field,
|
| 187 |
+
Value* newValue) override;
|
| 188 |
+
|
| 189 |
+
std::shared_ptr<SugaredValue> call(
|
| 190 |
+
const SourceRange& loc,
|
| 191 |
+
GraphFunction& m,
|
| 192 |
+
// note: names for args will be 'argument 0', 'argument 1', etc..
|
| 193 |
+
at::ArrayRef<NamedValue> args,
|
| 194 |
+
at::ArrayRef<NamedValue> kwargs,
|
| 195 |
+
size_t n_binders) override;
|
| 196 |
+
|
| 197 |
+
std::shared_ptr<SugaredValue> iter(const SourceRange& loc, GraphFunction& m)
|
| 198 |
+
override;
|
| 199 |
+
|
| 200 |
+
Value* getValue() const {
|
| 201 |
+
return value_;
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
Value* len(const SourceRange& loc, GraphFunction& m) override;
|
| 205 |
+
SugaredValuePtr getitem(
|
| 206 |
+
const SourceRange& loc,
|
| 207 |
+
GraphFunction& m,
|
| 208 |
+
Value* idx,
|
| 209 |
+
TypePtr type_hint = nullptr) override;
|
| 210 |
+
|
| 211 |
+
private:
|
| 212 |
+
Value* value_;
|
| 213 |
+
};
|
| 214 |
+
|
| 215 |
+
struct TORCH_API BuiltinFunction : public SugaredValue {
|
| 216 |
+
BuiltinFunction(Symbol symbol, c10::optional<NamedValue> self)
|
| 217 |
+
: symbol(symbol), self(std::move(self)) {}
|
| 218 |
+
|
| 219 |
+
// The symbol of the function (e.g. `aten::relu`).
|
| 220 |
+
Symbol symbol;
|
| 221 |
+
|
| 222 |
+
// if this is method, then this is the self argument.
|
| 223 |
+
c10::optional<NamedValue> self;
|
| 224 |
+
std::string kind() const override {
|
| 225 |
+
return "builtin";
|
| 226 |
+
}
|
| 227 |
+
std::shared_ptr<SugaredValue> call(
|
| 228 |
+
const SourceRange& loc,
|
| 229 |
+
GraphFunction& m,
|
| 230 |
+
at::ArrayRef<NamedValue> args,
|
| 231 |
+
at::ArrayRef<NamedValue> kwargs,
|
| 232 |
+
size_t n_binders) override;
|
| 233 |
+
|
| 234 |
+
// try to create this builtin but if it doesn't exist or the self argument
|
| 235 |
+
// cannot possibly match, then return nullptr. Use in situations where it is
|
| 236 |
+
// not clear if it is a valid builtin
|
| 237 |
+
static std::shared_ptr<BuiltinFunction> tryCreate(
|
| 238 |
+
Symbol symbol,
|
| 239 |
+
c10::optional<NamedValue> self);
|
| 240 |
+
};
|
| 241 |
+
|
| 242 |
+
struct TORCH_API SugaredTupleValue : public SugaredValue {
|
| 243 |
+
explicit SugaredTupleValue(std::vector<std::shared_ptr<SugaredValue>> tup)
|
| 244 |
+
: tup_(std::move(tup)){};
|
| 245 |
+
|
| 246 |
+
std::vector<std::shared_ptr<SugaredValue>> asTuple(
|
| 247 |
+
const SourceRange& loc,
|
| 248 |
+
GraphFunction& m,
|
| 249 |
+
const c10::optional<size_t>& size_hint = {}) override {
|
| 250 |
+
return tup_;
|
| 251 |
+
};
|
| 252 |
+
|
| 253 |
+
Value* asValue(const SourceRange& loc, GraphFunction& m) override {
|
| 254 |
+
std::vector<Value*> vec;
|
| 255 |
+
vec.reserve(tup_.size());
|
| 256 |
+
for (const auto& sv : tup_) {
|
| 257 |
+
vec.push_back(sv->asValue(loc, m));
|
| 258 |
+
}
|
| 259 |
+
Graph& g = *m.graph();
|
| 260 |
+
return g.insertNode(g.createTuple(vec))->output();
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
std::string kind() const override {
|
| 264 |
+
return "Tuple";
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
SugaredValuePtr getitem(
|
| 268 |
+
const SourceRange& loc,
|
| 269 |
+
GraphFunction& m,
|
| 270 |
+
Value* idx,
|
| 271 |
+
TypePtr type_hint = nullptr) override {
|
| 272 |
+
if (!(idx->type()->cast<IntType>() && toIValue(idx))) {
|
| 273 |
+
throw ErrorReport(loc)
|
| 274 |
+
<< "Expected integer literal for index but got a variable or non-integer. "
|
| 275 |
+
<< "ModuleList/Sequential indexing is only supported with integer literals. "
|
| 276 |
+
<< "For example, 'i = 4; self.layers[i](x)' will fail because i is not a literal. "
|
| 277 |
+
<< "Enumeration is supported, e.g. 'for index, v in enumerate(self): out = v(inp)'";
|
| 278 |
+
}
|
| 279 |
+
auto index = toIValue(idx)->toInt();
|
| 280 |
+
int64_t adj_index =
|
| 281 |
+
(index < 0) ? index + static_cast<int64_t>(tup_.size()) : index;
|
| 282 |
+
if (!(adj_index >= 0 && adj_index < static_cast<int64_t>(tup_.size()))) {
|
| 283 |
+
throw ErrorReport(loc)
|
| 284 |
+
<< "Index " << index << " out of range of length " << tup_.size();
|
| 285 |
+
}
|
| 286 |
+
return tup_.at(adj_index);
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
// This function is called when a SugaredValue is used to convert a
|
| 290 |
+
// SugaredValue to its iterator. For example, when iterating through a Dict we
|
| 291 |
+
// iterate over its keys
|
| 292 |
+
std::shared_ptr<SugaredValue> iter(const SourceRange& loc, GraphFunction& m)
|
| 293 |
+
override {
|
| 294 |
+
return shared_from_this();
|
| 295 |
+
};
|
| 296 |
+
|
| 297 |
+
// Because this is used to contain SugaredValues of Heterogenous types,
|
| 298 |
+
// we define staticLen() so that when this is iterated over it is emitted
|
| 299 |
+
// as an unrolled loop.
|
| 300 |
+
c10::optional<int64_t> staticLen() override {
|
| 301 |
+
return static_cast<int64_t>(tup_.size());
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
std::vector<std::shared_ptr<SugaredValue>> tup_;
|
| 305 |
+
};
|
| 306 |
+
|
| 307 |
+
struct TORCH_API BuiltinModule : public SugaredValue {
|
| 308 |
+
BuiltinModule(std::string name, c10::optional<int64_t> version = at::nullopt)
|
| 309 |
+
: name(std::move(name)), version(version) {}
|
| 310 |
+
|
| 311 |
+
std::string kind() const override {
|
| 312 |
+
return "builtin module";
|
| 313 |
+
}
|
| 314 |
+
std::shared_ptr<SugaredValue> attr(
|
| 315 |
+
const SourceRange& loc,
|
| 316 |
+
GraphFunction& m,
|
| 317 |
+
const std::string& field) override {
|
| 318 |
+
if (field == "autograd") {
|
| 319 |
+
// When refering torch.autograd, it is also considered to be a
|
| 320 |
+
// BuiltinModule and we will dispatch to the aten operators for the
|
| 321 |
+
// methods under its module.
|
| 322 |
+
return std::make_shared<BuiltinModule>("aten", version);
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
auto sym = Symbol::fromQualString(name + "::" + field);
|
| 326 |
+
return std::make_shared<BuiltinFunction>(sym, c10::nullopt);
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
private:
|
| 330 |
+
std::string name;
|
| 331 |
+
// when we add operator versioning, emit this op as it exising at 'version'
|
| 332 |
+
// if not set, use the latest version
|
| 333 |
+
c10::optional<int64_t> version;
|
| 334 |
+
};
|
| 335 |
+
|
| 336 |
+
// Represents a class, analagous to `int` or `dict`. Instances of classes,
|
| 337 |
+
// like `1` or `{"foo": 5}`, are represented as SimpleValues
|
| 338 |
+
struct TORCH_API ClassValue : public SugaredValue {
|
| 339 |
+
explicit ClassValue(ClassTypePtr type) : type_(std::move(type)) {}
|
| 340 |
+
|
| 341 |
+
// Call the type's constructor, as in:
|
| 342 |
+
// n = Foo(constructor_arg)
|
| 343 |
+
std::shared_ptr<SugaredValue> call(
|
| 344 |
+
const SourceRange& loc,
|
| 345 |
+
GraphFunction& m,
|
| 346 |
+
at::ArrayRef<NamedValue> args,
|
| 347 |
+
at::ArrayRef<NamedValue> kwargs,
|
| 348 |
+
size_t n_binders) override;
|
| 349 |
+
|
| 350 |
+
std::shared_ptr<SugaredValue> attr(
|
| 351 |
+
const SourceRange& loc,
|
| 352 |
+
GraphFunction& m,
|
| 353 |
+
const std::string& field) override;
|
| 354 |
+
|
| 355 |
+
std::string kind() const override {
|
| 356 |
+
return type_->str();
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
ClassTypePtr type_;
|
| 360 |
+
};
|
| 361 |
+
|
| 362 |
+
struct TORCH_API NamedTupleConstructor : public SugaredValue {
|
| 363 |
+
explicit NamedTupleConstructor(TupleTypePtr type) : type_(std::move(type)) {}
|
| 364 |
+
|
| 365 |
+
std::shared_ptr<SugaredValue> call(
|
| 366 |
+
const SourceRange& loc,
|
| 367 |
+
GraphFunction& m,
|
| 368 |
+
at::ArrayRef<NamedValue> args,
|
| 369 |
+
at::ArrayRef<NamedValue> kwargs,
|
| 370 |
+
size_t n_binders) override;
|
| 371 |
+
|
| 372 |
+
std::string kind() const override {
|
| 373 |
+
return type_->str();
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
TupleTypePtr type_;
|
| 377 |
+
};
|
| 378 |
+
|
| 379 |
+
struct FunctionValue : public SugaredValue {
|
| 380 |
+
FunctionValue(Function* callee) : callees_({callee}) {}
|
| 381 |
+
FunctionValue(const StrongFunctionPtr& p)
|
| 382 |
+
: callees_({p.function_}), cu_(p.cu_) {}
|
| 383 |
+
FunctionValue(const std::vector<StrongFunctionPtr>& callees) {
|
| 384 |
+
for (const StrongFunctionPtr& callee : callees) {
|
| 385 |
+
cu_ = cu_ ? cu_ : callee.cu_;
|
| 386 |
+
TORCH_INTERNAL_ASSERT(callee.cu_ == cu_);
|
| 387 |
+
callees_.push_back(callee.function_);
|
| 388 |
+
}
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
std::string kind() const override {
|
| 392 |
+
return "function";
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
std::shared_ptr<SugaredValue> call(
|
| 396 |
+
const SourceRange& loc,
|
| 397 |
+
GraphFunction& f,
|
| 398 |
+
at::ArrayRef<NamedValue> args,
|
| 399 |
+
at::ArrayRef<NamedValue> kwargs,
|
| 400 |
+
size_t n_binders) override {
|
| 401 |
+
std::vector<const FunctionSchema*> schemas;
|
| 402 |
+
for (Function* callee : callees_) {
|
| 403 |
+
try {
|
| 404 |
+
callee->ensure_defined();
|
| 405 |
+
} catch (const RecursiveMethodCallError&) {
|
| 406 |
+
throw ErrorReport(loc)
|
| 407 |
+
<< " function '" << callee->name() << "' is called recursively. "
|
| 408 |
+
<< "Recursive calls are not supported";
|
| 409 |
+
}
|
| 410 |
+
schemas.push_back(&callee->getSchema());
|
| 411 |
+
}
|
| 412 |
+
auto match = matchSchemas(schemas, loc, *f.graph(), args, kwargs);
|
| 413 |
+
Value* output =
|
| 414 |
+
f.graph()->insertFunctionCall(callees_[match.first], match.second);
|
| 415 |
+
output->node()->setSourceRange(loc);
|
| 416 |
+
return std::make_shared<SimpleValue>(output);
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
const std::vector<Function*>& callees() {
|
| 420 |
+
return callees_;
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
private:
|
| 424 |
+
std::vector<Function*> callees_;
|
| 425 |
+
// TODO holding this thing is creepy
|
| 426 |
+
std::shared_ptr<CompilationUnit> cu_;
|
| 427 |
+
};
|
| 428 |
+
|
| 429 |
+
struct TORCH_API ClosureValue : public SugaredValue {
|
| 430 |
+
ClosureValue(Value* value) : value_(value) {
|
| 431 |
+
TORCH_INTERNAL_ASSERT(value_->node()->kind() == prim::Closure);
|
| 432 |
+
}
|
| 433 |
+
std::string kind() const override {
|
| 434 |
+
return "closure";
|
| 435 |
+
}
|
| 436 |
+
Value* asValue(const SourceRange& range, GraphFunction& m) override {
|
| 437 |
+
return value_;
|
| 438 |
+
}
|
| 439 |
+
Value* value_;
|
| 440 |
+
};
|
| 441 |
+
|
| 442 |
+
// defines how a method obtained from a module/class/interface behaves in script
|
| 443 |
+
struct MethodValue : public SugaredValue {
|
| 444 |
+
MethodValue(Value* self, std::vector<std::string> method_names)
|
| 445 |
+
: self_(self), method_names_(std::move(method_names)) {}
|
| 446 |
+
MethodValue(Value* self, std::string method_name)
|
| 447 |
+
: MethodValue(self, std::vector<std::string>({std::move(method_name)})) {}
|
| 448 |
+
|
| 449 |
+
std::string kind() const override {
|
| 450 |
+
return "method";
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
std::shared_ptr<SugaredValue> call(
|
| 454 |
+
const SourceRange& loc,
|
| 455 |
+
GraphFunction& f,
|
| 456 |
+
at::ArrayRef<NamedValue> args,
|
| 457 |
+
at::ArrayRef<NamedValue> kwargs,
|
| 458 |
+
size_t n_binders) override {
|
| 459 |
+
std::vector<NamedValue> argsWithSelf = {self_};
|
| 460 |
+
argsWithSelf.insert(argsWithSelf.end(), args.begin(), args.end());
|
| 461 |
+
std::vector<const FunctionSchema*> schemas;
|
| 462 |
+
for (const std::string& method_name : method_names_) {
|
| 463 |
+
if (auto class_type = self_->type()->cast<ClassType>()) {
|
| 464 |
+
Function& method = class_type->getMethod(method_name);
|
| 465 |
+
try {
|
| 466 |
+
method.ensure_defined();
|
| 467 |
+
} catch (const RecursiveMethodCallError&) {
|
| 468 |
+
throw ErrorReport(loc)
|
| 469 |
+
<< " method '" << method.name() << "' is called recursively. "
|
| 470 |
+
<< "Recursive calls are not supported";
|
| 471 |
+
}
|
| 472 |
+
schemas.push_back(&method.getSchema());
|
| 473 |
+
} else if (auto interface_type = self_->type()->cast<InterfaceType>()) {
|
| 474 |
+
schemas.push_back(interface_type->getMethod(method_name));
|
| 475 |
+
} else {
|
| 476 |
+
TORCH_INTERNAL_ASSERT(
|
| 477 |
+
false, "method constructed that is not a class or interface");
|
| 478 |
+
}
|
| 479 |
+
}
|
| 480 |
+
auto match = matchSchemas(schemas, loc, *f.graph(), argsWithSelf, kwargs);
|
| 481 |
+
Value* output =
|
| 482 |
+
f.graph()->insertMethodCall(method_names_[match.first], match.second);
|
| 483 |
+
output->node()->setSourceRange(loc);
|
| 484 |
+
return std::make_shared<SimpleValue>(output);
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
private:
|
| 488 |
+
Value* self_;
|
| 489 |
+
std::vector<std::string> method_names_;
|
| 490 |
+
};
|
| 491 |
+
|
| 492 |
+
struct TORCH_API PrintValue : public SugaredValue {
|
| 493 |
+
std::string kind() const override {
|
| 494 |
+
return "print";
|
| 495 |
+
}
|
| 496 |
+
std::shared_ptr<SugaredValue> call(
|
| 497 |
+
const SourceRange& loc,
|
| 498 |
+
GraphFunction& m,
|
| 499 |
+
at::ArrayRef<NamedValue> args,
|
| 500 |
+
at::ArrayRef<NamedValue> kwargs,
|
| 501 |
+
size_t n_binders) override;
|
| 502 |
+
};
|
| 503 |
+
|
| 504 |
+
// expressions like int(x)
|
| 505 |
+
// these are the same as call prim::Int or equivalent except it
|
| 506 |
+
// is a noop when the input is a subtype of 'type'
|
| 507 |
+
struct TORCH_API CastValue : public BuiltinFunction {
|
| 508 |
+
CastValue(TypePtr type, c10::Symbol method)
|
| 509 |
+
: BuiltinFunction(method, c10::nullopt), type_(std::move(type)) {}
|
| 510 |
+
std::shared_ptr<SugaredValue> call(
|
| 511 |
+
const SourceRange& loc,
|
| 512 |
+
GraphFunction& m,
|
| 513 |
+
at::ArrayRef<NamedValue> args,
|
| 514 |
+
at::ArrayRef<NamedValue> kwargs,
|
| 515 |
+
size_t n_binders) override {
|
| 516 |
+
if (args.size() == 1 && kwargs.empty()) {
|
| 517 |
+
auto len_op = std::make_shared<BuiltinFunction>(aten::len, at::nullopt);
|
| 518 |
+
auto gt_op = std::make_shared<BuiltinFunction>(aten::gt, at::nullopt);
|
| 519 |
+
auto zero = m.graph()->insertConstant(0);
|
| 520 |
+
|
| 521 |
+
auto v = args[0].value(*m.graph());
|
| 522 |
+
if (v->type()->isSubtypeOf(*type_)) {
|
| 523 |
+
return std::make_shared<SimpleValue>(v);
|
| 524 |
+
} else if (
|
| 525 |
+
*type_ == *BoolType::get() &&
|
| 526 |
+
(v->type()->isSubtypeOf(*AnyListType::get()) ||
|
| 527 |
+
v->type()->isSubtypeOf(*StringType::get()) ||
|
| 528 |
+
v->type()->cast<DictType>())) {
|
| 529 |
+
auto len = len_op->call(loc, m, {v}, {}, 1);
|
| 530 |
+
return gt_op->call(loc, m, {len->asValue(loc, m), zero}, {}, 1);
|
| 531 |
+
}
|
| 532 |
+
}
|
| 533 |
+
return BuiltinFunction::call(loc, m, args, kwargs, n_binders);
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
private:
|
| 537 |
+
TypePtr type_;
|
| 538 |
+
};
|
| 539 |
+
|
| 540 |
+
struct TORCH_API TensorCastValue : public SugaredValue {
|
| 541 |
+
TensorCastValue(at::ScalarType type, NamedValue self)
|
| 542 |
+
: dtype_(type), self_(std::move(self)) {}
|
| 543 |
+
|
| 544 |
+
std::string kind() const override {
|
| 545 |
+
return "Cast";
|
| 546 |
+
}
|
| 547 |
+
|
| 548 |
+
std::shared_ptr<SugaredValue> call(
|
| 549 |
+
const SourceRange& loc,
|
| 550 |
+
GraphFunction& m,
|
| 551 |
+
at::ArrayRef<NamedValue> args,
|
| 552 |
+
at::ArrayRef<NamedValue> kwargs,
|
| 553 |
+
size_t n_binders) override {
|
| 554 |
+
TORCH_INTERNAL_ASSERT(args.empty() && kwargs.empty());
|
| 555 |
+
Value* dtype_const = m.graph()->insertConstant(dtype_, loc);
|
| 556 |
+
std::vector<NamedValue> kwargs_{
|
| 557 |
+
self_, NamedValue(loc, "dtype", dtype_const)};
|
| 558 |
+
Value* casted_val = m.graph()->insert(
|
| 559 |
+
/*opname=*/Symbol::fromQualString("aten::to"),
|
| 560 |
+
/*args=*/args,
|
| 561 |
+
/*kwargs=*/kwargs_,
|
| 562 |
+
/*range=*/loc);
|
| 563 |
+
return std::make_shared<SimpleValue>(casted_val);
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
at::ScalarType dtype_;
|
| 567 |
+
NamedValue self_;
|
| 568 |
+
};
|
| 569 |
+
|
| 570 |
+
// builtins operators and functions that call a method if it exists
|
| 571 |
+
// on a class type, like 'len(x)' and 'x + y'
|
| 572 |
+
struct TORCH_API MagicMethod : public SugaredValue {
|
| 573 |
+
MagicMethod(std::string desugared_name, SugaredValuePtr base)
|
| 574 |
+
: base_value_(std::move(base)),
|
| 575 |
+
desugared_name_(std::move(desugared_name)) {}
|
| 576 |
+
|
| 577 |
+
std::string kind() const override {
|
| 578 |
+
return desugared_name_;
|
| 579 |
+
}
|
| 580 |
+
|
| 581 |
+
std::shared_ptr<SugaredValue> call(
|
| 582 |
+
const SourceRange& loc,
|
| 583 |
+
GraphFunction& m,
|
| 584 |
+
at::ArrayRef<NamedValue> args,
|
| 585 |
+
at::ArrayRef<NamedValue> kwargs,
|
| 586 |
+
size_t n_binders) override;
|
| 587 |
+
|
| 588 |
+
private:
|
| 589 |
+
SugaredValuePtr base_value_;
|
| 590 |
+
std::string desugared_name_;
|
| 591 |
+
};
|
| 592 |
+
|
| 593 |
+
// things that look like function applications, but
|
| 594 |
+
// perform non-standard evaluation are represented
|
| 595 |
+
// with SpecialFormValues, e.g.
|
| 596 |
+
// isinstance(x, int)
|
| 597 |
+
// fork(fn)
|
| 598 |
+
// annotate(int, 3)
|
| 599 |
+
// The implementation of each value is handled by a case inside emitApplyExpr
|
| 600 |
+
struct TORCH_API SpecialFormValue : public SugaredValue {
|
| 601 |
+
SpecialFormValue(Symbol form) : form_(form) {}
|
| 602 |
+
std::string kind() const override {
|
| 603 |
+
return form_.toUnqualString();
|
| 604 |
+
}
|
| 605 |
+
Symbol form() const {
|
| 606 |
+
return form_;
|
| 607 |
+
}
|
| 608 |
+
static std::shared_ptr<SpecialFormValue> create(Symbol form) {
|
| 609 |
+
return std::make_shared<SpecialFormValue>(form);
|
| 610 |
+
}
|
| 611 |
+
|
| 612 |
+
private:
|
| 613 |
+
Symbol form_;
|
| 614 |
+
};
|
| 615 |
+
|
| 616 |
+
struct TORCH_API LegacyTensorConstructor : public SpecialFormValue {
|
| 617 |
+
LegacyTensorConstructor(Symbol form, at::ScalarType dtype, at::Device device)
|
| 618 |
+
: SpecialFormValue(form), device_(device), dtype_(dtype) {}
|
| 619 |
+
|
| 620 |
+
static std::shared_ptr<LegacyTensorConstructor> create(
|
| 621 |
+
Symbol form,
|
| 622 |
+
at::ScalarType dtype,
|
| 623 |
+
at::Device device) {
|
| 624 |
+
return std::make_shared<LegacyTensorConstructor>(form, dtype, device);
|
| 625 |
+
}
|
| 626 |
+
at::ScalarType dtype() const {
|
| 627 |
+
return dtype_;
|
| 628 |
+
}
|
| 629 |
+
|
| 630 |
+
private:
|
| 631 |
+
at::Device device_;
|
| 632 |
+
at::ScalarType dtype_;
|
| 633 |
+
};
|
| 634 |
+
|
| 635 |
+
// matched against for special handling of range expressions
|
| 636 |
+
struct TORCH_API RangeValue : SugaredValue {
|
| 637 |
+
RangeValue(
|
| 638 |
+
const SourceRange& loc,
|
| 639 |
+
GraphFunction& m,
|
| 640 |
+
std::vector<Value*> input,
|
| 641 |
+
c10::optional<int64_t> static_len = c10::nullopt);
|
| 642 |
+
|
| 643 |
+
std::string kind() const override {
|
| 644 |
+
return "range";
|
| 645 |
+
}
|
| 646 |
+
Value* len(const SourceRange& loc, GraphFunction& m) override;
|
| 647 |
+
SugaredValuePtr getitem(
|
| 648 |
+
const SourceRange& loc,
|
| 649 |
+
GraphFunction& m,
|
| 650 |
+
Value* idx,
|
| 651 |
+
TypePtr type_hint = nullptr) override;
|
| 652 |
+
std::shared_ptr<SugaredValue> iter(const SourceRange& loc, GraphFunction& m)
|
| 653 |
+
override;
|
| 654 |
+
|
| 655 |
+
// When Range is instantiated via enumerate(iterable_with_static_len),
|
| 656 |
+
// then it takes the static length of the iterable
|
| 657 |
+
c10::optional<int64_t> staticLen() override {
|
| 658 |
+
return static_len_;
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
private:
|
| 662 |
+
Value* start_{};
|
| 663 |
+
Value* end_{};
|
| 664 |
+
Value* step_{};
|
| 665 |
+
// a flag to determine if it's a simple range() call with only end_ from
|
| 666 |
+
// arguments If true, we will not insert length calculation and index
|
| 667 |
+
// derivation nodes to simplify the graph and enable more possible
|
| 668 |
+
// optimizations
|
| 669 |
+
bool has_only_end_{};
|
| 670 |
+
c10::optional<int64_t> static_len_;
|
| 671 |
+
};
|
| 672 |
+
|
| 673 |
+
// Specialized Tree structure to matched against for special handling
|
| 674 |
+
// of builtin functions iterables expressions like zip(), enumerate(), etc.
|
| 675 |
+
// zip and enumerate can be modeled as a tree of SimpleValue/RangeValue:
|
| 676 |
+
// zip(x, y) -> (x, y) with tuple assignment to each loop target
|
| 677 |
+
// enumerate(x) -> (range(0, math.inf, 1), x)
|
| 678 |
+
// So a complicated expression like zip(a, enumerate(b), range(0, 100)) will be:
|
| 679 |
+
// (a, (range(0, math.inf, 1), b), range(0, 100))
|
| 680 |
+
// We use those base iterables to fill in the loop information like
|
| 681 |
+
// max_trip_count and set the value table for loop targets
|
| 682 |
+
// Iterables can contain lists of SugaredValues like ModuleLists. If it
|
| 683 |
+
// does, then we emit it unrolled and require that all values it contains
|
| 684 |
+
// have a statically-determinable length.
|
| 685 |
+
struct TORCH_API IterableTree : SugaredValue {
|
| 686 |
+
IterableTree() = default;
|
| 687 |
+
IterableTree(
|
| 688 |
+
const SourceRange& range,
|
| 689 |
+
GraphFunction& m,
|
| 690 |
+
at::ArrayRef<SugaredValuePtr> children) {
|
| 691 |
+
for (const auto& child : children) {
|
| 692 |
+
addChild(range, m, child);
|
| 693 |
+
}
|
| 694 |
+
}
|
| 695 |
+
std::string kind() const override {
|
| 696 |
+
return "iterabletree";
|
| 697 |
+
}
|
| 698 |
+
|
| 699 |
+
std::shared_ptr<SugaredValue> iter(const SourceRange& loc, GraphFunction& m)
|
| 700 |
+
override {
|
| 701 |
+
return shared_from_this();
|
| 702 |
+
}
|
| 703 |
+
|
| 704 |
+
void addChild(
|
| 705 |
+
const SourceRange& range,
|
| 706 |
+
GraphFunction& m,
|
| 707 |
+
const SugaredValuePtr& iter_value);
|
| 708 |
+
|
| 709 |
+
std::vector<SugaredValuePtr> get_children() {
|
| 710 |
+
return children_;
|
| 711 |
+
}
|
| 712 |
+
|
| 713 |
+
// If this iterable contains a ModuleList or Tuple, then it will have a
|
| 714 |
+
// static length, and we will emit it as an unrolled for loop.
|
| 715 |
+
c10::optional<int64_t> staticLen() override {
|
| 716 |
+
return unroll_length_;
|
| 717 |
+
}
|
| 718 |
+
|
| 719 |
+
// given a IterableTree node, get all the base iterables/leaves under the
|
| 720 |
+
// IterableTree node. This enables
|
| 721 |
+
// us to get all the basic SugaredValues that contains valid loop information
|
| 722 |
+
// with len() and getitem()
|
| 723 |
+
std::vector<SugaredValuePtr> get_base_iterables();
|
| 724 |
+
|
| 725 |
+
Value* len(const SourceRange& loc, GraphFunction& m) override;
|
| 726 |
+
SugaredValuePtr getitem(
|
| 727 |
+
const SourceRange& loc,
|
| 728 |
+
GraphFunction& m,
|
| 729 |
+
Value* idx,
|
| 730 |
+
TypePtr type_hint = nullptr) override;
|
| 731 |
+
|
| 732 |
+
private:
|
| 733 |
+
c10::optional<int64_t> unroll_length_ = c10::nullopt;
|
| 734 |
+
std::vector<SugaredValuePtr> children_;
|
| 735 |
+
};
|
| 736 |
+
|
| 737 |
+
static inline std::vector<Value*> toValues(
|
| 738 |
+
Graph& g,
|
| 739 |
+
at::ArrayRef<NamedValue> nvs) {
|
| 740 |
+
return fmap(nvs, [&](const NamedValue& v) { return v.value(g); });
|
| 741 |
+
}
|
| 742 |
+
|
| 743 |
+
struct SimpleSelf : public Self {
|
| 744 |
+
explicit SimpleSelf(ClassTypePtr classType)
|
| 745 |
+
: Self(), classType_(std::move(classType)) {}
|
| 746 |
+
std::shared_ptr<SugaredValue> makeSugared(Value* v) const override {
|
| 747 |
+
v->setType(classType_);
|
| 748 |
+
return std::make_shared<SimpleValue>(v);
|
| 749 |
+
}
|
| 750 |
+
ClassTypePtr getClassType() const override {
|
| 751 |
+
return classType_;
|
| 752 |
+
}
|
| 753 |
+
|
| 754 |
+
private:
|
| 755 |
+
ClassTypePtr classType_;
|
| 756 |
+
};
|
| 757 |
+
|
| 758 |
+
// This is not a SimpleValue so it can not pass through the code paths that
|
| 759 |
+
// expect a SimpleValue as a sugared value.
|
| 760 |
+
struct TORCH_API ExceptionMessageValue : public SugaredValue {
|
| 761 |
+
explicit ExceptionMessageValue(
|
| 762 |
+
Value* value,
|
| 763 |
+
Value* qualified_class_name = nullptr)
|
| 764 |
+
: value_(value), qualified_class_name_(qualified_class_name) {}
|
| 765 |
+
|
| 766 |
+
std::string kind() const override {
|
| 767 |
+
return "exception message";
|
| 768 |
+
}
|
| 769 |
+
|
| 770 |
+
Value* getValue() {
|
| 771 |
+
return value_;
|
| 772 |
+
}
|
| 773 |
+
|
| 774 |
+
// qualified python class name
|
| 775 |
+
Value* getQualifiedClassName() {
|
| 776 |
+
return qualified_class_name_;
|
| 777 |
+
}
|
| 778 |
+
|
| 779 |
+
private:
|
| 780 |
+
Value* value_;
|
| 781 |
+
Value* qualified_class_name_;
|
| 782 |
+
};
|
| 783 |
+
|
| 784 |
+
struct TORCH_API ExceptionValue : public SugaredValue {
|
| 785 |
+
explicit ExceptionValue(std::string message) : message_(std::move(message)) {}
|
| 786 |
+
|
| 787 |
+
std::string kind() const override {
|
| 788 |
+
return "exception";
|
| 789 |
+
}
|
| 790 |
+
|
| 791 |
+
std::shared_ptr<SugaredValue> call(
|
| 792 |
+
const SourceRange& loc,
|
| 793 |
+
GraphFunction& m,
|
| 794 |
+
at::ArrayRef<NamedValue> args,
|
| 795 |
+
at::ArrayRef<NamedValue> /*attributes*/,
|
| 796 |
+
size_t /*n_binders*/) override {
|
| 797 |
+
auto exception_message = insertConstant(*m.graph(), message_ + ": ", loc);
|
| 798 |
+
for (auto& input : args) {
|
| 799 |
+
auto input_str = input.value(*m.graph());
|
| 800 |
+
if (!input_str->type()->isSubtypeOf(*StringType::get())) {
|
| 801 |
+
input_str =
|
| 802 |
+
emitBuiltinCall(loc, *m.graph(), aten::str, {input_str}, {});
|
| 803 |
+
}
|
| 804 |
+
exception_message = emitBuiltinCall(
|
| 805 |
+
loc, *m.graph(), aten::add, {exception_message, input_str}, {});
|
| 806 |
+
}
|
| 807 |
+
return std::make_shared<ExceptionMessageValue>(exception_message);
|
| 808 |
+
}
|
| 809 |
+
|
| 810 |
+
std::string message_;
|
| 811 |
+
};
|
| 812 |
+
|
| 813 |
+
struct TORCH_API SugaredEnumClass : public SugaredValue {
|
| 814 |
+
explicit SugaredEnumClass(EnumTypePtr enum_type)
|
| 815 |
+
: enum_type_(std::move(enum_type)) {}
|
| 816 |
+
|
| 817 |
+
std::string kind() const override {
|
| 818 |
+
return "EnumClass";
|
| 819 |
+
}
|
| 820 |
+
|
| 821 |
+
SugaredValuePtr attr(
|
| 822 |
+
const SourceRange& loc,
|
| 823 |
+
GraphFunction& m,
|
| 824 |
+
const std::string& field) override;
|
| 825 |
+
|
| 826 |
+
SugaredValuePtr iter(const SourceRange& loc, GraphFunction& m) override;
|
| 827 |
+
|
| 828 |
+
private:
|
| 829 |
+
EnumTypePtr enum_type_;
|
| 830 |
+
};
|
| 831 |
+
|
| 832 |
+
struct TORCH_API SliceValue : public SugaredValue {
|
| 833 |
+
explicit SliceValue(Value* start, Value* stop, Value* step)
|
| 834 |
+
: start_(start), stop_(stop), step_(step) {}
|
| 835 |
+
|
| 836 |
+
std::string kind() const override {
|
| 837 |
+
return "Python slice value";
|
| 838 |
+
}
|
| 839 |
+
|
| 840 |
+
Value* start() {
|
| 841 |
+
return start_;
|
| 842 |
+
};
|
| 843 |
+
Value* stop() {
|
| 844 |
+
return stop_;
|
| 845 |
+
};
|
| 846 |
+
Value* step() {
|
| 847 |
+
return step_;
|
| 848 |
+
};
|
| 849 |
+
|
| 850 |
+
private:
|
| 851 |
+
Value* start_;
|
| 852 |
+
Value* stop_;
|
| 853 |
+
Value* step_;
|
| 854 |
+
};
|
| 855 |
+
|
| 856 |
+
} // namespace jit
|
| 857 |
+
} // namespace torch
|
shared/package-files/4b/4b1b478b7c4d9aa7e859160e464f841c8d64db243918547d47ac5956c81a1c0e/_unpack_dual_native.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor> _unpack_dual(const at::Tensor & dual, int64_t level);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
shared/package-files/4b/4b1dd6bfcdc0ce85d83c444411f29098ccaf86851d9e48122bf26c491c8aa0b2/native_group_norm_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 native_group_norm {
|
| 18 |
+
using schema = ::std::tuple<at::Tensor,at::Tensor,at::Tensor> (const at::Tensor &, const c10::optional<at::Tensor> &, const c10::optional<at::Tensor> &, c10::SymInt, c10::SymInt, c10::SymInt, int64_t, double);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::native_group_norm")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "native_group_norm(Tensor input, Tensor? weight, Tensor? bias, SymInt N, SymInt C, SymInt HxW, int group, float eps) -> (Tensor, Tensor, Tensor)")
|
| 24 |
+
static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> call(const at::Tensor & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, c10::SymInt N, c10::SymInt C, c10::SymInt HxW, int64_t group, double eps);
|
| 25 |
+
static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, c10::SymInt N, c10::SymInt C, c10::SymInt HxW, int64_t group, double eps);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API native_group_norm_out {
|
| 29 |
+
using schema = ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> (const at::Tensor &, const c10::optional<at::Tensor> &, const c10::optional<at::Tensor> &, c10::SymInt, c10::SymInt, c10::SymInt, int64_t, double, 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::native_group_norm")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "native_group_norm.out(Tensor input, Tensor? weight, Tensor? bias, SymInt N, SymInt C, SymInt HxW, int group, float eps, *, 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 & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, c10::SymInt N, c10::SymInt C, c10::SymInt HxW, int64_t group, double eps, 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 & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, c10::SymInt N, c10::SymInt C, c10::SymInt HxW, int64_t group, double eps, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
}} // namespace at::_ops
|
shared/package-files/4b/4b24155cadc107580466570ad6ae4bb9e5afa72a3e53ad34b5d9e957ff3b41b1/nonhomogeneous.py
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
This File contains helper functions for nth_linear_constant_coeff_undetermined_coefficients,
|
| 3 |
+
nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients,
|
| 4 |
+
nth_linear_constant_coeff_variation_of_parameters,
|
| 5 |
+
and nth_linear_euler_eq_nonhomogeneous_variation_of_parameters.
|
| 6 |
+
|
| 7 |
+
All the functions in this file are used by more than one solvers so, instead of creating
|
| 8 |
+
instances in other classes for using them it is better to keep it here as separate helpers.
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
from collections import defaultdict
|
| 12 |
+
from sympy.core import Add, S
|
| 13 |
+
from sympy.core.function import diff, expand, _mexpand, expand_mul
|
| 14 |
+
from sympy.core.relational import Eq
|
| 15 |
+
from sympy.core.sorting import default_sort_key
|
| 16 |
+
from sympy.core.symbol import Dummy, Wild
|
| 17 |
+
from sympy.functions import exp, cos, cosh, im, log, re, sin, sinh, \
|
| 18 |
+
atan2, conjugate
|
| 19 |
+
from sympy.integrals import Integral
|
| 20 |
+
from sympy.polys import (Poly, RootOf, rootof, roots)
|
| 21 |
+
from sympy.simplify import collect, simplify, separatevars, powsimp, trigsimp # type: ignore
|
| 22 |
+
from sympy.utilities import numbered_symbols
|
| 23 |
+
from sympy.solvers.solvers import solve
|
| 24 |
+
from sympy.matrices import wronskian
|
| 25 |
+
from .subscheck import sub_func_doit
|
| 26 |
+
from sympy.solvers.ode.ode import get_numbered_constants
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _test_term(coeff, func, order):
|
| 30 |
+
r"""
|
| 31 |
+
Linear Euler ODEs have the form K*x**order*diff(y(x), x, order) = F(x),
|
| 32 |
+
where K is independent of x and y(x), order>= 0.
|
| 33 |
+
So we need to check that for each term, coeff == K*x**order from
|
| 34 |
+
some K. We have a few cases, since coeff may have several
|
| 35 |
+
different types.
|
| 36 |
+
"""
|
| 37 |
+
x = func.args[0]
|
| 38 |
+
f = func.func
|
| 39 |
+
if order < 0:
|
| 40 |
+
raise ValueError("order should be greater than 0")
|
| 41 |
+
if coeff == 0:
|
| 42 |
+
return True
|
| 43 |
+
if order == 0:
|
| 44 |
+
if x in coeff.free_symbols:
|
| 45 |
+
return False
|
| 46 |
+
return True
|
| 47 |
+
if coeff.is_Mul:
|
| 48 |
+
if coeff.has(f(x)):
|
| 49 |
+
return False
|
| 50 |
+
return x**order in coeff.args
|
| 51 |
+
elif coeff.is_Pow:
|
| 52 |
+
return coeff.as_base_exp() == (x, order)
|
| 53 |
+
elif order == 1:
|
| 54 |
+
return x == coeff
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _get_euler_characteristic_eq_sols(eq, func, match_obj):
|
| 59 |
+
r"""
|
| 60 |
+
Returns the solution of homogeneous part of the linear euler ODE and
|
| 61 |
+
the list of roots of characteristic equation.
|
| 62 |
+
|
| 63 |
+
The parameter ``match_obj`` is a dict of order:coeff terms, where order is the order
|
| 64 |
+
of the derivative on each term, and coeff is the coefficient of that derivative.
|
| 65 |
+
|
| 66 |
+
"""
|
| 67 |
+
x = func.args[0]
|
| 68 |
+
f = func.func
|
| 69 |
+
|
| 70 |
+
# First, set up characteristic equation.
|
| 71 |
+
chareq, symbol = S.Zero, Dummy('x')
|
| 72 |
+
|
| 73 |
+
for i in match_obj:
|
| 74 |
+
if i >= 0:
|
| 75 |
+
chareq += (match_obj[i]*diff(x**symbol, x, i)*x**-symbol).expand()
|
| 76 |
+
|
| 77 |
+
chareq = Poly(chareq, symbol)
|
| 78 |
+
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
|
| 79 |
+
collectterms = []
|
| 80 |
+
|
| 81 |
+
# A generator of constants
|
| 82 |
+
constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
|
| 83 |
+
constants.reverse()
|
| 84 |
+
|
| 85 |
+
# Create a dict root: multiplicity or charroots
|
| 86 |
+
charroots = defaultdict(int)
|
| 87 |
+
for root in chareqroots:
|
| 88 |
+
charroots[root] += 1
|
| 89 |
+
gsol = S.Zero
|
| 90 |
+
ln = log
|
| 91 |
+
for root, multiplicity in charroots.items():
|
| 92 |
+
for i in range(multiplicity):
|
| 93 |
+
if isinstance(root, RootOf):
|
| 94 |
+
gsol += (x**root) * constants.pop()
|
| 95 |
+
if multiplicity != 1:
|
| 96 |
+
raise ValueError("Value should be 1")
|
| 97 |
+
collectterms = [(0, root, 0)] + collectterms
|
| 98 |
+
elif root.is_real:
|
| 99 |
+
gsol += ln(x)**i*(x**root) * constants.pop()
|
| 100 |
+
collectterms = [(i, root, 0)] + collectterms
|
| 101 |
+
else:
|
| 102 |
+
reroot = re(root)
|
| 103 |
+
imroot = im(root)
|
| 104 |
+
gsol += ln(x)**i * (x**reroot) * (
|
| 105 |
+
constants.pop() * sin(abs(imroot)*ln(x))
|
| 106 |
+
+ constants.pop() * cos(imroot*ln(x)))
|
| 107 |
+
collectterms = [(i, reroot, imroot)] + collectterms
|
| 108 |
+
|
| 109 |
+
gsol = Eq(f(x), gsol)
|
| 110 |
+
|
| 111 |
+
gensols = []
|
| 112 |
+
# Keep track of when to use sin or cos for nonzero imroot
|
| 113 |
+
for i, reroot, imroot in collectterms:
|
| 114 |
+
if imroot == 0:
|
| 115 |
+
gensols.append(ln(x)**i*x**reroot)
|
| 116 |
+
else:
|
| 117 |
+
sin_form = ln(x)**i*x**reroot*sin(abs(imroot)*ln(x))
|
| 118 |
+
if sin_form in gensols:
|
| 119 |
+
cos_form = ln(x)**i*x**reroot*cos(imroot*ln(x))
|
| 120 |
+
gensols.append(cos_form)
|
| 121 |
+
else:
|
| 122 |
+
gensols.append(sin_form)
|
| 123 |
+
return gsol, gensols
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _solve_variation_of_parameters(eq, func, roots, homogen_sol, order, match_obj, simplify_flag=True):
|
| 127 |
+
r"""
|
| 128 |
+
Helper function for the method of variation of parameters and nonhomogeneous euler eq.
|
| 129 |
+
|
| 130 |
+
See the
|
| 131 |
+
:py:meth:`~sympy.solvers.ode.single.NthLinearConstantCoeffVariationOfParameters`
|
| 132 |
+
docstring for more information on this method.
|
| 133 |
+
|
| 134 |
+
The parameter are ``match_obj`` should be a dictionary that has the following
|
| 135 |
+
keys:
|
| 136 |
+
|
| 137 |
+
``list``
|
| 138 |
+
A list of solutions to the homogeneous equation.
|
| 139 |
+
|
| 140 |
+
``sol``
|
| 141 |
+
The general solution.
|
| 142 |
+
|
| 143 |
+
"""
|
| 144 |
+
f = func.func
|
| 145 |
+
x = func.args[0]
|
| 146 |
+
r = match_obj
|
| 147 |
+
psol = 0
|
| 148 |
+
wr = wronskian(roots, x)
|
| 149 |
+
|
| 150 |
+
if simplify_flag:
|
| 151 |
+
wr = simplify(wr) # We need much better simplification for
|
| 152 |
+
# some ODEs. See issue 4662, for example.
|
| 153 |
+
# To reduce commonly occurring sin(x)**2 + cos(x)**2 to 1
|
| 154 |
+
wr = trigsimp(wr, deep=True, recursive=True)
|
| 155 |
+
if not wr:
|
| 156 |
+
# The wronskian will be 0 iff the solutions are not linearly
|
| 157 |
+
# independent.
|
| 158 |
+
raise NotImplementedError("Cannot find " + str(order) +
|
| 159 |
+
" solutions to the homogeneous equation necessary to apply " +
|
| 160 |
+
"variation of parameters to " + str(eq) + " (Wronskian == 0)")
|
| 161 |
+
if len(roots) != order:
|
| 162 |
+
raise NotImplementedError("Cannot find " + str(order) +
|
| 163 |
+
" solutions to the homogeneous equation necessary to apply " +
|
| 164 |
+
"variation of parameters to " +
|
| 165 |
+
str(eq) + " (number of terms != order)")
|
| 166 |
+
negoneterm = S.NegativeOne**(order)
|
| 167 |
+
for i in roots:
|
| 168 |
+
psol += negoneterm*Integral(wronskian([sol for sol in roots if sol != i], x)*r[-1]/wr, x)*i/r[order]
|
| 169 |
+
negoneterm *= -1
|
| 170 |
+
|
| 171 |
+
if simplify_flag:
|
| 172 |
+
psol = simplify(psol)
|
| 173 |
+
psol = trigsimp(psol, deep=True)
|
| 174 |
+
return Eq(f(x), homogen_sol.rhs + psol)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _get_const_characteristic_eq_sols(r, func, order):
|
| 178 |
+
r"""
|
| 179 |
+
Returns the roots of characteristic equation of constant coefficient
|
| 180 |
+
linear ODE and list of collectterms which is later on used by simplification
|
| 181 |
+
to use collect on solution.
|
| 182 |
+
|
| 183 |
+
The parameter `r` is a dict of order:coeff terms, where order is the order of the
|
| 184 |
+
derivative on each term, and coeff is the coefficient of that derivative.
|
| 185 |
+
|
| 186 |
+
"""
|
| 187 |
+
x = func.args[0]
|
| 188 |
+
# First, set up characteristic equation.
|
| 189 |
+
chareq, symbol = S.Zero, Dummy('x')
|
| 190 |
+
|
| 191 |
+
for i in r.keys():
|
| 192 |
+
if isinstance(i, str) or i < 0:
|
| 193 |
+
pass
|
| 194 |
+
else:
|
| 195 |
+
chareq += r[i]*symbol**i
|
| 196 |
+
|
| 197 |
+
chareq = Poly(chareq, symbol)
|
| 198 |
+
# Can't just call roots because it doesn't return rootof for unsolveable
|
| 199 |
+
# polynomials.
|
| 200 |
+
chareqroots = roots(chareq, multiple=True)
|
| 201 |
+
if len(chareqroots) != order:
|
| 202 |
+
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
|
| 203 |
+
|
| 204 |
+
chareq_is_complex = not all(i.is_real for i in chareq.all_coeffs())
|
| 205 |
+
|
| 206 |
+
# Create a dict root: multiplicity or charroots
|
| 207 |
+
charroots = defaultdict(int)
|
| 208 |
+
for root in chareqroots:
|
| 209 |
+
charroots[root] += 1
|
| 210 |
+
# We need to keep track of terms so we can run collect() at the end.
|
| 211 |
+
# This is necessary for constantsimp to work properly.
|
| 212 |
+
collectterms = []
|
| 213 |
+
gensols = []
|
| 214 |
+
conjugate_roots = [] # used to prevent double-use of conjugate roots
|
| 215 |
+
# Loop over roots in theorder provided by roots/rootof...
|
| 216 |
+
for root in chareqroots:
|
| 217 |
+
# but don't repoeat multiple roots.
|
| 218 |
+
if root not in charroots:
|
| 219 |
+
continue
|
| 220 |
+
multiplicity = charroots.pop(root)
|
| 221 |
+
for i in range(multiplicity):
|
| 222 |
+
if chareq_is_complex:
|
| 223 |
+
gensols.append(x**i*exp(root*x))
|
| 224 |
+
collectterms = [(i, root, 0)] + collectterms
|
| 225 |
+
continue
|
| 226 |
+
reroot = re(root)
|
| 227 |
+
imroot = im(root)
|
| 228 |
+
if imroot.has(atan2) and reroot.has(atan2):
|
| 229 |
+
# Remove this condition when re and im stop returning
|
| 230 |
+
# circular atan2 usages.
|
| 231 |
+
gensols.append(x**i*exp(root*x))
|
| 232 |
+
collectterms = [(i, root, 0)] + collectterms
|
| 233 |
+
else:
|
| 234 |
+
if root in conjugate_roots:
|
| 235 |
+
collectterms = [(i, reroot, imroot)] + collectterms
|
| 236 |
+
continue
|
| 237 |
+
if imroot == 0:
|
| 238 |
+
gensols.append(x**i*exp(reroot*x))
|
| 239 |
+
collectterms = [(i, reroot, 0)] + collectterms
|
| 240 |
+
continue
|
| 241 |
+
conjugate_roots.append(conjugate(root))
|
| 242 |
+
gensols.append(x**i*exp(reroot*x) * sin(abs(imroot) * x))
|
| 243 |
+
gensols.append(x**i*exp(reroot*x) * cos( imroot * x))
|
| 244 |
+
|
| 245 |
+
# This ordering is important
|
| 246 |
+
collectterms = [(i, reroot, imroot)] + collectterms
|
| 247 |
+
return gensols, collectterms
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
# Ideally these kind of simplification functions shouldn't be part of solvers.
|
| 251 |
+
# odesimp should be improved to handle these kind of specific simplifications.
|
| 252 |
+
def _get_simplified_sol(sol, func, collectterms):
|
| 253 |
+
r"""
|
| 254 |
+
Helper function which collects the solution on
|
| 255 |
+
collectterms. Ideally this should be handled by odesimp.It is used
|
| 256 |
+
only when the simplify is set to True in dsolve.
|
| 257 |
+
|
| 258 |
+
The parameter ``collectterms`` is a list of tuple (i, reroot, imroot) where `i` is
|
| 259 |
+
the multiplicity of the root, reroot is real part and imroot being the imaginary part.
|
| 260 |
+
|
| 261 |
+
"""
|
| 262 |
+
f = func.func
|
| 263 |
+
x = func.args[0]
|
| 264 |
+
collectterms.sort(key=default_sort_key)
|
| 265 |
+
collectterms.reverse()
|
| 266 |
+
assert len(sol) == 1 and sol[0].lhs == f(x)
|
| 267 |
+
sol = sol[0].rhs
|
| 268 |
+
sol = expand_mul(sol)
|
| 269 |
+
for i, reroot, imroot in collectterms:
|
| 270 |
+
sol = collect(sol, x**i*exp(reroot*x)*sin(abs(imroot)*x))
|
| 271 |
+
sol = collect(sol, x**i*exp(reroot*x)*cos(imroot*x))
|
| 272 |
+
for i, reroot, imroot in collectterms:
|
| 273 |
+
sol = collect(sol, x**i*exp(reroot*x))
|
| 274 |
+
sol = powsimp(sol)
|
| 275 |
+
return Eq(f(x), sol)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _undetermined_coefficients_match(expr, x, func=None, eq_homogeneous=S.Zero):
|
| 279 |
+
r"""
|
| 280 |
+
Returns a trial function match if undetermined coefficients can be applied
|
| 281 |
+
to ``expr``, and ``None`` otherwise.
|
| 282 |
+
|
| 283 |
+
A trial expression can be found for an expression for use with the method
|
| 284 |
+
of undetermined coefficients if the expression is an
|
| 285 |
+
additive/multiplicative combination of constants, polynomials in `x` (the
|
| 286 |
+
independent variable of expr), `\sin(a x + b)`, `\cos(a x + b)`, and
|
| 287 |
+
`e^{a x}` terms (in other words, it has a finite number of linearly
|
| 288 |
+
independent derivatives).
|
| 289 |
+
|
| 290 |
+
Note that you may still need to multiply each term returned here by
|
| 291 |
+
sufficient `x` to make it linearly independent with the solutions to the
|
| 292 |
+
homogeneous equation.
|
| 293 |
+
|
| 294 |
+
This is intended for internal use by ``undetermined_coefficients`` hints.
|
| 295 |
+
|
| 296 |
+
SymPy currently has no way to convert `\sin^n(x) \cos^m(y)` into a sum of
|
| 297 |
+
only `\sin(a x)` and `\cos(b x)` terms, so these are not implemented. So,
|
| 298 |
+
for example, you will need to manually convert `\sin^2(x)` into `[1 +
|
| 299 |
+
\cos(2 x)]/2` to properly apply the method of undetermined coefficients on
|
| 300 |
+
it.
|
| 301 |
+
|
| 302 |
+
Examples
|
| 303 |
+
========
|
| 304 |
+
|
| 305 |
+
>>> from sympy import log, exp
|
| 306 |
+
>>> from sympy.solvers.ode.nonhomogeneous import _undetermined_coefficients_match
|
| 307 |
+
>>> from sympy.abc import x
|
| 308 |
+
>>> _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x)
|
| 309 |
+
{'test': True, 'trialset': {x*exp(x), exp(-x), exp(x)}}
|
| 310 |
+
>>> _undetermined_coefficients_match(log(x), x)
|
| 311 |
+
{'test': False}
|
| 312 |
+
|
| 313 |
+
"""
|
| 314 |
+
a = Wild('a', exclude=[x])
|
| 315 |
+
b = Wild('b', exclude=[x])
|
| 316 |
+
expr = powsimp(expr, combine='exp') # exp(x)*exp(2*x + 1) => exp(3*x + 1)
|
| 317 |
+
retdict = {}
|
| 318 |
+
|
| 319 |
+
def _test_term(expr, x):
|
| 320 |
+
r"""
|
| 321 |
+
Test if ``expr`` fits the proper form for undetermined coefficients.
|
| 322 |
+
"""
|
| 323 |
+
if not expr.has(x):
|
| 324 |
+
return True
|
| 325 |
+
elif expr.is_Add:
|
| 326 |
+
return all(_test_term(i, x) for i in expr.args)
|
| 327 |
+
elif expr.is_Mul:
|
| 328 |
+
if expr.has(sin, cos):
|
| 329 |
+
foundtrig = False
|
| 330 |
+
# Make sure that there is only one trig function in the args.
|
| 331 |
+
# See the docstring.
|
| 332 |
+
for i in expr.args:
|
| 333 |
+
if i.has(sin, cos):
|
| 334 |
+
if foundtrig:
|
| 335 |
+
return False
|
| 336 |
+
else:
|
| 337 |
+
foundtrig = True
|
| 338 |
+
return all(_test_term(i, x) for i in expr.args)
|
| 339 |
+
elif expr.is_Function:
|
| 340 |
+
if expr.func in (sin, cos, exp, sinh, cosh):
|
| 341 |
+
if expr.args[0].match(a*x + b):
|
| 342 |
+
return True
|
| 343 |
+
else:
|
| 344 |
+
return False
|
| 345 |
+
else:
|
| 346 |
+
return False
|
| 347 |
+
elif expr.is_Pow and expr.base.is_Symbol and expr.exp.is_Integer and \
|
| 348 |
+
expr.exp >= 0:
|
| 349 |
+
return True
|
| 350 |
+
elif expr.is_Pow and expr.base.is_number:
|
| 351 |
+
if expr.exp.match(a*x + b):
|
| 352 |
+
return True
|
| 353 |
+
else:
|
| 354 |
+
return False
|
| 355 |
+
elif expr.is_Symbol or expr.is_number:
|
| 356 |
+
return True
|
| 357 |
+
else:
|
| 358 |
+
return False
|
| 359 |
+
|
| 360 |
+
def _get_trial_set(expr, x, exprs=set()):
|
| 361 |
+
r"""
|
| 362 |
+
Returns a set of trial terms for undetermined coefficients.
|
| 363 |
+
|
| 364 |
+
The idea behind undetermined coefficients is that the terms expression
|
| 365 |
+
repeat themselves after a finite number of derivatives, except for the
|
| 366 |
+
coefficients (they are linearly dependent). So if we collect these,
|
| 367 |
+
we should have the terms of our trial function.
|
| 368 |
+
"""
|
| 369 |
+
def _remove_coefficient(expr, x):
|
| 370 |
+
r"""
|
| 371 |
+
Returns the expression without a coefficient.
|
| 372 |
+
|
| 373 |
+
Similar to expr.as_independent(x)[1], except it only works
|
| 374 |
+
multiplicatively.
|
| 375 |
+
"""
|
| 376 |
+
term = S.One
|
| 377 |
+
if expr.is_Mul:
|
| 378 |
+
for i in expr.args:
|
| 379 |
+
if i.has(x):
|
| 380 |
+
term *= i
|
| 381 |
+
elif expr.has(x):
|
| 382 |
+
term = expr
|
| 383 |
+
return term
|
| 384 |
+
|
| 385 |
+
expr = expand_mul(expr)
|
| 386 |
+
if expr.is_Add:
|
| 387 |
+
for term in expr.args:
|
| 388 |
+
if _remove_coefficient(term, x) in exprs:
|
| 389 |
+
pass
|
| 390 |
+
else:
|
| 391 |
+
exprs.add(_remove_coefficient(term, x))
|
| 392 |
+
exprs = exprs.union(_get_trial_set(term, x, exprs))
|
| 393 |
+
else:
|
| 394 |
+
term = _remove_coefficient(expr, x)
|
| 395 |
+
tmpset = exprs.union({term})
|
| 396 |
+
oldset = set()
|
| 397 |
+
while tmpset != oldset:
|
| 398 |
+
# If you get stuck in this loop, then _test_term is probably
|
| 399 |
+
# broken
|
| 400 |
+
oldset = tmpset.copy()
|
| 401 |
+
expr = expr.diff(x)
|
| 402 |
+
term = _remove_coefficient(expr, x)
|
| 403 |
+
if term.is_Add:
|
| 404 |
+
tmpset = tmpset.union(_get_trial_set(term, x, tmpset))
|
| 405 |
+
else:
|
| 406 |
+
tmpset.add(term)
|
| 407 |
+
exprs = tmpset
|
| 408 |
+
return exprs
|
| 409 |
+
|
| 410 |
+
def is_homogeneous_solution(term):
|
| 411 |
+
r""" This function checks whether the given trialset contains any root
|
| 412 |
+
of homogeneous equation"""
|
| 413 |
+
return expand(sub_func_doit(eq_homogeneous, func, term)).is_zero
|
| 414 |
+
|
| 415 |
+
retdict['test'] = _test_term(expr, x)
|
| 416 |
+
if retdict['test']:
|
| 417 |
+
# Try to generate a list of trial solutions that will have the
|
| 418 |
+
# undetermined coefficients. Note that if any of these are not linearly
|
| 419 |
+
# independent with any of the solutions to the homogeneous equation,
|
| 420 |
+
# then they will need to be multiplied by sufficient x to make them so.
|
| 421 |
+
# This function DOES NOT do that (it doesn't even look at the
|
| 422 |
+
# homogeneous equation).
|
| 423 |
+
temp_set = set()
|
| 424 |
+
for i in Add.make_args(expr):
|
| 425 |
+
act = _get_trial_set(i, x)
|
| 426 |
+
if eq_homogeneous is not S.Zero:
|
| 427 |
+
while any(is_homogeneous_solution(ts) for ts in act):
|
| 428 |
+
act = {x*ts for ts in act}
|
| 429 |
+
temp_set = temp_set.union(act)
|
| 430 |
+
|
| 431 |
+
retdict['trialset'] = temp_set
|
| 432 |
+
return retdict
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def _solve_undetermined_coefficients(eq, func, order, match, trialset):
|
| 436 |
+
r"""
|
| 437 |
+
Helper function for the method of undetermined coefficients.
|
| 438 |
+
|
| 439 |
+
See the
|
| 440 |
+
:py:meth:`~sympy.solvers.ode.single.NthLinearConstantCoeffUndeterminedCoefficients`
|
| 441 |
+
docstring for more information on this method.
|
| 442 |
+
|
| 443 |
+
The parameter ``trialset`` is the set of trial functions as returned by
|
| 444 |
+
``_undetermined_coefficients_match()['trialset']``.
|
| 445 |
+
|
| 446 |
+
The parameter ``match`` should be a dictionary that has the following
|
| 447 |
+
keys:
|
| 448 |
+
|
| 449 |
+
``list``
|
| 450 |
+
A list of solutions to the homogeneous equation.
|
| 451 |
+
|
| 452 |
+
``sol``
|
| 453 |
+
The general solution.
|
| 454 |
+
|
| 455 |
+
"""
|
| 456 |
+
r = match
|
| 457 |
+
coeffs = numbered_symbols('a', cls=Dummy)
|
| 458 |
+
coefflist = []
|
| 459 |
+
gensols = r['list']
|
| 460 |
+
gsol = r['sol']
|
| 461 |
+
f = func.func
|
| 462 |
+
x = func.args[0]
|
| 463 |
+
|
| 464 |
+
if len(gensols) != order:
|
| 465 |
+
raise NotImplementedError("Cannot find " + str(order) +
|
| 466 |
+
" solutions to the homogeneous equation necessary to apply" +
|
| 467 |
+
" undetermined coefficients to " + str(eq) +
|
| 468 |
+
" (number of terms != order)")
|
| 469 |
+
|
| 470 |
+
trialfunc = 0
|
| 471 |
+
for i in trialset:
|
| 472 |
+
c = next(coeffs)
|
| 473 |
+
coefflist.append(c)
|
| 474 |
+
trialfunc += c*i
|
| 475 |
+
|
| 476 |
+
eqs = sub_func_doit(eq, f(x), trialfunc)
|
| 477 |
+
|
| 478 |
+
coeffsdict = dict(list(zip(trialset, [0]*(len(trialset) + 1))))
|
| 479 |
+
|
| 480 |
+
eqs = _mexpand(eqs)
|
| 481 |
+
|
| 482 |
+
for i in Add.make_args(eqs):
|
| 483 |
+
s = separatevars(i, dict=True, symbols=[x])
|
| 484 |
+
if coeffsdict.get(s[x]):
|
| 485 |
+
coeffsdict[s[x]] += s['coeff']
|
| 486 |
+
else:
|
| 487 |
+
coeffsdict[s[x]] = s['coeff']
|
| 488 |
+
|
| 489 |
+
coeffvals = solve(list(coeffsdict.values()), coefflist)
|
| 490 |
+
|
| 491 |
+
if not coeffvals:
|
| 492 |
+
raise NotImplementedError(
|
| 493 |
+
"Could not solve `%s` using the "
|
| 494 |
+
"method of undetermined coefficients "
|
| 495 |
+
"(unable to solve for coefficients)." % eq)
|
| 496 |
+
|
| 497 |
+
psol = trialfunc.subs(coeffvals)
|
| 498 |
+
|
| 499 |
+
return Eq(f(x), gsol.rhs + psol)
|
shared/package-files/4b/4b28b46981bbb78cbd2b22060e2dd018c66fcff1cee52755425ad4900a90d6c3/es_ni.msg
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# created by tools/loadICU.tcl -- do not edit
|
| 2 |
+
namespace eval ::tcl::clock {
|
| 3 |
+
::msgcat::mcset es_NI DATE_FORMAT "%m-%d-%Y"
|
| 4 |
+
::msgcat::mcset es_NI TIME_FORMAT_12 "%I:%M:%S %P"
|
| 5 |
+
::msgcat::mcset es_NI DATE_TIME_FORMAT "%m-%d-%Y %I:%M:%S %P %z"
|
| 6 |
+
}
|
shared/package-files/4b/4b2b96775cdb43b50a6795957718f0519abace8a637e7f3d0b2d453395dd57ac/pastes.csv
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"","strength","batch","cask","sample"
|
| 2 |
+
"1",62.8,"A","a","A:a"
|
| 3 |
+
"2",62.6,"A","a","A:a"
|
| 4 |
+
"3",60.1,"A","b","A:b"
|
| 5 |
+
"4",62.3,"A","b","A:b"
|
| 6 |
+
"5",62.7,"A","c","A:c"
|
| 7 |
+
"6",63.1,"A","c","A:c"
|
| 8 |
+
"7",60,"B","a","B:a"
|
| 9 |
+
"8",61.4,"B","a","B:a"
|
| 10 |
+
"9",57.5,"B","b","B:b"
|
| 11 |
+
"10",56.9,"B","b","B:b"
|
| 12 |
+
"11",61.1,"B","c","B:c"
|
| 13 |
+
"12",58.9,"B","c","B:c"
|
| 14 |
+
"13",58.7,"C","a","C:a"
|
| 15 |
+
"14",57.5,"C","a","C:a"
|
| 16 |
+
"15",63.9,"C","b","C:b"
|
| 17 |
+
"16",63.1,"C","b","C:b"
|
| 18 |
+
"17",65.4,"C","c","C:c"
|
| 19 |
+
"18",63.7,"C","c","C:c"
|
| 20 |
+
"19",57.1,"D","a","D:a"
|
| 21 |
+
"20",56.4,"D","a","D:a"
|
| 22 |
+
"21",56.9,"D","b","D:b"
|
| 23 |
+
"22",58.6,"D","b","D:b"
|
| 24 |
+
"23",64.7,"D","c","D:c"
|
| 25 |
+
"24",64.5,"D","c","D:c"
|
| 26 |
+
"25",55.1,"E","a","E:a"
|
| 27 |
+
"26",55.1,"E","a","E:a"
|
| 28 |
+
"27",54.7,"E","b","E:b"
|
| 29 |
+
"28",54.2,"E","b","E:b"
|
| 30 |
+
"29",58.8,"E","c","E:c"
|
| 31 |
+
"30",57.5,"E","c","E:c"
|
| 32 |
+
"31",63.4,"F","a","F:a"
|
| 33 |
+
"32",64.9,"F","a","F:a"
|
| 34 |
+
"33",59.3,"F","b","F:b"
|
| 35 |
+
"34",58.1,"F","b","F:b"
|
| 36 |
+
"35",60.5,"F","c","F:c"
|
| 37 |
+
"36",60,"F","c","F:c"
|
| 38 |
+
"37",62.5,"G","a","G:a"
|
| 39 |
+
"38",62.6,"G","a","G:a"
|
| 40 |
+
"39",61,"G","b","G:b"
|
| 41 |
+
"40",58.7,"G","b","G:b"
|
| 42 |
+
"41",56.9,"G","c","G:c"
|
| 43 |
+
"42",57.7,"G","c","G:c"
|
| 44 |
+
"43",59.2,"H","a","H:a"
|
| 45 |
+
"44",59.4,"H","a","H:a"
|
| 46 |
+
"45",65.2,"H","b","H:b"
|
| 47 |
+
"46",66,"H","b","H:b"
|
| 48 |
+
"47",64.8,"H","c","H:c"
|
| 49 |
+
"48",64.1,"H","c","H:c"
|
| 50 |
+
"49",54.8,"I","a","I:a"
|
| 51 |
+
"50",54.8,"I","a","I:a"
|
| 52 |
+
"51",64,"I","b","I:b"
|
| 53 |
+
"52",64,"I","b","I:b"
|
| 54 |
+
"53",57.7,"I","c","I:c"
|
| 55 |
+
"54",56.8,"I","c","I:c"
|
| 56 |
+
"55",58.3,"J","a","J:a"
|
| 57 |
+
"56",59.3,"J","a","J:a"
|
| 58 |
+
"57",59.2,"J","b","J:b"
|
| 59 |
+
"58",59.2,"J","b","J:b"
|
| 60 |
+
"59",58.9,"J","c","J:c"
|
| 61 |
+
"60",56.6,"J","c","J:c"
|
shared/package-files/4b/4b2bc899cc5ebf58fa4db91310f3dfa85aa131c99cb579d067526582aefce8e5/kron_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 kron(const at::Tensor & self, const at::Tensor & other);
|
| 20 |
+
TORCH_API at::Tensor & kron_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
shared/package-files/4b/4b2c1587fa23eee028d6d98c8f2b4869f70b08931f02d3051597bd437bc0e988/cmd.pyi
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import abstractmethod
|
| 2 |
+
from distutils.dist import Distribution
|
| 3 |
+
from typing import Any, Callable, Iterable, List, Optional, Text, Tuple, Union
|
| 4 |
+
|
| 5 |
+
class Command:
|
| 6 |
+
sub_commands: List[Tuple[str, Optional[Callable[[Command], bool]]]]
|
| 7 |
+
def __init__(self, dist: Distribution) -> None: ...
|
| 8 |
+
@abstractmethod
|
| 9 |
+
def initialize_options(self) -> None: ...
|
| 10 |
+
@abstractmethod
|
| 11 |
+
def finalize_options(self) -> None: ...
|
| 12 |
+
@abstractmethod
|
| 13 |
+
def run(self) -> None: ...
|
| 14 |
+
def announce(self, msg: Text, level: int = ...) -> None: ...
|
| 15 |
+
def debug_print(self, msg: Text) -> None: ...
|
| 16 |
+
def ensure_string(self, option: str, default: Optional[str] = ...) -> None: ...
|
| 17 |
+
def ensure_string_list(self, option: Union[str, List[str]]) -> None: ...
|
| 18 |
+
def ensure_filename(self, option: str) -> None: ...
|
| 19 |
+
def ensure_dirname(self, option: str) -> None: ...
|
| 20 |
+
def get_command_name(self) -> str: ...
|
| 21 |
+
def set_undefined_options(self, src_cmd: Text, *option_pairs: Tuple[str, str]) -> None: ...
|
| 22 |
+
def get_finalized_command(self, command: Text, create: int = ...) -> Command: ...
|
| 23 |
+
def reinitialize_command(self, command: Union[Command, Text], reinit_subcommands: int = ...) -> Command: ...
|
| 24 |
+
def run_command(self, command: Text) -> None: ...
|
| 25 |
+
def get_sub_commands(self) -> List[str]: ...
|
| 26 |
+
def warn(self, msg: Text) -> None: ...
|
| 27 |
+
def execute(self, func: Callable[..., Any], args: Iterable[Any], msg: Optional[Text] = ..., level: int = ...) -> None: ...
|
| 28 |
+
def mkpath(self, name: str, mode: int = ...) -> None: ...
|
| 29 |
+
def copy_file(
|
| 30 |
+
self,
|
| 31 |
+
infile: str,
|
| 32 |
+
outfile: str,
|
| 33 |
+
preserve_mode: int = ...,
|
| 34 |
+
preserve_times: int = ...,
|
| 35 |
+
link: Optional[str] = ...,
|
| 36 |
+
level: Any = ...,
|
| 37 |
+
) -> Tuple[str, bool]: ... # level is not used
|
| 38 |
+
def copy_tree(
|
| 39 |
+
self,
|
| 40 |
+
infile: str,
|
| 41 |
+
outfile: str,
|
| 42 |
+
preserve_mode: int = ...,
|
| 43 |
+
preserve_times: int = ...,
|
| 44 |
+
preserve_symlinks: int = ...,
|
| 45 |
+
level: Any = ...,
|
| 46 |
+
) -> List[str]: ... # level is not used
|
| 47 |
+
def move_file(self, src: str, dst: str, level: Any = ...) -> str: ... # level is not used
|
| 48 |
+
def spawn(self, cmd: Iterable[str], search_path: int = ..., level: Any = ...) -> None: ... # level is not used
|
| 49 |
+
def make_archive(
|
| 50 |
+
self,
|
| 51 |
+
base_name: str,
|
| 52 |
+
format: str,
|
| 53 |
+
root_dir: Optional[str] = ...,
|
| 54 |
+
base_dir: Optional[str] = ...,
|
| 55 |
+
owner: Optional[str] = ...,
|
| 56 |
+
group: Optional[str] = ...,
|
| 57 |
+
) -> str: ...
|
| 58 |
+
def make_file(
|
| 59 |
+
self,
|
| 60 |
+
infiles: Union[str, List[str], Tuple[str]],
|
| 61 |
+
outfile: str,
|
| 62 |
+
func: Callable[..., Any],
|
| 63 |
+
args: List[Any],
|
| 64 |
+
exec_msg: Optional[str] = ...,
|
| 65 |
+
skip_msg: Optional[str] = ...,
|
| 66 |
+
level: Any = ...,
|
| 67 |
+
) -> None: ... # level is not used
|
shared/package-files/4b/4b324fa058f2204be2492bcf46f2fcd68d638d025c33e55ea9be76bc553ae894/selectors.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
from narwhals._compliant import CompliantSelector, LazySelectorNamespace
|
| 6 |
+
from narwhals._spark_like.expr import SparkLikeExpr
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from sqlframe.base.column import Column # noqa: F401
|
| 10 |
+
|
| 11 |
+
from narwhals._spark_like.dataframe import SparkLikeLazyFrame # noqa: F401
|
| 12 |
+
from narwhals._spark_like.expr import SparkWindowFunction
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class SparkLikeSelectorNamespace(LazySelectorNamespace["SparkLikeLazyFrame", "Column"]):
|
| 16 |
+
@property
|
| 17 |
+
def _selector(self) -> type[SparkLikeSelector]:
|
| 18 |
+
return SparkLikeSelector
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SparkLikeSelector(CompliantSelector["SparkLikeLazyFrame", "Column"], SparkLikeExpr): # type: ignore[misc]
|
| 22 |
+
_window_function: SparkWindowFunction | None = None
|
| 23 |
+
|
| 24 |
+
def _to_expr(self) -> SparkLikeExpr:
|
| 25 |
+
return SparkLikeExpr(
|
| 26 |
+
self._call,
|
| 27 |
+
evaluate_output_names=self._evaluate_output_names,
|
| 28 |
+
alias_output_names=self._alias_output_names,
|
| 29 |
+
version=self._version,
|
| 30 |
+
implementation=self._implementation,
|
| 31 |
+
)
|
shared/package-files/4b/4b37ecbb4f68a464be2b80e999987c75351d1782ced6671603468036ead2c338/new_empty_strided_compositeexplicitautogradnonfunctional_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 compositeexplicitautogradnonfunctional {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor new_empty_strided(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride, at::TensorOptions options={});
|
| 21 |
+
TORCH_API at::Tensor new_empty_strided(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
|
| 22 |
+
TORCH_API at::Tensor new_empty_strided_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, at::TensorOptions options={});
|
| 23 |
+
TORCH_API at::Tensor new_empty_strided_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
|
| 24 |
+
|
| 25 |
+
} // namespace compositeexplicitautogradnonfunctional
|
| 26 |
+
} // namespace at
|
shared/package-files/4b/4b3aa1d7d213d9806e9617e51608e8be626a5f89b907b856b5ee49057463b828/softshrink_backward_native.h
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
#include <ATen/ops/softshrink_backward_meta.h>
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
struct TORCH_API structured_softshrink_backward_out : public at::meta::structured_softshrink_backward {
|
| 20 |
+
void impl(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & lambd, const at::Tensor & grad_input);
|
| 21 |
+
};
|
| 22 |
+
} // namespace native
|
| 23 |
+
} // namespace at
|
shared/package-files/4b/4b3dfeb7d4f1d254acbb217b7a010b3240936cea015d4554340b76429176ed12/compat.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding: utf-8
|
| 2 |
+
"""Compatibility library."""
|
| 3 |
+
|
| 4 |
+
from typing import TYPE_CHECKING, Any, List
|
| 5 |
+
|
| 6 |
+
# scikit-learn is intentionally imported first here,
|
| 7 |
+
# see https://github.com/microsoft/LightGBM/issues/6509
|
| 8 |
+
"""sklearn"""
|
| 9 |
+
try:
|
| 10 |
+
from sklearn import __version__ as _sklearn_version
|
| 11 |
+
from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
|
| 12 |
+
from sklearn.preprocessing import LabelEncoder
|
| 13 |
+
from sklearn.utils.class_weight import compute_sample_weight
|
| 14 |
+
from sklearn.utils.multiclass import check_classification_targets
|
| 15 |
+
from sklearn.utils.validation import assert_all_finite, check_array, check_X_y
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
from sklearn.exceptions import NotFittedError
|
| 19 |
+
from sklearn.model_selection import BaseCrossValidator, GroupKFold, StratifiedKFold
|
| 20 |
+
except ImportError:
|
| 21 |
+
from sklearn.cross_validation import BaseCrossValidator, GroupKFold, StratifiedKFold
|
| 22 |
+
from sklearn.utils.validation import NotFittedError
|
| 23 |
+
try:
|
| 24 |
+
from sklearn.utils.validation import _check_sample_weight
|
| 25 |
+
except ImportError:
|
| 26 |
+
from sklearn.utils.validation import check_consistent_length
|
| 27 |
+
|
| 28 |
+
# dummy function to support older version of scikit-learn
|
| 29 |
+
def _check_sample_weight(sample_weight: Any, X: Any, dtype: Any = None) -> Any:
|
| 30 |
+
check_consistent_length(sample_weight, X)
|
| 31 |
+
return sample_weight
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
from sklearn.utils.validation import validate_data
|
| 35 |
+
except ImportError:
|
| 36 |
+
# validate_data() was added in scikit-learn 1.6, this function roughly imitates it for older versions.
|
| 37 |
+
# It can be removed when lightgbm's minimum scikit-learn version is at least 1.6.
|
| 38 |
+
def validate_data(
|
| 39 |
+
_estimator,
|
| 40 |
+
X,
|
| 41 |
+
y="no_validation",
|
| 42 |
+
accept_sparse: bool = True,
|
| 43 |
+
# 'force_all_finite' was renamed to 'ensure_all_finite' in scikit-learn 1.6
|
| 44 |
+
ensure_all_finite: bool = False,
|
| 45 |
+
ensure_min_samples: int = 1,
|
| 46 |
+
# trap other keyword arguments that only work on scikit-learn >=1.6, like 'reset'
|
| 47 |
+
**ignored_kwargs,
|
| 48 |
+
):
|
| 49 |
+
# it's safe to import _num_features unconditionally because:
|
| 50 |
+
#
|
| 51 |
+
# * it was first added in scikit-learn 0.24.2
|
| 52 |
+
# * lightgbm cannot be used with scikit-learn versions older than that
|
| 53 |
+
# * this validate_data() re-implementation will not be called in scikit-learn>=1.6
|
| 54 |
+
#
|
| 55 |
+
from sklearn.utils.validation import _num_features
|
| 56 |
+
|
| 57 |
+
# _num_features() raises a TypeError on 1-dimensional input. That's a problem
|
| 58 |
+
# because scikit-learn's 'check_fit1d' estimator check sets that expectation that
|
| 59 |
+
# estimators must raise a ValueError when a 1-dimensional input is passed to fit().
|
| 60 |
+
#
|
| 61 |
+
# So here, lightgbm avoids calling _num_features() on 1-dimensional inputs.
|
| 62 |
+
if hasattr(X, "shape") and len(X.shape) == 1:
|
| 63 |
+
n_features_in_ = 1
|
| 64 |
+
else:
|
| 65 |
+
n_features_in_ = _num_features(X)
|
| 66 |
+
|
| 67 |
+
no_val_y = isinstance(y, str) and y == "no_validation"
|
| 68 |
+
|
| 69 |
+
# NOTE: check_X_y() calls check_array() internally, so only need to call one or the other of them here
|
| 70 |
+
if no_val_y:
|
| 71 |
+
X = check_array(
|
| 72 |
+
X,
|
| 73 |
+
accept_sparse=accept_sparse,
|
| 74 |
+
force_all_finite=ensure_all_finite,
|
| 75 |
+
ensure_min_samples=ensure_min_samples,
|
| 76 |
+
)
|
| 77 |
+
else:
|
| 78 |
+
X, y = check_X_y(
|
| 79 |
+
X,
|
| 80 |
+
y,
|
| 81 |
+
accept_sparse=accept_sparse,
|
| 82 |
+
force_all_finite=ensure_all_finite,
|
| 83 |
+
ensure_min_samples=ensure_min_samples,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
# this only needs to be updated at fit() time
|
| 87 |
+
_estimator.n_features_in_ = n_features_in_
|
| 88 |
+
|
| 89 |
+
# raise the same error that scikit-learn's `validate_data()` does on scikit-learn>=1.6
|
| 90 |
+
if _estimator.__sklearn_is_fitted__() and _estimator._n_features != n_features_in_:
|
| 91 |
+
raise ValueError(
|
| 92 |
+
f"X has {n_features_in_} features, but {_estimator.__class__.__name__} "
|
| 93 |
+
f"is expecting {_estimator._n_features} features as input."
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
if no_val_y:
|
| 97 |
+
return X
|
| 98 |
+
else:
|
| 99 |
+
return X, y
|
| 100 |
+
|
| 101 |
+
SKLEARN_INSTALLED = True
|
| 102 |
+
_LGBMBaseCrossValidator = BaseCrossValidator
|
| 103 |
+
_LGBMModelBase = BaseEstimator
|
| 104 |
+
_LGBMRegressorBase = RegressorMixin
|
| 105 |
+
_LGBMClassifierBase = ClassifierMixin
|
| 106 |
+
_LGBMLabelEncoder = LabelEncoder
|
| 107 |
+
LGBMNotFittedError = NotFittedError
|
| 108 |
+
_LGBMStratifiedKFold = StratifiedKFold
|
| 109 |
+
_LGBMGroupKFold = GroupKFold
|
| 110 |
+
_LGBMCheckSampleWeight = _check_sample_weight
|
| 111 |
+
_LGBMAssertAllFinite = assert_all_finite
|
| 112 |
+
_LGBMCheckClassificationTargets = check_classification_targets
|
| 113 |
+
_LGBMComputeSampleWeight = compute_sample_weight
|
| 114 |
+
_LGBMValidateData = validate_data
|
| 115 |
+
except ImportError:
|
| 116 |
+
SKLEARN_INSTALLED = False
|
| 117 |
+
|
| 118 |
+
class _LGBMModelBase: # type: ignore
|
| 119 |
+
"""Dummy class for sklearn.base.BaseEstimator."""
|
| 120 |
+
|
| 121 |
+
pass
|
| 122 |
+
|
| 123 |
+
class _LGBMClassifierBase: # type: ignore
|
| 124 |
+
"""Dummy class for sklearn.base.ClassifierMixin."""
|
| 125 |
+
|
| 126 |
+
pass
|
| 127 |
+
|
| 128 |
+
class _LGBMRegressorBase: # type: ignore
|
| 129 |
+
"""Dummy class for sklearn.base.RegressorMixin."""
|
| 130 |
+
|
| 131 |
+
pass
|
| 132 |
+
|
| 133 |
+
_LGBMBaseCrossValidator = None
|
| 134 |
+
_LGBMLabelEncoder = None
|
| 135 |
+
LGBMNotFittedError = ValueError
|
| 136 |
+
_LGBMStratifiedKFold = None
|
| 137 |
+
_LGBMGroupKFold = None
|
| 138 |
+
_LGBMCheckSampleWeight = None
|
| 139 |
+
_LGBMAssertAllFinite = None
|
| 140 |
+
_LGBMCheckClassificationTargets = None
|
| 141 |
+
_LGBMComputeSampleWeight = None
|
| 142 |
+
_LGBMValidateData = None
|
| 143 |
+
_sklearn_version = None
|
| 144 |
+
|
| 145 |
+
# additional scikit-learn imports only for type hints
|
| 146 |
+
if TYPE_CHECKING:
|
| 147 |
+
# sklearn.utils.Tags can be imported unconditionally once
|
| 148 |
+
# lightgbm's minimum scikit-learn version is 1.6 or higher
|
| 149 |
+
try:
|
| 150 |
+
from sklearn.utils import Tags as _sklearn_Tags
|
| 151 |
+
except ImportError:
|
| 152 |
+
_sklearn_Tags = None
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
"""pandas"""
|
| 156 |
+
try:
|
| 157 |
+
from pandas import DataFrame as pd_DataFrame
|
| 158 |
+
from pandas import Series as pd_Series
|
| 159 |
+
from pandas import concat
|
| 160 |
+
|
| 161 |
+
try:
|
| 162 |
+
from pandas import CategoricalDtype as pd_CategoricalDtype
|
| 163 |
+
except ImportError:
|
| 164 |
+
from pandas.api.types import CategoricalDtype as pd_CategoricalDtype
|
| 165 |
+
PANDAS_INSTALLED = True
|
| 166 |
+
except ImportError:
|
| 167 |
+
PANDAS_INSTALLED = False
|
| 168 |
+
|
| 169 |
+
class pd_Series: # type: ignore
|
| 170 |
+
"""Dummy class for pandas.Series."""
|
| 171 |
+
|
| 172 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
| 173 |
+
pass
|
| 174 |
+
|
| 175 |
+
class pd_DataFrame: # type: ignore
|
| 176 |
+
"""Dummy class for pandas.DataFrame."""
|
| 177 |
+
|
| 178 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
| 179 |
+
pass
|
| 180 |
+
|
| 181 |
+
class pd_CategoricalDtype: # type: ignore
|
| 182 |
+
"""Dummy class for pandas.CategoricalDtype."""
|
| 183 |
+
|
| 184 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
| 185 |
+
pass
|
| 186 |
+
|
| 187 |
+
concat = None
|
| 188 |
+
|
| 189 |
+
"""matplotlib"""
|
| 190 |
+
try:
|
| 191 |
+
import matplotlib # noqa: F401
|
| 192 |
+
|
| 193 |
+
MATPLOTLIB_INSTALLED = True
|
| 194 |
+
except ImportError:
|
| 195 |
+
MATPLOTLIB_INSTALLED = False
|
| 196 |
+
|
| 197 |
+
"""graphviz"""
|
| 198 |
+
try:
|
| 199 |
+
import graphviz # noqa: F401
|
| 200 |
+
|
| 201 |
+
GRAPHVIZ_INSTALLED = True
|
| 202 |
+
except ImportError:
|
| 203 |
+
GRAPHVIZ_INSTALLED = False
|
| 204 |
+
|
| 205 |
+
"""datatable"""
|
| 206 |
+
try:
|
| 207 |
+
import datatable
|
| 208 |
+
|
| 209 |
+
if hasattr(datatable, "Frame"):
|
| 210 |
+
dt_DataTable = datatable.Frame
|
| 211 |
+
else:
|
| 212 |
+
dt_DataTable = datatable.DataTable
|
| 213 |
+
DATATABLE_INSTALLED = True
|
| 214 |
+
except ImportError:
|
| 215 |
+
DATATABLE_INSTALLED = False
|
| 216 |
+
|
| 217 |
+
class dt_DataTable: # type: ignore
|
| 218 |
+
"""Dummy class for datatable.DataTable."""
|
| 219 |
+
|
| 220 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
| 221 |
+
pass
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
"""dask"""
|
| 225 |
+
try:
|
| 226 |
+
from dask import delayed
|
| 227 |
+
from dask.array import Array as dask_Array
|
| 228 |
+
from dask.array import from_delayed as dask_array_from_delayed
|
| 229 |
+
from dask.bag import from_delayed as dask_bag_from_delayed
|
| 230 |
+
from dask.dataframe import DataFrame as dask_DataFrame
|
| 231 |
+
from dask.dataframe import Series as dask_Series
|
| 232 |
+
from dask.distributed import Client, Future, default_client, wait
|
| 233 |
+
|
| 234 |
+
DASK_INSTALLED = True
|
| 235 |
+
# catching 'ValueError' here because of this:
|
| 236 |
+
# https://github.com/microsoft/LightGBM/issues/6365#issuecomment-2002330003
|
| 237 |
+
#
|
| 238 |
+
# That's potentially risky as dask does some significant import-time processing,
|
| 239 |
+
# like loading configuration from environment variables and files, and catching
|
| 240 |
+
# ValueError here might hide issues with that config-loading.
|
| 241 |
+
#
|
| 242 |
+
# But in exchange, it's less likely that 'import lightgbm' will fail for
|
| 243 |
+
# dask-related reasons, which is beneficial for any workloads that are using
|
| 244 |
+
# lightgbm but not its Dask functionality.
|
| 245 |
+
except (ImportError, ValueError):
|
| 246 |
+
DASK_INSTALLED = False
|
| 247 |
+
|
| 248 |
+
dask_array_from_delayed = None # type: ignore[assignment]
|
| 249 |
+
dask_bag_from_delayed = None # type: ignore[assignment]
|
| 250 |
+
delayed = None
|
| 251 |
+
default_client = None # type: ignore[assignment]
|
| 252 |
+
wait = None # type: ignore[assignment]
|
| 253 |
+
|
| 254 |
+
class Client: # type: ignore
|
| 255 |
+
"""Dummy class for dask.distributed.Client."""
|
| 256 |
+
|
| 257 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
| 258 |
+
pass
|
| 259 |
+
|
| 260 |
+
class Future: # type: ignore
|
| 261 |
+
"""Dummy class for dask.distributed.Future."""
|
| 262 |
+
|
| 263 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
| 264 |
+
pass
|
| 265 |
+
|
| 266 |
+
class dask_Array: # type: ignore
|
| 267 |
+
"""Dummy class for dask.array.Array."""
|
| 268 |
+
|
| 269 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
| 270 |
+
pass
|
| 271 |
+
|
| 272 |
+
class dask_DataFrame: # type: ignore
|
| 273 |
+
"""Dummy class for dask.dataframe.DataFrame."""
|
| 274 |
+
|
| 275 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
| 276 |
+
pass
|
| 277 |
+
|
| 278 |
+
class dask_Series: # type: ignore
|
| 279 |
+
"""Dummy class for dask.dataframe.Series."""
|
| 280 |
+
|
| 281 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
| 282 |
+
pass
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
"""pyarrow"""
|
| 286 |
+
try:
|
| 287 |
+
import pyarrow.compute as pa_compute
|
| 288 |
+
from pyarrow import Array as pa_Array
|
| 289 |
+
from pyarrow import ChunkedArray as pa_ChunkedArray
|
| 290 |
+
from pyarrow import Table as pa_Table
|
| 291 |
+
from pyarrow import chunked_array as pa_chunked_array
|
| 292 |
+
from pyarrow.types import is_boolean as arrow_is_boolean
|
| 293 |
+
from pyarrow.types import is_floating as arrow_is_floating
|
| 294 |
+
from pyarrow.types import is_integer as arrow_is_integer
|
| 295 |
+
|
| 296 |
+
PYARROW_INSTALLED = True
|
| 297 |
+
except ImportError:
|
| 298 |
+
PYARROW_INSTALLED = False
|
| 299 |
+
|
| 300 |
+
class pa_Array: # type: ignore
|
| 301 |
+
"""Dummy class for pa.Array."""
|
| 302 |
+
|
| 303 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
| 304 |
+
pass
|
| 305 |
+
|
| 306 |
+
class pa_ChunkedArray: # type: ignore
|
| 307 |
+
"""Dummy class for pa.ChunkedArray."""
|
| 308 |
+
|
| 309 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
| 310 |
+
pass
|
| 311 |
+
|
| 312 |
+
class pa_Table: # type: ignore
|
| 313 |
+
"""Dummy class for pa.Table."""
|
| 314 |
+
|
| 315 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
| 316 |
+
pass
|
| 317 |
+
|
| 318 |
+
class pa_compute: # type: ignore
|
| 319 |
+
"""Dummy class for pyarrow.compute module."""
|
| 320 |
+
|
| 321 |
+
all = None
|
| 322 |
+
equal = None
|
| 323 |
+
|
| 324 |
+
pa_chunked_array = None
|
| 325 |
+
arrow_is_boolean = None
|
| 326 |
+
arrow_is_integer = None
|
| 327 |
+
arrow_is_floating = None
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
"""cffi"""
|
| 331 |
+
try:
|
| 332 |
+
from pyarrow.cffi import ffi as arrow_cffi
|
| 333 |
+
|
| 334 |
+
CFFI_INSTALLED = True
|
| 335 |
+
except ImportError:
|
| 336 |
+
CFFI_INSTALLED = False
|
| 337 |
+
|
| 338 |
+
class arrow_cffi: # type: ignore
|
| 339 |
+
"""Dummy class for pyarrow.cffi.ffi."""
|
| 340 |
+
|
| 341 |
+
CData = None
|
| 342 |
+
|
| 343 |
+
def __init__(self, *args: Any, **kwargs: Any):
|
| 344 |
+
pass
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
"""cpu_count()"""
|
| 348 |
+
try:
|
| 349 |
+
from joblib import cpu_count
|
| 350 |
+
|
| 351 |
+
def _LGBMCpuCount(only_physical_cores: bool = True) -> int:
|
| 352 |
+
return cpu_count(only_physical_cores=only_physical_cores)
|
| 353 |
+
except ImportError:
|
| 354 |
+
try:
|
| 355 |
+
from psutil import cpu_count
|
| 356 |
+
|
| 357 |
+
def _LGBMCpuCount(only_physical_cores: bool = True) -> int:
|
| 358 |
+
return cpu_count(logical=not only_physical_cores) or 1
|
| 359 |
+
except ImportError:
|
| 360 |
+
from multiprocessing import cpu_count
|
| 361 |
+
|
| 362 |
+
def _LGBMCpuCount(only_physical_cores: bool = True) -> int:
|
| 363 |
+
return cpu_count()
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
__all__: List[str] = []
|
shared/package-files/4b/4b3ea073c802fc2f8fdcbb8c2dc6527ccc71081153b643bf49071509ff43a3aa/weight_utils.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import torch.ao.nn.quantized.dynamic as nnqd
|
| 5 |
+
import torch.ao.nn.quantized as nnq
|
| 6 |
+
import torch.ao.nn.intrinsic.qat as nniqat
|
| 7 |
+
import torch.ao.nn.qat as nnqat
|
| 8 |
+
import torch.ao.nn.intrinsic as nni
|
| 9 |
+
import torch.ao.nn.intrinsic.quantized as nniq
|
| 10 |
+
toq = torch.ops.quantized
|
| 11 |
+
from torch.fx import GraphModule
|
| 12 |
+
from torch.fx.graph import Node
|
| 13 |
+
|
| 14 |
+
from .utils import (
|
| 15 |
+
get_target_type_str,
|
| 16 |
+
getattr_from_fqn,
|
| 17 |
+
return_first_non_observer_node,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
from .ns_types import (
|
| 21 |
+
NSSingleResultValuesType,
|
| 22 |
+
NSSingleResultType,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
from typing import List, Optional, Dict, Callable
|
| 26 |
+
|
| 27 |
+
def mod_weight_detach(mod: nn.Module) -> torch.Tensor:
|
| 28 |
+
return mod.weight.detach() # type: ignore[operator]
|
| 29 |
+
|
| 30 |
+
def mod_0_weight_detach(mod: nn.Module) -> torch.Tensor:
|
| 31 |
+
return mod[0].weight.detach() # type: ignore[index]
|
| 32 |
+
|
| 33 |
+
def mod_weight_bias_0(mod: nn.Module) -> torch.Tensor:
|
| 34 |
+
return mod._weight_bias()[0] # type: ignore[operator]
|
| 35 |
+
|
| 36 |
+
def get_lstm_weight(mod: nn.Module) -> List[torch.Tensor]:
|
| 37 |
+
res = []
|
| 38 |
+
for idx, param_name in enumerate(mod._flat_weights_names): # type: ignore[arg-type]
|
| 39 |
+
if 'weight_ih_l' in param_name or 'weight_hh_l' in param_name:
|
| 40 |
+
param_value = mod._flat_weights[idx].detach() # type: ignore[index]
|
| 41 |
+
res.append(param_value)
|
| 42 |
+
return res
|
| 43 |
+
|
| 44 |
+
def get_qlstm_weight(mod: nn.Module) -> List[torch.Tensor]:
|
| 45 |
+
res = []
|
| 46 |
+
for weight_value in mod._all_weight_values: # type: ignore[union-attr]
|
| 47 |
+
res.append(weight_value.param.__getstate__()[0][4][0].__getstate__()[0][0])
|
| 48 |
+
res.append(weight_value.param.__getstate__()[0][4][1].__getstate__()[0][0])
|
| 49 |
+
return res
|
| 50 |
+
|
| 51 |
+
def get_conv_mod_weight(mod: nn.Module) -> torch.Tensor:
|
| 52 |
+
if (
|
| 53 |
+
isinstance(mod, (nn.Conv1d, nn.Conv2d, nn.Conv3d))
|
| 54 |
+
):
|
| 55 |
+
return mod.weight.detach()
|
| 56 |
+
elif (
|
| 57 |
+
isinstance(mod, (nni.ConvReLU1d, nni.ConvReLU2d, nni.ConvReLU3d))
|
| 58 |
+
):
|
| 59 |
+
return mod[0].weight.detach()
|
| 60 |
+
else:
|
| 61 |
+
return mod._weight_bias()[0] # type: ignore[operator]
|
| 62 |
+
|
| 63 |
+
def get_linear_mod_weight(mod: nn.Module) -> torch.Tensor:
|
| 64 |
+
if isinstance(mod, nn.Linear):
|
| 65 |
+
return mod.weight.detach()
|
| 66 |
+
elif isinstance(mod, nni.LinearReLU):
|
| 67 |
+
return mod[0].weight.detach()
|
| 68 |
+
else:
|
| 69 |
+
return mod._weight_bias()[0] # type: ignore[operator]
|
| 70 |
+
|
| 71 |
+
def get_lstm_mod_weights(mod: nn.Module) -> List[torch.Tensor]:
|
| 72 |
+
# TODO(future PR): make more generic, handle everything
|
| 73 |
+
if isinstance(mod, nn.LSTM):
|
| 74 |
+
res = []
|
| 75 |
+
for idx, param_name in enumerate(mod._flat_weights_names):
|
| 76 |
+
if 'weight_ih_l' in param_name or 'weight_hh_l' in param_name:
|
| 77 |
+
param_value = mod._flat_weights[idx].detach()
|
| 78 |
+
res.append(param_value)
|
| 79 |
+
return res
|
| 80 |
+
else:
|
| 81 |
+
assert isinstance(mod, nnqd.LSTM), f"type {type(mod)} not handled yet"
|
| 82 |
+
res = []
|
| 83 |
+
for weight_value in mod._all_weight_values:
|
| 84 |
+
res.append(weight_value.param.__getstate__()[0][4][0].__getstate__()[0][0])
|
| 85 |
+
res.append(weight_value.param.__getstate__()[0][4][1].__getstate__()[0][0])
|
| 86 |
+
return res
|
| 87 |
+
|
| 88 |
+
def get_conv_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
|
| 89 |
+
# traverse backwards from the weight arg, accounting for any observers
|
| 90 |
+
weight_arg_node = node.args[1]
|
| 91 |
+
assert isinstance(weight_arg_node, Node)
|
| 92 |
+
weight_node = return_first_non_observer_node(weight_arg_node, gm)
|
| 93 |
+
assert isinstance(weight_node, Node)
|
| 94 |
+
assert weight_node.op == 'get_attr'
|
| 95 |
+
weight = getattr_from_fqn(gm, weight_node.target) # type: ignore[arg-type]
|
| 96 |
+
return weight.detach()
|
| 97 |
+
|
| 98 |
+
def get_qconv_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
|
| 99 |
+
# qconv state is arg 1
|
| 100 |
+
qconv_state_node = node.args[1]
|
| 101 |
+
assert isinstance(qconv_state_node, Node)
|
| 102 |
+
assert qconv_state_node.op == 'get_attr'
|
| 103 |
+
qconv_state_obj = getattr_from_fqn(gm, qconv_state_node.target) # type: ignore[arg-type]
|
| 104 |
+
return qconv_state_obj.weight()
|
| 105 |
+
|
| 106 |
+
def get_linear_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
|
| 107 |
+
# traverse backwards from the weight arg, accounting for any observers
|
| 108 |
+
# supported patterns:
|
| 109 |
+
# weight -> obs -> linear
|
| 110 |
+
# weight -> to(torch.float16) -> dequantize -> linear
|
| 111 |
+
linear_second_arg = node.args[1]
|
| 112 |
+
assert isinstance(linear_second_arg, Node)
|
| 113 |
+
|
| 114 |
+
if linear_second_arg.op == 'call_module':
|
| 115 |
+
# weight -> obs -> linear
|
| 116 |
+
weight_arg_node = node.args[1]
|
| 117 |
+
assert isinstance(weight_arg_node, Node)
|
| 118 |
+
weight_node = weight_arg_node.args[0]
|
| 119 |
+
assert isinstance(weight_node, Node)
|
| 120 |
+
assert weight_node.op == 'get_attr'
|
| 121 |
+
weight = getattr_from_fqn(gm, weight_node.target) # type: ignore[arg-type]
|
| 122 |
+
return weight.detach()
|
| 123 |
+
elif linear_second_arg.op == 'call_method':
|
| 124 |
+
# weight -> to(torch.float16) -> dequantize -> linear
|
| 125 |
+
assert linear_second_arg.op == 'call_method'
|
| 126 |
+
dequant_node = node.args[1]
|
| 127 |
+
assert isinstance(dequant_node, Node)
|
| 128 |
+
to_fp16_node = dequant_node.args[0]
|
| 129 |
+
assert isinstance(to_fp16_node, Node)
|
| 130 |
+
# extract the dtype, so we can cast to it before returning
|
| 131 |
+
target_dtype = to_fp16_node.args[1]
|
| 132 |
+
weight_node = to_fp16_node.args[0]
|
| 133 |
+
assert isinstance(weight_node, Node)
|
| 134 |
+
assert weight_node.op == 'get_attr'
|
| 135 |
+
weight = getattr_from_fqn(gm, weight_node.target) # type: ignore[arg-type]
|
| 136 |
+
# return the weight with fp16 cast
|
| 137 |
+
return weight.detach().to(target_dtype)
|
| 138 |
+
else:
|
| 139 |
+
assert linear_second_arg.op == 'get_attr'
|
| 140 |
+
weight = getattr_from_fqn(gm, linear_second_arg.target) # type: ignore[arg-type]
|
| 141 |
+
return weight.detach()
|
| 142 |
+
|
| 143 |
+
def get_qlinear_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
|
| 144 |
+
# packed weight is arg 1
|
| 145 |
+
packed_weight_node = node.args[1]
|
| 146 |
+
assert isinstance(packed_weight_node, Node)
|
| 147 |
+
assert packed_weight_node.op == 'get_attr'
|
| 148 |
+
packed_weight = getattr_from_fqn(gm, packed_weight_node.target) # type: ignore[arg-type]
|
| 149 |
+
# TODO(future PR): why does packed_weight.unpack() not work?
|
| 150 |
+
(weight, _bias), _name = packed_weight.__getstate__()
|
| 151 |
+
return weight
|
| 152 |
+
|
| 153 |
+
def get_op_to_type_to_weight_extraction_fn() -> Dict[str, Dict[Callable, Callable]]:
|
| 154 |
+
|
| 155 |
+
op_to_type_to_weight_extraction_fn: Dict[str, Dict[Callable, Callable]] = {
|
| 156 |
+
'call_module': {
|
| 157 |
+
# Conv1d
|
| 158 |
+
nn.Conv1d: mod_weight_detach,
|
| 159 |
+
nni.ConvReLU1d: mod_0_weight_detach,
|
| 160 |
+
nnq.Conv1d: mod_weight_bias_0,
|
| 161 |
+
nnqat.Conv1d: mod_weight_detach,
|
| 162 |
+
nniqat.ConvBn1d: mod_weight_detach,
|
| 163 |
+
nniqat.ConvBnReLU1d: mod_weight_detach,
|
| 164 |
+
nniqat.ConvReLU1d: mod_weight_detach,
|
| 165 |
+
nniq.ConvReLU1d: mod_weight_bias_0,
|
| 166 |
+
# Conv2d
|
| 167 |
+
nn.Conv2d: mod_weight_detach,
|
| 168 |
+
nni.ConvReLU2d: mod_0_weight_detach,
|
| 169 |
+
nnq.Conv2d: mod_weight_bias_0,
|
| 170 |
+
nnqat.Conv2d: mod_weight_detach,
|
| 171 |
+
nniqat.ConvBn2d: mod_weight_detach,
|
| 172 |
+
nniqat.ConvBnReLU2d: mod_weight_detach,
|
| 173 |
+
nniqat.ConvReLU2d: mod_weight_detach,
|
| 174 |
+
nniq.ConvReLU2d: mod_weight_bias_0,
|
| 175 |
+
# Conv3d
|
| 176 |
+
nn.Conv3d: mod_weight_detach,
|
| 177 |
+
nni.ConvReLU3d: mod_0_weight_detach,
|
| 178 |
+
nnq.Conv3d: mod_weight_bias_0,
|
| 179 |
+
nnqat.Conv3d: mod_weight_detach,
|
| 180 |
+
nniqat.ConvBn3d: mod_weight_detach,
|
| 181 |
+
nniqat.ConvBnReLU3d: mod_weight_detach,
|
| 182 |
+
nniqat.ConvReLU3d: mod_weight_detach,
|
| 183 |
+
nniq.ConvReLU3d: mod_weight_bias_0,
|
| 184 |
+
# Linear
|
| 185 |
+
nn.Linear: mod_weight_detach,
|
| 186 |
+
nnq.Linear: mod_weight_bias_0,
|
| 187 |
+
nni.LinearReLU: mod_0_weight_detach,
|
| 188 |
+
nniq.LinearReLU: mod_weight_bias_0,
|
| 189 |
+
nnqat.Linear: mod_weight_detach,
|
| 190 |
+
nnqd.Linear: mod_weight_bias_0,
|
| 191 |
+
nniqat.LinearReLU: mod_weight_detach,
|
| 192 |
+
nniqat.LinearBn1d: mod_weight_detach,
|
| 193 |
+
nn.modules.linear.NonDynamicallyQuantizableLinear: mod_weight_detach,
|
| 194 |
+
# LSTM
|
| 195 |
+
nn.LSTM: get_lstm_weight,
|
| 196 |
+
nnqd.LSTM: get_qlstm_weight,
|
| 197 |
+
},
|
| 198 |
+
'call_function': {
|
| 199 |
+
# Conv
|
| 200 |
+
F.conv1d: get_conv_fun_weight,
|
| 201 |
+
F.conv2d: get_conv_fun_weight,
|
| 202 |
+
F.conv3d: get_conv_fun_weight,
|
| 203 |
+
toq.conv1d: get_qconv_fun_weight,
|
| 204 |
+
toq.conv2d: get_qconv_fun_weight,
|
| 205 |
+
toq.conv3d: get_qconv_fun_weight,
|
| 206 |
+
toq.conv1d_relu: get_qconv_fun_weight,
|
| 207 |
+
toq.conv2d_relu: get_qconv_fun_weight,
|
| 208 |
+
toq.conv3d_relu: get_qconv_fun_weight,
|
| 209 |
+
# Linear
|
| 210 |
+
F.linear: get_linear_fun_weight,
|
| 211 |
+
toq.linear: get_qlinear_fun_weight,
|
| 212 |
+
toq.linear_relu: get_qlinear_fun_weight,
|
| 213 |
+
},
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
return op_to_type_to_weight_extraction_fn
|
| 217 |
+
|
| 218 |
+
def extract_weight_from_node(
|
| 219 |
+
node: Node,
|
| 220 |
+
gm: GraphModule,
|
| 221 |
+
op_to_type_to_weight_extraction_fn: Optional[Dict[str, Dict[Callable, Callable]]] = None,
|
| 222 |
+
) -> Optional[NSSingleResultType]:
|
| 223 |
+
res_type = NSSingleResultValuesType.WEIGHT.value
|
| 224 |
+
|
| 225 |
+
# Not all graphmodules have _node_name_to_scope, so only fill it
|
| 226 |
+
# out if it exists.
|
| 227 |
+
fqn = None
|
| 228 |
+
if hasattr(gm, '_node_name_to_scope'):
|
| 229 |
+
fqn = gm._node_name_to_scope[node.name][0] # type: ignore[index]
|
| 230 |
+
|
| 231 |
+
if op_to_type_to_weight_extraction_fn is None:
|
| 232 |
+
op_to_type_to_weight_extraction_fn = get_op_to_type_to_weight_extraction_fn()
|
| 233 |
+
|
| 234 |
+
ref_node_type = get_target_type_str(node, gm)
|
| 235 |
+
# for extracting weights, these are always the same
|
| 236 |
+
prev_node_type = ref_node_type
|
| 237 |
+
|
| 238 |
+
if node.op == 'call_function':
|
| 239 |
+
function_mapping = op_to_type_to_weight_extraction_fn['call_function']
|
| 240 |
+
for target_fn_type, weight_extraction_fn in function_mapping.items():
|
| 241 |
+
if node.target == target_fn_type:
|
| 242 |
+
weight = weight_extraction_fn(node, gm)
|
| 243 |
+
return {
|
| 244 |
+
'type': res_type,
|
| 245 |
+
'values': [weight],
|
| 246 |
+
'prev_node_name': node.name,
|
| 247 |
+
'prev_node_target_type': prev_node_type,
|
| 248 |
+
'ref_node_name': node.name,
|
| 249 |
+
'ref_node_target_type': ref_node_type,
|
| 250 |
+
'index_within_arg': 0,
|
| 251 |
+
'index_of_arg': 0,
|
| 252 |
+
'fqn': fqn,
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
elif node.op == 'call_module':
|
| 256 |
+
# for call_module, we need to look up the modules to do the type check
|
| 257 |
+
assert isinstance(node.target, str)
|
| 258 |
+
mod = getattr_from_fqn(gm, node.target)
|
| 259 |
+
module_mapping = op_to_type_to_weight_extraction_fn['call_module']
|
| 260 |
+
for target_mod_type, weight_extraction_fn in module_mapping.items():
|
| 261 |
+
if type(mod) == target_mod_type:
|
| 262 |
+
weight = weight_extraction_fn(mod)
|
| 263 |
+
return {
|
| 264 |
+
'type': res_type,
|
| 265 |
+
'values': [weight],
|
| 266 |
+
'prev_node_name': node.name,
|
| 267 |
+
'prev_node_target_type': prev_node_type,
|
| 268 |
+
'ref_node_name': node.name,
|
| 269 |
+
'ref_node_target_type': ref_node_type,
|
| 270 |
+
'index_within_arg': 0,
|
| 271 |
+
'index_of_arg': 0,
|
| 272 |
+
'fqn': fqn,
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
return None
|
shared/package-files/4b/4b45b4ec49e90135a8e6ccb557e140a0fa728514f50c73af79bf4fc976bb89b4/test_mocking.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
from numpy.testing import assert_array_equal
|
| 4 |
+
from scipy import sparse
|
| 5 |
+
|
| 6 |
+
from sklearn.datasets import load_iris
|
| 7 |
+
from sklearn.utils import _safe_indexing, check_array
|
| 8 |
+
from sklearn.utils._mocking import (
|
| 9 |
+
CheckingClassifier,
|
| 10 |
+
_MockEstimatorOnOffPrediction,
|
| 11 |
+
)
|
| 12 |
+
from sklearn.utils._testing import _convert_container
|
| 13 |
+
from sklearn.utils.fixes import CSR_CONTAINERS
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@pytest.fixture
|
| 17 |
+
def iris():
|
| 18 |
+
return load_iris(return_X_y=True)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _success(x):
|
| 22 |
+
return True
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _fail(x):
|
| 26 |
+
return False
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@pytest.mark.parametrize(
|
| 30 |
+
"kwargs",
|
| 31 |
+
[
|
| 32 |
+
{},
|
| 33 |
+
{"check_X": _success},
|
| 34 |
+
{"check_y": _success},
|
| 35 |
+
{"check_X": _success, "check_y": _success},
|
| 36 |
+
],
|
| 37 |
+
)
|
| 38 |
+
def test_check_on_fit_success(iris, kwargs):
|
| 39 |
+
X, y = iris
|
| 40 |
+
CheckingClassifier(**kwargs).fit(X, y)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@pytest.mark.parametrize(
|
| 44 |
+
"kwargs",
|
| 45 |
+
[
|
| 46 |
+
{"check_X": _fail},
|
| 47 |
+
{"check_y": _fail},
|
| 48 |
+
{"check_X": _success, "check_y": _fail},
|
| 49 |
+
{"check_X": _fail, "check_y": _success},
|
| 50 |
+
{"check_X": _fail, "check_y": _fail},
|
| 51 |
+
],
|
| 52 |
+
)
|
| 53 |
+
def test_check_on_fit_fail(iris, kwargs):
|
| 54 |
+
X, y = iris
|
| 55 |
+
clf = CheckingClassifier(**kwargs)
|
| 56 |
+
with pytest.raises(AssertionError):
|
| 57 |
+
clf.fit(X, y)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@pytest.mark.parametrize(
|
| 61 |
+
"pred_func", ["predict", "predict_proba", "decision_function", "score"]
|
| 62 |
+
)
|
| 63 |
+
def test_check_X_on_predict_success(iris, pred_func):
|
| 64 |
+
X, y = iris
|
| 65 |
+
clf = CheckingClassifier(check_X=_success).fit(X, y)
|
| 66 |
+
getattr(clf, pred_func)(X)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@pytest.mark.parametrize(
|
| 70 |
+
"pred_func", ["predict", "predict_proba", "decision_function", "score"]
|
| 71 |
+
)
|
| 72 |
+
def test_check_X_on_predict_fail(iris, pred_func):
|
| 73 |
+
X, y = iris
|
| 74 |
+
clf = CheckingClassifier(check_X=_success).fit(X, y)
|
| 75 |
+
clf.set_params(check_X=_fail)
|
| 76 |
+
with pytest.raises(AssertionError):
|
| 77 |
+
getattr(clf, pred_func)(X)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@pytest.mark.parametrize("input_type", ["list", "array", "sparse", "dataframe"])
|
| 81 |
+
def test_checking_classifier(iris, input_type):
|
| 82 |
+
# Check that the CheckingClassifier outputs what we expect
|
| 83 |
+
X, y = iris
|
| 84 |
+
X = _convert_container(X, input_type)
|
| 85 |
+
clf = CheckingClassifier()
|
| 86 |
+
clf.fit(X, y)
|
| 87 |
+
|
| 88 |
+
assert_array_equal(clf.classes_, np.unique(y))
|
| 89 |
+
assert len(clf.classes_) == 3
|
| 90 |
+
assert clf.n_features_in_ == 4
|
| 91 |
+
|
| 92 |
+
y_pred = clf.predict(X)
|
| 93 |
+
assert all(pred in clf.classes_ for pred in y_pred)
|
| 94 |
+
|
| 95 |
+
assert clf.score(X) == pytest.approx(0)
|
| 96 |
+
clf.set_params(foo_param=10)
|
| 97 |
+
assert clf.fit(X, y).score(X) == pytest.approx(1)
|
| 98 |
+
|
| 99 |
+
y_proba = clf.predict_proba(X)
|
| 100 |
+
assert y_proba.shape == (150, 3)
|
| 101 |
+
assert np.logical_and(y_proba >= 0, y_proba <= 1).all()
|
| 102 |
+
|
| 103 |
+
y_decision = clf.decision_function(X)
|
| 104 |
+
assert y_decision.shape == (150, 3)
|
| 105 |
+
|
| 106 |
+
# check the shape in case of binary classification
|
| 107 |
+
first_2_classes = np.logical_or(y == 0, y == 1)
|
| 108 |
+
X = _safe_indexing(X, first_2_classes)
|
| 109 |
+
y = _safe_indexing(y, first_2_classes)
|
| 110 |
+
clf.fit(X, y)
|
| 111 |
+
|
| 112 |
+
y_proba = clf.predict_proba(X)
|
| 113 |
+
assert y_proba.shape == (100, 2)
|
| 114 |
+
assert np.logical_and(y_proba >= 0, y_proba <= 1).all()
|
| 115 |
+
|
| 116 |
+
y_decision = clf.decision_function(X)
|
| 117 |
+
assert y_decision.shape == (100,)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
|
| 121 |
+
def test_checking_classifier_with_params(iris, csr_container):
|
| 122 |
+
X, y = iris
|
| 123 |
+
X_sparse = csr_container(X)
|
| 124 |
+
|
| 125 |
+
clf = CheckingClassifier(check_X=sparse.issparse)
|
| 126 |
+
with pytest.raises(AssertionError):
|
| 127 |
+
clf.fit(X, y)
|
| 128 |
+
clf.fit(X_sparse, y)
|
| 129 |
+
|
| 130 |
+
clf = CheckingClassifier(
|
| 131 |
+
check_X=check_array, check_X_params={"accept_sparse": False}
|
| 132 |
+
)
|
| 133 |
+
clf.fit(X, y)
|
| 134 |
+
with pytest.raises(TypeError, match="Sparse data was passed"):
|
| 135 |
+
clf.fit(X_sparse, y)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def test_checking_classifier_fit_params(iris):
|
| 139 |
+
# check the error raised when the number of samples is not the one expected
|
| 140 |
+
X, y = iris
|
| 141 |
+
clf = CheckingClassifier(expected_sample_weight=True)
|
| 142 |
+
sample_weight = np.ones(len(X) // 2)
|
| 143 |
+
|
| 144 |
+
msg = f"sample_weight.shape == ({len(X) // 2},), expected ({len(X)},)!"
|
| 145 |
+
with pytest.raises(ValueError) as exc:
|
| 146 |
+
clf.fit(X, y, sample_weight=sample_weight)
|
| 147 |
+
assert exc.value.args[0] == msg
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def test_checking_classifier_missing_fit_params(iris):
|
| 151 |
+
X, y = iris
|
| 152 |
+
clf = CheckingClassifier(expected_sample_weight=True)
|
| 153 |
+
err_msg = "Expected sample_weight to be passed"
|
| 154 |
+
with pytest.raises(AssertionError, match=err_msg):
|
| 155 |
+
clf.fit(X, y)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@pytest.mark.parametrize(
|
| 159 |
+
"methods_to_check",
|
| 160 |
+
[["predict"], ["predict", "predict_proba"]],
|
| 161 |
+
)
|
| 162 |
+
@pytest.mark.parametrize(
|
| 163 |
+
"predict_method", ["predict", "predict_proba", "decision_function", "score"]
|
| 164 |
+
)
|
| 165 |
+
def test_checking_classifier_methods_to_check(iris, methods_to_check, predict_method):
|
| 166 |
+
# check that methods_to_check allows to bypass checks
|
| 167 |
+
X, y = iris
|
| 168 |
+
|
| 169 |
+
clf = CheckingClassifier(
|
| 170 |
+
check_X=sparse.issparse,
|
| 171 |
+
methods_to_check=methods_to_check,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
clf.fit(X, y)
|
| 175 |
+
if predict_method in methods_to_check:
|
| 176 |
+
with pytest.raises(AssertionError):
|
| 177 |
+
getattr(clf, predict_method)(X)
|
| 178 |
+
else:
|
| 179 |
+
getattr(clf, predict_method)(X)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@pytest.mark.parametrize(
|
| 183 |
+
"response_methods",
|
| 184 |
+
[
|
| 185 |
+
["predict"],
|
| 186 |
+
["predict", "predict_proba"],
|
| 187 |
+
["predict", "decision_function"],
|
| 188 |
+
["predict", "predict_proba", "decision_function"],
|
| 189 |
+
],
|
| 190 |
+
)
|
| 191 |
+
def test_mock_estimator_on_off_prediction(iris, response_methods):
|
| 192 |
+
X, y = iris
|
| 193 |
+
estimator = _MockEstimatorOnOffPrediction(response_methods=response_methods)
|
| 194 |
+
|
| 195 |
+
estimator.fit(X, y)
|
| 196 |
+
assert hasattr(estimator, "classes_")
|
| 197 |
+
assert_array_equal(estimator.classes_, np.unique(y))
|
| 198 |
+
|
| 199 |
+
possible_responses = ["predict", "predict_proba", "decision_function"]
|
| 200 |
+
for response in possible_responses:
|
| 201 |
+
if response in response_methods:
|
| 202 |
+
assert hasattr(estimator, response)
|
| 203 |
+
assert getattr(estimator, response)(X) == response
|
| 204 |
+
else:
|
| 205 |
+
assert not hasattr(estimator, response)
|
shared/package-files/4b/4b479d20416e47fcc964ba77d97bb446eaf9b6325d0c4ccd513512645a609f24/citoh-6lpi
ADDED
|
Binary file (444 Bytes). View file
|
|
|
shared/package-files/4b/4b4a2ba49a08e73193559c825067eb9b3da3837be0ef936b42aae1e81fea18a7/conda.bat
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@REM Copyright (C) 2012 Anaconda, Inc
|
| 2 |
+
@REM SPDX-License-Identifier: BSD-3-Clause
|
| 3 |
+
|
| 4 |
+
@REM echo _CE_CONDA is %_CE_CONDA%
|
| 5 |
+
@REM echo _CE_M is %_CE_M%
|
| 6 |
+
@REM echo CONDA_EXE is %CONDA_EXE%
|
| 7 |
+
|
| 8 |
+
@IF NOT DEFINED _CE_CONDA (
|
| 9 |
+
@SET _CE_M=
|
| 10 |
+
@SET "CONDA_EXE=%~dp0..\Scripts\conda.exe"
|
| 11 |
+
)
|
| 12 |
+
@IF [%1]==[activate] "%~dp0_conda_activate" %*
|
| 13 |
+
@IF [%1]==[deactivate] "%~dp0_conda_activate" %*
|
| 14 |
+
|
| 15 |
+
@SET CONDA_EXES="%CONDA_EXE%" %_CE_M% %_CE_CONDA%
|
| 16 |
+
@CALL %CONDA_EXES% %*
|
| 17 |
+
|
| 18 |
+
@IF %errorlevel% NEQ 0 EXIT /B %errorlevel%
|
| 19 |
+
|
| 20 |
+
@IF [%1]==[install] "%~dp0_conda_activate" reactivate
|
| 21 |
+
@IF [%1]==[update] "%~dp0_conda_activate" reactivate
|
| 22 |
+
@IF [%1]==[upgrade] "%~dp0_conda_activate" reactivate
|
| 23 |
+
@IF [%1]==[remove] "%~dp0_conda_activate" reactivate
|
| 24 |
+
@IF [%1]==[uninstall] "%~dp0_conda_activate" reactivate
|
| 25 |
+
|
| 26 |
+
@EXIT /B %errorlevel%
|
shared/package-files/4b/4b4b0115c341185d2b33fcfa6be0c23479b0acaab811bf0d6535b3c59508316e/cuda_codegen.h
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <unordered_map>
|
| 4 |
+
#include <unordered_set>
|
| 5 |
+
|
| 6 |
+
#include <ATen/ATen.h>
|
| 7 |
+
#include <ATen/cuda/CUDAContext.h>
|
| 8 |
+
#include <ATen/cuda/nvrtc_stub/ATenNVRTC.h>
|
| 9 |
+
#include <c10/cuda/CUDACachingAllocator.h>
|
| 10 |
+
#include <c10/cuda/CUDAGuard.h>
|
| 11 |
+
#include <torch/csrc/jit/resource_guard.h>
|
| 12 |
+
#include <torch/csrc/jit/tensorexpr/codegen.h>
|
| 13 |
+
#include <torch/csrc/jit/tensorexpr/eval.h>
|
| 14 |
+
#include <torch/csrc/jit/tensorexpr/ir.h>
|
| 15 |
+
#include <torch/csrc/jit/tensorexpr/ir_printer.h>
|
| 16 |
+
#include <torch/csrc/jit/tensorexpr/ir_visitor.h>
|
| 17 |
+
#include <torch/csrc/jit/tensorexpr/llvm_codegen.h>
|
| 18 |
+
#include <torch/csrc/jit/tensorexpr/unique_name_manager.h>
|
| 19 |
+
|
| 20 |
+
namespace torch {
|
| 21 |
+
namespace jit {
|
| 22 |
+
namespace tensorexpr {
|
| 23 |
+
|
| 24 |
+
// A class that analyzes the given program relevant for Cuda backends.
|
| 25 |
+
class CudaAnalysis : public IRVisitor {
|
| 26 |
+
public:
|
| 27 |
+
CudaAnalysis() {
|
| 28 |
+
gpu_block_extents_ = {alloc<IntImm>(1), alloc<IntImm>(1), alloc<IntImm>(1)};
|
| 29 |
+
gpu_thread_extents_ = {
|
| 30 |
+
alloc<IntImm>(1), alloc<IntImm>(1), alloc<IntImm>(1)};
|
| 31 |
+
}
|
| 32 |
+
bool is_buf_store_target(BufPtr buf) const {
|
| 33 |
+
return store_targets_.count(buf) > 0;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
const std::unordered_set<VarPtr>& thread_local_bufs() const {
|
| 37 |
+
return thread_local_bufs_;
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
const std::unordered_set<VarPtr>& cross_block_bufs() const {
|
| 41 |
+
return cross_block_bufs_;
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
const std::vector<ExprPtr>& gpu_block_extents() const {
|
| 45 |
+
return gpu_block_extents_;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
const std::vector<ExprPtr>& gpu_thread_extents() const {
|
| 49 |
+
return gpu_thread_extents_;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
private:
|
| 53 |
+
void visit(StorePtr v) override {
|
| 54 |
+
store_targets_.insert(v->buf());
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
void visit(AllocatePtr v) override;
|
| 58 |
+
void visit(FreePtr v) override;
|
| 59 |
+
void visit(PlacementAllocatePtr v) override;
|
| 60 |
+
void visit(ForPtr v) override;
|
| 61 |
+
|
| 62 |
+
std::unordered_set<BufPtr> store_targets_;
|
| 63 |
+
std::unordered_set<VarPtr> thread_local_bufs_;
|
| 64 |
+
std::unordered_set<VarPtr> cross_block_bufs_;
|
| 65 |
+
|
| 66 |
+
std::vector<ExprPtr> gpu_block_extents_;
|
| 67 |
+
std::vector<ExprPtr> gpu_thread_extents_;
|
| 68 |
+
};
|
| 69 |
+
|
| 70 |
+
// An IRMutator that replaces binding loop options with Cuda metavars, and masks
|
| 71 |
+
// statements blocks which should execute with less reach than the launch
|
| 72 |
+
// parameter extent.
|
| 73 |
+
//
|
| 74 |
+
// We do this by segmenting each block into chunks which should have the same
|
| 75 |
+
// execution parameters, then if those params differ from the max mask each dim.
|
| 76 |
+
class GPUMetaVarRewriter : public IRMutator {
|
| 77 |
+
public:
|
| 78 |
+
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
|
| 79 |
+
explicit GPUMetaVarRewriter(const CudaAnalysis* cuda_analysis)
|
| 80 |
+
: cuda_analysis_(cuda_analysis) {
|
| 81 |
+
gpu_block_vars_ = {
|
| 82 |
+
alloc<Var>("blockIdx.x", kInt),
|
| 83 |
+
alloc<Var>("blockIdx.y", kInt),
|
| 84 |
+
alloc<Var>("blockIdx.z", kInt)};
|
| 85 |
+
gpu_thread_vars_ = {
|
| 86 |
+
alloc<Var>("threadIdx.x", kInt),
|
| 87 |
+
alloc<Var>("threadIdx.y", kInt),
|
| 88 |
+
alloc<Var>("threadIdx.z", kInt)};
|
| 89 |
+
|
| 90 |
+
current_block_reach_ = {
|
| 91 |
+
alloc<IntImm>(1), alloc<IntImm>(1), alloc<IntImm>(1)};
|
| 92 |
+
current_thread_reach_ = {
|
| 93 |
+
alloc<IntImm>(1), alloc<IntImm>(1), alloc<IntImm>(1)};
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
StmtPtr mutate(ForPtr v) override;
|
| 97 |
+
StmtPtr mutate(BlockPtr v) override;
|
| 98 |
+
|
| 99 |
+
const std::vector<VarPtr>& gpu_block_vars() const {
|
| 100 |
+
return gpu_block_vars_;
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
const std::vector<VarPtr>& gpu_thread_vars() const {
|
| 104 |
+
return gpu_thread_vars_;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
const std::vector<ExprPtr>& gpu_block_extents() const {
|
| 108 |
+
return cuda_analysis_->gpu_block_extents();
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
const std::vector<ExprPtr>& gpu_thread_extents() const {
|
| 112 |
+
return cuda_analysis_->gpu_thread_extents();
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
private:
|
| 116 |
+
// When processing a block, stores the contents of each sub-segment.
|
| 117 |
+
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
|
| 118 |
+
class Segment {
|
| 119 |
+
public:
|
| 120 |
+
void reset(bool mask) {
|
| 121 |
+
stmts_.clear();
|
| 122 |
+
mask_ = mask;
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
bool empty() const {
|
| 126 |
+
return stmts_.empty();
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
std::vector<StmtPtr>& stmts() {
|
| 130 |
+
return stmts_;
|
| 131 |
+
}
|
| 132 |
+
bool mask() {
|
| 133 |
+
return mask_;
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
private:
|
| 137 |
+
std::vector<StmtPtr> stmts_;
|
| 138 |
+
bool mask_{true};
|
| 139 |
+
};
|
| 140 |
+
|
| 141 |
+
// Returns true if the current execution scope is equivalent to the launch
|
| 142 |
+
// parameters.
|
| 143 |
+
bool isFullExtent();
|
| 144 |
+
|
| 145 |
+
std::vector<VarPtr> gpu_block_vars_;
|
| 146 |
+
std::vector<VarPtr> gpu_thread_vars_;
|
| 147 |
+
|
| 148 |
+
std::vector<ExprPtr> current_block_reach_;
|
| 149 |
+
std::vector<ExprPtr> current_thread_reach_;
|
| 150 |
+
|
| 151 |
+
const CudaAnalysis* cuda_analysis_;
|
| 152 |
+
};
|
| 153 |
+
|
| 154 |
+
// A class that overrides the underlying IRPrinter to produce Cuda C.
|
| 155 |
+
class CudaPrinter : public IRPrinter {
|
| 156 |
+
public:
|
| 157 |
+
explicit CudaPrinter(
|
| 158 |
+
std::ostream* os,
|
| 159 |
+
const CudaAnalysis* cuda_analysis,
|
| 160 |
+
bool has_random)
|
| 161 |
+
: IRPrinter(*os), cuda_analysis_(cuda_analysis) {
|
| 162 |
+
if (has_random) {
|
| 163 |
+
rand_func_ = alloc<Var>("rand", kHandle);
|
| 164 |
+
}
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
void visit(CastPtr v) override;
|
| 168 |
+
void visit(IntrinsicsPtr v) override;
|
| 169 |
+
void visit(ForPtr v) override;
|
| 170 |
+
|
| 171 |
+
void visit(LoadPtr v) override;
|
| 172 |
+
void visit(StorePtr v) override;
|
| 173 |
+
void visit(AtomicAddPtr v) override;
|
| 174 |
+
void visit(MaxPtr v) override;
|
| 175 |
+
void visit(MinPtr v) override;
|
| 176 |
+
void visit(IfThenElsePtr v) override;
|
| 177 |
+
void visit(BlockPtr v) override;
|
| 178 |
+
void visit(AllocatePtr v) override;
|
| 179 |
+
void visit(FreePtr v) override;
|
| 180 |
+
void visit(LetPtr v) override;
|
| 181 |
+
|
| 182 |
+
void visit(ExternalCallPtr v) override;
|
| 183 |
+
|
| 184 |
+
VarPtr rand_func() const {
|
| 185 |
+
return rand_func_;
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
std::string dtypeToCppString(const Dtype& dtype) override;
|
| 189 |
+
|
| 190 |
+
using IRPrinter::name_manager;
|
| 191 |
+
using IRPrinter::visit;
|
| 192 |
+
|
| 193 |
+
private:
|
| 194 |
+
VarPtr rand_func_;
|
| 195 |
+
const CudaAnalysis* cuda_analysis_;
|
| 196 |
+
|
| 197 |
+
void print_flat_alloc(AllocatePtr alloc);
|
| 198 |
+
};
|
| 199 |
+
|
| 200 |
+
// Construct Cuda C from the buffer and tensor input, and invoke the kernel
|
| 201 |
+
// when real arguments are provided.
|
| 202 |
+
class TORCH_CUDA_CU_API CudaCodeGen : public CodeGen {
|
| 203 |
+
public:
|
| 204 |
+
template <typename... Ts>
|
| 205 |
+
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
|
| 206 |
+
CudaCodeGen(StmtPtr stmt, Ts... ts)
|
| 207 |
+
: CodeGen(
|
| 208 |
+
stmt,
|
| 209 |
+
std::vector<BufferArg>({BufferArg(ts)...}),
|
| 210 |
+
at::Device(at::kCUDA, at::cuda::current_device())) {
|
| 211 |
+
Initialize();
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
|
| 215 |
+
CudaCodeGen(
|
| 216 |
+
StmtPtr stmt,
|
| 217 |
+
const std::vector<BufferArg>& buffer_args,
|
| 218 |
+
at::Device device = at::Device(at::kCUDA, at::cuda::current_device()),
|
| 219 |
+
const std::string& kernel_func_name = "func")
|
| 220 |
+
: CodeGen(stmt, buffer_args, device, kernel_func_name) {
|
| 221 |
+
Initialize();
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
~CudaCodeGen() override;
|
| 225 |
+
|
| 226 |
+
void call(const std::vector<CallArg>& args) override;
|
| 227 |
+
void call_raw(const std::vector<void*>& args) override;
|
| 228 |
+
void call_with_numel(void** args, int64_t numel) override;
|
| 229 |
+
|
| 230 |
+
template <typename... Ts>
|
| 231 |
+
void operator()(const Ts&... ts) {
|
| 232 |
+
call(std::vector<CallArg>({CallArg(ts)...}));
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
at::Tensor empty_strided(
|
| 236 |
+
c10::IntArrayRef size,
|
| 237 |
+
c10::IntArrayRef stride,
|
| 238 |
+
c10::optional<c10::ScalarType> dtype_opt,
|
| 239 |
+
c10::optional<c10::Layout> layout_opt,
|
| 240 |
+
c10::optional<c10::Device> device_opt,
|
| 241 |
+
c10::optional<bool> pin_memory_opt) override;
|
| 242 |
+
|
| 243 |
+
const std::vector<ExprPtr>& gpu_block_extents() const {
|
| 244 |
+
return cuda_analysis_->gpu_block_extents();
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
const std::vector<ExprPtr>& gpu_thread_extents() const {
|
| 248 |
+
return cuda_analysis_->gpu_thread_extents();
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
std::string getCodeText(const std::string& attr = "") override {
|
| 252 |
+
return oss_.str();
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
private:
|
| 256 |
+
void Initialize();
|
| 257 |
+
|
| 258 |
+
void CompileToNVRTC(const std::string& code, const std::string& func_name);
|
| 259 |
+
|
| 260 |
+
UniqueNameManager* name_manager() {
|
| 261 |
+
if (!printer_) {
|
| 262 |
+
throw std::runtime_error("Null IRPrinter is not expected");
|
| 263 |
+
}
|
| 264 |
+
return printer_->name_manager();
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
std::ostream& os() {
|
| 268 |
+
return printer_->os();
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
std::ostringstream oss_;
|
| 272 |
+
std::unique_ptr<CudaPrinter> printer_;
|
| 273 |
+
std::unique_ptr<CudaAnalysis> cuda_analysis_;
|
| 274 |
+
std::unique_ptr<GPUMetaVarRewriter> metavar_rewriter_;
|
| 275 |
+
std::unordered_set<std::string> taken_func_names;
|
| 276 |
+
std::mutex eval_lock_;
|
| 277 |
+
CUfunction function_;
|
| 278 |
+
bool has_random_ = false;
|
| 279 |
+
int thread_block_size_ = -1;
|
| 280 |
+
|
| 281 |
+
std::vector<bool> arg_pos_in_extents_;
|
| 282 |
+
#ifdef TORCH_ENABLE_LLVM
|
| 283 |
+
std::vector<ExprEval<LLVMCodeGen>> block_extents_eval_;
|
| 284 |
+
std::vector<ExprEval<LLVMCodeGen>> thread_extents_eval_;
|
| 285 |
+
#else
|
| 286 |
+
std::vector<ExprEval<SimpleIREvaluator>> block_extents_eval_;
|
| 287 |
+
std::vector<ExprEval<SimpleIREvaluator>> thread_extents_eval_;
|
| 288 |
+
#endif
|
| 289 |
+
|
| 290 |
+
std::string GetUniqueFuncName(const std::string& func_prefix);
|
| 291 |
+
};
|
| 292 |
+
|
| 293 |
+
} // namespace tensorexpr
|
| 294 |
+
} // namespace jit
|
| 295 |
+
} // namespace torch
|
shared/package-files/4b/4b4b84fbd86a6b8114d7493ff064ab950e1b3f1ec82e4ff36abee60aa9869a0c/_location.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DO NOT EDIT! This file was generated by jschema_to_python version 0.0.1.dev29,
|
| 2 |
+
# with extension for dataclasses and type annotation.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import dataclasses
|
| 7 |
+
from typing import List, Optional
|
| 8 |
+
|
| 9 |
+
from torch.onnx._internal.diagnostics.infra.sarif import (
|
| 10 |
+
_location_relationship,
|
| 11 |
+
_logical_location,
|
| 12 |
+
_message,
|
| 13 |
+
_physical_location,
|
| 14 |
+
_property_bag,
|
| 15 |
+
_region,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclasses.dataclass
|
| 20 |
+
class Location(object):
|
| 21 |
+
"""A location within a programming artifact."""
|
| 22 |
+
|
| 23 |
+
annotations: Optional[List[_region.Region]] = dataclasses.field(
|
| 24 |
+
default=None, metadata={"schema_property_name": "annotations"}
|
| 25 |
+
)
|
| 26 |
+
id: int = dataclasses.field(default=-1, metadata={"schema_property_name": "id"})
|
| 27 |
+
logical_locations: Optional[
|
| 28 |
+
List[_logical_location.LogicalLocation]
|
| 29 |
+
] = dataclasses.field(
|
| 30 |
+
default=None, metadata={"schema_property_name": "logicalLocations"}
|
| 31 |
+
)
|
| 32 |
+
message: Optional[_message.Message] = dataclasses.field(
|
| 33 |
+
default=None, metadata={"schema_property_name": "message"}
|
| 34 |
+
)
|
| 35 |
+
physical_location: Optional[
|
| 36 |
+
_physical_location.PhysicalLocation
|
| 37 |
+
] = dataclasses.field(
|
| 38 |
+
default=None, metadata={"schema_property_name": "physicalLocation"}
|
| 39 |
+
)
|
| 40 |
+
properties: Optional[_property_bag.PropertyBag] = dataclasses.field(
|
| 41 |
+
default=None, metadata={"schema_property_name": "properties"}
|
| 42 |
+
)
|
| 43 |
+
relationships: Optional[
|
| 44 |
+
List[_location_relationship.LocationRelationship]
|
| 45 |
+
] = dataclasses.field(
|
| 46 |
+
default=None, metadata={"schema_property_name": "relationships"}
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# flake8: noqa
|
shared/package-files/4b/4b505195f5d20f6e3c38537302e6793bdc3d5ba7ebd8d527d17f3060518c364d/error.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""create errno-specific classes for IO or os calls."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import errno
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
from typing import Callable
|
| 9 |
+
from typing import TYPE_CHECKING
|
| 10 |
+
from typing import TypeVar
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
if TYPE_CHECKING:
|
| 14 |
+
from typing_extensions import ParamSpec
|
| 15 |
+
|
| 16 |
+
P = ParamSpec("P")
|
| 17 |
+
|
| 18 |
+
R = TypeVar("R")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Error(EnvironmentError):
|
| 22 |
+
def __repr__(self) -> str:
|
| 23 |
+
return "{}.{} {!r}: {} ".format(
|
| 24 |
+
self.__class__.__module__,
|
| 25 |
+
self.__class__.__name__,
|
| 26 |
+
self.__class__.__doc__,
|
| 27 |
+
" ".join(map(str, self.args)),
|
| 28 |
+
# repr(self.args)
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
def __str__(self) -> str:
|
| 32 |
+
s = "[{}]: {}".format(
|
| 33 |
+
self.__class__.__doc__,
|
| 34 |
+
" ".join(map(str, self.args)),
|
| 35 |
+
)
|
| 36 |
+
return s
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
_winerrnomap = {
|
| 40 |
+
2: errno.ENOENT,
|
| 41 |
+
3: errno.ENOENT,
|
| 42 |
+
17: errno.EEXIST,
|
| 43 |
+
18: errno.EXDEV,
|
| 44 |
+
13: errno.EBUSY, # empty cd drive, but ENOMEDIUM seems unavailable
|
| 45 |
+
22: errno.ENOTDIR,
|
| 46 |
+
20: errno.ENOTDIR,
|
| 47 |
+
267: errno.ENOTDIR,
|
| 48 |
+
5: errno.EACCES, # anything better?
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class ErrorMaker:
|
| 53 |
+
"""lazily provides Exception classes for each possible POSIX errno
|
| 54 |
+
(as defined per the 'errno' module). All such instances
|
| 55 |
+
subclass EnvironmentError.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
_errno2class: dict[int, type[Error]] = {}
|
| 59 |
+
|
| 60 |
+
def __getattr__(self, name: str) -> type[Error]:
|
| 61 |
+
if name[0] == "_":
|
| 62 |
+
raise AttributeError(name)
|
| 63 |
+
eno = getattr(errno, name)
|
| 64 |
+
cls = self._geterrnoclass(eno)
|
| 65 |
+
setattr(self, name, cls)
|
| 66 |
+
return cls
|
| 67 |
+
|
| 68 |
+
def _geterrnoclass(self, eno: int) -> type[Error]:
|
| 69 |
+
try:
|
| 70 |
+
return self._errno2class[eno]
|
| 71 |
+
except KeyError:
|
| 72 |
+
clsname = errno.errorcode.get(eno, "UnknownErrno%d" % (eno,))
|
| 73 |
+
errorcls = type(
|
| 74 |
+
clsname,
|
| 75 |
+
(Error,),
|
| 76 |
+
{"__module__": "py.error", "__doc__": os.strerror(eno)},
|
| 77 |
+
)
|
| 78 |
+
self._errno2class[eno] = errorcls
|
| 79 |
+
return errorcls
|
| 80 |
+
|
| 81 |
+
def checked_call(
|
| 82 |
+
self, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs
|
| 83 |
+
) -> R:
|
| 84 |
+
"""Call a function and raise an errno-exception if applicable."""
|
| 85 |
+
__tracebackhide__ = True
|
| 86 |
+
try:
|
| 87 |
+
return func(*args, **kwargs)
|
| 88 |
+
except Error:
|
| 89 |
+
raise
|
| 90 |
+
except OSError as value:
|
| 91 |
+
if not hasattr(value, "errno"):
|
| 92 |
+
raise
|
| 93 |
+
errno = value.errno
|
| 94 |
+
if sys.platform == "win32":
|
| 95 |
+
try:
|
| 96 |
+
cls = self._geterrnoclass(_winerrnomap[errno])
|
| 97 |
+
except KeyError:
|
| 98 |
+
raise value
|
| 99 |
+
else:
|
| 100 |
+
# we are not on Windows, or we got a proper OSError
|
| 101 |
+
cls = self._geterrnoclass(errno)
|
| 102 |
+
|
| 103 |
+
raise cls(f"{func.__name__}{args!r}")
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
_error_maker = ErrorMaker()
|
| 107 |
+
checked_call = _error_maker.checked_call
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def __getattr__(attr: str) -> type[Error]:
|
| 111 |
+
return getattr(_error_maker, attr) # type: ignore[no-any-return]
|
shared/package-files/4b/4b53466cc8ba93760059fb11e2007cded9d7402087320a979b2ef86e710758da/test_indexing.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TestSetitemValidation:
|
| 10 |
+
def _check_setitem_invalid(self, arr, invalid):
|
| 11 |
+
msg = f"Invalid value '{invalid!s}' for dtype '{arr.dtype}'"
|
| 12 |
+
msg = re.escape(msg)
|
| 13 |
+
with pytest.raises(TypeError, match=msg):
|
| 14 |
+
arr[0] = invalid
|
| 15 |
+
|
| 16 |
+
with pytest.raises(TypeError, match=msg):
|
| 17 |
+
arr[:] = invalid
|
| 18 |
+
|
| 19 |
+
with pytest.raises(TypeError, match=msg):
|
| 20 |
+
arr[[0]] = invalid
|
| 21 |
+
|
| 22 |
+
# FIXME: don't leave commented-out
|
| 23 |
+
# with pytest.raises(TypeError):
|
| 24 |
+
# arr[[0]] = [invalid]
|
| 25 |
+
|
| 26 |
+
# with pytest.raises(TypeError):
|
| 27 |
+
# arr[[0]] = np.array([invalid], dtype=object)
|
| 28 |
+
|
| 29 |
+
# Series non-coercion, behavior subject to change
|
| 30 |
+
ser = pd.Series(arr)
|
| 31 |
+
with pytest.raises(TypeError, match=msg):
|
| 32 |
+
ser[0] = invalid
|
| 33 |
+
# TODO: so, so many other variants of this...
|
| 34 |
+
|
| 35 |
+
_invalid_scalars = [
|
| 36 |
+
1 + 2j,
|
| 37 |
+
"True",
|
| 38 |
+
"1",
|
| 39 |
+
"1.0",
|
| 40 |
+
pd.NaT,
|
| 41 |
+
np.datetime64("NaT"),
|
| 42 |
+
np.timedelta64("NaT"),
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
@pytest.mark.parametrize(
|
| 46 |
+
"invalid", _invalid_scalars + [1, 1.0, np.int64(1), np.float64(1)]
|
| 47 |
+
)
|
| 48 |
+
def test_setitem_validation_scalar_bool(self, invalid):
|
| 49 |
+
arr = pd.array([True, False, None], dtype="boolean")
|
| 50 |
+
self._check_setitem_invalid(arr, invalid)
|
| 51 |
+
|
| 52 |
+
@pytest.mark.parametrize("invalid", _invalid_scalars + [True, 1.5, np.float64(1.5)])
|
| 53 |
+
def test_setitem_validation_scalar_int(self, invalid, any_int_ea_dtype):
|
| 54 |
+
arr = pd.array([1, 2, None], dtype=any_int_ea_dtype)
|
| 55 |
+
self._check_setitem_invalid(arr, invalid)
|
| 56 |
+
|
| 57 |
+
@pytest.mark.parametrize("invalid", _invalid_scalars + [True])
|
| 58 |
+
def test_setitem_validation_scalar_float(self, invalid, float_ea_dtype):
|
| 59 |
+
arr = pd.array([1, 2, None], dtype=float_ea_dtype)
|
| 60 |
+
self._check_setitem_invalid(arr, invalid)
|
shared/package-files/4b/4b559c391b73696eafd9524ea9caee1872a8afc042fd6218c8ffbeb16d9562e7/aaa-22
ADDED
|
Binary file (1.26 kB). View file
|
|
|
shared/package-files/4b/4b597f52c1cb35ae8ed540d1db2dab52276c7874febd7a659ee50f26be26f61e/lindenmayer.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
""" turtle-example-suite:
|
| 3 |
+
|
| 4 |
+
xtx_lindenmayer_indian.py
|
| 5 |
+
|
| 6 |
+
Each morning women in Tamil Nadu, in southern
|
| 7 |
+
India, place designs, created by using rice
|
| 8 |
+
flour and known as kolam on the thresholds of
|
| 9 |
+
their homes.
|
| 10 |
+
|
| 11 |
+
These can be described by Lindenmayer systems,
|
| 12 |
+
which can easily be implemented with turtle
|
| 13 |
+
graphics and Python.
|
| 14 |
+
|
| 15 |
+
Two examples are shown here:
|
| 16 |
+
(1) the snake kolam
|
| 17 |
+
(2) anklets of Krishna
|
| 18 |
+
|
| 19 |
+
Taken from Marcia Ascher: Mathematics
|
| 20 |
+
Elsewhere, An Exploration of Ideas Across
|
| 21 |
+
Cultures
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
################################
|
| 25 |
+
# Mini Lindenmayer tool
|
| 26 |
+
###############################
|
| 27 |
+
|
| 28 |
+
from turtle import *
|
| 29 |
+
|
| 30 |
+
def replace( seq, replacementRules, n ):
|
| 31 |
+
for i in range(n):
|
| 32 |
+
newseq = ""
|
| 33 |
+
for element in seq:
|
| 34 |
+
newseq = newseq + replacementRules.get(element,element)
|
| 35 |
+
seq = newseq
|
| 36 |
+
return seq
|
| 37 |
+
|
| 38 |
+
def draw( commands, rules ):
|
| 39 |
+
for b in commands:
|
| 40 |
+
try:
|
| 41 |
+
rules[b]()
|
| 42 |
+
except TypeError:
|
| 43 |
+
try:
|
| 44 |
+
draw(rules[b], rules)
|
| 45 |
+
except:
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def main():
|
| 50 |
+
################################
|
| 51 |
+
# Example 1: Snake kolam
|
| 52 |
+
################################
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def r():
|
| 56 |
+
right(45)
|
| 57 |
+
|
| 58 |
+
def l():
|
| 59 |
+
left(45)
|
| 60 |
+
|
| 61 |
+
def f():
|
| 62 |
+
forward(7.5)
|
| 63 |
+
|
| 64 |
+
snake_rules = {"-":r, "+":l, "f":f, "b":"f+f+f--f--f+f+f"}
|
| 65 |
+
snake_replacementRules = {"b": "b+f+b--f--b+f+b"}
|
| 66 |
+
snake_start = "b--f--b--f"
|
| 67 |
+
|
| 68 |
+
drawing = replace(snake_start, snake_replacementRules, 3)
|
| 69 |
+
|
| 70 |
+
reset()
|
| 71 |
+
speed(3)
|
| 72 |
+
tracer(1,0)
|
| 73 |
+
ht()
|
| 74 |
+
up()
|
| 75 |
+
backward(195)
|
| 76 |
+
down()
|
| 77 |
+
draw(drawing, snake_rules)
|
| 78 |
+
|
| 79 |
+
from time import sleep
|
| 80 |
+
sleep(3)
|
| 81 |
+
|
| 82 |
+
################################
|
| 83 |
+
# Example 2: Anklets of Krishna
|
| 84 |
+
################################
|
| 85 |
+
|
| 86 |
+
def A():
|
| 87 |
+
color("red")
|
| 88 |
+
circle(10,90)
|
| 89 |
+
|
| 90 |
+
def B():
|
| 91 |
+
from math import sqrt
|
| 92 |
+
color("black")
|
| 93 |
+
l = 5/sqrt(2)
|
| 94 |
+
forward(l)
|
| 95 |
+
circle(l, 270)
|
| 96 |
+
forward(l)
|
| 97 |
+
|
| 98 |
+
def F():
|
| 99 |
+
color("green")
|
| 100 |
+
forward(10)
|
| 101 |
+
|
| 102 |
+
krishna_rules = {"a":A, "b":B, "f":F}
|
| 103 |
+
krishna_replacementRules = {"a" : "afbfa", "b" : "afbfbfbfa" }
|
| 104 |
+
krishna_start = "fbfbfbfb"
|
| 105 |
+
|
| 106 |
+
reset()
|
| 107 |
+
speed(0)
|
| 108 |
+
tracer(3,0)
|
| 109 |
+
ht()
|
| 110 |
+
left(45)
|
| 111 |
+
drawing = replace(krishna_start, krishna_replacementRules, 3)
|
| 112 |
+
draw(drawing, krishna_rules)
|
| 113 |
+
tracer(1)
|
| 114 |
+
return "Done!"
|
| 115 |
+
|
| 116 |
+
if __name__=='__main__':
|
| 117 |
+
msg = main()
|
| 118 |
+
print(msg)
|
| 119 |
+
mainloop()
|
shared/package-files/4b/4b5cdce106e003b746944b5c8b1299f16ad3d8e93ceb5cb2fb353c0cbb6f6697/hostkeys.pyi
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
import typing
|
| 3 |
+
from typing import Dict, Iterator, List, Optional
|
| 4 |
+
|
| 5 |
+
from paramiko.pkey import PKey
|
| 6 |
+
|
| 7 |
+
class _SubDict(typing.MutableMapping[str, PKey]):
|
| 8 |
+
# Internal to HostKeys.lookup()
|
| 9 |
+
def __init__(self, hostname: str, entries: List[HostKeyEntry], hostkeys: HostKeys) -> None: ...
|
| 10 |
+
def __iter__(self) -> Iterator[str]: ...
|
| 11 |
+
def __len__(self) -> int: ...
|
| 12 |
+
def __delitem__(self, key: str) -> None: ...
|
| 13 |
+
def __getitem__(self, key: str) -> PKey: ...
|
| 14 |
+
def __setitem__(self, key: str, val: PKey) -> None: ...
|
| 15 |
+
def keys(self) -> List[str]: ... # type: ignore
|
| 16 |
+
|
| 17 |
+
class HostKeys(collections.MutableMapping):
|
| 18 |
+
def __init__(self, filename: Optional[str] = ...) -> None: ...
|
| 19 |
+
def add(self, hostname: str, keytype: str, key: PKey) -> None: ...
|
| 20 |
+
def load(self, filename: str) -> None: ...
|
| 21 |
+
def save(self, filename: str) -> None: ...
|
| 22 |
+
def lookup(self, hostname: str) -> Optional[_SubDict]: ...
|
| 23 |
+
def check(self, hostname: str, key: PKey) -> bool: ...
|
| 24 |
+
def clear(self) -> None: ...
|
| 25 |
+
def __iter__(self) -> Iterator[str]: ...
|
| 26 |
+
def __len__(self) -> int: ...
|
| 27 |
+
def __getitem__(self, key: str) -> _SubDict: ...
|
| 28 |
+
def __delitem__(self, key: str) -> None: ...
|
| 29 |
+
def __setitem__(self, hostname: str, entry: Dict[str, PKey]) -> None: ...
|
| 30 |
+
def keys(self) -> List[str]: ... # type: ignore
|
| 31 |
+
def values(self) -> List[_SubDict]: ... # type: ignore
|
| 32 |
+
@staticmethod
|
| 33 |
+
def hash_host(hostname: str, salt: Optional[str] = ...) -> str: ...
|
| 34 |
+
|
| 35 |
+
class InvalidHostKey(Exception):
|
| 36 |
+
line: str
|
| 37 |
+
exc: Exception
|
| 38 |
+
def __init__(self, line: str, exc: Exception) -> None: ...
|
| 39 |
+
|
| 40 |
+
class HostKeyEntry:
|
| 41 |
+
valid: bool
|
| 42 |
+
hostnames: str
|
| 43 |
+
key: PKey
|
| 44 |
+
def __init__(self, hostnames: Optional[List[str]] = ..., key: Optional[PKey] = ...) -> None: ...
|
| 45 |
+
@classmethod
|
| 46 |
+
def from_line(cls, line: str, lineno: Optional[int] = ...) -> Optional[HostKeyEntry]: ...
|
| 47 |
+
def to_line(self) -> Optional[str]: ...
|
shared/package-files/4b/4b6228391845937f451053a54855ad815c9b4623fa87b0652e574755c94d914f/latin1prober.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
######################## BEGIN LICENSE BLOCK ########################
|
| 2 |
+
# The Original Code is Mozilla Universal charset detector code.
|
| 3 |
+
#
|
| 4 |
+
# The Initial Developer of the Original Code is
|
| 5 |
+
# Netscape Communications Corporation.
|
| 6 |
+
# Portions created by the Initial Developer are Copyright (C) 2001
|
| 7 |
+
# the Initial Developer. All Rights Reserved.
|
| 8 |
+
#
|
| 9 |
+
# Contributor(s):
|
| 10 |
+
# Mark Pilgrim - port to Python
|
| 11 |
+
# Shy Shalom - original C code
|
| 12 |
+
#
|
| 13 |
+
# This library is free software; you can redistribute it and/or
|
| 14 |
+
# modify it under the terms of the GNU Lesser General Public
|
| 15 |
+
# License as published by the Free Software Foundation; either
|
| 16 |
+
# version 2.1 of the License, or (at your option) any later version.
|
| 17 |
+
#
|
| 18 |
+
# This library is distributed in the hope that it will be useful,
|
| 19 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 20 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
| 21 |
+
# Lesser General Public License for more details.
|
| 22 |
+
#
|
| 23 |
+
# You should have received a copy of the GNU Lesser General Public
|
| 24 |
+
# License along with this library; if not, write to the Free Software
|
| 25 |
+
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
| 26 |
+
# 02110-1301 USA
|
| 27 |
+
######################### END LICENSE BLOCK #########################
|
| 28 |
+
|
| 29 |
+
from .charsetprober import CharSetProber
|
| 30 |
+
from .enums import ProbingState
|
| 31 |
+
|
| 32 |
+
FREQ_CAT_NUM = 4
|
| 33 |
+
|
| 34 |
+
UDF = 0 # undefined
|
| 35 |
+
OTH = 1 # other
|
| 36 |
+
ASC = 2 # ascii capital letter
|
| 37 |
+
ASS = 3 # ascii small letter
|
| 38 |
+
ACV = 4 # accent capital vowel
|
| 39 |
+
ACO = 5 # accent capital other
|
| 40 |
+
ASV = 6 # accent small vowel
|
| 41 |
+
ASO = 7 # accent small other
|
| 42 |
+
CLASS_NUM = 8 # total classes
|
| 43 |
+
|
| 44 |
+
Latin1_CharToClass = (
|
| 45 |
+
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 00 - 07
|
| 46 |
+
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 08 - 0F
|
| 47 |
+
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 10 - 17
|
| 48 |
+
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 18 - 1F
|
| 49 |
+
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 20 - 27
|
| 50 |
+
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 28 - 2F
|
| 51 |
+
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 30 - 37
|
| 52 |
+
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 38 - 3F
|
| 53 |
+
OTH, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 40 - 47
|
| 54 |
+
ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 48 - 4F
|
| 55 |
+
ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 50 - 57
|
| 56 |
+
ASC, ASC, ASC, OTH, OTH, OTH, OTH, OTH, # 58 - 5F
|
| 57 |
+
OTH, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 60 - 67
|
| 58 |
+
ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 68 - 6F
|
| 59 |
+
ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 70 - 77
|
| 60 |
+
ASS, ASS, ASS, OTH, OTH, OTH, OTH, OTH, # 78 - 7F
|
| 61 |
+
OTH, UDF, OTH, ASO, OTH, OTH, OTH, OTH, # 80 - 87
|
| 62 |
+
OTH, OTH, ACO, OTH, ACO, UDF, ACO, UDF, # 88 - 8F
|
| 63 |
+
UDF, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 90 - 97
|
| 64 |
+
OTH, OTH, ASO, OTH, ASO, UDF, ASO, ACO, # 98 - 9F
|
| 65 |
+
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A0 - A7
|
| 66 |
+
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A8 - AF
|
| 67 |
+
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B0 - B7
|
| 68 |
+
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B8 - BF
|
| 69 |
+
ACV, ACV, ACV, ACV, ACV, ACV, ACO, ACO, # C0 - C7
|
| 70 |
+
ACV, ACV, ACV, ACV, ACV, ACV, ACV, ACV, # C8 - CF
|
| 71 |
+
ACO, ACO, ACV, ACV, ACV, ACV, ACV, OTH, # D0 - D7
|
| 72 |
+
ACV, ACV, ACV, ACV, ACV, ACO, ACO, ACO, # D8 - DF
|
| 73 |
+
ASV, ASV, ASV, ASV, ASV, ASV, ASO, ASO, # E0 - E7
|
| 74 |
+
ASV, ASV, ASV, ASV, ASV, ASV, ASV, ASV, # E8 - EF
|
| 75 |
+
ASO, ASO, ASV, ASV, ASV, ASV, ASV, OTH, # F0 - F7
|
| 76 |
+
ASV, ASV, ASV, ASV, ASV, ASO, ASO, ASO, # F8 - FF
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# 0 : illegal
|
| 80 |
+
# 1 : very unlikely
|
| 81 |
+
# 2 : normal
|
| 82 |
+
# 3 : very likely
|
| 83 |
+
Latin1ClassModel = (
|
| 84 |
+
# UDF OTH ASC ASS ACV ACO ASV ASO
|
| 85 |
+
0, 0, 0, 0, 0, 0, 0, 0, # UDF
|
| 86 |
+
0, 3, 3, 3, 3, 3, 3, 3, # OTH
|
| 87 |
+
0, 3, 3, 3, 3, 3, 3, 3, # ASC
|
| 88 |
+
0, 3, 3, 3, 1, 1, 3, 3, # ASS
|
| 89 |
+
0, 3, 3, 3, 1, 2, 1, 2, # ACV
|
| 90 |
+
0, 3, 3, 3, 3, 3, 3, 3, # ACO
|
| 91 |
+
0, 3, 1, 3, 1, 1, 1, 3, # ASV
|
| 92 |
+
0, 3, 1, 3, 1, 1, 3, 3, # ASO
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class Latin1Prober(CharSetProber):
|
| 97 |
+
def __init__(self):
|
| 98 |
+
super(Latin1Prober, self).__init__()
|
| 99 |
+
self._last_char_class = None
|
| 100 |
+
self._freq_counter = None
|
| 101 |
+
self.reset()
|
| 102 |
+
|
| 103 |
+
def reset(self):
|
| 104 |
+
self._last_char_class = OTH
|
| 105 |
+
self._freq_counter = [0] * FREQ_CAT_NUM
|
| 106 |
+
CharSetProber.reset(self)
|
| 107 |
+
|
| 108 |
+
@property
|
| 109 |
+
def charset_name(self):
|
| 110 |
+
return "ISO-8859-1"
|
| 111 |
+
|
| 112 |
+
@property
|
| 113 |
+
def language(self):
|
| 114 |
+
return ""
|
| 115 |
+
|
| 116 |
+
def feed(self, byte_str):
|
| 117 |
+
byte_str = self.filter_with_english_letters(byte_str)
|
| 118 |
+
for c in byte_str:
|
| 119 |
+
char_class = Latin1_CharToClass[c]
|
| 120 |
+
freq = Latin1ClassModel[(self._last_char_class * CLASS_NUM)
|
| 121 |
+
+ char_class]
|
| 122 |
+
if freq == 0:
|
| 123 |
+
self._state = ProbingState.NOT_ME
|
| 124 |
+
break
|
| 125 |
+
self._freq_counter[freq] += 1
|
| 126 |
+
self._last_char_class = char_class
|
| 127 |
+
|
| 128 |
+
return self.state
|
| 129 |
+
|
| 130 |
+
def get_confidence(self):
|
| 131 |
+
if self.state == ProbingState.NOT_ME:
|
| 132 |
+
return 0.01
|
| 133 |
+
|
| 134 |
+
total = sum(self._freq_counter)
|
| 135 |
+
if total < 0.01:
|
| 136 |
+
confidence = 0.0
|
| 137 |
+
else:
|
| 138 |
+
confidence = ((self._freq_counter[3] - self._freq_counter[1] * 20.0)
|
| 139 |
+
/ total)
|
| 140 |
+
if confidence < 0.0:
|
| 141 |
+
confidence = 0.0
|
| 142 |
+
# lower the confidence of latin1 so that other more accurate
|
| 143 |
+
# detector can take priority.
|
| 144 |
+
confidence = confidence * 0.73
|
| 145 |
+
return confidence
|
shared/package-files/4b/4b622a5c23858a4977ff25240ae88e36dd26be6bf15bf39c2b9661956bf7f1c4/base_futures.pyi
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from typing import Any, Callable, List, Sequence, Tuple
|
| 3 |
+
from typing_extensions import Literal
|
| 4 |
+
|
| 5 |
+
if sys.version_info >= (3, 7):
|
| 6 |
+
from contextvars import Context
|
| 7 |
+
|
| 8 |
+
from . import futures
|
| 9 |
+
|
| 10 |
+
_PENDING: Literal["PENDING"] # undocumented
|
| 11 |
+
_CANCELLED: Literal["CANCELLED"] # undocumented
|
| 12 |
+
_FINISHED: Literal["FINISHED"] # undocumented
|
| 13 |
+
|
| 14 |
+
def isfuture(obj: object) -> bool: ...
|
| 15 |
+
|
| 16 |
+
if sys.version_info >= (3, 7):
|
| 17 |
+
def _format_callbacks(cb: Sequence[Tuple[Callable[[futures.Future[Any]], None], Context]]) -> str: ... # undocumented
|
| 18 |
+
|
| 19 |
+
else:
|
| 20 |
+
def _format_callbacks(cb: Sequence[Callable[[futures.Future[Any]], None]]) -> str: ... # undocumented
|
| 21 |
+
|
| 22 |
+
def _future_repr_info(future: futures.Future[Any]) -> List[str]: ... # undocumented
|
shared/package-files/4b/4b6291086e765ed3cd2c4df4535cfd344afe960ec624d0a67b5f729e5e621804/TensorProperties.h
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// See NOTE: [Tensor vs. TensorBase]
|
| 4 |
+
namespace at {
|
| 5 |
+
class TensorBase;
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
namespace at::native {
|
| 9 |
+
|
| 10 |
+
TORCH_API bool cudnn_is_acceptable(const TensorBase& self);
|
| 11 |
+
|
| 12 |
+
} // namespace at::native
|
shared/package-files/4b/4b62cd165422d03b6f5fcce2e8788a24006657841f898f190edbee1faa03fb7f/index_select_backward.h
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/index_select_backward_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::index_select_backward(Tensor grad, SymInt[] self_sizes, int dim, Tensor index) -> Tensor
|
| 26 |
+
inline at::Tensor index_select_backward(const at::Tensor & grad, at::IntArrayRef self_sizes, int64_t dim, const at::Tensor & index) {
|
| 27 |
+
return at::_ops::index_select_backward::call(grad, c10::fromIntArrayRefSlow(self_sizes), dim, index);
|
| 28 |
+
}
|
| 29 |
+
namespace symint {
|
| 30 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
|
| 31 |
+
at::Tensor index_select_backward(const at::Tensor & grad, at::IntArrayRef self_sizes, int64_t dim, const at::Tensor & index) {
|
| 32 |
+
return at::_ops::index_select_backward::call(grad, c10::fromIntArrayRefSlow(self_sizes), dim, index);
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
// aten::index_select_backward(Tensor grad, SymInt[] self_sizes, int dim, Tensor index) -> Tensor
|
| 37 |
+
inline at::Tensor index_select_backward_symint(const at::Tensor & grad, c10::SymIntArrayRef self_sizes, int64_t dim, const at::Tensor & index) {
|
| 38 |
+
return at::_ops::index_select_backward::call(grad, self_sizes, dim, index);
|
| 39 |
+
}
|
| 40 |
+
namespace symint {
|
| 41 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
|
| 42 |
+
at::Tensor index_select_backward(const at::Tensor & grad, c10::SymIntArrayRef self_sizes, int64_t dim, const at::Tensor & index) {
|
| 43 |
+
return at::_ops::index_select_backward::call(grad, self_sizes, dim, index);
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
}
|
shared/package-files/4b/4b63b0ba2c4df0d0a6d4fef0d7152b6eed81f6757e073cfb812bb5ab307fea42/cummax_ops.h
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API cummax {
|
| 18 |
+
using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &, int64_t);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cummax")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cummax(Tensor self, int dim) -> (Tensor values, Tensor indices)")
|
| 24 |
+
static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & self, int64_t dim);
|
| 25 |
+
static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API cummax_out {
|
| 29 |
+
using schema = ::std::tuple<at::Tensor &,at::Tensor &> (const at::Tensor &, int64_t, 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::cummax")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cummax.out(Tensor self, int dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)")
|
| 35 |
+
static ::std::tuple<at::Tensor &,at::Tensor &> call(const at::Tensor & self, int64_t dim, at::Tensor & values, at::Tensor & indices);
|
| 36 |
+
static ::std::tuple<at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, at::Tensor & values, at::Tensor & indices);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
struct TORCH_API cummax_dimname {
|
| 40 |
+
using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &, at::Dimname);
|
| 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::cummax")
|
| 44 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dimname")
|
| 45 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cummax.dimname(Tensor self, Dimname dim) -> (Tensor values, Tensor indices)")
|
| 46 |
+
static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & self, at::Dimname dim);
|
| 47 |
+
static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim);
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
struct TORCH_API cummax_dimname_out {
|
| 51 |
+
using schema = ::std::tuple<at::Tensor &,at::Tensor &> (const at::Tensor &, at::Dimname, at::Tensor &, at::Tensor &);
|
| 52 |
+
using ptr_schema = schema*;
|
| 53 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 54 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cummax")
|
| 55 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dimname_out")
|
| 56 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cummax.dimname_out(Tensor self, Dimname dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)")
|
| 57 |
+
static ::std::tuple<at::Tensor &,at::Tensor &> call(const at::Tensor & self, at::Dimname dim, at::Tensor & values, at::Tensor & indices);
|
| 58 |
+
static ::std::tuple<at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Dimname dim, at::Tensor & values, at::Tensor & indices);
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
}} // namespace at::_ops
|
shared/package-files/4b/4b6c5fb6ffc8dc10a47953000052c232df42bcd8707f5e9e428a3f3fef47c2db/_foreach_erfc_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 _foreach_erfc {
|
| 18 |
+
using schema = ::std::vector<at::Tensor> (at::TensorList);
|
| 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::_foreach_erfc")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_erfc(Tensor[] self) -> Tensor[]")
|
| 24 |
+
static ::std::vector<at::Tensor> call(at::TensorList self);
|
| 25 |
+
static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API _foreach_erfc_ {
|
| 29 |
+
using schema = void (at::TensorList);
|
| 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::_foreach_erfc_")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_erfc_(Tensor(a!)[] self) -> ()")
|
| 35 |
+
static void call(at::TensorList self);
|
| 36 |
+
static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
struct TORCH_API _foreach_erfc_out {
|
| 40 |
+
using schema = void (at::TensorList, at::TensorList);
|
| 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::_foreach_erfc")
|
| 44 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 45 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_erfc.out(Tensor[] self, *, Tensor(a!)[] out) -> ()")
|
| 46 |
+
static void call(at::TensorList self, at::TensorList out);
|
| 47 |
+
static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out);
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
}} // namespace at::_ops
|
shared/package-files/4b/4b6cb7a82b3b00ed4491096d37f398901e0fb1a990a9c22370fbbfd7cd7016a6/stochastic_process_types.py
ADDED
|
@@ -0,0 +1,2382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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4 |
+
Tuple as tTuple, Set as tSet)
|
| 5 |
+
from sympy.concrete.summations import Sum
|
| 6 |
+
from sympy.core.add import Add
|
| 7 |
+
from sympy.core.basic import Basic
|
| 8 |
+
from sympy.core.cache import cacheit
|
| 9 |
+
from sympy.core.containers import Tuple
|
| 10 |
+
from sympy.core.expr import Expr
|
| 11 |
+
from sympy.core.function import (Function, Lambda)
|
| 12 |
+
from sympy.core.mul import Mul
|
| 13 |
+
from sympy.core.numbers import (Integer, Rational, igcd, oo, pi)
|
| 14 |
+
from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
|
| 15 |
+
from sympy.core.singleton import S
|
| 16 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
| 17 |
+
from sympy.functions.combinatorial.factorials import factorial
|
| 18 |
+
from sympy.functions.elementary.exponential import exp
|
| 19 |
+
from sympy.functions.elementary.integers import ceiling
|
| 20 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 21 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 22 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 23 |
+
from sympy.logic.boolalg import (And, Not, Or)
|
| 24 |
+
from sympy.matrices.common import NonSquareMatrixError
|
| 25 |
+
from sympy.matrices.dense import (Matrix, eye, ones, zeros)
|
| 26 |
+
from sympy.matrices.expressions.blockmatrix import BlockMatrix
|
| 27 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
| 28 |
+
from sympy.matrices.expressions.special import Identity
|
| 29 |
+
from sympy.matrices.immutable import ImmutableMatrix
|
| 30 |
+
from sympy.sets.conditionset import ConditionSet
|
| 31 |
+
from sympy.sets.contains import Contains
|
| 32 |
+
from sympy.sets.fancysets import Range
|
| 33 |
+
from sympy.sets.sets import (FiniteSet, Intersection, Interval, Set, Union)
|
| 34 |
+
from sympy.solvers.solveset import linsolve
|
| 35 |
+
from sympy.tensor.indexed import (Indexed, IndexedBase)
|
| 36 |
+
from sympy.core.relational import Relational
|
| 37 |
+
from sympy.logic.boolalg import Boolean
|
| 38 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
| 39 |
+
from sympy.utilities.iterables import strongly_connected_components
|
| 40 |
+
from sympy.stats.joint_rv import JointDistribution
|
| 41 |
+
from sympy.stats.joint_rv_types import JointDistributionHandmade
|
| 42 |
+
from sympy.stats.rv import (RandomIndexedSymbol, random_symbols, RandomSymbol,
|
| 43 |
+
_symbol_converter, _value_check, pspace, given,
|
| 44 |
+
dependent, is_random, sample_iter, Distribution,
|
| 45 |
+
Density)
|
| 46 |
+
from sympy.stats.stochastic_process import StochasticPSpace
|
| 47 |
+
from sympy.stats.symbolic_probability import Probability, Expectation
|
| 48 |
+
from sympy.stats.frv_types import Bernoulli, BernoulliDistribution, FiniteRV
|
| 49 |
+
from sympy.stats.drv_types import Poisson, PoissonDistribution
|
| 50 |
+
from sympy.stats.crv_types import Normal, NormalDistribution, Gamma, GammaDistribution
|
| 51 |
+
from sympy.core.sympify import _sympify, sympify
|
| 52 |
+
|
| 53 |
+
EmptySet = S.EmptySet
|
| 54 |
+
|
| 55 |
+
__all__ = [
|
| 56 |
+
'StochasticProcess',
|
| 57 |
+
'DiscreteTimeStochasticProcess',
|
| 58 |
+
'DiscreteMarkovChain',
|
| 59 |
+
'TransitionMatrixOf',
|
| 60 |
+
'StochasticStateSpaceOf',
|
| 61 |
+
'GeneratorMatrixOf',
|
| 62 |
+
'ContinuousMarkovChain',
|
| 63 |
+
'BernoulliProcess',
|
| 64 |
+
'PoissonProcess',
|
| 65 |
+
'WienerProcess',
|
| 66 |
+
'GammaProcess'
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@is_random.register(Indexed)
|
| 71 |
+
def _(x):
|
| 72 |
+
return is_random(x.base)
|
| 73 |
+
|
| 74 |
+
@is_random.register(RandomIndexedSymbol) # type: ignore
|
| 75 |
+
def _(x):
|
| 76 |
+
return True
|
| 77 |
+
|
| 78 |
+
def _set_converter(itr):
|
| 79 |
+
"""
|
| 80 |
+
Helper function for converting list/tuple/set to Set.
|
| 81 |
+
If parameter is not an instance of list/tuple/set then
|
| 82 |
+
no operation is performed.
|
| 83 |
+
|
| 84 |
+
Returns
|
| 85 |
+
=======
|
| 86 |
+
|
| 87 |
+
Set
|
| 88 |
+
The argument converted to Set.
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
Raises
|
| 92 |
+
======
|
| 93 |
+
|
| 94 |
+
TypeError
|
| 95 |
+
If the argument is not an instance of list/tuple/set.
|
| 96 |
+
"""
|
| 97 |
+
if isinstance(itr, (list, tuple, set)):
|
| 98 |
+
itr = FiniteSet(*itr)
|
| 99 |
+
if not isinstance(itr, Set):
|
| 100 |
+
raise TypeError("%s is not an instance of list/tuple/set."%(itr))
|
| 101 |
+
return itr
|
| 102 |
+
|
| 103 |
+
def _state_converter(itr: tSequence) -> tUnion[Tuple, Range]:
|
| 104 |
+
"""
|
| 105 |
+
Helper function for converting list/tuple/set/Range/Tuple/FiniteSet
|
| 106 |
+
to tuple/Range.
|
| 107 |
+
"""
|
| 108 |
+
itr_ret: tUnion[Tuple, Range]
|
| 109 |
+
|
| 110 |
+
if isinstance(itr, (Tuple, set, FiniteSet)):
|
| 111 |
+
itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr))
|
| 112 |
+
|
| 113 |
+
elif isinstance(itr, (list, tuple)):
|
| 114 |
+
# check if states are unique
|
| 115 |
+
if len(set(itr)) != len(itr):
|
| 116 |
+
raise ValueError('The state space must have unique elements.')
|
| 117 |
+
itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr))
|
| 118 |
+
|
| 119 |
+
elif isinstance(itr, Range):
|
| 120 |
+
# the only ordered set in SymPy I know of
|
| 121 |
+
# try to convert to tuple
|
| 122 |
+
try:
|
| 123 |
+
itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr))
|
| 124 |
+
except (TypeError, ValueError):
|
| 125 |
+
itr_ret = itr
|
| 126 |
+
|
| 127 |
+
else:
|
| 128 |
+
raise TypeError("%s is not an instance of list/tuple/set/Range/Tuple/FiniteSet." % (itr))
|
| 129 |
+
return itr_ret
|
| 130 |
+
|
| 131 |
+
def _sym_sympify(arg):
|
| 132 |
+
"""
|
| 133 |
+
Converts an arbitrary expression to a type that can be used inside SymPy.
|
| 134 |
+
As generally strings are unwise to use in the expressions,
|
| 135 |
+
it returns the Symbol of argument if the string type argument is passed.
|
| 136 |
+
|
| 137 |
+
Parameters
|
| 138 |
+
=========
|
| 139 |
+
|
| 140 |
+
arg: The parameter to be converted to be used in SymPy.
|
| 141 |
+
|
| 142 |
+
Returns
|
| 143 |
+
=======
|
| 144 |
+
|
| 145 |
+
The converted parameter.
|
| 146 |
+
|
| 147 |
+
"""
|
| 148 |
+
if isinstance(arg, str):
|
| 149 |
+
return Symbol(arg)
|
| 150 |
+
else:
|
| 151 |
+
return _sympify(arg)
|
| 152 |
+
|
| 153 |
+
def _matrix_checks(matrix):
|
| 154 |
+
if not isinstance(matrix, (Matrix, MatrixSymbol, ImmutableMatrix)):
|
| 155 |
+
raise TypeError("Transition probabilities either should "
|
| 156 |
+
"be a Matrix or a MatrixSymbol.")
|
| 157 |
+
if matrix.shape[0] != matrix.shape[1]:
|
| 158 |
+
raise NonSquareMatrixError("%s is not a square matrix"%(matrix))
|
| 159 |
+
if isinstance(matrix, Matrix):
|
| 160 |
+
matrix = ImmutableMatrix(matrix.tolist())
|
| 161 |
+
return matrix
|
| 162 |
+
|
| 163 |
+
class StochasticProcess(Basic):
|
| 164 |
+
"""
|
| 165 |
+
Base class for all the stochastic processes whether
|
| 166 |
+
discrete or continuous.
|
| 167 |
+
|
| 168 |
+
Parameters
|
| 169 |
+
==========
|
| 170 |
+
|
| 171 |
+
sym: Symbol or str
|
| 172 |
+
state_space: Set
|
| 173 |
+
The state space of the stochastic process, by default S.Reals.
|
| 174 |
+
For discrete sets it is zero indexed.
|
| 175 |
+
|
| 176 |
+
See Also
|
| 177 |
+
========
|
| 178 |
+
|
| 179 |
+
DiscreteTimeStochasticProcess
|
| 180 |
+
"""
|
| 181 |
+
|
| 182 |
+
index_set = S.Reals
|
| 183 |
+
|
| 184 |
+
def __new__(cls, sym, state_space=S.Reals, **kwargs):
|
| 185 |
+
sym = _symbol_converter(sym)
|
| 186 |
+
state_space = _set_converter(state_space)
|
| 187 |
+
return Basic.__new__(cls, sym, state_space)
|
| 188 |
+
|
| 189 |
+
@property
|
| 190 |
+
def symbol(self):
|
| 191 |
+
return self.args[0]
|
| 192 |
+
|
| 193 |
+
@property
|
| 194 |
+
def state_space(self) -> tUnion[FiniteSet, Range]:
|
| 195 |
+
if not isinstance(self.args[1], (FiniteSet, Range)):
|
| 196 |
+
assert isinstance(self.args[1], Tuple)
|
| 197 |
+
return FiniteSet(*self.args[1])
|
| 198 |
+
return self.args[1]
|
| 199 |
+
|
| 200 |
+
def _deprecation_warn_distribution(self):
|
| 201 |
+
sympy_deprecation_warning(
|
| 202 |
+
"""
|
| 203 |
+
Calling the distribution method with a RandomIndexedSymbol
|
| 204 |
+
argument, like X.distribution(X(t)) is deprecated. Instead, call
|
| 205 |
+
distribution() with the given timestamp, like
|
| 206 |
+
|
| 207 |
+
X.distribution(t)
|
| 208 |
+
""",
|
| 209 |
+
deprecated_since_version="1.7.1",
|
| 210 |
+
active_deprecations_target="deprecated-distribution-randomindexedsymbol",
|
| 211 |
+
stacklevel=4,
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
def distribution(self, key=None):
|
| 215 |
+
if key is None:
|
| 216 |
+
self._deprecation_warn_distribution()
|
| 217 |
+
return Distribution()
|
| 218 |
+
|
| 219 |
+
def density(self, x):
|
| 220 |
+
return Density()
|
| 221 |
+
|
| 222 |
+
def __call__(self, time):
|
| 223 |
+
"""
|
| 224 |
+
Overridden in ContinuousTimeStochasticProcess.
|
| 225 |
+
"""
|
| 226 |
+
raise NotImplementedError("Use [] for indexing discrete time stochastic process.")
|
| 227 |
+
|
| 228 |
+
def __getitem__(self, time):
|
| 229 |
+
"""
|
| 230 |
+
Overridden in DiscreteTimeStochasticProcess.
|
| 231 |
+
"""
|
| 232 |
+
raise NotImplementedError("Use () for indexing continuous time stochastic process.")
|
| 233 |
+
|
| 234 |
+
def probability(self, condition):
|
| 235 |
+
raise NotImplementedError()
|
| 236 |
+
|
| 237 |
+
def joint_distribution(self, *args):
|
| 238 |
+
"""
|
| 239 |
+
Computes the joint distribution of the random indexed variables.
|
| 240 |
+
|
| 241 |
+
Parameters
|
| 242 |
+
==========
|
| 243 |
+
|
| 244 |
+
args: iterable
|
| 245 |
+
The finite list of random indexed variables/the key of a stochastic
|
| 246 |
+
process whose joint distribution has to be computed.
|
| 247 |
+
|
| 248 |
+
Returns
|
| 249 |
+
=======
|
| 250 |
+
|
| 251 |
+
JointDistribution
|
| 252 |
+
The joint distribution of the list of random indexed variables.
|
| 253 |
+
An unevaluated object is returned if it is not possible to
|
| 254 |
+
compute the joint distribution.
|
| 255 |
+
|
| 256 |
+
Raises
|
| 257 |
+
======
|
| 258 |
+
|
| 259 |
+
ValueError: When the arguments passed are not of type RandomIndexSymbol
|
| 260 |
+
or Number.
|
| 261 |
+
"""
|
| 262 |
+
args = list(args)
|
| 263 |
+
for i, arg in enumerate(args):
|
| 264 |
+
if S(arg).is_Number:
|
| 265 |
+
if self.index_set.is_subset(S.Integers):
|
| 266 |
+
args[i] = self.__getitem__(arg)
|
| 267 |
+
else:
|
| 268 |
+
args[i] = self.__call__(arg)
|
| 269 |
+
elif not isinstance(arg, RandomIndexedSymbol):
|
| 270 |
+
raise ValueError("Expected a RandomIndexedSymbol or "
|
| 271 |
+
"key not %s"%(type(arg)))
|
| 272 |
+
|
| 273 |
+
if args[0].pspace.distribution == Distribution():
|
| 274 |
+
return JointDistribution(*args)
|
| 275 |
+
density = Lambda(tuple(args),
|
| 276 |
+
expr=Mul.fromiter(arg.pspace.process.density(arg) for arg in args))
|
| 277 |
+
return JointDistributionHandmade(density)
|
| 278 |
+
|
| 279 |
+
def expectation(self, condition, given_condition):
|
| 280 |
+
raise NotImplementedError("Abstract method for expectation queries.")
|
| 281 |
+
|
| 282 |
+
def sample(self):
|
| 283 |
+
raise NotImplementedError("Abstract method for sampling queries.")
|
| 284 |
+
|
| 285 |
+
class DiscreteTimeStochasticProcess(StochasticProcess):
|
| 286 |
+
"""
|
| 287 |
+
Base class for all discrete stochastic processes.
|
| 288 |
+
"""
|
| 289 |
+
def __getitem__(self, time):
|
| 290 |
+
"""
|
| 291 |
+
For indexing discrete time stochastic processes.
|
| 292 |
+
|
| 293 |
+
Returns
|
| 294 |
+
=======
|
| 295 |
+
|
| 296 |
+
RandomIndexedSymbol
|
| 297 |
+
"""
|
| 298 |
+
time = sympify(time)
|
| 299 |
+
if not time.is_symbol and time not in self.index_set:
|
| 300 |
+
raise IndexError("%s is not in the index set of %s"%(time, self.symbol))
|
| 301 |
+
idx_obj = Indexed(self.symbol, time)
|
| 302 |
+
pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time))
|
| 303 |
+
return RandomIndexedSymbol(idx_obj, pspace_obj)
|
| 304 |
+
|
| 305 |
+
class ContinuousTimeStochasticProcess(StochasticProcess):
|
| 306 |
+
"""
|
| 307 |
+
Base class for all continuous time stochastic process.
|
| 308 |
+
"""
|
| 309 |
+
def __call__(self, time):
|
| 310 |
+
"""
|
| 311 |
+
For indexing continuous time stochastic processes.
|
| 312 |
+
|
| 313 |
+
Returns
|
| 314 |
+
=======
|
| 315 |
+
|
| 316 |
+
RandomIndexedSymbol
|
| 317 |
+
"""
|
| 318 |
+
time = sympify(time)
|
| 319 |
+
if not time.is_symbol and time not in self.index_set:
|
| 320 |
+
raise IndexError("%s is not in the index set of %s"%(time, self.symbol))
|
| 321 |
+
func_obj = Function(self.symbol)(time)
|
| 322 |
+
pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time))
|
| 323 |
+
return RandomIndexedSymbol(func_obj, pspace_obj)
|
| 324 |
+
|
| 325 |
+
class TransitionMatrixOf(Boolean):
|
| 326 |
+
"""
|
| 327 |
+
Assumes that the matrix is the transition matrix
|
| 328 |
+
of the process.
|
| 329 |
+
"""
|
| 330 |
+
|
| 331 |
+
def __new__(cls, process, matrix):
|
| 332 |
+
if not isinstance(process, DiscreteMarkovChain):
|
| 333 |
+
raise ValueError("Currently only DiscreteMarkovChain "
|
| 334 |
+
"support TransitionMatrixOf.")
|
| 335 |
+
matrix = _matrix_checks(matrix)
|
| 336 |
+
return Basic.__new__(cls, process, matrix)
|
| 337 |
+
|
| 338 |
+
process = property(lambda self: self.args[0])
|
| 339 |
+
matrix = property(lambda self: self.args[1])
|
| 340 |
+
|
| 341 |
+
class GeneratorMatrixOf(TransitionMatrixOf):
|
| 342 |
+
"""
|
| 343 |
+
Assumes that the matrix is the generator matrix
|
| 344 |
+
of the process.
|
| 345 |
+
"""
|
| 346 |
+
|
| 347 |
+
def __new__(cls, process, matrix):
|
| 348 |
+
if not isinstance(process, ContinuousMarkovChain):
|
| 349 |
+
raise ValueError("Currently only ContinuousMarkovChain "
|
| 350 |
+
"support GeneratorMatrixOf.")
|
| 351 |
+
matrix = _matrix_checks(matrix)
|
| 352 |
+
return Basic.__new__(cls, process, matrix)
|
| 353 |
+
|
| 354 |
+
class StochasticStateSpaceOf(Boolean):
|
| 355 |
+
|
| 356 |
+
def __new__(cls, process, state_space):
|
| 357 |
+
if not isinstance(process, (DiscreteMarkovChain, ContinuousMarkovChain)):
|
| 358 |
+
raise ValueError("Currently only DiscreteMarkovChain and ContinuousMarkovChain "
|
| 359 |
+
"support StochasticStateSpaceOf.")
|
| 360 |
+
state_space = _state_converter(state_space)
|
| 361 |
+
if isinstance(state_space, Range):
|
| 362 |
+
ss_size = ceiling((state_space.stop - state_space.start) / state_space.step)
|
| 363 |
+
else:
|
| 364 |
+
ss_size = len(state_space)
|
| 365 |
+
state_index = Range(ss_size)
|
| 366 |
+
return Basic.__new__(cls, process, state_index)
|
| 367 |
+
|
| 368 |
+
process = property(lambda self: self.args[0])
|
| 369 |
+
state_index = property(lambda self: self.args[1])
|
| 370 |
+
|
| 371 |
+
class MarkovProcess(StochasticProcess):
|
| 372 |
+
"""
|
| 373 |
+
Contains methods that handle queries
|
| 374 |
+
common to Markov processes.
|
| 375 |
+
"""
|
| 376 |
+
|
| 377 |
+
@property
|
| 378 |
+
def number_of_states(self) -> tUnion[Integer, Symbol]:
|
| 379 |
+
"""
|
| 380 |
+
The number of states in the Markov Chain.
|
| 381 |
+
"""
|
| 382 |
+
return _sympify(self.args[2].shape[0]) # type: ignore
|
| 383 |
+
|
| 384 |
+
@property
|
| 385 |
+
def _state_index(self):
|
| 386 |
+
"""
|
| 387 |
+
Returns state index as Range.
|
| 388 |
+
"""
|
| 389 |
+
return self.args[1]
|
| 390 |
+
|
| 391 |
+
@classmethod
|
| 392 |
+
def _sanity_checks(cls, state_space, trans_probs):
|
| 393 |
+
# Try to never have None as state_space or trans_probs.
|
| 394 |
+
# This helps a lot if we get it done at the start.
|
| 395 |
+
if (state_space is None) and (trans_probs is None):
|
| 396 |
+
_n = Dummy('n', integer=True, nonnegative=True)
|
| 397 |
+
state_space = _state_converter(Range(_n))
|
| 398 |
+
trans_probs = _matrix_checks(MatrixSymbol('_T', _n, _n))
|
| 399 |
+
|
| 400 |
+
elif state_space is None:
|
| 401 |
+
trans_probs = _matrix_checks(trans_probs)
|
| 402 |
+
state_space = _state_converter(Range(trans_probs.shape[0]))
|
| 403 |
+
|
| 404 |
+
elif trans_probs is None:
|
| 405 |
+
state_space = _state_converter(state_space)
|
| 406 |
+
if isinstance(state_space, Range):
|
| 407 |
+
_n = ceiling((state_space.stop - state_space.start) / state_space.step)
|
| 408 |
+
else:
|
| 409 |
+
_n = len(state_space)
|
| 410 |
+
trans_probs = MatrixSymbol('_T', _n, _n)
|
| 411 |
+
|
| 412 |
+
else:
|
| 413 |
+
state_space = _state_converter(state_space)
|
| 414 |
+
trans_probs = _matrix_checks(trans_probs)
|
| 415 |
+
# Range object doesn't want to give a symbolic size
|
| 416 |
+
# so we do it ourselves.
|
| 417 |
+
if isinstance(state_space, Range):
|
| 418 |
+
ss_size = ceiling((state_space.stop - state_space.start) / state_space.step)
|
| 419 |
+
else:
|
| 420 |
+
ss_size = len(state_space)
|
| 421 |
+
if ss_size != trans_probs.shape[0]:
|
| 422 |
+
raise ValueError('The size of the state space and the number of '
|
| 423 |
+
'rows of the transition matrix must be the same.')
|
| 424 |
+
|
| 425 |
+
return state_space, trans_probs
|
| 426 |
+
|
| 427 |
+
def _extract_information(self, given_condition):
|
| 428 |
+
"""
|
| 429 |
+
Helper function to extract information, like,
|
| 430 |
+
transition matrix/generator matrix, state space, etc.
|
| 431 |
+
"""
|
| 432 |
+
if isinstance(self, DiscreteMarkovChain):
|
| 433 |
+
trans_probs = self.transition_probabilities
|
| 434 |
+
state_index = self._state_index
|
| 435 |
+
elif isinstance(self, ContinuousMarkovChain):
|
| 436 |
+
trans_probs = self.generator_matrix
|
| 437 |
+
state_index = self._state_index
|
| 438 |
+
if isinstance(given_condition, And):
|
| 439 |
+
gcs = given_condition.args
|
| 440 |
+
given_condition = S.true
|
| 441 |
+
for gc in gcs:
|
| 442 |
+
if isinstance(gc, TransitionMatrixOf):
|
| 443 |
+
trans_probs = gc.matrix
|
| 444 |
+
if isinstance(gc, StochasticStateSpaceOf):
|
| 445 |
+
state_index = gc.state_index
|
| 446 |
+
if isinstance(gc, Relational):
|
| 447 |
+
given_condition = given_condition & gc
|
| 448 |
+
if isinstance(given_condition, TransitionMatrixOf):
|
| 449 |
+
trans_probs = given_condition.matrix
|
| 450 |
+
given_condition = S.true
|
| 451 |
+
if isinstance(given_condition, StochasticStateSpaceOf):
|
| 452 |
+
state_index = given_condition.state_index
|
| 453 |
+
given_condition = S.true
|
| 454 |
+
return trans_probs, state_index, given_condition
|
| 455 |
+
|
| 456 |
+
def _check_trans_probs(self, trans_probs, row_sum=1):
|
| 457 |
+
"""
|
| 458 |
+
Helper function for checking the validity of transition
|
| 459 |
+
probabilities.
|
| 460 |
+
"""
|
| 461 |
+
if not isinstance(trans_probs, MatrixSymbol):
|
| 462 |
+
rows = trans_probs.tolist()
|
| 463 |
+
for row in rows:
|
| 464 |
+
if (sum(row) - row_sum) != 0:
|
| 465 |
+
raise ValueError("Values in a row must sum to %s. "
|
| 466 |
+
"If you are using Float or floats then please use Rational."%(row_sum))
|
| 467 |
+
|
| 468 |
+
def _work_out_state_index(self, state_index, given_condition, trans_probs):
|
| 469 |
+
"""
|
| 470 |
+
Helper function to extract state space if there
|
| 471 |
+
is a random symbol in the given condition.
|
| 472 |
+
"""
|
| 473 |
+
# if given condition is None, then there is no need to work out
|
| 474 |
+
# state_space from random variables
|
| 475 |
+
if given_condition != None:
|
| 476 |
+
rand_var = list(given_condition.atoms(RandomSymbol) -
|
| 477 |
+
given_condition.atoms(RandomIndexedSymbol))
|
| 478 |
+
if len(rand_var) == 1:
|
| 479 |
+
state_index = rand_var[0].pspace.set
|
| 480 |
+
|
| 481 |
+
# `not None` is `True`. So the old test fails for symbolic sizes.
|
| 482 |
+
# Need to build the statement differently.
|
| 483 |
+
sym_cond = not self.number_of_states.is_Integer
|
| 484 |
+
cond1 = not sym_cond and len(state_index) != trans_probs.shape[0]
|
| 485 |
+
if cond1:
|
| 486 |
+
raise ValueError("state space is not compatible with the transition probabilities.")
|
| 487 |
+
if not isinstance(trans_probs.shape[0], Symbol):
|
| 488 |
+
state_index = FiniteSet(*range(trans_probs.shape[0]))
|
| 489 |
+
return state_index
|
| 490 |
+
|
| 491 |
+
@cacheit
|
| 492 |
+
def _preprocess(self, given_condition, evaluate):
|
| 493 |
+
"""
|
| 494 |
+
Helper function for pre-processing the information.
|
| 495 |
+
"""
|
| 496 |
+
is_insufficient = False
|
| 497 |
+
|
| 498 |
+
if not evaluate: # avoid pre-processing if the result is not to be evaluated
|
| 499 |
+
return (True, None, None, None)
|
| 500 |
+
|
| 501 |
+
# extracting transition matrix and state space
|
| 502 |
+
trans_probs, state_index, given_condition = self._extract_information(given_condition)
|
| 503 |
+
|
| 504 |
+
# given_condition does not have sufficient information
|
| 505 |
+
# for computations
|
| 506 |
+
if trans_probs is None or \
|
| 507 |
+
given_condition is None:
|
| 508 |
+
is_insufficient = True
|
| 509 |
+
else:
|
| 510 |
+
# checking transition probabilities
|
| 511 |
+
if isinstance(self, DiscreteMarkovChain):
|
| 512 |
+
self._check_trans_probs(trans_probs, row_sum=1)
|
| 513 |
+
elif isinstance(self, ContinuousMarkovChain):
|
| 514 |
+
self._check_trans_probs(trans_probs, row_sum=0)
|
| 515 |
+
|
| 516 |
+
# working out state space
|
| 517 |
+
state_index = self._work_out_state_index(state_index, given_condition, trans_probs)
|
| 518 |
+
|
| 519 |
+
return is_insufficient, trans_probs, state_index, given_condition
|
| 520 |
+
|
| 521 |
+
def replace_with_index(self, condition):
|
| 522 |
+
if isinstance(condition, Relational):
|
| 523 |
+
lhs, rhs = condition.lhs, condition.rhs
|
| 524 |
+
if not isinstance(lhs, RandomIndexedSymbol):
|
| 525 |
+
lhs, rhs = rhs, lhs
|
| 526 |
+
condition = type(condition)(self.index_of.get(lhs, lhs),
|
| 527 |
+
self.index_of.get(rhs, rhs))
|
| 528 |
+
return condition
|
| 529 |
+
|
| 530 |
+
def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
|
| 531 |
+
"""
|
| 532 |
+
Handles probability queries for Markov process.
|
| 533 |
+
|
| 534 |
+
Parameters
|
| 535 |
+
==========
|
| 536 |
+
|
| 537 |
+
condition: Relational
|
| 538 |
+
given_condition: Relational/And
|
| 539 |
+
|
| 540 |
+
Returns
|
| 541 |
+
=======
|
| 542 |
+
Probability
|
| 543 |
+
If the information is not sufficient.
|
| 544 |
+
Expr
|
| 545 |
+
In all other cases.
|
| 546 |
+
|
| 547 |
+
Note
|
| 548 |
+
====
|
| 549 |
+
Any information passed at the time of query overrides
|
| 550 |
+
any information passed at the time of object creation like
|
| 551 |
+
transition probabilities, state space.
|
| 552 |
+
Pass the transition matrix using TransitionMatrixOf,
|
| 553 |
+
generator matrix using GeneratorMatrixOf and state space
|
| 554 |
+
using StochasticStateSpaceOf in given_condition using & or And.
|
| 555 |
+
"""
|
| 556 |
+
check, mat, state_index, new_given_condition = \
|
| 557 |
+
self._preprocess(given_condition, evaluate)
|
| 558 |
+
|
| 559 |
+
rv = list(condition.atoms(RandomIndexedSymbol))
|
| 560 |
+
symbolic = False
|
| 561 |
+
for sym in rv:
|
| 562 |
+
if sym.key.is_symbol:
|
| 563 |
+
symbolic = True
|
| 564 |
+
break
|
| 565 |
+
|
| 566 |
+
if check:
|
| 567 |
+
return Probability(condition, new_given_condition)
|
| 568 |
+
|
| 569 |
+
if isinstance(self, ContinuousMarkovChain):
|
| 570 |
+
trans_probs = self.transition_probabilities(mat)
|
| 571 |
+
elif isinstance(self, DiscreteMarkovChain):
|
| 572 |
+
trans_probs = mat
|
| 573 |
+
condition = self.replace_with_index(condition)
|
| 574 |
+
given_condition = self.replace_with_index(given_condition)
|
| 575 |
+
new_given_condition = self.replace_with_index(new_given_condition)
|
| 576 |
+
|
| 577 |
+
if isinstance(condition, Relational):
|
| 578 |
+
if isinstance(new_given_condition, And):
|
| 579 |
+
gcs = new_given_condition.args
|
| 580 |
+
else:
|
| 581 |
+
gcs = (new_given_condition, )
|
| 582 |
+
min_key_rv = list(new_given_condition.atoms(RandomIndexedSymbol))
|
| 583 |
+
|
| 584 |
+
if len(min_key_rv):
|
| 585 |
+
min_key_rv = min_key_rv[0]
|
| 586 |
+
for r in rv:
|
| 587 |
+
if min_key_rv.key.is_symbol or r.key.is_symbol:
|
| 588 |
+
continue
|
| 589 |
+
if min_key_rv.key > r.key:
|
| 590 |
+
return Probability(condition)
|
| 591 |
+
else:
|
| 592 |
+
min_key_rv = None
|
| 593 |
+
return Probability(condition)
|
| 594 |
+
|
| 595 |
+
if symbolic:
|
| 596 |
+
return self._symbolic_probability(condition, new_given_condition, rv, min_key_rv)
|
| 597 |
+
|
| 598 |
+
if len(rv) > 1:
|
| 599 |
+
rv[0] = condition.lhs
|
| 600 |
+
rv[1] = condition.rhs
|
| 601 |
+
if rv[0].key < rv[1].key:
|
| 602 |
+
rv[0], rv[1] = rv[1], rv[0]
|
| 603 |
+
if isinstance(condition, Gt):
|
| 604 |
+
condition = Lt(condition.lhs, condition.rhs)
|
| 605 |
+
elif isinstance(condition, Lt):
|
| 606 |
+
condition = Gt(condition.lhs, condition.rhs)
|
| 607 |
+
elif isinstance(condition, Ge):
|
| 608 |
+
condition = Le(condition.lhs, condition.rhs)
|
| 609 |
+
elif isinstance(condition, Le):
|
| 610 |
+
condition = Ge(condition.lhs, condition.rhs)
|
| 611 |
+
s = Rational(0, 1)
|
| 612 |
+
n = len(self.state_space)
|
| 613 |
+
|
| 614 |
+
if isinstance(condition, (Eq, Ne)):
|
| 615 |
+
for i in range(0, n):
|
| 616 |
+
s += self.probability(Eq(rv[0], i), Eq(rv[1], i)) * self.probability(Eq(rv[1], i), new_given_condition)
|
| 617 |
+
return s if isinstance(condition, Eq) else 1 - s
|
| 618 |
+
else:
|
| 619 |
+
upper = 0
|
| 620 |
+
greater = False
|
| 621 |
+
if isinstance(condition, (Ge, Lt)):
|
| 622 |
+
upper = 1
|
| 623 |
+
if isinstance(condition, (Ge, Gt)):
|
| 624 |
+
greater = True
|
| 625 |
+
|
| 626 |
+
for i in range(0, n):
|
| 627 |
+
if i <= n//2:
|
| 628 |
+
for j in range(0, i + upper):
|
| 629 |
+
s += self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition)
|
| 630 |
+
else:
|
| 631 |
+
s += self.probability(Eq(rv[0], i), new_given_condition)
|
| 632 |
+
for j in range(i + upper, n):
|
| 633 |
+
s -= self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition)
|
| 634 |
+
return s if greater else 1 - s
|
| 635 |
+
|
| 636 |
+
rv = rv[0]
|
| 637 |
+
states = condition.as_set()
|
| 638 |
+
prob, gstate = {}, None
|
| 639 |
+
for gc in gcs:
|
| 640 |
+
if gc.has(min_key_rv):
|
| 641 |
+
if gc.has(Probability):
|
| 642 |
+
p, gp = (gc.rhs, gc.lhs) if isinstance(gc.lhs, Probability) \
|
| 643 |
+
else (gc.lhs, gc.rhs)
|
| 644 |
+
gr = gp.args[0]
|
| 645 |
+
gset = Intersection(gr.as_set(), state_index)
|
| 646 |
+
gstate = list(gset)[0]
|
| 647 |
+
prob[gset] = p
|
| 648 |
+
else:
|
| 649 |
+
_, gstate = (gc.lhs.key, gc.rhs) if isinstance(gc.lhs, RandomIndexedSymbol) \
|
| 650 |
+
else (gc.rhs.key, gc.lhs)
|
| 651 |
+
|
| 652 |
+
if not all(k in self.index_set for k in (rv.key, min_key_rv.key)):
|
| 653 |
+
raise IndexError("The timestamps of the process are not in it's index set.")
|
| 654 |
+
states = Intersection(states, state_index) if not isinstance(self.number_of_states, Symbol) else states
|
| 655 |
+
for state in Union(states, FiniteSet(gstate)):
|
| 656 |
+
if not state.is_Integer or Ge(state, mat.shape[0]) is True:
|
| 657 |
+
raise IndexError("No information is available for (%s, %s) in "
|
| 658 |
+
"transition probabilities of shape, (%s, %s). "
|
| 659 |
+
"State space is zero indexed."
|
| 660 |
+
%(gstate, state, mat.shape[0], mat.shape[1]))
|
| 661 |
+
if prob:
|
| 662 |
+
gstates = Union(*prob.keys())
|
| 663 |
+
if len(gstates) == 1:
|
| 664 |
+
gstate = list(gstates)[0]
|
| 665 |
+
gprob = list(prob.values())[0]
|
| 666 |
+
prob[gstates] = gprob
|
| 667 |
+
elif len(gstates) == len(state_index) - 1:
|
| 668 |
+
gstate = list(state_index - gstates)[0]
|
| 669 |
+
gprob = S.One - sum(prob.values())
|
| 670 |
+
prob[state_index - gstates] = gprob
|
| 671 |
+
else:
|
| 672 |
+
raise ValueError("Conflicting information.")
|
| 673 |
+
else:
|
| 674 |
+
gprob = S.One
|
| 675 |
+
|
| 676 |
+
if min_key_rv == rv:
|
| 677 |
+
return sum([prob[FiniteSet(state)] for state in states])
|
| 678 |
+
if isinstance(self, ContinuousMarkovChain):
|
| 679 |
+
return gprob * sum([trans_probs(rv.key - min_key_rv.key).__getitem__((gstate, state))
|
| 680 |
+
for state in states])
|
| 681 |
+
if isinstance(self, DiscreteMarkovChain):
|
| 682 |
+
return gprob * sum([(trans_probs**(rv.key - min_key_rv.key)).__getitem__((gstate, state))
|
| 683 |
+
for state in states])
|
| 684 |
+
|
| 685 |
+
if isinstance(condition, Not):
|
| 686 |
+
expr = condition.args[0]
|
| 687 |
+
return S.One - self.probability(expr, given_condition, evaluate, **kwargs)
|
| 688 |
+
|
| 689 |
+
if isinstance(condition, And):
|
| 690 |
+
compute_later, state2cond, conds = [], {}, condition.args
|
| 691 |
+
for expr in conds:
|
| 692 |
+
if isinstance(expr, Relational):
|
| 693 |
+
ris = list(expr.atoms(RandomIndexedSymbol))[0]
|
| 694 |
+
if state2cond.get(ris, None) is None:
|
| 695 |
+
state2cond[ris] = S.true
|
| 696 |
+
state2cond[ris] &= expr
|
| 697 |
+
else:
|
| 698 |
+
compute_later.append(expr)
|
| 699 |
+
ris = []
|
| 700 |
+
for ri in state2cond:
|
| 701 |
+
ris.append(ri)
|
| 702 |
+
cset = Intersection(state2cond[ri].as_set(), state_index)
|
| 703 |
+
if len(cset) == 0:
|
| 704 |
+
return S.Zero
|
| 705 |
+
state2cond[ri] = cset.as_relational(ri)
|
| 706 |
+
sorted_ris = sorted(ris, key=lambda ri: ri.key)
|
| 707 |
+
prod = self.probability(state2cond[sorted_ris[0]], given_condition, evaluate, **kwargs)
|
| 708 |
+
for i in range(1, len(sorted_ris)):
|
| 709 |
+
ri, prev_ri = sorted_ris[i], sorted_ris[i-1]
|
| 710 |
+
if not isinstance(state2cond[ri], Eq):
|
| 711 |
+
raise ValueError("The process is in multiple states at %s, unable to determine the probability."%(ri))
|
| 712 |
+
mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat)
|
| 713 |
+
prod *= self.probability(state2cond[ri], state2cond[prev_ri]
|
| 714 |
+
& mat_of
|
| 715 |
+
& StochasticStateSpaceOf(self, state_index),
|
| 716 |
+
evaluate, **kwargs)
|
| 717 |
+
for expr in compute_later:
|
| 718 |
+
prod *= self.probability(expr, given_condition, evaluate, **kwargs)
|
| 719 |
+
return prod
|
| 720 |
+
|
| 721 |
+
if isinstance(condition, Or):
|
| 722 |
+
return sum([self.probability(expr, given_condition, evaluate, **kwargs)
|
| 723 |
+
for expr in condition.args])
|
| 724 |
+
|
| 725 |
+
raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been "
|
| 726 |
+
"implemented yet."%(condition, given_condition))
|
| 727 |
+
|
| 728 |
+
def _symbolic_probability(self, condition, new_given_condition, rv, min_key_rv):
|
| 729 |
+
#Function to calculate probability for queries with symbols
|
| 730 |
+
if isinstance(condition, Relational):
|
| 731 |
+
curr_state = new_given_condition.rhs if isinstance(new_given_condition.lhs, RandomIndexedSymbol) \
|
| 732 |
+
else new_given_condition.lhs
|
| 733 |
+
next_state = condition.rhs if isinstance(condition.lhs, RandomIndexedSymbol) \
|
| 734 |
+
else condition.lhs
|
| 735 |
+
|
| 736 |
+
if isinstance(condition, (Eq, Ne)):
|
| 737 |
+
if isinstance(self, DiscreteMarkovChain):
|
| 738 |
+
P = self.transition_probabilities**(rv[0].key - min_key_rv.key)
|
| 739 |
+
else:
|
| 740 |
+
P = exp(self.generator_matrix*(rv[0].key - min_key_rv.key))
|
| 741 |
+
prob = P[curr_state, next_state] if isinstance(condition, Eq) else 1 - P[curr_state, next_state]
|
| 742 |
+
return Piecewise((prob, rv[0].key > min_key_rv.key), (Probability(condition), True))
|
| 743 |
+
else:
|
| 744 |
+
upper = 1
|
| 745 |
+
greater = False
|
| 746 |
+
if isinstance(condition, (Ge, Lt)):
|
| 747 |
+
upper = 0
|
| 748 |
+
if isinstance(condition, (Ge, Gt)):
|
| 749 |
+
greater = True
|
| 750 |
+
k = Dummy('k')
|
| 751 |
+
condition = Eq(condition.lhs, k) if isinstance(condition.lhs, RandomIndexedSymbol)\
|
| 752 |
+
else Eq(condition.rhs, k)
|
| 753 |
+
total = Sum(self.probability(condition, new_given_condition), (k, next_state + upper, self.state_space._sup))
|
| 754 |
+
return Piecewise((total, rv[0].key > min_key_rv.key), (Probability(condition), True)) if greater\
|
| 755 |
+
else Piecewise((1 - total, rv[0].key > min_key_rv.key), (Probability(condition), True))
|
| 756 |
+
else:
|
| 757 |
+
return Probability(condition, new_given_condition)
|
| 758 |
+
|
| 759 |
+
def expectation(self, expr, condition=None, evaluate=True, **kwargs):
|
| 760 |
+
"""
|
| 761 |
+
Handles expectation queries for markov process.
|
| 762 |
+
|
| 763 |
+
Parameters
|
| 764 |
+
==========
|
| 765 |
+
|
| 766 |
+
expr: RandomIndexedSymbol, Relational, Logic
|
| 767 |
+
Condition for which expectation has to be computed. Must
|
| 768 |
+
contain a RandomIndexedSymbol of the process.
|
| 769 |
+
condition: Relational, Logic
|
| 770 |
+
The given conditions under which computations should be done.
|
| 771 |
+
|
| 772 |
+
Returns
|
| 773 |
+
=======
|
| 774 |
+
|
| 775 |
+
Expectation
|
| 776 |
+
Unevaluated object if computations cannot be done due to
|
| 777 |
+
insufficient information.
|
| 778 |
+
Expr
|
| 779 |
+
In all other cases when the computations are successful.
|
| 780 |
+
|
| 781 |
+
Note
|
| 782 |
+
====
|
| 783 |
+
|
| 784 |
+
Any information passed at the time of query overrides
|
| 785 |
+
any information passed at the time of object creation like
|
| 786 |
+
transition probabilities, state space.
|
| 787 |
+
|
| 788 |
+
Pass the transition matrix using TransitionMatrixOf,
|
| 789 |
+
generator matrix using GeneratorMatrixOf and state space
|
| 790 |
+
using StochasticStateSpaceOf in given_condition using & or And.
|
| 791 |
+
"""
|
| 792 |
+
|
| 793 |
+
check, mat, state_index, condition = \
|
| 794 |
+
self._preprocess(condition, evaluate)
|
| 795 |
+
|
| 796 |
+
if check:
|
| 797 |
+
return Expectation(expr, condition)
|
| 798 |
+
|
| 799 |
+
rvs = random_symbols(expr)
|
| 800 |
+
if isinstance(expr, Expr) and isinstance(condition, Eq) \
|
| 801 |
+
and len(rvs) == 1:
|
| 802 |
+
# handle queries similar to E(f(X[i]), Eq(X[i-m], <some-state>))
|
| 803 |
+
condition=self.replace_with_index(condition)
|
| 804 |
+
state_index=self.replace_with_index(state_index)
|
| 805 |
+
rv = list(rvs)[0]
|
| 806 |
+
lhsg, rhsg = condition.lhs, condition.rhs
|
| 807 |
+
if not isinstance(lhsg, RandomIndexedSymbol):
|
| 808 |
+
lhsg, rhsg = (rhsg, lhsg)
|
| 809 |
+
if rhsg not in state_index:
|
| 810 |
+
raise ValueError("%s state is not in the state space."%(rhsg))
|
| 811 |
+
if rv.key < lhsg.key:
|
| 812 |
+
raise ValueError("Incorrect given condition is given, expectation "
|
| 813 |
+
"time %s < time %s"%(rv.key, rv.key))
|
| 814 |
+
mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat)
|
| 815 |
+
cond = condition & mat_of & \
|
| 816 |
+
StochasticStateSpaceOf(self, state_index)
|
| 817 |
+
func = lambda s: self.probability(Eq(rv, s), cond) * expr.subs(rv, self._state_index[s])
|
| 818 |
+
return sum([func(s) for s in state_index])
|
| 819 |
+
|
| 820 |
+
raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been "
|
| 821 |
+
"implemented yet."%(expr, condition))
|
| 822 |
+
|
| 823 |
+
class DiscreteMarkovChain(DiscreteTimeStochasticProcess, MarkovProcess):
|
| 824 |
+
"""
|
| 825 |
+
Represents a finite discrete time-homogeneous Markov chain.
|
| 826 |
+
|
| 827 |
+
This type of Markov Chain can be uniquely characterised by
|
| 828 |
+
its (ordered) state space and its one-step transition probability
|
| 829 |
+
matrix.
|
| 830 |
+
|
| 831 |
+
Parameters
|
| 832 |
+
==========
|
| 833 |
+
|
| 834 |
+
sym:
|
| 835 |
+
The name given to the Markov Chain
|
| 836 |
+
state_space:
|
| 837 |
+
Optional, by default, Range(n)
|
| 838 |
+
trans_probs:
|
| 839 |
+
Optional, by default, MatrixSymbol('_T', n, n)
|
| 840 |
+
|
| 841 |
+
Examples
|
| 842 |
+
========
|
| 843 |
+
|
| 844 |
+
>>> from sympy.stats import DiscreteMarkovChain, TransitionMatrixOf, P, E
|
| 845 |
+
>>> from sympy import Matrix, MatrixSymbol, Eq, symbols
|
| 846 |
+
>>> T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]])
|
| 847 |
+
>>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
|
| 848 |
+
>>> YS = DiscreteMarkovChain("Y")
|
| 849 |
+
|
| 850 |
+
>>> Y.state_space
|
| 851 |
+
{0, 1, 2}
|
| 852 |
+
>>> Y.transition_probabilities
|
| 853 |
+
Matrix([
|
| 854 |
+
[0.5, 0.2, 0.3],
|
| 855 |
+
[0.2, 0.5, 0.3],
|
| 856 |
+
[0.2, 0.3, 0.5]])
|
| 857 |
+
>>> TS = MatrixSymbol('T', 3, 3)
|
| 858 |
+
>>> P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TS))
|
| 859 |
+
T[0, 2]*T[1, 0] + T[1, 1]*T[1, 2] + T[1, 2]*T[2, 2]
|
| 860 |
+
>>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2)
|
| 861 |
+
0.36
|
| 862 |
+
|
| 863 |
+
Probabilities will be calculated based on indexes rather
|
| 864 |
+
than state names. For example, with the Sunny-Cloudy-Rainy
|
| 865 |
+
model with string state names:
|
| 866 |
+
|
| 867 |
+
>>> from sympy.core.symbol import Str
|
| 868 |
+
>>> Y = DiscreteMarkovChain("Y", [Str('Sunny'), Str('Cloudy'), Str('Rainy')], T)
|
| 869 |
+
>>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2)
|
| 870 |
+
0.36
|
| 871 |
+
|
| 872 |
+
This gives the same answer as the ``[0, 1, 2]`` state space.
|
| 873 |
+
Currently, there is no support for state names within probability
|
| 874 |
+
and expectation statements. Here is a work-around using ``Str``:
|
| 875 |
+
|
| 876 |
+
>>> P(Eq(Str('Rainy'), Y[3]), Eq(Y[1], Str('Cloudy'))).round(2)
|
| 877 |
+
0.36
|
| 878 |
+
|
| 879 |
+
Symbol state names can also be used:
|
| 880 |
+
|
| 881 |
+
>>> sunny, cloudy, rainy = symbols('Sunny, Cloudy, Rainy')
|
| 882 |
+
>>> Y = DiscreteMarkovChain("Y", [sunny, cloudy, rainy], T)
|
| 883 |
+
>>> P(Eq(Y[3], rainy), Eq(Y[1], cloudy)).round(2)
|
| 884 |
+
0.36
|
| 885 |
+
|
| 886 |
+
Expectations will be calculated as follows:
|
| 887 |
+
|
| 888 |
+
>>> E(Y[3], Eq(Y[1], cloudy))
|
| 889 |
+
0.38*Cloudy + 0.36*Rainy + 0.26*Sunny
|
| 890 |
+
|
| 891 |
+
Probability of expressions with multiple RandomIndexedSymbols
|
| 892 |
+
can also be calculated provided there is only 1 RandomIndexedSymbol
|
| 893 |
+
in the given condition. It is always better to use Rational instead
|
| 894 |
+
of floating point numbers for the probabilities in the
|
| 895 |
+
transition matrix to avoid errors.
|
| 896 |
+
|
| 897 |
+
>>> from sympy import Gt, Le, Rational
|
| 898 |
+
>>> T = Matrix([[Rational(5, 10), Rational(3, 10), Rational(2, 10)], [Rational(2, 10), Rational(7, 10), Rational(1, 10)], [Rational(3, 10), Rational(3, 10), Rational(4, 10)]])
|
| 899 |
+
>>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
|
| 900 |
+
>>> P(Eq(Y[3], Y[1]), Eq(Y[0], 0)).round(3)
|
| 901 |
+
0.409
|
| 902 |
+
>>> P(Gt(Y[3], Y[1]), Eq(Y[0], 0)).round(2)
|
| 903 |
+
0.36
|
| 904 |
+
>>> P(Le(Y[15], Y[10]), Eq(Y[8], 2)).round(7)
|
| 905 |
+
0.6963328
|
| 906 |
+
|
| 907 |
+
Symbolic probability queries are also supported
|
| 908 |
+
|
| 909 |
+
>>> a, b, c, d = symbols('a b c d')
|
| 910 |
+
>>> T = Matrix([[Rational(1, 10), Rational(4, 10), Rational(5, 10)], [Rational(3, 10), Rational(4, 10), Rational(3, 10)], [Rational(7, 10), Rational(2, 10), Rational(1, 10)]])
|
| 911 |
+
>>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
|
| 912 |
+
>>> query = P(Eq(Y[a], b), Eq(Y[c], d))
|
| 913 |
+
>>> query.subs({a:10, b:2, c:5, d:1}).round(4)
|
| 914 |
+
0.3096
|
| 915 |
+
>>> P(Eq(Y[10], 2), Eq(Y[5], 1)).evalf().round(4)
|
| 916 |
+
0.3096
|
| 917 |
+
>>> query_gt = P(Gt(Y[a], b), Eq(Y[c], d))
|
| 918 |
+
>>> query_gt.subs({a:21, b:0, c:5, d:0}).evalf().round(5)
|
| 919 |
+
0.64705
|
| 920 |
+
>>> P(Gt(Y[21], 0), Eq(Y[5], 0)).round(5)
|
| 921 |
+
0.64705
|
| 922 |
+
|
| 923 |
+
There is limited support for arbitrarily sized states:
|
| 924 |
+
|
| 925 |
+
>>> n = symbols('n', nonnegative=True, integer=True)
|
| 926 |
+
>>> T = MatrixSymbol('T', n, n)
|
| 927 |
+
>>> Y = DiscreteMarkovChain("Y", trans_probs=T)
|
| 928 |
+
>>> Y.state_space
|
| 929 |
+
Range(0, n, 1)
|
| 930 |
+
>>> query = P(Eq(Y[a], b), Eq(Y[c], d))
|
| 931 |
+
>>> query.subs({a:10, b:2, c:5, d:1})
|
| 932 |
+
(T**5)[1, 2]
|
| 933 |
+
|
| 934 |
+
References
|
| 935 |
+
==========
|
| 936 |
+
|
| 937 |
+
.. [1] https://en.wikipedia.org/wiki/Markov_chain#Discrete-time_Markov_chain
|
| 938 |
+
.. [2] https://web.archive.org/web/20201230182007/https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf
|
| 939 |
+
"""
|
| 940 |
+
index_set = S.Naturals0
|
| 941 |
+
|
| 942 |
+
def __new__(cls, sym, state_space=None, trans_probs=None):
|
| 943 |
+
sym = _symbol_converter(sym)
|
| 944 |
+
|
| 945 |
+
state_space, trans_probs = MarkovProcess._sanity_checks(state_space, trans_probs)
|
| 946 |
+
|
| 947 |
+
obj = Basic.__new__(cls, sym, state_space, trans_probs) # type: ignore
|
| 948 |
+
indices = {}
|
| 949 |
+
if isinstance(obj.number_of_states, Integer):
|
| 950 |
+
for index, state in enumerate(obj._state_index):
|
| 951 |
+
indices[state] = index
|
| 952 |
+
obj.index_of = indices
|
| 953 |
+
return obj
|
| 954 |
+
|
| 955 |
+
@property
|
| 956 |
+
def transition_probabilities(self):
|
| 957 |
+
"""
|
| 958 |
+
Transition probabilities of discrete Markov chain,
|
| 959 |
+
either an instance of Matrix or MatrixSymbol.
|
| 960 |
+
"""
|
| 961 |
+
return self.args[2]
|
| 962 |
+
|
| 963 |
+
def communication_classes(self) -> tList[tTuple[tList[Basic], Boolean, Integer]]:
|
| 964 |
+
"""
|
| 965 |
+
Returns the list of communication classes that partition
|
| 966 |
+
the states of the markov chain.
|
| 967 |
+
|
| 968 |
+
A communication class is defined to be a set of states
|
| 969 |
+
such that every state in that set is reachable from
|
| 970 |
+
every other state in that set. Due to its properties
|
| 971 |
+
this forms a class in the mathematical sense.
|
| 972 |
+
Communication classes are also known as recurrence
|
| 973 |
+
classes.
|
| 974 |
+
|
| 975 |
+
Returns
|
| 976 |
+
=======
|
| 977 |
+
|
| 978 |
+
classes
|
| 979 |
+
The ``classes`` are a list of tuples. Each
|
| 980 |
+
tuple represents a single communication class
|
| 981 |
+
with its properties. The first element in the
|
| 982 |
+
tuple is the list of states in the class, the
|
| 983 |
+
second element is whether the class is recurrent
|
| 984 |
+
and the third element is the period of the
|
| 985 |
+
communication class.
|
| 986 |
+
|
| 987 |
+
Examples
|
| 988 |
+
========
|
| 989 |
+
|
| 990 |
+
>>> from sympy.stats import DiscreteMarkovChain
|
| 991 |
+
>>> from sympy import Matrix
|
| 992 |
+
>>> T = Matrix([[0, 1, 0],
|
| 993 |
+
... [1, 0, 0],
|
| 994 |
+
... [1, 0, 0]])
|
| 995 |
+
>>> X = DiscreteMarkovChain('X', [1, 2, 3], T)
|
| 996 |
+
>>> classes = X.communication_classes()
|
| 997 |
+
>>> for states, is_recurrent, period in classes:
|
| 998 |
+
... states, is_recurrent, period
|
| 999 |
+
([1, 2], True, 2)
|
| 1000 |
+
([3], False, 1)
|
| 1001 |
+
|
| 1002 |
+
From this we can see that states ``1`` and ``2``
|
| 1003 |
+
communicate, are recurrent and have a period
|
| 1004 |
+
of 2. We can also see state ``3`` is transient
|
| 1005 |
+
with a period of 1.
|
| 1006 |
+
|
| 1007 |
+
Notes
|
| 1008 |
+
=====
|
| 1009 |
+
|
| 1010 |
+
The algorithm used is of order ``O(n**2)`` where
|
| 1011 |
+
``n`` is the number of states in the markov chain.
|
| 1012 |
+
It uses Tarjan's algorithm to find the classes
|
| 1013 |
+
themselves and then it uses a breadth-first search
|
| 1014 |
+
algorithm to find each class's periodicity.
|
| 1015 |
+
Most of the algorithm's components approach ``O(n)``
|
| 1016 |
+
as the matrix becomes more and more sparse.
|
| 1017 |
+
|
| 1018 |
+
References
|
| 1019 |
+
==========
|
| 1020 |
+
|
| 1021 |
+
.. [1] https://web.archive.org/web/20220207032113/https://www.columbia.edu/~ww2040/4701Sum07/4701-06-Notes-MCII.pdf
|
| 1022 |
+
.. [2] https://cecas.clemson.edu/~shierd/Shier/markov.pdf
|
| 1023 |
+
.. [3] https://ujcontent.uj.ac.za/esploro/outputs/graduate/Markov-chains--a-graph-theoretical/999849107691#file-0
|
| 1024 |
+
.. [4] https://www.mathworks.com/help/econ/dtmc.classify.html
|
| 1025 |
+
"""
|
| 1026 |
+
n = self.number_of_states
|
| 1027 |
+
T = self.transition_probabilities
|
| 1028 |
+
|
| 1029 |
+
if isinstance(T, MatrixSymbol):
|
| 1030 |
+
raise NotImplementedError("Cannot perform the operation with a symbolic matrix.")
|
| 1031 |
+
|
| 1032 |
+
# begin Tarjan's algorithm
|
| 1033 |
+
V = Range(n)
|
| 1034 |
+
# don't use state names. Rather use state
|
| 1035 |
+
# indexes since we use them for matrix
|
| 1036 |
+
# indexing here and later onward
|
| 1037 |
+
E = [(i, j) for i in V for j in V if T[i, j] != 0]
|
| 1038 |
+
classes = strongly_connected_components((V, E))
|
| 1039 |
+
# end Tarjan's algorithm
|
| 1040 |
+
|
| 1041 |
+
recurrence = []
|
| 1042 |
+
periods = []
|
| 1043 |
+
for class_ in classes:
|
| 1044 |
+
# begin recurrent check (similar to self._check_trans_probs())
|
| 1045 |
+
submatrix = T[class_, class_] # get the submatrix with those states
|
| 1046 |
+
is_recurrent = S.true
|
| 1047 |
+
rows = submatrix.tolist()
|
| 1048 |
+
for row in rows:
|
| 1049 |
+
if (sum(row) - 1) != 0:
|
| 1050 |
+
is_recurrent = S.false
|
| 1051 |
+
break
|
| 1052 |
+
recurrence.append(is_recurrent)
|
| 1053 |
+
# end recurrent check
|
| 1054 |
+
|
| 1055 |
+
# begin breadth-first search
|
| 1056 |
+
non_tree_edge_values: tSet[int] = set()
|
| 1057 |
+
visited = {class_[0]}
|
| 1058 |
+
newly_visited = {class_[0]}
|
| 1059 |
+
level = {class_[0]: 0}
|
| 1060 |
+
current_level = 0
|
| 1061 |
+
done = False # imitate a do-while loop
|
| 1062 |
+
while not done: # runs at most len(class_) times
|
| 1063 |
+
done = len(visited) == len(class_)
|
| 1064 |
+
current_level += 1
|
| 1065 |
+
|
| 1066 |
+
# this loop and the while loop above run a combined len(class_) number of times.
|
| 1067 |
+
# so this triple nested loop runs through each of the n states once.
|
| 1068 |
+
for i in newly_visited:
|
| 1069 |
+
|
| 1070 |
+
# the loop below runs len(class_) number of times
|
| 1071 |
+
# complexity is around about O(n * avg(len(class_)))
|
| 1072 |
+
newly_visited = {j for j in class_ if T[i, j] != 0}
|
| 1073 |
+
|
| 1074 |
+
new_tree_edges = newly_visited.difference(visited)
|
| 1075 |
+
for j in new_tree_edges:
|
| 1076 |
+
level[j] = current_level
|
| 1077 |
+
|
| 1078 |
+
new_non_tree_edges = newly_visited.intersection(visited)
|
| 1079 |
+
new_non_tree_edge_values = {level[i]-level[j]+1 for j in new_non_tree_edges}
|
| 1080 |
+
|
| 1081 |
+
non_tree_edge_values = non_tree_edge_values.union(new_non_tree_edge_values)
|
| 1082 |
+
visited = visited.union(new_tree_edges)
|
| 1083 |
+
|
| 1084 |
+
# igcd needs at least 2 arguments
|
| 1085 |
+
positive_ntev = {val_e for val_e in non_tree_edge_values if val_e > 0}
|
| 1086 |
+
if len(positive_ntev) == 0:
|
| 1087 |
+
periods.append(len(class_))
|
| 1088 |
+
elif len(positive_ntev) == 1:
|
| 1089 |
+
periods.append(positive_ntev.pop())
|
| 1090 |
+
else:
|
| 1091 |
+
periods.append(igcd(*positive_ntev))
|
| 1092 |
+
# end breadth-first search
|
| 1093 |
+
|
| 1094 |
+
# convert back to the user's state names
|
| 1095 |
+
classes = [[_sympify(self._state_index[i]) for i in class_] for class_ in classes]
|
| 1096 |
+
return list(zip(classes, recurrence, map(Integer,periods)))
|
| 1097 |
+
|
| 1098 |
+
def fundamental_matrix(self):
|
| 1099 |
+
"""
|
| 1100 |
+
Each entry fundamental matrix can be interpreted as
|
| 1101 |
+
the expected number of times the chains is in state j
|
| 1102 |
+
if it started in state i.
|
| 1103 |
+
|
| 1104 |
+
References
|
| 1105 |
+
==========
|
| 1106 |
+
|
| 1107 |
+
.. [1] https://lips.cs.princeton.edu/the-fundamental-matrix-of-a-finite-markov-chain/
|
| 1108 |
+
|
| 1109 |
+
"""
|
| 1110 |
+
_, _, _, Q = self.decompose()
|
| 1111 |
+
|
| 1112 |
+
if Q.shape[0] > 0: # if non-ergodic
|
| 1113 |
+
I = eye(Q.shape[0])
|
| 1114 |
+
if (I - Q).det() == 0:
|
| 1115 |
+
raise ValueError("The fundamental matrix doesn't exist.")
|
| 1116 |
+
return (I - Q).inv().as_immutable()
|
| 1117 |
+
else: # if ergodic
|
| 1118 |
+
P = self.transition_probabilities
|
| 1119 |
+
I = eye(P.shape[0])
|
| 1120 |
+
w = self.fixed_row_vector()
|
| 1121 |
+
W = Matrix([list(w) for i in range(0, P.shape[0])])
|
| 1122 |
+
if (I - P + W).det() == 0:
|
| 1123 |
+
raise ValueError("The fundamental matrix doesn't exist.")
|
| 1124 |
+
return (I - P + W).inv().as_immutable()
|
| 1125 |
+
|
| 1126 |
+
def absorbing_probabilities(self):
|
| 1127 |
+
"""
|
| 1128 |
+
Computes the absorbing probabilities, i.e.
|
| 1129 |
+
the ij-th entry of the matrix denotes the
|
| 1130 |
+
probability of Markov chain being absorbed
|
| 1131 |
+
in state j starting from state i.
|
| 1132 |
+
"""
|
| 1133 |
+
_, _, R, _ = self.decompose()
|
| 1134 |
+
N = self.fundamental_matrix()
|
| 1135 |
+
if R is None or N is None:
|
| 1136 |
+
return None
|
| 1137 |
+
return N*R
|
| 1138 |
+
|
| 1139 |
+
def absorbing_probabilites(self):
|
| 1140 |
+
sympy_deprecation_warning(
|
| 1141 |
+
"""
|
| 1142 |
+
DiscreteMarkovChain.absorbing_probabilites() is deprecated. Use
|
| 1143 |
+
absorbing_probabilities() instead (note the spelling difference).
|
| 1144 |
+
""",
|
| 1145 |
+
deprecated_since_version="1.7",
|
| 1146 |
+
active_deprecations_target="deprecated-absorbing_probabilites",
|
| 1147 |
+
)
|
| 1148 |
+
return self.absorbing_probabilities()
|
| 1149 |
+
|
| 1150 |
+
def is_regular(self):
|
| 1151 |
+
tuples = self.communication_classes()
|
| 1152 |
+
if len(tuples) == 0:
|
| 1153 |
+
return S.false # not defined for a 0x0 matrix
|
| 1154 |
+
classes, _, periods = list(zip(*tuples))
|
| 1155 |
+
return And(len(classes) == 1, periods[0] == 1)
|
| 1156 |
+
|
| 1157 |
+
def is_ergodic(self):
|
| 1158 |
+
tuples = self.communication_classes()
|
| 1159 |
+
if len(tuples) == 0:
|
| 1160 |
+
return S.false # not defined for a 0x0 matrix
|
| 1161 |
+
classes, _, _ = list(zip(*tuples))
|
| 1162 |
+
return S(len(classes) == 1)
|
| 1163 |
+
|
| 1164 |
+
def is_absorbing_state(self, state):
|
| 1165 |
+
trans_probs = self.transition_probabilities
|
| 1166 |
+
if isinstance(trans_probs, ImmutableMatrix) and \
|
| 1167 |
+
state < trans_probs.shape[0]:
|
| 1168 |
+
return S(trans_probs[state, state]) is S.One
|
| 1169 |
+
|
| 1170 |
+
def is_absorbing_chain(self):
|
| 1171 |
+
states, A, B, C = self.decompose()
|
| 1172 |
+
r = A.shape[0]
|
| 1173 |
+
return And(r > 0, A == Identity(r).as_explicit())
|
| 1174 |
+
|
| 1175 |
+
def stationary_distribution(self, condition_set=False) -> tUnion[ImmutableMatrix, ConditionSet, Lambda]:
|
| 1176 |
+
r"""
|
| 1177 |
+
The stationary distribution is any row vector, p, that solves p = pP,
|
| 1178 |
+
is row stochastic and each element in p must be nonnegative.
|
| 1179 |
+
That means in matrix form: :math:`(P-I)^T p^T = 0` and
|
| 1180 |
+
:math:`(1, \dots, 1) p = 1`
|
| 1181 |
+
where ``P`` is the one-step transition matrix.
|
| 1182 |
+
|
| 1183 |
+
All time-homogeneous Markov Chains with a finite state space
|
| 1184 |
+
have at least one stationary distribution. In addition, if
|
| 1185 |
+
a finite time-homogeneous Markov Chain is irreducible, the
|
| 1186 |
+
stationary distribution is unique.
|
| 1187 |
+
|
| 1188 |
+
Parameters
|
| 1189 |
+
==========
|
| 1190 |
+
|
| 1191 |
+
condition_set : bool
|
| 1192 |
+
If the chain has a symbolic size or transition matrix,
|
| 1193 |
+
it will return a ``Lambda`` if ``False`` and return a
|
| 1194 |
+
``ConditionSet`` if ``True``.
|
| 1195 |
+
|
| 1196 |
+
Examples
|
| 1197 |
+
========
|
| 1198 |
+
|
| 1199 |
+
>>> from sympy.stats import DiscreteMarkovChain
|
| 1200 |
+
>>> from sympy import Matrix, S
|
| 1201 |
+
|
| 1202 |
+
An irreducible Markov Chain
|
| 1203 |
+
|
| 1204 |
+
>>> T = Matrix([[S(1)/2, S(1)/2, 0],
|
| 1205 |
+
... [S(4)/5, S(1)/5, 0],
|
| 1206 |
+
... [1, 0, 0]])
|
| 1207 |
+
>>> X = DiscreteMarkovChain('X', trans_probs=T)
|
| 1208 |
+
>>> X.stationary_distribution()
|
| 1209 |
+
Matrix([[8/13, 5/13, 0]])
|
| 1210 |
+
|
| 1211 |
+
A reducible Markov Chain
|
| 1212 |
+
|
| 1213 |
+
>>> T = Matrix([[S(1)/2, S(1)/2, 0],
|
| 1214 |
+
... [S(4)/5, S(1)/5, 0],
|
| 1215 |
+
... [0, 0, 1]])
|
| 1216 |
+
>>> X = DiscreteMarkovChain('X', trans_probs=T)
|
| 1217 |
+
>>> X.stationary_distribution()
|
| 1218 |
+
Matrix([[8/13 - 8*tau0/13, 5/13 - 5*tau0/13, tau0]])
|
| 1219 |
+
|
| 1220 |
+
>>> Y = DiscreteMarkovChain('Y')
|
| 1221 |
+
>>> Y.stationary_distribution()
|
| 1222 |
+
Lambda((wm, _T), Eq(wm*_T, wm))
|
| 1223 |
+
|
| 1224 |
+
>>> Y.stationary_distribution(condition_set=True)
|
| 1225 |
+
ConditionSet(wm, Eq(wm*_T, wm))
|
| 1226 |
+
|
| 1227 |
+
References
|
| 1228 |
+
==========
|
| 1229 |
+
|
| 1230 |
+
.. [1] https://www.probabilitycourse.com/chapter11/11_2_6_stationary_and_limiting_distributions.php
|
| 1231 |
+
.. [2] https://web.archive.org/web/20210508104430/https://galton.uchicago.edu/~yibi/teaching/stat317/2014/Lectures/Lecture4_6up.pdf
|
| 1232 |
+
|
| 1233 |
+
See Also
|
| 1234 |
+
========
|
| 1235 |
+
|
| 1236 |
+
sympy.stats.DiscreteMarkovChain.limiting_distribution
|
| 1237 |
+
"""
|
| 1238 |
+
trans_probs = self.transition_probabilities
|
| 1239 |
+
n = self.number_of_states
|
| 1240 |
+
|
| 1241 |
+
if n == 0:
|
| 1242 |
+
return ImmutableMatrix(Matrix([[]]))
|
| 1243 |
+
|
| 1244 |
+
# symbolic matrix version
|
| 1245 |
+
if isinstance(trans_probs, MatrixSymbol):
|
| 1246 |
+
wm = MatrixSymbol('wm', 1, n)
|
| 1247 |
+
if condition_set:
|
| 1248 |
+
return ConditionSet(wm, Eq(wm * trans_probs, wm))
|
| 1249 |
+
else:
|
| 1250 |
+
return Lambda((wm, trans_probs), Eq(wm * trans_probs, wm))
|
| 1251 |
+
|
| 1252 |
+
# numeric matrix version
|
| 1253 |
+
a = Matrix(trans_probs - Identity(n)).T
|
| 1254 |
+
a[0, 0:n] = ones(1, n) # type: ignore
|
| 1255 |
+
b = zeros(n, 1)
|
| 1256 |
+
b[0, 0] = 1
|
| 1257 |
+
|
| 1258 |
+
soln = list(linsolve((a, b)))[0]
|
| 1259 |
+
return ImmutableMatrix([soln])
|
| 1260 |
+
|
| 1261 |
+
def fixed_row_vector(self):
|
| 1262 |
+
"""
|
| 1263 |
+
A wrapper for ``stationary_distribution()``.
|
| 1264 |
+
"""
|
| 1265 |
+
return self.stationary_distribution()
|
| 1266 |
+
|
| 1267 |
+
@property
|
| 1268 |
+
def limiting_distribution(self):
|
| 1269 |
+
"""
|
| 1270 |
+
The fixed row vector is the limiting
|
| 1271 |
+
distribution of a discrete Markov chain.
|
| 1272 |
+
"""
|
| 1273 |
+
return self.fixed_row_vector()
|
| 1274 |
+
|
| 1275 |
+
def decompose(self) -> tTuple[tList[Basic], ImmutableMatrix, ImmutableMatrix, ImmutableMatrix]:
|
| 1276 |
+
"""
|
| 1277 |
+
Decomposes the transition matrix into submatrices with
|
| 1278 |
+
special properties.
|
| 1279 |
+
|
| 1280 |
+
The transition matrix can be decomposed into 4 submatrices:
|
| 1281 |
+
- A - the submatrix from recurrent states to recurrent states.
|
| 1282 |
+
- B - the submatrix from transient to recurrent states.
|
| 1283 |
+
- C - the submatrix from transient to transient states.
|
| 1284 |
+
- O - the submatrix of zeros for recurrent to transient states.
|
| 1285 |
+
|
| 1286 |
+
Returns
|
| 1287 |
+
=======
|
| 1288 |
+
|
| 1289 |
+
states, A, B, C
|
| 1290 |
+
``states`` - a list of state names with the first being
|
| 1291 |
+
the recurrent states and the last being
|
| 1292 |
+
the transient states in the order
|
| 1293 |
+
of the row names of A and then the row names of C.
|
| 1294 |
+
``A`` - the submatrix from recurrent states to recurrent states.
|
| 1295 |
+
``B`` - the submatrix from transient to recurrent states.
|
| 1296 |
+
``C`` - the submatrix from transient to transient states.
|
| 1297 |
+
|
| 1298 |
+
Examples
|
| 1299 |
+
========
|
| 1300 |
+
|
| 1301 |
+
>>> from sympy.stats import DiscreteMarkovChain
|
| 1302 |
+
>>> from sympy import Matrix, S
|
| 1303 |
+
|
| 1304 |
+
One can decompose this chain for example:
|
| 1305 |
+
|
| 1306 |
+
>>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0],
|
| 1307 |
+
... [S(2)/5, S(1)/5, S(2)/5, 0, 0],
|
| 1308 |
+
... [0, 0, 1, 0, 0],
|
| 1309 |
+
... [0, 0, S(1)/2, S(1)/2, 0],
|
| 1310 |
+
... [S(1)/2, 0, 0, 0, S(1)/2]])
|
| 1311 |
+
>>> X = DiscreteMarkovChain('X', trans_probs=T)
|
| 1312 |
+
>>> states, A, B, C = X.decompose()
|
| 1313 |
+
>>> states
|
| 1314 |
+
[2, 0, 1, 3, 4]
|
| 1315 |
+
|
| 1316 |
+
>>> A # recurrent to recurrent
|
| 1317 |
+
Matrix([[1]])
|
| 1318 |
+
|
| 1319 |
+
>>> B # transient to recurrent
|
| 1320 |
+
Matrix([
|
| 1321 |
+
[ 0],
|
| 1322 |
+
[2/5],
|
| 1323 |
+
[1/2],
|
| 1324 |
+
[ 0]])
|
| 1325 |
+
|
| 1326 |
+
>>> C # transient to transient
|
| 1327 |
+
Matrix([
|
| 1328 |
+
[1/2, 1/2, 0, 0],
|
| 1329 |
+
[2/5, 1/5, 0, 0],
|
| 1330 |
+
[ 0, 0, 1/2, 0],
|
| 1331 |
+
[1/2, 0, 0, 1/2]])
|
| 1332 |
+
|
| 1333 |
+
This means that state 2 is the only absorbing state
|
| 1334 |
+
(since A is a 1x1 matrix). B is a 4x1 matrix since
|
| 1335 |
+
the 4 remaining transient states all merge into reccurent
|
| 1336 |
+
state 2. And C is the 4x4 matrix that shows how the
|
| 1337 |
+
transient states 0, 1, 3, 4 all interact.
|
| 1338 |
+
|
| 1339 |
+
See Also
|
| 1340 |
+
========
|
| 1341 |
+
|
| 1342 |
+
sympy.stats.DiscreteMarkovChain.communication_classes
|
| 1343 |
+
sympy.stats.DiscreteMarkovChain.canonical_form
|
| 1344 |
+
|
| 1345 |
+
References
|
| 1346 |
+
==========
|
| 1347 |
+
|
| 1348 |
+
.. [1] https://en.wikipedia.org/wiki/Absorbing_Markov_chain
|
| 1349 |
+
.. [2] https://people.brandeis.edu/~igusa/Math56aS08/Math56a_S08_notes015.pdf
|
| 1350 |
+
"""
|
| 1351 |
+
trans_probs = self.transition_probabilities
|
| 1352 |
+
|
| 1353 |
+
classes = self.communication_classes()
|
| 1354 |
+
r_states = []
|
| 1355 |
+
t_states = []
|
| 1356 |
+
|
| 1357 |
+
for states, recurrent, period in classes:
|
| 1358 |
+
if recurrent:
|
| 1359 |
+
r_states += states
|
| 1360 |
+
else:
|
| 1361 |
+
t_states += states
|
| 1362 |
+
|
| 1363 |
+
states = r_states + t_states
|
| 1364 |
+
indexes = [self.index_of[state] for state in states] # type: ignore
|
| 1365 |
+
|
| 1366 |
+
A = Matrix(len(r_states), len(r_states),
|
| 1367 |
+
lambda i, j: trans_probs[indexes[i], indexes[j]])
|
| 1368 |
+
|
| 1369 |
+
B = Matrix(len(t_states), len(r_states),
|
| 1370 |
+
lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[j]])
|
| 1371 |
+
|
| 1372 |
+
C = Matrix(len(t_states), len(t_states),
|
| 1373 |
+
lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[len(r_states) + j]])
|
| 1374 |
+
|
| 1375 |
+
return states, A.as_immutable(), B.as_immutable(), C.as_immutable()
|
| 1376 |
+
|
| 1377 |
+
def canonical_form(self) -> tTuple[tList[Basic], ImmutableMatrix]:
|
| 1378 |
+
"""
|
| 1379 |
+
Reorders the one-step transition matrix
|
| 1380 |
+
so that recurrent states appear first and transient
|
| 1381 |
+
states appear last. Other representations include inserting
|
| 1382 |
+
transient states first and recurrent states last.
|
| 1383 |
+
|
| 1384 |
+
Returns
|
| 1385 |
+
=======
|
| 1386 |
+
|
| 1387 |
+
states, P_new
|
| 1388 |
+
``states`` is the list that describes the order of the
|
| 1389 |
+
new states in the matrix
|
| 1390 |
+
so that the ith element in ``states`` is the state of the
|
| 1391 |
+
ith row of A.
|
| 1392 |
+
``P_new`` is the new transition matrix in canonical form.
|
| 1393 |
+
|
| 1394 |
+
Examples
|
| 1395 |
+
========
|
| 1396 |
+
|
| 1397 |
+
>>> from sympy.stats import DiscreteMarkovChain
|
| 1398 |
+
>>> from sympy import Matrix, S
|
| 1399 |
+
|
| 1400 |
+
You can convert your chain into canonical form:
|
| 1401 |
+
|
| 1402 |
+
>>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0],
|
| 1403 |
+
... [S(2)/5, S(1)/5, S(2)/5, 0, 0],
|
| 1404 |
+
... [0, 0, 1, 0, 0],
|
| 1405 |
+
... [0, 0, S(1)/2, S(1)/2, 0],
|
| 1406 |
+
... [S(1)/2, 0, 0, 0, S(1)/2]])
|
| 1407 |
+
>>> X = DiscreteMarkovChain('X', list(range(1, 6)), trans_probs=T)
|
| 1408 |
+
>>> states, new_matrix = X.canonical_form()
|
| 1409 |
+
>>> states
|
| 1410 |
+
[3, 1, 2, 4, 5]
|
| 1411 |
+
|
| 1412 |
+
>>> new_matrix
|
| 1413 |
+
Matrix([
|
| 1414 |
+
[ 1, 0, 0, 0, 0],
|
| 1415 |
+
[ 0, 1/2, 1/2, 0, 0],
|
| 1416 |
+
[2/5, 2/5, 1/5, 0, 0],
|
| 1417 |
+
[1/2, 0, 0, 1/2, 0],
|
| 1418 |
+
[ 0, 1/2, 0, 0, 1/2]])
|
| 1419 |
+
|
| 1420 |
+
The new states are [3, 1, 2, 4, 5] and you can
|
| 1421 |
+
create a new chain with this and its canonical
|
| 1422 |
+
form will remain the same (since it is already
|
| 1423 |
+
in canonical form).
|
| 1424 |
+
|
| 1425 |
+
>>> X = DiscreteMarkovChain('X', states, new_matrix)
|
| 1426 |
+
>>> states, new_matrix = X.canonical_form()
|
| 1427 |
+
>>> states
|
| 1428 |
+
[3, 1, 2, 4, 5]
|
| 1429 |
+
|
| 1430 |
+
>>> new_matrix
|
| 1431 |
+
Matrix([
|
| 1432 |
+
[ 1, 0, 0, 0, 0],
|
| 1433 |
+
[ 0, 1/2, 1/2, 0, 0],
|
| 1434 |
+
[2/5, 2/5, 1/5, 0, 0],
|
| 1435 |
+
[1/2, 0, 0, 1/2, 0],
|
| 1436 |
+
[ 0, 1/2, 0, 0, 1/2]])
|
| 1437 |
+
|
| 1438 |
+
This is not limited to absorbing chains:
|
| 1439 |
+
|
| 1440 |
+
>>> T = Matrix([[0, 5, 5, 0, 0],
|
| 1441 |
+
... [0, 0, 0, 10, 0],
|
| 1442 |
+
... [5, 0, 5, 0, 0],
|
| 1443 |
+
... [0, 10, 0, 0, 0],
|
| 1444 |
+
... [0, 3, 0, 3, 4]])/10
|
| 1445 |
+
>>> X = DiscreteMarkovChain('X', trans_probs=T)
|
| 1446 |
+
>>> states, new_matrix = X.canonical_form()
|
| 1447 |
+
>>> states
|
| 1448 |
+
[1, 3, 0, 2, 4]
|
| 1449 |
+
|
| 1450 |
+
>>> new_matrix
|
| 1451 |
+
Matrix([
|
| 1452 |
+
[ 0, 1, 0, 0, 0],
|
| 1453 |
+
[ 1, 0, 0, 0, 0],
|
| 1454 |
+
[ 1/2, 0, 0, 1/2, 0],
|
| 1455 |
+
[ 0, 0, 1/2, 1/2, 0],
|
| 1456 |
+
[3/10, 3/10, 0, 0, 2/5]])
|
| 1457 |
+
|
| 1458 |
+
See Also
|
| 1459 |
+
========
|
| 1460 |
+
|
| 1461 |
+
sympy.stats.DiscreteMarkovChain.communication_classes
|
| 1462 |
+
sympy.stats.DiscreteMarkovChain.decompose
|
| 1463 |
+
|
| 1464 |
+
References
|
| 1465 |
+
==========
|
| 1466 |
+
|
| 1467 |
+
.. [1] https://onlinelibrary.wiley.com/doi/pdf/10.1002/9780470316887.app1
|
| 1468 |
+
.. [2] http://www.columbia.edu/~ww2040/6711F12/lect1023big.pdf
|
| 1469 |
+
"""
|
| 1470 |
+
states, A, B, C = self.decompose()
|
| 1471 |
+
O = zeros(A.shape[0], C.shape[1])
|
| 1472 |
+
return states, BlockMatrix([[A, O], [B, C]]).as_explicit()
|
| 1473 |
+
|
| 1474 |
+
def sample(self):
|
| 1475 |
+
"""
|
| 1476 |
+
Returns
|
| 1477 |
+
=======
|
| 1478 |
+
|
| 1479 |
+
sample: iterator object
|
| 1480 |
+
iterator object containing the sample
|
| 1481 |
+
|
| 1482 |
+
"""
|
| 1483 |
+
if not isinstance(self.transition_probabilities, (Matrix, ImmutableMatrix)):
|
| 1484 |
+
raise ValueError("Transition Matrix must be provided for sampling")
|
| 1485 |
+
Tlist = self.transition_probabilities.tolist()
|
| 1486 |
+
samps = [random.choice(list(self.state_space))]
|
| 1487 |
+
yield samps[0]
|
| 1488 |
+
time = 1
|
| 1489 |
+
densities = {}
|
| 1490 |
+
for state in self.state_space:
|
| 1491 |
+
states = list(self.state_space)
|
| 1492 |
+
densities[state] = {states[i]: Tlist[state][i]
|
| 1493 |
+
for i in range(len(states))}
|
| 1494 |
+
while time < S.Infinity:
|
| 1495 |
+
samps.append((next(sample_iter(FiniteRV("_", densities[samps[time - 1]])))))
|
| 1496 |
+
yield samps[time]
|
| 1497 |
+
time += 1
|
| 1498 |
+
|
| 1499 |
+
class ContinuousMarkovChain(ContinuousTimeStochasticProcess, MarkovProcess):
|
| 1500 |
+
"""
|
| 1501 |
+
Represents continuous time Markov chain.
|
| 1502 |
+
|
| 1503 |
+
Parameters
|
| 1504 |
+
==========
|
| 1505 |
+
|
| 1506 |
+
sym : Symbol/str
|
| 1507 |
+
state_space : Set
|
| 1508 |
+
Optional, by default, S.Reals
|
| 1509 |
+
gen_mat : Matrix/ImmutableMatrix/MatrixSymbol
|
| 1510 |
+
Optional, by default, None
|
| 1511 |
+
|
| 1512 |
+
Examples
|
| 1513 |
+
========
|
| 1514 |
+
|
| 1515 |
+
>>> from sympy.stats import ContinuousMarkovChain, P
|
| 1516 |
+
>>> from sympy import Matrix, S, Eq, Gt
|
| 1517 |
+
>>> G = Matrix([[-S(1), S(1)], [S(1), -S(1)]])
|
| 1518 |
+
>>> C = ContinuousMarkovChain('C', state_space=[0, 1], gen_mat=G)
|
| 1519 |
+
>>> C.limiting_distribution()
|
| 1520 |
+
Matrix([[1/2, 1/2]])
|
| 1521 |
+
>>> C.state_space
|
| 1522 |
+
{0, 1}
|
| 1523 |
+
>>> C.generator_matrix
|
| 1524 |
+
Matrix([
|
| 1525 |
+
[-1, 1],
|
| 1526 |
+
[ 1, -1]])
|
| 1527 |
+
|
| 1528 |
+
Probability queries are supported
|
| 1529 |
+
|
| 1530 |
+
>>> P(Eq(C(1.96), 0), Eq(C(0.78), 1)).round(5)
|
| 1531 |
+
0.45279
|
| 1532 |
+
>>> P(Gt(C(1.7), 0), Eq(C(0.82), 1)).round(5)
|
| 1533 |
+
0.58602
|
| 1534 |
+
|
| 1535 |
+
Probability of expressions with multiple RandomIndexedSymbols
|
| 1536 |
+
can also be calculated provided there is only 1 RandomIndexedSymbol
|
| 1537 |
+
in the given condition. It is always better to use Rational instead
|
| 1538 |
+
of floating point numbers for the probabilities in the
|
| 1539 |
+
generator matrix to avoid errors.
|
| 1540 |
+
|
| 1541 |
+
>>> from sympy import Gt, Le, Rational
|
| 1542 |
+
>>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]])
|
| 1543 |
+
>>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G)
|
| 1544 |
+
>>> P(Eq(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5)
|
| 1545 |
+
0.37933
|
| 1546 |
+
>>> P(Gt(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5)
|
| 1547 |
+
0.34211
|
| 1548 |
+
>>> P(Le(C(1.57), C(3.14)), Eq(C(1.22), 1)).round(4)
|
| 1549 |
+
0.7143
|
| 1550 |
+
|
| 1551 |
+
Symbolic probability queries are also supported
|
| 1552 |
+
|
| 1553 |
+
>>> from sympy import symbols
|
| 1554 |
+
>>> a,b,c,d = symbols('a b c d')
|
| 1555 |
+
>>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]])
|
| 1556 |
+
>>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G)
|
| 1557 |
+
>>> query = P(Eq(C(a), b), Eq(C(c), d))
|
| 1558 |
+
>>> query.subs({a:3.65, b:2, c:1.78, d:1}).evalf().round(10)
|
| 1559 |
+
0.4002723175
|
| 1560 |
+
>>> P(Eq(C(3.65), 2), Eq(C(1.78), 1)).round(10)
|
| 1561 |
+
0.4002723175
|
| 1562 |
+
>>> query_gt = P(Gt(C(a), b), Eq(C(c), d))
|
| 1563 |
+
>>> query_gt.subs({a:43.2, b:0, c:3.29, d:2}).evalf().round(10)
|
| 1564 |
+
0.6832579186
|
| 1565 |
+
>>> P(Gt(C(43.2), 0), Eq(C(3.29), 2)).round(10)
|
| 1566 |
+
0.6832579186
|
| 1567 |
+
|
| 1568 |
+
References
|
| 1569 |
+
==========
|
| 1570 |
+
|
| 1571 |
+
.. [1] https://en.wikipedia.org/wiki/Markov_chain#Continuous-time_Markov_chain
|
| 1572 |
+
.. [2] https://u.math.biu.ac.il/~amirgi/CTMCnotes.pdf
|
| 1573 |
+
"""
|
| 1574 |
+
index_set = S.Reals
|
| 1575 |
+
|
| 1576 |
+
def __new__(cls, sym, state_space=None, gen_mat=None):
|
| 1577 |
+
sym = _symbol_converter(sym)
|
| 1578 |
+
state_space, gen_mat = MarkovProcess._sanity_checks(state_space, gen_mat)
|
| 1579 |
+
obj = Basic.__new__(cls, sym, state_space, gen_mat)
|
| 1580 |
+
indices = {}
|
| 1581 |
+
if isinstance(obj.number_of_states, Integer):
|
| 1582 |
+
for index, state in enumerate(obj.state_space):
|
| 1583 |
+
indices[state] = index
|
| 1584 |
+
obj.index_of = indices
|
| 1585 |
+
return obj
|
| 1586 |
+
|
| 1587 |
+
@property
|
| 1588 |
+
def generator_matrix(self):
|
| 1589 |
+
return self.args[2]
|
| 1590 |
+
|
| 1591 |
+
@cacheit
|
| 1592 |
+
def transition_probabilities(self, gen_mat=None):
|
| 1593 |
+
t = Dummy('t')
|
| 1594 |
+
if isinstance(gen_mat, (Matrix, ImmutableMatrix)) and \
|
| 1595 |
+
gen_mat.is_diagonalizable():
|
| 1596 |
+
# for faster computation use diagonalized generator matrix
|
| 1597 |
+
Q, D = gen_mat.diagonalize()
|
| 1598 |
+
return Lambda(t, Q*exp(t*D)*Q.inv())
|
| 1599 |
+
if gen_mat != None:
|
| 1600 |
+
return Lambda(t, exp(t*gen_mat))
|
| 1601 |
+
|
| 1602 |
+
def limiting_distribution(self):
|
| 1603 |
+
gen_mat = self.generator_matrix
|
| 1604 |
+
if gen_mat is None:
|
| 1605 |
+
return None
|
| 1606 |
+
if isinstance(gen_mat, MatrixSymbol):
|
| 1607 |
+
wm = MatrixSymbol('wm', 1, gen_mat.shape[0])
|
| 1608 |
+
return Lambda((wm, gen_mat), Eq(wm*gen_mat, wm))
|
| 1609 |
+
w = IndexedBase('w')
|
| 1610 |
+
wi = [w[i] for i in range(gen_mat.shape[0])]
|
| 1611 |
+
wm = Matrix([wi])
|
| 1612 |
+
eqs = (wm*gen_mat).tolist()[0]
|
| 1613 |
+
eqs.append(sum(wi) - 1)
|
| 1614 |
+
soln = list(linsolve(eqs, wi))[0]
|
| 1615 |
+
return ImmutableMatrix([soln])
|
| 1616 |
+
|
| 1617 |
+
|
| 1618 |
+
class BernoulliProcess(DiscreteTimeStochasticProcess):
|
| 1619 |
+
"""
|
| 1620 |
+
The Bernoulli process consists of repeated
|
| 1621 |
+
independent Bernoulli process trials with the same parameter `p`.
|
| 1622 |
+
It's assumed that the probability `p` applies to every
|
| 1623 |
+
trial and that the outcomes of each trial
|
| 1624 |
+
are independent of all the rest. Therefore Bernoulli Process
|
| 1625 |
+
is Discrete State and Discrete Time Stochastic Process.
|
| 1626 |
+
|
| 1627 |
+
Parameters
|
| 1628 |
+
==========
|
| 1629 |
+
|
| 1630 |
+
sym : Symbol/str
|
| 1631 |
+
success : Integer/str
|
| 1632 |
+
The event which is considered to be success. Default: 1.
|
| 1633 |
+
failure: Integer/str
|
| 1634 |
+
The event which is considered to be failure. Default: 0.
|
| 1635 |
+
p : Real Number between 0 and 1
|
| 1636 |
+
Represents the probability of getting success.
|
| 1637 |
+
|
| 1638 |
+
Examples
|
| 1639 |
+
========
|
| 1640 |
+
|
| 1641 |
+
>>> from sympy.stats import BernoulliProcess, P, E
|
| 1642 |
+
>>> from sympy import Eq, Gt
|
| 1643 |
+
>>> B = BernoulliProcess("B", p=0.7, success=1, failure=0)
|
| 1644 |
+
>>> B.state_space
|
| 1645 |
+
{0, 1}
|
| 1646 |
+
>>> (B.p).round(2)
|
| 1647 |
+
0.70
|
| 1648 |
+
>>> B.success
|
| 1649 |
+
1
|
| 1650 |
+
>>> B.failure
|
| 1651 |
+
0
|
| 1652 |
+
>>> X = B[1] + B[2] + B[3]
|
| 1653 |
+
>>> P(Eq(X, 0)).round(2)
|
| 1654 |
+
0.03
|
| 1655 |
+
>>> P(Eq(X, 2)).round(2)
|
| 1656 |
+
0.44
|
| 1657 |
+
>>> P(Eq(X, 4)).round(2)
|
| 1658 |
+
0
|
| 1659 |
+
>>> P(Gt(X, 1)).round(2)
|
| 1660 |
+
0.78
|
| 1661 |
+
>>> P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0) & Eq(B[4], 1)).round(2)
|
| 1662 |
+
0.04
|
| 1663 |
+
>>> B.joint_distribution(B[1], B[2])
|
| 1664 |
+
JointDistributionHandmade(Lambda((B[1], B[2]), Piecewise((0.7, Eq(B[1], 1)),
|
| 1665 |
+
(0.3, Eq(B[1], 0)), (0, True))*Piecewise((0.7, Eq(B[2], 1)), (0.3, Eq(B[2], 0)),
|
| 1666 |
+
(0, True))))
|
| 1667 |
+
>>> E(2*B[1] + B[2]).round(2)
|
| 1668 |
+
2.10
|
| 1669 |
+
>>> P(B[1] < 1).round(2)
|
| 1670 |
+
0.30
|
| 1671 |
+
|
| 1672 |
+
References
|
| 1673 |
+
==========
|
| 1674 |
+
|
| 1675 |
+
.. [1] https://en.wikipedia.org/wiki/Bernoulli_process
|
| 1676 |
+
.. [2] https://mathcs.clarku.edu/~djoyce/ma217/bernoulli.pdf
|
| 1677 |
+
|
| 1678 |
+
"""
|
| 1679 |
+
|
| 1680 |
+
index_set = S.Naturals0
|
| 1681 |
+
|
| 1682 |
+
def __new__(cls, sym, p, success=1, failure=0):
|
| 1683 |
+
_value_check(p >= 0 and p <= 1, 'Value of p must be between 0 and 1.')
|
| 1684 |
+
sym = _symbol_converter(sym)
|
| 1685 |
+
p = _sympify(p)
|
| 1686 |
+
success = _sym_sympify(success)
|
| 1687 |
+
failure = _sym_sympify(failure)
|
| 1688 |
+
return Basic.__new__(cls, sym, p, success, failure)
|
| 1689 |
+
|
| 1690 |
+
@property
|
| 1691 |
+
def symbol(self):
|
| 1692 |
+
return self.args[0]
|
| 1693 |
+
|
| 1694 |
+
@property
|
| 1695 |
+
def p(self):
|
| 1696 |
+
return self.args[1]
|
| 1697 |
+
|
| 1698 |
+
@property
|
| 1699 |
+
def success(self):
|
| 1700 |
+
return self.args[2]
|
| 1701 |
+
|
| 1702 |
+
@property
|
| 1703 |
+
def failure(self):
|
| 1704 |
+
return self.args[3]
|
| 1705 |
+
|
| 1706 |
+
@property
|
| 1707 |
+
def state_space(self):
|
| 1708 |
+
return _set_converter([self.success, self.failure])
|
| 1709 |
+
|
| 1710 |
+
def distribution(self, key=None):
|
| 1711 |
+
if key is None:
|
| 1712 |
+
self._deprecation_warn_distribution()
|
| 1713 |
+
return BernoulliDistribution(self.p)
|
| 1714 |
+
return BernoulliDistribution(self.p, self.success, self.failure)
|
| 1715 |
+
|
| 1716 |
+
def simple_rv(self, rv):
|
| 1717 |
+
return Bernoulli(rv.name, p=self.p,
|
| 1718 |
+
succ=self.success, fail=self.failure)
|
| 1719 |
+
|
| 1720 |
+
def expectation(self, expr, condition=None, evaluate=True, **kwargs):
|
| 1721 |
+
"""
|
| 1722 |
+
Computes expectation.
|
| 1723 |
+
|
| 1724 |
+
Parameters
|
| 1725 |
+
==========
|
| 1726 |
+
|
| 1727 |
+
expr : RandomIndexedSymbol, Relational, Logic
|
| 1728 |
+
Condition for which expectation has to be computed. Must
|
| 1729 |
+
contain a RandomIndexedSymbol of the process.
|
| 1730 |
+
condition : Relational, Logic
|
| 1731 |
+
The given conditions under which computations should be done.
|
| 1732 |
+
|
| 1733 |
+
Returns
|
| 1734 |
+
=======
|
| 1735 |
+
|
| 1736 |
+
Expectation of the RandomIndexedSymbol.
|
| 1737 |
+
|
| 1738 |
+
"""
|
| 1739 |
+
|
| 1740 |
+
return _SubstituteRV._expectation(expr, condition, evaluate, **kwargs)
|
| 1741 |
+
|
| 1742 |
+
def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
|
| 1743 |
+
"""
|
| 1744 |
+
Computes probability.
|
| 1745 |
+
|
| 1746 |
+
Parameters
|
| 1747 |
+
==========
|
| 1748 |
+
|
| 1749 |
+
condition : Relational
|
| 1750 |
+
Condition for which probability has to be computed. Must
|
| 1751 |
+
contain a RandomIndexedSymbol of the process.
|
| 1752 |
+
given_condition : Relational, Logic
|
| 1753 |
+
The given conditions under which computations should be done.
|
| 1754 |
+
|
| 1755 |
+
Returns
|
| 1756 |
+
=======
|
| 1757 |
+
|
| 1758 |
+
Probability of the condition.
|
| 1759 |
+
|
| 1760 |
+
"""
|
| 1761 |
+
|
| 1762 |
+
return _SubstituteRV._probability(condition, given_condition, evaluate, **kwargs)
|
| 1763 |
+
|
| 1764 |
+
def density(self, x):
|
| 1765 |
+
return Piecewise((self.p, Eq(x, self.success)),
|
| 1766 |
+
(1 - self.p, Eq(x, self.failure)),
|
| 1767 |
+
(S.Zero, True))
|
| 1768 |
+
|
| 1769 |
+
class _SubstituteRV:
|
| 1770 |
+
"""
|
| 1771 |
+
Internal class to handle the queries of expectation and probability
|
| 1772 |
+
by substitution.
|
| 1773 |
+
"""
|
| 1774 |
+
|
| 1775 |
+
@staticmethod
|
| 1776 |
+
def _rvindexed_subs(expr, condition=None):
|
| 1777 |
+
"""
|
| 1778 |
+
Substitutes the RandomIndexedSymbol with the RandomSymbol with
|
| 1779 |
+
same name, distribution and probability as RandomIndexedSymbol.
|
| 1780 |
+
|
| 1781 |
+
Parameters
|
| 1782 |
+
==========
|
| 1783 |
+
|
| 1784 |
+
expr: RandomIndexedSymbol, Relational, Logic
|
| 1785 |
+
Condition for which expectation has to be computed. Must
|
| 1786 |
+
contain a RandomIndexedSymbol of the process.
|
| 1787 |
+
condition: Relational, Logic
|
| 1788 |
+
The given conditions under which computations should be done.
|
| 1789 |
+
|
| 1790 |
+
"""
|
| 1791 |
+
|
| 1792 |
+
rvs_expr = random_symbols(expr)
|
| 1793 |
+
if len(rvs_expr) != 0:
|
| 1794 |
+
swapdict_expr = {}
|
| 1795 |
+
for rv in rvs_expr:
|
| 1796 |
+
if isinstance(rv, RandomIndexedSymbol):
|
| 1797 |
+
newrv = rv.pspace.process.simple_rv(rv) # substitute with equivalent simple rv
|
| 1798 |
+
swapdict_expr[rv] = newrv
|
| 1799 |
+
expr = expr.subs(swapdict_expr)
|
| 1800 |
+
rvs_cond = random_symbols(condition)
|
| 1801 |
+
if len(rvs_cond)!=0:
|
| 1802 |
+
swapdict_cond = {}
|
| 1803 |
+
for rv in rvs_cond:
|
| 1804 |
+
if isinstance(rv, RandomIndexedSymbol):
|
| 1805 |
+
newrv = rv.pspace.process.simple_rv(rv)
|
| 1806 |
+
swapdict_cond[rv] = newrv
|
| 1807 |
+
condition = condition.subs(swapdict_cond)
|
| 1808 |
+
return expr, condition
|
| 1809 |
+
|
| 1810 |
+
@classmethod
|
| 1811 |
+
def _expectation(self, expr, condition=None, evaluate=True, **kwargs):
|
| 1812 |
+
"""
|
| 1813 |
+
Internal method for computing expectation of indexed RV.
|
| 1814 |
+
|
| 1815 |
+
Parameters
|
| 1816 |
+
==========
|
| 1817 |
+
|
| 1818 |
+
expr: RandomIndexedSymbol, Relational, Logic
|
| 1819 |
+
Condition for which expectation has to be computed. Must
|
| 1820 |
+
contain a RandomIndexedSymbol of the process.
|
| 1821 |
+
condition: Relational, Logic
|
| 1822 |
+
The given conditions under which computations should be done.
|
| 1823 |
+
|
| 1824 |
+
Returns
|
| 1825 |
+
=======
|
| 1826 |
+
|
| 1827 |
+
Expectation of the RandomIndexedSymbol.
|
| 1828 |
+
|
| 1829 |
+
"""
|
| 1830 |
+
new_expr, new_condition = self._rvindexed_subs(expr, condition)
|
| 1831 |
+
|
| 1832 |
+
if not is_random(new_expr):
|
| 1833 |
+
return new_expr
|
| 1834 |
+
new_pspace = pspace(new_expr)
|
| 1835 |
+
if new_condition is not None:
|
| 1836 |
+
new_expr = given(new_expr, new_condition)
|
| 1837 |
+
if new_expr.is_Add: # As E is Linear
|
| 1838 |
+
return Add(*[new_pspace.compute_expectation(
|
| 1839 |
+
expr=arg, evaluate=evaluate, **kwargs)
|
| 1840 |
+
for arg in new_expr.args])
|
| 1841 |
+
return new_pspace.compute_expectation(
|
| 1842 |
+
new_expr, evaluate=evaluate, **kwargs)
|
| 1843 |
+
|
| 1844 |
+
@classmethod
|
| 1845 |
+
def _probability(self, condition, given_condition=None, evaluate=True, **kwargs):
|
| 1846 |
+
"""
|
| 1847 |
+
Internal method for computing probability of indexed RV
|
| 1848 |
+
|
| 1849 |
+
Parameters
|
| 1850 |
+
==========
|
| 1851 |
+
|
| 1852 |
+
condition: Relational
|
| 1853 |
+
Condition for which probability has to be computed. Must
|
| 1854 |
+
contain a RandomIndexedSymbol of the process.
|
| 1855 |
+
given_condition: Relational/And
|
| 1856 |
+
The given conditions under which computations should be done.
|
| 1857 |
+
|
| 1858 |
+
Returns
|
| 1859 |
+
=======
|
| 1860 |
+
|
| 1861 |
+
Probability of the condition.
|
| 1862 |
+
|
| 1863 |
+
"""
|
| 1864 |
+
new_condition, new_givencondition = self._rvindexed_subs(condition, given_condition)
|
| 1865 |
+
|
| 1866 |
+
if isinstance(new_givencondition, RandomSymbol):
|
| 1867 |
+
condrv = random_symbols(new_condition)
|
| 1868 |
+
if len(condrv) == 1 and condrv[0] == new_givencondition:
|
| 1869 |
+
return BernoulliDistribution(self._probability(new_condition), 0, 1)
|
| 1870 |
+
|
| 1871 |
+
if any(dependent(rv, new_givencondition) for rv in condrv):
|
| 1872 |
+
return Probability(new_condition, new_givencondition)
|
| 1873 |
+
else:
|
| 1874 |
+
return self._probability(new_condition)
|
| 1875 |
+
|
| 1876 |
+
if new_givencondition is not None and \
|
| 1877 |
+
not isinstance(new_givencondition, (Relational, Boolean)):
|
| 1878 |
+
raise ValueError("%s is not a relational or combination of relationals"
|
| 1879 |
+
% (new_givencondition))
|
| 1880 |
+
if new_givencondition == False or new_condition == False:
|
| 1881 |
+
return S.Zero
|
| 1882 |
+
if new_condition == True:
|
| 1883 |
+
return S.One
|
| 1884 |
+
if not isinstance(new_condition, (Relational, Boolean)):
|
| 1885 |
+
raise ValueError("%s is not a relational or combination of relationals"
|
| 1886 |
+
% (new_condition))
|
| 1887 |
+
|
| 1888 |
+
if new_givencondition is not None: # If there is a condition
|
| 1889 |
+
# Recompute on new conditional expr
|
| 1890 |
+
return self._probability(given(new_condition, new_givencondition, **kwargs), **kwargs)
|
| 1891 |
+
result = pspace(new_condition).probability(new_condition, **kwargs)
|
| 1892 |
+
if evaluate and hasattr(result, 'doit'):
|
| 1893 |
+
return result.doit()
|
| 1894 |
+
else:
|
| 1895 |
+
return result
|
| 1896 |
+
|
| 1897 |
+
def get_timerv_swaps(expr, condition):
|
| 1898 |
+
"""
|
| 1899 |
+
Finds the appropriate interval for each time stamp in expr by parsing
|
| 1900 |
+
the given condition and returns intervals for each timestamp and
|
| 1901 |
+
dictionary that maps variable time-stamped Random Indexed Symbol to its
|
| 1902 |
+
corresponding Random Indexed variable with fixed time stamp.
|
| 1903 |
+
|
| 1904 |
+
Parameters
|
| 1905 |
+
==========
|
| 1906 |
+
|
| 1907 |
+
expr: SymPy Expression
|
| 1908 |
+
Expression containing Random Indexed Symbols with variable time stamps
|
| 1909 |
+
condition: Relational/Boolean Expression
|
| 1910 |
+
Expression containing time bounds of variable time stamps in expr
|
| 1911 |
+
|
| 1912 |
+
Examples
|
| 1913 |
+
========
|
| 1914 |
+
|
| 1915 |
+
>>> from sympy.stats.stochastic_process_types import get_timerv_swaps, PoissonProcess
|
| 1916 |
+
>>> from sympy import symbols, Contains, Interval
|
| 1917 |
+
>>> x, t, d = symbols('x t d', positive=True)
|
| 1918 |
+
>>> X = PoissonProcess("X", 3)
|
| 1919 |
+
>>> get_timerv_swaps(x*X(t), Contains(t, Interval.Lopen(0, 1)))
|
| 1920 |
+
([Interval.Lopen(0, 1)], {X(t): X(1)})
|
| 1921 |
+
>>> get_timerv_swaps((X(t)**2 + X(d)**2), Contains(t, Interval.Lopen(0, 1))
|
| 1922 |
+
... & Contains(d, Interval.Ropen(1, 4))) # doctest: +SKIP
|
| 1923 |
+
([Interval.Ropen(1, 4), Interval.Lopen(0, 1)], {X(d): X(3), X(t): X(1)})
|
| 1924 |
+
|
| 1925 |
+
Returns
|
| 1926 |
+
=======
|
| 1927 |
+
|
| 1928 |
+
intervals: list
|
| 1929 |
+
List of Intervals/FiniteSet on which each time stamp is defined
|
| 1930 |
+
rv_swap: dict
|
| 1931 |
+
Dictionary mapping variable time Random Indexed Symbol to constant time
|
| 1932 |
+
Random Indexed Variable
|
| 1933 |
+
|
| 1934 |
+
"""
|
| 1935 |
+
|
| 1936 |
+
if not isinstance(condition, (Relational, Boolean)):
|
| 1937 |
+
raise ValueError("%s is not a relational or combination of relationals"
|
| 1938 |
+
% (condition))
|
| 1939 |
+
expr_syms = list(expr.atoms(RandomIndexedSymbol))
|
| 1940 |
+
if isinstance(condition, (And, Or)):
|
| 1941 |
+
given_cond_args = condition.args
|
| 1942 |
+
else: # single condition
|
| 1943 |
+
given_cond_args = (condition, )
|
| 1944 |
+
rv_swap = {}
|
| 1945 |
+
intervals = []
|
| 1946 |
+
for expr_sym in expr_syms:
|
| 1947 |
+
for arg in given_cond_args:
|
| 1948 |
+
if arg.has(expr_sym.key) and isinstance(expr_sym.key, Symbol):
|
| 1949 |
+
intv = _set_converter(arg.args[1])
|
| 1950 |
+
diff_key = intv._sup - intv._inf
|
| 1951 |
+
if diff_key == oo:
|
| 1952 |
+
raise ValueError("%s should have finite bounds" % str(expr_sym.name))
|
| 1953 |
+
elif diff_key == S.Zero: # has singleton set
|
| 1954 |
+
diff_key = intv._sup
|
| 1955 |
+
rv_swap[expr_sym] = expr_sym.subs({expr_sym.key: diff_key})
|
| 1956 |
+
intervals.append(intv)
|
| 1957 |
+
return intervals, rv_swap
|
| 1958 |
+
|
| 1959 |
+
|
| 1960 |
+
class CountingProcess(ContinuousTimeStochasticProcess):
|
| 1961 |
+
"""
|
| 1962 |
+
This class handles the common methods of the Counting Processes
|
| 1963 |
+
such as Poisson, Wiener and Gamma Processes
|
| 1964 |
+
"""
|
| 1965 |
+
index_set = _set_converter(Interval(0, oo))
|
| 1966 |
+
|
| 1967 |
+
@property
|
| 1968 |
+
def symbol(self):
|
| 1969 |
+
return self.args[0]
|
| 1970 |
+
|
| 1971 |
+
def expectation(self, expr, condition=None, evaluate=True, **kwargs):
|
| 1972 |
+
"""
|
| 1973 |
+
Computes expectation
|
| 1974 |
+
|
| 1975 |
+
Parameters
|
| 1976 |
+
==========
|
| 1977 |
+
|
| 1978 |
+
expr: RandomIndexedSymbol, Relational, Logic
|
| 1979 |
+
Condition for which expectation has to be computed. Must
|
| 1980 |
+
contain a RandomIndexedSymbol of the process.
|
| 1981 |
+
condition: Relational, Boolean
|
| 1982 |
+
The given conditions under which computations should be done, i.e,
|
| 1983 |
+
the intervals on which each variable time stamp in expr is defined
|
| 1984 |
+
|
| 1985 |
+
Returns
|
| 1986 |
+
=======
|
| 1987 |
+
|
| 1988 |
+
Expectation of the given expr
|
| 1989 |
+
|
| 1990 |
+
"""
|
| 1991 |
+
if condition is not None:
|
| 1992 |
+
intervals, rv_swap = get_timerv_swaps(expr, condition)
|
| 1993 |
+
# they are independent when they have non-overlapping intervals
|
| 1994 |
+
if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet
|
| 1995 |
+
for intv_comb in itertools.combinations(intervals, 2)):
|
| 1996 |
+
if expr.is_Add:
|
| 1997 |
+
return Add.fromiter(self.expectation(arg, condition)
|
| 1998 |
+
for arg in expr.args)
|
| 1999 |
+
expr = expr.subs(rv_swap)
|
| 2000 |
+
else:
|
| 2001 |
+
return Expectation(expr, condition)
|
| 2002 |
+
|
| 2003 |
+
return _SubstituteRV._expectation(expr, evaluate=evaluate, **kwargs)
|
| 2004 |
+
|
| 2005 |
+
def _solve_argwith_tworvs(self, arg):
|
| 2006 |
+
if arg.args[0].key >= arg.args[1].key or isinstance(arg, Eq):
|
| 2007 |
+
diff_key = abs(arg.args[0].key - arg.args[1].key)
|
| 2008 |
+
rv = arg.args[0]
|
| 2009 |
+
arg = arg.__class__(rv.pspace.process(diff_key), 0)
|
| 2010 |
+
else:
|
| 2011 |
+
diff_key = arg.args[1].key - arg.args[0].key
|
| 2012 |
+
rv = arg.args[1]
|
| 2013 |
+
arg = arg.__class__(rv.pspace.process(diff_key), 0)
|
| 2014 |
+
return arg
|
| 2015 |
+
|
| 2016 |
+
def _solve_numerical(self, condition, given_condition=None):
|
| 2017 |
+
if isinstance(condition, And):
|
| 2018 |
+
args_list = list(condition.args)
|
| 2019 |
+
else:
|
| 2020 |
+
args_list = [condition]
|
| 2021 |
+
if given_condition is not None:
|
| 2022 |
+
if isinstance(given_condition, And):
|
| 2023 |
+
args_list.extend(list(given_condition.args))
|
| 2024 |
+
else:
|
| 2025 |
+
args_list.extend([given_condition])
|
| 2026 |
+
# sort the args based on timestamp to get the independent increments in
|
| 2027 |
+
# each segment using all the condition args as well as given_condition args
|
| 2028 |
+
args_list = sorted(args_list, key=lambda x: x.args[0].key)
|
| 2029 |
+
result = []
|
| 2030 |
+
cond_args = list(condition.args) if isinstance(condition, And) else [condition]
|
| 2031 |
+
if args_list[0] in cond_args and not (is_random(args_list[0].args[0])
|
| 2032 |
+
and is_random(args_list[0].args[1])):
|
| 2033 |
+
result.append(_SubstituteRV._probability(args_list[0]))
|
| 2034 |
+
|
| 2035 |
+
if is_random(args_list[0].args[0]) and is_random(args_list[0].args[1]):
|
| 2036 |
+
arg = self._solve_argwith_tworvs(args_list[0])
|
| 2037 |
+
result.append(_SubstituteRV._probability(arg))
|
| 2038 |
+
|
| 2039 |
+
for i in range(len(args_list) - 1):
|
| 2040 |
+
curr, nex = args_list[i], args_list[i + 1]
|
| 2041 |
+
diff_key = nex.args[0].key - curr.args[0].key
|
| 2042 |
+
working_set = curr.args[0].pspace.process.state_space
|
| 2043 |
+
if curr.args[1] > nex.args[1]: #impossible condition so return 0
|
| 2044 |
+
result.append(0)
|
| 2045 |
+
break
|
| 2046 |
+
if isinstance(curr, Eq):
|
| 2047 |
+
working_set = Intersection(working_set, Interval.Lopen(curr.args[1], oo))
|
| 2048 |
+
else:
|
| 2049 |
+
working_set = Intersection(working_set, curr.as_set())
|
| 2050 |
+
if isinstance(nex, Eq):
|
| 2051 |
+
working_set = Intersection(working_set, Interval(-oo, nex.args[1]))
|
| 2052 |
+
else:
|
| 2053 |
+
working_set = Intersection(working_set, nex.as_set())
|
| 2054 |
+
if working_set == EmptySet:
|
| 2055 |
+
rv = Eq(curr.args[0].pspace.process(diff_key), 0)
|
| 2056 |
+
result.append(_SubstituteRV._probability(rv))
|
| 2057 |
+
else:
|
| 2058 |
+
if working_set.is_finite_set:
|
| 2059 |
+
if isinstance(curr, Eq) and isinstance(nex, Eq):
|
| 2060 |
+
rv = Eq(curr.args[0].pspace.process(diff_key), len(working_set))
|
| 2061 |
+
result.append(_SubstituteRV._probability(rv))
|
| 2062 |
+
elif isinstance(curr, Eq) ^ isinstance(nex, Eq):
|
| 2063 |
+
result.append(Add.fromiter(_SubstituteRV._probability(Eq(
|
| 2064 |
+
curr.args[0].pspace.process(diff_key), x))
|
| 2065 |
+
for x in range(len(working_set))))
|
| 2066 |
+
else:
|
| 2067 |
+
n = len(working_set)
|
| 2068 |
+
result.append(Add.fromiter((n - x)*_SubstituteRV._probability(Eq(
|
| 2069 |
+
curr.args[0].pspace.process(diff_key), x)) for x in range(n)))
|
| 2070 |
+
else:
|
| 2071 |
+
result.append(_SubstituteRV._probability(
|
| 2072 |
+
curr.args[0].pspace.process(diff_key) <= working_set._sup - working_set._inf))
|
| 2073 |
+
return Mul.fromiter(result)
|
| 2074 |
+
|
| 2075 |
+
|
| 2076 |
+
def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
|
| 2077 |
+
"""
|
| 2078 |
+
Computes probability.
|
| 2079 |
+
|
| 2080 |
+
Parameters
|
| 2081 |
+
==========
|
| 2082 |
+
|
| 2083 |
+
condition: Relational
|
| 2084 |
+
Condition for which probability has to be computed. Must
|
| 2085 |
+
contain a RandomIndexedSymbol of the process.
|
| 2086 |
+
given_condition: Relational, Boolean
|
| 2087 |
+
The given conditions under which computations should be done, i.e,
|
| 2088 |
+
the intervals on which each variable time stamp in expr is defined
|
| 2089 |
+
|
| 2090 |
+
Returns
|
| 2091 |
+
=======
|
| 2092 |
+
|
| 2093 |
+
Probability of the condition
|
| 2094 |
+
|
| 2095 |
+
"""
|
| 2096 |
+
check_numeric = True
|
| 2097 |
+
if isinstance(condition, (And, Or)):
|
| 2098 |
+
cond_args = condition.args
|
| 2099 |
+
else:
|
| 2100 |
+
cond_args = (condition, )
|
| 2101 |
+
# check that condition args are numeric or not
|
| 2102 |
+
if not all(arg.args[0].key.is_number for arg in cond_args):
|
| 2103 |
+
check_numeric = False
|
| 2104 |
+
if given_condition is not None:
|
| 2105 |
+
check_given_numeric = True
|
| 2106 |
+
if isinstance(given_condition, (And, Or)):
|
| 2107 |
+
given_cond_args = given_condition.args
|
| 2108 |
+
else:
|
| 2109 |
+
given_cond_args = (given_condition, )
|
| 2110 |
+
# check that given condition args are numeric or not
|
| 2111 |
+
if given_condition.has(Contains):
|
| 2112 |
+
check_given_numeric = False
|
| 2113 |
+
# Handle numerical queries
|
| 2114 |
+
if check_numeric and check_given_numeric:
|
| 2115 |
+
res = []
|
| 2116 |
+
if isinstance(condition, Or):
|
| 2117 |
+
res.append(Add.fromiter(self._solve_numerical(arg, given_condition)
|
| 2118 |
+
for arg in condition.args))
|
| 2119 |
+
if isinstance(given_condition, Or):
|
| 2120 |
+
res.append(Add.fromiter(self._solve_numerical(condition, arg)
|
| 2121 |
+
for arg in given_condition.args))
|
| 2122 |
+
if res:
|
| 2123 |
+
return Add.fromiter(res)
|
| 2124 |
+
return self._solve_numerical(condition, given_condition)
|
| 2125 |
+
|
| 2126 |
+
# No numeric queries, go by Contains?... then check that all the
|
| 2127 |
+
# given condition are in form of `Contains`
|
| 2128 |
+
if not all(arg.has(Contains) for arg in given_cond_args):
|
| 2129 |
+
raise ValueError("If given condition is passed with `Contains`, then "
|
| 2130 |
+
"please pass the evaluated condition with its corresponding information "
|
| 2131 |
+
"in terms of intervals of each time stamp to be passed in given condition.")
|
| 2132 |
+
|
| 2133 |
+
intervals, rv_swap = get_timerv_swaps(condition, given_condition)
|
| 2134 |
+
# they are independent when they have non-overlapping intervals
|
| 2135 |
+
if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet
|
| 2136 |
+
for intv_comb in itertools.combinations(intervals, 2)):
|
| 2137 |
+
if isinstance(condition, And):
|
| 2138 |
+
return Mul.fromiter(self.probability(arg, given_condition)
|
| 2139 |
+
for arg in condition.args)
|
| 2140 |
+
elif isinstance(condition, Or):
|
| 2141 |
+
return Add.fromiter(self.probability(arg, given_condition)
|
| 2142 |
+
for arg in condition.args)
|
| 2143 |
+
condition = condition.subs(rv_swap)
|
| 2144 |
+
else:
|
| 2145 |
+
return Probability(condition, given_condition)
|
| 2146 |
+
if check_numeric:
|
| 2147 |
+
return self._solve_numerical(condition)
|
| 2148 |
+
return _SubstituteRV._probability(condition, evaluate=evaluate, **kwargs)
|
| 2149 |
+
|
| 2150 |
+
class PoissonProcess(CountingProcess):
|
| 2151 |
+
"""
|
| 2152 |
+
The Poisson process is a counting process. It is usually used in scenarios
|
| 2153 |
+
where we are counting the occurrences of certain events that appear
|
| 2154 |
+
to happen at a certain rate, but completely at random.
|
| 2155 |
+
|
| 2156 |
+
Parameters
|
| 2157 |
+
==========
|
| 2158 |
+
|
| 2159 |
+
sym : Symbol/str
|
| 2160 |
+
lamda : Positive number
|
| 2161 |
+
Rate of the process, ``lambda > 0``
|
| 2162 |
+
|
| 2163 |
+
Examples
|
| 2164 |
+
========
|
| 2165 |
+
|
| 2166 |
+
>>> from sympy.stats import PoissonProcess, P, E
|
| 2167 |
+
>>> from sympy import symbols, Eq, Ne, Contains, Interval
|
| 2168 |
+
>>> X = PoissonProcess("X", lamda=3)
|
| 2169 |
+
>>> X.state_space
|
| 2170 |
+
Naturals0
|
| 2171 |
+
>>> X.lamda
|
| 2172 |
+
3
|
| 2173 |
+
>>> t1, t2 = symbols('t1 t2', positive=True)
|
| 2174 |
+
>>> P(X(t1) < 4)
|
| 2175 |
+
(9*t1**3/2 + 9*t1**2/2 + 3*t1 + 1)*exp(-3*t1)
|
| 2176 |
+
>>> P(Eq(X(t1), 2) | Ne(X(t1), 4), Contains(t1, Interval.Ropen(2, 4)))
|
| 2177 |
+
1 - 36*exp(-6)
|
| 2178 |
+
>>> P(Eq(X(t1), 2) & Eq(X(t2), 3), Contains(t1, Interval.Lopen(0, 2))
|
| 2179 |
+
... & Contains(t2, Interval.Lopen(2, 4)))
|
| 2180 |
+
648*exp(-12)
|
| 2181 |
+
>>> E(X(t1))
|
| 2182 |
+
3*t1
|
| 2183 |
+
>>> E(X(t1)**2 + 2*X(t2), Contains(t1, Interval.Lopen(0, 1))
|
| 2184 |
+
... & Contains(t2, Interval.Lopen(1, 2)))
|
| 2185 |
+
18
|
| 2186 |
+
>>> P(X(3) < 1, Eq(X(1), 0))
|
| 2187 |
+
exp(-6)
|
| 2188 |
+
>>> P(Eq(X(4), 3), Eq(X(2), 3))
|
| 2189 |
+
exp(-6)
|
| 2190 |
+
>>> P(X(2) <= 3, X(1) > 1)
|
| 2191 |
+
5*exp(-3)
|
| 2192 |
+
|
| 2193 |
+
Merging two Poisson Processes
|
| 2194 |
+
|
| 2195 |
+
>>> Y = PoissonProcess("Y", lamda=4)
|
| 2196 |
+
>>> Z = X + Y
|
| 2197 |
+
>>> Z.lamda
|
| 2198 |
+
7
|
| 2199 |
+
|
| 2200 |
+
Splitting a Poisson Process into two independent Poisson Processes
|
| 2201 |
+
|
| 2202 |
+
>>> N, M = Z.split(l1=2, l2=5)
|
| 2203 |
+
>>> N.lamda, M.lamda
|
| 2204 |
+
(2, 5)
|
| 2205 |
+
|
| 2206 |
+
References
|
| 2207 |
+
==========
|
| 2208 |
+
|
| 2209 |
+
.. [1] https://www.probabilitycourse.com/chapter11/11_0_0_intro.php
|
| 2210 |
+
.. [2] https://en.wikipedia.org/wiki/Poisson_point_process
|
| 2211 |
+
|
| 2212 |
+
"""
|
| 2213 |
+
|
| 2214 |
+
def __new__(cls, sym, lamda):
|
| 2215 |
+
_value_check(lamda > 0, 'lamda should be a positive number.')
|
| 2216 |
+
sym = _symbol_converter(sym)
|
| 2217 |
+
lamda = _sympify(lamda)
|
| 2218 |
+
return Basic.__new__(cls, sym, lamda)
|
| 2219 |
+
|
| 2220 |
+
@property
|
| 2221 |
+
def lamda(self):
|
| 2222 |
+
return self.args[1]
|
| 2223 |
+
|
| 2224 |
+
@property
|
| 2225 |
+
def state_space(self):
|
| 2226 |
+
return S.Naturals0
|
| 2227 |
+
|
| 2228 |
+
def distribution(self, key):
|
| 2229 |
+
if isinstance(key, RandomIndexedSymbol):
|
| 2230 |
+
self._deprecation_warn_distribution()
|
| 2231 |
+
return PoissonDistribution(self.lamda*key.key)
|
| 2232 |
+
return PoissonDistribution(self.lamda*key)
|
| 2233 |
+
|
| 2234 |
+
def density(self, x):
|
| 2235 |
+
return (self.lamda*x.key)**x / factorial(x) * exp(-(self.lamda*x.key))
|
| 2236 |
+
|
| 2237 |
+
def simple_rv(self, rv):
|
| 2238 |
+
return Poisson(rv.name, lamda=self.lamda*rv.key)
|
| 2239 |
+
|
| 2240 |
+
def __add__(self, other):
|
| 2241 |
+
if not isinstance(other, PoissonProcess):
|
| 2242 |
+
raise ValueError("Only instances of Poisson Process can be merged")
|
| 2243 |
+
return PoissonProcess(Dummy(self.symbol.name + other.symbol.name),
|
| 2244 |
+
self.lamda + other.lamda)
|
| 2245 |
+
|
| 2246 |
+
def split(self, l1, l2):
|
| 2247 |
+
if _sympify(l1 + l2) != self.lamda:
|
| 2248 |
+
raise ValueError("Sum of l1 and l2 should be %s" % str(self.lamda))
|
| 2249 |
+
return PoissonProcess(Dummy("l1"), l1), PoissonProcess(Dummy("l2"), l2)
|
| 2250 |
+
|
| 2251 |
+
class WienerProcess(CountingProcess):
|
| 2252 |
+
"""
|
| 2253 |
+
The Wiener process is a real valued continuous-time stochastic process.
|
| 2254 |
+
In physics it is used to study Brownian motion and it is often also called
|
| 2255 |
+
Brownian motion due to its historical connection with physical process of the
|
| 2256 |
+
same name originally observed by Scottish botanist Robert Brown.
|
| 2257 |
+
|
| 2258 |
+
Parameters
|
| 2259 |
+
==========
|
| 2260 |
+
|
| 2261 |
+
sym : Symbol/str
|
| 2262 |
+
|
| 2263 |
+
Examples
|
| 2264 |
+
========
|
| 2265 |
+
|
| 2266 |
+
>>> from sympy.stats import WienerProcess, P, E
|
| 2267 |
+
>>> from sympy import symbols, Contains, Interval
|
| 2268 |
+
>>> X = WienerProcess("X")
|
| 2269 |
+
>>> X.state_space
|
| 2270 |
+
Reals
|
| 2271 |
+
>>> t1, t2 = symbols('t1 t2', positive=True)
|
| 2272 |
+
>>> P(X(t1) < 7).simplify()
|
| 2273 |
+
erf(7*sqrt(2)/(2*sqrt(t1)))/2 + 1/2
|
| 2274 |
+
>>> P((X(t1) > 2) | (X(t1) < 4), Contains(t1, Interval.Ropen(2, 4))).simplify()
|
| 2275 |
+
-erf(1)/2 + erf(2)/2 + 1
|
| 2276 |
+
>>> E(X(t1))
|
| 2277 |
+
0
|
| 2278 |
+
>>> E(X(t1) + 2*X(t2), Contains(t1, Interval.Lopen(0, 1))
|
| 2279 |
+
... & Contains(t2, Interval.Lopen(1, 2)))
|
| 2280 |
+
0
|
| 2281 |
+
|
| 2282 |
+
References
|
| 2283 |
+
==========
|
| 2284 |
+
|
| 2285 |
+
.. [1] https://www.probabilitycourse.com/chapter11/11_4_0_brownian_motion_wiener_process.php
|
| 2286 |
+
.. [2] https://en.wikipedia.org/wiki/Wiener_process
|
| 2287 |
+
|
| 2288 |
+
"""
|
| 2289 |
+
def __new__(cls, sym):
|
| 2290 |
+
sym = _symbol_converter(sym)
|
| 2291 |
+
return Basic.__new__(cls, sym)
|
| 2292 |
+
|
| 2293 |
+
@property
|
| 2294 |
+
def state_space(self):
|
| 2295 |
+
return S.Reals
|
| 2296 |
+
|
| 2297 |
+
def distribution(self, key):
|
| 2298 |
+
if isinstance(key, RandomIndexedSymbol):
|
| 2299 |
+
self._deprecation_warn_distribution()
|
| 2300 |
+
return NormalDistribution(0, sqrt(key.key))
|
| 2301 |
+
return NormalDistribution(0, sqrt(key))
|
| 2302 |
+
|
| 2303 |
+
def density(self, x):
|
| 2304 |
+
return exp(-x**2/(2*x.key)) / (sqrt(2*pi)*sqrt(x.key))
|
| 2305 |
+
|
| 2306 |
+
def simple_rv(self, rv):
|
| 2307 |
+
return Normal(rv.name, 0, sqrt(rv.key))
|
| 2308 |
+
|
| 2309 |
+
|
| 2310 |
+
class GammaProcess(CountingProcess):
|
| 2311 |
+
r"""
|
| 2312 |
+
A Gamma process is a random process with independent gamma distributed
|
| 2313 |
+
increments. It is a pure-jump increasing Levy process.
|
| 2314 |
+
|
| 2315 |
+
Parameters
|
| 2316 |
+
==========
|
| 2317 |
+
|
| 2318 |
+
sym : Symbol/str
|
| 2319 |
+
lamda : Positive number
|
| 2320 |
+
Jump size of the process, ``lamda > 0``
|
| 2321 |
+
gamma : Positive number
|
| 2322 |
+
Rate of jump arrivals, `\gamma > 0`
|
| 2323 |
+
|
| 2324 |
+
Examples
|
| 2325 |
+
========
|
| 2326 |
+
|
| 2327 |
+
>>> from sympy.stats import GammaProcess, E, P, variance
|
| 2328 |
+
>>> from sympy import symbols, Contains, Interval, Not
|
| 2329 |
+
>>> t, d, x, l, g = symbols('t d x l g', positive=True)
|
| 2330 |
+
>>> X = GammaProcess("X", l, g)
|
| 2331 |
+
>>> E(X(t))
|
| 2332 |
+
g*t/l
|
| 2333 |
+
>>> variance(X(t)).simplify()
|
| 2334 |
+
g*t/l**2
|
| 2335 |
+
>>> X = GammaProcess('X', 1, 2)
|
| 2336 |
+
>>> P(X(t) < 1).simplify()
|
| 2337 |
+
lowergamma(2*t, 1)/gamma(2*t)
|
| 2338 |
+
>>> P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) &
|
| 2339 |
+
... Contains(d, Interval.Lopen(7, 8))).simplify()
|
| 2340 |
+
-4*exp(-3) + 472*exp(-8)/3 + 1
|
| 2341 |
+
>>> E(X(2) + x*E(X(5)))
|
| 2342 |
+
10*x + 4
|
| 2343 |
+
|
| 2344 |
+
References
|
| 2345 |
+
==========
|
| 2346 |
+
|
| 2347 |
+
.. [1] https://en.wikipedia.org/wiki/Gamma_process
|
| 2348 |
+
|
| 2349 |
+
"""
|
| 2350 |
+
def __new__(cls, sym, lamda, gamma):
|
| 2351 |
+
_value_check(lamda > 0, 'lamda should be a positive number')
|
| 2352 |
+
_value_check(gamma > 0, 'gamma should be a positive number')
|
| 2353 |
+
sym = _symbol_converter(sym)
|
| 2354 |
+
gamma = _sympify(gamma)
|
| 2355 |
+
lamda = _sympify(lamda)
|
| 2356 |
+
return Basic.__new__(cls, sym, lamda, gamma)
|
| 2357 |
+
|
| 2358 |
+
@property
|
| 2359 |
+
def lamda(self):
|
| 2360 |
+
return self.args[1]
|
| 2361 |
+
|
| 2362 |
+
@property
|
| 2363 |
+
def gamma(self):
|
| 2364 |
+
return self.args[2]
|
| 2365 |
+
|
| 2366 |
+
@property
|
| 2367 |
+
def state_space(self):
|
| 2368 |
+
return _set_converter(Interval(0, oo))
|
| 2369 |
+
|
| 2370 |
+
def distribution(self, key):
|
| 2371 |
+
if isinstance(key, RandomIndexedSymbol):
|
| 2372 |
+
self._deprecation_warn_distribution()
|
| 2373 |
+
return GammaDistribution(self.gamma*key.key, 1/self.lamda)
|
| 2374 |
+
return GammaDistribution(self.gamma*key, 1/self.lamda)
|
| 2375 |
+
|
| 2376 |
+
def density(self, x):
|
| 2377 |
+
k = self.gamma*x.key
|
| 2378 |
+
theta = 1/self.lamda
|
| 2379 |
+
return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k)
|
| 2380 |
+
|
| 2381 |
+
def simple_rv(self, rv):
|
| 2382 |
+
return Gamma(rv.name, self.gamma*rv.key, 1/self.lamda)
|