Publish 11 evaluated Astra histories with reproducible checkpoint artifacts (part 35)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +36 -0
- shared/package-files/ab/ab29fb90fe5bd78332c2da8e50be42f8d3af8dfdaa2b83ec5c6a42bea9a8fb81/blob +14 -0
- shared/package-files/ab/ab2d0f9637b9209bafb020637a32728430a310075c0cb2bfd9a81571ec7c67a5/blob +1 -0
- shared/package-files/ab/ab2f91050f5a4ea97e09dce3855f7e6c2d1e6b1153dbb2adab14d0f089137260/blob +3 -0
- shared/package-files/ab/ab31b0b56d7242624b62e8303f0ea97af46656dc5820e3fe5228ab2e22e11ed8/blob +30 -0
- shared/package-files/ab/ab33bc51cb9f5ab60c758444206dc7d2bbad93ddb61bede0b82e33349a161652/blob +92 -0
- shared/package-files/ab/ab34cb487f0fbc0918d5fafa410daf57e2b013f33cdf0757ba0b6925a3ff01b3/blob +13 -0
- shared/package-files/ab/ab370113df1c83c4f1e623c902f4383dd7f6c9ce91dabfb8c86252d7f0c421e6/blob +35 -0
- shared/package-files/ab/ab371cec1a3839605762ccb229d0c9c1d4d1b2d32a075673d0688662d9dd0671/blob +0 -0
- shared/package-files/ab/ab39c873e7fe1837175fd4cd11e75998528d80dae755cb78e74bfae94c99a183/blob +0 -0
- shared/package-files/ab/ab3b9a3943b225f4cffa590cdef6419d5aac1a2623ca96eb01348cff1ee61029/model_config.json +103 -0
- shared/package-files/ab/ab3d06b221fb6fab018eb20d80fd8b3004746a4e8c93300333f1086dadba26c1/blob +28 -0
- shared/package-files/ab/ab3d3254c6f895611e3930cbfc35b3e6ee5ac261883ca02cb991495e0c0724d5/blob +1431 -0
- shared/package-files/ab/ab3f08d9f8e6a7cf2f05beaac6af33cce76ce7b8eeb5500095ed4cb58dc6e6ac/blob +223 -0
- shared/package-files/ab/ab417fe03d04b9cecfbfaebaf029e50688ab8d7f83aba38435eab9142ab76b30/blob +26 -0
- shared/package-files/ab/ab4227e437234e0e8ba80418f90d7f5a7986efee0c84606a20c0eb4aecaccfc6/blob +29 -0
- shared/package-files/ab/ab439ca41391e16cdc42a2b16f7bbe3222f1bc12dc3caea1fde39225454ea2c8/blob +2421 -0
- shared/package-files/ab/ab448355bce6538ebff267fadd46a8e69604e0c832ae147dbe7f78409a904aff/blob +220 -0
- shared/package-files/ab/ab49726ba95b3ade0752e8de7edbd368aca9ac02ad53fc1f7fdc6ae2de917513/blob +54 -0
- shared/package-files/ab/ab4aa14c3d499d41f5c5930d56d69fd453de2bd55fde554e854ca6b0cc7714fd/blob +40 -0
- shared/package-files/ab/ab4c2456e1557560999802b513b581427ca6f0f3e3dd01d0e244956ec4a9e3d9/blob +23 -0
- shared/package-files/ab/ab50bb896a6f743ca611464dcb326f64bb0bb60c12918b428b1304f9f632203c/blob +5 -0
- shared/package-files/ab/ab5117f4081cab5c6cb575d6c8dc1b24220b3e596b9d3b5206d6dbf8869b00da/blob +560 -0
- shared/package-files/ab/ab52198b90afc94a7f3cdcdb438fd72eba00576e15128bc1133d93929c1427d7/blob +35 -0
- shared/package-files/ab/ab52403333cd797da62e4ffe8f9e67511f994cda73f3597610189343d8b76ed9/blob +26 -0
- shared/package-files/ab/ab529cbf71f881a411eaca3f3fbedea299e85869b6ebdc71b8233f2cf2c2222d/blob +1797 -0
- shared/package-files/ab/ab55b88bd16e51e688c76440eeae061b30d18772afe67bd65dcf9cd491c02291/blob +369 -0
- shared/package-files/ab/ab56282cd247bfeeefd81cf577f5d21d20d08e22600777ce62a9033a1c7ee57d/blob +0 -0
- shared/package-files/ab/ab56b130b5df29e4871924951fb08229d5857ed0a2b27cfd5d3f7f84dda43aef/blob +21 -0
- shared/package-files/ab/ab5ede532a8e10ad8b25829760b089ab2963faf99a086daf48d32db6aad04d19/blob +0 -0
- shared/package-files/ab/ab5f25a53347e316db071ba8d939c0ac6007b26a168b35e3cbff28e65e1fa81e/blob +319 -0
- shared/package-files/ab/ab62247474c5955df8aab42590e2f5049ae8b06fb86b5d2fc410dcc9047f8878/blob +65 -0
- shared/package-files/ab/ab6258127aa652aefcacef27a3d857419ddf73746ec4fad109ca6c2ebba8bc38/blob +48 -0
- shared/package-files/ab/ab656e5e6759a61c81d95347eaa4a70cc59262878f291b267e08ba5b4f675f7d/blob +3 -0
- shared/package-files/ab/ab66eadd51f995801fcc342cf4fe5c1342aabe3717af7580a881db52b30d63dc/blob +1377 -0
- shared/package-files/ab/ab671946216f6a0c7f00e0f593412d2c1b877f892f6cb42995861951d42b7657/blob +24 -0
- shared/package-files/ab/ab6a5deb5604bd1668a4b19842ba41375b0437020bb288457d4fe439821f3a34/blob +53 -0
- shared/package-files/ab/ab70fd0cb7e64c1500a3860c9cd50d5142ab024292c0ce50faf7ac77d03a4994/blob +0 -0
- shared/package-files/ab/ab72fb26cf95c7c869bb1c0c8bd6073bad2dfecb256be43acb83c3e75280c996/blob +20 -0
- shared/package-files/ab/ab773b1096807853dd50e55e1ceb05da30403097134e233b131eddb41eb4cc68/blob +488 -0
- shared/package-files/ab/ab77953666d62461bf4b40e2b7f4b7028f2a42acffe4f6135c500a0597b9cabe/blob +61 -0
- shared/package-files/ab/ab77a1488a2dd4667a4f23072236e0d2845fe208405eec1b4834985629ba7af8/blob +0 -0
- shared/package-files/ab/ab78926242b393e09aeb37854f11cce2160cafce02ef713e4aac341abed9b040/blob +165 -0
- shared/package-files/ab/ab795b429201a5bb575c6370d5e17090dfcfc317431aa9382f8e881366f43357/blob +0 -0
- shared/package-files/ab/ab7c6a6fe1688a764fa48f8e18e5ebb9f150f19e8df09877d52646e5418bc246/blob +3 -0
- shared/package-files/ab/ab7d4f29bebab1fba0832f9ae0d21c962f42822ca882f5a259d12d075cc23f4b/blob +24 -0
- shared/package-files/ab/ab8132b2d6593d5b283f739c1e70e355b020d885801bf432b28d79dd7800616f/blob +28 -0
- shared/package-files/ab/ab816ed7d7cb7eef4c238da27270f883543bdd06a9bf38f7d039e244486f276e/blob +874 -0
- shared/package-files/ab/ab82d8897c5fc1651cd62a38bd1541afdbb131a71f75e7cfbdc4656f74ce127c/blob +66 -0
- shared/package-files/ab/ab837b032c5aae84503fc0c733a116a26fd272e90dc4402fa68d3c9e51aed3b0/blob +21 -0
.gitattributes
CHANGED
|
@@ -777,3 +777,39 @@ shared/package-files/a9/a9d8cb904b2e9c8e9050b9a5c6fbaa23ed1787b4d05f11652e384045
|
|
| 777 |
shared/package-files/a9/a9e6b812a5a9ffe44a8962c3fd10fa53679fbc5952bd02abf02c55d7d73c4aad/blob filter=lfs diff=lfs merge=lfs -text
|
| 778 |
shared/package-files/aa/aa4b82cca13d02f1f088c9e02e13af5151df9af92fe788b9fe2a36ce9dc808cd/blob filter=lfs diff=lfs merge=lfs -text
|
| 779 |
shared/package-files/ab/ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db/blob filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 777 |
shared/package-files/a9/a9e6b812a5a9ffe44a8962c3fd10fa53679fbc5952bd02abf02c55d7d73c4aad/blob filter=lfs diff=lfs merge=lfs -text
|
| 778 |
shared/package-files/aa/aa4b82cca13d02f1f088c9e02e13af5151df9af92fe788b9fe2a36ce9dc808cd/blob filter=lfs diff=lfs merge=lfs -text
|
| 779 |
shared/package-files/ab/ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db/blob filter=lfs diff=lfs merge=lfs -text
|
| 780 |
+
shared/package-files/ab/ab2f91050f5a4ea97e09dce3855f7e6c2d1e6b1153dbb2adab14d0f089137260/blob filter=lfs diff=lfs merge=lfs -text
|
| 781 |
+
shared/package-files/ab/ab656e5e6759a61c81d95347eaa4a70cc59262878f291b267e08ba5b4f675f7d/blob filter=lfs diff=lfs merge=lfs -text
|
| 782 |
+
shared/package-files/ab/ab7c6a6fe1688a764fa48f8e18e5ebb9f150f19e8df09877d52646e5418bc246/blob filter=lfs diff=lfs merge=lfs -text
|
| 783 |
+
shared/package-files/ab/ab9388f413a20efd0857000f57c3921c5c7d7ebe07fc832f03f350f150423d4d/blob filter=lfs diff=lfs merge=lfs -text
|
| 784 |
+
shared/package-files/ab/abac8a45936f393a2c856af7434382b18276337c969a082c82a4f94ca716139e/blob filter=lfs diff=lfs merge=lfs -text
|
| 785 |
+
shared/package-files/ab/abd0feb59c961d9d9330d5bbe09dbc9e7b35347a8c7b2f2554813839ad590be3/blob filter=lfs diff=lfs merge=lfs -text
|
| 786 |
+
shared/package-files/ac/ac1eac9fced06aa971538f9436cbaa30e803cf37da881af3cddecdfdfced81cb/blob filter=lfs diff=lfs merge=lfs -text
|
| 787 |
+
shared/package-files/ac/ac5bd929d122652da56b9a23666429b5a52ff6a57f7620873abff4f78604ae0e/blob filter=lfs diff=lfs merge=lfs -text
|
| 788 |
+
shared/package-files/ac/ac8785903ed669a9962b7a837efb02bffeea43e9552e5b047b39505b7a583d60/blob filter=lfs diff=lfs merge=lfs -text
|
| 789 |
+
shared/package-files/ac/acc7bc91df0cedee35d24e5191cb48965806822fbfc4aea4da559f7435ab1841/blob filter=lfs diff=lfs merge=lfs -text
|
| 790 |
+
shared/package-files/ac/accac55bb262559affdbdb37a7028ff71c2679b3a74fd41e14d5d8208004e47e/blob filter=lfs diff=lfs merge=lfs -text
|
| 791 |
+
shared/package-files/ad/ad148328c5565076b4e985a41cc8498b7d82dda5a524c98b0934b9808d9cf80e/blob filter=lfs diff=lfs merge=lfs -text
|
| 792 |
+
shared/package-files/ad/adc4278e12e6f397b91bd3d77aa36a90c0fa73ffa7c36d4d663e27aa0d1907cb/blob filter=lfs diff=lfs merge=lfs -text
|
| 793 |
+
shared/package-files/ad/adc88690bcc3b1bfde01a3375879a78677c72e5cc331566627f47343313881a9/blob filter=lfs diff=lfs merge=lfs -text
|
| 794 |
+
shared/package-files/ad/addb6c696bc426f5a12deb1646a9c3b3286da178ef396a4a452744db3ea8c8fc/blob filter=lfs diff=lfs merge=lfs -text
|
| 795 |
+
shared/package-files/ae/ae10677466af541293ad126deba26286d35619dcb31639f00c7dc18dad5b4a13/blob filter=lfs diff=lfs merge=lfs -text
|
| 796 |
+
shared/package-files/ae/ae304da2366a5c08ae8148953dd1db095d39587c5c3d1d1d6438bfba175ce7c4/blob filter=lfs diff=lfs merge=lfs -text
|
| 797 |
+
shared/package-files/ae/ae31aa6f3c2b75e1eeb8294fec685c08941f11cf93a6e914ebb20ff43ae927c0/blob filter=lfs diff=lfs merge=lfs -text
|
| 798 |
+
shared/package-files/af/af2aaf48e18405dda1f392cbb0aa8cb8fe017e69d679caa9d9047d9aca0d0b3b/blob filter=lfs diff=lfs merge=lfs -text
|
| 799 |
+
shared/package-files/af/af90703e8c7aaddc43931e06e3ad03e5f160af9ec09c3855b3f5915b6c6f50cc/blob filter=lfs diff=lfs merge=lfs -text
|
| 800 |
+
shared/package-files/af/afab6df9a91b20a43fa0519d98436d2451711a585357caf7605a6228fac4bdc2/blob filter=lfs diff=lfs merge=lfs -text
|
| 801 |
+
shared/package-files/af/aff1358de79d3105038dfe6075853ad73ac9d0ec332f749e1b595e91fb85c13c/blob filter=lfs diff=lfs merge=lfs -text
|
| 802 |
+
shared/package-files/b0/b04b8c9d3fbcc1eb8a9db3b595659d5ed1b032e45060b8d2655405f220a8c933/blob filter=lfs diff=lfs merge=lfs -text
|
| 803 |
+
shared/package-files/b0/b05c67a1ceb3ca6f5caec89575ecad39725261fcd722f304fce8cdd2fa278999/blob filter=lfs diff=lfs merge=lfs -text
|
| 804 |
+
shared/package-files/b0/b0dcb85c17e1f35a460118de33ee035ed288899f2a982f9ec6d5a9c96525fd40/blob filter=lfs diff=lfs merge=lfs -text
|
| 805 |
+
shared/package-files/b1/b14af618690aeac35a23470fb0f8e1c3fca9f45f8d824a69d35eec4c6f1dca75/blob filter=lfs diff=lfs merge=lfs -text
|
| 806 |
+
shared/package-files/b1/b184b89e3c1075f22f6b71575b6fc20d4972b3cfd3b23322ca6fd596dcaef167/blob filter=lfs diff=lfs merge=lfs -text
|
| 807 |
+
shared/package-files/b1/b193cd7a47da341642e077b719c85e4c42efaed460527531a53a4621c9c41428/blob filter=lfs diff=lfs merge=lfs -text
|
| 808 |
+
shared/package-files/b1/b1cde583d76b3acaf6928648846f24d12e243799fd33870dcb8ba821a42e2db2/blob filter=lfs diff=lfs merge=lfs -text
|
| 809 |
+
shared/package-files/b1/b1d9c359af694c5c58042042b76dcda012f3873541ea895c03da24edda9a9847/blob filter=lfs diff=lfs merge=lfs -text
|
| 810 |
+
shared/package-files/b2/b20f2181780cdd883655488ce174a61425881ff8a2c2d3b2ebf40433fda72926/blob filter=lfs diff=lfs merge=lfs -text
|
| 811 |
+
shared/package-files/b2/b21bae3804b4066b4d1e50f4876126c01d69e72486689a726c4122476b774e33/blob filter=lfs diff=lfs merge=lfs -text
|
| 812 |
+
shared/package-files/b2/b22029d6f530c68a9737fb5394e779ffd3c221b6e53900aa84ea65429bdd18f1/blob filter=lfs diff=lfs merge=lfs -text
|
| 813 |
+
shared/package-files/b2/b2337523b68fbff0cbbed588b0a2e3e95057230f7ce0a4814ab3482738a85546/blob filter=lfs diff=lfs merge=lfs -text
|
| 814 |
+
shared/package-files/b2/b23879d49e9b2b7dd3c7ff153fa050dab48499715b971a6ff3708840d891d188/blob filter=lfs diff=lfs merge=lfs -text
|
| 815 |
+
shared/package-files/b2/b2db8e0e933034f7fe13e2cc7cc35ad58e265af8ae222af3add973045443d8f4/blob filter=lfs diff=lfs merge=lfs -text
|
shared/package-files/ab/ab29fb90fe5bd78332c2da8e50be42f8d3af8dfdaa2b83ec5c6a42bea9a8fb81/blob
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from pandas.core.dtypes.cast import dict_compat
|
| 4 |
+
|
| 5 |
+
from pandas import Timestamp
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_dict_compat():
|
| 9 |
+
data_datetime64 = {np.datetime64("1990-03-15"): 1, np.datetime64("2015-03-15"): 2}
|
| 10 |
+
data_unchanged = {1: 2, 3: 4, 5: 6}
|
| 11 |
+
expected = {Timestamp("1990-3-15"): 1, Timestamp("2015-03-15"): 2}
|
| 12 |
+
assert dict_compat(data_datetime64) == expected
|
| 13 |
+
assert dict_compat(expected) == expected
|
| 14 |
+
assert dict_compat(data_unchanged) == data_unchanged
|
shared/package-files/ab/ab2d0f9637b9209bafb020637a32728430a310075c0cb2bfd9a81571ec7c67a5/blob
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
markupsafe
|
shared/package-files/ab/ab2f91050f5a4ea97e09dce3855f7e6c2d1e6b1153dbb2adab14d0f089137260/blob
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ab2f91050f5a4ea97e09dce3855f7e6c2d1e6b1153dbb2adab14d0f089137260
|
| 3 |
+
size 24879987
|
shared/package-files/ab/ab31b0b56d7242624b62e8303f0ea97af46656dc5820e3fe5228ab2e22e11ed8/blob
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <c10/util/Optional.h>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/_print_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::_print(str s) -> ()
|
| 26 |
+
inline void _print(c10::string_view s) {
|
| 27 |
+
return at::_ops::_print::call(s);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
}
|
shared/package-files/ab/ab33bc51cb9f5ab60c758444206dc7d2bbad93ddb61bede0b82e33349a161652/blob
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
|
| 3 |
+
class BaseCache:
|
| 4 |
+
default_timeout: float
|
| 5 |
+
def __init__(self, default_timeout: float = ...): ...
|
| 6 |
+
def get(self, key): ...
|
| 7 |
+
def delete(self, key): ...
|
| 8 |
+
def get_many(self, *keys): ...
|
| 9 |
+
def get_dict(self, *keys): ...
|
| 10 |
+
def set(self, key, value, timeout: Optional[float] = ...): ...
|
| 11 |
+
def add(self, key, value, timeout: Optional[float] = ...): ...
|
| 12 |
+
def set_many(self, mapping, timeout: Optional[float] = ...): ...
|
| 13 |
+
def delete_many(self, *keys): ...
|
| 14 |
+
def has(self, key): ...
|
| 15 |
+
def clear(self): ...
|
| 16 |
+
def inc(self, key, delta=...): ...
|
| 17 |
+
def dec(self, key, delta=...): ...
|
| 18 |
+
|
| 19 |
+
class NullCache(BaseCache): ...
|
| 20 |
+
|
| 21 |
+
class SimpleCache(BaseCache):
|
| 22 |
+
clear: Any
|
| 23 |
+
def __init__(self, threshold: int = ..., default_timeout: float = ...): ...
|
| 24 |
+
def get(self, key): ...
|
| 25 |
+
def set(self, key, value, timeout: Optional[float] = ...): ...
|
| 26 |
+
def add(self, key, value, timeout: Optional[float] = ...): ...
|
| 27 |
+
def delete(self, key): ...
|
| 28 |
+
def has(self, key): ...
|
| 29 |
+
|
| 30 |
+
class MemcachedCache(BaseCache):
|
| 31 |
+
key_prefix: Any
|
| 32 |
+
def __init__(self, servers: Optional[Any] = ..., default_timeout: float = ..., key_prefix: Optional[Any] = ...): ...
|
| 33 |
+
def get(self, key): ...
|
| 34 |
+
def get_dict(self, *keys): ...
|
| 35 |
+
def add(self, key, value, timeout: Optional[float] = ...): ...
|
| 36 |
+
def set(self, key, value, timeout: Optional[float] = ...): ...
|
| 37 |
+
def get_many(self, *keys): ...
|
| 38 |
+
def set_many(self, mapping, timeout: Optional[float] = ...): ...
|
| 39 |
+
def delete(self, key): ...
|
| 40 |
+
def delete_many(self, *keys): ...
|
| 41 |
+
def has(self, key): ...
|
| 42 |
+
def clear(self): ...
|
| 43 |
+
def inc(self, key, delta=...): ...
|
| 44 |
+
def dec(self, key, delta=...): ...
|
| 45 |
+
def import_preferred_memcache_lib(self, servers): ...
|
| 46 |
+
|
| 47 |
+
GAEMemcachedCache: Any
|
| 48 |
+
|
| 49 |
+
class RedisCache(BaseCache):
|
| 50 |
+
key_prefix: Any
|
| 51 |
+
def __init__(
|
| 52 |
+
self,
|
| 53 |
+
host: str = ...,
|
| 54 |
+
port: int = ...,
|
| 55 |
+
password: Optional[Any] = ...,
|
| 56 |
+
db: int = ...,
|
| 57 |
+
default_timeout: float = ...,
|
| 58 |
+
key_prefix: Optional[Any] = ...,
|
| 59 |
+
**kwargs,
|
| 60 |
+
): ...
|
| 61 |
+
def dump_object(self, value): ...
|
| 62 |
+
def load_object(self, value): ...
|
| 63 |
+
def get(self, key): ...
|
| 64 |
+
def get_many(self, *keys): ...
|
| 65 |
+
def set(self, key, value, timeout: Optional[float] = ...): ...
|
| 66 |
+
def add(self, key, value, timeout: Optional[float] = ...): ...
|
| 67 |
+
def set_many(self, mapping, timeout: Optional[float] = ...): ...
|
| 68 |
+
def delete(self, key): ...
|
| 69 |
+
def delete_many(self, *keys): ...
|
| 70 |
+
def has(self, key): ...
|
| 71 |
+
def clear(self): ...
|
| 72 |
+
def inc(self, key, delta=...): ...
|
| 73 |
+
def dec(self, key, delta=...): ...
|
| 74 |
+
|
| 75 |
+
class FileSystemCache(BaseCache):
|
| 76 |
+
def __init__(self, cache_dir, threshold: int = ..., default_timeout: float = ..., mode: int = ...): ...
|
| 77 |
+
def clear(self): ...
|
| 78 |
+
def get(self, key): ...
|
| 79 |
+
def add(self, key, value, timeout: Optional[float] = ...): ...
|
| 80 |
+
def set(self, key, value, timeout: Optional[float] = ...): ...
|
| 81 |
+
def delete(self, key): ...
|
| 82 |
+
def has(self, key): ...
|
| 83 |
+
|
| 84 |
+
class UWSGICache(BaseCache):
|
| 85 |
+
cache: Any
|
| 86 |
+
def __init__(self, default_timeout: float = ..., cache: str = ...): ...
|
| 87 |
+
def get(self, key): ...
|
| 88 |
+
def delete(self, key): ...
|
| 89 |
+
def set(self, key, value, timeout: Optional[float] = ...): ...
|
| 90 |
+
def add(self, key, value, timeout: Optional[float] = ...): ...
|
| 91 |
+
def clear(self): ...
|
| 92 |
+
def has(self, key): ...
|
shared/package-files/ab/ab34cb487f0fbc0918d5fafa410daf57e2b013f33cdf0757ba0b6925a3ff01b3/blob
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Verify certificates using native system trust stores"""
|
| 2 |
+
|
| 3 |
+
import sys as _sys
|
| 4 |
+
|
| 5 |
+
if _sys.version_info < (3, 10):
|
| 6 |
+
raise ImportError("truststore requires Python 3.10 or later")
|
| 7 |
+
|
| 8 |
+
from ._api import SSLContext, extract_from_ssl, inject_into_ssl # noqa: E402
|
| 9 |
+
|
| 10 |
+
del _api, _sys # type: ignore[name-defined] # noqa: F821
|
| 11 |
+
|
| 12 |
+
__all__ = ["SSLContext", "inject_into_ssl", "extract_from_ssl"]
|
| 13 |
+
__version__ = "0.8.0"
|
shared/package-files/ab/ab370113df1c83c4f1e623c902f4383dd7f6c9ce91dabfb8c86252d7f0c421e6/blob
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
// or more contributor license agreements. See the NOTICE file
|
| 3 |
+
// distributed with this work for additional information
|
| 4 |
+
// regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
// to you under the Apache License, Version 2.0 (the
|
| 6 |
+
// "License"); you may not use this file except in compliance
|
| 7 |
+
// with the License. You may obtain a copy of the License at
|
| 8 |
+
//
|
| 9 |
+
// http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
//
|
| 11 |
+
// Unless required by applicable law or agreed to in writing,
|
| 12 |
+
// software distributed under the License is distributed on an
|
| 13 |
+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
// KIND, either express or implied. See the License for the
|
| 15 |
+
// specific language governing permissions and limitations
|
| 16 |
+
// under the License.
|
| 17 |
+
|
| 18 |
+
#pragma once
|
| 19 |
+
|
| 20 |
+
#include <string>
|
| 21 |
+
#include <string_view>
|
| 22 |
+
|
| 23 |
+
#include "arrow/util/visibility.h"
|
| 24 |
+
|
| 25 |
+
namespace arrow {
|
| 26 |
+
namespace util {
|
| 27 |
+
|
| 28 |
+
ARROW_EXPORT
|
| 29 |
+
std::string base64_encode(std::string_view s);
|
| 30 |
+
|
| 31 |
+
ARROW_EXPORT
|
| 32 |
+
std::string base64_decode(std::string_view s);
|
| 33 |
+
|
| 34 |
+
} // namespace util
|
| 35 |
+
} // namespace arrow
|
shared/package-files/ab/ab371cec1a3839605762ccb229d0c9c1d4d1b2d32a075673d0688662d9dd0671/blob
ADDED
|
Binary file (594 Bytes). View file
|
|
|
shared/package-files/ab/ab39c873e7fe1837175fd4cd11e75998528d80dae755cb78e74bfae94c99a183/blob
ADDED
|
Binary file (661 Bytes). View file
|
|
|
shared/package-files/ab/ab3b9a3943b225f4cffa590cdef6419d5aac1a2623ca96eb01348cff1ee61029/model_config.json
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"fingerprint": "Morgan4096-radius2",
|
| 3 |
+
"inference_workers": 4,
|
| 4 |
+
"mass_coefficient": 0.05,
|
| 5 |
+
"mass_parameters": {
|
| 6 |
+
"all": {
|
| 7 |
+
"offset": 0.0017379104733558116,
|
| 8 |
+
"scale": 0.22784726949100334
|
| 9 |
+
},
|
| 10 |
+
"[M+H]+": {
|
| 11 |
+
"offset": 0.0026598596314496036,
|
| 12 |
+
"scale": 0.15197921970275186
|
| 13 |
+
},
|
| 14 |
+
"[M+H]+|CE_known": {
|
| 15 |
+
"offset": -7.5456039222815375e-06,
|
| 16 |
+
"scale": 0.1
|
| 17 |
+
},
|
| 18 |
+
"[M+H]+ Orbitrap|CE_known": {
|
| 19 |
+
"offset": -0.0012137828913790357,
|
| 20 |
+
"scale": 0.1
|
| 21 |
+
},
|
| 22 |
+
"[M+H]+|CE_missing": {
|
| 23 |
+
"offset": 0.34631438891746547,
|
| 24 |
+
"scale": 1.2049855792590873
|
| 25 |
+
},
|
| 26 |
+
"[M+H]+ QTOF|CE_missing": {
|
| 27 |
+
"offset": 0.31476867963403604,
|
| 28 |
+
"scale": 1.1661727787433172
|
| 29 |
+
},
|
| 30 |
+
"[M+H]+ |CE_missing": {
|
| 31 |
+
"offset": -0.07318393565829291,
|
| 32 |
+
"scale": 0.9669946819840058
|
| 33 |
+
},
|
| 34 |
+
"[M+H]+ Orbitrap|CE_missing": {
|
| 35 |
+
"offset": 0.4053671391343552,
|
| 36 |
+
"scale": 1.2247049028286892
|
| 37 |
+
},
|
| 38 |
+
"[M+Na]+": {
|
| 39 |
+
"offset": -0.18138664899886367,
|
| 40 |
+
"scale": 2.7908660677201578
|
| 41 |
+
},
|
| 42 |
+
"[M+Na]+|CE_known": {
|
| 43 |
+
"offset": -0.01708129304095346,
|
| 44 |
+
"scale": 0.1
|
| 45 |
+
},
|
| 46 |
+
"[M+Na]+ Orbitrap|CE_known": {
|
| 47 |
+
"offset": -0.010102936926932657,
|
| 48 |
+
"scale": 0.1
|
| 49 |
+
},
|
| 50 |
+
"[M+Na]+|CE_missing": {
|
| 51 |
+
"offset": -0.32485984366270015,
|
| 52 |
+
"scale": 3.2315997762307016
|
| 53 |
+
},
|
| 54 |
+
"[M+Na]+ |CE_missing": {
|
| 55 |
+
"offset": -0.0487177506227377,
|
| 56 |
+
"scale": 0.5698143697858935
|
| 57 |
+
},
|
| 58 |
+
"[M+Na]+ Orbitrap|CE_missing": {
|
| 59 |
+
"offset": -0.438501156388837,
|
| 60 |
+
"scale": 4.0867859774060795
|
| 61 |
+
},
|
| 62 |
+
"[M+Na]+ QTOF|CE_missing": {
|
| 63 |
+
"offset": 0.005669038371233242,
|
| 64 |
+
"scale": 0.551818998766307
|
| 65 |
+
},
|
| 66 |
+
"[M+Na]+ QTOF|CE_known": {
|
| 67 |
+
"offset": -0.09100474226353564,
|
| 68 |
+
"scale": 0.6701640150891102
|
| 69 |
+
},
|
| 70 |
+
"[M+H]+ QTOF|CE_known": {
|
| 71 |
+
"offset": 6.490960030784106e-05,
|
| 72 |
+
"scale": 0.1
|
| 73 |
+
}
|
| 74 |
+
},
|
| 75 |
+
"ion_masses": {
|
| 76 |
+
"[M+H]+": 1.007276466621,
|
| 77 |
+
"[M+Na]+": 22.989220702091
|
| 78 |
+
},
|
| 79 |
+
"mass_conditioning": "energy_presence",
|
| 80 |
+
"method": "equal-weight-peak-ensemble",
|
| 81 |
+
"score": "cosine_idf_cauchy_mass",
|
| 82 |
+
"ensemble_rule": "mean_probabilities",
|
| 83 |
+
"members": [
|
| 84 |
+
{
|
| 85 |
+
"width": 384,
|
| 86 |
+
"depth": 4,
|
| 87 |
+
"dropout": 0.1,
|
| 88 |
+
"feature_version": "peak-transformer-fine-mass-defect-v1",
|
| 89 |
+
"max_peaks": 64,
|
| 90 |
+
"fingerprint": "Morgan4096-radius2",
|
| 91 |
+
"score": "cosine_sigmoid"
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"width": 384,
|
| 95 |
+
"depth": 4,
|
| 96 |
+
"dropout": 0.1,
|
| 97 |
+
"feature_version": "peak-transformer-fine-mass-defect-v1",
|
| 98 |
+
"max_peaks": 10,
|
| 99 |
+
"fingerprint": "Morgan4096-radius2",
|
| 100 |
+
"score": "cosine_sigmoid"
|
| 101 |
+
}
|
| 102 |
+
]
|
| 103 |
+
}
|
shared/package-files/ab/ab3d06b221fb6fab018eb20d80fd8b3004746a4e8c93300333f1086dadba26c1/blob
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 compositeimplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor fft_irfft(const at::Tensor & self, c10::optional<int64_t> n=c10::nullopt, int64_t dim=-1, c10::optional<c10::string_view> norm=c10::nullopt);
|
| 21 |
+
TORCH_API at::Tensor fft_irfft_symint(const at::Tensor & self, c10::optional<c10::SymInt> n=c10::nullopt, int64_t dim=-1, c10::optional<c10::string_view> norm=c10::nullopt);
|
| 22 |
+
TORCH_API at::Tensor & fft_irfft_out(at::Tensor & out, const at::Tensor & self, c10::optional<int64_t> n=c10::nullopt, int64_t dim=-1, c10::optional<c10::string_view> norm=c10::nullopt);
|
| 23 |
+
TORCH_API at::Tensor & fft_irfft_outf(const at::Tensor & self, c10::optional<int64_t> n, int64_t dim, c10::optional<c10::string_view> norm, at::Tensor & out);
|
| 24 |
+
TORCH_API at::Tensor & fft_irfft_symint_out(at::Tensor & out, const at::Tensor & self, c10::optional<c10::SymInt> n=c10::nullopt, int64_t dim=-1, c10::optional<c10::string_view> norm=c10::nullopt);
|
| 25 |
+
TORCH_API at::Tensor & fft_irfft_symint_outf(const at::Tensor & self, c10::optional<c10::SymInt> n, int64_t dim, c10::optional<c10::string_view> norm, at::Tensor & out);
|
| 26 |
+
|
| 27 |
+
} // namespace compositeimplicitautograd
|
| 28 |
+
} // namespace at
|
shared/package-files/ab/ab3d3254c6f895611e3930cbfc35b3e6ee5ac261883ca02cb991495e0c0724d5/blob
ADDED
|
@@ -0,0 +1,1431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
Elliptic functions historically comprise the elliptic integrals
|
| 3 |
+
and their inverses, and originate from the problem of computing the
|
| 4 |
+
arc length of an ellipse. From a more modern point of view,
|
| 5 |
+
an elliptic function is defined as a doubly periodic function, i.e.
|
| 6 |
+
a function which satisfies
|
| 7 |
+
|
| 8 |
+
.. math ::
|
| 9 |
+
|
| 10 |
+
f(z + 2 \omega_1) = f(z + 2 \omega_2) = f(z)
|
| 11 |
+
|
| 12 |
+
for some half-periods `\omega_1, \omega_2` with
|
| 13 |
+
`\mathrm{Im}[\omega_1 / \omega_2] > 0`. The canonical elliptic
|
| 14 |
+
functions are the Jacobi elliptic functions. More broadly, this section
|
| 15 |
+
includes quasi-doubly periodic functions (such as the Jacobi theta
|
| 16 |
+
functions) and other functions useful in the study of elliptic functions.
|
| 17 |
+
|
| 18 |
+
Many different conventions for the arguments of
|
| 19 |
+
elliptic functions are in use. It is even standard to use
|
| 20 |
+
different parameterizations for different functions in the same
|
| 21 |
+
text or software (and mpmath is no exception).
|
| 22 |
+
The usual parameters are the elliptic nome `q`, which usually
|
| 23 |
+
must satisfy `|q| < 1`; the elliptic parameter `m` (an arbitrary
|
| 24 |
+
complex number); the elliptic modulus `k` (an arbitrary complex
|
| 25 |
+
number); and the half-period ratio `\tau`, which usually must
|
| 26 |
+
satisfy `\mathrm{Im}[\tau] > 0`.
|
| 27 |
+
These quantities can be expressed in terms of each other
|
| 28 |
+
using the following relations:
|
| 29 |
+
|
| 30 |
+
.. math ::
|
| 31 |
+
|
| 32 |
+
m = k^2
|
| 33 |
+
|
| 34 |
+
.. math ::
|
| 35 |
+
|
| 36 |
+
\tau = i \frac{K(1-m)}{K(m)}
|
| 37 |
+
|
| 38 |
+
.. math ::
|
| 39 |
+
|
| 40 |
+
q = e^{i \pi \tau}
|
| 41 |
+
|
| 42 |
+
.. math ::
|
| 43 |
+
|
| 44 |
+
k = \frac{\vartheta_2^2(q)}{\vartheta_3^2(q)}
|
| 45 |
+
|
| 46 |
+
In addition, an alternative definition is used for the nome in
|
| 47 |
+
number theory, which we here denote by q-bar:
|
| 48 |
+
|
| 49 |
+
.. math ::
|
| 50 |
+
|
| 51 |
+
\bar{q} = q^2 = e^{2 i \pi \tau}
|
| 52 |
+
|
| 53 |
+
For convenience, mpmath provides functions to convert
|
| 54 |
+
between the various parameters (:func:`~mpmath.qfrom`, :func:`~mpmath.mfrom`,
|
| 55 |
+
:func:`~mpmath.kfrom`, :func:`~mpmath.taufrom`, :func:`~mpmath.qbarfrom`).
|
| 56 |
+
|
| 57 |
+
**References**
|
| 58 |
+
|
| 59 |
+
1. [AbramowitzStegun]_
|
| 60 |
+
|
| 61 |
+
2. [WhittakerWatson]_
|
| 62 |
+
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
from .functions import defun, defun_wrapped
|
| 66 |
+
|
| 67 |
+
@defun_wrapped
|
| 68 |
+
def eta(ctx, tau):
|
| 69 |
+
r"""
|
| 70 |
+
Returns the Dedekind eta function of tau in the upper half-plane.
|
| 71 |
+
|
| 72 |
+
>>> from mpmath import *
|
| 73 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 74 |
+
>>> eta(1j); gamma(0.25) / (2*pi**0.75)
|
| 75 |
+
(0.7682254223260566590025942 + 0.0j)
|
| 76 |
+
0.7682254223260566590025942
|
| 77 |
+
>>> tau = sqrt(2) + sqrt(5)*1j
|
| 78 |
+
>>> eta(-1/tau); sqrt(-1j*tau) * eta(tau)
|
| 79 |
+
(0.9022859908439376463573294 + 0.07985093673948098408048575j)
|
| 80 |
+
(0.9022859908439376463573295 + 0.07985093673948098408048575j)
|
| 81 |
+
>>> eta(tau+1); exp(pi*1j/12) * eta(tau)
|
| 82 |
+
(0.4493066139717553786223114 + 0.3290014793877986663915939j)
|
| 83 |
+
(0.4493066139717553786223114 + 0.3290014793877986663915939j)
|
| 84 |
+
>>> f = lambda z: diff(eta, z) / eta(z)
|
| 85 |
+
>>> chop(36*diff(f,tau)**2 - 24*diff(f,tau,2)*f(tau) + diff(f,tau,3))
|
| 86 |
+
0.0
|
| 87 |
+
|
| 88 |
+
"""
|
| 89 |
+
if ctx.im(tau) <= 0.0:
|
| 90 |
+
raise ValueError("eta is only defined in the upper half-plane")
|
| 91 |
+
q = ctx.expjpi(tau/12)
|
| 92 |
+
return q * ctx.qp(q**24)
|
| 93 |
+
|
| 94 |
+
def nome(ctx, m):
|
| 95 |
+
m = ctx.convert(m)
|
| 96 |
+
if not m:
|
| 97 |
+
return m
|
| 98 |
+
if m == ctx.one:
|
| 99 |
+
return m
|
| 100 |
+
if ctx.isnan(m):
|
| 101 |
+
return m
|
| 102 |
+
if ctx.isinf(m):
|
| 103 |
+
if m == ctx.ninf:
|
| 104 |
+
return type(m)(-1)
|
| 105 |
+
else:
|
| 106 |
+
return ctx.mpc(-1)
|
| 107 |
+
a = ctx.ellipk(ctx.one-m)
|
| 108 |
+
b = ctx.ellipk(m)
|
| 109 |
+
v = ctx.exp(-ctx.pi*a/b)
|
| 110 |
+
if not ctx._im(m) and ctx._re(m) < 1:
|
| 111 |
+
if ctx._is_real_type(m):
|
| 112 |
+
return v.real
|
| 113 |
+
else:
|
| 114 |
+
return v.real + 0j
|
| 115 |
+
elif m == 2:
|
| 116 |
+
v = ctx.mpc(0, v.imag)
|
| 117 |
+
return v
|
| 118 |
+
|
| 119 |
+
@defun_wrapped
|
| 120 |
+
def qfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None):
|
| 121 |
+
r"""
|
| 122 |
+
Returns the elliptic nome `q`, given any of `q, m, k, \tau, \bar{q}`::
|
| 123 |
+
|
| 124 |
+
>>> from mpmath import *
|
| 125 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 126 |
+
>>> qfrom(q=0.25)
|
| 127 |
+
0.25
|
| 128 |
+
>>> qfrom(m=mfrom(q=0.25))
|
| 129 |
+
0.25
|
| 130 |
+
>>> qfrom(k=kfrom(q=0.25))
|
| 131 |
+
0.25
|
| 132 |
+
>>> qfrom(tau=taufrom(q=0.25))
|
| 133 |
+
(0.25 + 0.0j)
|
| 134 |
+
>>> qfrom(qbar=qbarfrom(q=0.25))
|
| 135 |
+
0.25
|
| 136 |
+
|
| 137 |
+
"""
|
| 138 |
+
if q is not None:
|
| 139 |
+
return ctx.convert(q)
|
| 140 |
+
if m is not None:
|
| 141 |
+
return nome(ctx, m)
|
| 142 |
+
if k is not None:
|
| 143 |
+
return nome(ctx, ctx.convert(k)**2)
|
| 144 |
+
if tau is not None:
|
| 145 |
+
return ctx.expjpi(tau)
|
| 146 |
+
if qbar is not None:
|
| 147 |
+
return ctx.sqrt(qbar)
|
| 148 |
+
|
| 149 |
+
@defun_wrapped
|
| 150 |
+
def qbarfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None):
|
| 151 |
+
r"""
|
| 152 |
+
Returns the number-theoretic nome `\bar q`, given any of
|
| 153 |
+
`q, m, k, \tau, \bar{q}`::
|
| 154 |
+
|
| 155 |
+
>>> from mpmath import *
|
| 156 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 157 |
+
>>> qbarfrom(qbar=0.25)
|
| 158 |
+
0.25
|
| 159 |
+
>>> qbarfrom(q=qfrom(qbar=0.25))
|
| 160 |
+
0.25
|
| 161 |
+
>>> qbarfrom(m=extraprec(20)(mfrom)(qbar=0.25)) # ill-conditioned
|
| 162 |
+
0.25
|
| 163 |
+
>>> qbarfrom(k=extraprec(20)(kfrom)(qbar=0.25)) # ill-conditioned
|
| 164 |
+
0.25
|
| 165 |
+
>>> qbarfrom(tau=taufrom(qbar=0.25))
|
| 166 |
+
(0.25 + 0.0j)
|
| 167 |
+
|
| 168 |
+
"""
|
| 169 |
+
if qbar is not None:
|
| 170 |
+
return ctx.convert(qbar)
|
| 171 |
+
if q is not None:
|
| 172 |
+
return ctx.convert(q) ** 2
|
| 173 |
+
if m is not None:
|
| 174 |
+
return nome(ctx, m) ** 2
|
| 175 |
+
if k is not None:
|
| 176 |
+
return nome(ctx, ctx.convert(k)**2) ** 2
|
| 177 |
+
if tau is not None:
|
| 178 |
+
return ctx.expjpi(2*tau)
|
| 179 |
+
|
| 180 |
+
@defun_wrapped
|
| 181 |
+
def taufrom(ctx, q=None, m=None, k=None, tau=None, qbar=None):
|
| 182 |
+
r"""
|
| 183 |
+
Returns the elliptic half-period ratio `\tau`, given any of
|
| 184 |
+
`q, m, k, \tau, \bar{q}`::
|
| 185 |
+
|
| 186 |
+
>>> from mpmath import *
|
| 187 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 188 |
+
>>> taufrom(tau=0.5j)
|
| 189 |
+
(0.0 + 0.5j)
|
| 190 |
+
>>> taufrom(q=qfrom(tau=0.5j))
|
| 191 |
+
(0.0 + 0.5j)
|
| 192 |
+
>>> taufrom(m=mfrom(tau=0.5j))
|
| 193 |
+
(0.0 + 0.5j)
|
| 194 |
+
>>> taufrom(k=kfrom(tau=0.5j))
|
| 195 |
+
(0.0 + 0.5j)
|
| 196 |
+
>>> taufrom(qbar=qbarfrom(tau=0.5j))
|
| 197 |
+
(0.0 + 0.5j)
|
| 198 |
+
|
| 199 |
+
"""
|
| 200 |
+
if tau is not None:
|
| 201 |
+
return ctx.convert(tau)
|
| 202 |
+
if m is not None:
|
| 203 |
+
m = ctx.convert(m)
|
| 204 |
+
return ctx.j*ctx.ellipk(1-m)/ctx.ellipk(m)
|
| 205 |
+
if k is not None:
|
| 206 |
+
k = ctx.convert(k)
|
| 207 |
+
return ctx.j*ctx.ellipk(1-k**2)/ctx.ellipk(k**2)
|
| 208 |
+
if q is not None:
|
| 209 |
+
return ctx.log(q) / (ctx.pi*ctx.j)
|
| 210 |
+
if qbar is not None:
|
| 211 |
+
qbar = ctx.convert(qbar)
|
| 212 |
+
return ctx.log(qbar) / (2*ctx.pi*ctx.j)
|
| 213 |
+
|
| 214 |
+
@defun_wrapped
|
| 215 |
+
def kfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None):
|
| 216 |
+
r"""
|
| 217 |
+
Returns the elliptic modulus `k`, given any of
|
| 218 |
+
`q, m, k, \tau, \bar{q}`::
|
| 219 |
+
|
| 220 |
+
>>> from mpmath import *
|
| 221 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 222 |
+
>>> kfrom(k=0.25)
|
| 223 |
+
0.25
|
| 224 |
+
>>> kfrom(m=mfrom(k=0.25))
|
| 225 |
+
0.25
|
| 226 |
+
>>> kfrom(q=qfrom(k=0.25))
|
| 227 |
+
0.25
|
| 228 |
+
>>> kfrom(tau=taufrom(k=0.25))
|
| 229 |
+
(0.25 + 0.0j)
|
| 230 |
+
>>> kfrom(qbar=qbarfrom(k=0.25))
|
| 231 |
+
0.25
|
| 232 |
+
|
| 233 |
+
As `q \to 1` and `q \to -1`, `k` rapidly approaches
|
| 234 |
+
`1` and `i \infty` respectively::
|
| 235 |
+
|
| 236 |
+
>>> kfrom(q=0.75)
|
| 237 |
+
0.9999999999999899166471767
|
| 238 |
+
>>> kfrom(q=-0.75)
|
| 239 |
+
(0.0 + 7041781.096692038332790615j)
|
| 240 |
+
>>> kfrom(q=1)
|
| 241 |
+
1
|
| 242 |
+
>>> kfrom(q=-1)
|
| 243 |
+
(0.0 + +infj)
|
| 244 |
+
"""
|
| 245 |
+
if k is not None:
|
| 246 |
+
return ctx.convert(k)
|
| 247 |
+
if m is not None:
|
| 248 |
+
return ctx.sqrt(m)
|
| 249 |
+
if tau is not None:
|
| 250 |
+
q = ctx.expjpi(tau)
|
| 251 |
+
if qbar is not None:
|
| 252 |
+
q = ctx.sqrt(qbar)
|
| 253 |
+
if q == 1:
|
| 254 |
+
return q
|
| 255 |
+
if q == -1:
|
| 256 |
+
return ctx.mpc(0,'inf')
|
| 257 |
+
return (ctx.jtheta(2,0,q)/ctx.jtheta(3,0,q))**2
|
| 258 |
+
|
| 259 |
+
@defun_wrapped
|
| 260 |
+
def mfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None):
|
| 261 |
+
r"""
|
| 262 |
+
Returns the elliptic parameter `m`, given any of
|
| 263 |
+
`q, m, k, \tau, \bar{q}`::
|
| 264 |
+
|
| 265 |
+
>>> from mpmath import *
|
| 266 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 267 |
+
>>> mfrom(m=0.25)
|
| 268 |
+
0.25
|
| 269 |
+
>>> mfrom(q=qfrom(m=0.25))
|
| 270 |
+
0.25
|
| 271 |
+
>>> mfrom(k=kfrom(m=0.25))
|
| 272 |
+
0.25
|
| 273 |
+
>>> mfrom(tau=taufrom(m=0.25))
|
| 274 |
+
(0.25 + 0.0j)
|
| 275 |
+
>>> mfrom(qbar=qbarfrom(m=0.25))
|
| 276 |
+
0.25
|
| 277 |
+
|
| 278 |
+
As `q \to 1` and `q \to -1`, `m` rapidly approaches
|
| 279 |
+
`1` and `-\infty` respectively::
|
| 280 |
+
|
| 281 |
+
>>> mfrom(q=0.75)
|
| 282 |
+
0.9999999999999798332943533
|
| 283 |
+
>>> mfrom(q=-0.75)
|
| 284 |
+
-49586681013729.32611558353
|
| 285 |
+
>>> mfrom(q=1)
|
| 286 |
+
1.0
|
| 287 |
+
>>> mfrom(q=-1)
|
| 288 |
+
-inf
|
| 289 |
+
|
| 290 |
+
The inverse nome as a function of `q` has an integer
|
| 291 |
+
Taylor series expansion::
|
| 292 |
+
|
| 293 |
+
>>> taylor(lambda q: mfrom(q), 0, 7)
|
| 294 |
+
[0.0, 16.0, -128.0, 704.0, -3072.0, 11488.0, -38400.0, 117632.0]
|
| 295 |
+
|
| 296 |
+
"""
|
| 297 |
+
if m is not None:
|
| 298 |
+
return m
|
| 299 |
+
if k is not None:
|
| 300 |
+
return k**2
|
| 301 |
+
if tau is not None:
|
| 302 |
+
q = ctx.expjpi(tau)
|
| 303 |
+
if qbar is not None:
|
| 304 |
+
q = ctx.sqrt(qbar)
|
| 305 |
+
if q == 1:
|
| 306 |
+
return ctx.convert(q)
|
| 307 |
+
if q == -1:
|
| 308 |
+
return q*ctx.inf
|
| 309 |
+
v = (ctx.jtheta(2,0,q)/ctx.jtheta(3,0,q))**4
|
| 310 |
+
if ctx._is_real_type(q) and q < 0:
|
| 311 |
+
v = v.real
|
| 312 |
+
return v
|
| 313 |
+
|
| 314 |
+
jacobi_spec = {
|
| 315 |
+
'sn' : ([3],[2],[1],[4], 'sin', 'tanh'),
|
| 316 |
+
'cn' : ([4],[2],[2],[4], 'cos', 'sech'),
|
| 317 |
+
'dn' : ([4],[3],[3],[4], '1', 'sech'),
|
| 318 |
+
'ns' : ([2],[3],[4],[1], 'csc', 'coth'),
|
| 319 |
+
'nc' : ([2],[4],[4],[2], 'sec', 'cosh'),
|
| 320 |
+
'nd' : ([3],[4],[4],[3], '1', 'cosh'),
|
| 321 |
+
'sc' : ([3],[4],[1],[2], 'tan', 'sinh'),
|
| 322 |
+
'sd' : ([3,3],[2,4],[1],[3], 'sin', 'sinh'),
|
| 323 |
+
'cd' : ([3],[2],[2],[3], 'cos', '1'),
|
| 324 |
+
'cs' : ([4],[3],[2],[1], 'cot', 'csch'),
|
| 325 |
+
'dc' : ([2],[3],[3],[2], 'sec', '1'),
|
| 326 |
+
'ds' : ([2,4],[3,3],[3],[1], 'csc', 'csch'),
|
| 327 |
+
'cc' : None,
|
| 328 |
+
'ss' : None,
|
| 329 |
+
'nn' : None,
|
| 330 |
+
'dd' : None
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
@defun
|
| 334 |
+
def ellipfun(ctx, kind, u=None, m=None, q=None, k=None, tau=None):
|
| 335 |
+
try:
|
| 336 |
+
S = jacobi_spec[kind]
|
| 337 |
+
except KeyError:
|
| 338 |
+
raise ValueError("First argument must be a two-character string "
|
| 339 |
+
"containing 's', 'c', 'd' or 'n', e.g.: 'sn'")
|
| 340 |
+
if u is None:
|
| 341 |
+
def f(*args, **kwargs):
|
| 342 |
+
return ctx.ellipfun(kind, *args, **kwargs)
|
| 343 |
+
f.__name__ = kind
|
| 344 |
+
return f
|
| 345 |
+
prec = ctx.prec
|
| 346 |
+
try:
|
| 347 |
+
ctx.prec += 10
|
| 348 |
+
u = ctx.convert(u)
|
| 349 |
+
q = ctx.qfrom(m=m, q=q, k=k, tau=tau)
|
| 350 |
+
if S is None:
|
| 351 |
+
v = ctx.one + 0*q*u
|
| 352 |
+
elif q == ctx.zero:
|
| 353 |
+
if S[4] == '1': v = ctx.one
|
| 354 |
+
else: v = getattr(ctx, S[4])(u)
|
| 355 |
+
v += 0*q*u
|
| 356 |
+
elif q == ctx.one:
|
| 357 |
+
if S[5] == '1': v = ctx.one
|
| 358 |
+
else: v = getattr(ctx, S[5])(u)
|
| 359 |
+
v += 0*q*u
|
| 360 |
+
else:
|
| 361 |
+
t = u / ctx.jtheta(3, 0, q)**2
|
| 362 |
+
v = ctx.one
|
| 363 |
+
for a in S[0]: v *= ctx.jtheta(a, 0, q)
|
| 364 |
+
for b in S[1]: v /= ctx.jtheta(b, 0, q)
|
| 365 |
+
for c in S[2]: v *= ctx.jtheta(c, t, q)
|
| 366 |
+
for d in S[3]: v /= ctx.jtheta(d, t, q)
|
| 367 |
+
finally:
|
| 368 |
+
ctx.prec = prec
|
| 369 |
+
return +v
|
| 370 |
+
|
| 371 |
+
@defun_wrapped
|
| 372 |
+
def kleinj(ctx, tau=None, **kwargs):
|
| 373 |
+
r"""
|
| 374 |
+
Evaluates the Klein j-invariant, which is a modular function defined for
|
| 375 |
+
`\tau` in the upper half-plane as
|
| 376 |
+
|
| 377 |
+
.. math ::
|
| 378 |
+
|
| 379 |
+
J(\tau) = \frac{g_2^3(\tau)}{g_2^3(\tau) - 27 g_3^2(\tau)}
|
| 380 |
+
|
| 381 |
+
where `g_2` and `g_3` are the modular invariants of the Weierstrass
|
| 382 |
+
elliptic function,
|
| 383 |
+
|
| 384 |
+
.. math ::
|
| 385 |
+
|
| 386 |
+
g_2(\tau) = 60 \sum_{(m,n) \in \mathbb{Z}^2 \setminus (0,0)} (m \tau+n)^{-4}
|
| 387 |
+
|
| 388 |
+
g_3(\tau) = 140 \sum_{(m,n) \in \mathbb{Z}^2 \setminus (0,0)} (m \tau+n)^{-6}.
|
| 389 |
+
|
| 390 |
+
An alternative, common notation is that of the j-function
|
| 391 |
+
`j(\tau) = 1728 J(\tau)`.
|
| 392 |
+
|
| 393 |
+
**Plots**
|
| 394 |
+
|
| 395 |
+
.. literalinclude :: /plots/kleinj.py
|
| 396 |
+
.. image :: /plots/kleinj.png
|
| 397 |
+
.. literalinclude :: /plots/kleinj2.py
|
| 398 |
+
.. image :: /plots/kleinj2.png
|
| 399 |
+
|
| 400 |
+
**Examples**
|
| 401 |
+
|
| 402 |
+
Verifying the functional equation `J(\tau) = J(\tau+1) = J(-\tau^{-1})`::
|
| 403 |
+
|
| 404 |
+
>>> from mpmath import *
|
| 405 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 406 |
+
>>> tau = 0.625+0.75*j
|
| 407 |
+
>>> tau = 0.625+0.75*j
|
| 408 |
+
>>> kleinj(tau)
|
| 409 |
+
(-0.1507492166511182267125242 + 0.07595948379084571927228948j)
|
| 410 |
+
>>> kleinj(tau+1)
|
| 411 |
+
(-0.1507492166511182267125242 + 0.07595948379084571927228948j)
|
| 412 |
+
>>> kleinj(-1/tau)
|
| 413 |
+
(-0.1507492166511182267125242 + 0.07595948379084571927228946j)
|
| 414 |
+
|
| 415 |
+
The j-function has a famous Laurent series expansion in terms of the nome
|
| 416 |
+
`\bar{q}`, `j(\tau) = \bar{q}^{-1} + 744 + 196884\bar{q} + \ldots`::
|
| 417 |
+
|
| 418 |
+
>>> mp.dps = 15
|
| 419 |
+
>>> taylor(lambda q: 1728*q*kleinj(qbar=q), 0, 5, singular=True)
|
| 420 |
+
[1.0, 744.0, 196884.0, 21493760.0, 864299970.0, 20245856256.0]
|
| 421 |
+
|
| 422 |
+
The j-function admits exact evaluation at special algebraic points
|
| 423 |
+
related to the Heegner numbers 1, 2, 3, 7, 11, 19, 43, 67, 163::
|
| 424 |
+
|
| 425 |
+
>>> @extraprec(10)
|
| 426 |
+
... def h(n):
|
| 427 |
+
... v = (1+sqrt(n)*j)
|
| 428 |
+
... if n > 2:
|
| 429 |
+
... v *= 0.5
|
| 430 |
+
... return v
|
| 431 |
+
...
|
| 432 |
+
>>> mp.dps = 25
|
| 433 |
+
>>> for n in [1,2,3,7,11,19,43,67,163]:
|
| 434 |
+
... n, chop(1728*kleinj(h(n)))
|
| 435 |
+
...
|
| 436 |
+
(1, 1728.0)
|
| 437 |
+
(2, 8000.0)
|
| 438 |
+
(3, 0.0)
|
| 439 |
+
(7, -3375.0)
|
| 440 |
+
(11, -32768.0)
|
| 441 |
+
(19, -884736.0)
|
| 442 |
+
(43, -884736000.0)
|
| 443 |
+
(67, -147197952000.0)
|
| 444 |
+
(163, -262537412640768000.0)
|
| 445 |
+
|
| 446 |
+
Also at other special points, the j-function assumes explicit
|
| 447 |
+
algebraic values, e.g.::
|
| 448 |
+
|
| 449 |
+
>>> chop(1728*kleinj(j*sqrt(5)))
|
| 450 |
+
1264538.909475140509320227
|
| 451 |
+
>>> identify(cbrt(_)) # note: not simplified
|
| 452 |
+
'((100+sqrt(13520))/2)'
|
| 453 |
+
>>> (50+26*sqrt(5))**3
|
| 454 |
+
1264538.909475140509320227
|
| 455 |
+
|
| 456 |
+
"""
|
| 457 |
+
q = ctx.qfrom(tau=tau, **kwargs)
|
| 458 |
+
t2 = ctx.jtheta(2,0,q)
|
| 459 |
+
t3 = ctx.jtheta(3,0,q)
|
| 460 |
+
t4 = ctx.jtheta(4,0,q)
|
| 461 |
+
P = (t2**8 + t3**8 + t4**8)**3
|
| 462 |
+
Q = 54*(t2*t3*t4)**8
|
| 463 |
+
return P/Q
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def RF_calc(ctx, x, y, z, r):
|
| 467 |
+
if y == z: return RC_calc(ctx, x, y, r)
|
| 468 |
+
if x == z: return RC_calc(ctx, y, x, r)
|
| 469 |
+
if x == y: return RC_calc(ctx, z, x, r)
|
| 470 |
+
if not (ctx.isnormal(x) and ctx.isnormal(y) and ctx.isnormal(z)):
|
| 471 |
+
if ctx.isnan(x) or ctx.isnan(y) or ctx.isnan(z):
|
| 472 |
+
return x*y*z
|
| 473 |
+
if ctx.isinf(x) or ctx.isinf(y) or ctx.isinf(z):
|
| 474 |
+
return ctx.zero
|
| 475 |
+
xm,ym,zm = x,y,z
|
| 476 |
+
A0 = Am = (x+y+z)/3
|
| 477 |
+
Q = ctx.root(3*r, -6) * max(abs(A0-x),abs(A0-y),abs(A0-z))
|
| 478 |
+
g = ctx.mpf(0.25)
|
| 479 |
+
pow4 = ctx.one
|
| 480 |
+
while 1:
|
| 481 |
+
xs = ctx.sqrt(xm)
|
| 482 |
+
ys = ctx.sqrt(ym)
|
| 483 |
+
zs = ctx.sqrt(zm)
|
| 484 |
+
lm = xs*ys + xs*zs + ys*zs
|
| 485 |
+
Am1 = (Am+lm)*g
|
| 486 |
+
xm, ym, zm = (xm+lm)*g, (ym+lm)*g, (zm+lm)*g
|
| 487 |
+
if pow4 * Q < abs(Am):
|
| 488 |
+
break
|
| 489 |
+
Am = Am1
|
| 490 |
+
pow4 *= g
|
| 491 |
+
t = pow4/Am
|
| 492 |
+
X = (A0-x)*t
|
| 493 |
+
Y = (A0-y)*t
|
| 494 |
+
Z = -X-Y
|
| 495 |
+
E2 = X*Y-Z**2
|
| 496 |
+
E3 = X*Y*Z
|
| 497 |
+
return ctx.power(Am,-0.5) * (9240-924*E2+385*E2**2+660*E3-630*E2*E3)/9240
|
| 498 |
+
|
| 499 |
+
def RC_calc(ctx, x, y, r, pv=True):
|
| 500 |
+
if not (ctx.isnormal(x) and ctx.isnormal(y)):
|
| 501 |
+
if ctx.isinf(x) or ctx.isinf(y):
|
| 502 |
+
return 1/(x*y)
|
| 503 |
+
if y == 0:
|
| 504 |
+
return ctx.inf
|
| 505 |
+
if x == 0:
|
| 506 |
+
return ctx.pi / ctx.sqrt(y) / 2
|
| 507 |
+
raise ValueError
|
| 508 |
+
# Cauchy principal value
|
| 509 |
+
if pv and ctx._im(y) == 0 and ctx._re(y) < 0:
|
| 510 |
+
return ctx.sqrt(x/(x-y)) * RC_calc(ctx, x-y, -y, r)
|
| 511 |
+
if x == y:
|
| 512 |
+
return 1/ctx.sqrt(x)
|
| 513 |
+
extraprec = 2*max(0,-ctx.mag(x-y)+ctx.mag(x))
|
| 514 |
+
ctx.prec += extraprec
|
| 515 |
+
if ctx._is_real_type(x) and ctx._is_real_type(y):
|
| 516 |
+
x = ctx._re(x)
|
| 517 |
+
y = ctx._re(y)
|
| 518 |
+
a = ctx.sqrt(x/y)
|
| 519 |
+
if x < y:
|
| 520 |
+
b = ctx.sqrt(y-x)
|
| 521 |
+
v = ctx.acos(a)/b
|
| 522 |
+
else:
|
| 523 |
+
b = ctx.sqrt(x-y)
|
| 524 |
+
v = ctx.acosh(a)/b
|
| 525 |
+
else:
|
| 526 |
+
sx = ctx.sqrt(x)
|
| 527 |
+
sy = ctx.sqrt(y)
|
| 528 |
+
v = ctx.acos(sx/sy)/(ctx.sqrt((1-x/y))*sy)
|
| 529 |
+
ctx.prec -= extraprec
|
| 530 |
+
return v
|
| 531 |
+
|
| 532 |
+
def RJ_calc(ctx, x, y, z, p, r, integration):
|
| 533 |
+
"""
|
| 534 |
+
With integration == 0, computes RJ only using Carlson's algorithm
|
| 535 |
+
(may be wrong for some values).
|
| 536 |
+
With integration == 1, uses an initial integration to make sure
|
| 537 |
+
Carlson's algorithm is correct.
|
| 538 |
+
With integration == 2, uses only integration.
|
| 539 |
+
"""
|
| 540 |
+
if not (ctx.isnormal(x) and ctx.isnormal(y) and \
|
| 541 |
+
ctx.isnormal(z) and ctx.isnormal(p)):
|
| 542 |
+
if ctx.isnan(x) or ctx.isnan(y) or ctx.isnan(z) or ctx.isnan(p):
|
| 543 |
+
return x*y*z
|
| 544 |
+
if ctx.isinf(x) or ctx.isinf(y) or ctx.isinf(z) or ctx.isinf(p):
|
| 545 |
+
return ctx.zero
|
| 546 |
+
if not p:
|
| 547 |
+
return ctx.inf
|
| 548 |
+
if (not x) + (not y) + (not z) > 1:
|
| 549 |
+
return ctx.inf
|
| 550 |
+
# Check conditions and fall back on integration for argument
|
| 551 |
+
# reduction if needed. The following conditions might be needlessly
|
| 552 |
+
# restrictive.
|
| 553 |
+
initial_integral = ctx.zero
|
| 554 |
+
if integration >= 1:
|
| 555 |
+
ok = (x.real >= 0 and y.real >= 0 and z.real >= 0 and p.real > 0)
|
| 556 |
+
if not ok:
|
| 557 |
+
if x == p or y == p or z == p:
|
| 558 |
+
ok = True
|
| 559 |
+
if not ok:
|
| 560 |
+
if p.imag != 0 or p.real >= 0:
|
| 561 |
+
if (x.imag == 0 and x.real >= 0 and ctx.conj(y) == z):
|
| 562 |
+
ok = True
|
| 563 |
+
if (y.imag == 0 and y.real >= 0 and ctx.conj(x) == z):
|
| 564 |
+
ok = True
|
| 565 |
+
if (z.imag == 0 and z.real >= 0 and ctx.conj(x) == y):
|
| 566 |
+
ok = True
|
| 567 |
+
if not ok or (integration == 2):
|
| 568 |
+
N = ctx.ceil(-min(x.real, y.real, z.real, p.real)) + 1
|
| 569 |
+
# Integrate around any singularities
|
| 570 |
+
if all((t.imag >= 0 or t.real > 0) for t in [x, y, z, p]):
|
| 571 |
+
margin = ctx.j
|
| 572 |
+
elif all((t.imag < 0 or t.real > 0) for t in [x, y, z, p]):
|
| 573 |
+
margin = -ctx.j
|
| 574 |
+
else:
|
| 575 |
+
margin = 1
|
| 576 |
+
# Go through the upper half-plane, but low enough that any
|
| 577 |
+
# parameter starting in the lower plane doesn't cross the
|
| 578 |
+
# branch cut
|
| 579 |
+
for t in [x, y, z, p]:
|
| 580 |
+
if t.imag >= 0 or t.real > 0:
|
| 581 |
+
continue
|
| 582 |
+
margin = min(margin, abs(t.imag) * 0.5)
|
| 583 |
+
margin *= ctx.j
|
| 584 |
+
N += margin
|
| 585 |
+
F = lambda t: 1/(ctx.sqrt(t+x)*ctx.sqrt(t+y)*ctx.sqrt(t+z)*(t+p))
|
| 586 |
+
if integration == 2:
|
| 587 |
+
return 1.5 * ctx.quadsubdiv(F, [0, N, ctx.inf])
|
| 588 |
+
initial_integral = 1.5 * ctx.quadsubdiv(F, [0, N])
|
| 589 |
+
x += N; y += N; z += N; p += N
|
| 590 |
+
xm,ym,zm,pm = x,y,z,p
|
| 591 |
+
A0 = Am = (x + y + z + 2*p)/5
|
| 592 |
+
delta = (p-x)*(p-y)*(p-z)
|
| 593 |
+
Q = ctx.root(0.25*r, -6) * max(abs(A0-x),abs(A0-y),abs(A0-z),abs(A0-p))
|
| 594 |
+
g = ctx.mpf(0.25)
|
| 595 |
+
pow4 = ctx.one
|
| 596 |
+
S = 0
|
| 597 |
+
while 1:
|
| 598 |
+
sx = ctx.sqrt(xm)
|
| 599 |
+
sy = ctx.sqrt(ym)
|
| 600 |
+
sz = ctx.sqrt(zm)
|
| 601 |
+
sp = ctx.sqrt(pm)
|
| 602 |
+
lm = sx*sy + sx*sz + sy*sz
|
| 603 |
+
Am1 = (Am+lm)*g
|
| 604 |
+
xm = (xm+lm)*g; ym = (ym+lm)*g; zm = (zm+lm)*g; pm = (pm+lm)*g
|
| 605 |
+
dm = (sp+sx) * (sp+sy) * (sp+sz)
|
| 606 |
+
em = delta * pow4**3 / dm**2
|
| 607 |
+
if pow4 * Q < abs(Am):
|
| 608 |
+
break
|
| 609 |
+
T = RC_calc(ctx, ctx.one, ctx.one+em, r) * pow4 / dm
|
| 610 |
+
S += T
|
| 611 |
+
pow4 *= g
|
| 612 |
+
Am = Am1
|
| 613 |
+
t = pow4 / Am
|
| 614 |
+
X = (A0-x)*t
|
| 615 |
+
Y = (A0-y)*t
|
| 616 |
+
Z = (A0-z)*t
|
| 617 |
+
P = (-X-Y-Z)/2
|
| 618 |
+
E2 = X*Y + X*Z + Y*Z - 3*P**2
|
| 619 |
+
E3 = X*Y*Z + 2*E2*P + 4*P**3
|
| 620 |
+
E4 = (2*X*Y*Z + E2*P + 3*P**3)*P
|
| 621 |
+
E5 = X*Y*Z*P**2
|
| 622 |
+
P = 24024 - 5148*E2 + 2457*E2**2 + 4004*E3 - 4158*E2*E3 - 3276*E4 + 2772*E5
|
| 623 |
+
Q = 24024
|
| 624 |
+
v1 = pow4 * ctx.power(Am, -1.5) * P/Q
|
| 625 |
+
v2 = 6*S
|
| 626 |
+
return initial_integral + v1 + v2
|
| 627 |
+
|
| 628 |
+
@defun
|
| 629 |
+
def elliprf(ctx, x, y, z):
|
| 630 |
+
r"""
|
| 631 |
+
Evaluates the Carlson symmetric elliptic integral of the first kind
|
| 632 |
+
|
| 633 |
+
.. math ::
|
| 634 |
+
|
| 635 |
+
R_F(x,y,z) = \frac{1}{2}
|
| 636 |
+
\int_0^{\infty} \frac{dt}{\sqrt{(t+x)(t+y)(t+z)}}
|
| 637 |
+
|
| 638 |
+
which is defined for `x,y,z \notin (-\infty,0)`, and with
|
| 639 |
+
at most one of `x,y,z` being zero.
|
| 640 |
+
|
| 641 |
+
For real `x,y,z \ge 0`, the principal square root is taken in the integrand.
|
| 642 |
+
For complex `x,y,z`, the principal square root is taken as `t \to \infty`
|
| 643 |
+
and as `t \to 0` non-principal branches are chosen as necessary so as to
|
| 644 |
+
make the integrand continuous.
|
| 645 |
+
|
| 646 |
+
**Examples**
|
| 647 |
+
|
| 648 |
+
Some basic values and limits::
|
| 649 |
+
|
| 650 |
+
>>> from mpmath import *
|
| 651 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 652 |
+
>>> elliprf(0,1,1); pi/2
|
| 653 |
+
1.570796326794896619231322
|
| 654 |
+
1.570796326794896619231322
|
| 655 |
+
>>> elliprf(0,1,inf)
|
| 656 |
+
0.0
|
| 657 |
+
>>> elliprf(1,1,1)
|
| 658 |
+
1.0
|
| 659 |
+
>>> elliprf(2,2,2)**2
|
| 660 |
+
0.5
|
| 661 |
+
>>> elliprf(1,0,0); elliprf(0,0,1); elliprf(0,1,0); elliprf(0,0,0)
|
| 662 |
+
+inf
|
| 663 |
+
+inf
|
| 664 |
+
+inf
|
| 665 |
+
+inf
|
| 666 |
+
|
| 667 |
+
Representing complete elliptic integrals in terms of `R_F`::
|
| 668 |
+
|
| 669 |
+
>>> m = mpf(0.75)
|
| 670 |
+
>>> ellipk(m); elliprf(0,1-m,1)
|
| 671 |
+
2.156515647499643235438675
|
| 672 |
+
2.156515647499643235438675
|
| 673 |
+
>>> ellipe(m); elliprf(0,1-m,1)-m*elliprd(0,1-m,1)/3
|
| 674 |
+
1.211056027568459524803563
|
| 675 |
+
1.211056027568459524803563
|
| 676 |
+
|
| 677 |
+
Some symmetries and argument transformations::
|
| 678 |
+
|
| 679 |
+
>>> x,y,z = 2,3,4
|
| 680 |
+
>>> elliprf(x,y,z); elliprf(y,x,z); elliprf(z,y,x)
|
| 681 |
+
0.5840828416771517066928492
|
| 682 |
+
0.5840828416771517066928492
|
| 683 |
+
0.5840828416771517066928492
|
| 684 |
+
>>> k = mpf(100000)
|
| 685 |
+
>>> elliprf(k*x,k*y,k*z); k**(-0.5) * elliprf(x,y,z)
|
| 686 |
+
0.001847032121923321253219284
|
| 687 |
+
0.001847032121923321253219284
|
| 688 |
+
>>> l = sqrt(x*y) + sqrt(y*z) + sqrt(z*x)
|
| 689 |
+
>>> elliprf(x,y,z); 2*elliprf(x+l,y+l,z+l)
|
| 690 |
+
0.5840828416771517066928492
|
| 691 |
+
0.5840828416771517066928492
|
| 692 |
+
>>> elliprf((x+l)/4,(y+l)/4,(z+l)/4)
|
| 693 |
+
0.5840828416771517066928492
|
| 694 |
+
|
| 695 |
+
Comparing with numerical integration::
|
| 696 |
+
|
| 697 |
+
>>> x,y,z = 2,3,4
|
| 698 |
+
>>> elliprf(x,y,z)
|
| 699 |
+
0.5840828416771517066928492
|
| 700 |
+
>>> f = lambda t: 0.5*((t+x)*(t+y)*(t+z))**(-0.5)
|
| 701 |
+
>>> q = extradps(25)(quad)
|
| 702 |
+
>>> q(f, [0,inf])
|
| 703 |
+
0.5840828416771517066928492
|
| 704 |
+
|
| 705 |
+
With the following arguments, the square root in the integrand becomes
|
| 706 |
+
discontinuous at `t = 1/2` if the principal branch is used. To obtain
|
| 707 |
+
the right value, `-\sqrt{r}` must be taken instead of `\sqrt{r}`
|
| 708 |
+
on `t \in (0, 1/2)`::
|
| 709 |
+
|
| 710 |
+
>>> x,y,z = j-1,j,0
|
| 711 |
+
>>> elliprf(x,y,z)
|
| 712 |
+
(0.7961258658423391329305694 - 1.213856669836495986430094j)
|
| 713 |
+
>>> -q(f, [0,0.5]) + q(f, [0.5,inf])
|
| 714 |
+
(0.7961258658423391329305694 - 1.213856669836495986430094j)
|
| 715 |
+
|
| 716 |
+
The so-called *first lemniscate constant*, a transcendental number::
|
| 717 |
+
|
| 718 |
+
>>> elliprf(0,1,2)
|
| 719 |
+
1.31102877714605990523242
|
| 720 |
+
>>> extradps(25)(quad)(lambda t: 1/sqrt(1-t**4), [0,1])
|
| 721 |
+
1.31102877714605990523242
|
| 722 |
+
>>> gamma('1/4')**2/(4*sqrt(2*pi))
|
| 723 |
+
1.31102877714605990523242
|
| 724 |
+
|
| 725 |
+
**References**
|
| 726 |
+
|
| 727 |
+
1. [Carlson]_
|
| 728 |
+
2. [DLMF]_ Chapter 19. Elliptic Integrals
|
| 729 |
+
|
| 730 |
+
"""
|
| 731 |
+
x = ctx.convert(x)
|
| 732 |
+
y = ctx.convert(y)
|
| 733 |
+
z = ctx.convert(z)
|
| 734 |
+
prec = ctx.prec
|
| 735 |
+
try:
|
| 736 |
+
ctx.prec += 20
|
| 737 |
+
tol = ctx.eps * 2**10
|
| 738 |
+
v = RF_calc(ctx, x, y, z, tol)
|
| 739 |
+
finally:
|
| 740 |
+
ctx.prec = prec
|
| 741 |
+
return +v
|
| 742 |
+
|
| 743 |
+
@defun
|
| 744 |
+
def elliprc(ctx, x, y, pv=True):
|
| 745 |
+
r"""
|
| 746 |
+
Evaluates the degenerate Carlson symmetric elliptic integral
|
| 747 |
+
of the first kind
|
| 748 |
+
|
| 749 |
+
.. math ::
|
| 750 |
+
|
| 751 |
+
R_C(x,y) = R_F(x,y,y) =
|
| 752 |
+
\frac{1}{2} \int_0^{\infty} \frac{dt}{(t+y) \sqrt{(t+x)}}.
|
| 753 |
+
|
| 754 |
+
If `y \in (-\infty,0)`, either a value defined by continuity,
|
| 755 |
+
or with *pv=True* the Cauchy principal value, can be computed.
|
| 756 |
+
|
| 757 |
+
If `x \ge 0, y > 0`, the value can be expressed in terms of
|
| 758 |
+
elementary functions as
|
| 759 |
+
|
| 760 |
+
.. math ::
|
| 761 |
+
|
| 762 |
+
R_C(x,y) =
|
| 763 |
+
\begin{cases}
|
| 764 |
+
\dfrac{1}{\sqrt{y-x}}
|
| 765 |
+
\cos^{-1}\left(\sqrt{\dfrac{x}{y}}\right), & x < y \\
|
| 766 |
+
\dfrac{1}{\sqrt{y}}, & x = y \\
|
| 767 |
+
\dfrac{1}{\sqrt{x-y}}
|
| 768 |
+
\cosh^{-1}\left(\sqrt{\dfrac{x}{y}}\right), & x > y \\
|
| 769 |
+
\end{cases}.
|
| 770 |
+
|
| 771 |
+
**Examples**
|
| 772 |
+
|
| 773 |
+
Some special values and limits::
|
| 774 |
+
|
| 775 |
+
>>> from mpmath import *
|
| 776 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 777 |
+
>>> elliprc(1,2)*4; elliprc(0,1)*2; +pi
|
| 778 |
+
3.141592653589793238462643
|
| 779 |
+
3.141592653589793238462643
|
| 780 |
+
3.141592653589793238462643
|
| 781 |
+
>>> elliprc(1,0)
|
| 782 |
+
+inf
|
| 783 |
+
>>> elliprc(5,5)**2
|
| 784 |
+
0.2
|
| 785 |
+
>>> elliprc(1,inf); elliprc(inf,1); elliprc(inf,inf)
|
| 786 |
+
0.0
|
| 787 |
+
0.0
|
| 788 |
+
0.0
|
| 789 |
+
|
| 790 |
+
Comparing with the elementary closed-form solution::
|
| 791 |
+
|
| 792 |
+
>>> elliprc('1/3', '1/5'); sqrt(7.5)*acosh(sqrt('5/3'))
|
| 793 |
+
2.041630778983498390751238
|
| 794 |
+
2.041630778983498390751238
|
| 795 |
+
>>> elliprc('1/5', '1/3'); sqrt(7.5)*acos(sqrt('3/5'))
|
| 796 |
+
1.875180765206547065111085
|
| 797 |
+
1.875180765206547065111085
|
| 798 |
+
|
| 799 |
+
Comparing with numerical integration::
|
| 800 |
+
|
| 801 |
+
>>> q = extradps(25)(quad)
|
| 802 |
+
>>> elliprc(2, -3, pv=True)
|
| 803 |
+
0.3333969101113672670749334
|
| 804 |
+
>>> elliprc(2, -3, pv=False)
|
| 805 |
+
(0.3333969101113672670749334 + 0.7024814731040726393156375j)
|
| 806 |
+
>>> 0.5*q(lambda t: 1/(sqrt(t+2)*(t-3)), [0,3-j,6,inf])
|
| 807 |
+
(0.3333969101113672670749334 + 0.7024814731040726393156375j)
|
| 808 |
+
|
| 809 |
+
"""
|
| 810 |
+
x = ctx.convert(x)
|
| 811 |
+
y = ctx.convert(y)
|
| 812 |
+
prec = ctx.prec
|
| 813 |
+
try:
|
| 814 |
+
ctx.prec += 20
|
| 815 |
+
tol = ctx.eps * 2**10
|
| 816 |
+
v = RC_calc(ctx, x, y, tol, pv)
|
| 817 |
+
finally:
|
| 818 |
+
ctx.prec = prec
|
| 819 |
+
return +v
|
| 820 |
+
|
| 821 |
+
@defun
|
| 822 |
+
def elliprj(ctx, x, y, z, p, integration=1):
|
| 823 |
+
r"""
|
| 824 |
+
Evaluates the Carlson symmetric elliptic integral of the third kind
|
| 825 |
+
|
| 826 |
+
.. math ::
|
| 827 |
+
|
| 828 |
+
R_J(x,y,z,p) = \frac{3}{2}
|
| 829 |
+
\int_0^{\infty} \frac{dt}{(t+p)\sqrt{(t+x)(t+y)(t+z)}}.
|
| 830 |
+
|
| 831 |
+
Like :func:`~mpmath.elliprf`, the branch of the square root in the integrand
|
| 832 |
+
is defined so as to be continuous along the path of integration for
|
| 833 |
+
complex values of the arguments.
|
| 834 |
+
|
| 835 |
+
**Examples**
|
| 836 |
+
|
| 837 |
+
Some values and limits::
|
| 838 |
+
|
| 839 |
+
>>> from mpmath import *
|
| 840 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 841 |
+
>>> elliprj(1,1,1,1)
|
| 842 |
+
1.0
|
| 843 |
+
>>> elliprj(2,2,2,2); 1/(2*sqrt(2))
|
| 844 |
+
0.3535533905932737622004222
|
| 845 |
+
0.3535533905932737622004222
|
| 846 |
+
>>> elliprj(0,1,2,2)
|
| 847 |
+
1.067937989667395702268688
|
| 848 |
+
>>> 3*(2*gamma('5/4')**2-pi**2/gamma('1/4')**2)/(sqrt(2*pi))
|
| 849 |
+
1.067937989667395702268688
|
| 850 |
+
>>> elliprj(0,1,1,2); 3*pi*(2-sqrt(2))/4
|
| 851 |
+
1.380226776765915172432054
|
| 852 |
+
1.380226776765915172432054
|
| 853 |
+
>>> elliprj(1,3,2,0); elliprj(0,1,1,0); elliprj(0,0,0,0)
|
| 854 |
+
+inf
|
| 855 |
+
+inf
|
| 856 |
+
+inf
|
| 857 |
+
>>> elliprj(1,inf,1,0); elliprj(1,1,1,inf)
|
| 858 |
+
0.0
|
| 859 |
+
0.0
|
| 860 |
+
>>> chop(elliprj(1+j, 1-j, 1, 1))
|
| 861 |
+
0.8505007163686739432927844
|
| 862 |
+
|
| 863 |
+
Scale transformation::
|
| 864 |
+
|
| 865 |
+
>>> x,y,z,p = 2,3,4,5
|
| 866 |
+
>>> k = mpf(100000)
|
| 867 |
+
>>> elliprj(k*x,k*y,k*z,k*p); k**(-1.5)*elliprj(x,y,z,p)
|
| 868 |
+
4.521291677592745527851168e-9
|
| 869 |
+
4.521291677592745527851168e-9
|
| 870 |
+
|
| 871 |
+
Comparing with numerical integration::
|
| 872 |
+
|
| 873 |
+
>>> elliprj(1,2,3,4)
|
| 874 |
+
0.2398480997495677621758617
|
| 875 |
+
>>> f = lambda t: 1/((t+4)*sqrt((t+1)*(t+2)*(t+3)))
|
| 876 |
+
>>> 1.5*quad(f, [0,inf])
|
| 877 |
+
0.2398480997495677621758617
|
| 878 |
+
>>> elliprj(1,2+1j,3,4-2j)
|
| 879 |
+
(0.216888906014633498739952 + 0.04081912627366673332369512j)
|
| 880 |
+
>>> f = lambda t: 1/((t+4-2j)*sqrt((t+1)*(t+2+1j)*(t+3)))
|
| 881 |
+
>>> 1.5*quad(f, [0,inf])
|
| 882 |
+
(0.216888906014633498739952 + 0.04081912627366673332369511j)
|
| 883 |
+
|
| 884 |
+
"""
|
| 885 |
+
x = ctx.convert(x)
|
| 886 |
+
y = ctx.convert(y)
|
| 887 |
+
z = ctx.convert(z)
|
| 888 |
+
p = ctx.convert(p)
|
| 889 |
+
prec = ctx.prec
|
| 890 |
+
try:
|
| 891 |
+
ctx.prec += 20
|
| 892 |
+
tol = ctx.eps * 2**10
|
| 893 |
+
v = RJ_calc(ctx, x, y, z, p, tol, integration)
|
| 894 |
+
finally:
|
| 895 |
+
ctx.prec = prec
|
| 896 |
+
return +v
|
| 897 |
+
|
| 898 |
+
@defun
|
| 899 |
+
def elliprd(ctx, x, y, z):
|
| 900 |
+
r"""
|
| 901 |
+
Evaluates the degenerate Carlson symmetric elliptic integral
|
| 902 |
+
of the third kind or Carlson elliptic integral of the
|
| 903 |
+
second kind `R_D(x,y,z) = R_J(x,y,z,z)`.
|
| 904 |
+
|
| 905 |
+
See :func:`~mpmath.elliprj` for additional information.
|
| 906 |
+
|
| 907 |
+
**Examples**
|
| 908 |
+
|
| 909 |
+
>>> from mpmath import *
|
| 910 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 911 |
+
>>> elliprd(1,2,3)
|
| 912 |
+
0.2904602810289906442326534
|
| 913 |
+
>>> elliprj(1,2,3,3)
|
| 914 |
+
0.2904602810289906442326534
|
| 915 |
+
|
| 916 |
+
The so-called *second lemniscate constant*, a transcendental number::
|
| 917 |
+
|
| 918 |
+
>>> elliprd(0,2,1)/3
|
| 919 |
+
0.5990701173677961037199612
|
| 920 |
+
>>> extradps(25)(quad)(lambda t: t**2/sqrt(1-t**4), [0,1])
|
| 921 |
+
0.5990701173677961037199612
|
| 922 |
+
>>> gamma('3/4')**2/sqrt(2*pi)
|
| 923 |
+
0.5990701173677961037199612
|
| 924 |
+
|
| 925 |
+
"""
|
| 926 |
+
return ctx.elliprj(x,y,z,z)
|
| 927 |
+
|
| 928 |
+
@defun
|
| 929 |
+
def elliprg(ctx, x, y, z):
|
| 930 |
+
r"""
|
| 931 |
+
Evaluates the Carlson completely symmetric elliptic integral
|
| 932 |
+
of the second kind
|
| 933 |
+
|
| 934 |
+
.. math ::
|
| 935 |
+
|
| 936 |
+
R_G(x,y,z) = \frac{1}{4} \int_0^{\infty}
|
| 937 |
+
\frac{t}{\sqrt{(t+x)(t+y)(t+z)}}
|
| 938 |
+
\left( \frac{x}{t+x} + \frac{y}{t+y} + \frac{z}{t+z}\right) dt.
|
| 939 |
+
|
| 940 |
+
**Examples**
|
| 941 |
+
|
| 942 |
+
Evaluation for real and complex arguments::
|
| 943 |
+
|
| 944 |
+
>>> from mpmath import *
|
| 945 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 946 |
+
>>> elliprg(0,1,1)*4; +pi
|
| 947 |
+
3.141592653589793238462643
|
| 948 |
+
3.141592653589793238462643
|
| 949 |
+
>>> elliprg(0,0.5,1)
|
| 950 |
+
0.6753219405238377512600874
|
| 951 |
+
>>> chop(elliprg(1+j, 1-j, 2))
|
| 952 |
+
1.172431327676416604532822
|
| 953 |
+
|
| 954 |
+
A double integral that can be evaluated in terms of `R_G`::
|
| 955 |
+
|
| 956 |
+
>>> x,y,z = 2,3,4
|
| 957 |
+
>>> def f(t,u):
|
| 958 |
+
... st = fp.sin(t); ct = fp.cos(t)
|
| 959 |
+
... su = fp.sin(u); cu = fp.cos(u)
|
| 960 |
+
... return (x*(st*cu)**2 + y*(st*su)**2 + z*ct**2)**0.5 * st
|
| 961 |
+
...
|
| 962 |
+
>>> nprint(mpf(fp.quad(f, [0,fp.pi], [0,2*fp.pi])/(4*fp.pi)), 13)
|
| 963 |
+
1.725503028069
|
| 964 |
+
>>> nprint(elliprg(x,y,z), 13)
|
| 965 |
+
1.725503028069
|
| 966 |
+
|
| 967 |
+
"""
|
| 968 |
+
x = ctx.convert(x)
|
| 969 |
+
y = ctx.convert(y)
|
| 970 |
+
z = ctx.convert(z)
|
| 971 |
+
zeros = (not x) + (not y) + (not z)
|
| 972 |
+
if zeros == 3:
|
| 973 |
+
return (x+y+z)*0
|
| 974 |
+
if zeros == 2:
|
| 975 |
+
if x: return 0.5*ctx.sqrt(x)
|
| 976 |
+
if y: return 0.5*ctx.sqrt(y)
|
| 977 |
+
return 0.5*ctx.sqrt(z)
|
| 978 |
+
if zeros == 1:
|
| 979 |
+
if not z:
|
| 980 |
+
x, z = z, x
|
| 981 |
+
def terms():
|
| 982 |
+
T1 = 0.5*z*ctx.elliprf(x,y,z)
|
| 983 |
+
T2 = -0.5*(x-z)*(y-z)*ctx.elliprd(x,y,z)/3
|
| 984 |
+
T3 = 0.5*ctx.sqrt(x)*ctx.sqrt(y)/ctx.sqrt(z)
|
| 985 |
+
return T1,T2,T3
|
| 986 |
+
return ctx.sum_accurately(terms)
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
@defun_wrapped
|
| 990 |
+
def ellipf(ctx, phi, m):
|
| 991 |
+
r"""
|
| 992 |
+
Evaluates the Legendre incomplete elliptic integral of the first kind
|
| 993 |
+
|
| 994 |
+
.. math ::
|
| 995 |
+
|
| 996 |
+
F(\phi,m) = \int_0^{\phi} \frac{dt}{\sqrt{1-m \sin^2 t}}
|
| 997 |
+
|
| 998 |
+
or equivalently
|
| 999 |
+
|
| 1000 |
+
.. math ::
|
| 1001 |
+
|
| 1002 |
+
F(\phi,m) = \int_0^{\sin \phi}
|
| 1003 |
+
\frac{dt}{\left(\sqrt{1-t^2}\right)\left(\sqrt{1-mt^2}\right)}.
|
| 1004 |
+
|
| 1005 |
+
The function reduces to a complete elliptic integral of the first kind
|
| 1006 |
+
(see :func:`~mpmath.ellipk`) when `\phi = \frac{\pi}{2}`; that is,
|
| 1007 |
+
|
| 1008 |
+
.. math ::
|
| 1009 |
+
|
| 1010 |
+
F\left(\frac{\pi}{2}, m\right) = K(m).
|
| 1011 |
+
|
| 1012 |
+
In the defining integral, it is assumed that the principal branch
|
| 1013 |
+
of the square root is taken and that the path of integration avoids
|
| 1014 |
+
crossing any branch cuts. Outside `-\pi/2 \le \Re(\phi) \le \pi/2`,
|
| 1015 |
+
the function extends quasi-periodically as
|
| 1016 |
+
|
| 1017 |
+
.. math ::
|
| 1018 |
+
|
| 1019 |
+
F(\phi + n \pi, m) = 2 n K(m) + F(\phi,m), n \in \mathbb{Z}.
|
| 1020 |
+
|
| 1021 |
+
**Plots**
|
| 1022 |
+
|
| 1023 |
+
.. literalinclude :: /plots/ellipf.py
|
| 1024 |
+
.. image :: /plots/ellipf.png
|
| 1025 |
+
|
| 1026 |
+
**Examples**
|
| 1027 |
+
|
| 1028 |
+
Basic values and limits::
|
| 1029 |
+
|
| 1030 |
+
>>> from mpmath import *
|
| 1031 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 1032 |
+
>>> ellipf(0,1)
|
| 1033 |
+
0.0
|
| 1034 |
+
>>> ellipf(0,0)
|
| 1035 |
+
0.0
|
| 1036 |
+
>>> ellipf(1,0); ellipf(2+3j,0)
|
| 1037 |
+
1.0
|
| 1038 |
+
(2.0 + 3.0j)
|
| 1039 |
+
>>> ellipf(1,1); log(sec(1)+tan(1))
|
| 1040 |
+
1.226191170883517070813061
|
| 1041 |
+
1.226191170883517070813061
|
| 1042 |
+
>>> ellipf(pi/2, -0.5); ellipk(-0.5)
|
| 1043 |
+
1.415737208425956198892166
|
| 1044 |
+
1.415737208425956198892166
|
| 1045 |
+
>>> ellipf(pi/2+eps, 1); ellipf(-pi/2-eps, 1)
|
| 1046 |
+
+inf
|
| 1047 |
+
+inf
|
| 1048 |
+
>>> ellipf(1.5, 1)
|
| 1049 |
+
3.340677542798311003320813
|
| 1050 |
+
|
| 1051 |
+
Comparing with numerical integration::
|
| 1052 |
+
|
| 1053 |
+
>>> z,m = 0.5, 1.25
|
| 1054 |
+
>>> ellipf(z,m)
|
| 1055 |
+
0.5287219202206327872978255
|
| 1056 |
+
>>> quad(lambda t: (1-m*sin(t)**2)**(-0.5), [0,z])
|
| 1057 |
+
0.5287219202206327872978255
|
| 1058 |
+
|
| 1059 |
+
The arguments may be complex numbers::
|
| 1060 |
+
|
| 1061 |
+
>>> ellipf(3j, 0.5)
|
| 1062 |
+
(0.0 + 1.713602407841590234804143j)
|
| 1063 |
+
>>> ellipf(3+4j, 5-6j)
|
| 1064 |
+
(1.269131241950351323305741 - 0.3561052815014558335412538j)
|
| 1065 |
+
>>> z,m = 2+3j, 1.25
|
| 1066 |
+
>>> k = 1011
|
| 1067 |
+
>>> ellipf(z+pi*k,m); ellipf(z,m) + 2*k*ellipk(m)
|
| 1068 |
+
(4086.184383622179764082821 - 3003.003538923749396546871j)
|
| 1069 |
+
(4086.184383622179764082821 - 3003.003538923749396546871j)
|
| 1070 |
+
|
| 1071 |
+
For `|\Re(z)| < \pi/2`, the function can be expressed as a
|
| 1072 |
+
hypergeometric series of two variables
|
| 1073 |
+
(see :func:`~mpmath.appellf1`)::
|
| 1074 |
+
|
| 1075 |
+
>>> z,m = 0.5, 0.25
|
| 1076 |
+
>>> ellipf(z,m)
|
| 1077 |
+
0.5050887275786480788831083
|
| 1078 |
+
>>> sin(z)*appellf1(0.5,0.5,0.5,1.5,sin(z)**2,m*sin(z)**2)
|
| 1079 |
+
0.5050887275786480788831083
|
| 1080 |
+
|
| 1081 |
+
"""
|
| 1082 |
+
z = phi
|
| 1083 |
+
if not (ctx.isnormal(z) and ctx.isnormal(m)):
|
| 1084 |
+
if m == 0:
|
| 1085 |
+
return z + m
|
| 1086 |
+
if z == 0:
|
| 1087 |
+
return z * m
|
| 1088 |
+
if m == ctx.inf or m == ctx.ninf: return z/m
|
| 1089 |
+
raise ValueError
|
| 1090 |
+
x = z.real
|
| 1091 |
+
ctx.prec += max(0, ctx.mag(x))
|
| 1092 |
+
pi = +ctx.pi
|
| 1093 |
+
away = abs(x) > pi/2
|
| 1094 |
+
if m == 1:
|
| 1095 |
+
if away:
|
| 1096 |
+
return ctx.inf
|
| 1097 |
+
if away:
|
| 1098 |
+
d = ctx.nint(x/pi)
|
| 1099 |
+
z = z-pi*d
|
| 1100 |
+
P = 2*d*ctx.ellipk(m)
|
| 1101 |
+
else:
|
| 1102 |
+
P = 0
|
| 1103 |
+
c, s = ctx.cos_sin(z)
|
| 1104 |
+
return s * ctx.elliprf(c**2, 1-m*s**2, 1) + P
|
| 1105 |
+
|
| 1106 |
+
@defun_wrapped
|
| 1107 |
+
def ellipe(ctx, *args):
|
| 1108 |
+
r"""
|
| 1109 |
+
Called with a single argument `m`, evaluates the Legendre complete
|
| 1110 |
+
elliptic integral of the second kind, `E(m)`, defined by
|
| 1111 |
+
|
| 1112 |
+
.. math :: E(m) = \int_0^{\pi/2} \sqrt{1-m \sin^2 t} \, dt \,=\,
|
| 1113 |
+
\frac{\pi}{2}
|
| 1114 |
+
\,_2F_1\left(\frac{1}{2}, -\frac{1}{2}, 1, m\right).
|
| 1115 |
+
|
| 1116 |
+
Called with two arguments `\phi, m`, evaluates the incomplete elliptic
|
| 1117 |
+
integral of the second kind
|
| 1118 |
+
|
| 1119 |
+
.. math ::
|
| 1120 |
+
|
| 1121 |
+
E(\phi,m) = \int_0^{\phi} \sqrt{1-m \sin^2 t} \, dt =
|
| 1122 |
+
\int_0^{\sin z}
|
| 1123 |
+
\frac{\sqrt{1-mt^2}}{\sqrt{1-t^2}} \, dt.
|
| 1124 |
+
|
| 1125 |
+
The incomplete integral reduces to a complete integral when
|
| 1126 |
+
`\phi = \frac{\pi}{2}`; that is,
|
| 1127 |
+
|
| 1128 |
+
.. math ::
|
| 1129 |
+
|
| 1130 |
+
E\left(\frac{\pi}{2}, m\right) = E(m).
|
| 1131 |
+
|
| 1132 |
+
In the defining integral, it is assumed that the principal branch
|
| 1133 |
+
of the square root is taken and that the path of integration avoids
|
| 1134 |
+
crossing any branch cuts. Outside `-\pi/2 \le \Re(z) \le \pi/2`,
|
| 1135 |
+
the function extends quasi-periodically as
|
| 1136 |
+
|
| 1137 |
+
.. math ::
|
| 1138 |
+
|
| 1139 |
+
E(\phi + n \pi, m) = 2 n E(m) + E(\phi,m), n \in \mathbb{Z}.
|
| 1140 |
+
|
| 1141 |
+
**Plots**
|
| 1142 |
+
|
| 1143 |
+
.. literalinclude :: /plots/ellipe.py
|
| 1144 |
+
.. image :: /plots/ellipe.png
|
| 1145 |
+
|
| 1146 |
+
**Examples for the complete integral**
|
| 1147 |
+
|
| 1148 |
+
Basic values and limits::
|
| 1149 |
+
|
| 1150 |
+
>>> from mpmath import *
|
| 1151 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 1152 |
+
>>> ellipe(0)
|
| 1153 |
+
1.570796326794896619231322
|
| 1154 |
+
>>> ellipe(1)
|
| 1155 |
+
1.0
|
| 1156 |
+
>>> ellipe(-1)
|
| 1157 |
+
1.910098894513856008952381
|
| 1158 |
+
>>> ellipe(2)
|
| 1159 |
+
(0.5990701173677961037199612 + 0.5990701173677961037199612j)
|
| 1160 |
+
>>> ellipe(inf)
|
| 1161 |
+
(0.0 + +infj)
|
| 1162 |
+
>>> ellipe(-inf)
|
| 1163 |
+
+inf
|
| 1164 |
+
|
| 1165 |
+
Verifying the defining integral and hypergeometric
|
| 1166 |
+
representation::
|
| 1167 |
+
|
| 1168 |
+
>>> ellipe(0.5)
|
| 1169 |
+
1.350643881047675502520175
|
| 1170 |
+
>>> quad(lambda t: sqrt(1-0.5*sin(t)**2), [0, pi/2])
|
| 1171 |
+
1.350643881047675502520175
|
| 1172 |
+
>>> pi/2*hyp2f1(0.5,-0.5,1,0.5)
|
| 1173 |
+
1.350643881047675502520175
|
| 1174 |
+
|
| 1175 |
+
Evaluation is supported for arbitrary complex `m`::
|
| 1176 |
+
|
| 1177 |
+
>>> ellipe(0.5+0.25j)
|
| 1178 |
+
(1.360868682163129682716687 - 0.1238733442561786843557315j)
|
| 1179 |
+
>>> ellipe(3+4j)
|
| 1180 |
+
(1.499553520933346954333612 - 1.577879007912758274533309j)
|
| 1181 |
+
|
| 1182 |
+
A definite integral::
|
| 1183 |
+
|
| 1184 |
+
>>> quad(ellipe, [0,1])
|
| 1185 |
+
1.333333333333333333333333
|
| 1186 |
+
|
| 1187 |
+
**Examples for the incomplete integral**
|
| 1188 |
+
|
| 1189 |
+
Basic values and limits::
|
| 1190 |
+
|
| 1191 |
+
>>> ellipe(0,1)
|
| 1192 |
+
0.0
|
| 1193 |
+
>>> ellipe(0,0)
|
| 1194 |
+
0.0
|
| 1195 |
+
>>> ellipe(1,0)
|
| 1196 |
+
1.0
|
| 1197 |
+
>>> ellipe(2+3j,0)
|
| 1198 |
+
(2.0 + 3.0j)
|
| 1199 |
+
>>> ellipe(1,1); sin(1)
|
| 1200 |
+
0.8414709848078965066525023
|
| 1201 |
+
0.8414709848078965066525023
|
| 1202 |
+
>>> ellipe(pi/2, -0.5); ellipe(-0.5)
|
| 1203 |
+
1.751771275694817862026502
|
| 1204 |
+
1.751771275694817862026502
|
| 1205 |
+
>>> ellipe(pi/2, 1); ellipe(-pi/2, 1)
|
| 1206 |
+
1.0
|
| 1207 |
+
-1.0
|
| 1208 |
+
>>> ellipe(1.5, 1)
|
| 1209 |
+
0.9974949866040544309417234
|
| 1210 |
+
|
| 1211 |
+
Comparing with numerical integration::
|
| 1212 |
+
|
| 1213 |
+
>>> z,m = 0.5, 1.25
|
| 1214 |
+
>>> ellipe(z,m)
|
| 1215 |
+
0.4740152182652628394264449
|
| 1216 |
+
>>> quad(lambda t: sqrt(1-m*sin(t)**2), [0,z])
|
| 1217 |
+
0.4740152182652628394264449
|
| 1218 |
+
|
| 1219 |
+
The arguments may be complex numbers::
|
| 1220 |
+
|
| 1221 |
+
>>> ellipe(3j, 0.5)
|
| 1222 |
+
(0.0 + 7.551991234890371873502105j)
|
| 1223 |
+
>>> ellipe(3+4j, 5-6j)
|
| 1224 |
+
(24.15299022574220502424466 + 75.2503670480325997418156j)
|
| 1225 |
+
>>> k = 35
|
| 1226 |
+
>>> z,m = 2+3j, 1.25
|
| 1227 |
+
>>> ellipe(z+pi*k,m); ellipe(z,m) + 2*k*ellipe(m)
|
| 1228 |
+
(48.30138799412005235090766 + 17.47255216721987688224357j)
|
| 1229 |
+
(48.30138799412005235090766 + 17.47255216721987688224357j)
|
| 1230 |
+
|
| 1231 |
+
For `|\Re(z)| < \pi/2`, the function can be expressed as a
|
| 1232 |
+
hypergeometric series of two variables
|
| 1233 |
+
(see :func:`~mpmath.appellf1`)::
|
| 1234 |
+
|
| 1235 |
+
>>> z,m = 0.5, 0.25
|
| 1236 |
+
>>> ellipe(z,m)
|
| 1237 |
+
0.4950017030164151928870375
|
| 1238 |
+
>>> sin(z)*appellf1(0.5,0.5,-0.5,1.5,sin(z)**2,m*sin(z)**2)
|
| 1239 |
+
0.4950017030164151928870376
|
| 1240 |
+
|
| 1241 |
+
"""
|
| 1242 |
+
if len(args) == 1:
|
| 1243 |
+
return ctx._ellipe(args[0])
|
| 1244 |
+
else:
|
| 1245 |
+
phi, m = args
|
| 1246 |
+
z = phi
|
| 1247 |
+
if not (ctx.isnormal(z) and ctx.isnormal(m)):
|
| 1248 |
+
if m == 0:
|
| 1249 |
+
return z + m
|
| 1250 |
+
if z == 0:
|
| 1251 |
+
return z * m
|
| 1252 |
+
if m == ctx.inf or m == ctx.ninf:
|
| 1253 |
+
return ctx.inf
|
| 1254 |
+
raise ValueError
|
| 1255 |
+
x = z.real
|
| 1256 |
+
ctx.prec += max(0, ctx.mag(x))
|
| 1257 |
+
pi = +ctx.pi
|
| 1258 |
+
away = abs(x) > pi/2
|
| 1259 |
+
if away:
|
| 1260 |
+
d = ctx.nint(x/pi)
|
| 1261 |
+
z = z-pi*d
|
| 1262 |
+
P = 2*d*ctx.ellipe(m)
|
| 1263 |
+
else:
|
| 1264 |
+
P = 0
|
| 1265 |
+
def terms():
|
| 1266 |
+
c, s = ctx.cos_sin(z)
|
| 1267 |
+
x = c**2
|
| 1268 |
+
y = 1-m*s**2
|
| 1269 |
+
RF = ctx.elliprf(x, y, 1)
|
| 1270 |
+
RD = ctx.elliprd(x, y, 1)
|
| 1271 |
+
return s*RF, -m*s**3*RD/3
|
| 1272 |
+
return ctx.sum_accurately(terms) + P
|
| 1273 |
+
|
| 1274 |
+
@defun_wrapped
|
| 1275 |
+
def ellippi(ctx, *args):
|
| 1276 |
+
r"""
|
| 1277 |
+
Called with three arguments `n, \phi, m`, evaluates the Legendre
|
| 1278 |
+
incomplete elliptic integral of the third kind
|
| 1279 |
+
|
| 1280 |
+
.. math ::
|
| 1281 |
+
|
| 1282 |
+
\Pi(n; \phi, m) = \int_0^{\phi}
|
| 1283 |
+
\frac{dt}{(1-n \sin^2 t) \sqrt{1-m \sin^2 t}} =
|
| 1284 |
+
\int_0^{\sin \phi}
|
| 1285 |
+
\frac{dt}{(1-nt^2) \sqrt{1-t^2} \sqrt{1-mt^2}}.
|
| 1286 |
+
|
| 1287 |
+
Called with two arguments `n, m`, evaluates the complete
|
| 1288 |
+
elliptic integral of the third kind
|
| 1289 |
+
`\Pi(n,m) = \Pi(n; \frac{\pi}{2},m)`.
|
| 1290 |
+
|
| 1291 |
+
In the defining integral, it is assumed that the principal branch
|
| 1292 |
+
of the square root is taken and that the path of integration avoids
|
| 1293 |
+
crossing any branch cuts. Outside `-\pi/2 \le \Re(\phi) \le \pi/2`,
|
| 1294 |
+
the function extends quasi-periodically as
|
| 1295 |
+
|
| 1296 |
+
.. math ::
|
| 1297 |
+
|
| 1298 |
+
\Pi(n,\phi+k\pi,m) = 2k\Pi(n,m) + \Pi(n,\phi,m), k \in \mathbb{Z}.
|
| 1299 |
+
|
| 1300 |
+
**Plots**
|
| 1301 |
+
|
| 1302 |
+
.. literalinclude :: /plots/ellippi.py
|
| 1303 |
+
.. image :: /plots/ellippi.png
|
| 1304 |
+
|
| 1305 |
+
**Examples for the complete integral**
|
| 1306 |
+
|
| 1307 |
+
Some basic values and limits::
|
| 1308 |
+
|
| 1309 |
+
>>> from mpmath import *
|
| 1310 |
+
>>> mp.dps = 25; mp.pretty = True
|
| 1311 |
+
>>> ellippi(0,-5); ellipk(-5)
|
| 1312 |
+
0.9555039270640439337379334
|
| 1313 |
+
0.9555039270640439337379334
|
| 1314 |
+
>>> ellippi(inf,2)
|
| 1315 |
+
0.0
|
| 1316 |
+
>>> ellippi(2,inf)
|
| 1317 |
+
0.0
|
| 1318 |
+
>>> abs(ellippi(1,5))
|
| 1319 |
+
+inf
|
| 1320 |
+
>>> abs(ellippi(0.25,1))
|
| 1321 |
+
+inf
|
| 1322 |
+
|
| 1323 |
+
Evaluation in terms of simpler functions::
|
| 1324 |
+
|
| 1325 |
+
>>> ellippi(0.25,0.25); ellipe(0.25)/(1-0.25)
|
| 1326 |
+
1.956616279119236207279727
|
| 1327 |
+
1.956616279119236207279727
|
| 1328 |
+
>>> ellippi(3,0); pi/(2*sqrt(-2))
|
| 1329 |
+
(0.0 - 1.11072073453959156175397j)
|
| 1330 |
+
(0.0 - 1.11072073453959156175397j)
|
| 1331 |
+
>>> ellippi(-3,0); pi/(2*sqrt(4))
|
| 1332 |
+
0.7853981633974483096156609
|
| 1333 |
+
0.7853981633974483096156609
|
| 1334 |
+
|
| 1335 |
+
**Examples for the incomplete integral**
|
| 1336 |
+
|
| 1337 |
+
Basic values and limits::
|
| 1338 |
+
|
| 1339 |
+
>>> ellippi(0.25,-0.5); ellippi(0.25,pi/2,-0.5)
|
| 1340 |
+
1.622944760954741603710555
|
| 1341 |
+
1.622944760954741603710555
|
| 1342 |
+
>>> ellippi(1,0,1)
|
| 1343 |
+
0.0
|
| 1344 |
+
>>> ellippi(inf,0,1)
|
| 1345 |
+
0.0
|
| 1346 |
+
>>> ellippi(0,0.25,0.5); ellipf(0.25,0.5)
|
| 1347 |
+
0.2513040086544925794134591
|
| 1348 |
+
0.2513040086544925794134591
|
| 1349 |
+
>>> ellippi(1,1,1); (log(sec(1)+tan(1))+sec(1)*tan(1))/2
|
| 1350 |
+
2.054332933256248668692452
|
| 1351 |
+
2.054332933256248668692452
|
| 1352 |
+
>>> ellippi(0.25, 53*pi/2, 0.75); 53*ellippi(0.25,0.75)
|
| 1353 |
+
135.240868757890840755058
|
| 1354 |
+
135.240868757890840755058
|
| 1355 |
+
>>> ellippi(0.5,pi/4,0.5); 2*ellipe(pi/4,0.5)-1/sqrt(3)
|
| 1356 |
+
0.9190227391656969903987269
|
| 1357 |
+
0.9190227391656969903987269
|
| 1358 |
+
|
| 1359 |
+
Complex arguments are supported::
|
| 1360 |
+
|
| 1361 |
+
>>> ellippi(0.5, 5+6j-2*pi, -7-8j)
|
| 1362 |
+
(-0.3612856620076747660410167 + 0.5217735339984807829755815j)
|
| 1363 |
+
|
| 1364 |
+
Some degenerate cases::
|
| 1365 |
+
|
| 1366 |
+
>>> ellippi(1,1)
|
| 1367 |
+
+inf
|
| 1368 |
+
>>> ellippi(1,0)
|
| 1369 |
+
+inf
|
| 1370 |
+
>>> ellippi(1,2,0)
|
| 1371 |
+
+inf
|
| 1372 |
+
>>> ellippi(1,2,1)
|
| 1373 |
+
+inf
|
| 1374 |
+
>>> ellippi(1,0,1)
|
| 1375 |
+
0.0
|
| 1376 |
+
|
| 1377 |
+
"""
|
| 1378 |
+
if len(args) == 2:
|
| 1379 |
+
n, m = args
|
| 1380 |
+
complete = True
|
| 1381 |
+
z = phi = ctx.pi/2
|
| 1382 |
+
else:
|
| 1383 |
+
n, phi, m = args
|
| 1384 |
+
complete = False
|
| 1385 |
+
z = phi
|
| 1386 |
+
if not (ctx.isnormal(n) and ctx.isnormal(z) and ctx.isnormal(m)):
|
| 1387 |
+
if ctx.isnan(n) or ctx.isnan(z) or ctx.isnan(m):
|
| 1388 |
+
raise ValueError
|
| 1389 |
+
if complete:
|
| 1390 |
+
if m == 0:
|
| 1391 |
+
if n == 1:
|
| 1392 |
+
return ctx.inf
|
| 1393 |
+
return ctx.pi/(2*ctx.sqrt(1-n))
|
| 1394 |
+
if n == 0: return ctx.ellipk(m)
|
| 1395 |
+
if ctx.isinf(n) or ctx.isinf(m): return ctx.zero
|
| 1396 |
+
else:
|
| 1397 |
+
if z == 0: return z
|
| 1398 |
+
if ctx.isinf(n): return ctx.zero
|
| 1399 |
+
if ctx.isinf(m): return ctx.zero
|
| 1400 |
+
if ctx.isinf(n) or ctx.isinf(z) or ctx.isinf(m):
|
| 1401 |
+
raise ValueError
|
| 1402 |
+
if complete:
|
| 1403 |
+
if m == 1:
|
| 1404 |
+
if n == 1:
|
| 1405 |
+
return ctx.inf
|
| 1406 |
+
return -ctx.inf/ctx.sign(n-1)
|
| 1407 |
+
away = False
|
| 1408 |
+
else:
|
| 1409 |
+
x = z.real
|
| 1410 |
+
ctx.prec += max(0, ctx.mag(x))
|
| 1411 |
+
pi = +ctx.pi
|
| 1412 |
+
away = abs(x) > pi/2
|
| 1413 |
+
if away:
|
| 1414 |
+
d = ctx.nint(x/pi)
|
| 1415 |
+
z = z-pi*d
|
| 1416 |
+
P = 2*d*ctx.ellippi(n,m)
|
| 1417 |
+
if ctx.isinf(P):
|
| 1418 |
+
return ctx.inf
|
| 1419 |
+
else:
|
| 1420 |
+
P = 0
|
| 1421 |
+
def terms():
|
| 1422 |
+
if complete:
|
| 1423 |
+
c, s = ctx.zero, ctx.one
|
| 1424 |
+
else:
|
| 1425 |
+
c, s = ctx.cos_sin(z)
|
| 1426 |
+
x = c**2
|
| 1427 |
+
y = 1-m*s**2
|
| 1428 |
+
RF = ctx.elliprf(x, y, 1)
|
| 1429 |
+
RJ = ctx.elliprj(x, y, 1, 1-n*s**2)
|
| 1430 |
+
return s*RF, n*s**3*RJ/3
|
| 1431 |
+
return ctx.sum_accurately(terms) + P
|
shared/package-files/ab/ab3f08d9f8e6a7cf2f05beaac6af33cce76ce7b8eeb5500095ed4cb58dc6e6ac/blob
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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8 |
+
namespace c10 {
|
| 9 |
+
|
| 10 |
+
namespace detail {
|
| 11 |
+
|
| 12 |
+
struct IncrementRAII final {
|
| 13 |
+
public:
|
| 14 |
+
explicit IncrementRAII(std::atomic<int32_t>* counter) : _counter(counter) {
|
| 15 |
+
_counter->fetch_add(1);
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
~IncrementRAII() {
|
| 19 |
+
_counter->fetch_sub(1);
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
private:
|
| 23 |
+
std::atomic<int32_t>* _counter;
|
| 24 |
+
|
| 25 |
+
C10_DISABLE_COPY_AND_ASSIGN(IncrementRAII);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
} // namespace detail
|
| 29 |
+
|
| 30 |
+
// LeftRight wait-free readers synchronization primitive
|
| 31 |
+
// https://hal.archives-ouvertes.fr/hal-01207881/document
|
| 32 |
+
//
|
| 33 |
+
// LeftRight is quite easy to use (it can make an arbitrary
|
| 34 |
+
// data structure permit wait-free reads), but it has some
|
| 35 |
+
// particular performance characteristics you should be aware
|
| 36 |
+
// of if you're deciding to use it:
|
| 37 |
+
//
|
| 38 |
+
// - Reads still incur an atomic write (this is how LeftRight
|
| 39 |
+
// keeps track of how long it needs to keep around the old
|
| 40 |
+
// data structure)
|
| 41 |
+
//
|
| 42 |
+
// - Writes get executed twice, to keep both the left and right
|
| 43 |
+
// versions up to date. So if your write is expensive or
|
| 44 |
+
// nondeterministic, this is also an inappropriate structure
|
| 45 |
+
//
|
| 46 |
+
// LeftRight is used fairly rarely in PyTorch's codebase. If you
|
| 47 |
+
// are still not sure if you need it or not, consult your local
|
| 48 |
+
// C++ expert.
|
| 49 |
+
//
|
| 50 |
+
template <class T>
|
| 51 |
+
class LeftRight final {
|
| 52 |
+
public:
|
| 53 |
+
template <class... Args>
|
| 54 |
+
explicit LeftRight(const Args&... args)
|
| 55 |
+
: _counters{{{0}, {0}}},
|
| 56 |
+
_foregroundCounterIndex(0),
|
| 57 |
+
_foregroundDataIndex(0),
|
| 58 |
+
_data{{T{args...}, T{args...}}},
|
| 59 |
+
_writeMutex() {}
|
| 60 |
+
|
| 61 |
+
// Copying and moving would not be threadsafe.
|
| 62 |
+
// Needs more thought and careful design to make that work.
|
| 63 |
+
LeftRight(const LeftRight&) = delete;
|
| 64 |
+
LeftRight(LeftRight&&) noexcept = delete;
|
| 65 |
+
LeftRight& operator=(const LeftRight&) = delete;
|
| 66 |
+
LeftRight& operator=(LeftRight&&) noexcept = delete;
|
| 67 |
+
|
| 68 |
+
~LeftRight() {
|
| 69 |
+
// wait until any potentially running writers are finished
|
| 70 |
+
{ std::unique_lock<std::mutex> lock(_writeMutex); }
|
| 71 |
+
|
| 72 |
+
// wait until any potentially running readers are finished
|
| 73 |
+
while (_counters[0].load() != 0 || _counters[1].load() != 0) {
|
| 74 |
+
std::this_thread::yield();
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
template <typename F>
|
| 79 |
+
auto read(F&& readFunc) const {
|
| 80 |
+
detail::IncrementRAII _increment_counter(
|
| 81 |
+
&_counters[_foregroundCounterIndex.load()]);
|
| 82 |
+
|
| 83 |
+
return std::forward<F>(readFunc)(_data[_foregroundDataIndex.load()]);
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
// Throwing an exception in writeFunc is ok but causes the state to be either
|
| 87 |
+
// the old or the new state, depending on if the first or the second call to
|
| 88 |
+
// writeFunc threw.
|
| 89 |
+
template <typename F>
|
| 90 |
+
auto write(F&& writeFunc) {
|
| 91 |
+
std::unique_lock<std::mutex> lock(_writeMutex);
|
| 92 |
+
|
| 93 |
+
return _write(std::forward<F>(writeFunc));
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
private:
|
| 97 |
+
template <class F>
|
| 98 |
+
auto _write(const F& writeFunc) {
|
| 99 |
+
/*
|
| 100 |
+
* Assume, A is in background and B in foreground. In simplified terms, we
|
| 101 |
+
* want to do the following:
|
| 102 |
+
* 1. Write to A (old background)
|
| 103 |
+
* 2. Switch A/B
|
| 104 |
+
* 3. Write to B (new background)
|
| 105 |
+
*
|
| 106 |
+
* More detailed algorithm (explanations on why this is important are below
|
| 107 |
+
* in code):
|
| 108 |
+
* 1. Write to A
|
| 109 |
+
* 2. Switch A/B data pointers
|
| 110 |
+
* 3. Wait until A counter is zero
|
| 111 |
+
* 4. Switch A/B counters
|
| 112 |
+
* 5. Wait until B counter is zero
|
| 113 |
+
* 6. Write to B
|
| 114 |
+
*/
|
| 115 |
+
|
| 116 |
+
auto localDataIndex = _foregroundDataIndex.load();
|
| 117 |
+
|
| 118 |
+
// 1. Write to A
|
| 119 |
+
_callWriteFuncOnBackgroundInstance(writeFunc, localDataIndex);
|
| 120 |
+
|
| 121 |
+
// 2. Switch A/B data pointers
|
| 122 |
+
localDataIndex = localDataIndex ^ 1;
|
| 123 |
+
_foregroundDataIndex = localDataIndex;
|
| 124 |
+
|
| 125 |
+
/*
|
| 126 |
+
* 3. Wait until A counter is zero
|
| 127 |
+
*
|
| 128 |
+
* In the previous write run, A was foreground and B was background.
|
| 129 |
+
* There was a time after switching _foregroundDataIndex (B to foreground)
|
| 130 |
+
* and before switching _foregroundCounterIndex, in which new readers could
|
| 131 |
+
* have read B but incremented A's counter.
|
| 132 |
+
*
|
| 133 |
+
* In this current run, we just switched _foregroundDataIndex (A back to
|
| 134 |
+
* foreground), but before writing to the new background B, we have to make
|
| 135 |
+
* sure A's counter was zero briefly, so all these old readers are gone.
|
| 136 |
+
*/
|
| 137 |
+
auto localCounterIndex = _foregroundCounterIndex.load();
|
| 138 |
+
_waitForBackgroundCounterToBeZero(localCounterIndex);
|
| 139 |
+
|
| 140 |
+
/*
|
| 141 |
+
* 4. Switch A/B counters
|
| 142 |
+
*
|
| 143 |
+
* Now that we know all readers on B are really gone, we can switch the
|
| 144 |
+
* counters and have new readers increment A's counter again, which is the
|
| 145 |
+
* correct counter since they're reading A.
|
| 146 |
+
*/
|
| 147 |
+
localCounterIndex = localCounterIndex ^ 1;
|
| 148 |
+
_foregroundCounterIndex = localCounterIndex;
|
| 149 |
+
|
| 150 |
+
/*
|
| 151 |
+
* 5. Wait until B counter is zero
|
| 152 |
+
*
|
| 153 |
+
* This waits for all the readers on B that came in while both data and
|
| 154 |
+
* counter for B was in foreground, i.e. normal readers that happened
|
| 155 |
+
* outside of that brief gap between switching data and counter.
|
| 156 |
+
*/
|
| 157 |
+
_waitForBackgroundCounterToBeZero(localCounterIndex);
|
| 158 |
+
|
| 159 |
+
// 6. Write to B
|
| 160 |
+
return _callWriteFuncOnBackgroundInstance(writeFunc, localDataIndex);
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
template <class F>
|
| 164 |
+
auto _callWriteFuncOnBackgroundInstance(
|
| 165 |
+
const F& writeFunc,
|
| 166 |
+
uint8_t localDataIndex) {
|
| 167 |
+
try {
|
| 168 |
+
return writeFunc(_data[localDataIndex ^ 1]);
|
| 169 |
+
} catch (...) {
|
| 170 |
+
// recover invariant by copying from the foreground instance
|
| 171 |
+
_data[localDataIndex ^ 1] = _data[localDataIndex];
|
| 172 |
+
// rethrow
|
| 173 |
+
throw;
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
void _waitForBackgroundCounterToBeZero(uint8_t counterIndex) {
|
| 178 |
+
while (_counters[counterIndex ^ 1].load() != 0) {
|
| 179 |
+
std::this_thread::yield();
|
| 180 |
+
}
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
mutable std::array<std::atomic<int32_t>, 2> _counters;
|
| 184 |
+
std::atomic<uint8_t> _foregroundCounterIndex;
|
| 185 |
+
std::atomic<uint8_t> _foregroundDataIndex;
|
| 186 |
+
std::array<T, 2> _data;
|
| 187 |
+
std::mutex _writeMutex;
|
| 188 |
+
};
|
| 189 |
+
|
| 190 |
+
// RWSafeLeftRightWrapper is API compatible with LeftRight and uses a
|
| 191 |
+
// read-write lock to protect T (data).
|
| 192 |
+
template <class T>
|
| 193 |
+
class RWSafeLeftRightWrapper final {
|
| 194 |
+
public:
|
| 195 |
+
template <class... Args>
|
| 196 |
+
explicit RWSafeLeftRightWrapper(const Args&... args) : data_{args...} {}
|
| 197 |
+
|
| 198 |
+
// RWSafeLeftRightWrapper is not copyable or moveable since LeftRight
|
| 199 |
+
// is not copyable or moveable.
|
| 200 |
+
RWSafeLeftRightWrapper(const RWSafeLeftRightWrapper&) = delete;
|
| 201 |
+
RWSafeLeftRightWrapper(RWSafeLeftRightWrapper&&) noexcept = delete;
|
| 202 |
+
RWSafeLeftRightWrapper& operator=(const RWSafeLeftRightWrapper&) = delete;
|
| 203 |
+
RWSafeLeftRightWrapper& operator=(RWSafeLeftRightWrapper&&) noexcept = delete;
|
| 204 |
+
|
| 205 |
+
template <typename F>
|
| 206 |
+
// NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
|
| 207 |
+
auto read(F&& readFunc) const {
|
| 208 |
+
return data_.withLock(
|
| 209 |
+
[&readFunc](T const& data) { return std::forward<F>(readFunc)(data); });
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
template <typename F>
|
| 213 |
+
// NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
|
| 214 |
+
auto write(F&& writeFunc) {
|
| 215 |
+
return data_.withLock(
|
| 216 |
+
[&writeFunc](T& data) { return std::forward<F>(writeFunc)(data); });
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
private:
|
| 220 |
+
c10::Synchronized<T> data_;
|
| 221 |
+
};
|
| 222 |
+
|
| 223 |
+
} // namespace c10
|
shared/package-files/ab/ab417fe03d04b9cecfbfaebaf029e50688ab8d7f83aba38435eab9142ab76b30/blob
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Set
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
# This module is defined in torch/csrc/distributed/autograd/init.cpp
|
| 6 |
+
|
| 7 |
+
class DistAutogradContext:
|
| 8 |
+
def _context_id(self) -> int: ...
|
| 9 |
+
def _recv_functions(self) -> Dict[int, Any]: ...
|
| 10 |
+
def _send_functions(self) -> Dict[int, Any]: ...
|
| 11 |
+
def _known_worker_ids(self) -> Set[int]: ...
|
| 12 |
+
|
| 13 |
+
def _new_context() -> DistAutogradContext: ...
|
| 14 |
+
def _release_context(context_id: int) -> None: ...
|
| 15 |
+
def _get_max_id() -> int: ...
|
| 16 |
+
def _is_valid_context(worker_id: int) -> bool: ...
|
| 17 |
+
def _retrieve_context(context_id: int) -> DistAutogradContext: ...
|
| 18 |
+
def _current_context() -> DistAutogradContext: ...
|
| 19 |
+
def _init(worker_id: int) -> None: ...
|
| 20 |
+
def _get_debug_info() -> Dict[str, str]: ...
|
| 21 |
+
def backward(
|
| 22 |
+
context_id: int,
|
| 23 |
+
roots: List[torch.Tensor],
|
| 24 |
+
retain_graph=False,
|
| 25 |
+
) -> None: ...
|
| 26 |
+
def get_gradients(context_id: int) -> Dict[torch.Tensor, torch.Tensor]: ...
|
shared/package-files/ab/ab4227e437234e0e8ba80418f90d7f5a7986efee0c84606a20c0eb4aecaccfc6/blob
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import signal
|
| 2 |
+
import sys
|
| 3 |
+
from numba import njit
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def sigterm_handler(signum, frame):
|
| 8 |
+
raise RuntimeError("Caught SIGTERM")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@njit(parallel=True)
|
| 12 |
+
def busy_func_inner(a, b):
|
| 13 |
+
c = a + b * np.sqrt(a) + np.sqrt(b)
|
| 14 |
+
d = np.sqrt(a + b * np.sqrt(a) + np.sqrt(b))
|
| 15 |
+
return c + d
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def busy_func(a, b, q=None):
|
| 19 |
+
sys.stdout.flush()
|
| 20 |
+
sys.stderr.flush()
|
| 21 |
+
signal.signal(signal.SIGTERM, sigterm_handler)
|
| 22 |
+
try:
|
| 23 |
+
z = busy_func_inner(a, b)
|
| 24 |
+
sys.stdout.flush()
|
| 25 |
+
sys.stderr.flush()
|
| 26 |
+
return z
|
| 27 |
+
except Exception as e:
|
| 28 |
+
if q is not None:
|
| 29 |
+
q.put(e)
|
shared/package-files/ab/ab439ca41391e16cdc42a2b16f7bbe3222f1bc12dc3caea1fde39225454ea2c8/blob
ADDED
|
@@ -0,0 +1,2421 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
# cython: profile=False
|
| 19 |
+
# distutils: language = c++
|
| 20 |
+
|
| 21 |
+
from collections.abc import Sequence
|
| 22 |
+
from textwrap import indent
|
| 23 |
+
import warnings
|
| 24 |
+
|
| 25 |
+
from cython.operator cimport dereference as deref
|
| 26 |
+
from pyarrow.includes.common cimport *
|
| 27 |
+
from pyarrow.includes.libarrow cimport *
|
| 28 |
+
from pyarrow.includes.libarrow_python cimport *
|
| 29 |
+
from pyarrow.lib cimport (_Weakrefable, Buffer, Schema,
|
| 30 |
+
check_status,
|
| 31 |
+
MemoryPool, maybe_unbox_memory_pool,
|
| 32 |
+
Table, KeyValueMetadata,
|
| 33 |
+
pyarrow_wrap_chunked_array,
|
| 34 |
+
pyarrow_wrap_schema,
|
| 35 |
+
pyarrow_unwrap_data_type,
|
| 36 |
+
pyarrow_unwrap_metadata,
|
| 37 |
+
pyarrow_unwrap_schema,
|
| 38 |
+
pyarrow_wrap_table,
|
| 39 |
+
pyarrow_wrap_batch,
|
| 40 |
+
pyarrow_wrap_scalar,
|
| 41 |
+
NativeFile, get_reader, get_writer,
|
| 42 |
+
string_to_timeunit)
|
| 43 |
+
|
| 44 |
+
from pyarrow.lib import (ArrowException, NativeFile, BufferOutputStream,
|
| 45 |
+
ListType, LargeListType,
|
| 46 |
+
_stringify_path,
|
| 47 |
+
tobytes, frombytes, is_threading_enabled)
|
| 48 |
+
|
| 49 |
+
cimport cpython as cp
|
| 50 |
+
|
| 51 |
+
_DEFAULT_ROW_GROUP_SIZE = 1024*1024
|
| 52 |
+
_MAX_ROW_GROUP_SIZE = 64*1024*1024
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
cdef Type _unwrap_list_type(obj) except *:
|
| 56 |
+
if obj is ListType:
|
| 57 |
+
return _Type_LIST
|
| 58 |
+
elif obj is LargeListType:
|
| 59 |
+
return _Type_LARGE_LIST
|
| 60 |
+
else:
|
| 61 |
+
raise TypeError(f"Unexpected list_type: {obj!r}")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
cdef class Statistics(_Weakrefable):
|
| 65 |
+
"""Statistics for a single column in a single row group."""
|
| 66 |
+
|
| 67 |
+
def __init__(self):
|
| 68 |
+
raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly")
|
| 69 |
+
|
| 70 |
+
def __cinit__(self):
|
| 71 |
+
pass
|
| 72 |
+
|
| 73 |
+
def __repr__(self):
|
| 74 |
+
return f"""{object.__repr__(self)}
|
| 75 |
+
has_min_max: {self.has_min_max}
|
| 76 |
+
min: {self.min}
|
| 77 |
+
max: {self.max}
|
| 78 |
+
null_count: {self.null_count}
|
| 79 |
+
distinct_count: {self.distinct_count}
|
| 80 |
+
num_values: {self.num_values}
|
| 81 |
+
physical_type: {self.physical_type}
|
| 82 |
+
logical_type: {self.logical_type}
|
| 83 |
+
converted_type (legacy): {self.converted_type}"""
|
| 84 |
+
|
| 85 |
+
def to_dict(self):
|
| 86 |
+
"""
|
| 87 |
+
Get dictionary representation of statistics.
|
| 88 |
+
|
| 89 |
+
Returns
|
| 90 |
+
-------
|
| 91 |
+
dict
|
| 92 |
+
Dictionary with a key for each attribute of this class.
|
| 93 |
+
"""
|
| 94 |
+
d = dict(
|
| 95 |
+
has_min_max=self.has_min_max,
|
| 96 |
+
min=self.min,
|
| 97 |
+
max=self.max,
|
| 98 |
+
null_count=self.null_count,
|
| 99 |
+
distinct_count=self.distinct_count,
|
| 100 |
+
num_values=self.num_values,
|
| 101 |
+
physical_type=self.physical_type
|
| 102 |
+
)
|
| 103 |
+
return d
|
| 104 |
+
|
| 105 |
+
def __eq__(self, other):
|
| 106 |
+
try:
|
| 107 |
+
return self.equals(other)
|
| 108 |
+
except TypeError:
|
| 109 |
+
return NotImplemented
|
| 110 |
+
|
| 111 |
+
def equals(self, Statistics other):
|
| 112 |
+
"""
|
| 113 |
+
Return whether the two column statistics objects are equal.
|
| 114 |
+
|
| 115 |
+
Parameters
|
| 116 |
+
----------
|
| 117 |
+
other : Statistics
|
| 118 |
+
Statistics to compare against.
|
| 119 |
+
|
| 120 |
+
Returns
|
| 121 |
+
-------
|
| 122 |
+
are_equal : bool
|
| 123 |
+
"""
|
| 124 |
+
return self.statistics.get().Equals(deref(other.statistics.get()))
|
| 125 |
+
|
| 126 |
+
@property
|
| 127 |
+
def has_min_max(self):
|
| 128 |
+
"""Whether min and max are present (bool)."""
|
| 129 |
+
return self.statistics.get().HasMinMax()
|
| 130 |
+
|
| 131 |
+
@property
|
| 132 |
+
def has_null_count(self):
|
| 133 |
+
"""Whether null count is present (bool)."""
|
| 134 |
+
return self.statistics.get().HasNullCount()
|
| 135 |
+
|
| 136 |
+
@property
|
| 137 |
+
def has_distinct_count(self):
|
| 138 |
+
"""Whether distinct count is preset (bool)."""
|
| 139 |
+
return self.statistics.get().HasDistinctCount()
|
| 140 |
+
|
| 141 |
+
@property
|
| 142 |
+
def min_raw(self):
|
| 143 |
+
"""Min value as physical type (bool, int, float, or bytes)."""
|
| 144 |
+
if self.has_min_max:
|
| 145 |
+
return _cast_statistic_raw_min(self.statistics.get())
|
| 146 |
+
else:
|
| 147 |
+
return None
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def max_raw(self):
|
| 151 |
+
"""Max value as physical type (bool, int, float, or bytes)."""
|
| 152 |
+
if self.has_min_max:
|
| 153 |
+
return _cast_statistic_raw_max(self.statistics.get())
|
| 154 |
+
else:
|
| 155 |
+
return None
|
| 156 |
+
|
| 157 |
+
@property
|
| 158 |
+
def min(self):
|
| 159 |
+
"""
|
| 160 |
+
Min value as logical type.
|
| 161 |
+
|
| 162 |
+
Returned as the Python equivalent of logical type, such as datetime.date
|
| 163 |
+
for dates and decimal.Decimal for decimals.
|
| 164 |
+
"""
|
| 165 |
+
if self.has_min_max:
|
| 166 |
+
min_scalar, _ = _cast_statistics(self.statistics.get())
|
| 167 |
+
return min_scalar.as_py()
|
| 168 |
+
else:
|
| 169 |
+
return None
|
| 170 |
+
|
| 171 |
+
@property
|
| 172 |
+
def max(self):
|
| 173 |
+
"""
|
| 174 |
+
Max value as logical type.
|
| 175 |
+
|
| 176 |
+
Returned as the Python equivalent of logical type, such as datetime.date
|
| 177 |
+
for dates and decimal.Decimal for decimals.
|
| 178 |
+
"""
|
| 179 |
+
if self.has_min_max:
|
| 180 |
+
_, max_scalar = _cast_statistics(self.statistics.get())
|
| 181 |
+
return max_scalar.as_py()
|
| 182 |
+
else:
|
| 183 |
+
return None
|
| 184 |
+
|
| 185 |
+
@property
|
| 186 |
+
def null_count(self):
|
| 187 |
+
"""Number of null values in chunk (int)."""
|
| 188 |
+
if self.has_null_count:
|
| 189 |
+
return self.statistics.get().null_count()
|
| 190 |
+
else:
|
| 191 |
+
return None
|
| 192 |
+
|
| 193 |
+
@property
|
| 194 |
+
def distinct_count(self):
|
| 195 |
+
"""Distinct number of values in chunk (int)."""
|
| 196 |
+
if self.has_distinct_count:
|
| 197 |
+
return self.statistics.get().distinct_count()
|
| 198 |
+
else:
|
| 199 |
+
return None
|
| 200 |
+
|
| 201 |
+
@property
|
| 202 |
+
def num_values(self):
|
| 203 |
+
"""Number of non-null values (int)."""
|
| 204 |
+
return self.statistics.get().num_values()
|
| 205 |
+
|
| 206 |
+
@property
|
| 207 |
+
def physical_type(self):
|
| 208 |
+
"""Physical type of column (str)."""
|
| 209 |
+
raw_physical_type = self.statistics.get().physical_type()
|
| 210 |
+
return physical_type_name_from_enum(raw_physical_type)
|
| 211 |
+
|
| 212 |
+
@property
|
| 213 |
+
def logical_type(self):
|
| 214 |
+
"""Logical type of column (:class:`ParquetLogicalType`)."""
|
| 215 |
+
return wrap_logical_type(self.statistics.get().descr().logical_type())
|
| 216 |
+
|
| 217 |
+
@property
|
| 218 |
+
def converted_type(self):
|
| 219 |
+
"""Legacy converted type (str or None)."""
|
| 220 |
+
raw_converted_type = self.statistics.get().descr().converted_type()
|
| 221 |
+
return converted_type_name_from_enum(raw_converted_type)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
cdef class ParquetLogicalType(_Weakrefable):
|
| 225 |
+
"""Logical type of parquet type."""
|
| 226 |
+
|
| 227 |
+
def __init__(self):
|
| 228 |
+
raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly")
|
| 229 |
+
|
| 230 |
+
cdef:
|
| 231 |
+
shared_ptr[const CParquetLogicalType] type
|
| 232 |
+
|
| 233 |
+
def __cinit__(self):
|
| 234 |
+
pass
|
| 235 |
+
|
| 236 |
+
cdef init(self, const shared_ptr[const CParquetLogicalType]& type):
|
| 237 |
+
self.type = type
|
| 238 |
+
|
| 239 |
+
def __repr__(self):
|
| 240 |
+
return f"{object.__repr__(self)}\n {self}"
|
| 241 |
+
|
| 242 |
+
def __str__(self):
|
| 243 |
+
return frombytes(self.type.get().ToString(), safe=True)
|
| 244 |
+
|
| 245 |
+
def to_json(self):
|
| 246 |
+
"""
|
| 247 |
+
Get a JSON string containing type and type parameters.
|
| 248 |
+
|
| 249 |
+
Returns
|
| 250 |
+
-------
|
| 251 |
+
json : str
|
| 252 |
+
JSON representation of type, with at least a field called 'Type'
|
| 253 |
+
which contains the type name. If the type is parameterized, such
|
| 254 |
+
as a decimal with scale and precision, will contain those as fields
|
| 255 |
+
as well.
|
| 256 |
+
"""
|
| 257 |
+
return frombytes(self.type.get().ToJSON())
|
| 258 |
+
|
| 259 |
+
@property
|
| 260 |
+
def type(self):
|
| 261 |
+
"""Name of the logical type (str)."""
|
| 262 |
+
return logical_type_name_from_enum(self.type.get().type())
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
cdef wrap_logical_type(const shared_ptr[const CParquetLogicalType]& type):
|
| 266 |
+
cdef ParquetLogicalType out = ParquetLogicalType.__new__(ParquetLogicalType)
|
| 267 |
+
out.init(type)
|
| 268 |
+
return out
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
cdef _cast_statistic_raw_min(CStatistics* statistics):
|
| 272 |
+
cdef ParquetType physical_type = statistics.physical_type()
|
| 273 |
+
cdef uint32_t type_length = statistics.descr().type_length()
|
| 274 |
+
if physical_type == ParquetType_BOOLEAN:
|
| 275 |
+
return (<CBoolStatistics*> statistics).min()
|
| 276 |
+
elif physical_type == ParquetType_INT32:
|
| 277 |
+
return (<CInt32Statistics*> statistics).min()
|
| 278 |
+
elif physical_type == ParquetType_INT64:
|
| 279 |
+
return (<CInt64Statistics*> statistics).min()
|
| 280 |
+
elif physical_type == ParquetType_FLOAT:
|
| 281 |
+
return (<CFloatStatistics*> statistics).min()
|
| 282 |
+
elif physical_type == ParquetType_DOUBLE:
|
| 283 |
+
return (<CDoubleStatistics*> statistics).min()
|
| 284 |
+
elif physical_type == ParquetType_BYTE_ARRAY:
|
| 285 |
+
return _box_byte_array((<CByteArrayStatistics*> statistics).min())
|
| 286 |
+
elif physical_type == ParquetType_FIXED_LEN_BYTE_ARRAY:
|
| 287 |
+
return _box_flba((<CFLBAStatistics*> statistics).min(), type_length)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
cdef _cast_statistic_raw_max(CStatistics* statistics):
|
| 291 |
+
cdef ParquetType physical_type = statistics.physical_type()
|
| 292 |
+
cdef uint32_t type_length = statistics.descr().type_length()
|
| 293 |
+
if physical_type == ParquetType_BOOLEAN:
|
| 294 |
+
return (<CBoolStatistics*> statistics).max()
|
| 295 |
+
elif physical_type == ParquetType_INT32:
|
| 296 |
+
return (<CInt32Statistics*> statistics).max()
|
| 297 |
+
elif physical_type == ParquetType_INT64:
|
| 298 |
+
return (<CInt64Statistics*> statistics).max()
|
| 299 |
+
elif physical_type == ParquetType_FLOAT:
|
| 300 |
+
return (<CFloatStatistics*> statistics).max()
|
| 301 |
+
elif physical_type == ParquetType_DOUBLE:
|
| 302 |
+
return (<CDoubleStatistics*> statistics).max()
|
| 303 |
+
elif physical_type == ParquetType_BYTE_ARRAY:
|
| 304 |
+
return _box_byte_array((<CByteArrayStatistics*> statistics).max())
|
| 305 |
+
elif physical_type == ParquetType_FIXED_LEN_BYTE_ARRAY:
|
| 306 |
+
return _box_flba((<CFLBAStatistics*> statistics).max(), type_length)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
cdef _cast_statistics(CStatistics* statistics):
|
| 310 |
+
cdef:
|
| 311 |
+
shared_ptr[CScalar] c_min
|
| 312 |
+
shared_ptr[CScalar] c_max
|
| 313 |
+
check_status(StatisticsAsScalars(statistics[0], &c_min, &c_max))
|
| 314 |
+
return (pyarrow_wrap_scalar(c_min), pyarrow_wrap_scalar(c_max))
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
cdef _box_byte_array(ParquetByteArray val):
|
| 318 |
+
return cp.PyBytes_FromStringAndSize(<char*> val.ptr, <Py_ssize_t> val.len)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
cdef _box_flba(ParquetFLBA val, uint32_t len):
|
| 322 |
+
return cp.PyBytes_FromStringAndSize(<char*> val.ptr, <Py_ssize_t> len)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
cdef class GeoStatistics(_Weakrefable):
|
| 326 |
+
"""Statistics for columns with geospatial data types (experimental)
|
| 327 |
+
|
| 328 |
+
These statistics provide a bounding box and list of geometry types for
|
| 329 |
+
geospatial columns (GEOMETRY or GEOGRAPHY). All components may be None
|
| 330 |
+
if a file does not provide information about a particular component.
|
| 331 |
+
"""
|
| 332 |
+
|
| 333 |
+
def __init__(self):
|
| 334 |
+
raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly")
|
| 335 |
+
|
| 336 |
+
def __cinit__(self):
|
| 337 |
+
pass
|
| 338 |
+
|
| 339 |
+
def __repr__(self):
|
| 340 |
+
return f"""{object.__repr__(self)}
|
| 341 |
+
geospatial_types: {self.geospatial_types}
|
| 342 |
+
xmin: {self.xmin}, xmax: {self.xmax}
|
| 343 |
+
ymin: {self.ymin}, ymax: {self.ymax}
|
| 344 |
+
zmin: {self.zmin}, zmax: {self.zmax}
|
| 345 |
+
mmin: {self.mmin}, mmax: {self.mmax}"""
|
| 346 |
+
|
| 347 |
+
def to_dict(self):
|
| 348 |
+
"""Dictionary summary of these statistics"""
|
| 349 |
+
out = {
|
| 350 |
+
"geospatial_types": self.geospatial_types,
|
| 351 |
+
"xmin": self.xmin,
|
| 352 |
+
"xmax": self.xmax,
|
| 353 |
+
"ymin": self.ymin,
|
| 354 |
+
"ymax": self.ymax,
|
| 355 |
+
"zmin": self.zmin,
|
| 356 |
+
"zmax": self.zmax,
|
| 357 |
+
"mmin": self.mmin,
|
| 358 |
+
"mmax": self.mmax
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
return out
|
| 362 |
+
|
| 363 |
+
@property
|
| 364 |
+
def geospatial_types(self):
|
| 365 |
+
"""Unique geometry types
|
| 366 |
+
|
| 367 |
+
Contains an integer code for each geometry type code encountered in the
|
| 368 |
+
geometries represented by these statistics. The geometry type codes are
|
| 369 |
+
ISO WKB geometry type codes returned in sorted order without duplicates.
|
| 370 |
+
|
| 371 |
+
This property may be None if geospatial types are not available.
|
| 372 |
+
"""
|
| 373 |
+
cdef optional[vector[int32_t]] maybe_geometry_types = \
|
| 374 |
+
self.statistics.get().geometry_types()
|
| 375 |
+
if not maybe_geometry_types.has_value():
|
| 376 |
+
return None
|
| 377 |
+
|
| 378 |
+
return list(maybe_geometry_types.value())
|
| 379 |
+
|
| 380 |
+
@property
|
| 381 |
+
def xmin(self):
|
| 382 |
+
"""Minimum X value or None if not available
|
| 383 |
+
|
| 384 |
+
Note that Parquet permits "wraparound" bounds in the X direction only
|
| 385 |
+
to more compactly represent bounds for geometries with components on
|
| 386 |
+
both sides of the antimeridian. This case is denoted by xmin > xmax.
|
| 387 |
+
"""
|
| 388 |
+
return self.statistics.get().lower_bound()[0] if self._x_valid() else None
|
| 389 |
+
|
| 390 |
+
@property
|
| 391 |
+
def xmax(self):
|
| 392 |
+
"""Maximum X value or None if not available
|
| 393 |
+
|
| 394 |
+
Note that Parquet permits "wraparound" bounds in the X direction only
|
| 395 |
+
(see xmin).
|
| 396 |
+
"""
|
| 397 |
+
return self.statistics.get().upper_bound()[0] if self._x_valid() else None
|
| 398 |
+
|
| 399 |
+
@property
|
| 400 |
+
def ymin(self):
|
| 401 |
+
"""Minimum Y value or None if not available"""
|
| 402 |
+
return self.statistics.get().lower_bound()[1] if self._y_valid() else None
|
| 403 |
+
|
| 404 |
+
@property
|
| 405 |
+
def ymax(self):
|
| 406 |
+
"""Maximum Y value or None if not available"""
|
| 407 |
+
return self.statistics.get().upper_bound()[1] if self._y_valid() else None
|
| 408 |
+
|
| 409 |
+
@property
|
| 410 |
+
def zmin(self):
|
| 411 |
+
"""Minimum Z value or None if not available"""
|
| 412 |
+
return self.statistics.get().lower_bound()[2] if self._z_valid() else None
|
| 413 |
+
|
| 414 |
+
@property
|
| 415 |
+
def zmax(self):
|
| 416 |
+
"""Maximum Z value or None if not available"""
|
| 417 |
+
return self.statistics.get().upper_bound()[2] if self._z_valid() else None
|
| 418 |
+
|
| 419 |
+
@property
|
| 420 |
+
def mmin(self):
|
| 421 |
+
"""Minimum M value or None if not available"""
|
| 422 |
+
return self.statistics.get().lower_bound()[3] if self._m_valid() else None
|
| 423 |
+
|
| 424 |
+
@property
|
| 425 |
+
def mmax(self):
|
| 426 |
+
"""Maximum M value or None if not available"""
|
| 427 |
+
return self.statistics.get().upper_bound()[3] if self._m_valid() else None
|
| 428 |
+
|
| 429 |
+
# Helpers to calculate the availability of a given dimension. For statistics
|
| 430 |
+
# read from a file, dimension_empty should always be false because there is
|
| 431 |
+
# no way to represent an empty range in Thrift; however, we check to be safe.
|
| 432 |
+
def _x_valid(self):
|
| 433 |
+
return self.statistics.get().dimension_valid()[0] \
|
| 434 |
+
and not self.statistics.get().dimension_empty()[0]
|
| 435 |
+
|
| 436 |
+
def _y_valid(self):
|
| 437 |
+
return self.statistics.get().dimension_valid()[1] \
|
| 438 |
+
and not self.statistics.get().dimension_empty()[1]
|
| 439 |
+
|
| 440 |
+
def _z_valid(self):
|
| 441 |
+
return self.statistics.get().dimension_valid()[2] \
|
| 442 |
+
and not self.statistics.get().dimension_empty()[2]
|
| 443 |
+
|
| 444 |
+
def _m_valid(self):
|
| 445 |
+
return self.statistics.get().dimension_valid()[3] \
|
| 446 |
+
and not self.statistics.get().dimension_empty()[3]
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
cdef class ColumnChunkMetaData(_Weakrefable):
|
| 450 |
+
"""Column metadata for a single row group."""
|
| 451 |
+
|
| 452 |
+
def __init__(self):
|
| 453 |
+
raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly")
|
| 454 |
+
|
| 455 |
+
def __cinit__(self):
|
| 456 |
+
pass
|
| 457 |
+
|
| 458 |
+
def __repr__(self):
|
| 459 |
+
statistics = indent(repr(self.statistics), 4 * ' ')
|
| 460 |
+
geo_statistics = indent(repr(self.geo_statistics), 4 * ' ')
|
| 461 |
+
return f"""{object.__repr__(self)}
|
| 462 |
+
file_offset: {self.file_offset}
|
| 463 |
+
file_path: {self.file_path}
|
| 464 |
+
physical_type: {self.physical_type}
|
| 465 |
+
num_values: {self.num_values}
|
| 466 |
+
path_in_schema: {self.path_in_schema}
|
| 467 |
+
is_stats_set: {self.is_stats_set}
|
| 468 |
+
statistics:
|
| 469 |
+
{statistics}
|
| 470 |
+
geo_statistics:
|
| 471 |
+
{geo_statistics}
|
| 472 |
+
compression: {self.compression}
|
| 473 |
+
encodings: {self.encodings}
|
| 474 |
+
has_dictionary_page: {self.has_dictionary_page}
|
| 475 |
+
dictionary_page_offset: {self.dictionary_page_offset}
|
| 476 |
+
data_page_offset: {self.data_page_offset}
|
| 477 |
+
total_compressed_size: {self.total_compressed_size}
|
| 478 |
+
total_uncompressed_size: {self.total_uncompressed_size}"""
|
| 479 |
+
|
| 480 |
+
def to_dict(self):
|
| 481 |
+
"""
|
| 482 |
+
Get dictionary representation of the column chunk metadata.
|
| 483 |
+
|
| 484 |
+
Returns
|
| 485 |
+
-------
|
| 486 |
+
dict
|
| 487 |
+
Dictionary with a key for each attribute of this class.
|
| 488 |
+
"""
|
| 489 |
+
statistics = self.statistics.to_dict() if self.is_stats_set else None
|
| 490 |
+
if self.is_geo_stats_set:
|
| 491 |
+
geo_statistics = self.geo_statistics.to_dict()
|
| 492 |
+
else:
|
| 493 |
+
geo_statistics = None
|
| 494 |
+
|
| 495 |
+
d = dict(
|
| 496 |
+
file_offset=self.file_offset,
|
| 497 |
+
file_path=self.file_path,
|
| 498 |
+
physical_type=self.physical_type,
|
| 499 |
+
num_values=self.num_values,
|
| 500 |
+
path_in_schema=self.path_in_schema,
|
| 501 |
+
is_stats_set=self.is_stats_set,
|
| 502 |
+
statistics=statistics,
|
| 503 |
+
geo_statistics=geo_statistics,
|
| 504 |
+
compression=self.compression,
|
| 505 |
+
encodings=self.encodings,
|
| 506 |
+
has_dictionary_page=self.has_dictionary_page,
|
| 507 |
+
dictionary_page_offset=self.dictionary_page_offset,
|
| 508 |
+
data_page_offset=self.data_page_offset,
|
| 509 |
+
total_compressed_size=self.total_compressed_size,
|
| 510 |
+
total_uncompressed_size=self.total_uncompressed_size
|
| 511 |
+
)
|
| 512 |
+
return d
|
| 513 |
+
|
| 514 |
+
def __eq__(self, other):
|
| 515 |
+
try:
|
| 516 |
+
return self.equals(other)
|
| 517 |
+
except TypeError:
|
| 518 |
+
return NotImplemented
|
| 519 |
+
|
| 520 |
+
def equals(self, ColumnChunkMetaData other):
|
| 521 |
+
"""
|
| 522 |
+
Return whether the two column chunk metadata objects are equal.
|
| 523 |
+
|
| 524 |
+
Parameters
|
| 525 |
+
----------
|
| 526 |
+
other : ColumnChunkMetaData
|
| 527 |
+
Metadata to compare against.
|
| 528 |
+
|
| 529 |
+
Returns
|
| 530 |
+
-------
|
| 531 |
+
are_equal : bool
|
| 532 |
+
"""
|
| 533 |
+
return self.metadata.Equals(deref(other.metadata))
|
| 534 |
+
|
| 535 |
+
@property
|
| 536 |
+
def file_offset(self):
|
| 537 |
+
"""Offset into file where column chunk is located (int)."""
|
| 538 |
+
return self.metadata.file_offset()
|
| 539 |
+
|
| 540 |
+
@property
|
| 541 |
+
def file_path(self):
|
| 542 |
+
"""Optional file path if set (str or None)."""
|
| 543 |
+
return frombytes(self.metadata.file_path())
|
| 544 |
+
|
| 545 |
+
@property
|
| 546 |
+
def physical_type(self):
|
| 547 |
+
"""Physical type of column (str)."""
|
| 548 |
+
return physical_type_name_from_enum(self.metadata.type())
|
| 549 |
+
|
| 550 |
+
@property
|
| 551 |
+
def num_values(self):
|
| 552 |
+
"""Total number of values (int)."""
|
| 553 |
+
return self.metadata.num_values()
|
| 554 |
+
|
| 555 |
+
@property
|
| 556 |
+
def path_in_schema(self):
|
| 557 |
+
"""Nested path to field, separated by periods (str)."""
|
| 558 |
+
path = self.metadata.path_in_schema().get().ToDotString()
|
| 559 |
+
return frombytes(path)
|
| 560 |
+
|
| 561 |
+
@property
|
| 562 |
+
def is_stats_set(self):
|
| 563 |
+
"""Whether or not statistics are present in metadata (bool)."""
|
| 564 |
+
return self.metadata.is_stats_set()
|
| 565 |
+
|
| 566 |
+
@property
|
| 567 |
+
def statistics(self):
|
| 568 |
+
"""Statistics for column chunk (:class:`Statistics`)."""
|
| 569 |
+
if not self.metadata.is_stats_set():
|
| 570 |
+
return None
|
| 571 |
+
cdef Statistics statistics = Statistics.__new__(Statistics)
|
| 572 |
+
statistics.init(self.metadata.statistics(), self)
|
| 573 |
+
return statistics
|
| 574 |
+
|
| 575 |
+
@property
|
| 576 |
+
def is_geo_stats_set(self):
|
| 577 |
+
"""Whether or not geometry statistics are present in metadata (bool)."""
|
| 578 |
+
return self.metadata.is_geo_stats_set()
|
| 579 |
+
|
| 580 |
+
@property
|
| 581 |
+
def geo_statistics(self):
|
| 582 |
+
"""Statistics for column chunk (:class:`GeoStatistics`)."""
|
| 583 |
+
c_geo_statistics = self.metadata.geo_statistics()
|
| 584 |
+
if not c_geo_statistics or not c_geo_statistics.get().is_valid():
|
| 585 |
+
return None
|
| 586 |
+
cdef GeoStatistics geo_statistics = GeoStatistics.__new__(GeoStatistics)
|
| 587 |
+
geo_statistics.init(c_geo_statistics, self)
|
| 588 |
+
return geo_statistics
|
| 589 |
+
|
| 590 |
+
@property
|
| 591 |
+
def compression(self):
|
| 592 |
+
"""
|
| 593 |
+
Type of compression used for column (str).
|
| 594 |
+
|
| 595 |
+
One of 'UNCOMPRESSED', 'SNAPPY', 'GZIP', 'LZO', 'BROTLI', 'LZ4', 'ZSTD',
|
| 596 |
+
or 'UNKNOWN'.
|
| 597 |
+
"""
|
| 598 |
+
return compression_name_from_enum(self.metadata.compression())
|
| 599 |
+
|
| 600 |
+
@property
|
| 601 |
+
def encodings(self):
|
| 602 |
+
"""
|
| 603 |
+
Encodings used for column (tuple of str).
|
| 604 |
+
|
| 605 |
+
One of 'PLAIN', 'BIT_PACKED', 'RLE', 'BYTE_STREAM_SPLIT', 'DELTA_BINARY_PACKED',
|
| 606 |
+
'DELTA_LENGTH_BYTE_ARRAY', 'DELTA_BYTE_ARRAY'.
|
| 607 |
+
"""
|
| 608 |
+
return tuple(map(encoding_name_from_enum, self.metadata.encodings()))
|
| 609 |
+
|
| 610 |
+
@property
|
| 611 |
+
def has_dictionary_page(self):
|
| 612 |
+
"""Whether there is dictionary data present in the column chunk (bool)."""
|
| 613 |
+
return bool(self.metadata.has_dictionary_page())
|
| 614 |
+
|
| 615 |
+
@property
|
| 616 |
+
def dictionary_page_offset(self):
|
| 617 |
+
"""Offset of dictionary page relative to beginning of the file (int)."""
|
| 618 |
+
if self.has_dictionary_page:
|
| 619 |
+
return self.metadata.dictionary_page_offset()
|
| 620 |
+
else:
|
| 621 |
+
return None
|
| 622 |
+
|
| 623 |
+
@property
|
| 624 |
+
def data_page_offset(self):
|
| 625 |
+
"""Offset of data page relative to beginning of the file (int)."""
|
| 626 |
+
return self.metadata.data_page_offset()
|
| 627 |
+
|
| 628 |
+
@property
|
| 629 |
+
def has_index_page(self):
|
| 630 |
+
"""Not yet supported."""
|
| 631 |
+
raise NotImplementedError('not supported in parquet-cpp')
|
| 632 |
+
|
| 633 |
+
@property
|
| 634 |
+
def index_page_offset(self):
|
| 635 |
+
"""Not yet supported."""
|
| 636 |
+
raise NotImplementedError("parquet-cpp doesn't return valid values")
|
| 637 |
+
|
| 638 |
+
@property
|
| 639 |
+
def total_compressed_size(self):
|
| 640 |
+
"""Compressed size in bytes (int)."""
|
| 641 |
+
return self.metadata.total_compressed_size()
|
| 642 |
+
|
| 643 |
+
@property
|
| 644 |
+
def total_uncompressed_size(self):
|
| 645 |
+
"""Uncompressed size in bytes (int)."""
|
| 646 |
+
return self.metadata.total_uncompressed_size()
|
| 647 |
+
|
| 648 |
+
@property
|
| 649 |
+
def has_offset_index(self):
|
| 650 |
+
"""Whether the column chunk has an offset index"""
|
| 651 |
+
return self.metadata.GetOffsetIndexLocation().has_value()
|
| 652 |
+
|
| 653 |
+
@property
|
| 654 |
+
def has_column_index(self):
|
| 655 |
+
"""Whether the column chunk has a column index"""
|
| 656 |
+
return self.metadata.GetColumnIndexLocation().has_value()
|
| 657 |
+
|
| 658 |
+
@property
|
| 659 |
+
def metadata(self):
|
| 660 |
+
"""Additional metadata as key value pairs (dict[bytes, bytes])."""
|
| 661 |
+
cdef:
|
| 662 |
+
unordered_map[c_string, c_string] metadata
|
| 663 |
+
const CKeyValueMetadata* underlying_metadata
|
| 664 |
+
underlying_metadata = self.metadata.key_value_metadata().get()
|
| 665 |
+
if underlying_metadata != NULL:
|
| 666 |
+
underlying_metadata.ToUnorderedMap(&metadata)
|
| 667 |
+
return metadata
|
| 668 |
+
else:
|
| 669 |
+
return None
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
cdef class SortingColumn:
|
| 673 |
+
"""
|
| 674 |
+
Sorting specification for a single column.
|
| 675 |
+
|
| 676 |
+
Returned by :meth:`RowGroupMetaData.sorting_columns` and used in
|
| 677 |
+
:class:`ParquetWriter` to specify the sort order of the data.
|
| 678 |
+
|
| 679 |
+
Parameters
|
| 680 |
+
----------
|
| 681 |
+
column_index : int
|
| 682 |
+
Index of column that data is sorted by.
|
| 683 |
+
descending : bool, default False
|
| 684 |
+
Whether column is sorted in descending order.
|
| 685 |
+
nulls_first : bool, default False
|
| 686 |
+
Whether null values appear before valid values.
|
| 687 |
+
|
| 688 |
+
Notes
|
| 689 |
+
-----
|
| 690 |
+
|
| 691 |
+
Column indices are zero-based, refer only to leaf fields, and are in
|
| 692 |
+
depth-first order. This may make the column indices for nested schemas
|
| 693 |
+
different from what you expect. In most cases, it will be easier to
|
| 694 |
+
specify the sort order using column names instead of column indices
|
| 695 |
+
and converting using the ``from_ordering`` method.
|
| 696 |
+
|
| 697 |
+
Examples
|
| 698 |
+
--------
|
| 699 |
+
|
| 700 |
+
In other APIs, sort order is specified by names, such as:
|
| 701 |
+
|
| 702 |
+
>>> sort_order = [('id', 'ascending'), ('timestamp', 'descending')]
|
| 703 |
+
|
| 704 |
+
For Parquet, the column index must be used instead:
|
| 705 |
+
|
| 706 |
+
>>> import pyarrow.parquet as pq
|
| 707 |
+
>>> [pq.SortingColumn(0), pq.SortingColumn(1, descending=True)]
|
| 708 |
+
[SortingColumn(column_index=0, descending=False, nulls_first=False), SortingColumn(column_index=1, descending=True, nulls_first=False)]
|
| 709 |
+
|
| 710 |
+
Convert the sort_order into the list of sorting columns with
|
| 711 |
+
``from_ordering`` (note that the schema must be provided as well):
|
| 712 |
+
|
| 713 |
+
>>> import pyarrow as pa
|
| 714 |
+
>>> schema = pa.schema([('id', pa.int64()), ('timestamp', pa.timestamp('ms'))])
|
| 715 |
+
>>> sorting_columns = pq.SortingColumn.from_ordering(schema, sort_order)
|
| 716 |
+
>>> sorting_columns
|
| 717 |
+
(SortingColumn(column_index=0, descending=False, nulls_first=False), SortingColumn(column_index=1, descending=True, nulls_first=False))
|
| 718 |
+
|
| 719 |
+
Convert back to the sort order with ``to_ordering``:
|
| 720 |
+
|
| 721 |
+
>>> pq.SortingColumn.to_ordering(schema, sorting_columns)
|
| 722 |
+
((('id', 'ascending'), ('timestamp', 'descending')), 'at_end')
|
| 723 |
+
|
| 724 |
+
See Also
|
| 725 |
+
--------
|
| 726 |
+
RowGroupMetaData.sorting_columns
|
| 727 |
+
"""
|
| 728 |
+
cdef int column_index
|
| 729 |
+
cdef c_bool descending
|
| 730 |
+
cdef c_bool nulls_first
|
| 731 |
+
|
| 732 |
+
def __init__(self, int column_index, c_bool descending=False, c_bool nulls_first=False):
|
| 733 |
+
self.column_index = column_index
|
| 734 |
+
self.descending = descending
|
| 735 |
+
self.nulls_first = nulls_first
|
| 736 |
+
|
| 737 |
+
@classmethod
|
| 738 |
+
def from_ordering(cls, Schema schema, sort_keys, null_placement='at_end'):
|
| 739 |
+
"""
|
| 740 |
+
Create a tuple of SortingColumn objects from the same arguments as
|
| 741 |
+
:class:`pyarrow.compute.SortOptions`.
|
| 742 |
+
|
| 743 |
+
Parameters
|
| 744 |
+
----------
|
| 745 |
+
schema : Schema
|
| 746 |
+
Schema of the input data.
|
| 747 |
+
sort_keys : Sequence of (name, order) tuples
|
| 748 |
+
Names of field/column keys (str) to sort the input on,
|
| 749 |
+
along with the order each field/column is sorted in.
|
| 750 |
+
Accepted values for `order` are "ascending", "descending".
|
| 751 |
+
null_placement : {'at_start', 'at_end'}, default 'at_end'
|
| 752 |
+
Where null values should appear in the sort order.
|
| 753 |
+
|
| 754 |
+
Returns
|
| 755 |
+
-------
|
| 756 |
+
sorting_columns : tuple of SortingColumn
|
| 757 |
+
"""
|
| 758 |
+
if null_placement == 'at_start':
|
| 759 |
+
nulls_first = True
|
| 760 |
+
elif null_placement == 'at_end':
|
| 761 |
+
nulls_first = False
|
| 762 |
+
else:
|
| 763 |
+
raise ValueError('null_placement must be "at_start" or "at_end"')
|
| 764 |
+
|
| 765 |
+
col_map = _name_to_index_map(schema)
|
| 766 |
+
|
| 767 |
+
sorting_columns = []
|
| 768 |
+
|
| 769 |
+
for sort_key in sort_keys:
|
| 770 |
+
if isinstance(sort_key, str):
|
| 771 |
+
name = sort_key
|
| 772 |
+
descending = False
|
| 773 |
+
elif (isinstance(sort_key, tuple) and len(sort_key) == 2 and
|
| 774 |
+
isinstance(sort_key[0], str) and
|
| 775 |
+
isinstance(sort_key[1], str)):
|
| 776 |
+
name, descending = sort_key
|
| 777 |
+
if descending == "descending":
|
| 778 |
+
descending = True
|
| 779 |
+
elif descending == "ascending":
|
| 780 |
+
descending = False
|
| 781 |
+
else:
|
| 782 |
+
raise ValueError(f"Invalid sort key direction: {descending}")
|
| 783 |
+
else:
|
| 784 |
+
raise ValueError(f"Invalid sort key: {sort_key}")
|
| 785 |
+
|
| 786 |
+
try:
|
| 787 |
+
column_index = col_map[name]
|
| 788 |
+
except KeyError:
|
| 789 |
+
raise ValueError(
|
| 790 |
+
f"Sort key name '{name}' not found in schema:\n{schema}")
|
| 791 |
+
|
| 792 |
+
sorting_columns.append(
|
| 793 |
+
cls(column_index, descending=descending, nulls_first=nulls_first)
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
return tuple(sorting_columns)
|
| 797 |
+
|
| 798 |
+
@staticmethod
|
| 799 |
+
def to_ordering(Schema schema, sorting_columns):
|
| 800 |
+
"""
|
| 801 |
+
Convert a tuple of SortingColumn objects to the same format as
|
| 802 |
+
:class:`pyarrow.compute.SortOptions`.
|
| 803 |
+
|
| 804 |
+
Parameters
|
| 805 |
+
----------
|
| 806 |
+
schema : Schema
|
| 807 |
+
Schema of the input data.
|
| 808 |
+
sorting_columns : tuple of SortingColumn
|
| 809 |
+
Columns to sort the input on.
|
| 810 |
+
|
| 811 |
+
Returns
|
| 812 |
+
-------
|
| 813 |
+
sort_keys : tuple of (name, order) tuples
|
| 814 |
+
null_placement : {'at_start', 'at_end'}
|
| 815 |
+
"""
|
| 816 |
+
col_map = {i: name for name, i in _name_to_index_map(schema).items()}
|
| 817 |
+
|
| 818 |
+
sort_keys = []
|
| 819 |
+
nulls_first = None
|
| 820 |
+
|
| 821 |
+
for sorting_column in sorting_columns:
|
| 822 |
+
name = col_map[sorting_column.column_index]
|
| 823 |
+
if sorting_column.descending:
|
| 824 |
+
order = "descending"
|
| 825 |
+
else:
|
| 826 |
+
order = "ascending"
|
| 827 |
+
sort_keys.append((name, order))
|
| 828 |
+
if nulls_first is None:
|
| 829 |
+
nulls_first = sorting_column.nulls_first
|
| 830 |
+
elif nulls_first != sorting_column.nulls_first:
|
| 831 |
+
raise ValueError("Sorting columns have inconsistent null placement")
|
| 832 |
+
|
| 833 |
+
if nulls_first:
|
| 834 |
+
null_placement = "at_start"
|
| 835 |
+
else:
|
| 836 |
+
null_placement = "at_end"
|
| 837 |
+
|
| 838 |
+
return tuple(sort_keys), null_placement
|
| 839 |
+
|
| 840 |
+
def __repr__(self):
|
| 841 |
+
return f"{self.__class__.__name__}(column_index={self.column_index}, " \
|
| 842 |
+
f"descending={self.descending}, nulls_first={self.nulls_first})"
|
| 843 |
+
|
| 844 |
+
def __eq__(self, SortingColumn other):
|
| 845 |
+
return (self.column_index == other.column_index and
|
| 846 |
+
self.descending == other.descending and
|
| 847 |
+
self.nulls_first == other.nulls_first)
|
| 848 |
+
|
| 849 |
+
def __hash__(self):
|
| 850 |
+
return hash((self.column_index, self.descending, self.nulls_first))
|
| 851 |
+
|
| 852 |
+
@property
|
| 853 |
+
def column_index(self):
|
| 854 |
+
""""Index of column data is sorted by (int)."""
|
| 855 |
+
return self.column_index
|
| 856 |
+
|
| 857 |
+
@property
|
| 858 |
+
def descending(self):
|
| 859 |
+
"""Whether column is sorted in descending order (bool)."""
|
| 860 |
+
return self.descending
|
| 861 |
+
|
| 862 |
+
@property
|
| 863 |
+
def nulls_first(self):
|
| 864 |
+
"""Whether null values appear before valid values (bool)."""
|
| 865 |
+
return self.nulls_first
|
| 866 |
+
|
| 867 |
+
def to_dict(self):
|
| 868 |
+
"""
|
| 869 |
+
Get dictionary representation of the SortingColumn.
|
| 870 |
+
|
| 871 |
+
Returns
|
| 872 |
+
-------
|
| 873 |
+
dict
|
| 874 |
+
Dictionary with a key for each attribute of this class.
|
| 875 |
+
"""
|
| 876 |
+
d = dict(
|
| 877 |
+
column_index=self.column_index,
|
| 878 |
+
descending=self.descending,
|
| 879 |
+
nulls_first=self.nulls_first
|
| 880 |
+
)
|
| 881 |
+
return d
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
cdef class RowGroupMetaData(_Weakrefable):
|
| 885 |
+
"""Metadata for a single row group."""
|
| 886 |
+
|
| 887 |
+
def __init__(self):
|
| 888 |
+
raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly")
|
| 889 |
+
|
| 890 |
+
def __cinit__(self):
|
| 891 |
+
pass
|
| 892 |
+
|
| 893 |
+
def __reduce__(self):
|
| 894 |
+
return RowGroupMetaData, (self.parent, self.index)
|
| 895 |
+
|
| 896 |
+
def __eq__(self, other):
|
| 897 |
+
try:
|
| 898 |
+
return self.equals(other)
|
| 899 |
+
except TypeError:
|
| 900 |
+
return NotImplemented
|
| 901 |
+
|
| 902 |
+
def equals(self, RowGroupMetaData other):
|
| 903 |
+
"""
|
| 904 |
+
Return whether the two row group metadata objects are equal.
|
| 905 |
+
|
| 906 |
+
Parameters
|
| 907 |
+
----------
|
| 908 |
+
other : RowGroupMetaData
|
| 909 |
+
Metadata to compare against.
|
| 910 |
+
|
| 911 |
+
Returns
|
| 912 |
+
-------
|
| 913 |
+
are_equal : bool
|
| 914 |
+
"""
|
| 915 |
+
return self.metadata.Equals(deref(other.metadata))
|
| 916 |
+
|
| 917 |
+
def column(self, int i):
|
| 918 |
+
"""
|
| 919 |
+
Get column metadata at given index.
|
| 920 |
+
|
| 921 |
+
Parameters
|
| 922 |
+
----------
|
| 923 |
+
i : int
|
| 924 |
+
Index of column to get metadata for.
|
| 925 |
+
|
| 926 |
+
Returns
|
| 927 |
+
-------
|
| 928 |
+
ColumnChunkMetaData
|
| 929 |
+
Metadata for column within this chunk.
|
| 930 |
+
"""
|
| 931 |
+
if i < 0 or i >= self.num_columns:
|
| 932 |
+
raise IndexError(f'{i} out of bounds')
|
| 933 |
+
cdef ColumnChunkMetaData chunk = ColumnChunkMetaData.__new__(ColumnChunkMetaData)
|
| 934 |
+
chunk.init(self, i)
|
| 935 |
+
return chunk
|
| 936 |
+
|
| 937 |
+
def __repr__(self):
|
| 938 |
+
return f"""{object.__repr__(self)}
|
| 939 |
+
num_columns: {self.num_columns}
|
| 940 |
+
num_rows: {self.num_rows}
|
| 941 |
+
total_byte_size: {self.total_byte_size}
|
| 942 |
+
sorting_columns: {self.sorting_columns}"""
|
| 943 |
+
|
| 944 |
+
def to_dict(self):
|
| 945 |
+
"""
|
| 946 |
+
Get dictionary representation of the row group metadata.
|
| 947 |
+
|
| 948 |
+
Returns
|
| 949 |
+
-------
|
| 950 |
+
dict
|
| 951 |
+
Dictionary with a key for each attribute of this class.
|
| 952 |
+
"""
|
| 953 |
+
columns = []
|
| 954 |
+
d = dict(
|
| 955 |
+
num_columns=self.num_columns,
|
| 956 |
+
num_rows=self.num_rows,
|
| 957 |
+
total_byte_size=self.total_byte_size,
|
| 958 |
+
columns=columns,
|
| 959 |
+
sorting_columns=[col.to_dict() for col in self.sorting_columns]
|
| 960 |
+
)
|
| 961 |
+
for i in range(self.num_columns):
|
| 962 |
+
columns.append(self.column(i).to_dict())
|
| 963 |
+
return d
|
| 964 |
+
|
| 965 |
+
@property
|
| 966 |
+
def num_columns(self):
|
| 967 |
+
"""Number of columns in this row group (int)."""
|
| 968 |
+
return self.metadata.num_columns()
|
| 969 |
+
|
| 970 |
+
@property
|
| 971 |
+
def num_rows(self):
|
| 972 |
+
"""Number of rows in this row group (int)."""
|
| 973 |
+
return self.metadata.num_rows()
|
| 974 |
+
|
| 975 |
+
@property
|
| 976 |
+
def total_byte_size(self):
|
| 977 |
+
"""Total byte size of all the uncompressed column data in this row group (int)."""
|
| 978 |
+
return self.metadata.total_byte_size()
|
| 979 |
+
|
| 980 |
+
@property
|
| 981 |
+
def sorting_columns(self):
|
| 982 |
+
"""Columns the row group is sorted by (tuple of :class:`SortingColumn`))."""
|
| 983 |
+
out = []
|
| 984 |
+
cdef vector[CSortingColumn] sorting_columns = self.metadata.sorting_columns()
|
| 985 |
+
for sorting_col in sorting_columns:
|
| 986 |
+
out.append(SortingColumn(
|
| 987 |
+
sorting_col.column_idx,
|
| 988 |
+
sorting_col.descending,
|
| 989 |
+
sorting_col.nulls_first
|
| 990 |
+
))
|
| 991 |
+
return tuple(out)
|
| 992 |
+
|
| 993 |
+
|
| 994 |
+
def _reconstruct_filemetadata(Buffer serialized):
|
| 995 |
+
cdef:
|
| 996 |
+
FileMetaData metadata = FileMetaData.__new__(FileMetaData)
|
| 997 |
+
CBuffer *buffer = serialized.buffer.get()
|
| 998 |
+
uint32_t metadata_len = <uint32_t>buffer.size()
|
| 999 |
+
|
| 1000 |
+
metadata.init(CFileMetaData_Make(buffer.data(), &metadata_len))
|
| 1001 |
+
|
| 1002 |
+
return metadata
|
| 1003 |
+
|
| 1004 |
+
|
| 1005 |
+
cdef class FileMetaData(_Weakrefable):
|
| 1006 |
+
"""Parquet metadata for a single file."""
|
| 1007 |
+
|
| 1008 |
+
def __init__(self):
|
| 1009 |
+
raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly")
|
| 1010 |
+
|
| 1011 |
+
def __cinit__(self):
|
| 1012 |
+
pass
|
| 1013 |
+
|
| 1014 |
+
def __reduce__(self):
|
| 1015 |
+
cdef:
|
| 1016 |
+
NativeFile sink = BufferOutputStream()
|
| 1017 |
+
COutputStream* c_sink = sink.get_output_stream().get()
|
| 1018 |
+
with nogil:
|
| 1019 |
+
self._metadata.WriteTo(c_sink)
|
| 1020 |
+
|
| 1021 |
+
cdef Buffer buffer = sink.getvalue()
|
| 1022 |
+
return _reconstruct_filemetadata, (buffer,)
|
| 1023 |
+
|
| 1024 |
+
def __hash__(self):
|
| 1025 |
+
return hash((self.schema,
|
| 1026 |
+
self.num_rows,
|
| 1027 |
+
self.num_row_groups,
|
| 1028 |
+
self.format_version,
|
| 1029 |
+
self.serialized_size))
|
| 1030 |
+
|
| 1031 |
+
def __repr__(self):
|
| 1032 |
+
return f"""{object.__repr__(self)}
|
| 1033 |
+
created_by: {self.created_by}
|
| 1034 |
+
num_columns: {self.num_columns}
|
| 1035 |
+
num_rows: {self.num_rows}
|
| 1036 |
+
num_row_groups: {self.num_row_groups}
|
| 1037 |
+
format_version: {self.format_version}
|
| 1038 |
+
serialized_size: {self.serialized_size}"""
|
| 1039 |
+
|
| 1040 |
+
def to_dict(self):
|
| 1041 |
+
"""
|
| 1042 |
+
Get dictionary representation of the file metadata.
|
| 1043 |
+
|
| 1044 |
+
Returns
|
| 1045 |
+
-------
|
| 1046 |
+
dict
|
| 1047 |
+
Dictionary with a key for each attribute of this class.
|
| 1048 |
+
"""
|
| 1049 |
+
row_groups = []
|
| 1050 |
+
d = dict(
|
| 1051 |
+
created_by=self.created_by,
|
| 1052 |
+
num_columns=self.num_columns,
|
| 1053 |
+
num_rows=self.num_rows,
|
| 1054 |
+
num_row_groups=self.num_row_groups,
|
| 1055 |
+
row_groups=row_groups,
|
| 1056 |
+
format_version=self.format_version,
|
| 1057 |
+
serialized_size=self.serialized_size
|
| 1058 |
+
)
|
| 1059 |
+
for i in range(self.num_row_groups):
|
| 1060 |
+
row_groups.append(self.row_group(i).to_dict())
|
| 1061 |
+
return d
|
| 1062 |
+
|
| 1063 |
+
def __eq__(self, other):
|
| 1064 |
+
try:
|
| 1065 |
+
return self.equals(other)
|
| 1066 |
+
except TypeError:
|
| 1067 |
+
return NotImplemented
|
| 1068 |
+
|
| 1069 |
+
def equals(self, FileMetaData other not None):
|
| 1070 |
+
"""
|
| 1071 |
+
Return whether the two file metadata objects are equal.
|
| 1072 |
+
|
| 1073 |
+
Parameters
|
| 1074 |
+
----------
|
| 1075 |
+
other : FileMetaData
|
| 1076 |
+
Metadata to compare against.
|
| 1077 |
+
|
| 1078 |
+
Returns
|
| 1079 |
+
-------
|
| 1080 |
+
are_equal : bool
|
| 1081 |
+
"""
|
| 1082 |
+
return self._metadata.Equals(deref(other._metadata))
|
| 1083 |
+
|
| 1084 |
+
@property
|
| 1085 |
+
def schema(self):
|
| 1086 |
+
"""Schema of the file (:class:`ParquetSchema`)."""
|
| 1087 |
+
if self._schema is None:
|
| 1088 |
+
self._schema = ParquetSchema(self)
|
| 1089 |
+
return self._schema
|
| 1090 |
+
|
| 1091 |
+
@property
|
| 1092 |
+
def serialized_size(self):
|
| 1093 |
+
"""Size of the original thrift encoded metadata footer (int)."""
|
| 1094 |
+
return self._metadata.size()
|
| 1095 |
+
|
| 1096 |
+
@property
|
| 1097 |
+
def num_columns(self):
|
| 1098 |
+
"""Number of columns in file (int)."""
|
| 1099 |
+
return self._metadata.num_columns()
|
| 1100 |
+
|
| 1101 |
+
@property
|
| 1102 |
+
def num_rows(self):
|
| 1103 |
+
"""Total number of rows in file (int)."""
|
| 1104 |
+
return self._metadata.num_rows()
|
| 1105 |
+
|
| 1106 |
+
@property
|
| 1107 |
+
def num_row_groups(self):
|
| 1108 |
+
"""Number of row groups in file (int)."""
|
| 1109 |
+
return self._metadata.num_row_groups()
|
| 1110 |
+
|
| 1111 |
+
@property
|
| 1112 |
+
def format_version(self):
|
| 1113 |
+
"""
|
| 1114 |
+
Parquet format version used in file (str, such as '1.0', '2.4').
|
| 1115 |
+
|
| 1116 |
+
If version is missing or unparsable, will default to assuming '2.6'.
|
| 1117 |
+
"""
|
| 1118 |
+
cdef ParquetVersion version = self._metadata.version()
|
| 1119 |
+
if version == ParquetVersion_V1:
|
| 1120 |
+
return '1.0'
|
| 1121 |
+
elif version == ParquetVersion_V2_4:
|
| 1122 |
+
return '2.4'
|
| 1123 |
+
elif version == ParquetVersion_V2_6:
|
| 1124 |
+
return '2.6'
|
| 1125 |
+
else:
|
| 1126 |
+
warnings.warn(f'Unrecognized file version, assuming 2.6: {version}')
|
| 1127 |
+
return '2.6'
|
| 1128 |
+
|
| 1129 |
+
@property
|
| 1130 |
+
def created_by(self):
|
| 1131 |
+
"""
|
| 1132 |
+
String describing source of the parquet file (str).
|
| 1133 |
+
|
| 1134 |
+
This typically includes library name and version number. For example, Arrow 7.0's
|
| 1135 |
+
writer returns 'parquet-cpp-arrow version 7.0.0'.
|
| 1136 |
+
"""
|
| 1137 |
+
return frombytes(self._metadata.created_by())
|
| 1138 |
+
|
| 1139 |
+
@property
|
| 1140 |
+
def metadata(self):
|
| 1141 |
+
"""Additional metadata as key value pairs (dict[bytes, bytes])."""
|
| 1142 |
+
cdef:
|
| 1143 |
+
unordered_map[c_string, c_string] metadata
|
| 1144 |
+
const CKeyValueMetadata* underlying_metadata
|
| 1145 |
+
underlying_metadata = self._metadata.key_value_metadata().get()
|
| 1146 |
+
if underlying_metadata != NULL:
|
| 1147 |
+
underlying_metadata.ToUnorderedMap(&metadata)
|
| 1148 |
+
return metadata
|
| 1149 |
+
else:
|
| 1150 |
+
return None
|
| 1151 |
+
|
| 1152 |
+
def row_group(self, int i):
|
| 1153 |
+
"""
|
| 1154 |
+
Get metadata for row group at index i.
|
| 1155 |
+
|
| 1156 |
+
Parameters
|
| 1157 |
+
----------
|
| 1158 |
+
i : int
|
| 1159 |
+
Row group index to get.
|
| 1160 |
+
|
| 1161 |
+
Returns
|
| 1162 |
+
-------
|
| 1163 |
+
row_group_metadata : RowGroupMetaData
|
| 1164 |
+
"""
|
| 1165 |
+
cdef RowGroupMetaData row_group = RowGroupMetaData.__new__(RowGroupMetaData)
|
| 1166 |
+
row_group.init(self, i)
|
| 1167 |
+
return row_group
|
| 1168 |
+
|
| 1169 |
+
def set_file_path(self, path):
|
| 1170 |
+
"""
|
| 1171 |
+
Set ColumnChunk file paths to the given value.
|
| 1172 |
+
|
| 1173 |
+
This method modifies the ``file_path`` field of each ColumnChunk
|
| 1174 |
+
in the FileMetaData to be a particular value.
|
| 1175 |
+
|
| 1176 |
+
Parameters
|
| 1177 |
+
----------
|
| 1178 |
+
path : str
|
| 1179 |
+
The file path to set on all ColumnChunks.
|
| 1180 |
+
"""
|
| 1181 |
+
cdef:
|
| 1182 |
+
c_string c_path = tobytes(path)
|
| 1183 |
+
self._metadata.set_file_path(c_path)
|
| 1184 |
+
|
| 1185 |
+
def append_row_groups(self, FileMetaData other):
|
| 1186 |
+
"""
|
| 1187 |
+
Append row groups from other FileMetaData object.
|
| 1188 |
+
|
| 1189 |
+
Parameters
|
| 1190 |
+
----------
|
| 1191 |
+
other : FileMetaData
|
| 1192 |
+
Other metadata to append row groups from.
|
| 1193 |
+
"""
|
| 1194 |
+
cdef shared_ptr[CFileMetaData] c_metadata
|
| 1195 |
+
|
| 1196 |
+
c_metadata = other.sp_metadata
|
| 1197 |
+
self._metadata.AppendRowGroups(deref(c_metadata))
|
| 1198 |
+
|
| 1199 |
+
def write_metadata_file(self, where):
|
| 1200 |
+
"""
|
| 1201 |
+
Write the metadata to a metadata-only Parquet file.
|
| 1202 |
+
|
| 1203 |
+
Parameters
|
| 1204 |
+
----------
|
| 1205 |
+
where : path or file-like object
|
| 1206 |
+
Where to write the metadata. Should be a writable path on
|
| 1207 |
+
the local filesystem, or a writable file-like object.
|
| 1208 |
+
"""
|
| 1209 |
+
cdef:
|
| 1210 |
+
shared_ptr[COutputStream] sink
|
| 1211 |
+
c_string c_where
|
| 1212 |
+
|
| 1213 |
+
try:
|
| 1214 |
+
where = _stringify_path(where)
|
| 1215 |
+
except TypeError:
|
| 1216 |
+
get_writer(where, &sink)
|
| 1217 |
+
else:
|
| 1218 |
+
c_where = tobytes(where)
|
| 1219 |
+
with nogil:
|
| 1220 |
+
sink = GetResultValue(FileOutputStream.Open(c_where))
|
| 1221 |
+
|
| 1222 |
+
with nogil:
|
| 1223 |
+
check_status(
|
| 1224 |
+
WriteMetaDataFile(deref(self._metadata), sink.get()))
|
| 1225 |
+
|
| 1226 |
+
|
| 1227 |
+
cdef class ParquetSchema(_Weakrefable):
|
| 1228 |
+
"""A Parquet schema."""
|
| 1229 |
+
|
| 1230 |
+
def __cinit__(self, FileMetaData container):
|
| 1231 |
+
self.parent = container
|
| 1232 |
+
self.schema = container._metadata.schema()
|
| 1233 |
+
|
| 1234 |
+
def __repr__(self):
|
| 1235 |
+
return f"{object.__repr__(self)}\n{frombytes(self.schema.ToString(), safe=True)}"
|
| 1236 |
+
|
| 1237 |
+
def __reduce__(self):
|
| 1238 |
+
return ParquetSchema, (self.parent,)
|
| 1239 |
+
|
| 1240 |
+
def __len__(self):
|
| 1241 |
+
return self.schema.num_columns()
|
| 1242 |
+
|
| 1243 |
+
def __getitem__(self, i):
|
| 1244 |
+
return self.column(i)
|
| 1245 |
+
|
| 1246 |
+
def __hash__(self):
|
| 1247 |
+
return hash(self.schema.ToString())
|
| 1248 |
+
|
| 1249 |
+
@property
|
| 1250 |
+
def names(self):
|
| 1251 |
+
"""Name of each field (list of str)."""
|
| 1252 |
+
return [self[i].name for i in range(len(self))]
|
| 1253 |
+
|
| 1254 |
+
def to_arrow_schema(self):
|
| 1255 |
+
"""
|
| 1256 |
+
Convert Parquet schema to effective Arrow schema.
|
| 1257 |
+
|
| 1258 |
+
Returns
|
| 1259 |
+
-------
|
| 1260 |
+
schema : Schema
|
| 1261 |
+
"""
|
| 1262 |
+
cdef shared_ptr[CSchema] sp_arrow_schema
|
| 1263 |
+
|
| 1264 |
+
with nogil:
|
| 1265 |
+
check_status(FromParquetSchema(
|
| 1266 |
+
self.schema, default_arrow_reader_properties(),
|
| 1267 |
+
self.parent._metadata.key_value_metadata(),
|
| 1268 |
+
&sp_arrow_schema))
|
| 1269 |
+
|
| 1270 |
+
return pyarrow_wrap_schema(sp_arrow_schema)
|
| 1271 |
+
|
| 1272 |
+
def __eq__(self, other):
|
| 1273 |
+
try:
|
| 1274 |
+
return self.equals(other)
|
| 1275 |
+
except TypeError:
|
| 1276 |
+
return NotImplemented
|
| 1277 |
+
|
| 1278 |
+
def equals(self, ParquetSchema other):
|
| 1279 |
+
"""
|
| 1280 |
+
Return whether the two schemas are equal.
|
| 1281 |
+
|
| 1282 |
+
Parameters
|
| 1283 |
+
----------
|
| 1284 |
+
other : ParquetSchema
|
| 1285 |
+
Schema to compare against.
|
| 1286 |
+
|
| 1287 |
+
Returns
|
| 1288 |
+
-------
|
| 1289 |
+
are_equal : bool
|
| 1290 |
+
"""
|
| 1291 |
+
return self.schema.Equals(deref(other.schema))
|
| 1292 |
+
|
| 1293 |
+
def column(self, i):
|
| 1294 |
+
"""
|
| 1295 |
+
Return the schema for a single column.
|
| 1296 |
+
|
| 1297 |
+
Parameters
|
| 1298 |
+
----------
|
| 1299 |
+
i : int
|
| 1300 |
+
Index of column in schema.
|
| 1301 |
+
|
| 1302 |
+
Returns
|
| 1303 |
+
-------
|
| 1304 |
+
column_schema : ColumnSchema
|
| 1305 |
+
"""
|
| 1306 |
+
if i < 0 or i >= len(self):
|
| 1307 |
+
raise IndexError(f'{i} out of bounds')
|
| 1308 |
+
|
| 1309 |
+
return ColumnSchema(self, i)
|
| 1310 |
+
|
| 1311 |
+
|
| 1312 |
+
cdef class ColumnSchema(_Weakrefable):
|
| 1313 |
+
"""Schema for a single column."""
|
| 1314 |
+
cdef:
|
| 1315 |
+
int index
|
| 1316 |
+
ParquetSchema parent
|
| 1317 |
+
const ColumnDescriptor* descr
|
| 1318 |
+
|
| 1319 |
+
def __cinit__(self, ParquetSchema schema, int index):
|
| 1320 |
+
self.parent = schema
|
| 1321 |
+
self.index = index # for pickling support
|
| 1322 |
+
self.descr = schema.schema.Column(index)
|
| 1323 |
+
|
| 1324 |
+
def __eq__(self, other):
|
| 1325 |
+
try:
|
| 1326 |
+
return self.equals(other)
|
| 1327 |
+
except TypeError:
|
| 1328 |
+
return NotImplemented
|
| 1329 |
+
|
| 1330 |
+
def __reduce__(self):
|
| 1331 |
+
return ColumnSchema, (self.parent, self.index)
|
| 1332 |
+
|
| 1333 |
+
def equals(self, ColumnSchema other):
|
| 1334 |
+
"""
|
| 1335 |
+
Return whether the two column schemas are equal.
|
| 1336 |
+
|
| 1337 |
+
Parameters
|
| 1338 |
+
----------
|
| 1339 |
+
other : ColumnSchema
|
| 1340 |
+
Schema to compare against.
|
| 1341 |
+
|
| 1342 |
+
Returns
|
| 1343 |
+
-------
|
| 1344 |
+
are_equal : bool
|
| 1345 |
+
"""
|
| 1346 |
+
return self.descr.Equals(deref(other.descr))
|
| 1347 |
+
|
| 1348 |
+
def __repr__(self):
|
| 1349 |
+
physical_type = self.physical_type
|
| 1350 |
+
converted_type = self.converted_type
|
| 1351 |
+
if converted_type == 'DECIMAL':
|
| 1352 |
+
converted_type = f'DECIMAL({self.precision}, {self.scale})'
|
| 1353 |
+
elif physical_type == 'FIXED_LEN_BYTE_ARRAY':
|
| 1354 |
+
converted_type = f'FIXED_LEN_BYTE_ARRAY(length={self.length})'
|
| 1355 |
+
|
| 1356 |
+
return f"""<ParquetColumnSchema>
|
| 1357 |
+
name: {self.name}
|
| 1358 |
+
path: {self.path}
|
| 1359 |
+
max_definition_level: {self.max_definition_level}
|
| 1360 |
+
max_repetition_level: {self.max_repetition_level}
|
| 1361 |
+
physical_type: {physical_type}
|
| 1362 |
+
logical_type: {self.logical_type}
|
| 1363 |
+
converted_type (legacy): {converted_type}"""
|
| 1364 |
+
|
| 1365 |
+
@property
|
| 1366 |
+
def name(self):
|
| 1367 |
+
"""Name of field (str)."""
|
| 1368 |
+
return frombytes(self.descr.name())
|
| 1369 |
+
|
| 1370 |
+
@property
|
| 1371 |
+
def path(self):
|
| 1372 |
+
"""Nested path to field, separated by periods (str)."""
|
| 1373 |
+
return frombytes(self.descr.path().get().ToDotString())
|
| 1374 |
+
|
| 1375 |
+
@property
|
| 1376 |
+
def max_definition_level(self):
|
| 1377 |
+
"""Maximum definition level (int)."""
|
| 1378 |
+
return self.descr.max_definition_level()
|
| 1379 |
+
|
| 1380 |
+
@property
|
| 1381 |
+
def max_repetition_level(self):
|
| 1382 |
+
"""Maximum repetition level (int)."""
|
| 1383 |
+
return self.descr.max_repetition_level()
|
| 1384 |
+
|
| 1385 |
+
@property
|
| 1386 |
+
def physical_type(self):
|
| 1387 |
+
"""Name of physical type (str)."""
|
| 1388 |
+
return physical_type_name_from_enum(self.descr.physical_type())
|
| 1389 |
+
|
| 1390 |
+
@property
|
| 1391 |
+
def logical_type(self):
|
| 1392 |
+
"""Logical type of column (:class:`ParquetLogicalType`)."""
|
| 1393 |
+
return wrap_logical_type(self.descr.logical_type())
|
| 1394 |
+
|
| 1395 |
+
@property
|
| 1396 |
+
def converted_type(self):
|
| 1397 |
+
"""Legacy converted type (str or None)."""
|
| 1398 |
+
return converted_type_name_from_enum(self.descr.converted_type())
|
| 1399 |
+
|
| 1400 |
+
# FIXED_LEN_BYTE_ARRAY attribute
|
| 1401 |
+
@property
|
| 1402 |
+
def length(self):
|
| 1403 |
+
"""Array length if fixed length byte array type, None otherwise (int or None)."""
|
| 1404 |
+
return self.descr.type_length()
|
| 1405 |
+
|
| 1406 |
+
# Decimal attributes
|
| 1407 |
+
@property
|
| 1408 |
+
def precision(self):
|
| 1409 |
+
"""Precision if decimal type, None otherwise (int or None)."""
|
| 1410 |
+
return self.descr.type_precision()
|
| 1411 |
+
|
| 1412 |
+
@property
|
| 1413 |
+
def scale(self):
|
| 1414 |
+
"""Scale if decimal type, None otherwise (int or None)."""
|
| 1415 |
+
return self.descr.type_scale()
|
| 1416 |
+
|
| 1417 |
+
|
| 1418 |
+
cdef physical_type_name_from_enum(ParquetType type_):
|
| 1419 |
+
return {
|
| 1420 |
+
ParquetType_BOOLEAN: 'BOOLEAN',
|
| 1421 |
+
ParquetType_INT32: 'INT32',
|
| 1422 |
+
ParquetType_INT64: 'INT64',
|
| 1423 |
+
ParquetType_INT96: 'INT96',
|
| 1424 |
+
ParquetType_FLOAT: 'FLOAT',
|
| 1425 |
+
ParquetType_DOUBLE: 'DOUBLE',
|
| 1426 |
+
ParquetType_BYTE_ARRAY: 'BYTE_ARRAY',
|
| 1427 |
+
ParquetType_FIXED_LEN_BYTE_ARRAY: 'FIXED_LEN_BYTE_ARRAY',
|
| 1428 |
+
}.get(type_, 'UNKNOWN')
|
| 1429 |
+
|
| 1430 |
+
|
| 1431 |
+
cdef logical_type_name_from_enum(ParquetLogicalTypeId type_):
|
| 1432 |
+
return {
|
| 1433 |
+
ParquetLogicalType_UNDEFINED: 'UNDEFINED',
|
| 1434 |
+
ParquetLogicalType_STRING: 'STRING',
|
| 1435 |
+
ParquetLogicalType_MAP: 'MAP',
|
| 1436 |
+
ParquetLogicalType_LIST: 'LIST',
|
| 1437 |
+
ParquetLogicalType_ENUM: 'ENUM',
|
| 1438 |
+
ParquetLogicalType_DECIMAL: 'DECIMAL',
|
| 1439 |
+
ParquetLogicalType_DATE: 'DATE',
|
| 1440 |
+
ParquetLogicalType_TIME: 'TIME',
|
| 1441 |
+
ParquetLogicalType_TIMESTAMP: 'TIMESTAMP',
|
| 1442 |
+
ParquetLogicalType_INT: 'INT',
|
| 1443 |
+
ParquetLogicalType_FLOAT16: 'FLOAT16',
|
| 1444 |
+
ParquetLogicalType_JSON: 'JSON',
|
| 1445 |
+
ParquetLogicalType_BSON: 'BSON',
|
| 1446 |
+
ParquetLogicalType_UUID: 'UUID',
|
| 1447 |
+
ParquetLogicalType_NONE: 'NONE',
|
| 1448 |
+
}.get(type_, 'UNKNOWN')
|
| 1449 |
+
|
| 1450 |
+
|
| 1451 |
+
cdef converted_type_name_from_enum(ParquetConvertedType type_):
|
| 1452 |
+
return {
|
| 1453 |
+
ParquetConvertedType_NONE: 'NONE',
|
| 1454 |
+
ParquetConvertedType_UTF8: 'UTF8',
|
| 1455 |
+
ParquetConvertedType_MAP: 'MAP',
|
| 1456 |
+
ParquetConvertedType_MAP_KEY_VALUE: 'MAP_KEY_VALUE',
|
| 1457 |
+
ParquetConvertedType_LIST: 'LIST',
|
| 1458 |
+
ParquetConvertedType_ENUM: 'ENUM',
|
| 1459 |
+
ParquetConvertedType_DECIMAL: 'DECIMAL',
|
| 1460 |
+
ParquetConvertedType_DATE: 'DATE',
|
| 1461 |
+
ParquetConvertedType_TIME_MILLIS: 'TIME_MILLIS',
|
| 1462 |
+
ParquetConvertedType_TIME_MICROS: 'TIME_MICROS',
|
| 1463 |
+
ParquetConvertedType_TIMESTAMP_MILLIS: 'TIMESTAMP_MILLIS',
|
| 1464 |
+
ParquetConvertedType_TIMESTAMP_MICROS: 'TIMESTAMP_MICROS',
|
| 1465 |
+
ParquetConvertedType_UINT_8: 'UINT_8',
|
| 1466 |
+
ParquetConvertedType_UINT_16: 'UINT_16',
|
| 1467 |
+
ParquetConvertedType_UINT_32: 'UINT_32',
|
| 1468 |
+
ParquetConvertedType_UINT_64: 'UINT_64',
|
| 1469 |
+
ParquetConvertedType_INT_8: 'INT_8',
|
| 1470 |
+
ParquetConvertedType_INT_16: 'INT_16',
|
| 1471 |
+
ParquetConvertedType_INT_32: 'INT_32',
|
| 1472 |
+
ParquetConvertedType_INT_64: 'INT_64',
|
| 1473 |
+
ParquetConvertedType_JSON: 'JSON',
|
| 1474 |
+
ParquetConvertedType_BSON: 'BSON',
|
| 1475 |
+
ParquetConvertedType_INTERVAL: 'INTERVAL',
|
| 1476 |
+
}.get(type_, 'UNKNOWN')
|
| 1477 |
+
|
| 1478 |
+
|
| 1479 |
+
cdef encoding_name_from_enum(ParquetEncoding encoding_):
|
| 1480 |
+
return {
|
| 1481 |
+
ParquetEncoding_PLAIN: 'PLAIN',
|
| 1482 |
+
ParquetEncoding_PLAIN_DICTIONARY: 'PLAIN_DICTIONARY',
|
| 1483 |
+
ParquetEncoding_RLE: 'RLE',
|
| 1484 |
+
ParquetEncoding_BIT_PACKED: 'BIT_PACKED',
|
| 1485 |
+
ParquetEncoding_DELTA_BINARY_PACKED: 'DELTA_BINARY_PACKED',
|
| 1486 |
+
ParquetEncoding_DELTA_LENGTH_BYTE_ARRAY: 'DELTA_LENGTH_BYTE_ARRAY',
|
| 1487 |
+
ParquetEncoding_DELTA_BYTE_ARRAY: 'DELTA_BYTE_ARRAY',
|
| 1488 |
+
ParquetEncoding_RLE_DICTIONARY: 'RLE_DICTIONARY',
|
| 1489 |
+
ParquetEncoding_BYTE_STREAM_SPLIT: 'BYTE_STREAM_SPLIT',
|
| 1490 |
+
}.get(encoding_, 'UNKNOWN')
|
| 1491 |
+
|
| 1492 |
+
|
| 1493 |
+
cdef encoding_enum_from_name(str encoding_name):
|
| 1494 |
+
enc = {
|
| 1495 |
+
'PLAIN': ParquetEncoding_PLAIN,
|
| 1496 |
+
'BIT_PACKED': ParquetEncoding_BIT_PACKED,
|
| 1497 |
+
'RLE': ParquetEncoding_RLE,
|
| 1498 |
+
'BYTE_STREAM_SPLIT': ParquetEncoding_BYTE_STREAM_SPLIT,
|
| 1499 |
+
'DELTA_BINARY_PACKED': ParquetEncoding_DELTA_BINARY_PACKED,
|
| 1500 |
+
'DELTA_LENGTH_BYTE_ARRAY': ParquetEncoding_DELTA_LENGTH_BYTE_ARRAY,
|
| 1501 |
+
'DELTA_BYTE_ARRAY': ParquetEncoding_DELTA_BYTE_ARRAY,
|
| 1502 |
+
'RLE_DICTIONARY': 'dict',
|
| 1503 |
+
'PLAIN_DICTIONARY': 'dict',
|
| 1504 |
+
}.get(encoding_name, None)
|
| 1505 |
+
if enc is None:
|
| 1506 |
+
raise ValueError(f"Unsupported column encoding: {encoding_name!r}")
|
| 1507 |
+
elif enc == 'dict':
|
| 1508 |
+
raise ValueError(f"{encoding_name!r} is already used by default.")
|
| 1509 |
+
else:
|
| 1510 |
+
return enc
|
| 1511 |
+
|
| 1512 |
+
|
| 1513 |
+
cdef compression_name_from_enum(ParquetCompression compression_):
|
| 1514 |
+
return {
|
| 1515 |
+
ParquetCompression_UNCOMPRESSED: 'UNCOMPRESSED',
|
| 1516 |
+
ParquetCompression_SNAPPY: 'SNAPPY',
|
| 1517 |
+
ParquetCompression_GZIP: 'GZIP',
|
| 1518 |
+
ParquetCompression_LZO: 'LZO',
|
| 1519 |
+
ParquetCompression_BROTLI: 'BROTLI',
|
| 1520 |
+
ParquetCompression_LZ4: 'LZ4',
|
| 1521 |
+
ParquetCompression_ZSTD: 'ZSTD',
|
| 1522 |
+
}.get(compression_, 'UNKNOWN')
|
| 1523 |
+
|
| 1524 |
+
|
| 1525 |
+
cdef int check_compression_name(name) except -1:
|
| 1526 |
+
if name.upper() not in {'NONE', 'SNAPPY', 'GZIP', 'LZO', 'BROTLI', 'LZ4',
|
| 1527 |
+
'ZSTD'}:
|
| 1528 |
+
raise ArrowException("Unsupported compression: " + name)
|
| 1529 |
+
return 0
|
| 1530 |
+
|
| 1531 |
+
|
| 1532 |
+
cdef ParquetCompression compression_from_name(name):
|
| 1533 |
+
name = name.upper()
|
| 1534 |
+
if name == 'SNAPPY':
|
| 1535 |
+
return ParquetCompression_SNAPPY
|
| 1536 |
+
elif name == 'GZIP':
|
| 1537 |
+
return ParquetCompression_GZIP
|
| 1538 |
+
elif name == 'LZO':
|
| 1539 |
+
return ParquetCompression_LZO
|
| 1540 |
+
elif name == 'BROTLI':
|
| 1541 |
+
return ParquetCompression_BROTLI
|
| 1542 |
+
elif name == 'LZ4':
|
| 1543 |
+
return ParquetCompression_LZ4
|
| 1544 |
+
elif name == 'ZSTD':
|
| 1545 |
+
return ParquetCompression_ZSTD
|
| 1546 |
+
else:
|
| 1547 |
+
return ParquetCompression_UNCOMPRESSED
|
| 1548 |
+
|
| 1549 |
+
|
| 1550 |
+
cdef class ParquetReader(_Weakrefable):
|
| 1551 |
+
cdef:
|
| 1552 |
+
object source
|
| 1553 |
+
CMemoryPool* pool
|
| 1554 |
+
UniquePtrNoGIL[FileReader] reader
|
| 1555 |
+
FileMetaData _metadata
|
| 1556 |
+
shared_ptr[CRandomAccessFile] rd_handle
|
| 1557 |
+
|
| 1558 |
+
cdef public:
|
| 1559 |
+
_column_idx_map
|
| 1560 |
+
|
| 1561 |
+
def __cinit__(self, MemoryPool memory_pool=None):
|
| 1562 |
+
self.pool = maybe_unbox_memory_pool(memory_pool)
|
| 1563 |
+
self._metadata = None
|
| 1564 |
+
|
| 1565 |
+
def open(self, object source not None, *, bint use_memory_map=False,
|
| 1566 |
+
read_dictionary=None, binary_type=None, list_type=None,
|
| 1567 |
+
FileMetaData metadata=None,
|
| 1568 |
+
int buffer_size=0, bint pre_buffer=False,
|
| 1569 |
+
coerce_int96_timestamp_unit=None,
|
| 1570 |
+
FileDecryptionProperties decryption_properties=None,
|
| 1571 |
+
thrift_string_size_limit=None,
|
| 1572 |
+
thrift_container_size_limit=None,
|
| 1573 |
+
page_checksum_verification=False,
|
| 1574 |
+
arrow_extensions_enabled=False):
|
| 1575 |
+
"""
|
| 1576 |
+
Open a parquet file for reading.
|
| 1577 |
+
|
| 1578 |
+
Parameters
|
| 1579 |
+
----------
|
| 1580 |
+
source : str, pathlib.Path, pyarrow.NativeFile, or file-like object
|
| 1581 |
+
use_memory_map : bool, default False
|
| 1582 |
+
read_dictionary : iterable[int or str], optional
|
| 1583 |
+
binary_type : pyarrow.DataType, optional
|
| 1584 |
+
list_type : subclass of pyarrow.DataType, optional
|
| 1585 |
+
metadata : FileMetaData, optional
|
| 1586 |
+
buffer_size : int, default 0
|
| 1587 |
+
pre_buffer : bool, default False
|
| 1588 |
+
coerce_int96_timestamp_unit : str, optional
|
| 1589 |
+
decryption_properties : FileDecryptionProperties, optional
|
| 1590 |
+
thrift_string_size_limit : int, optional
|
| 1591 |
+
thrift_container_size_limit : int, optional
|
| 1592 |
+
page_checksum_verification : bool, default False
|
| 1593 |
+
arrow_extensions_enabled : bool, default False
|
| 1594 |
+
"""
|
| 1595 |
+
cdef:
|
| 1596 |
+
shared_ptr[CFileMetaData] c_metadata
|
| 1597 |
+
CReaderProperties properties = default_reader_properties()
|
| 1598 |
+
ArrowReaderProperties arrow_props = (
|
| 1599 |
+
default_arrow_reader_properties())
|
| 1600 |
+
FileReaderBuilder builder
|
| 1601 |
+
|
| 1602 |
+
if pre_buffer and not is_threading_enabled():
|
| 1603 |
+
pre_buffer = False
|
| 1604 |
+
|
| 1605 |
+
if metadata is not None:
|
| 1606 |
+
c_metadata = metadata.sp_metadata
|
| 1607 |
+
|
| 1608 |
+
if buffer_size > 0:
|
| 1609 |
+
properties.enable_buffered_stream()
|
| 1610 |
+
properties.set_buffer_size(buffer_size)
|
| 1611 |
+
elif buffer_size == 0:
|
| 1612 |
+
properties.disable_buffered_stream()
|
| 1613 |
+
else:
|
| 1614 |
+
raise ValueError('Buffer size must be larger than zero')
|
| 1615 |
+
|
| 1616 |
+
if thrift_string_size_limit is not None:
|
| 1617 |
+
if thrift_string_size_limit <= 0:
|
| 1618 |
+
raise ValueError("thrift_string_size_limit "
|
| 1619 |
+
"must be larger than zero")
|
| 1620 |
+
properties.set_thrift_string_size_limit(thrift_string_size_limit)
|
| 1621 |
+
if thrift_container_size_limit is not None:
|
| 1622 |
+
if thrift_container_size_limit <= 0:
|
| 1623 |
+
raise ValueError("thrift_container_size_limit "
|
| 1624 |
+
"must be larger than zero")
|
| 1625 |
+
properties.set_thrift_container_size_limit(
|
| 1626 |
+
thrift_container_size_limit)
|
| 1627 |
+
|
| 1628 |
+
if decryption_properties is not None:
|
| 1629 |
+
properties.file_decryption_properties(
|
| 1630 |
+
decryption_properties.unwrap())
|
| 1631 |
+
|
| 1632 |
+
arrow_props.set_pre_buffer(pre_buffer)
|
| 1633 |
+
|
| 1634 |
+
properties.set_page_checksum_verification(page_checksum_verification)
|
| 1635 |
+
|
| 1636 |
+
if binary_type is not None:
|
| 1637 |
+
c_binary_type = pyarrow_unwrap_data_type(binary_type)
|
| 1638 |
+
arrow_props.set_binary_type(c_binary_type.get().id())
|
| 1639 |
+
|
| 1640 |
+
if list_type is not None:
|
| 1641 |
+
arrow_props.set_list_type(_unwrap_list_type(list_type))
|
| 1642 |
+
|
| 1643 |
+
if coerce_int96_timestamp_unit is None:
|
| 1644 |
+
# use the default defined in default_arrow_reader_properties()
|
| 1645 |
+
pass
|
| 1646 |
+
else:
|
| 1647 |
+
arrow_props.set_coerce_int96_timestamp_unit(
|
| 1648 |
+
string_to_timeunit(coerce_int96_timestamp_unit))
|
| 1649 |
+
|
| 1650 |
+
arrow_props.set_arrow_extensions_enabled(arrow_extensions_enabled)
|
| 1651 |
+
|
| 1652 |
+
self.source = source
|
| 1653 |
+
get_reader(source, use_memory_map, &self.rd_handle)
|
| 1654 |
+
|
| 1655 |
+
with nogil:
|
| 1656 |
+
check_status(builder.Open(self.rd_handle, properties, c_metadata))
|
| 1657 |
+
|
| 1658 |
+
# Set up metadata
|
| 1659 |
+
with nogil:
|
| 1660 |
+
c_metadata = builder.raw_reader().metadata()
|
| 1661 |
+
cdef FileMetaData result = FileMetaData.__new__(FileMetaData)
|
| 1662 |
+
self._metadata = result
|
| 1663 |
+
result.init(c_metadata)
|
| 1664 |
+
|
| 1665 |
+
if read_dictionary is not None:
|
| 1666 |
+
self._set_read_dictionary(read_dictionary, &arrow_props)
|
| 1667 |
+
|
| 1668 |
+
with nogil:
|
| 1669 |
+
check_status(builder.memory_pool(self.pool)
|
| 1670 |
+
.properties(arrow_props)
|
| 1671 |
+
.Build(&self.reader))
|
| 1672 |
+
|
| 1673 |
+
cdef _set_read_dictionary(self, read_dictionary,
|
| 1674 |
+
ArrowReaderProperties* props):
|
| 1675 |
+
for column in read_dictionary:
|
| 1676 |
+
if not isinstance(column, int):
|
| 1677 |
+
column = self.column_name_idx(column)
|
| 1678 |
+
props.set_read_dictionary(column, True)
|
| 1679 |
+
|
| 1680 |
+
@property
|
| 1681 |
+
def column_paths(self):
|
| 1682 |
+
cdef:
|
| 1683 |
+
FileMetaData container = self.metadata
|
| 1684 |
+
const CFileMetaData* metadata = container._metadata
|
| 1685 |
+
vector[c_string] path
|
| 1686 |
+
int i = 0
|
| 1687 |
+
|
| 1688 |
+
paths = []
|
| 1689 |
+
for i in range(0, metadata.num_columns()):
|
| 1690 |
+
path = (metadata.schema().Column(i)
|
| 1691 |
+
.path().get().ToDotVector())
|
| 1692 |
+
paths.append([frombytes(x) for x in path])
|
| 1693 |
+
|
| 1694 |
+
return paths
|
| 1695 |
+
|
| 1696 |
+
@property
|
| 1697 |
+
def metadata(self):
|
| 1698 |
+
return self._metadata
|
| 1699 |
+
|
| 1700 |
+
@property
|
| 1701 |
+
def schema_arrow(self):
|
| 1702 |
+
cdef shared_ptr[CSchema] out
|
| 1703 |
+
with nogil:
|
| 1704 |
+
check_status(self.reader.get().GetSchema(&out))
|
| 1705 |
+
return pyarrow_wrap_schema(out)
|
| 1706 |
+
|
| 1707 |
+
@property
|
| 1708 |
+
def num_row_groups(self):
|
| 1709 |
+
return self.reader.get().num_row_groups()
|
| 1710 |
+
|
| 1711 |
+
def set_use_threads(self, bint use_threads):
|
| 1712 |
+
"""
|
| 1713 |
+
Parameters
|
| 1714 |
+
----------
|
| 1715 |
+
use_threads : bool
|
| 1716 |
+
"""
|
| 1717 |
+
if is_threading_enabled():
|
| 1718 |
+
self.reader.get().set_use_threads(use_threads)
|
| 1719 |
+
else:
|
| 1720 |
+
self.reader.get().set_use_threads(False)
|
| 1721 |
+
|
| 1722 |
+
def set_batch_size(self, int64_t batch_size):
|
| 1723 |
+
"""
|
| 1724 |
+
Parameters
|
| 1725 |
+
----------
|
| 1726 |
+
batch_size : int64
|
| 1727 |
+
"""
|
| 1728 |
+
self.reader.get().set_batch_size(batch_size)
|
| 1729 |
+
|
| 1730 |
+
def iter_batches(self, int64_t batch_size, row_groups, column_indices=None,
|
| 1731 |
+
bint use_threads=True):
|
| 1732 |
+
"""
|
| 1733 |
+
Parameters
|
| 1734 |
+
----------
|
| 1735 |
+
batch_size : int64
|
| 1736 |
+
row_groups : list[int]
|
| 1737 |
+
column_indices : list[int], optional
|
| 1738 |
+
use_threads : bool, default True
|
| 1739 |
+
|
| 1740 |
+
Yields
|
| 1741 |
+
------
|
| 1742 |
+
next : RecordBatch
|
| 1743 |
+
"""
|
| 1744 |
+
cdef:
|
| 1745 |
+
vector[int] c_row_groups
|
| 1746 |
+
vector[int] c_column_indices
|
| 1747 |
+
shared_ptr[CRecordBatch] record_batch
|
| 1748 |
+
UniquePtrNoGIL[CRecordBatchReader] recordbatchreader
|
| 1749 |
+
|
| 1750 |
+
self.set_batch_size(batch_size)
|
| 1751 |
+
|
| 1752 |
+
if use_threads:
|
| 1753 |
+
self.set_use_threads(use_threads)
|
| 1754 |
+
|
| 1755 |
+
for row_group in row_groups:
|
| 1756 |
+
c_row_groups.push_back(row_group)
|
| 1757 |
+
|
| 1758 |
+
if column_indices is not None:
|
| 1759 |
+
for index in column_indices:
|
| 1760 |
+
c_column_indices.push_back(index)
|
| 1761 |
+
with nogil:
|
| 1762 |
+
recordbatchreader = GetResultValue(
|
| 1763 |
+
self.reader.get().GetRecordBatchReader(
|
| 1764 |
+
c_row_groups, c_column_indices
|
| 1765 |
+
)
|
| 1766 |
+
)
|
| 1767 |
+
else:
|
| 1768 |
+
with nogil:
|
| 1769 |
+
recordbatchreader = GetResultValue(
|
| 1770 |
+
self.reader.get().GetRecordBatchReader(
|
| 1771 |
+
c_row_groups
|
| 1772 |
+
)
|
| 1773 |
+
)
|
| 1774 |
+
|
| 1775 |
+
while True:
|
| 1776 |
+
with nogil:
|
| 1777 |
+
check_status(
|
| 1778 |
+
recordbatchreader.get().ReadNext(&record_batch)
|
| 1779 |
+
)
|
| 1780 |
+
if record_batch.get() == NULL:
|
| 1781 |
+
break
|
| 1782 |
+
|
| 1783 |
+
yield pyarrow_wrap_batch(record_batch)
|
| 1784 |
+
|
| 1785 |
+
def read_row_group(self, int i, column_indices=None,
|
| 1786 |
+
bint use_threads=True):
|
| 1787 |
+
"""
|
| 1788 |
+
Parameters
|
| 1789 |
+
----------
|
| 1790 |
+
i : int
|
| 1791 |
+
column_indices : list[int], optional
|
| 1792 |
+
use_threads : bool, default True
|
| 1793 |
+
|
| 1794 |
+
Returns
|
| 1795 |
+
-------
|
| 1796 |
+
table : pyarrow.Table
|
| 1797 |
+
"""
|
| 1798 |
+
return self.read_row_groups([i], column_indices, use_threads)
|
| 1799 |
+
|
| 1800 |
+
def read_row_groups(self, row_groups not None, column_indices=None,
|
| 1801 |
+
bint use_threads=True):
|
| 1802 |
+
"""
|
| 1803 |
+
Parameters
|
| 1804 |
+
----------
|
| 1805 |
+
row_groups : list[int]
|
| 1806 |
+
column_indices : list[int], optional
|
| 1807 |
+
use_threads : bool, default True
|
| 1808 |
+
|
| 1809 |
+
Returns
|
| 1810 |
+
-------
|
| 1811 |
+
table : pyarrow.Table
|
| 1812 |
+
"""
|
| 1813 |
+
cdef:
|
| 1814 |
+
shared_ptr[CTable] ctable
|
| 1815 |
+
vector[int] c_row_groups
|
| 1816 |
+
vector[int] c_column_indices
|
| 1817 |
+
|
| 1818 |
+
self.set_use_threads(use_threads)
|
| 1819 |
+
|
| 1820 |
+
for row_group in row_groups:
|
| 1821 |
+
c_row_groups.push_back(row_group)
|
| 1822 |
+
|
| 1823 |
+
if column_indices is not None:
|
| 1824 |
+
for index in column_indices:
|
| 1825 |
+
c_column_indices.push_back(index)
|
| 1826 |
+
|
| 1827 |
+
with nogil:
|
| 1828 |
+
check_status(self.reader.get()
|
| 1829 |
+
.ReadRowGroups(c_row_groups, c_column_indices,
|
| 1830 |
+
&ctable))
|
| 1831 |
+
else:
|
| 1832 |
+
# Read all columns
|
| 1833 |
+
with nogil:
|
| 1834 |
+
check_status(self.reader.get()
|
| 1835 |
+
.ReadRowGroups(c_row_groups, &ctable))
|
| 1836 |
+
return pyarrow_wrap_table(ctable)
|
| 1837 |
+
|
| 1838 |
+
def read_all(self, column_indices=None, bint use_threads=True):
|
| 1839 |
+
"""
|
| 1840 |
+
Parameters
|
| 1841 |
+
----------
|
| 1842 |
+
column_indices : list[int], optional
|
| 1843 |
+
use_threads : bool, default True
|
| 1844 |
+
|
| 1845 |
+
Returns
|
| 1846 |
+
-------
|
| 1847 |
+
table : pyarrow.Table
|
| 1848 |
+
"""
|
| 1849 |
+
cdef:
|
| 1850 |
+
shared_ptr[CTable] ctable
|
| 1851 |
+
vector[int] c_column_indices
|
| 1852 |
+
|
| 1853 |
+
self.set_use_threads(use_threads)
|
| 1854 |
+
|
| 1855 |
+
if column_indices is not None:
|
| 1856 |
+
for index in column_indices:
|
| 1857 |
+
c_column_indices.push_back(index)
|
| 1858 |
+
|
| 1859 |
+
with nogil:
|
| 1860 |
+
check_status(self.reader.get()
|
| 1861 |
+
.ReadTable(c_column_indices, &ctable))
|
| 1862 |
+
else:
|
| 1863 |
+
# Read all columns
|
| 1864 |
+
with nogil:
|
| 1865 |
+
check_status(self.reader.get()
|
| 1866 |
+
.ReadTable(&ctable))
|
| 1867 |
+
return pyarrow_wrap_table(ctable)
|
| 1868 |
+
|
| 1869 |
+
def scan_contents(self, column_indices=None, batch_size=65536):
|
| 1870 |
+
"""
|
| 1871 |
+
Parameters
|
| 1872 |
+
----------
|
| 1873 |
+
column_indices : list[int], optional
|
| 1874 |
+
batch_size : int32, default 65536
|
| 1875 |
+
|
| 1876 |
+
Returns
|
| 1877 |
+
-------
|
| 1878 |
+
num_rows : int64
|
| 1879 |
+
"""
|
| 1880 |
+
cdef:
|
| 1881 |
+
vector[int] c_column_indices
|
| 1882 |
+
int32_t c_batch_size
|
| 1883 |
+
int64_t c_num_rows
|
| 1884 |
+
|
| 1885 |
+
if column_indices is not None:
|
| 1886 |
+
for index in column_indices:
|
| 1887 |
+
c_column_indices.push_back(index)
|
| 1888 |
+
|
| 1889 |
+
c_batch_size = batch_size
|
| 1890 |
+
|
| 1891 |
+
with nogil:
|
| 1892 |
+
check_status(self.reader.get()
|
| 1893 |
+
.ScanContents(c_column_indices, c_batch_size,
|
| 1894 |
+
&c_num_rows))
|
| 1895 |
+
|
| 1896 |
+
return c_num_rows
|
| 1897 |
+
|
| 1898 |
+
def column_name_idx(self, column_name):
|
| 1899 |
+
"""
|
| 1900 |
+
Find the index of a column by its name.
|
| 1901 |
+
|
| 1902 |
+
Parameters
|
| 1903 |
+
----------
|
| 1904 |
+
column_name : str
|
| 1905 |
+
Name of the column; separation of nesting levels is done via ".".
|
| 1906 |
+
|
| 1907 |
+
Returns
|
| 1908 |
+
-------
|
| 1909 |
+
column_idx : int
|
| 1910 |
+
Integer index of the column in the schema.
|
| 1911 |
+
"""
|
| 1912 |
+
cdef:
|
| 1913 |
+
FileMetaData container = self.metadata
|
| 1914 |
+
const CFileMetaData* metadata = container._metadata
|
| 1915 |
+
int i = 0
|
| 1916 |
+
|
| 1917 |
+
if self._column_idx_map is None:
|
| 1918 |
+
self._column_idx_map = {}
|
| 1919 |
+
for i in range(0, metadata.num_columns()):
|
| 1920 |
+
col_bytes = tobytes(metadata.schema().Column(i)
|
| 1921 |
+
.path().get().ToDotString())
|
| 1922 |
+
self._column_idx_map[col_bytes] = i
|
| 1923 |
+
|
| 1924 |
+
return self._column_idx_map[tobytes(column_name)]
|
| 1925 |
+
|
| 1926 |
+
def read_column(self, int column_index):
|
| 1927 |
+
"""
|
| 1928 |
+
Read the column at the specified index.
|
| 1929 |
+
|
| 1930 |
+
Parameters
|
| 1931 |
+
----------
|
| 1932 |
+
column_index : int
|
| 1933 |
+
Index of the column.
|
| 1934 |
+
|
| 1935 |
+
Returns
|
| 1936 |
+
-------
|
| 1937 |
+
column : pyarrow.ChunkedArray
|
| 1938 |
+
"""
|
| 1939 |
+
cdef shared_ptr[CChunkedArray] out
|
| 1940 |
+
with nogil:
|
| 1941 |
+
check_status(self.reader.get()
|
| 1942 |
+
.ReadColumn(column_index, &out))
|
| 1943 |
+
return pyarrow_wrap_chunked_array(out)
|
| 1944 |
+
|
| 1945 |
+
def close(self):
|
| 1946 |
+
if not self.closed:
|
| 1947 |
+
with nogil:
|
| 1948 |
+
check_status(self.rd_handle.get().Close())
|
| 1949 |
+
|
| 1950 |
+
@property
|
| 1951 |
+
def closed(self):
|
| 1952 |
+
if self.rd_handle == NULL:
|
| 1953 |
+
return True
|
| 1954 |
+
with nogil:
|
| 1955 |
+
closed = self.rd_handle.get().closed()
|
| 1956 |
+
return closed
|
| 1957 |
+
|
| 1958 |
+
|
| 1959 |
+
cdef CSortingColumn _convert_sorting_column(SortingColumn sorting_column):
|
| 1960 |
+
cdef CSortingColumn c_sorting_column
|
| 1961 |
+
|
| 1962 |
+
c_sorting_column.column_idx = sorting_column.column_index
|
| 1963 |
+
c_sorting_column.descending = sorting_column.descending
|
| 1964 |
+
c_sorting_column.nulls_first = sorting_column.nulls_first
|
| 1965 |
+
|
| 1966 |
+
return c_sorting_column
|
| 1967 |
+
|
| 1968 |
+
|
| 1969 |
+
cdef vector[CSortingColumn] _convert_sorting_columns(sorting_columns) except *:
|
| 1970 |
+
if not (isinstance(sorting_columns, Sequence)
|
| 1971 |
+
and all(isinstance(col, SortingColumn) for col in sorting_columns)):
|
| 1972 |
+
raise ValueError(
|
| 1973 |
+
"'sorting_columns' must be a list of `SortingColumn`")
|
| 1974 |
+
|
| 1975 |
+
cdef vector[CSortingColumn] c_sorting_columns = [_convert_sorting_column(col)
|
| 1976 |
+
for col in sorting_columns]
|
| 1977 |
+
|
| 1978 |
+
return c_sorting_columns
|
| 1979 |
+
|
| 1980 |
+
|
| 1981 |
+
cdef shared_ptr[WriterProperties] _create_writer_properties(
|
| 1982 |
+
use_dictionary=None,
|
| 1983 |
+
compression=None,
|
| 1984 |
+
version=None,
|
| 1985 |
+
write_statistics=None,
|
| 1986 |
+
data_page_size=None,
|
| 1987 |
+
max_rows_per_page=None,
|
| 1988 |
+
compression_level=None,
|
| 1989 |
+
use_byte_stream_split=False,
|
| 1990 |
+
column_encoding=None,
|
| 1991 |
+
data_page_version=None,
|
| 1992 |
+
FileEncryptionProperties encryption_properties=None,
|
| 1993 |
+
write_batch_size=None,
|
| 1994 |
+
dictionary_pagesize_limit=None,
|
| 1995 |
+
write_page_index=False,
|
| 1996 |
+
write_page_checksum=False,
|
| 1997 |
+
sorting_columns=None,
|
| 1998 |
+
store_decimal_as_integer=False,
|
| 1999 |
+
use_content_defined_chunking=False) except *:
|
| 2000 |
+
|
| 2001 |
+
"""General writer properties"""
|
| 2002 |
+
cdef:
|
| 2003 |
+
shared_ptr[WriterProperties] properties
|
| 2004 |
+
WriterProperties.Builder props
|
| 2005 |
+
CdcOptions cdc_options
|
| 2006 |
+
|
| 2007 |
+
# data_page_version
|
| 2008 |
+
|
| 2009 |
+
if data_page_version is not None:
|
| 2010 |
+
if data_page_version == "1.0":
|
| 2011 |
+
props.data_page_version(ParquetDataPageVersion_V1)
|
| 2012 |
+
elif data_page_version == "2.0":
|
| 2013 |
+
props.data_page_version(ParquetDataPageVersion_V2)
|
| 2014 |
+
else:
|
| 2015 |
+
raise ValueError(
|
| 2016 |
+
f"Unsupported Parquet data page version: {data_page_version}")
|
| 2017 |
+
|
| 2018 |
+
# version
|
| 2019 |
+
|
| 2020 |
+
if version is not None:
|
| 2021 |
+
if version == "1.0":
|
| 2022 |
+
props.version(ParquetVersion_V1)
|
| 2023 |
+
elif version == "2.4":
|
| 2024 |
+
props.version(ParquetVersion_V2_4)
|
| 2025 |
+
elif version == "2.6":
|
| 2026 |
+
props.version(ParquetVersion_V2_6)
|
| 2027 |
+
else:
|
| 2028 |
+
raise ValueError(f"Unsupported Parquet format version: {version}")
|
| 2029 |
+
|
| 2030 |
+
# compression
|
| 2031 |
+
|
| 2032 |
+
if isinstance(compression, basestring):
|
| 2033 |
+
check_compression_name(compression)
|
| 2034 |
+
props.compression(compression_from_name(compression))
|
| 2035 |
+
elif compression is not None:
|
| 2036 |
+
for column, codec in compression.iteritems():
|
| 2037 |
+
check_compression_name(codec)
|
| 2038 |
+
props.compression(tobytes(column), compression_from_name(codec))
|
| 2039 |
+
|
| 2040 |
+
if isinstance(compression_level, int):
|
| 2041 |
+
props.compression_level(compression_level)
|
| 2042 |
+
elif compression_level is not None:
|
| 2043 |
+
for column, level in compression_level.iteritems():
|
| 2044 |
+
props.compression_level(tobytes(column), level)
|
| 2045 |
+
|
| 2046 |
+
# use_dictionary
|
| 2047 |
+
|
| 2048 |
+
if isinstance(use_dictionary, bool):
|
| 2049 |
+
if use_dictionary:
|
| 2050 |
+
props.enable_dictionary()
|
| 2051 |
+
if column_encoding is not None:
|
| 2052 |
+
raise ValueError(
|
| 2053 |
+
"To use 'column_encoding' set 'use_dictionary' to False")
|
| 2054 |
+
else:
|
| 2055 |
+
props.disable_dictionary()
|
| 2056 |
+
elif use_dictionary is not None:
|
| 2057 |
+
# Deactivate dictionary encoding by default
|
| 2058 |
+
props.disable_dictionary()
|
| 2059 |
+
for column in use_dictionary:
|
| 2060 |
+
props.enable_dictionary(tobytes(column))
|
| 2061 |
+
if (column_encoding is not None and
|
| 2062 |
+
column_encoding.get(column) is not None):
|
| 2063 |
+
raise ValueError(
|
| 2064 |
+
"To use 'column_encoding' set 'use_dictionary' to False")
|
| 2065 |
+
|
| 2066 |
+
# write_statistics
|
| 2067 |
+
|
| 2068 |
+
if isinstance(write_statistics, bool):
|
| 2069 |
+
if write_statistics:
|
| 2070 |
+
props.enable_statistics()
|
| 2071 |
+
else:
|
| 2072 |
+
props.disable_statistics()
|
| 2073 |
+
elif write_statistics is not None:
|
| 2074 |
+
# Deactivate statistics by default and enable for specified columns
|
| 2075 |
+
props.disable_statistics()
|
| 2076 |
+
for column in write_statistics:
|
| 2077 |
+
props.enable_statistics(tobytes(column))
|
| 2078 |
+
|
| 2079 |
+
# sorting_columns
|
| 2080 |
+
|
| 2081 |
+
if sorting_columns is not None:
|
| 2082 |
+
props.set_sorting_columns(_convert_sorting_columns(sorting_columns))
|
| 2083 |
+
|
| 2084 |
+
# use_byte_stream_split
|
| 2085 |
+
|
| 2086 |
+
if isinstance(use_byte_stream_split, bool):
|
| 2087 |
+
if use_byte_stream_split:
|
| 2088 |
+
if column_encoding is not None:
|
| 2089 |
+
raise ValueError(
|
| 2090 |
+
"'use_byte_stream_split' cannot be passed"
|
| 2091 |
+
"together with 'column_encoding'")
|
| 2092 |
+
else:
|
| 2093 |
+
props.encoding(ParquetEncoding_BYTE_STREAM_SPLIT)
|
| 2094 |
+
elif use_byte_stream_split is not None:
|
| 2095 |
+
for column in use_byte_stream_split:
|
| 2096 |
+
if column_encoding is None:
|
| 2097 |
+
column_encoding = {column: 'BYTE_STREAM_SPLIT'}
|
| 2098 |
+
elif column_encoding.get(column, None) is None:
|
| 2099 |
+
column_encoding[column] = 'BYTE_STREAM_SPLIT'
|
| 2100 |
+
else:
|
| 2101 |
+
raise ValueError(
|
| 2102 |
+
"'use_byte_stream_split' cannot be passed"
|
| 2103 |
+
"together with 'column_encoding'")
|
| 2104 |
+
|
| 2105 |
+
# store_decimal_as_integer
|
| 2106 |
+
|
| 2107 |
+
if isinstance(store_decimal_as_integer, bool):
|
| 2108 |
+
if store_decimal_as_integer:
|
| 2109 |
+
props.enable_store_decimal_as_integer()
|
| 2110 |
+
else:
|
| 2111 |
+
props.disable_store_decimal_as_integer()
|
| 2112 |
+
else:
|
| 2113 |
+
raise TypeError("'store_decimal_as_integer' must be a boolean")
|
| 2114 |
+
|
| 2115 |
+
# column_encoding
|
| 2116 |
+
# encoding map - encode individual columns
|
| 2117 |
+
|
| 2118 |
+
if column_encoding is not None:
|
| 2119 |
+
if isinstance(column_encoding, dict):
|
| 2120 |
+
for column, _encoding in column_encoding.items():
|
| 2121 |
+
props.encoding(tobytes(column),
|
| 2122 |
+
encoding_enum_from_name(_encoding))
|
| 2123 |
+
elif isinstance(column_encoding, str):
|
| 2124 |
+
props.encoding(encoding_enum_from_name(column_encoding))
|
| 2125 |
+
else:
|
| 2126 |
+
raise TypeError(
|
| 2127 |
+
"'column_encoding' should be a dictionary or a string")
|
| 2128 |
+
|
| 2129 |
+
# size limits
|
| 2130 |
+
if data_page_size is not None:
|
| 2131 |
+
props.data_pagesize(data_page_size)
|
| 2132 |
+
|
| 2133 |
+
if max_rows_per_page is not None:
|
| 2134 |
+
props.max_rows_per_page(max_rows_per_page)
|
| 2135 |
+
|
| 2136 |
+
if write_batch_size is not None:
|
| 2137 |
+
props.write_batch_size(write_batch_size)
|
| 2138 |
+
|
| 2139 |
+
if dictionary_pagesize_limit is not None:
|
| 2140 |
+
props.dictionary_pagesize_limit(dictionary_pagesize_limit)
|
| 2141 |
+
|
| 2142 |
+
# content defined chunking
|
| 2143 |
+
|
| 2144 |
+
if use_content_defined_chunking is True:
|
| 2145 |
+
props.enable_content_defined_chunking()
|
| 2146 |
+
elif use_content_defined_chunking is False:
|
| 2147 |
+
props.disable_content_defined_chunking()
|
| 2148 |
+
elif isinstance(use_content_defined_chunking, dict):
|
| 2149 |
+
defined_keys = use_content_defined_chunking.keys()
|
| 2150 |
+
mandatory_keys = {"min_chunk_size", "max_chunk_size"}
|
| 2151 |
+
allowed_keys = {"min_chunk_size", "max_chunk_size", "norm_level"}
|
| 2152 |
+
unknown_keys = defined_keys - allowed_keys
|
| 2153 |
+
missing_keys = mandatory_keys - defined_keys
|
| 2154 |
+
if unknown_keys:
|
| 2155 |
+
raise ValueError(
|
| 2156 |
+
f"Unknown options in 'use_content_defined_chunking': {unknown_keys}")
|
| 2157 |
+
if missing_keys:
|
| 2158 |
+
raise ValueError(
|
| 2159 |
+
f"Missing options in 'use_content_defined_chunking': {missing_keys}")
|
| 2160 |
+
cdc_options.min_chunk_size = use_content_defined_chunking["min_chunk_size"]
|
| 2161 |
+
cdc_options.max_chunk_size = use_content_defined_chunking["max_chunk_size"]
|
| 2162 |
+
cdc_options.norm_level = use_content_defined_chunking.get("norm_level", 0)
|
| 2163 |
+
props.enable_content_defined_chunking()
|
| 2164 |
+
props.content_defined_chunking_options(cdc_options)
|
| 2165 |
+
else:
|
| 2166 |
+
raise TypeError(
|
| 2167 |
+
"'use_content_defined_chunking' should be either boolean or a dictionary")
|
| 2168 |
+
|
| 2169 |
+
# encryption
|
| 2170 |
+
|
| 2171 |
+
if encryption_properties is not None:
|
| 2172 |
+
props.encryption(
|
| 2173 |
+
(<FileEncryptionProperties>encryption_properties).unwrap())
|
| 2174 |
+
|
| 2175 |
+
# For backwards compatibility reasons we cap the maximum row group size
|
| 2176 |
+
# at 64Mi rows. This could be changed in the future, though it would be
|
| 2177 |
+
# a breaking change.
|
| 2178 |
+
#
|
| 2179 |
+
# The user can always specify a smaller row group size (and the default
|
| 2180 |
+
# is smaller) when calling write_table. If the call to write_table uses
|
| 2181 |
+
# a size larger than this then it will be latched to this value.
|
| 2182 |
+
props.max_row_group_length(_MAX_ROW_GROUP_SIZE)
|
| 2183 |
+
|
| 2184 |
+
# checksum
|
| 2185 |
+
|
| 2186 |
+
if write_page_checksum:
|
| 2187 |
+
props.enable_page_checksum()
|
| 2188 |
+
else:
|
| 2189 |
+
props.disable_page_checksum()
|
| 2190 |
+
|
| 2191 |
+
# page index
|
| 2192 |
+
|
| 2193 |
+
if write_page_index:
|
| 2194 |
+
props.enable_write_page_index()
|
| 2195 |
+
else:
|
| 2196 |
+
props.disable_write_page_index()
|
| 2197 |
+
|
| 2198 |
+
properties = props.build()
|
| 2199 |
+
|
| 2200 |
+
return properties
|
| 2201 |
+
|
| 2202 |
+
|
| 2203 |
+
cdef shared_ptr[ArrowWriterProperties] _create_arrow_writer_properties(
|
| 2204 |
+
use_deprecated_int96_timestamps=False,
|
| 2205 |
+
coerce_timestamps=None,
|
| 2206 |
+
allow_truncated_timestamps=False,
|
| 2207 |
+
writer_engine_version=None,
|
| 2208 |
+
use_compliant_nested_type=True,
|
| 2209 |
+
store_schema=True,
|
| 2210 |
+
write_time_adjusted_to_utc=False) except *:
|
| 2211 |
+
"""Arrow writer properties"""
|
| 2212 |
+
cdef:
|
| 2213 |
+
shared_ptr[ArrowWriterProperties] arrow_properties
|
| 2214 |
+
ArrowWriterProperties.Builder arrow_props
|
| 2215 |
+
|
| 2216 |
+
# Store the original Arrow schema so things like dictionary types can
|
| 2217 |
+
# be automatically reconstructed
|
| 2218 |
+
if store_schema:
|
| 2219 |
+
arrow_props.store_schema()
|
| 2220 |
+
|
| 2221 |
+
# int96 support
|
| 2222 |
+
|
| 2223 |
+
if use_deprecated_int96_timestamps:
|
| 2224 |
+
arrow_props.enable_deprecated_int96_timestamps()
|
| 2225 |
+
else:
|
| 2226 |
+
arrow_props.disable_deprecated_int96_timestamps()
|
| 2227 |
+
|
| 2228 |
+
# coerce_timestamps
|
| 2229 |
+
|
| 2230 |
+
if coerce_timestamps == 'ms':
|
| 2231 |
+
arrow_props.coerce_timestamps(TimeUnit_MILLI)
|
| 2232 |
+
elif coerce_timestamps == 'us':
|
| 2233 |
+
arrow_props.coerce_timestamps(TimeUnit_MICRO)
|
| 2234 |
+
elif coerce_timestamps is not None:
|
| 2235 |
+
raise ValueError(f'Invalid value for coerce_timestamps: {coerce_timestamps}')
|
| 2236 |
+
|
| 2237 |
+
# allow_truncated_timestamps
|
| 2238 |
+
|
| 2239 |
+
if allow_truncated_timestamps:
|
| 2240 |
+
arrow_props.allow_truncated_timestamps()
|
| 2241 |
+
else:
|
| 2242 |
+
arrow_props.disallow_truncated_timestamps()
|
| 2243 |
+
|
| 2244 |
+
# use_compliant_nested_type
|
| 2245 |
+
|
| 2246 |
+
if use_compliant_nested_type:
|
| 2247 |
+
arrow_props.enable_compliant_nested_types()
|
| 2248 |
+
else:
|
| 2249 |
+
arrow_props.disable_compliant_nested_types()
|
| 2250 |
+
|
| 2251 |
+
# writer_engine_version
|
| 2252 |
+
|
| 2253 |
+
if writer_engine_version == "V1":
|
| 2254 |
+
warnings.warn("V1 parquet writer engine is a no-op. Use V2.")
|
| 2255 |
+
arrow_props.set_engine_version(ArrowWriterEngineVersion.V1)
|
| 2256 |
+
elif writer_engine_version != "V2":
|
| 2257 |
+
raise ValueError(f"Unsupported Writer Engine Version: {writer_engine_version}")
|
| 2258 |
+
|
| 2259 |
+
arrow_props.set_time_adjusted_to_utc(write_time_adjusted_to_utc)
|
| 2260 |
+
|
| 2261 |
+
arrow_properties = arrow_props.build()
|
| 2262 |
+
|
| 2263 |
+
return arrow_properties
|
| 2264 |
+
|
| 2265 |
+
cdef _name_to_index_map(Schema arrow_schema):
|
| 2266 |
+
cdef:
|
| 2267 |
+
shared_ptr[CSchema] sp_arrow_schema
|
| 2268 |
+
shared_ptr[SchemaDescriptor] sp_parquet_schema
|
| 2269 |
+
shared_ptr[WriterProperties] props = _create_writer_properties()
|
| 2270 |
+
shared_ptr[ArrowWriterProperties] arrow_props = _create_arrow_writer_properties(
|
| 2271 |
+
use_deprecated_int96_timestamps=False,
|
| 2272 |
+
coerce_timestamps=None,
|
| 2273 |
+
allow_truncated_timestamps=False,
|
| 2274 |
+
writer_engine_version="V2"
|
| 2275 |
+
)
|
| 2276 |
+
|
| 2277 |
+
sp_arrow_schema = pyarrow_unwrap_schema(arrow_schema)
|
| 2278 |
+
|
| 2279 |
+
with nogil:
|
| 2280 |
+
check_status(ToParquetSchema(
|
| 2281 |
+
sp_arrow_schema.get(), deref(props.get()), deref(arrow_props.get()), &sp_parquet_schema))
|
| 2282 |
+
|
| 2283 |
+
out = dict()
|
| 2284 |
+
|
| 2285 |
+
cdef SchemaDescriptor* parquet_schema = sp_parquet_schema.get()
|
| 2286 |
+
|
| 2287 |
+
for i in range(parquet_schema.num_columns()):
|
| 2288 |
+
name = frombytes(parquet_schema.Column(i).path().get().ToDotString())
|
| 2289 |
+
out[name] = i
|
| 2290 |
+
|
| 2291 |
+
return out
|
| 2292 |
+
|
| 2293 |
+
|
| 2294 |
+
cdef class ParquetWriter(_Weakrefable):
|
| 2295 |
+
cdef:
|
| 2296 |
+
unique_ptr[FileWriter] writer
|
| 2297 |
+
shared_ptr[COutputStream] sink
|
| 2298 |
+
bint own_sink
|
| 2299 |
+
|
| 2300 |
+
def __cinit__(self, where, Schema schema not None, use_dictionary=None,
|
| 2301 |
+
compression=None, version=None,
|
| 2302 |
+
write_statistics=None,
|
| 2303 |
+
MemoryPool memory_pool=None,
|
| 2304 |
+
use_deprecated_int96_timestamps=False,
|
| 2305 |
+
coerce_timestamps=None,
|
| 2306 |
+
data_page_size=None,
|
| 2307 |
+
max_rows_per_page=None,
|
| 2308 |
+
allow_truncated_timestamps=False,
|
| 2309 |
+
compression_level=None,
|
| 2310 |
+
use_byte_stream_split=False,
|
| 2311 |
+
column_encoding=None,
|
| 2312 |
+
writer_engine_version=None,
|
| 2313 |
+
data_page_version=None,
|
| 2314 |
+
use_compliant_nested_type=True,
|
| 2315 |
+
encryption_properties=None,
|
| 2316 |
+
write_batch_size=None,
|
| 2317 |
+
dictionary_pagesize_limit=None,
|
| 2318 |
+
store_schema=True,
|
| 2319 |
+
write_page_index=False,
|
| 2320 |
+
write_page_checksum=False,
|
| 2321 |
+
sorting_columns=None,
|
| 2322 |
+
store_decimal_as_integer=False,
|
| 2323 |
+
use_content_defined_chunking=False,
|
| 2324 |
+
write_time_adjusted_to_utc=False):
|
| 2325 |
+
cdef:
|
| 2326 |
+
shared_ptr[WriterProperties] properties
|
| 2327 |
+
shared_ptr[ArrowWriterProperties] arrow_properties
|
| 2328 |
+
c_string c_where
|
| 2329 |
+
CMemoryPool* pool
|
| 2330 |
+
|
| 2331 |
+
try:
|
| 2332 |
+
where = _stringify_path(where)
|
| 2333 |
+
except TypeError:
|
| 2334 |
+
get_writer(where, &self.sink)
|
| 2335 |
+
self.own_sink = False
|
| 2336 |
+
else:
|
| 2337 |
+
c_where = tobytes(where)
|
| 2338 |
+
with nogil:
|
| 2339 |
+
self.sink = GetResultValue(FileOutputStream.Open(c_where))
|
| 2340 |
+
self.own_sink = True
|
| 2341 |
+
|
| 2342 |
+
properties = _create_writer_properties(
|
| 2343 |
+
use_dictionary=use_dictionary,
|
| 2344 |
+
compression=compression,
|
| 2345 |
+
version=version,
|
| 2346 |
+
write_statistics=write_statistics,
|
| 2347 |
+
data_page_size=data_page_size,
|
| 2348 |
+
max_rows_per_page=max_rows_per_page,
|
| 2349 |
+
compression_level=compression_level,
|
| 2350 |
+
use_byte_stream_split=use_byte_stream_split,
|
| 2351 |
+
column_encoding=column_encoding,
|
| 2352 |
+
data_page_version=data_page_version,
|
| 2353 |
+
encryption_properties=encryption_properties,
|
| 2354 |
+
write_batch_size=write_batch_size,
|
| 2355 |
+
dictionary_pagesize_limit=dictionary_pagesize_limit,
|
| 2356 |
+
write_page_index=write_page_index,
|
| 2357 |
+
write_page_checksum=write_page_checksum,
|
| 2358 |
+
sorting_columns=sorting_columns,
|
| 2359 |
+
store_decimal_as_integer=store_decimal_as_integer,
|
| 2360 |
+
use_content_defined_chunking=use_content_defined_chunking
|
| 2361 |
+
)
|
| 2362 |
+
arrow_properties = _create_arrow_writer_properties(
|
| 2363 |
+
use_deprecated_int96_timestamps=use_deprecated_int96_timestamps,
|
| 2364 |
+
coerce_timestamps=coerce_timestamps,
|
| 2365 |
+
allow_truncated_timestamps=allow_truncated_timestamps,
|
| 2366 |
+
writer_engine_version=writer_engine_version,
|
| 2367 |
+
use_compliant_nested_type=use_compliant_nested_type,
|
| 2368 |
+
store_schema=store_schema,
|
| 2369 |
+
write_time_adjusted_to_utc=write_time_adjusted_to_utc,
|
| 2370 |
+
)
|
| 2371 |
+
|
| 2372 |
+
pool = maybe_unbox_memory_pool(memory_pool)
|
| 2373 |
+
with nogil:
|
| 2374 |
+
self.writer = move(GetResultValue(
|
| 2375 |
+
FileWriter.Open(deref(schema.schema), pool,
|
| 2376 |
+
self.sink, properties, arrow_properties)))
|
| 2377 |
+
|
| 2378 |
+
def close(self):
|
| 2379 |
+
with nogil:
|
| 2380 |
+
check_status(self.writer.get().Close())
|
| 2381 |
+
if self.own_sink:
|
| 2382 |
+
check_status(self.sink.get().Close())
|
| 2383 |
+
|
| 2384 |
+
def write_table(self, Table table, row_group_size=None):
|
| 2385 |
+
cdef:
|
| 2386 |
+
CTable* ctable = table.table
|
| 2387 |
+
int64_t c_row_group_size
|
| 2388 |
+
|
| 2389 |
+
if row_group_size is None or row_group_size == -1:
|
| 2390 |
+
c_row_group_size = min(ctable.num_rows(), _DEFAULT_ROW_GROUP_SIZE)
|
| 2391 |
+
elif row_group_size == 0:
|
| 2392 |
+
raise ValueError('Row group size cannot be 0')
|
| 2393 |
+
else:
|
| 2394 |
+
c_row_group_size = row_group_size
|
| 2395 |
+
|
| 2396 |
+
with nogil:
|
| 2397 |
+
check_status(self.writer.get()
|
| 2398 |
+
.WriteTable(deref(ctable), c_row_group_size))
|
| 2399 |
+
|
| 2400 |
+
def add_key_value_metadata(self, key_value_metadata):
|
| 2401 |
+
cdef:
|
| 2402 |
+
shared_ptr[const CKeyValueMetadata] c_metadata
|
| 2403 |
+
|
| 2404 |
+
c_metadata = pyarrow_unwrap_metadata(KeyValueMetadata(key_value_metadata))
|
| 2405 |
+
with nogil:
|
| 2406 |
+
check_status(self.writer.get()
|
| 2407 |
+
.AddKeyValueMetadata(c_metadata))
|
| 2408 |
+
|
| 2409 |
+
@property
|
| 2410 |
+
def metadata(self):
|
| 2411 |
+
cdef:
|
| 2412 |
+
shared_ptr[CFileMetaData] metadata
|
| 2413 |
+
FileMetaData result
|
| 2414 |
+
with nogil:
|
| 2415 |
+
metadata = self.writer.get().metadata()
|
| 2416 |
+
if metadata:
|
| 2417 |
+
result = FileMetaData.__new__(FileMetaData)
|
| 2418 |
+
result.init(metadata)
|
| 2419 |
+
return result
|
| 2420 |
+
raise RuntimeError(
|
| 2421 |
+
'file metadata is only available after writer close')
|
shared/package-files/ab/ab448355bce6538ebff267fadd46a8e69604e0c832ae147dbe7f78409a904aff/blob
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Known facts in assumptions module.
|
| 3 |
+
|
| 4 |
+
This module defines the facts between unary predicates in ``get_known_facts()``,
|
| 5 |
+
and supports functions to generate the contents in
|
| 6 |
+
``sympy.assumptions.ask_generated`` file.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from sympy.assumptions.ask import Q
|
| 10 |
+
from sympy.assumptions.assume import AppliedPredicate
|
| 11 |
+
from sympy.core.cache import cacheit
|
| 12 |
+
from sympy.core.symbol import Symbol
|
| 13 |
+
from sympy.logic.boolalg import (to_cnf, And, Not, Implies, Equivalent,
|
| 14 |
+
Exclusive,)
|
| 15 |
+
from sympy.logic.inference import satisfiable
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@cacheit
|
| 19 |
+
def get_composite_predicates():
|
| 20 |
+
# To reduce the complexity of sat solver, these predicates are
|
| 21 |
+
# transformed into the combination of primitive predicates.
|
| 22 |
+
return {
|
| 23 |
+
Q.real : Q.negative | Q.zero | Q.positive,
|
| 24 |
+
Q.integer : Q.even | Q.odd,
|
| 25 |
+
Q.nonpositive : Q.negative | Q.zero,
|
| 26 |
+
Q.nonzero : Q.negative | Q.positive,
|
| 27 |
+
Q.nonnegative : Q.zero | Q.positive,
|
| 28 |
+
Q.extended_real : Q.negative_infinite | Q.negative | Q.zero | Q.positive | Q.positive_infinite,
|
| 29 |
+
Q.extended_positive: Q.positive | Q.positive_infinite,
|
| 30 |
+
Q.extended_negative: Q.negative | Q.negative_infinite,
|
| 31 |
+
Q.extended_nonzero: Q.negative_infinite | Q.negative | Q.positive | Q.positive_infinite,
|
| 32 |
+
Q.extended_nonpositive: Q.negative_infinite | Q.negative | Q.zero,
|
| 33 |
+
Q.extended_nonnegative: Q.zero | Q.positive | Q.positive_infinite,
|
| 34 |
+
Q.complex : Q.algebraic | Q.transcendental
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@cacheit
|
| 39 |
+
def get_known_facts(x=None):
|
| 40 |
+
"""
|
| 41 |
+
Facts between unary predicates.
|
| 42 |
+
|
| 43 |
+
Parameters
|
| 44 |
+
==========
|
| 45 |
+
|
| 46 |
+
x : Symbol, optional
|
| 47 |
+
Placeholder symbol for unary facts. Default is ``Symbol('x')``.
|
| 48 |
+
|
| 49 |
+
Returns
|
| 50 |
+
=======
|
| 51 |
+
|
| 52 |
+
fact : Known facts in conjugated normal form.
|
| 53 |
+
|
| 54 |
+
"""
|
| 55 |
+
if x is None:
|
| 56 |
+
x = Symbol('x')
|
| 57 |
+
|
| 58 |
+
fact = And(
|
| 59 |
+
# primitive predicates for extended real exclude each other.
|
| 60 |
+
Exclusive(Q.negative_infinite(x), Q.negative(x), Q.zero(x),
|
| 61 |
+
Q.positive(x), Q.positive_infinite(x)),
|
| 62 |
+
|
| 63 |
+
# build complex plane
|
| 64 |
+
Exclusive(Q.real(x), Q.imaginary(x)),
|
| 65 |
+
Implies(Q.real(x) | Q.imaginary(x), Q.complex(x)),
|
| 66 |
+
|
| 67 |
+
# other subsets of complex
|
| 68 |
+
Exclusive(Q.transcendental(x), Q.algebraic(x)),
|
| 69 |
+
Equivalent(Q.real(x), Q.rational(x) | Q.irrational(x)),
|
| 70 |
+
Exclusive(Q.irrational(x), Q.rational(x)),
|
| 71 |
+
Implies(Q.rational(x), Q.algebraic(x)),
|
| 72 |
+
|
| 73 |
+
# integers
|
| 74 |
+
Exclusive(Q.even(x), Q.odd(x)),
|
| 75 |
+
Implies(Q.integer(x), Q.rational(x)),
|
| 76 |
+
Implies(Q.zero(x), Q.even(x)),
|
| 77 |
+
Exclusive(Q.composite(x), Q.prime(x)),
|
| 78 |
+
Implies(Q.composite(x) | Q.prime(x), Q.integer(x) & Q.positive(x)),
|
| 79 |
+
Implies(Q.even(x) & Q.positive(x) & ~Q.prime(x), Q.composite(x)),
|
| 80 |
+
|
| 81 |
+
# hermitian and antihermitian
|
| 82 |
+
Implies(Q.real(x), Q.hermitian(x)),
|
| 83 |
+
Implies(Q.imaginary(x), Q.antihermitian(x)),
|
| 84 |
+
Implies(Q.zero(x), Q.hermitian(x) | Q.antihermitian(x)),
|
| 85 |
+
|
| 86 |
+
# define finity and infinity, and build extended real line
|
| 87 |
+
Exclusive(Q.infinite(x), Q.finite(x)),
|
| 88 |
+
Implies(Q.complex(x), Q.finite(x)),
|
| 89 |
+
Implies(Q.negative_infinite(x) | Q.positive_infinite(x), Q.infinite(x)),
|
| 90 |
+
|
| 91 |
+
# commutativity
|
| 92 |
+
Implies(Q.finite(x) | Q.infinite(x), Q.commutative(x)),
|
| 93 |
+
|
| 94 |
+
# matrices
|
| 95 |
+
Implies(Q.orthogonal(x), Q.positive_definite(x)),
|
| 96 |
+
Implies(Q.orthogonal(x), Q.unitary(x)),
|
| 97 |
+
Implies(Q.unitary(x) & Q.real_elements(x), Q.orthogonal(x)),
|
| 98 |
+
Implies(Q.unitary(x), Q.normal(x)),
|
| 99 |
+
Implies(Q.unitary(x), Q.invertible(x)),
|
| 100 |
+
Implies(Q.normal(x), Q.square(x)),
|
| 101 |
+
Implies(Q.diagonal(x), Q.normal(x)),
|
| 102 |
+
Implies(Q.positive_definite(x), Q.invertible(x)),
|
| 103 |
+
Implies(Q.diagonal(x), Q.upper_triangular(x)),
|
| 104 |
+
Implies(Q.diagonal(x), Q.lower_triangular(x)),
|
| 105 |
+
Implies(Q.lower_triangular(x), Q.triangular(x)),
|
| 106 |
+
Implies(Q.upper_triangular(x), Q.triangular(x)),
|
| 107 |
+
Implies(Q.triangular(x), Q.upper_triangular(x) | Q.lower_triangular(x)),
|
| 108 |
+
Implies(Q.upper_triangular(x) & Q.lower_triangular(x), Q.diagonal(x)),
|
| 109 |
+
Implies(Q.diagonal(x), Q.symmetric(x)),
|
| 110 |
+
Implies(Q.unit_triangular(x), Q.triangular(x)),
|
| 111 |
+
Implies(Q.invertible(x), Q.fullrank(x)),
|
| 112 |
+
Implies(Q.invertible(x), Q.square(x)),
|
| 113 |
+
Implies(Q.symmetric(x), Q.square(x)),
|
| 114 |
+
Implies(Q.fullrank(x) & Q.square(x), Q.invertible(x)),
|
| 115 |
+
Equivalent(Q.invertible(x), ~Q.singular(x)),
|
| 116 |
+
Implies(Q.integer_elements(x), Q.real_elements(x)),
|
| 117 |
+
Implies(Q.real_elements(x), Q.complex_elements(x)),
|
| 118 |
+
)
|
| 119 |
+
return fact
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def generate_known_facts_dict(keys, fact):
|
| 123 |
+
"""
|
| 124 |
+
Computes and returns a dictionary which contains the relations between
|
| 125 |
+
unary predicates.
|
| 126 |
+
|
| 127 |
+
Each key is a predicate, and item is two groups of predicates.
|
| 128 |
+
First group contains the predicates which are implied by the key, and
|
| 129 |
+
second group contains the predicates which are rejected by the key.
|
| 130 |
+
|
| 131 |
+
All predicates in *keys* and *fact* must be unary and have same placeholder
|
| 132 |
+
symbol.
|
| 133 |
+
|
| 134 |
+
Parameters
|
| 135 |
+
==========
|
| 136 |
+
|
| 137 |
+
keys : list of AppliedPredicate instances.
|
| 138 |
+
|
| 139 |
+
fact : Fact between predicates in conjugated normal form.
|
| 140 |
+
|
| 141 |
+
Examples
|
| 142 |
+
========
|
| 143 |
+
|
| 144 |
+
>>> from sympy import Q, And, Implies
|
| 145 |
+
>>> from sympy.assumptions.facts import generate_known_facts_dict
|
| 146 |
+
>>> from sympy.abc import x
|
| 147 |
+
>>> keys = [Q.even(x), Q.odd(x), Q.zero(x)]
|
| 148 |
+
>>> fact = And(Implies(Q.even(x), ~Q.odd(x)),
|
| 149 |
+
... Implies(Q.zero(x), Q.even(x)))
|
| 150 |
+
>>> generate_known_facts_dict(keys, fact)
|
| 151 |
+
{Q.even: ({Q.even}, {Q.odd}),
|
| 152 |
+
Q.odd: ({Q.odd}, {Q.even, Q.zero}),
|
| 153 |
+
Q.zero: ({Q.even, Q.zero}, {Q.odd})}
|
| 154 |
+
"""
|
| 155 |
+
fact_cnf = to_cnf(fact)
|
| 156 |
+
mapping = single_fact_lookup(keys, fact_cnf)
|
| 157 |
+
|
| 158 |
+
ret = {}
|
| 159 |
+
for key, value in mapping.items():
|
| 160 |
+
implied = set()
|
| 161 |
+
rejected = set()
|
| 162 |
+
for expr in value:
|
| 163 |
+
if isinstance(expr, AppliedPredicate):
|
| 164 |
+
implied.add(expr.function)
|
| 165 |
+
elif isinstance(expr, Not):
|
| 166 |
+
pred = expr.args[0]
|
| 167 |
+
rejected.add(pred.function)
|
| 168 |
+
ret[key.function] = (implied, rejected)
|
| 169 |
+
return ret
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@cacheit
|
| 173 |
+
def get_known_facts_keys():
|
| 174 |
+
"""
|
| 175 |
+
Return every unary predicates registered to ``Q``.
|
| 176 |
+
|
| 177 |
+
This function is used to generate the keys for
|
| 178 |
+
``generate_known_facts_dict``.
|
| 179 |
+
|
| 180 |
+
"""
|
| 181 |
+
exclude = set()
|
| 182 |
+
for pred in [Q.eq, Q.ne, Q.gt, Q.lt, Q.ge, Q.le]:
|
| 183 |
+
# exclude polyadic predicates
|
| 184 |
+
exclude.add(pred)
|
| 185 |
+
|
| 186 |
+
result = []
|
| 187 |
+
for attr in Q.__class__.__dict__:
|
| 188 |
+
if attr.startswith('__'):
|
| 189 |
+
continue
|
| 190 |
+
pred = getattr(Q, attr)
|
| 191 |
+
if pred in exclude:
|
| 192 |
+
continue
|
| 193 |
+
result.append(pred)
|
| 194 |
+
return result
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def single_fact_lookup(known_facts_keys, known_facts_cnf):
|
| 198 |
+
# Return the dictionary for quick lookup of single fact
|
| 199 |
+
mapping = {}
|
| 200 |
+
for key in known_facts_keys:
|
| 201 |
+
mapping[key] = {key}
|
| 202 |
+
for other_key in known_facts_keys:
|
| 203 |
+
if other_key != key:
|
| 204 |
+
if ask_full_inference(other_key, key, known_facts_cnf):
|
| 205 |
+
mapping[key].add(other_key)
|
| 206 |
+
if ask_full_inference(~other_key, key, known_facts_cnf):
|
| 207 |
+
mapping[key].add(~other_key)
|
| 208 |
+
return mapping
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def ask_full_inference(proposition, assumptions, known_facts_cnf):
|
| 212 |
+
"""
|
| 213 |
+
Method for inferring properties about objects.
|
| 214 |
+
|
| 215 |
+
"""
|
| 216 |
+
if not satisfiable(And(known_facts_cnf, assumptions, proposition)):
|
| 217 |
+
return False
|
| 218 |
+
if not satisfiable(And(known_facts_cnf, assumptions, Not(proposition))):
|
| 219 |
+
return True
|
| 220 |
+
return None
|
shared/package-files/ab/ab49726ba95b3ade0752e8de7edbd368aca9ac02ad53fc1f7fdc6ae2de917513/blob
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Iterator, Tuple, Union
|
| 2 |
+
from .api import ShardedOptimizer
|
| 3 |
+
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
|
| 6 |
+
from torch.distributed._shard.sharded_tensor import (
|
| 7 |
+
ShardedTensor
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
def named_params_with_sharded_tensor(
|
| 11 |
+
module: nn.Module,
|
| 12 |
+
prefix: str = '',
|
| 13 |
+
recurse: bool = True,
|
| 14 |
+
) -> Iterator[Tuple[str, Union[nn.Parameter, ShardedTensor]]]:
|
| 15 |
+
|
| 16 |
+
r"""Returns an iterator over module parameters (together with the
|
| 17 |
+
ShardedTensor parameters), yielding both the name of the parameter
|
| 18 |
+
as well as the parameter itself. This is typically passed to a
|
| 19 |
+
:class:torch.distributed._shard.sharded_optim.ShardedOptimizer
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
prefix (str): prefix to prepend to all parameter names.
|
| 23 |
+
recurse (bool): if True, then yields parameters of this module
|
| 24 |
+
and all submodules. Otherwise, yields only parameters that
|
| 25 |
+
are direct members of this module.
|
| 26 |
+
|
| 27 |
+
Yields:
|
| 28 |
+
(str, Union[Tensor, ShardedTensor]): Tuple containing
|
| 29 |
+
the name and parameter (or ShardedTensor parameter)
|
| 30 |
+
|
| 31 |
+
Example::
|
| 32 |
+
|
| 33 |
+
>>> # xdoctest: +SKIP
|
| 34 |
+
>>> model = torch.nn.Linear(*linear_size)
|
| 35 |
+
>>> shard_parameter(model, "weight", spec)
|
| 36 |
+
>>> for name, param in named_params_with_sharded_tensor(model):
|
| 37 |
+
>>> if name in ['weight']:
|
| 38 |
+
>>> print(param.size())
|
| 39 |
+
|
| 40 |
+
"""
|
| 41 |
+
modules = module.named_modules(prefix=prefix) if recurse else [(prefix, module)]
|
| 42 |
+
|
| 43 |
+
memo = set()
|
| 44 |
+
for mod_prefix, mod in modules:
|
| 45 |
+
# find all sharded tensor params
|
| 46 |
+
for name, val in vars(mod).items():
|
| 47 |
+
if isinstance(val, ShardedTensor) and val not in memo:
|
| 48 |
+
memo.add(val)
|
| 49 |
+
name = mod_prefix + ('.' if mod_prefix else '') + name
|
| 50 |
+
yield name, val
|
| 51 |
+
|
| 52 |
+
# find all nn.Parameters
|
| 53 |
+
for name, val in module.named_parameters():
|
| 54 |
+
yield name, val
|
shared/package-files/ab/ab4aa14c3d499d41f5c5930d56d69fd453de2bd55fde554e854ca6b0cc7714fd/blob
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Utilities imported from ipython_genutils
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
import textwrap
|
| 7 |
+
from textwrap import dedent
|
| 8 |
+
from textwrap import indent as _indent
|
| 9 |
+
from typing import List
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def indent(val):
|
| 13 |
+
res = _indent(val, " ")
|
| 14 |
+
return res
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def wrap_paragraphs(text: str, ncols: int = 80) -> List[str]:
|
| 18 |
+
"""Wrap multiple paragraphs to fit a specified width.
|
| 19 |
+
|
| 20 |
+
This is equivalent to textwrap.wrap, but with support for multiple
|
| 21 |
+
paragraphs, as separated by empty lines.
|
| 22 |
+
|
| 23 |
+
Returns
|
| 24 |
+
-------
|
| 25 |
+
|
| 26 |
+
list of complete paragraphs, wrapped to fill `ncols` columns.
|
| 27 |
+
"""
|
| 28 |
+
paragraph_re = re.compile(r"\n(\s*\n)+", re.MULTILINE)
|
| 29 |
+
text = dedent(text).strip()
|
| 30 |
+
paragraphs = paragraph_re.split(text)[::2] # every other entry is space
|
| 31 |
+
out_ps = []
|
| 32 |
+
indent_re = re.compile(r"\n\s+", re.MULTILINE)
|
| 33 |
+
for p in paragraphs:
|
| 34 |
+
# presume indentation that survives dedent is meaningful formatting,
|
| 35 |
+
# so don't fill unless text is flush.
|
| 36 |
+
if indent_re.search(p) is None:
|
| 37 |
+
# wrap paragraph
|
| 38 |
+
p = textwrap.fill(p, ncols)
|
| 39 |
+
out_ps.append(p)
|
| 40 |
+
return out_ps
|
shared/package-files/ab/ab4c2456e1557560999802b513b581427ca6f0f3e3dd01d0e244956ec4a9e3d9/blob
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cpu {
|
| 19 |
+
|
| 20 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor> _embedding_bag_forward_only(const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq=false, int64_t mode=0, bool sparse=false, const c10::optional<at::Tensor> & per_sample_weights={}, bool include_last_offset=false, int64_t padding_idx=-1);
|
| 21 |
+
|
| 22 |
+
} // namespace cpu
|
| 23 |
+
} // namespace at
|
shared/package-files/ab/ab50bb896a6f743ca611464dcb326f64bb0bb60c12918b428b1304f9f632203c/blob
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Module to implement predicate classes.
|
| 3 |
+
|
| 4 |
+
Class of every predicate registered to ``Q`` is defined here.
|
| 5 |
+
"""
|
shared/package-files/ab/ab5117f4081cab5c6cb575d6c8dc1b24220b3e596b9d3b5206d6dbf8869b00da/blob
ADDED
|
@@ -0,0 +1,560 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <ATen/CPUGeneratorImpl.h>
|
| 4 |
+
#include <ATen/DeviceAccelerator.h>
|
| 5 |
+
#include <ATen/LinalgBackend.h>
|
| 6 |
+
#include <ATen/core/ATenGeneral.h>
|
| 7 |
+
#include <ATen/core/DeprecatedTypeProperties.h>
|
| 8 |
+
#include <ATen/core/Generator.h>
|
| 9 |
+
#include <ATen/core/LegacyTypeDispatch.h>
|
| 10 |
+
#include <ATen/detail/AcceleratorHooksInterface.h>
|
| 11 |
+
#include <ATen/detail/CUDAHooksInterface.h>
|
| 12 |
+
#include <ATen/detail/HIPHooksInterface.h>
|
| 13 |
+
#include <ATen/detail/IPUHooksInterface.h>
|
| 14 |
+
#include <ATen/detail/MPSHooksInterface.h>
|
| 15 |
+
#include <ATen/detail/MTIAHooksInterface.h>
|
| 16 |
+
#include <ATen/detail/ORTHooksInterface.h>
|
| 17 |
+
#include <ATen/detail/PrivateUse1HooksInterface.h>
|
| 18 |
+
#include <ATen/detail/XPUHooksInterface.h>
|
| 19 |
+
#include <c10/core/QEngine.h>
|
| 20 |
+
#include <c10/core/impl/DeviceGuardImplInterface.h>
|
| 21 |
+
#include <c10/util/CallOnce.h>
|
| 22 |
+
#include <c10/util/Exception.h>
|
| 23 |
+
#include <c10/util/env.h>
|
| 24 |
+
#include <c10/util/irange.h>
|
| 25 |
+
|
| 26 |
+
#include <cstdint>
|
| 27 |
+
#include <mutex>
|
| 28 |
+
|
| 29 |
+
namespace at {
|
| 30 |
+
|
| 31 |
+
class Tensor;
|
| 32 |
+
|
| 33 |
+
enum class TORCH_API Float32MatmulPrecision { HIGHEST, HIGH, MEDIUM };
|
| 34 |
+
|
| 35 |
+
class TORCH_API Context {
|
| 36 |
+
public:
|
| 37 |
+
Context();
|
| 38 |
+
|
| 39 |
+
const Generator& defaultGenerator(Device device) {
|
| 40 |
+
c10::DeviceType device_type = device.type();
|
| 41 |
+
initCUDAIfNeeded(device_type);
|
| 42 |
+
initHIPIfNeeded(device_type);
|
| 43 |
+
if (device_type == at::kCPU) {
|
| 44 |
+
return at::detail::getDefaultCPUGenerator();
|
| 45 |
+
} else if (device_type == at::kCUDA) {
|
| 46 |
+
return at::detail::getCUDAHooks().getDefaultCUDAGenerator(device.index());
|
| 47 |
+
} else if (device_type == at::kMPS) {
|
| 48 |
+
return at::detail::getMPSHooks().getDefaultMPSGenerator();
|
| 49 |
+
} else if (device_type == at::kXPU) {
|
| 50 |
+
return at::detail::getXPUHooks().getDefaultXPUGenerator(device.index());
|
| 51 |
+
} else if (device_type == at::kIPU) {
|
| 52 |
+
return at::detail::getIPUHooks().getDefaultIPUGenerator(device.index());
|
| 53 |
+
} else if (device_type == at::kPrivateUse1) {
|
| 54 |
+
return at::GetPrivateUse1HooksInterface()->getDefaultGenerator(
|
| 55 |
+
device.index());
|
| 56 |
+
} else {
|
| 57 |
+
AT_ERROR(c10::DeviceTypeName(device_type), " device type not enabled.");
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
const AcceleratorHooksInterface& getAcceleratorHooksInterface(
|
| 61 |
+
c10::optional<c10::DeviceType> opt_device_type = c10::nullopt) {
|
| 62 |
+
c10::DeviceType device_type = opt_device_type.has_value()
|
| 63 |
+
? opt_device_type.value()
|
| 64 |
+
: at::getAccelerator(true).value();
|
| 65 |
+
if (device_type == at::kCUDA) {
|
| 66 |
+
return at::detail::getCUDAHooks();
|
| 67 |
+
} else if (device_type == at::kMPS) {
|
| 68 |
+
return at::detail::getMPSHooks();
|
| 69 |
+
} else if (device_type == at::kPrivateUse1) {
|
| 70 |
+
return at::detail::getPrivateUse1Hooks();
|
| 71 |
+
} else {
|
| 72 |
+
AT_ERROR(
|
| 73 |
+
c10::DeviceTypeName(device_type), " device type not an accelerator.");
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
Device getDeviceFromPtr(void* data, c10::DeviceType device_type) {
|
| 77 |
+
initCUDAIfNeeded(device_type);
|
| 78 |
+
initHIPIfNeeded(device_type);
|
| 79 |
+
initXPUIfNeeded(device_type);
|
| 80 |
+
if (device_type == at::kCPU) {
|
| 81 |
+
return c10::DeviceType::CPU;
|
| 82 |
+
} else if (device_type == at::kCUDA) {
|
| 83 |
+
return at::detail::getCUDAHooks().getDeviceFromPtr(data);
|
| 84 |
+
} else if (device_type == at::kXPU) {
|
| 85 |
+
return at::detail::getXPUHooks().getDeviceFromPtr(data);
|
| 86 |
+
} else if (device_type == at::kPrivateUse1) {
|
| 87 |
+
return at::GetPrivateUse1HooksInterface()->getDeviceFromPtr(data);
|
| 88 |
+
} else {
|
| 89 |
+
AT_ERROR(c10::DeviceTypeName(device_type), " device type not enabled.");
|
| 90 |
+
}
|
| 91 |
+
}
|
| 92 |
+
static bool isPinnedPtr(const void* data) {
|
| 93 |
+
return detail::getCUDAHooks().isPinnedPtr(data);
|
| 94 |
+
}
|
| 95 |
+
static bool hasOpenMP();
|
| 96 |
+
static bool hasMKL();
|
| 97 |
+
static bool hasLAPACK();
|
| 98 |
+
static bool hasMKLDNN();
|
| 99 |
+
static bool hasMAGMA() {
|
| 100 |
+
return detail::getCUDAHooks().hasMAGMA();
|
| 101 |
+
}
|
| 102 |
+
static bool hasCUDA() {
|
| 103 |
+
return detail::getCUDAHooks().hasCUDA();
|
| 104 |
+
}
|
| 105 |
+
static bool hasMTIA() {
|
| 106 |
+
return detail::getMTIAHooks().hasMTIA();
|
| 107 |
+
}
|
| 108 |
+
static bool hasCUDART() {
|
| 109 |
+
return detail::getCUDAHooks().hasCUDART();
|
| 110 |
+
}
|
| 111 |
+
static long versionCUDART() {
|
| 112 |
+
return detail::getCUDAHooks().versionCUDART();
|
| 113 |
+
}
|
| 114 |
+
static bool hasCuDNN() {
|
| 115 |
+
return detail::getCUDAHooks().hasCuDNN();
|
| 116 |
+
}
|
| 117 |
+
static long versionCuDNN() {
|
| 118 |
+
return detail::getCUDAHooks().versionCuDNN();
|
| 119 |
+
}
|
| 120 |
+
static bool hasCuSOLVER() {
|
| 121 |
+
return detail::getCUDAHooks().hasCuSOLVER();
|
| 122 |
+
}
|
| 123 |
+
static bool hasHIP() {
|
| 124 |
+
return detail::getHIPHooks().hasHIP();
|
| 125 |
+
}
|
| 126 |
+
static bool hasMPS() {
|
| 127 |
+
return detail::getMPSHooks().hasMPS();
|
| 128 |
+
}
|
| 129 |
+
static bool hasIPU() {
|
| 130 |
+
return c10::impl::hasDeviceGuardImpl(c10::DeviceType::IPU);
|
| 131 |
+
}
|
| 132 |
+
static bool hasXLA() {
|
| 133 |
+
return c10::impl::hasDeviceGuardImpl(c10::DeviceType::XLA);
|
| 134 |
+
}
|
| 135 |
+
static bool hasXPU() {
|
| 136 |
+
return detail::getXPUHooks().hasXPU();
|
| 137 |
+
}
|
| 138 |
+
static bool hasLazy() {
|
| 139 |
+
return c10::impl::hasDeviceGuardImpl(c10::DeviceType::Lazy);
|
| 140 |
+
}
|
| 141 |
+
static bool hasORT() {
|
| 142 |
+
return c10::impl::hasDeviceGuardImpl(c10::DeviceType::ORT);
|
| 143 |
+
}
|
| 144 |
+
// defined in header so that getNonVariableType has ability to inline
|
| 145 |
+
// call_once check. getNonVariableType is called fairly frequently
|
| 146 |
+
void lazyInitCUDA() {
|
| 147 |
+
c10::call_once(thc_init, [&] { detail::getCUDAHooks().initCUDA(); });
|
| 148 |
+
}
|
| 149 |
+
void lazyInitHIP() {
|
| 150 |
+
c10::call_once(thh_init, [&] { detail::getHIPHooks().initHIP(); });
|
| 151 |
+
}
|
| 152 |
+
void lazyInitXPU() {
|
| 153 |
+
c10::call_once(thx_init, [&] { detail::getXPUHooks().initXPU(); });
|
| 154 |
+
}
|
| 155 |
+
void lazyInitPrivateUse1() {
|
| 156 |
+
c10::call_once(thp_init, [&] {
|
| 157 |
+
if (isPrivateUse1HooksRegistered()) {
|
| 158 |
+
at::GetPrivateUse1HooksInterface()->initPrivateUse1();
|
| 159 |
+
}
|
| 160 |
+
});
|
| 161 |
+
}
|
| 162 |
+
static const at::cuda::NVRTC& getNVRTC() {
|
| 163 |
+
return detail::getCUDAHooks().nvrtc();
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
static bool setFlushDenormal(bool on);
|
| 167 |
+
|
| 168 |
+
// NB: This method is *purely* whether or not a user requested
|
| 169 |
+
// that CuDNN was enabled, it doesn't actually say anything about
|
| 170 |
+
// whether or not CuDNN is actually usable. Use cudnn_is_acceptable
|
| 171 |
+
// to test this instead
|
| 172 |
+
bool userEnabledCuDNN() const;
|
| 173 |
+
void setUserEnabledCuDNN(bool e);
|
| 174 |
+
bool userEnabledMkldnn() const;
|
| 175 |
+
void setUserEnabledMkldnn(bool e);
|
| 176 |
+
bool benchmarkCuDNN() const;
|
| 177 |
+
void setBenchmarkCuDNN(bool);
|
| 178 |
+
int benchmarkLimitCuDNN() const;
|
| 179 |
+
void setBenchmarkLimitCuDNN(int);
|
| 180 |
+
bool deterministicCuDNN() const;
|
| 181 |
+
void setDeterministicCuDNN(bool);
|
| 182 |
+
bool userEnabledNNPACK() const;
|
| 183 |
+
void setUserEnabledNNPACK(bool e);
|
| 184 |
+
|
| 185 |
+
// Note [Disabling Fused SDP Kernels]
|
| 186 |
+
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 187 |
+
// Flash and Memory Efficient SDP kernels are enabled by default.
|
| 188 |
+
// However, they can be disabled by setting
|
| 189 |
+
// at::globalContext().setUserEnabledFlashSDP(false) flag.
|
| 190 |
+
// This is useful for debugging purposes. For example, if you want to
|
| 191 |
+
// compare the performance of the flash SDP kernels with the unfused
|
| 192 |
+
// kernel, you can disable the flash SDP kernels. By disabling
|
| 193 |
+
// the math SDP kernel, you can force your code to use flash kernels.
|
| 194 |
+
// The math SDP kernel can be disabled by setting
|
| 195 |
+
// at::globalContext().setUserEnabledMathSDP(false) flag.
|
| 196 |
+
void setSDPUseFlash(bool);
|
| 197 |
+
bool userEnabledFlashSDP() const;
|
| 198 |
+
|
| 199 |
+
void setSDPUseMemEfficient(bool);
|
| 200 |
+
bool userEnabledMemEfficientSDP() const;
|
| 201 |
+
|
| 202 |
+
void setSDPUseMath(bool);
|
| 203 |
+
bool userEnabledMathSDP() const;
|
| 204 |
+
|
| 205 |
+
void setSDPUseCuDNN(bool);
|
| 206 |
+
bool userEnabledCuDNNSDP() const;
|
| 207 |
+
|
| 208 |
+
at::LinalgBackend linalgPreferredBackend() const;
|
| 209 |
+
void setLinalgPreferredBackend(at::LinalgBackend);
|
| 210 |
+
|
| 211 |
+
// Note [Enabling Deterministic Operations]
|
| 212 |
+
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 213 |
+
// Operations in PyTorch that normally act nondeterministically, but have an
|
| 214 |
+
// alternate deterministic implementation, should satisfy the following
|
| 215 |
+
// requirements:
|
| 216 |
+
//
|
| 217 |
+
// * Include this comment: "See Note [Enabling Deterministic Operations]"
|
| 218 |
+
//
|
| 219 |
+
// * Check the value of `at::globalContext().deterministicAlgorithms()` to
|
| 220 |
+
// toggle
|
| 221 |
+
// between nondeterministic and deterministic implementations.
|
| 222 |
+
//
|
| 223 |
+
// * Have an entry in the list of PyTorch operations that toggle between
|
| 224 |
+
// nondeterministic
|
| 225 |
+
// and deterministic implementations, in the docstring of
|
| 226 |
+
// `use_deterministic_algorithms()` in torch/__init__.py
|
| 227 |
+
//
|
| 228 |
+
// `example_func()` below shows an example of toggling between
|
| 229 |
+
// nondeterministic and deterministic implementations:
|
| 230 |
+
//
|
| 231 |
+
// void example_func() {
|
| 232 |
+
// // See Note [Enabling Deterministic Operations]
|
| 233 |
+
// if (at::globalContext().deterministicAlgorithms()) {
|
| 234 |
+
// example_func_deterministic();
|
| 235 |
+
// } else {
|
| 236 |
+
// example_func_nondeterministic();
|
| 237 |
+
// }
|
| 238 |
+
// }
|
| 239 |
+
|
| 240 |
+
bool deterministicAlgorithms() const;
|
| 241 |
+
bool deterministicAlgorithmsWarnOnly() const;
|
| 242 |
+
void setDeterministicAlgorithms(bool, bool);
|
| 243 |
+
bool deterministicFillUninitializedMemory() const;
|
| 244 |
+
void setDeterministicFillUninitializedMemory(bool);
|
| 245 |
+
|
| 246 |
+
// Note [Writing Nondeterministic Operations]
|
| 247 |
+
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 248 |
+
// Operations in PyTorch that act nondeterministically and do not have an
|
| 249 |
+
// alternate deterministic implementation should satisfy the following
|
| 250 |
+
// requirements:
|
| 251 |
+
//
|
| 252 |
+
// * Include this comment: "See Note [Writing Nondeterministic Operations]"
|
| 253 |
+
//
|
| 254 |
+
// * Include a comment explaining why the operation is nondeterministic.
|
| 255 |
+
//
|
| 256 |
+
// * Throw an error when `Context::deterministicAlgorithms()` is true. Most
|
| 257 |
+
// of the time, this should be accomplished by calling
|
| 258 |
+
// `at::globalContext().alertNotDeterminstic()`. However, if the
|
| 259 |
+
// nondeterministic behavior is caused by the CuBLAS workspace
|
| 260 |
+
// configuration in CUDA >= 10.2,
|
| 261 |
+
// `at::globalContext().alertCuBLASConfigNotDeterministic()` should be
|
| 262 |
+
// called instead (in this case, a comment explaining why the operation is
|
| 263 |
+
// nondeterministic is not necessary). See below for details on these
|
| 264 |
+
// methods.
|
| 265 |
+
//
|
| 266 |
+
// * Have an entry in the list of nondeterministic PyTorch operations in the
|
| 267 |
+
// docstring of `use_deterministic_algorithms()` in torch/__init__.py
|
| 268 |
+
//
|
| 269 |
+
// * Have a test function in `test/test_torch.py` whose name begins with
|
| 270 |
+
// `test_nondeterministic_alert_`. Alternatively, if CuBLAS workspace
|
| 271 |
+
// configuration is the reason for nondeterminism, the operation should be
|
| 272 |
+
// included in the `test_cublas_config_nondeterministic_alert` test. Any new
|
| 273 |
+
// tests should ideally follow a pattern similar to the existing ones.
|
| 274 |
+
//
|
| 275 |
+
// `example_func()` below shows an example of the comments and error-throwing
|
| 276 |
+
// code for a nondeterministic operation:
|
| 277 |
+
//
|
| 278 |
+
// void example_func() {
|
| 279 |
+
// // See Note [Writing Nondeterministic Operations]
|
| 280 |
+
// // Nondeterministic because <reason>
|
| 281 |
+
// at::globalContext().alertNondeterministic("example_func");
|
| 282 |
+
// ...
|
| 283 |
+
// }
|
| 284 |
+
|
| 285 |
+
// Throws an error if `Context::deterministicAlgorithms()` is true
|
| 286 |
+
static void alertNotDeterministic(c10::string_view const& caller);
|
| 287 |
+
|
| 288 |
+
// Throws an error if `Context::deterministicAlgorithms()` is true, CUDA
|
| 289 |
+
// >= 10.2, and CUBLAS_WORKSPACE_CONFIG is not set to either ":16:8" or
|
| 290 |
+
// ":4096:8". For more details:
|
| 291 |
+
// https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility
|
| 292 |
+
void alertCuBLASConfigNotDeterministic() const;
|
| 293 |
+
|
| 294 |
+
void setFloat32MatmulPrecision(const std::string& s);
|
| 295 |
+
bool allowTF32CuDNN() const;
|
| 296 |
+
void setAllowTF32CuDNN(bool);
|
| 297 |
+
bool allowTF32CuBLAS() const;
|
| 298 |
+
void setAllowTF32CuBLAS(bool);
|
| 299 |
+
Float32MatmulPrecision float32MatmulPrecision() const;
|
| 300 |
+
void setFloat32MatmulPrecision(Float32MatmulPrecision p);
|
| 301 |
+
bool allowFP16ReductionCuBLAS() const;
|
| 302 |
+
void setAllowFP16ReductionCuBLAS(bool);
|
| 303 |
+
bool allowBF16ReductionCuBLAS() const;
|
| 304 |
+
void setAllowBF16ReductionCuBLAS(bool);
|
| 305 |
+
at::QEngine qEngine() const;
|
| 306 |
+
void setQEngine(at::QEngine e);
|
| 307 |
+
static const std::vector<at::QEngine>& supportedQEngines();
|
| 308 |
+
static bool isXNNPACKAvailable();
|
| 309 |
+
void setCheckSparseTensorInvariants(bool e);
|
| 310 |
+
bool checkSparseTensorInvariants() const;
|
| 311 |
+
// This method is used to release the original weight after pre-packing.
|
| 312 |
+
// It should be called once before loading/running the model.
|
| 313 |
+
// NB: By default it is set to true for mobile builds.
|
| 314 |
+
void setReleaseWeightsWhenPrepacking(bool e);
|
| 315 |
+
bool releaseWeightsWhenPrepacking() const;
|
| 316 |
+
|
| 317 |
+
void setDisplayVmapFallbackWarnings(bool enabled);
|
| 318 |
+
bool areVmapFallbackWarningsEnabled() const;
|
| 319 |
+
|
| 320 |
+
void setDefaultMobileCPUAllocator();
|
| 321 |
+
void unsetDefaultMobileCPUAllocator();
|
| 322 |
+
bool allowFP16ReductionCPU() const;
|
| 323 |
+
void setAllowFP16ReductionCPU(bool);
|
| 324 |
+
|
| 325 |
+
private:
|
| 326 |
+
void initCUDAIfNeeded(c10::DeviceType p) {
|
| 327 |
+
if (p == c10::DeviceType::CUDA) {
|
| 328 |
+
lazyInitCUDA();
|
| 329 |
+
}
|
| 330 |
+
}
|
| 331 |
+
void initHIPIfNeeded(c10::DeviceType p) {
|
| 332 |
+
if (p == c10::DeviceType::HIP) {
|
| 333 |
+
lazyInitHIP();
|
| 334 |
+
}
|
| 335 |
+
}
|
| 336 |
+
void initXPUIfNeeded(c10::DeviceType p) {
|
| 337 |
+
if (p == c10::DeviceType::XPU) {
|
| 338 |
+
lazyInitXPU();
|
| 339 |
+
}
|
| 340 |
+
}
|
| 341 |
+
static bool checkCuBLASConfigDeterministic();
|
| 342 |
+
c10::once_flag thc_init;
|
| 343 |
+
c10::once_flag thh_init;
|
| 344 |
+
c10::once_flag thx_init;
|
| 345 |
+
c10::once_flag thp_init;
|
| 346 |
+
bool enabled_cudnn = true;
|
| 347 |
+
bool deterministic_cudnn = false;
|
| 348 |
+
bool _deterministic_algorithms = false;
|
| 349 |
+
bool _deterministic_algorithms_warn_only = false;
|
| 350 |
+
bool _deterministic_fill_uninitialized_memory = true;
|
| 351 |
+
bool enabled_flashSDP = true;
|
| 352 |
+
bool enabled_mem_efficientSDP = true;
|
| 353 |
+
bool enabled_mathSDP = true;
|
| 354 |
+
bool enabled_cudnnSDP = false;
|
| 355 |
+
#ifdef USE_ROCM
|
| 356 |
+
bool benchmark_cudnn = true;
|
| 357 |
+
#else
|
| 358 |
+
bool benchmark_cudnn = false;
|
| 359 |
+
#endif
|
| 360 |
+
Float32MatmulPrecision float32_matmul_precision =
|
| 361 |
+
c10::utils::check_env("TORCH_ALLOW_TF32_CUBLAS_OVERRIDE") == true
|
| 362 |
+
? at::Float32MatmulPrecision::HIGH
|
| 363 |
+
: at::Float32MatmulPrecision::HIGHEST;
|
| 364 |
+
int benchmark_limit_cudnn = 10;
|
| 365 |
+
bool allow_tf32_cudnn = true;
|
| 366 |
+
bool allow_fp16_reduction_cublas = true;
|
| 367 |
+
bool allow_bf16_reduction_cublas = true;
|
| 368 |
+
bool enabled_mkldnn = true;
|
| 369 |
+
bool enabled_nnpack = true;
|
| 370 |
+
at::LinalgBackend linalg_preferred_backend =
|
| 371 |
+
c10::utils::check_env("TORCH_LINALG_PREFER_CUSOLVER") == true
|
| 372 |
+
? at::LinalgBackend::Cusolver
|
| 373 |
+
: at::LinalgBackend::Default;
|
| 374 |
+
#ifdef C10_MOBILE
|
| 375 |
+
bool release_original_weights = true;
|
| 376 |
+
#else
|
| 377 |
+
bool release_original_weights = false;
|
| 378 |
+
#endif
|
| 379 |
+
bool display_vmap_fallback_warnings_ = false;
|
| 380 |
+
c10::optional<at::QEngine> quantized_engine = c10::nullopt;
|
| 381 |
+
bool enable_sparse_tensor_invariant_checks = false;
|
| 382 |
+
bool allow_fp16_reduction_cpu = false;
|
| 383 |
+
|
| 384 |
+
Allocator* prev_allocator_ptr_{nullptr};
|
| 385 |
+
};
|
| 386 |
+
|
| 387 |
+
TORCH_API Context& globalContext();
|
| 388 |
+
|
| 389 |
+
static inline void init() {
|
| 390 |
+
globalContext();
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
TORCH_API Allocator* getCPUAllocator();
|
| 394 |
+
|
| 395 |
+
static inline DeprecatedTypeProperties& getDeprecatedTypeProperties(
|
| 396 |
+
Backend p,
|
| 397 |
+
ScalarType s) {
|
| 398 |
+
return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties(
|
| 399 |
+
p, s);
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
static inline DeprecatedTypeProperties& CPU(ScalarType s) {
|
| 403 |
+
return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties(
|
| 404 |
+
Backend::CPU, s);
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
static inline DeprecatedTypeProperties& CUDA(ScalarType s) {
|
| 408 |
+
return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties(
|
| 409 |
+
Backend::CUDA, s);
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
static inline DeprecatedTypeProperties& HIP(ScalarType s) {
|
| 413 |
+
return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties(
|
| 414 |
+
Backend::HIP, s);
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
static inline DeprecatedTypeProperties& MPS(ScalarType s) {
|
| 418 |
+
return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties(
|
| 419 |
+
Backend::MPS, s);
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
static inline bool hasCUDA() {
|
| 423 |
+
return globalContext().hasCUDA();
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
static inline bool hasMTIA() {
|
| 427 |
+
return globalContext().hasMTIA();
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
static inline bool hasHIP() {
|
| 431 |
+
return globalContext().hasHIP();
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
static inline bool hasIPU() {
|
| 435 |
+
return globalContext().hasIPU();
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
static inline bool hasXLA() {
|
| 439 |
+
return globalContext().hasXLA();
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
static inline bool hasMPS() {
|
| 443 |
+
return globalContext().hasMPS();
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
static inline bool hasORT() {
|
| 447 |
+
return globalContext().hasORT();
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
static inline bool hasXPU() {
|
| 451 |
+
return globalContext().hasXPU();
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
// Despite its name, this function returns the number of *CUDA* GPUs.
|
| 455 |
+
static inline size_t getNumGPUs() {
|
| 456 |
+
// WARNING: DO NOT ADD LOGIC TO HANDLE OTHER DEVICE TYPES TO THIS
|
| 457 |
+
// FUNCTION. If you are interested in interrogating the number of
|
| 458 |
+
// devices for a specific device type, add that function to the
|
| 459 |
+
// relevant library (e.g., similar to at::cuda::device_count())
|
| 460 |
+
if (hasCUDA() && hasHIP()) {
|
| 461 |
+
throw std::runtime_error(
|
| 462 |
+
"Enabling both CUDA and HIP in ATen is not supported, as HIP masquerades "
|
| 463 |
+
"to be CUDA (e.g., when you say CUDA, on a HIP build of ATen, this actually "
|
| 464 |
+
"means HIP. Rebuild PyTorch with one or the other disabled.");
|
| 465 |
+
} else if (hasCUDA()) {
|
| 466 |
+
return detail::getCUDAHooks().getNumGPUs();
|
| 467 |
+
} else if (hasHIP()) {
|
| 468 |
+
return detail::getHIPHooks().getNumGPUs();
|
| 469 |
+
} else {
|
| 470 |
+
return 0;
|
| 471 |
+
}
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
static inline bool hasOpenMP() {
|
| 475 |
+
return globalContext().hasOpenMP();
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
static inline bool hasMKL() {
|
| 479 |
+
return globalContext().hasMKL();
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
static inline bool hasLAPACK() {
|
| 483 |
+
return globalContext().hasLAPACK();
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
static inline bool hasMAGMA() {
|
| 487 |
+
return globalContext().hasMAGMA();
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
static inline bool hasMKLDNN() {
|
| 491 |
+
return globalContext().hasMKLDNN();
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
static inline void manual_seed(uint64_t seed) {
|
| 495 |
+
auto gen = globalContext().defaultGenerator(c10::DeviceType::CPU);
|
| 496 |
+
{
|
| 497 |
+
// See Note [Acquire lock when using random generators]
|
| 498 |
+
std::lock_guard<std::mutex> lock(gen.mutex());
|
| 499 |
+
gen.set_current_seed(seed);
|
| 500 |
+
}
|
| 501 |
+
// NB: Sometimes we build with CUDA, but we don't have any GPUs
|
| 502 |
+
// available. In that case, we must not seed CUDA; it will fail!
|
| 503 |
+
const auto cuda_num_gpus = detail::getCUDAHooks().getNumGPUs();
|
| 504 |
+
if (hasCUDA() && cuda_num_gpus > 0) {
|
| 505 |
+
for (const auto i : c10::irange(cuda_num_gpus)) {
|
| 506 |
+
auto cuda_gen = globalContext().defaultGenerator(
|
| 507 |
+
Device(at::kCUDA, static_cast<c10::DeviceIndex>(i)));
|
| 508 |
+
{
|
| 509 |
+
// See Note [Acquire lock when using random generators]
|
| 510 |
+
std::lock_guard<std::mutex> lock(cuda_gen.mutex());
|
| 511 |
+
cuda_gen.set_current_seed(seed);
|
| 512 |
+
}
|
| 513 |
+
}
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
const auto xpu_num_gpus = detail::getXPUHooks().getNumGPUs();
|
| 517 |
+
if (hasXPU() && xpu_num_gpus) {
|
| 518 |
+
for (const auto i : c10::irange(xpu_num_gpus)) {
|
| 519 |
+
auto xpu_gen = globalContext().defaultGenerator(
|
| 520 |
+
Device(at::kXPU, static_cast<c10::DeviceIndex>(i)));
|
| 521 |
+
{
|
| 522 |
+
// See Note [Acquire lock when using random generators]
|
| 523 |
+
std::lock_guard<std::mutex> lock(xpu_gen.mutex());
|
| 524 |
+
xpu_gen.set_current_seed(seed);
|
| 525 |
+
}
|
| 526 |
+
}
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
if (hasMPS()) {
|
| 530 |
+
auto mps_gen = globalContext().defaultGenerator(c10::DeviceType::MPS);
|
| 531 |
+
// See Note [Acquire lock when using random generators]
|
| 532 |
+
std::lock_guard<std::mutex> lock(mps_gen.mutex());
|
| 533 |
+
mps_gen.set_current_seed(seed);
|
| 534 |
+
}
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
// When the global flag `allow_tf32` is set to true, cuBLAS handles are
|
| 538 |
+
// automatically configured to use math mode CUBLAS_TF32_TENSOR_OP_MATH.
|
| 539 |
+
// For some operators, such as addmv, TF32 offers no performance improvement
|
| 540 |
+
// but causes precision loss. To help this case, this class implements
|
| 541 |
+
// a RAII guard that can be used to quickly disable TF32 within its scope.
|
| 542 |
+
//
|
| 543 |
+
// Usage:
|
| 544 |
+
// NoTF32Guard disable_tf32;
|
| 545 |
+
struct TORCH_API NoTF32Guard {
|
| 546 |
+
NoTF32Guard();
|
| 547 |
+
~NoTF32Guard();
|
| 548 |
+
static bool should_disable_tf32();
|
| 549 |
+
|
| 550 |
+
private:
|
| 551 |
+
bool changed = false;
|
| 552 |
+
};
|
| 553 |
+
|
| 554 |
+
struct TORCH_API ROCmBackwardPassGuard {
|
| 555 |
+
ROCmBackwardPassGuard();
|
| 556 |
+
~ROCmBackwardPassGuard();
|
| 557 |
+
static bool is_backward_pass();
|
| 558 |
+
};
|
| 559 |
+
|
| 560 |
+
} // namespace at
|
shared/package-files/ab/ab52198b90afc94a7f3cdcdb438fd72eba00576e15128bc1133d93929c1427d7/blob
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
// or more contributor license agreements. See the NOTICE file
|
| 3 |
+
// distributed with this work for additional information
|
| 4 |
+
// regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
// to you under the Apache License, Version 2.0 (the
|
| 6 |
+
// "License"); you may not use this file except in compliance
|
| 7 |
+
// with the License. You may obtain a copy of the License at
|
| 8 |
+
//
|
| 9 |
+
// http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
//
|
| 11 |
+
// Unless required by applicable law or agreed to in writing,
|
| 12 |
+
// software distributed under the License is distributed on an
|
| 13 |
+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
// KIND, either express or implied. See the License for the
|
| 15 |
+
// specific language governing permissions and limitations
|
| 16 |
+
// under the License.
|
| 17 |
+
|
| 18 |
+
#pragma once
|
| 19 |
+
|
| 20 |
+
#include <time.h>
|
| 21 |
+
|
| 22 |
+
#include "arrow/util/visibility.h"
|
| 23 |
+
|
| 24 |
+
#ifdef __cplusplus
|
| 25 |
+
extern "C" {
|
| 26 |
+
#endif
|
| 27 |
+
|
| 28 |
+
// A less featureful implementation of strptime() for platforms lacking
|
| 29 |
+
// a standard implementation (e.g. Windows).
|
| 30 |
+
ARROW_EXPORT char* arrow_strptime(const char* __restrict, const char* __restrict,
|
| 31 |
+
struct tm* __restrict);
|
| 32 |
+
|
| 33 |
+
#ifdef __cplusplus
|
| 34 |
+
} // extern "C"
|
| 35 |
+
#endif
|
shared/package-files/ab/ab52403333cd797da62e4ffe8f9e67511f994cda73f3597610189343d8b76ed9/blob
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace compositeexplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor & as_strided_scatter_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, c10::optional<int64_t> storage_offset=c10::nullopt);
|
| 21 |
+
TORCH_API at::Tensor & as_strided_scatter_outf(const at::Tensor & self, const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, c10::optional<int64_t> storage_offset, at::Tensor & out);
|
| 22 |
+
TORCH_API at::Tensor & as_strided_scatter_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional<c10::SymInt> storage_offset=c10::nullopt);
|
| 23 |
+
TORCH_API at::Tensor & as_strided_scatter_symint_outf(const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional<c10::SymInt> storage_offset, at::Tensor & out);
|
| 24 |
+
|
| 25 |
+
} // namespace compositeexplicitautograd
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Multi-layer Perceptron"""
|
| 2 |
+
|
| 3 |
+
# Authors: The scikit-learn developers
|
| 4 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 5 |
+
|
| 6 |
+
import warnings
|
| 7 |
+
from abc import ABC, abstractmethod
|
| 8 |
+
from itertools import chain, pairwise
|
| 9 |
+
from numbers import Integral, Real
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import scipy.optimize
|
| 13 |
+
|
| 14 |
+
from ..base import (
|
| 15 |
+
BaseEstimator,
|
| 16 |
+
ClassifierMixin,
|
| 17 |
+
RegressorMixin,
|
| 18 |
+
_fit_context,
|
| 19 |
+
is_classifier,
|
| 20 |
+
)
|
| 21 |
+
from ..exceptions import ConvergenceWarning
|
| 22 |
+
from ..metrics import accuracy_score, r2_score
|
| 23 |
+
from ..model_selection import train_test_split
|
| 24 |
+
from ..preprocessing import LabelBinarizer
|
| 25 |
+
from ..utils import (
|
| 26 |
+
_safe_indexing,
|
| 27 |
+
check_random_state,
|
| 28 |
+
column_or_1d,
|
| 29 |
+
gen_batches,
|
| 30 |
+
shuffle,
|
| 31 |
+
)
|
| 32 |
+
from ..utils._param_validation import Interval, Options, StrOptions
|
| 33 |
+
from ..utils.extmath import safe_sparse_dot
|
| 34 |
+
from ..utils.fixes import _get_additional_lbfgs_options_dict
|
| 35 |
+
from ..utils.metaestimators import available_if
|
| 36 |
+
from ..utils.multiclass import (
|
| 37 |
+
_check_partial_fit_first_call,
|
| 38 |
+
type_of_target,
|
| 39 |
+
unique_labels,
|
| 40 |
+
)
|
| 41 |
+
from ..utils.optimize import _check_optimize_result
|
| 42 |
+
from ..utils.validation import _check_sample_weight, check_is_fitted, validate_data
|
| 43 |
+
from ._base import ACTIVATIONS, DERIVATIVES, LOSS_FUNCTIONS
|
| 44 |
+
from ._stochastic_optimizers import AdamOptimizer, SGDOptimizer
|
| 45 |
+
|
| 46 |
+
_STOCHASTIC_SOLVERS = ["sgd", "adam"]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _pack(coefs_, intercepts_):
|
| 50 |
+
"""Pack the parameters into a single vector."""
|
| 51 |
+
return np.hstack([l.ravel() for l in coefs_ + intercepts_])
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class BaseMultilayerPerceptron(BaseEstimator, ABC):
|
| 55 |
+
"""Base class for MLP classification and regression.
|
| 56 |
+
|
| 57 |
+
Warning: This class should not be used directly.
|
| 58 |
+
Use derived classes instead.
|
| 59 |
+
|
| 60 |
+
.. versionadded:: 0.18
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
_parameter_constraints: dict = {
|
| 64 |
+
"hidden_layer_sizes": [
|
| 65 |
+
"array-like",
|
| 66 |
+
Interval(Integral, 1, None, closed="left"),
|
| 67 |
+
],
|
| 68 |
+
"activation": [StrOptions({"identity", "logistic", "tanh", "relu"})],
|
| 69 |
+
"solver": [StrOptions({"lbfgs", "sgd", "adam"})],
|
| 70 |
+
"alpha": [Interval(Real, 0, None, closed="left")],
|
| 71 |
+
"batch_size": [
|
| 72 |
+
StrOptions({"auto"}),
|
| 73 |
+
Interval(Integral, 1, None, closed="left"),
|
| 74 |
+
],
|
| 75 |
+
"learning_rate": [StrOptions({"constant", "invscaling", "adaptive"})],
|
| 76 |
+
"learning_rate_init": [Interval(Real, 0, None, closed="neither")],
|
| 77 |
+
"power_t": [Interval(Real, 0, None, closed="left")],
|
| 78 |
+
"max_iter": [Interval(Integral, 1, None, closed="left")],
|
| 79 |
+
"shuffle": ["boolean"],
|
| 80 |
+
"random_state": ["random_state"],
|
| 81 |
+
"tol": [Interval(Real, 0, None, closed="left")],
|
| 82 |
+
"verbose": ["verbose"],
|
| 83 |
+
"warm_start": ["boolean"],
|
| 84 |
+
"momentum": [Interval(Real, 0, 1, closed="both")],
|
| 85 |
+
"nesterovs_momentum": ["boolean"],
|
| 86 |
+
"early_stopping": ["boolean"],
|
| 87 |
+
"validation_fraction": [Interval(Real, 0, 1, closed="left")],
|
| 88 |
+
"beta_1": [Interval(Real, 0, 1, closed="left")],
|
| 89 |
+
"beta_2": [Interval(Real, 0, 1, closed="left")],
|
| 90 |
+
"epsilon": [Interval(Real, 0, None, closed="neither")],
|
| 91 |
+
"n_iter_no_change": [
|
| 92 |
+
Interval(Integral, 1, None, closed="left"),
|
| 93 |
+
Options(Real, {np.inf}),
|
| 94 |
+
],
|
| 95 |
+
"max_fun": [Interval(Integral, 1, None, closed="left")],
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
@abstractmethod
|
| 99 |
+
def __init__(
|
| 100 |
+
self,
|
| 101 |
+
hidden_layer_sizes,
|
| 102 |
+
activation,
|
| 103 |
+
solver,
|
| 104 |
+
alpha,
|
| 105 |
+
batch_size,
|
| 106 |
+
learning_rate,
|
| 107 |
+
learning_rate_init,
|
| 108 |
+
power_t,
|
| 109 |
+
max_iter,
|
| 110 |
+
loss,
|
| 111 |
+
shuffle,
|
| 112 |
+
random_state,
|
| 113 |
+
tol,
|
| 114 |
+
verbose,
|
| 115 |
+
warm_start,
|
| 116 |
+
momentum,
|
| 117 |
+
nesterovs_momentum,
|
| 118 |
+
early_stopping,
|
| 119 |
+
validation_fraction,
|
| 120 |
+
beta_1,
|
| 121 |
+
beta_2,
|
| 122 |
+
epsilon,
|
| 123 |
+
n_iter_no_change,
|
| 124 |
+
max_fun,
|
| 125 |
+
):
|
| 126 |
+
self.activation = activation
|
| 127 |
+
self.solver = solver
|
| 128 |
+
self.alpha = alpha
|
| 129 |
+
self.batch_size = batch_size
|
| 130 |
+
self.learning_rate = learning_rate
|
| 131 |
+
self.learning_rate_init = learning_rate_init
|
| 132 |
+
self.power_t = power_t
|
| 133 |
+
self.max_iter = max_iter
|
| 134 |
+
self.loss = loss
|
| 135 |
+
self.hidden_layer_sizes = hidden_layer_sizes
|
| 136 |
+
self.shuffle = shuffle
|
| 137 |
+
self.random_state = random_state
|
| 138 |
+
self.tol = tol
|
| 139 |
+
self.verbose = verbose
|
| 140 |
+
self.warm_start = warm_start
|
| 141 |
+
self.momentum = momentum
|
| 142 |
+
self.nesterovs_momentum = nesterovs_momentum
|
| 143 |
+
self.early_stopping = early_stopping
|
| 144 |
+
self.validation_fraction = validation_fraction
|
| 145 |
+
self.beta_1 = beta_1
|
| 146 |
+
self.beta_2 = beta_2
|
| 147 |
+
self.epsilon = epsilon
|
| 148 |
+
self.n_iter_no_change = n_iter_no_change
|
| 149 |
+
self.max_fun = max_fun
|
| 150 |
+
|
| 151 |
+
def _unpack(self, packed_parameters):
|
| 152 |
+
"""Extract the coefficients and intercepts from packed_parameters."""
|
| 153 |
+
for i in range(self.n_layers_ - 1):
|
| 154 |
+
start, end, shape = self._coef_indptr[i]
|
| 155 |
+
self.coefs_[i] = np.reshape(packed_parameters[start:end], shape)
|
| 156 |
+
|
| 157 |
+
start, end = self._intercept_indptr[i]
|
| 158 |
+
self.intercepts_[i] = packed_parameters[start:end]
|
| 159 |
+
|
| 160 |
+
def _forward_pass(self, activations):
|
| 161 |
+
"""Perform a forward pass on the network by computing the values
|
| 162 |
+
of the neurons in the hidden layers and the output layer.
|
| 163 |
+
|
| 164 |
+
Parameters
|
| 165 |
+
----------
|
| 166 |
+
activations : list, length = n_layers - 1
|
| 167 |
+
The ith element of the list holds the values of the ith layer.
|
| 168 |
+
"""
|
| 169 |
+
hidden_activation = ACTIVATIONS[self.activation]
|
| 170 |
+
# Iterate over the hidden layers
|
| 171 |
+
for i in range(self.n_layers_ - 1):
|
| 172 |
+
activations[i + 1] = safe_sparse_dot(activations[i], self.coefs_[i])
|
| 173 |
+
activations[i + 1] += self.intercepts_[i]
|
| 174 |
+
|
| 175 |
+
# For the hidden layers
|
| 176 |
+
if (i + 1) != (self.n_layers_ - 1):
|
| 177 |
+
hidden_activation(activations[i + 1])
|
| 178 |
+
|
| 179 |
+
# For the last layer
|
| 180 |
+
output_activation = ACTIVATIONS[self.out_activation_]
|
| 181 |
+
output_activation(activations[i + 1])
|
| 182 |
+
|
| 183 |
+
return activations
|
| 184 |
+
|
| 185 |
+
def _forward_pass_fast(self, X, check_input=True):
|
| 186 |
+
"""Predict using the trained model
|
| 187 |
+
|
| 188 |
+
This is the same as _forward_pass but does not record the activations
|
| 189 |
+
of all layers and only returns the last layer's activation.
|
| 190 |
+
|
| 191 |
+
Parameters
|
| 192 |
+
----------
|
| 193 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
| 194 |
+
The input data.
|
| 195 |
+
|
| 196 |
+
check_input : bool, default=True
|
| 197 |
+
Perform input data validation or not.
|
| 198 |
+
|
| 199 |
+
Returns
|
| 200 |
+
-------
|
| 201 |
+
y_pred : ndarray of shape (n_samples,) or (n_samples, n_outputs)
|
| 202 |
+
The decision function of the samples for each class in the model.
|
| 203 |
+
"""
|
| 204 |
+
if check_input:
|
| 205 |
+
X = validate_data(self, X, accept_sparse=["csr", "csc"], reset=False)
|
| 206 |
+
|
| 207 |
+
# Initialize first layer
|
| 208 |
+
activation = X
|
| 209 |
+
|
| 210 |
+
# Forward propagate
|
| 211 |
+
hidden_activation = ACTIVATIONS[self.activation]
|
| 212 |
+
for i in range(self.n_layers_ - 1):
|
| 213 |
+
activation = safe_sparse_dot(activation, self.coefs_[i])
|
| 214 |
+
activation += self.intercepts_[i]
|
| 215 |
+
if i != self.n_layers_ - 2:
|
| 216 |
+
hidden_activation(activation)
|
| 217 |
+
output_activation = ACTIVATIONS[self.out_activation_]
|
| 218 |
+
output_activation(activation)
|
| 219 |
+
|
| 220 |
+
return activation
|
| 221 |
+
|
| 222 |
+
def _compute_loss_grad(
|
| 223 |
+
self, layer, sw_sum, activations, deltas, coef_grads, intercept_grads
|
| 224 |
+
):
|
| 225 |
+
"""Compute the gradient of loss with respect to coefs and intercept for
|
| 226 |
+
specified layer.
|
| 227 |
+
|
| 228 |
+
This function does backpropagation for the specified one layer.
|
| 229 |
+
"""
|
| 230 |
+
coef_grads[layer] = safe_sparse_dot(activations[layer].T, deltas[layer])
|
| 231 |
+
coef_grads[layer] += self.alpha * self.coefs_[layer]
|
| 232 |
+
coef_grads[layer] /= sw_sum
|
| 233 |
+
|
| 234 |
+
intercept_grads[layer] = np.sum(deltas[layer], axis=0) / sw_sum
|
| 235 |
+
|
| 236 |
+
def _loss_grad_lbfgs(
|
| 237 |
+
self,
|
| 238 |
+
packed_coef_inter,
|
| 239 |
+
X,
|
| 240 |
+
y,
|
| 241 |
+
sample_weight,
|
| 242 |
+
activations,
|
| 243 |
+
deltas,
|
| 244 |
+
coef_grads,
|
| 245 |
+
intercept_grads,
|
| 246 |
+
):
|
| 247 |
+
"""Compute the MLP loss function and its corresponding derivatives
|
| 248 |
+
with respect to the different parameters given in the initialization.
|
| 249 |
+
|
| 250 |
+
Returned gradients are packed in a single vector so it can be used
|
| 251 |
+
in lbfgs
|
| 252 |
+
|
| 253 |
+
Parameters
|
| 254 |
+
----------
|
| 255 |
+
packed_coef_inter : ndarray
|
| 256 |
+
A vector comprising the flattened coefficients and intercepts.
|
| 257 |
+
|
| 258 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
| 259 |
+
The input data.
|
| 260 |
+
|
| 261 |
+
y : ndarray of shape (n_samples,)
|
| 262 |
+
The target values.
|
| 263 |
+
|
| 264 |
+
sample_weight : array-like of shape (n_samples,), default=None
|
| 265 |
+
Sample weights.
|
| 266 |
+
|
| 267 |
+
activations : list, length = n_layers - 1
|
| 268 |
+
The ith element of the list holds the values of the ith layer.
|
| 269 |
+
|
| 270 |
+
deltas : list, length = n_layers - 1
|
| 271 |
+
The ith element of the list holds the difference between the
|
| 272 |
+
activations of the i + 1 layer and the backpropagated error.
|
| 273 |
+
More specifically, deltas are gradients of loss with respect to z
|
| 274 |
+
in each layer, where z = wx + b is the value of a particular layer
|
| 275 |
+
before passing through the activation function
|
| 276 |
+
|
| 277 |
+
coef_grads : list, length = n_layers - 1
|
| 278 |
+
The ith element contains the amount of change used to update the
|
| 279 |
+
coefficient parameters of the ith layer in an iteration.
|
| 280 |
+
|
| 281 |
+
intercept_grads : list, length = n_layers - 1
|
| 282 |
+
The ith element contains the amount of change used to update the
|
| 283 |
+
intercept parameters of the ith layer in an iteration.
|
| 284 |
+
|
| 285 |
+
Returns
|
| 286 |
+
-------
|
| 287 |
+
loss : float
|
| 288 |
+
grad : array-like, shape (number of nodes of all layers,)
|
| 289 |
+
"""
|
| 290 |
+
self._unpack(packed_coef_inter)
|
| 291 |
+
loss, coef_grads, intercept_grads = self._backprop(
|
| 292 |
+
X, y, sample_weight, activations, deltas, coef_grads, intercept_grads
|
| 293 |
+
)
|
| 294 |
+
grad = _pack(coef_grads, intercept_grads)
|
| 295 |
+
return loss, grad
|
| 296 |
+
|
| 297 |
+
def _backprop(
|
| 298 |
+
self, X, y, sample_weight, activations, deltas, coef_grads, intercept_grads
|
| 299 |
+
):
|
| 300 |
+
"""Compute the MLP loss function and its corresponding derivatives
|
| 301 |
+
with respect to each parameter: weights and bias vectors.
|
| 302 |
+
|
| 303 |
+
Parameters
|
| 304 |
+
----------
|
| 305 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
| 306 |
+
The input data.
|
| 307 |
+
|
| 308 |
+
y : ndarray of shape (n_samples,)
|
| 309 |
+
The target values.
|
| 310 |
+
|
| 311 |
+
sample_weight : array-like of shape (n_samples,), default=None
|
| 312 |
+
Sample weights.
|
| 313 |
+
|
| 314 |
+
activations : list, length = n_layers - 1
|
| 315 |
+
The ith element of the list holds the values of the ith layer.
|
| 316 |
+
|
| 317 |
+
deltas : list, length = n_layers - 1
|
| 318 |
+
The ith element of the list holds the difference between the
|
| 319 |
+
activations of the i + 1 layer and the backpropagated error.
|
| 320 |
+
More specifically, deltas are gradients of loss with respect to z
|
| 321 |
+
in each layer, where z = wx + b is the value of a particular layer
|
| 322 |
+
before passing through the activation function
|
| 323 |
+
|
| 324 |
+
coef_grads : list, length = n_layers - 1
|
| 325 |
+
The ith element contains the amount of change used to update the
|
| 326 |
+
coefficient parameters of the ith layer in an iteration.
|
| 327 |
+
|
| 328 |
+
intercept_grads : list, length = n_layers - 1
|
| 329 |
+
The ith element contains the amount of change used to update the
|
| 330 |
+
intercept parameters of the ith layer in an iteration.
|
| 331 |
+
|
| 332 |
+
Returns
|
| 333 |
+
-------
|
| 334 |
+
loss : float
|
| 335 |
+
coef_grads : list, length = n_layers - 1
|
| 336 |
+
intercept_grads : list, length = n_layers - 1
|
| 337 |
+
"""
|
| 338 |
+
n_samples = X.shape[0]
|
| 339 |
+
|
| 340 |
+
# Forward propagate
|
| 341 |
+
activations = self._forward_pass(activations)
|
| 342 |
+
|
| 343 |
+
# Get loss
|
| 344 |
+
loss_func_name = self.loss
|
| 345 |
+
if loss_func_name == "log_loss" and self.out_activation_ == "logistic":
|
| 346 |
+
loss_func_name = "binary_log_loss"
|
| 347 |
+
loss = LOSS_FUNCTIONS[loss_func_name](y, activations[-1], sample_weight)
|
| 348 |
+
# Add L2 regularization term to loss
|
| 349 |
+
values = 0
|
| 350 |
+
for s in self.coefs_:
|
| 351 |
+
s = s.ravel()
|
| 352 |
+
values += np.dot(s, s)
|
| 353 |
+
if sample_weight is None:
|
| 354 |
+
sw_sum = n_samples
|
| 355 |
+
else:
|
| 356 |
+
sw_sum = sample_weight.sum()
|
| 357 |
+
loss += (0.5 * self.alpha) * values / sw_sum
|
| 358 |
+
|
| 359 |
+
# Backward propagate
|
| 360 |
+
last = self.n_layers_ - 2
|
| 361 |
+
|
| 362 |
+
# The calculation of delta[last] is as follows:
|
| 363 |
+
# delta[last] = d/dz loss(y, act(z)) = act(z) - y
|
| 364 |
+
# with z=x@w + b being the output of the last layer before passing through the
|
| 365 |
+
# output activation, act(z) = activations[-1].
|
| 366 |
+
# The simple formula for delta[last] here works with following (canonical
|
| 367 |
+
# loss-link) combinations of output activation and loss function:
|
| 368 |
+
# sigmoid and binary cross entropy, softmax and categorical cross
|
| 369 |
+
# entropy, and identity with squared loss
|
| 370 |
+
deltas[last] = activations[-1] - y
|
| 371 |
+
if sample_weight is not None:
|
| 372 |
+
deltas[last] *= sample_weight.reshape(-1, 1)
|
| 373 |
+
|
| 374 |
+
# Compute gradient for the last layer
|
| 375 |
+
self._compute_loss_grad(
|
| 376 |
+
last, sw_sum, activations, deltas, coef_grads, intercept_grads
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
inplace_derivative = DERIVATIVES[self.activation]
|
| 380 |
+
# Iterate over the hidden layers
|
| 381 |
+
for i in range(last, 0, -1):
|
| 382 |
+
deltas[i - 1] = safe_sparse_dot(deltas[i], self.coefs_[i].T)
|
| 383 |
+
inplace_derivative(activations[i], deltas[i - 1])
|
| 384 |
+
|
| 385 |
+
self._compute_loss_grad(
|
| 386 |
+
i - 1, sw_sum, activations, deltas, coef_grads, intercept_grads
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
return loss, coef_grads, intercept_grads
|
| 390 |
+
|
| 391 |
+
def _initialize(self, y, layer_units, dtype):
|
| 392 |
+
# set all attributes, allocate weights etc. for first call
|
| 393 |
+
# Initialize parameters
|
| 394 |
+
self.n_iter_ = 0
|
| 395 |
+
self.t_ = 0
|
| 396 |
+
self.n_outputs_ = y.shape[1]
|
| 397 |
+
|
| 398 |
+
# Compute the number of layers
|
| 399 |
+
self.n_layers_ = len(layer_units)
|
| 400 |
+
|
| 401 |
+
# Output for regression
|
| 402 |
+
if not is_classifier(self):
|
| 403 |
+
if self.loss == "poisson":
|
| 404 |
+
self.out_activation_ = "exp"
|
| 405 |
+
else:
|
| 406 |
+
# loss = "squared_error"
|
| 407 |
+
self.out_activation_ = "identity"
|
| 408 |
+
# Output for multi class
|
| 409 |
+
elif self._label_binarizer.y_type_ == "multiclass":
|
| 410 |
+
self.out_activation_ = "softmax"
|
| 411 |
+
# Output for binary class and multi-label
|
| 412 |
+
else:
|
| 413 |
+
self.out_activation_ = "logistic"
|
| 414 |
+
|
| 415 |
+
# Initialize coefficient and intercept layers
|
| 416 |
+
self.coefs_ = []
|
| 417 |
+
self.intercepts_ = []
|
| 418 |
+
|
| 419 |
+
for i in range(self.n_layers_ - 1):
|
| 420 |
+
coef_init, intercept_init = self._init_coef(
|
| 421 |
+
layer_units[i], layer_units[i + 1], dtype
|
| 422 |
+
)
|
| 423 |
+
self.coefs_.append(coef_init)
|
| 424 |
+
self.intercepts_.append(intercept_init)
|
| 425 |
+
|
| 426 |
+
self._best_coefs = [c.copy() for c in self.coefs_]
|
| 427 |
+
self._best_intercepts = [i.copy() for i in self.intercepts_]
|
| 428 |
+
|
| 429 |
+
if self.solver in _STOCHASTIC_SOLVERS:
|
| 430 |
+
self.loss_curve_ = []
|
| 431 |
+
self._no_improvement_count = 0
|
| 432 |
+
if self.early_stopping:
|
| 433 |
+
self.validation_scores_ = []
|
| 434 |
+
self.best_validation_score_ = -np.inf
|
| 435 |
+
self.best_loss_ = None
|
| 436 |
+
else:
|
| 437 |
+
self.best_loss_ = np.inf
|
| 438 |
+
self.validation_scores_ = None
|
| 439 |
+
self.best_validation_score_ = None
|
| 440 |
+
|
| 441 |
+
def _init_coef(self, fan_in, fan_out, dtype):
|
| 442 |
+
# Use the initialization method recommended by
|
| 443 |
+
# Glorot et al.
|
| 444 |
+
factor = 6.0
|
| 445 |
+
if self.activation == "logistic":
|
| 446 |
+
factor = 2.0
|
| 447 |
+
init_bound = np.sqrt(factor / (fan_in + fan_out))
|
| 448 |
+
|
| 449 |
+
# Generate weights and bias:
|
| 450 |
+
coef_init = self._random_state.uniform(
|
| 451 |
+
-init_bound, init_bound, (fan_in, fan_out)
|
| 452 |
+
)
|
| 453 |
+
intercept_init = self._random_state.uniform(-init_bound, init_bound, fan_out)
|
| 454 |
+
coef_init = coef_init.astype(dtype, copy=False)
|
| 455 |
+
intercept_init = intercept_init.astype(dtype, copy=False)
|
| 456 |
+
return coef_init, intercept_init
|
| 457 |
+
|
| 458 |
+
def _fit(self, X, y, sample_weight=None, incremental=False):
|
| 459 |
+
# Make sure self.hidden_layer_sizes is a list
|
| 460 |
+
hidden_layer_sizes = self.hidden_layer_sizes
|
| 461 |
+
if not hasattr(hidden_layer_sizes, "__iter__"):
|
| 462 |
+
hidden_layer_sizes = [hidden_layer_sizes]
|
| 463 |
+
hidden_layer_sizes = list(hidden_layer_sizes)
|
| 464 |
+
|
| 465 |
+
if np.any(np.array(hidden_layer_sizes) <= 0):
|
| 466 |
+
raise ValueError(
|
| 467 |
+
"hidden_layer_sizes must be > 0, got %s." % hidden_layer_sizes
|
| 468 |
+
)
|
| 469 |
+
first_pass = not hasattr(self, "coefs_") or (
|
| 470 |
+
not self.warm_start and not incremental
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
X, y = self._validate_input(X, y, incremental, reset=first_pass)
|
| 474 |
+
n_samples, n_features = X.shape
|
| 475 |
+
if sample_weight is not None:
|
| 476 |
+
sample_weight = _check_sample_weight(sample_weight, X)
|
| 477 |
+
|
| 478 |
+
# Ensure y is 2D
|
| 479 |
+
if y.ndim == 1:
|
| 480 |
+
y = y.reshape((-1, 1))
|
| 481 |
+
|
| 482 |
+
self.n_outputs_ = y.shape[1]
|
| 483 |
+
|
| 484 |
+
layer_units = [n_features] + hidden_layer_sizes + [self.n_outputs_]
|
| 485 |
+
|
| 486 |
+
# check random state
|
| 487 |
+
self._random_state = check_random_state(self.random_state)
|
| 488 |
+
|
| 489 |
+
if first_pass:
|
| 490 |
+
# First time training the model
|
| 491 |
+
self._initialize(y, layer_units, X.dtype)
|
| 492 |
+
|
| 493 |
+
# Initialize lists
|
| 494 |
+
activations = [X] + [None] * (len(layer_units) - 1)
|
| 495 |
+
deltas = [None] * (len(activations) - 1)
|
| 496 |
+
|
| 497 |
+
coef_grads = [
|
| 498 |
+
np.empty((n_fan_in_, n_fan_out_), dtype=X.dtype)
|
| 499 |
+
for n_fan_in_, n_fan_out_ in pairwise(layer_units)
|
| 500 |
+
]
|
| 501 |
+
|
| 502 |
+
intercept_grads = [
|
| 503 |
+
np.empty(n_fan_out_, dtype=X.dtype) for n_fan_out_ in layer_units[1:]
|
| 504 |
+
]
|
| 505 |
+
|
| 506 |
+
# Run the Stochastic optimization solver
|
| 507 |
+
if self.solver in _STOCHASTIC_SOLVERS:
|
| 508 |
+
self._fit_stochastic(
|
| 509 |
+
X,
|
| 510 |
+
y,
|
| 511 |
+
sample_weight,
|
| 512 |
+
activations,
|
| 513 |
+
deltas,
|
| 514 |
+
coef_grads,
|
| 515 |
+
intercept_grads,
|
| 516 |
+
layer_units,
|
| 517 |
+
incremental,
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
# Run the LBFGS solver
|
| 521 |
+
elif self.solver == "lbfgs":
|
| 522 |
+
self._fit_lbfgs(
|
| 523 |
+
X,
|
| 524 |
+
y,
|
| 525 |
+
sample_weight,
|
| 526 |
+
activations,
|
| 527 |
+
deltas,
|
| 528 |
+
coef_grads,
|
| 529 |
+
intercept_grads,
|
| 530 |
+
layer_units,
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
# validate parameter weights
|
| 534 |
+
weights = chain(self.coefs_, self.intercepts_)
|
| 535 |
+
if not all(np.isfinite(w).all() for w in weights):
|
| 536 |
+
raise ValueError(
|
| 537 |
+
"Solver produced non-finite parameter weights. The input data may"
|
| 538 |
+
" contain large values and need to be preprocessed."
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
return self
|
| 542 |
+
|
| 543 |
+
def _fit_lbfgs(
|
| 544 |
+
self,
|
| 545 |
+
X,
|
| 546 |
+
y,
|
| 547 |
+
sample_weight,
|
| 548 |
+
activations,
|
| 549 |
+
deltas,
|
| 550 |
+
coef_grads,
|
| 551 |
+
intercept_grads,
|
| 552 |
+
layer_units,
|
| 553 |
+
):
|
| 554 |
+
# Store meta information for the parameters
|
| 555 |
+
self._coef_indptr = []
|
| 556 |
+
self._intercept_indptr = []
|
| 557 |
+
start = 0
|
| 558 |
+
|
| 559 |
+
# Save sizes and indices of coefficients for faster unpacking
|
| 560 |
+
for i in range(self.n_layers_ - 1):
|
| 561 |
+
n_fan_in, n_fan_out = layer_units[i], layer_units[i + 1]
|
| 562 |
+
|
| 563 |
+
end = start + (n_fan_in * n_fan_out)
|
| 564 |
+
self._coef_indptr.append((start, end, (n_fan_in, n_fan_out)))
|
| 565 |
+
start = end
|
| 566 |
+
|
| 567 |
+
# Save sizes and indices of intercepts for faster unpacking
|
| 568 |
+
for i in range(self.n_layers_ - 1):
|
| 569 |
+
end = start + layer_units[i + 1]
|
| 570 |
+
self._intercept_indptr.append((start, end))
|
| 571 |
+
start = end
|
| 572 |
+
|
| 573 |
+
# Run LBFGS
|
| 574 |
+
packed_coef_inter = _pack(self.coefs_, self.intercepts_)
|
| 575 |
+
|
| 576 |
+
if self.verbose is True or self.verbose >= 1:
|
| 577 |
+
iprint = 1
|
| 578 |
+
else:
|
| 579 |
+
iprint = -1
|
| 580 |
+
|
| 581 |
+
opt_res = scipy.optimize.minimize(
|
| 582 |
+
self._loss_grad_lbfgs,
|
| 583 |
+
packed_coef_inter,
|
| 584 |
+
method="L-BFGS-B",
|
| 585 |
+
jac=True,
|
| 586 |
+
options={
|
| 587 |
+
"maxfun": self.max_fun,
|
| 588 |
+
"maxiter": self.max_iter,
|
| 589 |
+
"gtol": self.tol,
|
| 590 |
+
**_get_additional_lbfgs_options_dict("iprint", iprint),
|
| 591 |
+
},
|
| 592 |
+
args=(
|
| 593 |
+
X,
|
| 594 |
+
y,
|
| 595 |
+
sample_weight,
|
| 596 |
+
activations,
|
| 597 |
+
deltas,
|
| 598 |
+
coef_grads,
|
| 599 |
+
intercept_grads,
|
| 600 |
+
),
|
| 601 |
+
)
|
| 602 |
+
self.n_iter_ = _check_optimize_result("lbfgs", opt_res, self.max_iter)
|
| 603 |
+
self.loss_ = opt_res.fun
|
| 604 |
+
self._unpack(opt_res.x)
|
| 605 |
+
|
| 606 |
+
def _fit_stochastic(
|
| 607 |
+
self,
|
| 608 |
+
X,
|
| 609 |
+
y,
|
| 610 |
+
sample_weight,
|
| 611 |
+
activations,
|
| 612 |
+
deltas,
|
| 613 |
+
coef_grads,
|
| 614 |
+
intercept_grads,
|
| 615 |
+
layer_units,
|
| 616 |
+
incremental,
|
| 617 |
+
):
|
| 618 |
+
params = self.coefs_ + self.intercepts_
|
| 619 |
+
if not incremental or not hasattr(self, "_optimizer"):
|
| 620 |
+
if self.solver == "sgd":
|
| 621 |
+
self._optimizer = SGDOptimizer(
|
| 622 |
+
params,
|
| 623 |
+
self.learning_rate_init,
|
| 624 |
+
self.learning_rate,
|
| 625 |
+
self.momentum,
|
| 626 |
+
self.nesterovs_momentum,
|
| 627 |
+
self.power_t,
|
| 628 |
+
)
|
| 629 |
+
elif self.solver == "adam":
|
| 630 |
+
self._optimizer = AdamOptimizer(
|
| 631 |
+
params,
|
| 632 |
+
self.learning_rate_init,
|
| 633 |
+
self.beta_1,
|
| 634 |
+
self.beta_2,
|
| 635 |
+
self.epsilon,
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
# early_stopping in partial_fit doesn't make sense
|
| 639 |
+
if self.early_stopping and incremental:
|
| 640 |
+
raise ValueError("partial_fit does not support early_stopping=True")
|
| 641 |
+
early_stopping = self.early_stopping
|
| 642 |
+
if early_stopping:
|
| 643 |
+
# don't stratify in multilabel classification
|
| 644 |
+
should_stratify = is_classifier(self) and self.n_outputs_ == 1
|
| 645 |
+
stratify = y if should_stratify else None
|
| 646 |
+
if sample_weight is None:
|
| 647 |
+
X_train, X_val, y_train, y_val = train_test_split(
|
| 648 |
+
X,
|
| 649 |
+
y,
|
| 650 |
+
random_state=self._random_state,
|
| 651 |
+
test_size=self.validation_fraction,
|
| 652 |
+
stratify=stratify,
|
| 653 |
+
)
|
| 654 |
+
sample_weight_train = sample_weight_val = None
|
| 655 |
+
else:
|
| 656 |
+
# TODO: incorporate sample_weight in sampling here.
|
| 657 |
+
(
|
| 658 |
+
X_train,
|
| 659 |
+
X_val,
|
| 660 |
+
y_train,
|
| 661 |
+
y_val,
|
| 662 |
+
sample_weight_train,
|
| 663 |
+
sample_weight_val,
|
| 664 |
+
) = train_test_split(
|
| 665 |
+
X,
|
| 666 |
+
y,
|
| 667 |
+
sample_weight,
|
| 668 |
+
random_state=self._random_state,
|
| 669 |
+
test_size=self.validation_fraction,
|
| 670 |
+
stratify=stratify,
|
| 671 |
+
)
|
| 672 |
+
if X_val.shape[0] < 2:
|
| 673 |
+
raise ValueError(
|
| 674 |
+
"The validation set is too small. Increase 'validation_fraction' "
|
| 675 |
+
"or the size of your dataset."
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
if is_classifier(self):
|
| 679 |
+
y_val = self._label_binarizer.inverse_transform(y_val)
|
| 680 |
+
else:
|
| 681 |
+
X_train, y_train, sample_weight_train = X, y, sample_weight
|
| 682 |
+
X_val = y_val = sample_weight_val = None
|
| 683 |
+
|
| 684 |
+
n_samples = X_train.shape[0]
|
| 685 |
+
sample_idx = np.arange(n_samples, dtype=int)
|
| 686 |
+
|
| 687 |
+
if self.batch_size == "auto":
|
| 688 |
+
batch_size = min(200, n_samples)
|
| 689 |
+
else:
|
| 690 |
+
if self.batch_size > n_samples:
|
| 691 |
+
warnings.warn(
|
| 692 |
+
"Got `batch_size` less than 1 or larger than "
|
| 693 |
+
"sample size. It is going to be clipped"
|
| 694 |
+
)
|
| 695 |
+
batch_size = np.clip(self.batch_size, 1, n_samples)
|
| 696 |
+
|
| 697 |
+
try:
|
| 698 |
+
self.n_iter_ = 0
|
| 699 |
+
for it in range(self.max_iter):
|
| 700 |
+
if self.shuffle:
|
| 701 |
+
# Only shuffle the sample indices instead of X and y to
|
| 702 |
+
# reduce the memory footprint. These indices will be used
|
| 703 |
+
# to slice the X and y.
|
| 704 |
+
sample_idx = shuffle(sample_idx, random_state=self._random_state)
|
| 705 |
+
|
| 706 |
+
accumulated_loss = 0.0
|
| 707 |
+
for batch_slice in gen_batches(n_samples, batch_size):
|
| 708 |
+
if self.shuffle:
|
| 709 |
+
batch_idx = sample_idx[batch_slice]
|
| 710 |
+
X_batch = _safe_indexing(X_train, batch_idx)
|
| 711 |
+
else:
|
| 712 |
+
batch_idx = batch_slice
|
| 713 |
+
X_batch = X_train[batch_idx]
|
| 714 |
+
y_batch = y_train[batch_idx]
|
| 715 |
+
if sample_weight is None:
|
| 716 |
+
sample_weight_batch = None
|
| 717 |
+
else:
|
| 718 |
+
sample_weight_batch = sample_weight_train[batch_idx]
|
| 719 |
+
|
| 720 |
+
activations[0] = X_batch
|
| 721 |
+
batch_loss, coef_grads, intercept_grads = self._backprop(
|
| 722 |
+
X_batch,
|
| 723 |
+
y_batch,
|
| 724 |
+
sample_weight_batch,
|
| 725 |
+
activations,
|
| 726 |
+
deltas,
|
| 727 |
+
coef_grads,
|
| 728 |
+
intercept_grads,
|
| 729 |
+
)
|
| 730 |
+
accumulated_loss += batch_loss * (
|
| 731 |
+
batch_slice.stop - batch_slice.start
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
# update weights
|
| 735 |
+
grads = coef_grads + intercept_grads
|
| 736 |
+
self._optimizer.update_params(params, grads)
|
| 737 |
+
|
| 738 |
+
self.n_iter_ += 1
|
| 739 |
+
self.loss_ = accumulated_loss / X_train.shape[0]
|
| 740 |
+
|
| 741 |
+
self.t_ += n_samples
|
| 742 |
+
self.loss_curve_.append(self.loss_)
|
| 743 |
+
if self.verbose:
|
| 744 |
+
print("Iteration %d, loss = %.8f" % (self.n_iter_, self.loss_))
|
| 745 |
+
|
| 746 |
+
# update no_improvement_count based on training loss or
|
| 747 |
+
# validation score according to early_stopping
|
| 748 |
+
self._update_no_improvement_count(
|
| 749 |
+
early_stopping, X_val, y_val, sample_weight_val
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
+
# for learning rate that needs to be updated at iteration end
|
| 753 |
+
self._optimizer.iteration_ends(self.t_)
|
| 754 |
+
|
| 755 |
+
if self._no_improvement_count > self.n_iter_no_change:
|
| 756 |
+
# not better than last `n_iter_no_change` iterations by tol
|
| 757 |
+
# stop or decrease learning rate
|
| 758 |
+
if early_stopping:
|
| 759 |
+
msg = (
|
| 760 |
+
"Validation score did not improve more than "
|
| 761 |
+
"tol=%f for %d consecutive epochs."
|
| 762 |
+
% (self.tol, self.n_iter_no_change)
|
| 763 |
+
)
|
| 764 |
+
else:
|
| 765 |
+
msg = (
|
| 766 |
+
"Training loss did not improve more than tol=%f"
|
| 767 |
+
" for %d consecutive epochs."
|
| 768 |
+
% (self.tol, self.n_iter_no_change)
|
| 769 |
+
)
|
| 770 |
+
|
| 771 |
+
is_stopping = self._optimizer.trigger_stopping(msg, self.verbose)
|
| 772 |
+
if is_stopping:
|
| 773 |
+
break
|
| 774 |
+
else:
|
| 775 |
+
self._no_improvement_count = 0
|
| 776 |
+
|
| 777 |
+
if incremental:
|
| 778 |
+
break
|
| 779 |
+
|
| 780 |
+
if self.n_iter_ == self.max_iter:
|
| 781 |
+
warnings.warn(
|
| 782 |
+
"Stochastic Optimizer: Maximum iterations (%d) "
|
| 783 |
+
"reached and the optimization hasn't converged yet."
|
| 784 |
+
% self.max_iter,
|
| 785 |
+
ConvergenceWarning,
|
| 786 |
+
)
|
| 787 |
+
except KeyboardInterrupt:
|
| 788 |
+
warnings.warn("Training interrupted by user.")
|
| 789 |
+
|
| 790 |
+
if early_stopping:
|
| 791 |
+
# restore best weights
|
| 792 |
+
self.coefs_ = self._best_coefs
|
| 793 |
+
self.intercepts_ = self._best_intercepts
|
| 794 |
+
|
| 795 |
+
def _update_no_improvement_count(self, early_stopping, X, y, sample_weight):
|
| 796 |
+
if early_stopping:
|
| 797 |
+
# compute validation score (can be NaN), use that for stopping
|
| 798 |
+
val_score = self._score(X, y, sample_weight=sample_weight)
|
| 799 |
+
|
| 800 |
+
self.validation_scores_.append(val_score)
|
| 801 |
+
|
| 802 |
+
if self.verbose:
|
| 803 |
+
print("Validation score: %f" % self.validation_scores_[-1])
|
| 804 |
+
# update best parameters
|
| 805 |
+
# use validation_scores_, not loss_curve_
|
| 806 |
+
# let's hope no-one overloads .score with mse
|
| 807 |
+
last_valid_score = self.validation_scores_[-1]
|
| 808 |
+
|
| 809 |
+
if last_valid_score < (self.best_validation_score_ + self.tol):
|
| 810 |
+
self._no_improvement_count += 1
|
| 811 |
+
else:
|
| 812 |
+
self._no_improvement_count = 0
|
| 813 |
+
|
| 814 |
+
if last_valid_score > self.best_validation_score_:
|
| 815 |
+
self.best_validation_score_ = last_valid_score
|
| 816 |
+
self._best_coefs = [c.copy() for c in self.coefs_]
|
| 817 |
+
self._best_intercepts = [i.copy() for i in self.intercepts_]
|
| 818 |
+
else:
|
| 819 |
+
if self.loss_curve_[-1] > self.best_loss_ - self.tol:
|
| 820 |
+
self._no_improvement_count += 1
|
| 821 |
+
else:
|
| 822 |
+
self._no_improvement_count = 0
|
| 823 |
+
if self.loss_curve_[-1] < self.best_loss_:
|
| 824 |
+
self.best_loss_ = self.loss_curve_[-1]
|
| 825 |
+
|
| 826 |
+
@_fit_context(prefer_skip_nested_validation=True)
|
| 827 |
+
def fit(self, X, y, sample_weight=None):
|
| 828 |
+
"""Fit the model to data matrix X and target(s) y.
|
| 829 |
+
|
| 830 |
+
Parameters
|
| 831 |
+
----------
|
| 832 |
+
X : ndarray or sparse matrix of shape (n_samples, n_features)
|
| 833 |
+
The input data.
|
| 834 |
+
|
| 835 |
+
y : ndarray of shape (n_samples,) or (n_samples, n_outputs)
|
| 836 |
+
The target values (class labels in classification, real numbers in
|
| 837 |
+
regression).
|
| 838 |
+
|
| 839 |
+
sample_weight : array-like of shape (n_samples,), default=None
|
| 840 |
+
Sample weights.
|
| 841 |
+
|
| 842 |
+
.. versionadded:: 1.7
|
| 843 |
+
|
| 844 |
+
Returns
|
| 845 |
+
-------
|
| 846 |
+
self : object
|
| 847 |
+
Returns a trained MLP model.
|
| 848 |
+
"""
|
| 849 |
+
return self._fit(X, y, sample_weight=sample_weight, incremental=False)
|
| 850 |
+
|
| 851 |
+
def _check_solver(self):
|
| 852 |
+
if self.solver not in _STOCHASTIC_SOLVERS:
|
| 853 |
+
raise AttributeError(
|
| 854 |
+
"partial_fit is only available for stochastic"
|
| 855 |
+
" optimizers. %s is not stochastic." % self.solver
|
| 856 |
+
)
|
| 857 |
+
return True
|
| 858 |
+
|
| 859 |
+
def _score_with_function(self, X, y, sample_weight, score_function):
|
| 860 |
+
"""Private score method without input validation."""
|
| 861 |
+
# Input validation would remove feature names, so we disable it
|
| 862 |
+
y_pred = self._predict(X, check_input=False)
|
| 863 |
+
|
| 864 |
+
if np.isnan(y_pred).any() or np.isinf(y_pred).any():
|
| 865 |
+
return np.nan
|
| 866 |
+
|
| 867 |
+
return score_function(y, y_pred, sample_weight=sample_weight)
|
| 868 |
+
|
| 869 |
+
def __sklearn_tags__(self):
|
| 870 |
+
tags = super().__sklearn_tags__()
|
| 871 |
+
tags.input_tags.sparse = True
|
| 872 |
+
return tags
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
class MLPClassifier(ClassifierMixin, BaseMultilayerPerceptron):
|
| 876 |
+
"""Multi-layer Perceptron classifier.
|
| 877 |
+
|
| 878 |
+
This model optimizes the log-loss function using LBFGS or stochastic
|
| 879 |
+
gradient descent.
|
| 880 |
+
|
| 881 |
+
.. versionadded:: 0.18
|
| 882 |
+
|
| 883 |
+
Parameters
|
| 884 |
+
----------
|
| 885 |
+
hidden_layer_sizes : array-like of shape(n_layers - 2,), default=(100,)
|
| 886 |
+
The ith element represents the number of neurons in the ith
|
| 887 |
+
hidden layer.
|
| 888 |
+
|
| 889 |
+
activation : {'identity', 'logistic', 'tanh', 'relu'}, default='relu'
|
| 890 |
+
Activation function for the hidden layer.
|
| 891 |
+
|
| 892 |
+
- 'identity', no-op activation, useful to implement linear bottleneck,
|
| 893 |
+
returns f(x) = x
|
| 894 |
+
|
| 895 |
+
- 'logistic', the logistic sigmoid function,
|
| 896 |
+
returns f(x) = 1 / (1 + exp(-x)).
|
| 897 |
+
|
| 898 |
+
- 'tanh', the hyperbolic tan function,
|
| 899 |
+
returns f(x) = tanh(x).
|
| 900 |
+
|
| 901 |
+
- 'relu', the rectified linear unit function,
|
| 902 |
+
returns f(x) = max(0, x)
|
| 903 |
+
|
| 904 |
+
solver : {'lbfgs', 'sgd', 'adam'}, default='adam'
|
| 905 |
+
The solver for weight optimization.
|
| 906 |
+
|
| 907 |
+
- 'lbfgs' is an optimizer in the family of quasi-Newton methods.
|
| 908 |
+
|
| 909 |
+
- 'sgd' refers to stochastic gradient descent.
|
| 910 |
+
|
| 911 |
+
- 'adam' refers to a stochastic gradient-based optimizer proposed
|
| 912 |
+
by Kingma, Diederik, and Jimmy Ba
|
| 913 |
+
|
| 914 |
+
For a comparison between Adam optimizer and SGD, see
|
| 915 |
+
:ref:`sphx_glr_auto_examples_neural_networks_plot_mlp_training_curves.py`.
|
| 916 |
+
|
| 917 |
+
Note: The default solver 'adam' works pretty well on relatively
|
| 918 |
+
large datasets (with thousands of training samples or more) in terms of
|
| 919 |
+
both training time and validation score.
|
| 920 |
+
For small datasets, however, 'lbfgs' can converge faster and perform
|
| 921 |
+
better.
|
| 922 |
+
|
| 923 |
+
alpha : float, default=0.0001
|
| 924 |
+
Strength of the L2 regularization term. The L2 regularization term
|
| 925 |
+
is divided by the sample size when added to the loss.
|
| 926 |
+
|
| 927 |
+
For an example usage and visualization of varying regularization, see
|
| 928 |
+
:ref:`sphx_glr_auto_examples_neural_networks_plot_mlp_alpha.py`.
|
| 929 |
+
|
| 930 |
+
batch_size : int, default='auto'
|
| 931 |
+
Size of minibatches for stochastic optimizers.
|
| 932 |
+
If the solver is 'lbfgs', the classifier will not use minibatch.
|
| 933 |
+
When set to "auto", `batch_size=min(200, n_samples)`.
|
| 934 |
+
|
| 935 |
+
learning_rate : {'constant', 'invscaling', 'adaptive'}, default='constant'
|
| 936 |
+
Learning rate schedule for weight updates.
|
| 937 |
+
|
| 938 |
+
- 'constant' is a constant learning rate given by
|
| 939 |
+
'learning_rate_init'.
|
| 940 |
+
|
| 941 |
+
- 'invscaling' gradually decreases the learning rate at each
|
| 942 |
+
time step 't' using an inverse scaling exponent of 'power_t'.
|
| 943 |
+
effective_learning_rate = learning_rate_init / pow(t, power_t)
|
| 944 |
+
|
| 945 |
+
- 'adaptive' keeps the learning rate constant to
|
| 946 |
+
'learning_rate_init' as long as training loss keeps decreasing.
|
| 947 |
+
Each time two consecutive epochs fail to decrease training loss by at
|
| 948 |
+
least tol, or fail to increase validation score by at least tol if
|
| 949 |
+
'early_stopping' is on, the current learning rate is divided by 5.
|
| 950 |
+
|
| 951 |
+
Only used when ``solver='sgd'``.
|
| 952 |
+
|
| 953 |
+
learning_rate_init : float, default=0.001
|
| 954 |
+
The initial learning rate used. It controls the step-size
|
| 955 |
+
in updating the weights. Only used when solver='sgd' or 'adam'.
|
| 956 |
+
|
| 957 |
+
power_t : float, default=0.5
|
| 958 |
+
The exponent for inverse scaling learning rate.
|
| 959 |
+
It is used in updating effective learning rate when the learning_rate
|
| 960 |
+
is set to 'invscaling'. Only used when solver='sgd'.
|
| 961 |
+
|
| 962 |
+
max_iter : int, default=200
|
| 963 |
+
Maximum number of iterations. The solver iterates until convergence
|
| 964 |
+
(determined by 'tol') or this number of iterations. For stochastic
|
| 965 |
+
solvers ('sgd', 'adam'), note that this determines the number of epochs
|
| 966 |
+
(how many times each data point will be used), not the number of
|
| 967 |
+
gradient steps.
|
| 968 |
+
|
| 969 |
+
shuffle : bool, default=True
|
| 970 |
+
Whether to shuffle samples in each iteration. Only used when
|
| 971 |
+
solver='sgd' or 'adam'.
|
| 972 |
+
|
| 973 |
+
random_state : int, RandomState instance, default=None
|
| 974 |
+
Determines random number generation for weights and bias
|
| 975 |
+
initialization, train-test split if early stopping is used, and batch
|
| 976 |
+
sampling when solver='sgd' or 'adam'.
|
| 977 |
+
Pass an int for reproducible results across multiple function calls.
|
| 978 |
+
See :term:`Glossary <random_state>`.
|
| 979 |
+
|
| 980 |
+
tol : float, default=1e-4
|
| 981 |
+
Tolerance for the optimization. When the loss or score is not improving
|
| 982 |
+
by at least ``tol`` for ``n_iter_no_change`` consecutive iterations,
|
| 983 |
+
unless ``learning_rate`` is set to 'adaptive', convergence is
|
| 984 |
+
considered to be reached and training stops.
|
| 985 |
+
|
| 986 |
+
verbose : bool, default=False
|
| 987 |
+
Whether to print progress messages to stdout.
|
| 988 |
+
|
| 989 |
+
warm_start : bool, default=False
|
| 990 |
+
When set to True, reuse the solution of the previous
|
| 991 |
+
call to fit as initialization, otherwise, just erase the
|
| 992 |
+
previous solution. See :term:`the Glossary <warm_start>`.
|
| 993 |
+
|
| 994 |
+
momentum : float, default=0.9
|
| 995 |
+
Momentum for gradient descent update. Should be between 0 and 1. Only
|
| 996 |
+
used when solver='sgd'.
|
| 997 |
+
|
| 998 |
+
nesterovs_momentum : bool, default=True
|
| 999 |
+
Whether to use Nesterov's momentum. Only used when solver='sgd' and
|
| 1000 |
+
momentum > 0.
|
| 1001 |
+
|
| 1002 |
+
early_stopping : bool, default=False
|
| 1003 |
+
Whether to use early stopping to terminate training when validation
|
| 1004 |
+
score is not improving. If set to true, it will automatically set
|
| 1005 |
+
aside 10% of training data as validation and terminate training when
|
| 1006 |
+
validation score is not improving by at least ``tol`` for
|
| 1007 |
+
``n_iter_no_change`` consecutive epochs. The split is stratified,
|
| 1008 |
+
except in a multilabel setting.
|
| 1009 |
+
If early stopping is False, then the training stops when the training
|
| 1010 |
+
loss does not improve by more than tol for n_iter_no_change consecutive
|
| 1011 |
+
passes over the training set.
|
| 1012 |
+
Only effective when solver='sgd' or 'adam'.
|
| 1013 |
+
|
| 1014 |
+
validation_fraction : float, default=0.1
|
| 1015 |
+
The proportion of training data to set aside as validation set for
|
| 1016 |
+
early stopping. Must be between 0 and 1.
|
| 1017 |
+
Only used if early_stopping is True.
|
| 1018 |
+
|
| 1019 |
+
beta_1 : float, default=0.9
|
| 1020 |
+
Exponential decay rate for estimates of first moment vector in adam,
|
| 1021 |
+
should be in [0, 1). Only used when solver='adam'.
|
| 1022 |
+
|
| 1023 |
+
beta_2 : float, default=0.999
|
| 1024 |
+
Exponential decay rate for estimates of second moment vector in adam,
|
| 1025 |
+
should be in [0, 1). Only used when solver='adam'.
|
| 1026 |
+
|
| 1027 |
+
epsilon : float, default=1e-8
|
| 1028 |
+
Value for numerical stability in adam. Only used when solver='adam'.
|
| 1029 |
+
|
| 1030 |
+
n_iter_no_change : int, default=10
|
| 1031 |
+
Maximum number of epochs to not meet ``tol`` improvement.
|
| 1032 |
+
Only effective when solver='sgd' or 'adam'.
|
| 1033 |
+
|
| 1034 |
+
.. versionadded:: 0.20
|
| 1035 |
+
|
| 1036 |
+
max_fun : int, default=15000
|
| 1037 |
+
Only used when solver='lbfgs'. Maximum number of loss function calls.
|
| 1038 |
+
The solver iterates until convergence (determined by 'tol'), number
|
| 1039 |
+
of iterations reaches max_iter, or this number of loss function calls.
|
| 1040 |
+
Note that number of loss function calls will be greater than or equal
|
| 1041 |
+
to the number of iterations for the `MLPClassifier`.
|
| 1042 |
+
|
| 1043 |
+
.. versionadded:: 0.22
|
| 1044 |
+
|
| 1045 |
+
Attributes
|
| 1046 |
+
----------
|
| 1047 |
+
classes_ : ndarray or list of ndarray of shape (n_classes,)
|
| 1048 |
+
Class labels for each output.
|
| 1049 |
+
|
| 1050 |
+
loss_ : float
|
| 1051 |
+
The current loss computed with the loss function.
|
| 1052 |
+
|
| 1053 |
+
best_loss_ : float or None
|
| 1054 |
+
The minimum loss reached by the solver throughout fitting.
|
| 1055 |
+
If `early_stopping=True`, this attribute is set to `None`. Refer to
|
| 1056 |
+
the `best_validation_score_` fitted attribute instead.
|
| 1057 |
+
|
| 1058 |
+
loss_curve_ : list of shape (`n_iter_`,)
|
| 1059 |
+
The ith element in the list represents the loss at the ith iteration.
|
| 1060 |
+
|
| 1061 |
+
validation_scores_ : list of shape (`n_iter_`,) or None
|
| 1062 |
+
The score at each iteration on a held-out validation set. The score
|
| 1063 |
+
reported is the accuracy score. Only available if `early_stopping=True`,
|
| 1064 |
+
otherwise the attribute is set to `None`.
|
| 1065 |
+
|
| 1066 |
+
best_validation_score_ : float or None
|
| 1067 |
+
The best validation score (i.e. accuracy score) that triggered the
|
| 1068 |
+
early stopping. Only available if `early_stopping=True`, otherwise the
|
| 1069 |
+
attribute is set to `None`.
|
| 1070 |
+
|
| 1071 |
+
t_ : int
|
| 1072 |
+
The number of training samples seen by the solver during fitting.
|
| 1073 |
+
|
| 1074 |
+
coefs_ : list of shape (n_layers - 1,)
|
| 1075 |
+
The ith element in the list represents the weight matrix corresponding
|
| 1076 |
+
to layer i.
|
| 1077 |
+
|
| 1078 |
+
intercepts_ : list of shape (n_layers - 1,)
|
| 1079 |
+
The ith element in the list represents the bias vector corresponding to
|
| 1080 |
+
layer i + 1.
|
| 1081 |
+
|
| 1082 |
+
n_features_in_ : int
|
| 1083 |
+
Number of features seen during :term:`fit`.
|
| 1084 |
+
|
| 1085 |
+
.. versionadded:: 0.24
|
| 1086 |
+
|
| 1087 |
+
feature_names_in_ : ndarray of shape (`n_features_in_`,)
|
| 1088 |
+
Names of features seen during :term:`fit`. Defined only when `X`
|
| 1089 |
+
has feature names that are all strings.
|
| 1090 |
+
|
| 1091 |
+
.. versionadded:: 1.0
|
| 1092 |
+
|
| 1093 |
+
n_iter_ : int
|
| 1094 |
+
The number of iterations the solver has run.
|
| 1095 |
+
|
| 1096 |
+
n_layers_ : int
|
| 1097 |
+
Number of layers.
|
| 1098 |
+
|
| 1099 |
+
n_outputs_ : int
|
| 1100 |
+
Number of outputs.
|
| 1101 |
+
|
| 1102 |
+
out_activation_ : str
|
| 1103 |
+
Name of the output activation function.
|
| 1104 |
+
|
| 1105 |
+
See Also
|
| 1106 |
+
--------
|
| 1107 |
+
MLPRegressor : Multi-layer Perceptron regressor.
|
| 1108 |
+
BernoulliRBM : Bernoulli Restricted Boltzmann Machine (RBM).
|
| 1109 |
+
|
| 1110 |
+
Notes
|
| 1111 |
+
-----
|
| 1112 |
+
MLPClassifier trains iteratively since at each time step
|
| 1113 |
+
the partial derivatives of the loss function with respect to the model
|
| 1114 |
+
parameters are computed to update the parameters.
|
| 1115 |
+
|
| 1116 |
+
It can also have a regularization term added to the loss function
|
| 1117 |
+
that shrinks model parameters to prevent overfitting.
|
| 1118 |
+
|
| 1119 |
+
This implementation works with data represented as dense numpy arrays or
|
| 1120 |
+
sparse scipy arrays of floating point values.
|
| 1121 |
+
|
| 1122 |
+
References
|
| 1123 |
+
----------
|
| 1124 |
+
Hinton, Geoffrey E. "Connectionist learning procedures."
|
| 1125 |
+
Artificial intelligence 40.1 (1989): 185-234.
|
| 1126 |
+
|
| 1127 |
+
Glorot, Xavier, and Yoshua Bengio.
|
| 1128 |
+
"Understanding the difficulty of training deep feedforward neural networks."
|
| 1129 |
+
International Conference on Artificial Intelligence and Statistics. 2010.
|
| 1130 |
+
|
| 1131 |
+
:arxiv:`He, Kaiming, et al (2015). "Delving deep into rectifiers:
|
| 1132 |
+
Surpassing human-level performance on imagenet classification." <1502.01852>`
|
| 1133 |
+
|
| 1134 |
+
:arxiv:`Kingma, Diederik, and Jimmy Ba (2014)
|
| 1135 |
+
"Adam: A method for stochastic optimization." <1412.6980>`
|
| 1136 |
+
|
| 1137 |
+
Examples
|
| 1138 |
+
--------
|
| 1139 |
+
>>> from sklearn.neural_network import MLPClassifier
|
| 1140 |
+
>>> from sklearn.datasets import make_classification
|
| 1141 |
+
>>> from sklearn.model_selection import train_test_split
|
| 1142 |
+
>>> X, y = make_classification(n_samples=100, random_state=1)
|
| 1143 |
+
>>> X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y,
|
| 1144 |
+
... random_state=1)
|
| 1145 |
+
>>> clf = MLPClassifier(random_state=1, max_iter=300).fit(X_train, y_train)
|
| 1146 |
+
>>> clf.predict_proba(X_test[:1])
|
| 1147 |
+
array([[0.0383, 0.961]])
|
| 1148 |
+
>>> clf.predict(X_test[:5, :])
|
| 1149 |
+
array([1, 0, 1, 0, 1])
|
| 1150 |
+
>>> clf.score(X_test, y_test)
|
| 1151 |
+
0.8...
|
| 1152 |
+
"""
|
| 1153 |
+
|
| 1154 |
+
def __init__(
|
| 1155 |
+
self,
|
| 1156 |
+
hidden_layer_sizes=(100,),
|
| 1157 |
+
activation="relu",
|
| 1158 |
+
*,
|
| 1159 |
+
solver="adam",
|
| 1160 |
+
alpha=0.0001,
|
| 1161 |
+
batch_size="auto",
|
| 1162 |
+
learning_rate="constant",
|
| 1163 |
+
learning_rate_init=0.001,
|
| 1164 |
+
power_t=0.5,
|
| 1165 |
+
max_iter=200,
|
| 1166 |
+
shuffle=True,
|
| 1167 |
+
random_state=None,
|
| 1168 |
+
tol=1e-4,
|
| 1169 |
+
verbose=False,
|
| 1170 |
+
warm_start=False,
|
| 1171 |
+
momentum=0.9,
|
| 1172 |
+
nesterovs_momentum=True,
|
| 1173 |
+
early_stopping=False,
|
| 1174 |
+
validation_fraction=0.1,
|
| 1175 |
+
beta_1=0.9,
|
| 1176 |
+
beta_2=0.999,
|
| 1177 |
+
epsilon=1e-8,
|
| 1178 |
+
n_iter_no_change=10,
|
| 1179 |
+
max_fun=15000,
|
| 1180 |
+
):
|
| 1181 |
+
super().__init__(
|
| 1182 |
+
hidden_layer_sizes=hidden_layer_sizes,
|
| 1183 |
+
activation=activation,
|
| 1184 |
+
solver=solver,
|
| 1185 |
+
alpha=alpha,
|
| 1186 |
+
batch_size=batch_size,
|
| 1187 |
+
learning_rate=learning_rate,
|
| 1188 |
+
learning_rate_init=learning_rate_init,
|
| 1189 |
+
power_t=power_t,
|
| 1190 |
+
max_iter=max_iter,
|
| 1191 |
+
loss="log_loss",
|
| 1192 |
+
shuffle=shuffle,
|
| 1193 |
+
random_state=random_state,
|
| 1194 |
+
tol=tol,
|
| 1195 |
+
verbose=verbose,
|
| 1196 |
+
warm_start=warm_start,
|
| 1197 |
+
momentum=momentum,
|
| 1198 |
+
nesterovs_momentum=nesterovs_momentum,
|
| 1199 |
+
early_stopping=early_stopping,
|
| 1200 |
+
validation_fraction=validation_fraction,
|
| 1201 |
+
beta_1=beta_1,
|
| 1202 |
+
beta_2=beta_2,
|
| 1203 |
+
epsilon=epsilon,
|
| 1204 |
+
n_iter_no_change=n_iter_no_change,
|
| 1205 |
+
max_fun=max_fun,
|
| 1206 |
+
)
|
| 1207 |
+
|
| 1208 |
+
def _validate_input(self, X, y, incremental, reset):
|
| 1209 |
+
X, y = validate_data(
|
| 1210 |
+
self,
|
| 1211 |
+
X,
|
| 1212 |
+
y,
|
| 1213 |
+
accept_sparse=["csr", "csc"],
|
| 1214 |
+
multi_output=True,
|
| 1215 |
+
dtype=(np.float64, np.float32),
|
| 1216 |
+
reset=reset,
|
| 1217 |
+
)
|
| 1218 |
+
if y.ndim == 2 and y.shape[1] == 1:
|
| 1219 |
+
y = column_or_1d(y, warn=True)
|
| 1220 |
+
|
| 1221 |
+
# Matrix of actions to be taken under the possible combinations:
|
| 1222 |
+
# The case that incremental == True and classes_ not defined is
|
| 1223 |
+
# already checked by _check_partial_fit_first_call that is called
|
| 1224 |
+
# in _partial_fit below.
|
| 1225 |
+
# The cases are already grouped into the respective if blocks below.
|
| 1226 |
+
#
|
| 1227 |
+
# incremental warm_start classes_ def action
|
| 1228 |
+
# 0 0 0 define classes_
|
| 1229 |
+
# 0 1 0 define classes_
|
| 1230 |
+
# 0 0 1 redefine classes_
|
| 1231 |
+
#
|
| 1232 |
+
# 0 1 1 check compat warm_start
|
| 1233 |
+
# 1 1 1 check compat warm_start
|
| 1234 |
+
#
|
| 1235 |
+
# 1 0 1 check compat last fit
|
| 1236 |
+
#
|
| 1237 |
+
# Note the reliance on short-circuiting here, so that the second
|
| 1238 |
+
# or part implies that classes_ is defined.
|
| 1239 |
+
if (not hasattr(self, "classes_")) or (not self.warm_start and not incremental):
|
| 1240 |
+
self._label_binarizer = LabelBinarizer()
|
| 1241 |
+
self._label_binarizer.fit(y)
|
| 1242 |
+
self.classes_ = self._label_binarizer.classes_
|
| 1243 |
+
else:
|
| 1244 |
+
classes = unique_labels(y)
|
| 1245 |
+
if self.warm_start:
|
| 1246 |
+
if set(classes) != set(self.classes_):
|
| 1247 |
+
raise ValueError(
|
| 1248 |
+
"warm_start can only be used where `y` has the same "
|
| 1249 |
+
"classes as in the previous call to fit. Previously "
|
| 1250 |
+
f"got {self.classes_}, `y` has {classes}"
|
| 1251 |
+
)
|
| 1252 |
+
elif len(np.setdiff1d(classes, self.classes_, assume_unique=True)):
|
| 1253 |
+
raise ValueError(
|
| 1254 |
+
"`y` has classes not in `self.classes_`. "
|
| 1255 |
+
f"`self.classes_` has {self.classes_}. 'y' has {classes}."
|
| 1256 |
+
)
|
| 1257 |
+
|
| 1258 |
+
# This downcast to bool is to prevent upcasting when working with
|
| 1259 |
+
# float32 data
|
| 1260 |
+
y = self._label_binarizer.transform(y).astype(bool)
|
| 1261 |
+
return X, y
|
| 1262 |
+
|
| 1263 |
+
def predict(self, X):
|
| 1264 |
+
"""Predict using the multi-layer perceptron classifier.
|
| 1265 |
+
|
| 1266 |
+
Parameters
|
| 1267 |
+
----------
|
| 1268 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
| 1269 |
+
The input data.
|
| 1270 |
+
|
| 1271 |
+
Returns
|
| 1272 |
+
-------
|
| 1273 |
+
y : ndarray, shape (n_samples,) or (n_samples, n_classes)
|
| 1274 |
+
The predicted classes.
|
| 1275 |
+
"""
|
| 1276 |
+
check_is_fitted(self)
|
| 1277 |
+
return self._predict(X)
|
| 1278 |
+
|
| 1279 |
+
def _predict(self, X, check_input=True):
|
| 1280 |
+
"""Private predict method with optional input validation"""
|
| 1281 |
+
y_pred = self._forward_pass_fast(X, check_input=check_input)
|
| 1282 |
+
|
| 1283 |
+
if self.n_outputs_ == 1:
|
| 1284 |
+
y_pred = y_pred.ravel()
|
| 1285 |
+
|
| 1286 |
+
return self._label_binarizer.inverse_transform(y_pred)
|
| 1287 |
+
|
| 1288 |
+
def _score(self, X, y, sample_weight=None):
|
| 1289 |
+
return super()._score_with_function(
|
| 1290 |
+
X, y, sample_weight=sample_weight, score_function=accuracy_score
|
| 1291 |
+
)
|
| 1292 |
+
|
| 1293 |
+
@available_if(lambda est: est._check_solver())
|
| 1294 |
+
@_fit_context(prefer_skip_nested_validation=True)
|
| 1295 |
+
def partial_fit(self, X, y, sample_weight=None, classes=None):
|
| 1296 |
+
"""Update the model with a single iteration over the given data.
|
| 1297 |
+
|
| 1298 |
+
Parameters
|
| 1299 |
+
----------
|
| 1300 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
| 1301 |
+
The input data.
|
| 1302 |
+
|
| 1303 |
+
y : array-like of shape (n_samples,)
|
| 1304 |
+
The target values.
|
| 1305 |
+
|
| 1306 |
+
sample_weight : array-like of shape (n_samples,), default=None
|
| 1307 |
+
Sample weights.
|
| 1308 |
+
|
| 1309 |
+
.. versionadded:: 1.7
|
| 1310 |
+
|
| 1311 |
+
classes : array of shape (n_classes,), default=None
|
| 1312 |
+
Classes across all calls to partial_fit.
|
| 1313 |
+
Can be obtained via `np.unique(y_all)`, where y_all is the
|
| 1314 |
+
target vector of the entire dataset.
|
| 1315 |
+
This argument is required for the first call to partial_fit
|
| 1316 |
+
and can be omitted in the subsequent calls.
|
| 1317 |
+
Note that y doesn't need to contain all labels in `classes`.
|
| 1318 |
+
|
| 1319 |
+
Returns
|
| 1320 |
+
-------
|
| 1321 |
+
self : object
|
| 1322 |
+
Trained MLP model.
|
| 1323 |
+
"""
|
| 1324 |
+
if _check_partial_fit_first_call(self, classes):
|
| 1325 |
+
self._label_binarizer = LabelBinarizer()
|
| 1326 |
+
if type_of_target(y).startswith("multilabel"):
|
| 1327 |
+
self._label_binarizer.fit(y)
|
| 1328 |
+
else:
|
| 1329 |
+
self._label_binarizer.fit(classes)
|
| 1330 |
+
|
| 1331 |
+
return self._fit(X, y, sample_weight=sample_weight, incremental=True)
|
| 1332 |
+
|
| 1333 |
+
def predict_log_proba(self, X):
|
| 1334 |
+
"""Return the log of probability estimates.
|
| 1335 |
+
|
| 1336 |
+
Parameters
|
| 1337 |
+
----------
|
| 1338 |
+
X : ndarray of shape (n_samples, n_features)
|
| 1339 |
+
The input data.
|
| 1340 |
+
|
| 1341 |
+
Returns
|
| 1342 |
+
-------
|
| 1343 |
+
log_y_prob : ndarray of shape (n_samples, n_classes)
|
| 1344 |
+
The predicted log-probability of the sample for each class
|
| 1345 |
+
in the model, where classes are ordered as they are in
|
| 1346 |
+
`self.classes_`. Equivalent to `log(predict_proba(X))`.
|
| 1347 |
+
"""
|
| 1348 |
+
y_prob = self.predict_proba(X)
|
| 1349 |
+
return np.log(y_prob, out=y_prob)
|
| 1350 |
+
|
| 1351 |
+
def predict_proba(self, X):
|
| 1352 |
+
"""Probability estimates.
|
| 1353 |
+
|
| 1354 |
+
Parameters
|
| 1355 |
+
----------
|
| 1356 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
| 1357 |
+
The input data.
|
| 1358 |
+
|
| 1359 |
+
Returns
|
| 1360 |
+
-------
|
| 1361 |
+
y_prob : ndarray of shape (n_samples, n_classes)
|
| 1362 |
+
The predicted probability of the sample for each class in the
|
| 1363 |
+
model, where classes are ordered as they are in `self.classes_`.
|
| 1364 |
+
"""
|
| 1365 |
+
check_is_fitted(self)
|
| 1366 |
+
y_pred = self._forward_pass_fast(X)
|
| 1367 |
+
|
| 1368 |
+
if self.n_outputs_ == 1:
|
| 1369 |
+
y_pred = y_pred.ravel()
|
| 1370 |
+
|
| 1371 |
+
if y_pred.ndim == 1:
|
| 1372 |
+
return np.vstack([1 - y_pred, y_pred]).T
|
| 1373 |
+
else:
|
| 1374 |
+
return y_pred
|
| 1375 |
+
|
| 1376 |
+
def __sklearn_tags__(self):
|
| 1377 |
+
tags = super().__sklearn_tags__()
|
| 1378 |
+
tags.classifier_tags.multi_label = True
|
| 1379 |
+
return tags
|
| 1380 |
+
|
| 1381 |
+
|
| 1382 |
+
class MLPRegressor(RegressorMixin, BaseMultilayerPerceptron):
|
| 1383 |
+
"""Multi-layer Perceptron regressor.
|
| 1384 |
+
|
| 1385 |
+
This model optimizes the squared error using LBFGS or stochastic gradient
|
| 1386 |
+
descent.
|
| 1387 |
+
|
| 1388 |
+
.. versionadded:: 0.18
|
| 1389 |
+
|
| 1390 |
+
Parameters
|
| 1391 |
+
----------
|
| 1392 |
+
loss : {'squared_error', 'poisson'}, default='squared_error'
|
| 1393 |
+
The loss function to use when training the weights. Note that the
|
| 1394 |
+
"squared error" and "poisson" losses actually implement
|
| 1395 |
+
"half squares error" and "half poisson deviance" to simplify the
|
| 1396 |
+
computation of the gradient. Furthermore, the "poisson" loss internally uses
|
| 1397 |
+
a log-link (exponential as the output activation function) and requires
|
| 1398 |
+
``y >= 0``.
|
| 1399 |
+
|
| 1400 |
+
.. versionchanged:: 1.7
|
| 1401 |
+
Added parameter `loss` and option 'poisson'.
|
| 1402 |
+
|
| 1403 |
+
hidden_layer_sizes : array-like of shape(n_layers - 2,), default=(100,)
|
| 1404 |
+
The ith element represents the number of neurons in the ith
|
| 1405 |
+
hidden layer.
|
| 1406 |
+
|
| 1407 |
+
activation : {'identity', 'logistic', 'tanh', 'relu'}, default='relu'
|
| 1408 |
+
Activation function for the hidden layer.
|
| 1409 |
+
|
| 1410 |
+
- 'identity', no-op activation, useful to implement linear bottleneck,
|
| 1411 |
+
returns f(x) = x
|
| 1412 |
+
|
| 1413 |
+
- 'logistic', the logistic sigmoid function,
|
| 1414 |
+
returns f(x) = 1 / (1 + exp(-x)).
|
| 1415 |
+
|
| 1416 |
+
- 'tanh', the hyperbolic tan function,
|
| 1417 |
+
returns f(x) = tanh(x).
|
| 1418 |
+
|
| 1419 |
+
- 'relu', the rectified linear unit function,
|
| 1420 |
+
returns f(x) = max(0, x)
|
| 1421 |
+
|
| 1422 |
+
solver : {'lbfgs', 'sgd', 'adam'}, default='adam'
|
| 1423 |
+
The solver for weight optimization.
|
| 1424 |
+
|
| 1425 |
+
- 'lbfgs' is an optimizer in the family of quasi-Newton methods.
|
| 1426 |
+
|
| 1427 |
+
- 'sgd' refers to stochastic gradient descent.
|
| 1428 |
+
|
| 1429 |
+
- 'adam' refers to a stochastic gradient-based optimizer proposed by
|
| 1430 |
+
Kingma, Diederik, and Jimmy Ba
|
| 1431 |
+
|
| 1432 |
+
For a comparison between Adam optimizer and SGD, see
|
| 1433 |
+
:ref:`sphx_glr_auto_examples_neural_networks_plot_mlp_training_curves.py`.
|
| 1434 |
+
|
| 1435 |
+
Note: The default solver 'adam' works pretty well on relatively
|
| 1436 |
+
large datasets (with thousands of training samples or more) in terms of
|
| 1437 |
+
both training time and validation score.
|
| 1438 |
+
For small datasets, however, 'lbfgs' can converge faster and perform
|
| 1439 |
+
better.
|
| 1440 |
+
|
| 1441 |
+
alpha : float, default=0.0001
|
| 1442 |
+
Strength of the L2 regularization term. The L2 regularization term
|
| 1443 |
+
is divided by the sample size when added to the loss.
|
| 1444 |
+
|
| 1445 |
+
batch_size : int, default='auto'
|
| 1446 |
+
Size of minibatches for stochastic optimizers.
|
| 1447 |
+
If the solver is 'lbfgs', the regressor will not use minibatch.
|
| 1448 |
+
When set to "auto", `batch_size=min(200, n_samples)`.
|
| 1449 |
+
|
| 1450 |
+
learning_rate : {'constant', 'invscaling', 'adaptive'}, default='constant'
|
| 1451 |
+
Learning rate schedule for weight updates.
|
| 1452 |
+
|
| 1453 |
+
- 'constant' is a constant learning rate given by
|
| 1454 |
+
'learning_rate_init'.
|
| 1455 |
+
|
| 1456 |
+
- 'invscaling' gradually decreases the learning rate ``learning_rate_``
|
| 1457 |
+
at each time step 't' using an inverse scaling exponent of 'power_t'.
|
| 1458 |
+
effective_learning_rate = learning_rate_init / pow(t, power_t)
|
| 1459 |
+
|
| 1460 |
+
- 'adaptive' keeps the learning rate constant to
|
| 1461 |
+
'learning_rate_init' as long as training loss keeps decreasing.
|
| 1462 |
+
Each time two consecutive epochs fail to decrease training loss by at
|
| 1463 |
+
least tol, or fail to increase validation score by at least tol if
|
| 1464 |
+
'early_stopping' is on, the current learning rate is divided by 5.
|
| 1465 |
+
|
| 1466 |
+
Only used when solver='sgd'.
|
| 1467 |
+
|
| 1468 |
+
learning_rate_init : float, default=0.001
|
| 1469 |
+
The initial learning rate used. It controls the step-size
|
| 1470 |
+
in updating the weights. Only used when solver='sgd' or 'adam'.
|
| 1471 |
+
|
| 1472 |
+
power_t : float, default=0.5
|
| 1473 |
+
The exponent for inverse scaling learning rate.
|
| 1474 |
+
It is used in updating effective learning rate when the learning_rate
|
| 1475 |
+
is set to 'invscaling'. Only used when solver='sgd'.
|
| 1476 |
+
|
| 1477 |
+
max_iter : int, default=200
|
| 1478 |
+
Maximum number of iterations. The solver iterates until convergence
|
| 1479 |
+
(determined by 'tol') or this number of iterations. For stochastic
|
| 1480 |
+
solvers ('sgd', 'adam'), note that this determines the number of epochs
|
| 1481 |
+
(how many times each data point will be used), not the number of
|
| 1482 |
+
gradient steps.
|
| 1483 |
+
|
| 1484 |
+
shuffle : bool, default=True
|
| 1485 |
+
Whether to shuffle samples in each iteration. Only used when
|
| 1486 |
+
solver='sgd' or 'adam'.
|
| 1487 |
+
|
| 1488 |
+
random_state : int, RandomState instance, default=None
|
| 1489 |
+
Determines random number generation for weights and bias
|
| 1490 |
+
initialization, train-test split if early stopping is used, and batch
|
| 1491 |
+
sampling when solver='sgd' or 'adam'.
|
| 1492 |
+
Pass an int for reproducible results across multiple function calls.
|
| 1493 |
+
See :term:`Glossary <random_state>`.
|
| 1494 |
+
|
| 1495 |
+
tol : float, default=1e-4
|
| 1496 |
+
Tolerance for the optimization. When the loss or score is not improving
|
| 1497 |
+
by at least ``tol`` for ``n_iter_no_change`` consecutive iterations,
|
| 1498 |
+
unless ``learning_rate`` is set to 'adaptive', convergence is
|
| 1499 |
+
considered to be reached and training stops.
|
| 1500 |
+
|
| 1501 |
+
verbose : bool, default=False
|
| 1502 |
+
Whether to print progress messages to stdout.
|
| 1503 |
+
|
| 1504 |
+
warm_start : bool, default=False
|
| 1505 |
+
When set to True, reuse the solution of the previous
|
| 1506 |
+
call to fit as initialization, otherwise, just erase the
|
| 1507 |
+
previous solution. See :term:`the Glossary <warm_start>`.
|
| 1508 |
+
|
| 1509 |
+
momentum : float, default=0.9
|
| 1510 |
+
Momentum for gradient descent update. Should be between 0 and 1. Only
|
| 1511 |
+
used when solver='sgd'.
|
| 1512 |
+
|
| 1513 |
+
nesterovs_momentum : bool, default=True
|
| 1514 |
+
Whether to use Nesterov's momentum. Only used when solver='sgd' and
|
| 1515 |
+
momentum > 0.
|
| 1516 |
+
|
| 1517 |
+
early_stopping : bool, default=False
|
| 1518 |
+
Whether to use early stopping to terminate training when validation
|
| 1519 |
+
score is not improving. If set to True, it will automatically set
|
| 1520 |
+
aside ``validation_fraction`` of training data as validation and
|
| 1521 |
+
terminate training when validation score is not improving by at
|
| 1522 |
+
least ``tol`` for ``n_iter_no_change`` consecutive epochs.
|
| 1523 |
+
Only effective when solver='sgd' or 'adam'.
|
| 1524 |
+
|
| 1525 |
+
validation_fraction : float, default=0.1
|
| 1526 |
+
The proportion of training data to set aside as validation set for
|
| 1527 |
+
early stopping. Must be between 0 and 1.
|
| 1528 |
+
Only used if early_stopping is True.
|
| 1529 |
+
|
| 1530 |
+
beta_1 : float, default=0.9
|
| 1531 |
+
Exponential decay rate for estimates of first moment vector in adam,
|
| 1532 |
+
should be in [0, 1). Only used when solver='adam'.
|
| 1533 |
+
|
| 1534 |
+
beta_2 : float, default=0.999
|
| 1535 |
+
Exponential decay rate for estimates of second moment vector in adam,
|
| 1536 |
+
should be in [0, 1). Only used when solver='adam'.
|
| 1537 |
+
|
| 1538 |
+
epsilon : float, default=1e-8
|
| 1539 |
+
Value for numerical stability in adam. Only used when solver='adam'.
|
| 1540 |
+
|
| 1541 |
+
n_iter_no_change : int, default=10
|
| 1542 |
+
Maximum number of epochs to not meet ``tol`` improvement.
|
| 1543 |
+
Only effective when solver='sgd' or 'adam'.
|
| 1544 |
+
|
| 1545 |
+
.. versionadded:: 0.20
|
| 1546 |
+
|
| 1547 |
+
max_fun : int, default=15000
|
| 1548 |
+
Only used when solver='lbfgs'. Maximum number of function calls.
|
| 1549 |
+
The solver iterates until convergence (determined by ``tol``), number
|
| 1550 |
+
of iterations reaches max_iter, or this number of function calls.
|
| 1551 |
+
Note that number of function calls will be greater than or equal to
|
| 1552 |
+
the number of iterations for the MLPRegressor.
|
| 1553 |
+
|
| 1554 |
+
.. versionadded:: 0.22
|
| 1555 |
+
|
| 1556 |
+
Attributes
|
| 1557 |
+
----------
|
| 1558 |
+
loss_ : float
|
| 1559 |
+
The current loss computed with the loss function.
|
| 1560 |
+
|
| 1561 |
+
best_loss_ : float
|
| 1562 |
+
The minimum loss reached by the solver throughout fitting.
|
| 1563 |
+
If `early_stopping=True`, this attribute is set to `None`. Refer to
|
| 1564 |
+
the `best_validation_score_` fitted attribute instead.
|
| 1565 |
+
Only accessible when solver='sgd' or 'adam'.
|
| 1566 |
+
|
| 1567 |
+
loss_curve_ : list of shape (`n_iter_`,)
|
| 1568 |
+
Loss value evaluated at the end of each training step.
|
| 1569 |
+
The ith element in the list represents the loss at the ith iteration.
|
| 1570 |
+
Only accessible when solver='sgd' or 'adam'.
|
| 1571 |
+
|
| 1572 |
+
validation_scores_ : list of shape (`n_iter_`,) or None
|
| 1573 |
+
The score at each iteration on a held-out validation set. The score
|
| 1574 |
+
reported is the R2 score. Only available if `early_stopping=True`,
|
| 1575 |
+
otherwise the attribute is set to `None`.
|
| 1576 |
+
Only accessible when solver='sgd' or 'adam'.
|
| 1577 |
+
|
| 1578 |
+
best_validation_score_ : float or None
|
| 1579 |
+
The best validation score (i.e. R2 score) that triggered the
|
| 1580 |
+
early stopping. Only available if `early_stopping=True`, otherwise the
|
| 1581 |
+
attribute is set to `None`.
|
| 1582 |
+
Only accessible when solver='sgd' or 'adam'.
|
| 1583 |
+
|
| 1584 |
+
t_ : int
|
| 1585 |
+
The number of training samples seen by the solver during fitting.
|
| 1586 |
+
Mathematically equals `n_iters * X.shape[0]`, it means
|
| 1587 |
+
`time_step` and it is used by optimizer's learning rate scheduler.
|
| 1588 |
+
|
| 1589 |
+
coefs_ : list of shape (n_layers - 1,)
|
| 1590 |
+
The ith element in the list represents the weight matrix corresponding
|
| 1591 |
+
to layer i.
|
| 1592 |
+
|
| 1593 |
+
intercepts_ : list of shape (n_layers - 1,)
|
| 1594 |
+
The ith element in the list represents the bias vector corresponding to
|
| 1595 |
+
layer i + 1.
|
| 1596 |
+
|
| 1597 |
+
n_features_in_ : int
|
| 1598 |
+
Number of features seen during :term:`fit`.
|
| 1599 |
+
|
| 1600 |
+
.. versionadded:: 0.24
|
| 1601 |
+
|
| 1602 |
+
feature_names_in_ : ndarray of shape (`n_features_in_`,)
|
| 1603 |
+
Names of features seen during :term:`fit`. Defined only when `X`
|
| 1604 |
+
has feature names that are all strings.
|
| 1605 |
+
|
| 1606 |
+
.. versionadded:: 1.0
|
| 1607 |
+
|
| 1608 |
+
n_iter_ : int
|
| 1609 |
+
The number of iterations the solver has run.
|
| 1610 |
+
|
| 1611 |
+
n_layers_ : int
|
| 1612 |
+
Number of layers.
|
| 1613 |
+
|
| 1614 |
+
n_outputs_ : int
|
| 1615 |
+
Number of outputs.
|
| 1616 |
+
|
| 1617 |
+
out_activation_ : str
|
| 1618 |
+
Name of the output activation function.
|
| 1619 |
+
|
| 1620 |
+
See Also
|
| 1621 |
+
--------
|
| 1622 |
+
BernoulliRBM : Bernoulli Restricted Boltzmann Machine (RBM).
|
| 1623 |
+
MLPClassifier : Multi-layer Perceptron classifier.
|
| 1624 |
+
sklearn.linear_model.SGDRegressor : Linear model fitted by minimizing
|
| 1625 |
+
a regularized empirical loss with SGD.
|
| 1626 |
+
|
| 1627 |
+
Notes
|
| 1628 |
+
-----
|
| 1629 |
+
MLPRegressor trains iteratively since at each time step
|
| 1630 |
+
the partial derivatives of the loss function with respect to the model
|
| 1631 |
+
parameters are computed to update the parameters.
|
| 1632 |
+
|
| 1633 |
+
It can also have a regularization term added to the loss function
|
| 1634 |
+
that shrinks model parameters to prevent overfitting.
|
| 1635 |
+
|
| 1636 |
+
This implementation works with data represented as dense and sparse numpy
|
| 1637 |
+
arrays of floating point values.
|
| 1638 |
+
|
| 1639 |
+
References
|
| 1640 |
+
----------
|
| 1641 |
+
Hinton, Geoffrey E. "Connectionist learning procedures."
|
| 1642 |
+
Artificial intelligence 40.1 (1989): 185-234.
|
| 1643 |
+
|
| 1644 |
+
Glorot, Xavier, and Yoshua Bengio.
|
| 1645 |
+
"Understanding the difficulty of training deep feedforward neural networks."
|
| 1646 |
+
International Conference on Artificial Intelligence and Statistics. 2010.
|
| 1647 |
+
|
| 1648 |
+
:arxiv:`He, Kaiming, et al (2015). "Delving deep into rectifiers:
|
| 1649 |
+
Surpassing human-level performance on imagenet classification." <1502.01852>`
|
| 1650 |
+
|
| 1651 |
+
:arxiv:`Kingma, Diederik, and Jimmy Ba (2014)
|
| 1652 |
+
"Adam: A method for stochastic optimization." <1412.6980>`
|
| 1653 |
+
|
| 1654 |
+
Examples
|
| 1655 |
+
--------
|
| 1656 |
+
>>> from sklearn.neural_network import MLPRegressor
|
| 1657 |
+
>>> from sklearn.datasets import make_regression
|
| 1658 |
+
>>> from sklearn.model_selection import train_test_split
|
| 1659 |
+
>>> X, y = make_regression(n_samples=200, n_features=20, random_state=1)
|
| 1660 |
+
>>> X_train, X_test, y_train, y_test = train_test_split(X, y,
|
| 1661 |
+
... random_state=1)
|
| 1662 |
+
>>> regr = MLPRegressor(random_state=1, max_iter=2000, tol=0.1)
|
| 1663 |
+
>>> regr.fit(X_train, y_train)
|
| 1664 |
+
MLPRegressor(max_iter=2000, random_state=1, tol=0.1)
|
| 1665 |
+
>>> regr.predict(X_test[:2])
|
| 1666 |
+
array([ 28.98, -291])
|
| 1667 |
+
>>> regr.score(X_test, y_test)
|
| 1668 |
+
0.98
|
| 1669 |
+
"""
|
| 1670 |
+
|
| 1671 |
+
_parameter_constraints: dict = {
|
| 1672 |
+
**BaseMultilayerPerceptron._parameter_constraints,
|
| 1673 |
+
"loss": [StrOptions({"squared_error", "poisson"})],
|
| 1674 |
+
}
|
| 1675 |
+
|
| 1676 |
+
def __init__(
|
| 1677 |
+
self,
|
| 1678 |
+
loss="squared_error",
|
| 1679 |
+
hidden_layer_sizes=(100,),
|
| 1680 |
+
activation="relu",
|
| 1681 |
+
*,
|
| 1682 |
+
solver="adam",
|
| 1683 |
+
alpha=0.0001,
|
| 1684 |
+
batch_size="auto",
|
| 1685 |
+
learning_rate="constant",
|
| 1686 |
+
learning_rate_init=0.001,
|
| 1687 |
+
power_t=0.5,
|
| 1688 |
+
max_iter=200,
|
| 1689 |
+
shuffle=True,
|
| 1690 |
+
random_state=None,
|
| 1691 |
+
tol=1e-4,
|
| 1692 |
+
verbose=False,
|
| 1693 |
+
warm_start=False,
|
| 1694 |
+
momentum=0.9,
|
| 1695 |
+
nesterovs_momentum=True,
|
| 1696 |
+
early_stopping=False,
|
| 1697 |
+
validation_fraction=0.1,
|
| 1698 |
+
beta_1=0.9,
|
| 1699 |
+
beta_2=0.999,
|
| 1700 |
+
epsilon=1e-8,
|
| 1701 |
+
n_iter_no_change=10,
|
| 1702 |
+
max_fun=15000,
|
| 1703 |
+
):
|
| 1704 |
+
super().__init__(
|
| 1705 |
+
hidden_layer_sizes=hidden_layer_sizes,
|
| 1706 |
+
activation=activation,
|
| 1707 |
+
solver=solver,
|
| 1708 |
+
alpha=alpha,
|
| 1709 |
+
batch_size=batch_size,
|
| 1710 |
+
learning_rate=learning_rate,
|
| 1711 |
+
learning_rate_init=learning_rate_init,
|
| 1712 |
+
power_t=power_t,
|
| 1713 |
+
max_iter=max_iter,
|
| 1714 |
+
loss=loss,
|
| 1715 |
+
shuffle=shuffle,
|
| 1716 |
+
random_state=random_state,
|
| 1717 |
+
tol=tol,
|
| 1718 |
+
verbose=verbose,
|
| 1719 |
+
warm_start=warm_start,
|
| 1720 |
+
momentum=momentum,
|
| 1721 |
+
nesterovs_momentum=nesterovs_momentum,
|
| 1722 |
+
early_stopping=early_stopping,
|
| 1723 |
+
validation_fraction=validation_fraction,
|
| 1724 |
+
beta_1=beta_1,
|
| 1725 |
+
beta_2=beta_2,
|
| 1726 |
+
epsilon=epsilon,
|
| 1727 |
+
n_iter_no_change=n_iter_no_change,
|
| 1728 |
+
max_fun=max_fun,
|
| 1729 |
+
)
|
| 1730 |
+
|
| 1731 |
+
def predict(self, X):
|
| 1732 |
+
"""Predict using the multi-layer perceptron model.
|
| 1733 |
+
|
| 1734 |
+
Parameters
|
| 1735 |
+
----------
|
| 1736 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
| 1737 |
+
The input data.
|
| 1738 |
+
|
| 1739 |
+
Returns
|
| 1740 |
+
-------
|
| 1741 |
+
y : ndarray of shape (n_samples, n_outputs)
|
| 1742 |
+
The predicted values.
|
| 1743 |
+
"""
|
| 1744 |
+
check_is_fitted(self)
|
| 1745 |
+
return self._predict(X)
|
| 1746 |
+
|
| 1747 |
+
def _predict(self, X, check_input=True):
|
| 1748 |
+
"""Private predict method with optional input validation"""
|
| 1749 |
+
y_pred = self._forward_pass_fast(X, check_input=check_input)
|
| 1750 |
+
if y_pred.shape[1] == 1:
|
| 1751 |
+
return y_pred.ravel()
|
| 1752 |
+
return y_pred
|
| 1753 |
+
|
| 1754 |
+
def _score(self, X, y, sample_weight=None):
|
| 1755 |
+
return super()._score_with_function(
|
| 1756 |
+
X, y, sample_weight=sample_weight, score_function=r2_score
|
| 1757 |
+
)
|
| 1758 |
+
|
| 1759 |
+
def _validate_input(self, X, y, incremental, reset):
|
| 1760 |
+
X, y = validate_data(
|
| 1761 |
+
self,
|
| 1762 |
+
X,
|
| 1763 |
+
y,
|
| 1764 |
+
accept_sparse=["csr", "csc"],
|
| 1765 |
+
multi_output=True,
|
| 1766 |
+
y_numeric=True,
|
| 1767 |
+
dtype=(np.float64, np.float32),
|
| 1768 |
+
reset=reset,
|
| 1769 |
+
)
|
| 1770 |
+
if y.ndim == 2 and y.shape[1] == 1:
|
| 1771 |
+
y = column_or_1d(y, warn=True)
|
| 1772 |
+
return X, y
|
| 1773 |
+
|
| 1774 |
+
@available_if(lambda est: est._check_solver)
|
| 1775 |
+
@_fit_context(prefer_skip_nested_validation=True)
|
| 1776 |
+
def partial_fit(self, X, y, sample_weight=None):
|
| 1777 |
+
"""Update the model with a single iteration over the given data.
|
| 1778 |
+
|
| 1779 |
+
Parameters
|
| 1780 |
+
----------
|
| 1781 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
| 1782 |
+
The input data.
|
| 1783 |
+
|
| 1784 |
+
y : ndarray of shape (n_samples,)
|
| 1785 |
+
The target values.
|
| 1786 |
+
|
| 1787 |
+
sample_weight : array-like of shape (n_samples,), default=None
|
| 1788 |
+
Sample weights.
|
| 1789 |
+
|
| 1790 |
+
.. versionadded:: 1.6
|
| 1791 |
+
|
| 1792 |
+
Returns
|
| 1793 |
+
-------
|
| 1794 |
+
self : object
|
| 1795 |
+
Trained MLP model.
|
| 1796 |
+
"""
|
| 1797 |
+
return self._fit(X, y, sample_weight=sample_weight, incremental=True)
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test functions for models.tools
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from statsmodels.compat.pandas import assert_frame_equal, assert_series_equal
|
| 6 |
+
from statsmodels.compat.python import lrange
|
| 7 |
+
|
| 8 |
+
import itertools
|
| 9 |
+
import string
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
from numpy.testing import (
|
| 13 |
+
assert_almost_equal,
|
| 14 |
+
assert_array_equal,
|
| 15 |
+
assert_equal,
|
| 16 |
+
assert_string_equal,
|
| 17 |
+
)
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import pytest
|
| 20 |
+
|
| 21 |
+
from statsmodels.datasets import longley
|
| 22 |
+
from statsmodels.tools import tools
|
| 23 |
+
from statsmodels.tools.tools import pinv_extended
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@pytest.fixture(scope="module")
|
| 27 |
+
def string_var():
|
| 28 |
+
string_var = [
|
| 29 |
+
string.ascii_lowercase[0:5],
|
| 30 |
+
string.ascii_lowercase[5:10],
|
| 31 |
+
string.ascii_lowercase[10:15],
|
| 32 |
+
string.ascii_lowercase[15:20],
|
| 33 |
+
string.ascii_lowercase[20:25],
|
| 34 |
+
]
|
| 35 |
+
string_var *= 5
|
| 36 |
+
string_var = np.asarray(sorted(string_var))
|
| 37 |
+
series = pd.Series(string_var, name="string_var")
|
| 38 |
+
return series
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class TestTools:
|
| 42 |
+
def test_add_constant_list(self):
|
| 43 |
+
x = lrange(1, 5)
|
| 44 |
+
x = tools.add_constant(x)
|
| 45 |
+
y = np.asarray([[1, 1, 1, 1], [1, 2, 3, 4.0]]).T
|
| 46 |
+
assert_equal(x, y)
|
| 47 |
+
|
| 48 |
+
def test_add_constant_1d(self):
|
| 49 |
+
x = np.arange(1, 5)
|
| 50 |
+
x = tools.add_constant(x)
|
| 51 |
+
y = np.asarray([[1, 1, 1, 1], [1, 2, 3, 4.0]]).T
|
| 52 |
+
assert_equal(x, y)
|
| 53 |
+
|
| 54 |
+
def test_add_constant_has_constant1d(self):
|
| 55 |
+
x = np.ones(5)
|
| 56 |
+
x = tools.add_constant(x, has_constant="skip")
|
| 57 |
+
assert_equal(x, np.ones((5, 1)))
|
| 58 |
+
|
| 59 |
+
with pytest.raises(ValueError):
|
| 60 |
+
tools.add_constant(x, has_constant="raise")
|
| 61 |
+
|
| 62 |
+
assert_equal(tools.add_constant(x, has_constant="add"), np.ones((5, 2)))
|
| 63 |
+
|
| 64 |
+
def test_add_constant_has_constant2d(self):
|
| 65 |
+
x = np.asarray([[1, 1, 1, 1], [1, 2, 3, 4.0]]).T
|
| 66 |
+
y = tools.add_constant(x, has_constant="skip")
|
| 67 |
+
assert_equal(x, y)
|
| 68 |
+
|
| 69 |
+
with pytest.raises(ValueError):
|
| 70 |
+
tools.add_constant(x, has_constant="raise")
|
| 71 |
+
|
| 72 |
+
assert_equal(
|
| 73 |
+
tools.add_constant(x, has_constant="add"),
|
| 74 |
+
np.column_stack((np.ones(4), x)),
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
def test_add_constant_series(self):
|
| 78 |
+
s = pd.Series([1.0, 2.0, 3.0])
|
| 79 |
+
output = tools.add_constant(s)
|
| 80 |
+
expected = pd.Series([1.0, 1.0, 1.0], name="const")
|
| 81 |
+
assert_series_equal(expected, output["const"])
|
| 82 |
+
|
| 83 |
+
def test_add_constant_dataframe(self):
|
| 84 |
+
df = pd.DataFrame([[1.0, "a", 4], [2.0, "bc", 9], [3.0, "def", 16]])
|
| 85 |
+
output = tools.add_constant(df)
|
| 86 |
+
expected = pd.Series([1.0, 1.0, 1.0], name="const")
|
| 87 |
+
assert_series_equal(expected, output["const"])
|
| 88 |
+
dfc = df.copy()
|
| 89 |
+
dfc.insert(0, "const", np.ones(3))
|
| 90 |
+
assert_frame_equal(dfc, output)
|
| 91 |
+
|
| 92 |
+
def test_add_constant_zeros(self):
|
| 93 |
+
a = np.zeros(100)
|
| 94 |
+
output = tools.add_constant(a)
|
| 95 |
+
assert_equal(output[:, 0], np.ones(100))
|
| 96 |
+
|
| 97 |
+
s = pd.Series([0.0, 0.0, 0.0])
|
| 98 |
+
output = tools.add_constant(s)
|
| 99 |
+
expected = pd.Series([1.0, 1.0, 1.0], name="const")
|
| 100 |
+
assert_series_equal(expected, output["const"])
|
| 101 |
+
|
| 102 |
+
df = pd.DataFrame([[0.0, "a", 4], [0.0, "bc", 9], [0.0, "def", 16]])
|
| 103 |
+
output = tools.add_constant(df)
|
| 104 |
+
dfc = df.copy()
|
| 105 |
+
dfc.insert(0, "const", np.ones(3))
|
| 106 |
+
assert_frame_equal(dfc, output)
|
| 107 |
+
|
| 108 |
+
df = pd.DataFrame([[1.0, "a", 0], [0.0, "bc", 0], [0.0, "def", 0]])
|
| 109 |
+
output = tools.add_constant(df)
|
| 110 |
+
dfc = df.copy()
|
| 111 |
+
dfc.insert(0, "const", np.ones(3))
|
| 112 |
+
assert_frame_equal(dfc, output)
|
| 113 |
+
|
| 114 |
+
def test_drop_missing(self):
|
| 115 |
+
_y = np.array([[1.0, 2.0, np.nan], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])
|
| 116 |
+
# axis=1 looks for missing values across the columns of each row, so
|
| 117 |
+
# the row holding the nan is dropped
|
| 118 |
+
assert_almost_equal(
|
| 119 |
+
tools.drop_missing(_y, axis=1),
|
| 120 |
+
np.array([[4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]),
|
| 121 |
+
)
|
| 122 |
+
# axis=0 looks across the rows of each column, so the column holding
|
| 123 |
+
# the nan is dropped instead
|
| 124 |
+
assert_almost_equal(
|
| 125 |
+
tools.drop_missing(_y, axis=0),
|
| 126 |
+
np.array([[1.0, 2.0], [4.0, 5.0], [7.0, 8.0]]),
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
def test_drop_missing_x(self):
|
| 130 |
+
_y = np.array([[1.0, 2.0], [3.0, np.nan], [5.0, 6.0]])
|
| 131 |
+
_x = np.array([[1.0, np.nan], [1.0, 1.0], [1.0, 1.0]])
|
| 132 |
+
y, x = tools.drop_missing(_y, _x, axis=0)
|
| 133 |
+
assert_almost_equal(y, np.array([[1.0], [3.0], [5.0]]))
|
| 134 |
+
assert_almost_equal(x, np.array([[1.0], [1.0], [1.0]]))
|
| 135 |
+
|
| 136 |
+
# axis=1 with two variables: a row is dropped if either _y or _x
|
| 137 |
+
# is missing anywhere in that row
|
| 138 |
+
_y = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
|
| 139 |
+
_x = np.array([[1.0, 1.0], [1.0, np.nan], [1.0, 1.0]])
|
| 140 |
+
y, x = tools.drop_missing(_y, _x, axis=1)
|
| 141 |
+
assert_almost_equal(y, np.array([[1.0, 2.0], [5.0, 6.0]]))
|
| 142 |
+
assert_almost_equal(x, np.array([[1.0, 1.0], [1.0, 1.0]]))
|
| 143 |
+
|
| 144 |
+
def test_recipr(self):
|
| 145 |
+
X = np.array([[2, 1], [-1, 0]])
|
| 146 |
+
Y = tools.recipr(X)
|
| 147 |
+
assert_almost_equal(Y, np.array([[0.5, 1], [0, 0]]))
|
| 148 |
+
|
| 149 |
+
def test_recipr0(self):
|
| 150 |
+
X = np.array([[2, 1], [-4, 0]])
|
| 151 |
+
Y = tools.recipr0(X)
|
| 152 |
+
assert_almost_equal(Y, np.array([[0.5, 1], [-0.25, 0]]))
|
| 153 |
+
|
| 154 |
+
def test_extendedpinv(self):
|
| 155 |
+
rs = np.random.RandomState(4783891)
|
| 156 |
+
X = rs.standard_normal((40, 10))
|
| 157 |
+
np_inv = np.linalg.pinv(X)
|
| 158 |
+
np_sing_vals = np.linalg.svd(X, 0, 0)
|
| 159 |
+
sm_inv, sing_vals = pinv_extended(X)
|
| 160 |
+
assert_almost_equal(np_inv, sm_inv)
|
| 161 |
+
assert_almost_equal(np_sing_vals, sing_vals)
|
| 162 |
+
|
| 163 |
+
def test_extendedpinv_singular(self):
|
| 164 |
+
rs = np.random.RandomState(4783893)
|
| 165 |
+
X = rs.standard_normal((40, 10))
|
| 166 |
+
X[:, 5] = X[:, 1] + X[:, 3]
|
| 167 |
+
np_inv = np.linalg.pinv(X)
|
| 168 |
+
np_sing_vals = np.linalg.svd(X, 0, 0)
|
| 169 |
+
sm_inv, sing_vals = pinv_extended(X)
|
| 170 |
+
assert_almost_equal(np_inv, sm_inv)
|
| 171 |
+
assert_almost_equal(np_sing_vals, sing_vals)
|
| 172 |
+
|
| 173 |
+
def test_fullrank(self):
|
| 174 |
+
import warnings
|
| 175 |
+
|
| 176 |
+
rs = np.random.RandomState(4783895)
|
| 177 |
+
with warnings.catch_warnings():
|
| 178 |
+
warnings.simplefilter("ignore")
|
| 179 |
+
X = rs.standard_normal((40, 10))
|
| 180 |
+
X[:, 0] = X[:, 1] + X[:, 2]
|
| 181 |
+
|
| 182 |
+
Y = tools.fullrank(X)
|
| 183 |
+
assert_equal(Y.shape, (40, 9))
|
| 184 |
+
|
| 185 |
+
X[:, 5] = X[:, 3] + X[:, 4]
|
| 186 |
+
Y = tools.fullrank(X)
|
| 187 |
+
assert_equal(Y.shape, (40, 8))
|
| 188 |
+
warnings.simplefilter("ignore")
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def test_estimable():
|
| 192 |
+
rng = np.random.RandomState(20120713)
|
| 193 |
+
N, P = (40, 10)
|
| 194 |
+
X = rng.normal(size=(N, P))
|
| 195 |
+
C = rng.normal(size=(1, P))
|
| 196 |
+
isestimable = tools.isestimable
|
| 197 |
+
assert isestimable(C, X)
|
| 198 |
+
assert isestimable(np.eye(P), X)
|
| 199 |
+
for row in np.eye(P):
|
| 200 |
+
assert isestimable(row, X)
|
| 201 |
+
X = np.ones((40, 2))
|
| 202 |
+
assert isestimable([1, 1], X)
|
| 203 |
+
assert not isestimable([1, 0], X)
|
| 204 |
+
assert not isestimable([0, 1], X)
|
| 205 |
+
assert not isestimable(np.eye(2), X)
|
| 206 |
+
halfX = rng.normal(size=(N, 5))
|
| 207 |
+
X = np.hstack([halfX, halfX])
|
| 208 |
+
assert not isestimable(np.hstack([np.eye(5), np.zeros((5, 5))]), X)
|
| 209 |
+
assert not isestimable(np.hstack([np.zeros((5, 5)), np.eye(5)]), X)
|
| 210 |
+
assert isestimable(np.hstack([np.eye(5), np.eye(5)]), X)
|
| 211 |
+
# Test array_like for design
|
| 212 |
+
XL = X.tolist()
|
| 213 |
+
assert isestimable(np.hstack([np.eye(5), np.eye(5)]), XL)
|
| 214 |
+
# Test ValueError for incorrect number of columns
|
| 215 |
+
X = rng.normal(size=(N, 5))
|
| 216 |
+
for n in range(1, 4):
|
| 217 |
+
with pytest.raises(ValueError):
|
| 218 |
+
isestimable(np.ones((n,)), X)
|
| 219 |
+
with pytest.raises(ValueError):
|
| 220 |
+
isestimable(np.eye(4), X)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
@pytest.mark.parametrize("method", ["ip", "qr", "svd"])
|
| 224 |
+
def test_matrix_rank_column_order(method):
|
| 225 |
+
# the rank of a matrix is a property of its column space, so it does not
|
| 226 |
+
# depend on the order the columns are given in. The regressor here is
|
| 227 |
+
# measured on a much larger scale than the intercept, which is the case
|
| 228 |
+
# that separates a tolerance taken from the leading diagonal element of
|
| 229 |
+
# the R matrix from one taken from the largest.
|
| 230 |
+
x = 1e3 * np.arange(1.0, 41.0) / 7.0
|
| 231 |
+
exog = np.column_stack((np.ones(40), x, 2.0 * x))
|
| 232 |
+
|
| 233 |
+
for cols in itertools.permutations(range(exog.shape[1])):
|
| 234 |
+
rank = tools.matrix_rank(exog[:, list(cols)], method=method)
|
| 235 |
+
assert_equal(rank, 2, err_msg=f"column order {cols}")
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def test_pandas_const_series():
|
| 239 |
+
dta = longley.load_pandas()
|
| 240 |
+
series = dta.exog["GNP"]
|
| 241 |
+
series = tools.add_constant(series, prepend=False)
|
| 242 |
+
assert_string_equal("const", series.columns[1])
|
| 243 |
+
assert_equal(series.var(axis=0).iloc[1], 0)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def test_pandas_const_series_prepend():
|
| 247 |
+
dta = longley.load_pandas()
|
| 248 |
+
series = dta.exog["GNP"]
|
| 249 |
+
series = tools.add_constant(series, prepend=True)
|
| 250 |
+
assert_string_equal("const", series.columns[0])
|
| 251 |
+
assert_equal(series.var(axis=0).iloc[0], 0)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def test_pandas_const_df():
|
| 255 |
+
dta = longley.load_pandas().exog
|
| 256 |
+
dta = tools.add_constant(dta, prepend=False)
|
| 257 |
+
assert_string_equal("const", dta.columns[-1])
|
| 258 |
+
assert_equal(dta.var(axis=0).iloc[-1], 0)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def test_pandas_const_df_prepend():
|
| 262 |
+
dta = longley.load_pandas().exog
|
| 263 |
+
# regression test for #1025
|
| 264 |
+
dta["UNEMP"] /= dta["UNEMP"].std()
|
| 265 |
+
dta = tools.add_constant(dta, prepend=True)
|
| 266 |
+
assert_string_equal("const", dta.columns[0])
|
| 267 |
+
assert_equal(dta.var(axis=0).iloc[0], 0)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class TestNanDot:
|
| 271 |
+
@classmethod
|
| 272 |
+
def setup_class(cls):
|
| 273 |
+
nan = np.nan
|
| 274 |
+
cls.mx_1 = np.array([[nan, 1.0], [2.0, 3.0]])
|
| 275 |
+
cls.mx_2 = np.array([[nan, nan], [2.0, 3.0]])
|
| 276 |
+
cls.mx_3 = np.array([[0.0, 0.0], [0.0, 0.0]])
|
| 277 |
+
cls.mx_4 = np.array([[1.0, 0.0], [1.0, 0.0]])
|
| 278 |
+
cls.mx_5 = np.array([[0.0, 1.0], [0.0, 1.0]])
|
| 279 |
+
cls.mx_6 = np.array([[1.0, 2.0], [3.0, 4.0]])
|
| 280 |
+
|
| 281 |
+
def test_11(self):
|
| 282 |
+
test_res = tools.nan_dot(self.mx_1, self.mx_1)
|
| 283 |
+
expected_res = np.array([[np.nan, np.nan], [np.nan, 11.0]])
|
| 284 |
+
assert_array_equal(test_res, expected_res)
|
| 285 |
+
|
| 286 |
+
def test_12(self):
|
| 287 |
+
nan = np.nan
|
| 288 |
+
test_res = tools.nan_dot(self.mx_1, self.mx_2)
|
| 289 |
+
expected_res = np.array([[nan, nan], [nan, nan]])
|
| 290 |
+
assert_array_equal(test_res, expected_res)
|
| 291 |
+
|
| 292 |
+
def test_13(self):
|
| 293 |
+
test_res = tools.nan_dot(self.mx_1, self.mx_3)
|
| 294 |
+
expected_res = np.array([[0.0, 0.0], [0.0, 0.0]])
|
| 295 |
+
assert_array_equal(test_res, expected_res)
|
| 296 |
+
|
| 297 |
+
def test_14(self):
|
| 298 |
+
nan = np.nan
|
| 299 |
+
test_res = tools.nan_dot(self.mx_1, self.mx_4)
|
| 300 |
+
expected_res = np.array([[nan, 0.0], [5.0, 0.0]])
|
| 301 |
+
assert_array_equal(test_res, expected_res)
|
| 302 |
+
|
| 303 |
+
def test_41(self):
|
| 304 |
+
nan = np.nan
|
| 305 |
+
test_res = tools.nan_dot(self.mx_4, self.mx_1)
|
| 306 |
+
expected_res = np.array([[nan, 1.0], [nan, 1.0]])
|
| 307 |
+
assert_array_equal(test_res, expected_res)
|
| 308 |
+
|
| 309 |
+
def test_23(self):
|
| 310 |
+
test_res = tools.nan_dot(self.mx_2, self.mx_3)
|
| 311 |
+
expected_res = np.array([[0.0, 0.0], [0.0, 0.0]])
|
| 312 |
+
assert_array_equal(test_res, expected_res)
|
| 313 |
+
|
| 314 |
+
def test_32(self):
|
| 315 |
+
test_res = tools.nan_dot(self.mx_3, self.mx_2)
|
| 316 |
+
expected_res = np.array([[0.0, 0.0], [0.0, 0.0]])
|
| 317 |
+
assert_array_equal(test_res, expected_res)
|
| 318 |
+
|
| 319 |
+
def test_24(self):
|
| 320 |
+
nan = np.nan
|
| 321 |
+
test_res = tools.nan_dot(self.mx_2, self.mx_4)
|
| 322 |
+
expected_res = np.array([[nan, 0.0], [5.0, 0.0]])
|
| 323 |
+
assert_array_equal(test_res, expected_res)
|
| 324 |
+
|
| 325 |
+
def test_25(self):
|
| 326 |
+
nan = np.nan
|
| 327 |
+
test_res = tools.nan_dot(self.mx_2, self.mx_5)
|
| 328 |
+
expected_res = np.array([[0.0, nan], [0.0, 5.0]])
|
| 329 |
+
assert_array_equal(test_res, expected_res)
|
| 330 |
+
|
| 331 |
+
def test_66(self):
|
| 332 |
+
test_res = tools.nan_dot(self.mx_6, self.mx_6)
|
| 333 |
+
expected_res = np.array([[7.0, 10.0], [15.0, 22.0]])
|
| 334 |
+
assert_array_equal(test_res, expected_res)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class TestEnsure2d:
|
| 338 |
+
@classmethod
|
| 339 |
+
def setup_class(cls):
|
| 340 |
+
x = np.arange(400.0).reshape((100, 4))
|
| 341 |
+
cls.df = pd.DataFrame(x, columns=["a", "b", "c", "d"])
|
| 342 |
+
cls.series = cls.df.iloc[:, 0]
|
| 343 |
+
cls.ndarray = x
|
| 344 |
+
|
| 345 |
+
def test_enfore_numpy(self):
|
| 346 |
+
results = tools._ensure_2d(self.df, True)
|
| 347 |
+
assert_array_equal(results[0], self.ndarray)
|
| 348 |
+
assert_array_equal(results[1], self.df.columns)
|
| 349 |
+
results = tools._ensure_2d(self.series, True)
|
| 350 |
+
assert_array_equal(results[0], self.ndarray[:, [0]])
|
| 351 |
+
assert_array_equal(results[1], self.df.columns[0])
|
| 352 |
+
|
| 353 |
+
def test_pandas(self):
|
| 354 |
+
results = tools._ensure_2d(self.df, False)
|
| 355 |
+
assert_frame_equal(results[0], self.df)
|
| 356 |
+
assert_array_equal(results[1], self.df.columns)
|
| 357 |
+
|
| 358 |
+
results = tools._ensure_2d(self.series, False)
|
| 359 |
+
assert_frame_equal(results[0], self.df.iloc[:, [0]])
|
| 360 |
+
assert_equal(results[1], self.df.columns[0])
|
| 361 |
+
|
| 362 |
+
def test_numpy(self):
|
| 363 |
+
results = tools._ensure_2d(self.ndarray)
|
| 364 |
+
assert_array_equal(results[0], self.ndarray)
|
| 365 |
+
assert_equal(results[1], None)
|
| 366 |
+
|
| 367 |
+
results = tools._ensure_2d(self.ndarray[:, 0])
|
| 368 |
+
assert_array_equal(results[0], self.ndarray[:, [0]])
|
| 369 |
+
assert_equal(results[1], None)
|
shared/package-files/ab/ab56282cd247bfeeefd81cf577f5d21d20d08e22600777ce62a9033a1c7ee57d/blob
ADDED
|
Binary file (29.7 kB). View file
|
|
|
shared/package-files/ab/ab56b130b5df29e4871924951fb08229d5857ed0a2b27cfd5d3f7f84dda43aef/blob
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 max_pool2d(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride={}, at::IntArrayRef padding=0, at::IntArrayRef dilation=1, bool ceil_mode=false);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
shared/package-files/ab/ab5ede532a8e10ad8b25829760b089ab2963faf99a086daf48d32db6aad04d19/blob
ADDED
|
Binary file (760 Bytes). View file
|
|
|
shared/package-files/ab/ab5f25a53347e316db071ba8d939c0ac6007b26a168b35e3cbff28e65e1fa81e/blob
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: platformdirs
|
| 3 |
+
Version: 3.10.0
|
| 4 |
+
Summary: A small Python package for determining appropriate platform-specific dirs, e.g. a "user data dir".
|
| 5 |
+
Project-URL: Documentation, https://platformdirs.readthedocs.io
|
| 6 |
+
Project-URL: Homepage, https://github.com/platformdirs/platformdirs
|
| 7 |
+
Project-URL: Source, https://github.com/platformdirs/platformdirs
|
| 8 |
+
Project-URL: Tracker, https://github.com/platformdirs/platformdirs/issues
|
| 9 |
+
Maintainer-email: Bernát Gábor <gaborjbernat@gmail.com>, Julian Berman <Julian@GrayVines.com>, Ofek Lev <oss@ofek.dev>, Ronny Pfannschmidt <opensource@ronnypfannschmidt.de>
|
| 10 |
+
License-Expression: MIT
|
| 11 |
+
License-File: LICENSE
|
| 12 |
+
Keywords: appdirs,application,cache,directory,log,user
|
| 13 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 14 |
+
Classifier: Intended Audience :: Developers
|
| 15 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 16 |
+
Classifier: Operating System :: OS Independent
|
| 17 |
+
Classifier: Programming Language :: Python
|
| 18 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.7
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 25 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 26 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 27 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 28 |
+
Requires-Python: >=3.7
|
| 29 |
+
Requires-Dist: typing-extensions>=4.7.1; python_version < '3.8'
|
| 30 |
+
Provides-Extra: docs
|
| 31 |
+
Requires-Dist: furo>=2023.7.26; extra == 'docs'
|
| 32 |
+
Requires-Dist: proselint>=0.13; extra == 'docs'
|
| 33 |
+
Requires-Dist: sphinx-autodoc-typehints>=1.24; extra == 'docs'
|
| 34 |
+
Requires-Dist: sphinx>=7.1.1; extra == 'docs'
|
| 35 |
+
Provides-Extra: test
|
| 36 |
+
Requires-Dist: appdirs==1.4.4; extra == 'test'
|
| 37 |
+
Requires-Dist: covdefaults>=2.3; extra == 'test'
|
| 38 |
+
Requires-Dist: pytest-cov>=4.1; extra == 'test'
|
| 39 |
+
Requires-Dist: pytest-mock>=3.11.1; extra == 'test'
|
| 40 |
+
Requires-Dist: pytest>=7.4; extra == 'test'
|
| 41 |
+
Description-Content-Type: text/x-rst
|
| 42 |
+
|
| 43 |
+
The problem
|
| 44 |
+
===========
|
| 45 |
+
|
| 46 |
+
.. image:: https://github.com/platformdirs/platformdirs/workflows/Test/badge.svg
|
| 47 |
+
:target: https://github.com/platformdirs/platformdirs/actions?query=workflow%3ATest
|
| 48 |
+
|
| 49 |
+
When writing desktop application, finding the right location to store user data
|
| 50 |
+
and configuration varies per platform. Even for single-platform apps, there
|
| 51 |
+
may by plenty of nuances in figuring out the right location.
|
| 52 |
+
|
| 53 |
+
For example, if running on macOS, you should use::
|
| 54 |
+
|
| 55 |
+
~/Library/Application Support/<AppName>
|
| 56 |
+
|
| 57 |
+
If on Windows (at least English Win) that should be::
|
| 58 |
+
|
| 59 |
+
C:\Documents and Settings\<User>\Application Data\Local Settings\<AppAuthor>\<AppName>
|
| 60 |
+
|
| 61 |
+
or possibly::
|
| 62 |
+
|
| 63 |
+
C:\Documents and Settings\<User>\Application Data\<AppAuthor>\<AppName>
|
| 64 |
+
|
| 65 |
+
for `roaming profiles <https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-vista/cc766489(v=ws.10)>`_ but that is another story.
|
| 66 |
+
|
| 67 |
+
On Linux (and other Unices), according to the `XDG Basedir Spec`_, it should be::
|
| 68 |
+
|
| 69 |
+
~/.local/share/<AppName>
|
| 70 |
+
|
| 71 |
+
.. _XDG Basedir Spec: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
|
| 72 |
+
|
| 73 |
+
``platformdirs`` to the rescue
|
| 74 |
+
==============================
|
| 75 |
+
|
| 76 |
+
This kind of thing is what the ``platformdirs`` package is for.
|
| 77 |
+
``platformdirs`` will help you choose an appropriate:
|
| 78 |
+
|
| 79 |
+
- user data dir (``user_data_dir``)
|
| 80 |
+
- user config dir (``user_config_dir``)
|
| 81 |
+
- user cache dir (``user_cache_dir``)
|
| 82 |
+
- site data dir (``site_data_dir``)
|
| 83 |
+
- site config dir (``site_config_dir``)
|
| 84 |
+
- user log dir (``user_log_dir``)
|
| 85 |
+
- user documents dir (``user_documents_dir``)
|
| 86 |
+
- user downloads dir (``user_downloads_dir``)
|
| 87 |
+
- user pictures dir (``user_pictures_dir``)
|
| 88 |
+
- user videos dir (``user_videos_dir``)
|
| 89 |
+
- user music dir (``user_music_dir``)
|
| 90 |
+
- user desktop dir (``user_desktop_dir``)
|
| 91 |
+
- user runtime dir (``user_runtime_dir``)
|
| 92 |
+
|
| 93 |
+
And also:
|
| 94 |
+
|
| 95 |
+
- Is slightly opinionated on the directory names used. Look for "OPINION" in
|
| 96 |
+
documentation and code for when an opinion is being applied.
|
| 97 |
+
|
| 98 |
+
Example output
|
| 99 |
+
==============
|
| 100 |
+
|
| 101 |
+
On macOS:
|
| 102 |
+
|
| 103 |
+
.. code-block:: pycon
|
| 104 |
+
|
| 105 |
+
>>> from platformdirs import *
|
| 106 |
+
>>> appname = "SuperApp"
|
| 107 |
+
>>> appauthor = "Acme"
|
| 108 |
+
>>> user_data_dir(appname, appauthor)
|
| 109 |
+
'/Users/trentm/Library/Application Support/SuperApp'
|
| 110 |
+
>>> site_data_dir(appname, appauthor)
|
| 111 |
+
'/Library/Application Support/SuperApp'
|
| 112 |
+
>>> user_cache_dir(appname, appauthor)
|
| 113 |
+
'/Users/trentm/Library/Caches/SuperApp'
|
| 114 |
+
>>> user_log_dir(appname, appauthor)
|
| 115 |
+
'/Users/trentm/Library/Logs/SuperApp'
|
| 116 |
+
>>> user_documents_dir()
|
| 117 |
+
'/Users/trentm/Documents'
|
| 118 |
+
>>> user_downloads_dir()
|
| 119 |
+
'/Users/trentm/Downloads'
|
| 120 |
+
>>> user_pictures_dir()
|
| 121 |
+
'/Users/trentm/Pictures'
|
| 122 |
+
>>> user_videos_dir()
|
| 123 |
+
'/Users/trentm/Movies'
|
| 124 |
+
>>> user_music_dir()
|
| 125 |
+
'/Users/trentm/Music'
|
| 126 |
+
>>> user_desktop_dir()
|
| 127 |
+
'/Users/trentm/Desktop'
|
| 128 |
+
>>> user_runtime_dir(appname, appauthor)
|
| 129 |
+
'/Users/trentm/Library/Caches/TemporaryItems/SuperApp'
|
| 130 |
+
|
| 131 |
+
On Windows:
|
| 132 |
+
|
| 133 |
+
.. code-block:: pycon
|
| 134 |
+
|
| 135 |
+
>>> from platformdirs import *
|
| 136 |
+
>>> appname = "SuperApp"
|
| 137 |
+
>>> appauthor = "Acme"
|
| 138 |
+
>>> user_data_dir(appname, appauthor)
|
| 139 |
+
'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp'
|
| 140 |
+
>>> user_data_dir(appname, appauthor, roaming=True)
|
| 141 |
+
'C:\\Users\\trentm\\AppData\\Roaming\\Acme\\SuperApp'
|
| 142 |
+
>>> user_cache_dir(appname, appauthor)
|
| 143 |
+
'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Cache'
|
| 144 |
+
>>> user_log_dir(appname, appauthor)
|
| 145 |
+
'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Logs'
|
| 146 |
+
>>> user_documents_dir()
|
| 147 |
+
'C:\\Users\\trentm\\Documents'
|
| 148 |
+
>>> user_downloads_dir()
|
| 149 |
+
'C:\\Users\\trentm\\Downloads'
|
| 150 |
+
>>> user_pictures_dir()
|
| 151 |
+
'C:\\Users\\trentm\\Pictures'
|
| 152 |
+
>>> user_videos_dir()
|
| 153 |
+
'C:\\Users\\trentm\\Videos'
|
| 154 |
+
>>> user_music_dir()
|
| 155 |
+
'C:\\Users\\trentm\\Music'
|
| 156 |
+
>>> user_desktop_dir()
|
| 157 |
+
'C:\\Users\\trentm\\Desktop'
|
| 158 |
+
>>> user_runtime_dir(appname, appauthor)
|
| 159 |
+
'C:\\Users\\trentm\\AppData\\Local\\Temp\\Acme\\SuperApp'
|
| 160 |
+
|
| 161 |
+
On Linux:
|
| 162 |
+
|
| 163 |
+
.. code-block:: pycon
|
| 164 |
+
|
| 165 |
+
>>> from platformdirs import *
|
| 166 |
+
>>> appname = "SuperApp"
|
| 167 |
+
>>> appauthor = "Acme"
|
| 168 |
+
>>> user_data_dir(appname, appauthor)
|
| 169 |
+
'/home/trentm/.local/share/SuperApp'
|
| 170 |
+
>>> site_data_dir(appname, appauthor)
|
| 171 |
+
'/usr/local/share/SuperApp'
|
| 172 |
+
>>> site_data_dir(appname, appauthor, multipath=True)
|
| 173 |
+
'/usr/local/share/SuperApp:/usr/share/SuperApp'
|
| 174 |
+
>>> user_cache_dir(appname, appauthor)
|
| 175 |
+
'/home/trentm/.cache/SuperApp'
|
| 176 |
+
>>> user_log_dir(appname, appauthor)
|
| 177 |
+
'/home/trentm/.cache/SuperApp/log'
|
| 178 |
+
>>> user_config_dir(appname)
|
| 179 |
+
'/home/trentm/.config/SuperApp'
|
| 180 |
+
>>> user_documents_dir()
|
| 181 |
+
'/home/trentm/Documents'
|
| 182 |
+
>>> user_downloads_dir()
|
| 183 |
+
'/home/trentm/Downloads'
|
| 184 |
+
>>> user_pictures_dir()
|
| 185 |
+
'/home/trentm/Pictures'
|
| 186 |
+
>>> user_videos_dir()
|
| 187 |
+
'/home/trentm/Videos'
|
| 188 |
+
>>> user_music_dir()
|
| 189 |
+
'/home/trentm/Music'
|
| 190 |
+
>>> user_desktop_dir()
|
| 191 |
+
'/home/trentm/Desktop'
|
| 192 |
+
>>> user_runtime_dir(appname, appauthor)
|
| 193 |
+
'/run/user/{os.getuid()}/SuperApp'
|
| 194 |
+
>>> site_config_dir(appname)
|
| 195 |
+
'/etc/xdg/SuperApp'
|
| 196 |
+
>>> os.environ["XDG_CONFIG_DIRS"] = "/etc:/usr/local/etc"
|
| 197 |
+
>>> site_config_dir(appname, multipath=True)
|
| 198 |
+
'/etc/SuperApp:/usr/local/etc/SuperApp'
|
| 199 |
+
|
| 200 |
+
On Android::
|
| 201 |
+
|
| 202 |
+
>>> from platformdirs import *
|
| 203 |
+
>>> appname = "SuperApp"
|
| 204 |
+
>>> appauthor = "Acme"
|
| 205 |
+
>>> user_data_dir(appname, appauthor)
|
| 206 |
+
'/data/data/com.myApp/files/SuperApp'
|
| 207 |
+
>>> user_cache_dir(appname, appauthor)
|
| 208 |
+
'/data/data/com.myApp/cache/SuperApp'
|
| 209 |
+
>>> user_log_dir(appname, appauthor)
|
| 210 |
+
'/data/data/com.myApp/cache/SuperApp/log'
|
| 211 |
+
>>> user_config_dir(appname)
|
| 212 |
+
'/data/data/com.myApp/shared_prefs/SuperApp'
|
| 213 |
+
>>> user_documents_dir()
|
| 214 |
+
'/storage/emulated/0/Documents'
|
| 215 |
+
>>> user_downloads_dir()
|
| 216 |
+
'/storage/emulated/0/Downloads'
|
| 217 |
+
>>> user_pictures_dir()
|
| 218 |
+
'/storage/emulated/0/Pictures'
|
| 219 |
+
>>> user_videos_dir()
|
| 220 |
+
'/storage/emulated/0/DCIM/Camera'
|
| 221 |
+
>>> user_music_dir()
|
| 222 |
+
'/storage/emulated/0/Music'
|
| 223 |
+
>>> user_desktop_dir()
|
| 224 |
+
'/storage/emulated/0/Desktop'
|
| 225 |
+
>>> user_runtime_dir(appname, appauthor)
|
| 226 |
+
'/data/data/com.myApp/cache/SuperApp/tmp'
|
| 227 |
+
|
| 228 |
+
Note: Some android apps like Termux and Pydroid are used as shells. These
|
| 229 |
+
apps are used by the end user to emulate Linux environment. Presence of
|
| 230 |
+
``SHELL`` environment variable is used by Platformdirs to differentiate
|
| 231 |
+
between general android apps and android apps used as shells. Shell android
|
| 232 |
+
apps also support ``XDG_*`` environment variables.
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
``PlatformDirs`` for convenience
|
| 236 |
+
================================
|
| 237 |
+
|
| 238 |
+
.. code-block:: pycon
|
| 239 |
+
|
| 240 |
+
>>> from platformdirs import PlatformDirs
|
| 241 |
+
>>> dirs = PlatformDirs("SuperApp", "Acme")
|
| 242 |
+
>>> dirs.user_data_dir
|
| 243 |
+
'/Users/trentm/Library/Application Support/SuperApp'
|
| 244 |
+
>>> dirs.site_data_dir
|
| 245 |
+
'/Library/Application Support/SuperApp'
|
| 246 |
+
>>> dirs.user_cache_dir
|
| 247 |
+
'/Users/trentm/Library/Caches/SuperApp'
|
| 248 |
+
>>> dirs.user_log_dir
|
| 249 |
+
'/Users/trentm/Library/Logs/SuperApp'
|
| 250 |
+
>>> dirs.user_documents_dir
|
| 251 |
+
'/Users/trentm/Documents'
|
| 252 |
+
>>> dirs.user_downloads_dir
|
| 253 |
+
'/Users/trentm/Downloads'
|
| 254 |
+
>>> dirs.user_pictures_dir
|
| 255 |
+
'/Users/trentm/Pictures'
|
| 256 |
+
>>> dirs.user_videos_dir
|
| 257 |
+
'/Users/trentm/Movies'
|
| 258 |
+
>>> dirs.user_music_dir
|
| 259 |
+
'/Users/trentm/Music'
|
| 260 |
+
>>> dirs.user_desktop_dir
|
| 261 |
+
'/Users/trentm/Desktop'
|
| 262 |
+
>>> dirs.user_runtime_dir
|
| 263 |
+
'/Users/trentm/Library/Caches/TemporaryItems/SuperApp'
|
| 264 |
+
|
| 265 |
+
Per-version isolation
|
| 266 |
+
=====================
|
| 267 |
+
|
| 268 |
+
If you have multiple versions of your app in use that you want to be
|
| 269 |
+
able to run side-by-side, then you may want version-isolation for these
|
| 270 |
+
dirs::
|
| 271 |
+
|
| 272 |
+
>>> from platformdirs import PlatformDirs
|
| 273 |
+
>>> dirs = PlatformDirs("SuperApp", "Acme", version="1.0")
|
| 274 |
+
>>> dirs.user_data_dir
|
| 275 |
+
'/Users/trentm/Library/Application Support/SuperApp/1.0'
|
| 276 |
+
>>> dirs.site_data_dir
|
| 277 |
+
'/Library/Application Support/SuperApp/1.0'
|
| 278 |
+
>>> dirs.user_cache_dir
|
| 279 |
+
'/Users/trentm/Library/Caches/SuperApp/1.0'
|
| 280 |
+
>>> dirs.user_log_dir
|
| 281 |
+
'/Users/trentm/Library/Logs/SuperApp/1.0'
|
| 282 |
+
>>> dirs.user_documents_dir
|
| 283 |
+
'/Users/trentm/Documents'
|
| 284 |
+
>>> dirs.user_downloads_dir
|
| 285 |
+
'/Users/trentm/Downloads'
|
| 286 |
+
>>> dirs.user_pictures_dir
|
| 287 |
+
'/Users/trentm/Pictures'
|
| 288 |
+
>>> dirs.user_videos_dir
|
| 289 |
+
'/Users/trentm/Movies'
|
| 290 |
+
>>> dirs.user_music_dir
|
| 291 |
+
'/Users/trentm/Music'
|
| 292 |
+
>>> dirs.user_desktop_dir
|
| 293 |
+
'/Users/trentm/Desktop'
|
| 294 |
+
>>> dirs.user_runtime_dir
|
| 295 |
+
'/Users/trentm/Library/Caches/TemporaryItems/SuperApp/1.0'
|
| 296 |
+
|
| 297 |
+
Be wary of using this for configuration files though; you'll need to handle
|
| 298 |
+
migrating configuration files manually.
|
| 299 |
+
|
| 300 |
+
Why this Fork?
|
| 301 |
+
==============
|
| 302 |
+
|
| 303 |
+
This repository is a friendly fork of the wonderful work started by
|
| 304 |
+
`ActiveState <https://github.com/ActiveState/appdirs>`_ who created
|
| 305 |
+
``appdirs``, this package's ancestor.
|
| 306 |
+
|
| 307 |
+
Maintaining an open source project is no easy task, particularly
|
| 308 |
+
from within an organization, and the Python community is indebted
|
| 309 |
+
to ``appdirs`` (and to Trent Mick and Jeff Rouse in particular) for
|
| 310 |
+
creating an incredibly useful simple module, as evidenced by the wide
|
| 311 |
+
number of users it has attracted over the years.
|
| 312 |
+
|
| 313 |
+
Nonetheless, given the number of long-standing open issues
|
| 314 |
+
and pull requests, and no clear path towards `ensuring
|
| 315 |
+
that maintenance of the package would continue or grow
|
| 316 |
+
<https://github.com/ActiveState/appdirs/issues/79>`_, this fork was
|
| 317 |
+
created.
|
| 318 |
+
|
| 319 |
+
Contributions are most welcome.
|
shared/package-files/ab/ab62247474c5955df8aab42590e2f5049ae8b06fb86b5d2fc410dcc9047f8878/blob
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#ifndef NUMBA_NRT_EXTERNAL_H_
|
| 2 |
+
#define NUMBA_NRT_EXTERNAL_H_
|
| 3 |
+
|
| 4 |
+
#include <stdlib.h>
|
| 5 |
+
|
| 6 |
+
typedef struct MemInfo NRT_MemInfo;
|
| 7 |
+
|
| 8 |
+
typedef void NRT_managed_dtor(void *data);
|
| 9 |
+
|
| 10 |
+
typedef void *(*NRT_external_malloc_func)(size_t size, void *opaque_data);
|
| 11 |
+
typedef void *(*NRT_external_realloc_func)(void *ptr, size_t new_size, void *opaque_data);
|
| 12 |
+
typedef void (*NRT_external_free_func)(void *ptr, void *opaque_data);
|
| 13 |
+
|
| 14 |
+
struct ExternalMemAllocator {
|
| 15 |
+
NRT_external_malloc_func malloc;
|
| 16 |
+
NRT_external_realloc_func realloc;
|
| 17 |
+
NRT_external_free_func free;
|
| 18 |
+
void *opaque_data;
|
| 19 |
+
};
|
| 20 |
+
|
| 21 |
+
typedef struct ExternalMemAllocator NRT_ExternalAllocator;
|
| 22 |
+
|
| 23 |
+
typedef struct {
|
| 24 |
+
/* Methods to create MemInfos.
|
| 25 |
+
|
| 26 |
+
MemInfos are like smart pointers for objects that are managed by the Numba.
|
| 27 |
+
*/
|
| 28 |
+
|
| 29 |
+
/* Allocate memory
|
| 30 |
+
|
| 31 |
+
*nbytes* is the number of bytes to be allocated
|
| 32 |
+
|
| 33 |
+
Returning a new reference.
|
| 34 |
+
*/
|
| 35 |
+
NRT_MemInfo* (*allocate)(size_t nbytes);
|
| 36 |
+
/* Allocates memory using an external allocator but still using Numba's MemInfo.
|
| 37 |
+
*
|
| 38 |
+
* NOTE: An externally provided allocator must behave the same way as C99
|
| 39 |
+
* stdlib.h's "malloc" function with respect to return value
|
| 40 |
+
* (including the behaviour that occurs when requesting an allocation
|
| 41 |
+
* of size 0 bytes).
|
| 42 |
+
*/
|
| 43 |
+
NRT_MemInfo* (*allocate_external)(size_t nbytes, NRT_ExternalAllocator *allocator);
|
| 44 |
+
|
| 45 |
+
/* Convert externally allocated memory into a MemInfo.
|
| 46 |
+
|
| 47 |
+
*data* is the memory pointer
|
| 48 |
+
*dtor* is the deallocator of the memory
|
| 49 |
+
*/
|
| 50 |
+
NRT_MemInfo* (*manage_memory)(void *data, NRT_managed_dtor dtor);
|
| 51 |
+
|
| 52 |
+
/* Acquire a reference */
|
| 53 |
+
void (*acquire)(NRT_MemInfo* mi);
|
| 54 |
+
|
| 55 |
+
/* Release a reference */
|
| 56 |
+
void (*release)(NRT_MemInfo* mi);
|
| 57 |
+
|
| 58 |
+
/* Get MemInfo data pointer */
|
| 59 |
+
void* (*get_data)(NRT_MemInfo* mi);
|
| 60 |
+
|
| 61 |
+
} NRT_api_functions;
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
#endif /* NUMBA_NRT_EXTERNAL_H_ */
|
shared/package-files/ab/ab6258127aa652aefcacef27a3d857419ddf73746ec4fad109ca6c2ebba8bc38/blob
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Various made-up tests to hit different branches of the code in specfun.c
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from numpy.testing import assert_allclose
|
| 7 |
+
from scipy import special
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_cva2_cv0_branches():
|
| 11 |
+
res, resp = special.mathieu_cem([40, 129], [13, 14], [30, 45])
|
| 12 |
+
assert_allclose(res, np.array([-0.3741211, 0.74441928]))
|
| 13 |
+
assert_allclose(resp, np.array([-37.02872758, -86.13549877]))
|
| 14 |
+
|
| 15 |
+
res, resp = special.mathieu_sem([40, 129], [13, 14], [30, 45])
|
| 16 |
+
assert_allclose(res, np.array([0.92955551, 0.66771207]))
|
| 17 |
+
assert_allclose(resp, np.array([-14.91073448, 96.02954185]))
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def test_chgm_branches():
|
| 21 |
+
res = special.eval_genlaguerre(-3.2, 3, 2.5)
|
| 22 |
+
assert_allclose(res, -0.7077721935779854)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_hygfz_branches():
|
| 26 |
+
"""(z == 1.0) && (c-a-b > 0.0)"""
|
| 27 |
+
res = special.hyp2f1(1.5, 2.5, 4.5, 1.+0.j)
|
| 28 |
+
assert_allclose(res, 10.30835089459151+0j)
|
| 29 |
+
"""(cabs(z+1) < eps) && (fabs(c-a+b - 1.0) < eps)"""
|
| 30 |
+
res = special.hyp2f1(5+5e-16, 2, 2, -1.0 + 5e-16j)
|
| 31 |
+
assert_allclose(res, 0.031249999999999986+3.9062499999999994e-17j)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_pro_rad1():
|
| 35 |
+
# https://github.com/scipy/scipy/issues/21058
|
| 36 |
+
# Reference values taken from WolframAlpha
|
| 37 |
+
# SpheroidalS1(1, 1, 30, 1.1)
|
| 38 |
+
# SpheroidalS1Prime(1, 1, 30, 1.1)
|
| 39 |
+
res = special.pro_rad1(1, 1, 30, 1.1)
|
| 40 |
+
assert_allclose(res, (0.009657872296166435, 3.253369651472877), rtol=2e-5)
|
| 41 |
+
|
| 42 |
+
def test_pro_rad2():
|
| 43 |
+
# https://github.com/scipy/scipy/issues/21461
|
| 44 |
+
# Reference values taken from WolframAlpha
|
| 45 |
+
# SpheroidalS2(0, 0, 3, 1.02)
|
| 46 |
+
# SpheroidalS2Prime(0, 0, 3, 1.02)
|
| 47 |
+
res = special.pro_rad2(0, 0, 3, 1.02)
|
| 48 |
+
assert_allclose(res, (-0.35089596858528077, 13.652764213480872), rtol=10e-10)
|
shared/package-files/ab/ab656e5e6759a61c81d95347eaa4a70cc59262878f291b267e08ba5b4f675f7d/blob
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# menu.tcl --
|
| 2 |
+
#
|
| 3 |
+
# This file defines the default bindings for Tk menus and menubuttons.
|
| 4 |
+
# It also implements keyboard traversal of menus and implements a few
|
| 5 |
+
# other utility procedures related to menus.
|
| 6 |
+
#
|
| 7 |
+
# Copyright (c) 1992-1994 The Regents of the University of California.
|
| 8 |
+
# Copyright (c) 1994-1997 Sun Microsystems, Inc.
|
| 9 |
+
# Copyright (c) 1998-1999 Scriptics Corporation.
|
| 10 |
+
# Copyright (c) 2007 Daniel A. Steffen <das@users.sourceforge.net>
|
| 11 |
+
#
|
| 12 |
+
# See the file "license.terms" for information on usage and redistribution
|
| 13 |
+
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
|
| 14 |
+
#
|
| 15 |
+
|
| 16 |
+
#-------------------------------------------------------------------------
|
| 17 |
+
# Elements of tk::Priv that are used in this file:
|
| 18 |
+
#
|
| 19 |
+
# cursor - Saves the -cursor option for the posted menubutton.
|
| 20 |
+
# focus - Saves the focus during a menu selection operation.
|
| 21 |
+
# Focus gets restored here when the menu is unposted.
|
| 22 |
+
# grabGlobal - Used in conjunction with tk::Priv(oldGrab): if
|
| 23 |
+
# tk::Priv(oldGrab) is non-empty, then tk::Priv(grabGlobal)
|
| 24 |
+
# contains either an empty string or "-global" to
|
| 25 |
+
# indicate whether the old grab was a local one or
|
| 26 |
+
# a global one.
|
| 27 |
+
# inMenubutton - The name of the menubutton widget containing
|
| 28 |
+
# the mouse, or an empty string if the mouse is
|
| 29 |
+
# not over any menubutton.
|
| 30 |
+
# menuBar - The name of the menubar that is the root
|
| 31 |
+
# of the cascade hierarchy which is currently
|
| 32 |
+
# posted. This is null when there is no menu currently
|
| 33 |
+
# being pulled down from a menu bar.
|
| 34 |
+
# oldGrab - Window that had the grab before a menu was posted.
|
| 35 |
+
# Used to restore the grab state after the menu
|
| 36 |
+
# is unposted. Empty string means there was no
|
| 37 |
+
# grab previously set.
|
| 38 |
+
# popup - If a menu has been popped up via tk_popup, this
|
| 39 |
+
# gives the name of the menu. Otherwise this
|
| 40 |
+
# value is empty.
|
| 41 |
+
# postedMb - Name of the menubutton whose menu is currently
|
| 42 |
+
# posted, or an empty string if nothing is posted
|
| 43 |
+
# A grab is set on this widget.
|
| 44 |
+
# relief - Used to save the original relief of the current
|
| 45 |
+
# menubutton.
|
| 46 |
+
# window - When the mouse is over a menu, this holds the
|
| 47 |
+
# name of the menu; it's cleared when the mouse
|
| 48 |
+
# leaves the menu.
|
| 49 |
+
# tearoff - Whether the last menu posted was a tearoff or not.
|
| 50 |
+
# This is true always for unix, for tearoffs for Mac
|
| 51 |
+
# and Windows.
|
| 52 |
+
# activeMenu - This is the last active menu for use
|
| 53 |
+
# with the <<MenuSelect>> virtual event.
|
| 54 |
+
# activeItem - This is the last active menu item for
|
| 55 |
+
# use with the <<MenuSelect>> virtual event.
|
| 56 |
+
#-------------------------------------------------------------------------
|
| 57 |
+
|
| 58 |
+
#-------------------------------------------------------------------------
|
| 59 |
+
# Overall note:
|
| 60 |
+
# This file is tricky because there are five different ways that menus
|
| 61 |
+
# can be used:
|
| 62 |
+
#
|
| 63 |
+
# 1. As a pulldown from a menubutton. In this style, the variable
|
| 64 |
+
# tk::Priv(postedMb) identifies the posted menubutton.
|
| 65 |
+
# 2. As a torn-off menu copied from some other menu. In this style
|
| 66 |
+
# tk::Priv(postedMb) is empty, and menu's type is "tearoff".
|
| 67 |
+
# 3. As an option menu, triggered from an option menubutton. In this
|
| 68 |
+
# style tk::Priv(postedMb) identifies the posted menubutton.
|
| 69 |
+
# 4. As a popup menu. In this style tk::Priv(postedMb) is empty and
|
| 70 |
+
# the top-level menu's type is "normal".
|
| 71 |
+
# 5. As a pulldown from a menubar. The variable tk::Priv(menubar) has
|
| 72 |
+
# the owning menubar, and the menu itself is of type "normal".
|
| 73 |
+
#
|
| 74 |
+
# The various binding procedures use the state described above to
|
| 75 |
+
# distinguish the various cases and take different actions in each
|
| 76 |
+
# case.
|
| 77 |
+
#-------------------------------------------------------------------------
|
| 78 |
+
|
| 79 |
+
#-------------------------------------------------------------------------
|
| 80 |
+
# The code below creates the default class bindings for menus
|
| 81 |
+
# and menubuttons.
|
| 82 |
+
#-------------------------------------------------------------------------
|
| 83 |
+
|
| 84 |
+
bind Menubutton <FocusIn> {}
|
| 85 |
+
bind Menubutton <Enter> {
|
| 86 |
+
tk::MbEnter %W
|
| 87 |
+
}
|
| 88 |
+
bind Menubutton <Leave> {
|
| 89 |
+
tk::MbLeave %W
|
| 90 |
+
}
|
| 91 |
+
bind Menubutton <1> {
|
| 92 |
+
if {$tk::Priv(inMenubutton) ne ""} {
|
| 93 |
+
tk::MbPost $tk::Priv(inMenubutton) %X %Y
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
bind Menubutton <Motion> {
|
| 97 |
+
tk::MbMotion %W up %X %Y
|
| 98 |
+
}
|
| 99 |
+
bind Menubutton <B1-Motion> {
|
| 100 |
+
tk::MbMotion %W down %X %Y
|
| 101 |
+
}
|
| 102 |
+
bind Menubutton <ButtonRelease-1> {
|
| 103 |
+
tk::MbButtonUp %W
|
| 104 |
+
}
|
| 105 |
+
bind Menubutton <space> {
|
| 106 |
+
tk::MbPost %W
|
| 107 |
+
tk::MenuFirstEntry [%W cget -menu]
|
| 108 |
+
}
|
| 109 |
+
bind Menubutton <<Invoke>> {
|
| 110 |
+
tk::MbPost %W
|
| 111 |
+
tk::MenuFirstEntry [%W cget -menu]
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
# Must set focus when mouse enters a menu, in order to allow
|
| 115 |
+
# mixed-mode processing using both the mouse and the keyboard.
|
| 116 |
+
# Don't set the focus if the event comes from a grab release,
|
| 117 |
+
# though: such an event can happen after as part of unposting
|
| 118 |
+
# a cascaded chain of menus, after the focus has already been
|
| 119 |
+
# restored to wherever it was before menu selection started.
|
| 120 |
+
|
| 121 |
+
bind Menu <FocusIn> {}
|
| 122 |
+
|
| 123 |
+
bind Menu <Enter> {
|
| 124 |
+
set tk::Priv(window) %W
|
| 125 |
+
if {[%W cget -type] eq "tearoff"} {
|
| 126 |
+
if {"%m" ne "NotifyUngrab"} {
|
| 127 |
+
if {[tk windowingsystem] eq "x11"} {
|
| 128 |
+
tk_menuSetFocus %W
|
| 129 |
+
}
|
| 130 |
+
}
|
| 131 |
+
}
|
| 132 |
+
tk::MenuMotion %W %x %y %s
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
bind Menu <Leave> {
|
| 136 |
+
tk::MenuLeave %W %X %Y %s
|
| 137 |
+
}
|
| 138 |
+
bind Menu <Motion> {
|
| 139 |
+
tk::MenuMotion %W %x %y %s
|
| 140 |
+
}
|
| 141 |
+
bind Menu <Button> {
|
| 142 |
+
tk::MenuButtonDown %W
|
| 143 |
+
}
|
| 144 |
+
bind Menu <ButtonRelease> {
|
| 145 |
+
tk::MenuInvoke %W 1
|
| 146 |
+
}
|
| 147 |
+
bind Menu <space> {
|
| 148 |
+
tk::MenuInvoke %W 0
|
| 149 |
+
}
|
| 150 |
+
bind Menu <<Invoke>> {
|
| 151 |
+
tk::MenuInvoke %W 0
|
| 152 |
+
}
|
| 153 |
+
bind Menu <Return> {
|
| 154 |
+
tk::MenuInvoke %W 0
|
| 155 |
+
}
|
| 156 |
+
bind Menu <Escape> {
|
| 157 |
+
tk::MenuEscape %W
|
| 158 |
+
}
|
| 159 |
+
bind Menu <<PrevChar>> {
|
| 160 |
+
tk::MenuLeftArrow %W
|
| 161 |
+
}
|
| 162 |
+
bind Menu <<NextChar>> {
|
| 163 |
+
tk::MenuRightArrow %W
|
| 164 |
+
}
|
| 165 |
+
bind Menu <<PrevLine>> {
|
| 166 |
+
tk::MenuUpArrow %W
|
| 167 |
+
}
|
| 168 |
+
bind Menu <<NextLine>> {
|
| 169 |
+
tk::MenuDownArrow %W
|
| 170 |
+
}
|
| 171 |
+
bind Menu <KeyPress> {
|
| 172 |
+
tk::TraverseWithinMenu %W %A
|
| 173 |
+
break
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
# The following bindings apply to all windows, and are used to
|
| 177 |
+
# implement keyboard menu traversal.
|
| 178 |
+
|
| 179 |
+
if {[tk windowingsystem] eq "x11"} {
|
| 180 |
+
bind all <Alt-KeyPress> {
|
| 181 |
+
tk::TraverseToMenu %W %A
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
bind all <F10> {
|
| 185 |
+
tk::FirstMenu %W
|
| 186 |
+
}
|
| 187 |
+
} else {
|
| 188 |
+
bind Menubutton <Alt-KeyPress> {
|
| 189 |
+
tk::TraverseToMenu %W %A
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
bind Menubutton <F10> {
|
| 193 |
+
tk::FirstMenu %W
|
| 194 |
+
}
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
# ::tk::MbEnter --
|
| 198 |
+
# This procedure is invoked when the mouse enters a menubutton
|
| 199 |
+
# widget. It activates the widget unless it is disabled. Note:
|
| 200 |
+
# this procedure is only invoked when mouse button 1 is *not* down.
|
| 201 |
+
# The procedure ::tk::MbB1Enter is invoked if the button is down.
|
| 202 |
+
#
|
| 203 |
+
# Arguments:
|
| 204 |
+
# w - The name of the widget.
|
| 205 |
+
|
| 206 |
+
proc ::tk::MbEnter w {
|
| 207 |
+
variable ::tk::Priv
|
| 208 |
+
|
| 209 |
+
if {$Priv(inMenubutton) ne ""} {
|
| 210 |
+
MbLeave $Priv(inMenubutton)
|
| 211 |
+
}
|
| 212 |
+
set Priv(inMenubutton) $w
|
| 213 |
+
if {[$w cget -state] ne "disabled" && [tk windowingsystem] ne "aqua"} {
|
| 214 |
+
$w configure -state active
|
| 215 |
+
}
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
# ::tk::MbLeave --
|
| 219 |
+
# This procedure is invoked when the mouse leaves a menubutton widget.
|
| 220 |
+
# It de-activates the widget, if the widget still exists.
|
| 221 |
+
#
|
| 222 |
+
# Arguments:
|
| 223 |
+
# w - The name of the widget.
|
| 224 |
+
|
| 225 |
+
proc ::tk::MbLeave w {
|
| 226 |
+
variable ::tk::Priv
|
| 227 |
+
|
| 228 |
+
set Priv(inMenubutton) {}
|
| 229 |
+
if {![winfo exists $w]} {
|
| 230 |
+
return
|
| 231 |
+
}
|
| 232 |
+
if {[$w cget -state] eq "active" && [tk windowingsystem] ne "aqua"} {
|
| 233 |
+
$w configure -state normal
|
| 234 |
+
}
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
# ::tk::MbPost --
|
| 239 |
+
# Given a menubutton, this procedure does all the work of posting
|
| 240 |
+
# its associated menu and unposting any other menu that is currently
|
| 241 |
+
# posted.
|
| 242 |
+
#
|
| 243 |
+
# Arguments:
|
| 244 |
+
# w - The name of the menubutton widget whose menu
|
| 245 |
+
# is to be posted.
|
| 246 |
+
# x, y - Root coordinates of cursor, used for positioning
|
| 247 |
+
# option menus. If not specified, then the center
|
| 248 |
+
# of the menubutton is used for an option menu.
|
| 249 |
+
|
| 250 |
+
proc ::tk::MbPost {w {x {}} {y {}}} {
|
| 251 |
+
global errorInfo
|
| 252 |
+
variable ::tk::Priv
|
| 253 |
+
|
| 254 |
+
if {[$w cget -state] eq "disabled" || $w eq $Priv(postedMb)} {
|
| 255 |
+
return
|
| 256 |
+
}
|
| 257 |
+
set menu [$w cget -menu]
|
| 258 |
+
if {$menu eq ""} {
|
| 259 |
+
return
|
| 260 |
+
}
|
| 261 |
+
set tearoff [expr {[tk windowingsystem] eq "x11" \
|
| 262 |
+
|| [$menu cget -type] eq "tearoff"}]
|
| 263 |
+
if {[string first $w $menu] != 0} {
|
| 264 |
+
return -code error -errorcode {TK MENUBUTTON POST_NONCHILD} \
|
| 265 |
+
"can't post $menu: it isn't a descendant of $w"
|
| 266 |
+
}
|
| 267 |
+
set cur $Priv(postedMb)
|
| 268 |
+
if {$cur ne ""} {
|
| 269 |
+
MenuUnpost {}
|
| 270 |
+
}
|
| 271 |
+
if {$::tk_strictMotif} {
|
| 272 |
+
set Priv(cursor) [$w cget -cursor]
|
| 273 |
+
$w configure -cursor arrow
|
| 274 |
+
}
|
| 275 |
+
if {[tk windowingsystem] ne "aqua"} {
|
| 276 |
+
set Priv(relief) [$w cget -relief]
|
| 277 |
+
$w configure -relief raised
|
| 278 |
+
} else {
|
| 279 |
+
$w configure -state active
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
set Priv(postedMb) $w
|
| 283 |
+
set Priv(focus) [focus]
|
| 284 |
+
$menu activate none
|
| 285 |
+
GenerateMenuSelect $menu
|
| 286 |
+
update idletasks
|
| 287 |
+
|
| 288 |
+
if {[catch {PostMenubuttonMenu $w $menu} msg opt]} {
|
| 289 |
+
# Error posting menu (e.g. bogus -postcommand). Unpost it and
|
| 290 |
+
# reflect the error.
|
| 291 |
+
MenuUnpost {}
|
| 292 |
+
return -options $opt $msg
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
set Priv(tearoff) $tearoff
|
| 296 |
+
if {$tearoff != 0 && [tk windowingsystem] ne "aqua"} {
|
| 297 |
+
focus $menu
|
| 298 |
+
if {[winfo viewable $w]} {
|
| 299 |
+
SaveGrabInfo $w
|
| 300 |
+
grab -global $w
|
| 301 |
+
}
|
| 302 |
+
}
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
# ::tk::MenuUnpost --
|
| 306 |
+
# This procedure unposts a given menu, plus all of its ancestors up
|
| 307 |
+
# to (and including) a menubutton, if any. It also restores various
|
| 308 |
+
# values to what they were before the menu was posted, and releases
|
| 309 |
+
# a grab if there's a menubutton involved. Special notes:
|
| 310 |
+
# 1. It's important to unpost all menus before releasing the grab, so
|
| 311 |
+
# that any Enter-Leave events (e.g. from menu back to main
|
| 312 |
+
# application) have mode NotifyGrab.
|
| 313 |
+
# 2. Be sure to enclose various groups of commands in "catch" so that
|
| 314 |
+
# the procedure will complete even if the menubutton or the menu
|
| 315 |
+
# or the grab window has been deleted.
|
| 316 |
+
#
|
| 317 |
+
# Arguments:
|
| 318 |
+
# menu - Name of a menu to unpost. Ignored if there
|
| 319 |
+
# is a posted menubutton.
|
| 320 |
+
|
| 321 |
+
proc ::tk::MenuUnpost menu {
|
| 322 |
+
variable ::tk::Priv
|
| 323 |
+
set mb $Priv(postedMb)
|
| 324 |
+
|
| 325 |
+
# Restore focus right away (otherwise X will take focus away when
|
| 326 |
+
# the menu is unmapped and under some window managers (e.g. olvwm)
|
| 327 |
+
# we'll lose the focus completely).
|
| 328 |
+
|
| 329 |
+
catch {focus $Priv(focus)}
|
| 330 |
+
set Priv(focus) ""
|
| 331 |
+
|
| 332 |
+
# Unpost menu(s) and restore some stuff that's dependent on
|
| 333 |
+
# what was posted.
|
| 334 |
+
|
| 335 |
+
after cancel [array get Priv menuActivatedTimer]
|
| 336 |
+
unset -nocomplain Priv(menuActivated)
|
| 337 |
+
after cancel [array get Priv menuDeactivatedTimer]
|
| 338 |
+
unset -nocomplain Priv(menuDeactivated)
|
| 339 |
+
|
| 340 |
+
catch {
|
| 341 |
+
if {$mb ne ""} {
|
| 342 |
+
set menu [$mb cget -menu]
|
| 343 |
+
$menu unpost
|
| 344 |
+
set Priv(postedMb) {}
|
| 345 |
+
if {$::tk_strictMotif} {
|
| 346 |
+
$mb configure -cursor $Priv(cursor)
|
| 347 |
+
}
|
| 348 |
+
if {[tk windowingsystem] ne "aqua"} {
|
| 349 |
+
$mb configure -relief $Priv(relief)
|
| 350 |
+
} else {
|
| 351 |
+
$mb configure -state normal
|
| 352 |
+
}
|
| 353 |
+
} elseif {$Priv(popup) ne ""} {
|
| 354 |
+
$Priv(popup) unpost
|
| 355 |
+
set Priv(popup) {}
|
| 356 |
+
} elseif {[$menu cget -type] ne "menubar" && [$menu cget -type] ne "tearoff"} {
|
| 357 |
+
# We're in a cascaded sub-menu from a torn-off menu or popup.
|
| 358 |
+
# Unpost all the menus up to the toplevel one (but not
|
| 359 |
+
# including the top-level torn-off one) and deactivate the
|
| 360 |
+
# top-level torn off menu if there is one.
|
| 361 |
+
|
| 362 |
+
while {1} {
|
| 363 |
+
set parent [winfo parent $menu]
|
| 364 |
+
if {[winfo class $parent] ne "Menu" || ![winfo ismapped $parent]} {
|
| 365 |
+
break
|
| 366 |
+
}
|
| 367 |
+
$parent activate none
|
| 368 |
+
$parent postcascade none
|
| 369 |
+
GenerateMenuSelect $parent
|
| 370 |
+
set type [$parent cget -type]
|
| 371 |
+
if {$type eq "menubar" || $type eq "tearoff"} {
|
| 372 |
+
break
|
| 373 |
+
}
|
| 374 |
+
set menu $parent
|
| 375 |
+
}
|
| 376 |
+
if {[$menu cget -type] ne "menubar"} {
|
| 377 |
+
$menu unpost
|
| 378 |
+
}
|
| 379 |
+
}
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
if {($Priv(tearoff) != 0) || $Priv(menuBar) ne ""} {
|
| 383 |
+
# Release grab, if any, and restore the previous grab, if there
|
| 384 |
+
# was one.
|
| 385 |
+
if {$menu ne ""} {
|
| 386 |
+
set grab [grab current $menu]
|
| 387 |
+
if {$grab ne ""} {
|
| 388 |
+
grab release $grab
|
| 389 |
+
}
|
| 390 |
+
}
|
| 391 |
+
RestoreOldGrab
|
| 392 |
+
if {$Priv(menuBar) ne ""} {
|
| 393 |
+
if {$::tk_strictMotif} {
|
| 394 |
+
$Priv(menuBar) configure -cursor $Priv(cursor)
|
| 395 |
+
}
|
| 396 |
+
set Priv(menuBar) {}
|
| 397 |
+
}
|
| 398 |
+
if {[tk windowingsystem] ne "x11"} {
|
| 399 |
+
set Priv(tearoff) 0
|
| 400 |
+
}
|
| 401 |
+
}
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
# ::tk::MbMotion --
|
| 405 |
+
# This procedure handles mouse motion events inside menubuttons, and
|
| 406 |
+
# also outside menubuttons when a menubutton has a grab (e.g. when a
|
| 407 |
+
# menu selection operation is in progress).
|
| 408 |
+
#
|
| 409 |
+
# Arguments:
|
| 410 |
+
# w - The name of the menubutton widget.
|
| 411 |
+
# upDown - "down" means button 1 is pressed, "up" means
|
| 412 |
+
# it isn't.
|
| 413 |
+
# rootx, rooty - Coordinates of mouse, in (virtual?) root window.
|
| 414 |
+
|
| 415 |
+
proc ::tk::MbMotion {w upDown rootx rooty} {
|
| 416 |
+
variable ::tk::Priv
|
| 417 |
+
|
| 418 |
+
if {$Priv(inMenubutton) eq $w} {
|
| 419 |
+
return
|
| 420 |
+
}
|
| 421 |
+
set new [winfo containing $rootx $rooty]
|
| 422 |
+
if {$new ne $Priv(inMenubutton) \
|
| 423 |
+
&& ($new eq "" || [winfo toplevel $new] eq [winfo toplevel $w])} {
|
| 424 |
+
if {$Priv(inMenubutton) ne ""} {
|
| 425 |
+
MbLeave $Priv(inMenubutton)
|
| 426 |
+
}
|
| 427 |
+
if {$new ne "" \
|
| 428 |
+
&& [winfo class $new] eq "Menubutton" \
|
| 429 |
+
&& ([$new cget -indicatoron] == 0) \
|
| 430 |
+
&& ([$w cget -indicatoron] == 0)} {
|
| 431 |
+
if {$upDown eq "down"} {
|
| 432 |
+
MbPost $new $rootx $rooty
|
| 433 |
+
} else {
|
| 434 |
+
MbEnter $new
|
| 435 |
+
}
|
| 436 |
+
}
|
| 437 |
+
}
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
# ::tk::MbButtonUp --
|
| 441 |
+
# This procedure is invoked to handle button 1 releases for menubuttons.
|
| 442 |
+
# If the release happens inside the menubutton then leave its menu
|
| 443 |
+
# posted with element 0 activated. Otherwise, unpost the menu.
|
| 444 |
+
#
|
| 445 |
+
# Arguments:
|
| 446 |
+
# w - The name of the menubutton widget.
|
| 447 |
+
|
| 448 |
+
proc ::tk::MbButtonUp w {
|
| 449 |
+
variable ::tk::Priv
|
| 450 |
+
|
| 451 |
+
set menu [$w cget -menu]
|
| 452 |
+
set tearoff [expr {[tk windowingsystem] eq "x11" || \
|
| 453 |
+
($menu ne "" && [$menu cget -type] eq "tearoff")}]
|
| 454 |
+
if {($tearoff != 0) && $Priv(postedMb) eq $w \
|
| 455 |
+
&& $Priv(inMenubutton) eq $w} {
|
| 456 |
+
MenuFirstEntry [$Priv(postedMb) cget -menu]
|
| 457 |
+
} else {
|
| 458 |
+
MenuUnpost {}
|
| 459 |
+
}
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
# ::tk::MenuMotion --
|
| 463 |
+
# This procedure is called to handle mouse motion events for menus.
|
| 464 |
+
# It does two things. First, it resets the active element in the
|
| 465 |
+
# menu, if the mouse is over the menu. Second, if a mouse button
|
| 466 |
+
# is down, it posts and unposts cascade entries to match the mouse
|
| 467 |
+
# position.
|
| 468 |
+
#
|
| 469 |
+
# Arguments:
|
| 470 |
+
# menu - The menu window.
|
| 471 |
+
# x - The x position of the mouse.
|
| 472 |
+
# y - The y position of the mouse.
|
| 473 |
+
# state - Modifier state (tells whether buttons are down).
|
| 474 |
+
|
| 475 |
+
proc ::tk::MenuMotion {menu x y state} {
|
| 476 |
+
variable ::tk::Priv
|
| 477 |
+
if {$menu eq $Priv(window)} {
|
| 478 |
+
set active [$menu index active]
|
| 479 |
+
if {[$menu cget -type] eq "menubar"} {
|
| 480 |
+
if {[info exists Priv(focus)] && $menu ne $Priv(focus)} {
|
| 481 |
+
$menu activate @$x,$y
|
| 482 |
+
GenerateMenuSelect $menu
|
| 483 |
+
}
|
| 484 |
+
} else {
|
| 485 |
+
$menu activate @$x,$y
|
| 486 |
+
GenerateMenuSelect $menu
|
| 487 |
+
}
|
| 488 |
+
set index [$menu index @$x,$y]
|
| 489 |
+
if {[info exists Priv(menuActivated)] \
|
| 490 |
+
&& $index ne "none" \
|
| 491 |
+
&& $index ne $active} {
|
| 492 |
+
set mode [option get $menu clickToFocus ClickToFocus]
|
| 493 |
+
if {[string is false $mode]} {
|
| 494 |
+
set delay [expr {[$menu cget -type] eq "menubar" ? 0 : 50}]
|
| 495 |
+
if {[$menu type $index] eq "cascade"} {
|
| 496 |
+
# Catch these postcascade commands since the menu could be
|
| 497 |
+
# destroyed before they run.
|
| 498 |
+
set Priv(menuActivatedTimer) \
|
| 499 |
+
[after $delay "catch {$menu postcascade active}"]
|
| 500 |
+
} else {
|
| 501 |
+
set Priv(menuDeactivatedTimer) \
|
| 502 |
+
[after $delay "catch {$menu postcascade none}"]
|
| 503 |
+
}
|
| 504 |
+
}
|
| 505 |
+
}
|
| 506 |
+
}
|
| 507 |
+
}
|
| 508 |
+
|
| 509 |
+
# ::tk::MenuButtonDown --
|
| 510 |
+
# Handles button presses in menus. There are a couple of tricky things
|
| 511 |
+
# here:
|
| 512 |
+
# 1. Change the posted cascade entry (if any) to match the mouse position.
|
| 513 |
+
# 2. If there is a posted menubutton, must grab to the menubutton; this
|
| 514 |
+
# overrrides the implicit grab on button press, so that the menu
|
| 515 |
+
# button can track mouse motions over other menubuttons and change
|
| 516 |
+
# the posted menu.
|
| 517 |
+
# 3. If there's no posted menubutton (e.g. because we're a torn-off menu
|
| 518 |
+
# or one of its descendants) must grab to the top-level menu so that
|
| 519 |
+
# we can track mouse motions across the entire menu hierarchy.
|
| 520 |
+
#
|
| 521 |
+
# Arguments:
|
| 522 |
+
# menu - The menu window.
|
| 523 |
+
|
| 524 |
+
proc ::tk::MenuButtonDown menu {
|
| 525 |
+
variable ::tk::Priv
|
| 526 |
+
|
| 527 |
+
if {![winfo viewable $menu]} {
|
| 528 |
+
return
|
| 529 |
+
}
|
| 530 |
+
if {[$menu index active] eq "none"} {
|
| 531 |
+
if {[$menu cget -type] ne "menubar" } {
|
| 532 |
+
set Priv(window) {}
|
| 533 |
+
}
|
| 534 |
+
return
|
| 535 |
+
}
|
| 536 |
+
$menu postcascade active
|
| 537 |
+
if {$Priv(postedMb) ne "" && [winfo viewable $Priv(postedMb)]} {
|
| 538 |
+
grab -global $Priv(postedMb)
|
| 539 |
+
} else {
|
| 540 |
+
while {[$menu cget -type] eq "normal" \
|
| 541 |
+
&& [winfo class [winfo parent $menu]] eq "Menu" \
|
| 542 |
+
&& [winfo ismapped [winfo parent $menu]]} {
|
| 543 |
+
set menu [winfo parent $menu]
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
if {$Priv(menuBar) eq {}} {
|
| 547 |
+
set Priv(menuBar) $menu
|
| 548 |
+
if {$::tk_strictMotif} {
|
| 549 |
+
set Priv(cursor) [$menu cget -cursor]
|
| 550 |
+
$menu configure -cursor arrow
|
| 551 |
+
}
|
| 552 |
+
if {[$menu type active] eq "cascade"} {
|
| 553 |
+
set Priv(menuActivated) 1
|
| 554 |
+
}
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
# Don't update grab information if the grab window isn't changing.
|
| 558 |
+
# Otherwise, we'll get an error when we unpost the menus and
|
| 559 |
+
# restore the grab, since the old grab window will not be viewable
|
| 560 |
+
# anymore.
|
| 561 |
+
|
| 562 |
+
if {$menu ne [grab current $menu]} {
|
| 563 |
+
SaveGrabInfo $menu
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
# Must re-grab even if the grab window hasn't changed, in order
|
| 567 |
+
# to release the implicit grab from the button press.
|
| 568 |
+
|
| 569 |
+
if {[tk windowingsystem] eq "x11"} {
|
| 570 |
+
grab -global $menu
|
| 571 |
+
}
|
| 572 |
+
}
|
| 573 |
+
}
|
| 574 |
+
|
| 575 |
+
# ::tk::MenuLeave --
|
| 576 |
+
# This procedure is invoked to handle Leave events for a menu. It
|
| 577 |
+
# deactivates everything unless the active element is a cascade element
|
| 578 |
+
# and the mouse is now over the submenu.
|
| 579 |
+
#
|
| 580 |
+
# Arguments:
|
| 581 |
+
# menu - The menu window.
|
| 582 |
+
# rootx, rooty - Root coordinates of mouse.
|
| 583 |
+
# state - Modifier state.
|
| 584 |
+
|
| 585 |
+
proc ::tk::MenuLeave {menu rootx rooty state} {
|
| 586 |
+
variable ::tk::Priv
|
| 587 |
+
set Priv(window) {}
|
| 588 |
+
if {[$menu index active] eq "none"} {
|
| 589 |
+
return
|
| 590 |
+
}
|
| 591 |
+
if {[$menu type active] eq "cascade" \
|
| 592 |
+
&& [winfo containing $rootx $rooty] eq \
|
| 593 |
+
[$menu entrycget active -menu]} {
|
| 594 |
+
return
|
| 595 |
+
}
|
| 596 |
+
$menu activate none
|
| 597 |
+
GenerateMenuSelect $menu
|
| 598 |
+
}
|
| 599 |
+
|
| 600 |
+
# ::tk::MenuInvoke --
|
| 601 |
+
# This procedure is invoked when button 1 is released over a menu.
|
| 602 |
+
# It invokes the appropriate menu action and unposts the menu if
|
| 603 |
+
# it came from a menubutton.
|
| 604 |
+
#
|
| 605 |
+
# Arguments:
|
| 606 |
+
# w - Name of the menu widget.
|
| 607 |
+
# buttonRelease - 1 means this procedure is called because of
|
| 608 |
+
# a button release; 0 means because of keystroke.
|
| 609 |
+
|
| 610 |
+
proc ::tk::MenuInvoke {w buttonRelease} {
|
| 611 |
+
variable ::tk::Priv
|
| 612 |
+
|
| 613 |
+
if {$buttonRelease && $Priv(window) eq ""} {
|
| 614 |
+
# Mouse was pressed over a menu without a menu button, then
|
| 615 |
+
# dragged off the menu (possibly with a cascade posted) and
|
| 616 |
+
# released. Unpost everything and quit.
|
| 617 |
+
|
| 618 |
+
$w postcascade none
|
| 619 |
+
$w activate none
|
| 620 |
+
event generate $w <<MenuSelect>>
|
| 621 |
+
MenuUnpost $w
|
| 622 |
+
return
|
| 623 |
+
}
|
| 624 |
+
if {[$w type active] eq "cascade"} {
|
| 625 |
+
$w postcascade active
|
| 626 |
+
set menu [$w entrycget active -menu]
|
| 627 |
+
MenuFirstEntry $menu
|
| 628 |
+
} elseif {[$w type active] eq "tearoff"} {
|
| 629 |
+
::tk::TearOffMenu $w
|
| 630 |
+
MenuUnpost $w
|
| 631 |
+
} elseif {[$w cget -type] eq "menubar"} {
|
| 632 |
+
$w postcascade none
|
| 633 |
+
set active [$w index active]
|
| 634 |
+
set isCascade [string equal [$w type $active] "cascade"]
|
| 635 |
+
|
| 636 |
+
# Only de-activate the active item if it's a cascade; this prevents
|
| 637 |
+
# the annoying "activation flicker" you otherwise get with
|
| 638 |
+
# checkbuttons/commands/etc. on menubars
|
| 639 |
+
|
| 640 |
+
if { $isCascade } {
|
| 641 |
+
$w activate none
|
| 642 |
+
event generate $w <<MenuSelect>>
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
MenuUnpost $w
|
| 646 |
+
|
| 647 |
+
# If the active item is not a cascade, invoke it. This enables
|
| 648 |
+
# the use of checkbuttons/commands/etc. on menubars (which is legal,
|
| 649 |
+
# but not recommended)
|
| 650 |
+
|
| 651 |
+
if { !$isCascade } {
|
| 652 |
+
uplevel #0 [list $w invoke $active]
|
| 653 |
+
}
|
| 654 |
+
} else {
|
| 655 |
+
set active [$w index active]
|
| 656 |
+
if {$Priv(popup) eq "" || $active ne "none"} {
|
| 657 |
+
MenuUnpost $w
|
| 658 |
+
}
|
| 659 |
+
uplevel #0 [list $w invoke active]
|
| 660 |
+
}
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
# ::tk::MenuEscape --
|
| 664 |
+
# This procedure is invoked for the Cancel (or Escape) key. It unposts
|
| 665 |
+
# the given menu and, if it is the top-level menu for a menu button,
|
| 666 |
+
# unposts the menu button as well.
|
| 667 |
+
#
|
| 668 |
+
# Arguments:
|
| 669 |
+
# menu - Name of the menu window.
|
| 670 |
+
|
| 671 |
+
proc ::tk::MenuEscape menu {
|
| 672 |
+
set parent [winfo parent $menu]
|
| 673 |
+
if {[winfo class $parent] ne "Menu"} {
|
| 674 |
+
MenuUnpost $menu
|
| 675 |
+
} elseif {[$parent cget -type] eq "menubar"} {
|
| 676 |
+
MenuUnpost $menu
|
| 677 |
+
RestoreOldGrab
|
| 678 |
+
} else {
|
| 679 |
+
MenuNextMenu $menu left
|
| 680 |
+
}
|
| 681 |
+
}
|
| 682 |
+
|
| 683 |
+
# The following routines handle arrow keys. Arrow keys behave
|
| 684 |
+
# differently depending on whether the menu is a menu bar or not.
|
| 685 |
+
|
| 686 |
+
proc ::tk::MenuUpArrow {menu} {
|
| 687 |
+
if {[$menu cget -type] eq "menubar"} {
|
| 688 |
+
MenuNextMenu $menu left
|
| 689 |
+
} else {
|
| 690 |
+
MenuNextEntry $menu -1
|
| 691 |
+
}
|
| 692 |
+
}
|
| 693 |
+
|
| 694 |
+
proc ::tk::MenuDownArrow {menu} {
|
| 695 |
+
if {[$menu cget -type] eq "menubar"} {
|
| 696 |
+
MenuNextMenu $menu right
|
| 697 |
+
} else {
|
| 698 |
+
MenuNextEntry $menu 1
|
| 699 |
+
}
|
| 700 |
+
}
|
| 701 |
+
|
| 702 |
+
proc ::tk::MenuLeftArrow {menu} {
|
| 703 |
+
if {[$menu cget -type] eq "menubar"} {
|
| 704 |
+
MenuNextEntry $menu -1
|
| 705 |
+
} else {
|
| 706 |
+
MenuNextMenu $menu left
|
| 707 |
+
}
|
| 708 |
+
}
|
| 709 |
+
|
| 710 |
+
proc ::tk::MenuRightArrow {menu} {
|
| 711 |
+
if {[$menu cget -type] eq "menubar"} {
|
| 712 |
+
MenuNextEntry $menu 1
|
| 713 |
+
} else {
|
| 714 |
+
MenuNextMenu $menu right
|
| 715 |
+
}
|
| 716 |
+
}
|
| 717 |
+
|
| 718 |
+
# ::tk::MenuNextMenu --
|
| 719 |
+
# This procedure is invoked to handle "left" and "right" traversal
|
| 720 |
+
# motions in menus. It traverses to the next menu in a menu bar,
|
| 721 |
+
# or into or out of a cascaded menu.
|
| 722 |
+
#
|
| 723 |
+
# Arguments:
|
| 724 |
+
# menu - The menu that received the keyboard
|
| 725 |
+
# event.
|
| 726 |
+
# direction - Direction in which to move: "left" or "right"
|
| 727 |
+
|
| 728 |
+
proc ::tk::MenuNextMenu {menu direction} {
|
| 729 |
+
variable ::tk::Priv
|
| 730 |
+
|
| 731 |
+
# First handle traversals into and out of cascaded menus.
|
| 732 |
+
|
| 733 |
+
if {$direction eq "right"} {
|
| 734 |
+
set count 1
|
| 735 |
+
set parent [winfo parent $menu]
|
| 736 |
+
set class [winfo class $parent]
|
| 737 |
+
if {[$menu type active] eq "cascade"} {
|
| 738 |
+
$menu postcascade active
|
| 739 |
+
set m2 [$menu entrycget active -menu]
|
| 740 |
+
if {$m2 ne ""} {
|
| 741 |
+
MenuFirstEntry $m2
|
| 742 |
+
}
|
| 743 |
+
return
|
| 744 |
+
} else {
|
| 745 |
+
set parent [winfo parent $menu]
|
| 746 |
+
while {$parent ne "."} {
|
| 747 |
+
if {[winfo class $parent] eq "Menu" \
|
| 748 |
+
&& [$parent cget -type] eq "menubar"} {
|
| 749 |
+
tk_menuSetFocus $parent
|
| 750 |
+
MenuNextEntry $parent 1
|
| 751 |
+
return
|
| 752 |
+
}
|
| 753 |
+
set parent [winfo parent $parent]
|
| 754 |
+
}
|
| 755 |
+
}
|
| 756 |
+
} else {
|
| 757 |
+
set count -1
|
| 758 |
+
set m2 [winfo parent $menu]
|
| 759 |
+
if {[winfo class $m2] eq "Menu"} {
|
| 760 |
+
$menu activate none
|
| 761 |
+
GenerateMenuSelect $menu
|
| 762 |
+
tk_menuSetFocus $m2
|
| 763 |
+
|
| 764 |
+
$m2 postcascade none
|
| 765 |
+
|
| 766 |
+
if {[$m2 cget -type] ne "menubar"} {
|
| 767 |
+
return
|
| 768 |
+
}
|
| 769 |
+
}
|
| 770 |
+
}
|
| 771 |
+
|
| 772 |
+
# Can't traverse into or out of a cascaded menu. Go to the next
|
| 773 |
+
# or previous menubutton, if that makes sense.
|
| 774 |
+
|
| 775 |
+
set m2 [winfo parent $menu]
|
| 776 |
+
if {[winfo class $m2] eq "Menu" && [$m2 cget -type] eq "menubar"} {
|
| 777 |
+
tk_menuSetFocus $m2
|
| 778 |
+
MenuNextEntry $m2 -1
|
| 779 |
+
return
|
| 780 |
+
}
|
| 781 |
+
|
| 782 |
+
set w $Priv(postedMb)
|
| 783 |
+
if {$w eq ""} {
|
| 784 |
+
return
|
| 785 |
+
}
|
| 786 |
+
set buttons [winfo children [winfo parent $w]]
|
| 787 |
+
set length [llength $buttons]
|
| 788 |
+
set i [expr {[lsearch -exact $buttons $w] + $count}]
|
| 789 |
+
while {1} {
|
| 790 |
+
while {$i < 0} {
|
| 791 |
+
incr i $length
|
| 792 |
+
}
|
| 793 |
+
while {$i >= $length} {
|
| 794 |
+
incr i -$length
|
| 795 |
+
}
|
| 796 |
+
set mb [lindex $buttons $i]
|
| 797 |
+
if {[winfo class $mb] eq "Menubutton" \
|
| 798 |
+
&& [$mb cget -state] ne "disabled" \
|
| 799 |
+
&& [$mb cget -menu] ne "" \
|
| 800 |
+
&& [[$mb cget -menu] index last] ne "none"} {
|
| 801 |
+
break
|
| 802 |
+
}
|
| 803 |
+
if {$mb eq $w} {
|
| 804 |
+
return
|
| 805 |
+
}
|
| 806 |
+
incr i $count
|
| 807 |
+
}
|
| 808 |
+
MbPost $mb
|
| 809 |
+
MenuFirstEntry [$mb cget -menu]
|
| 810 |
+
}
|
| 811 |
+
|
| 812 |
+
# ::tk::MenuNextEntry --
|
| 813 |
+
# Activate the next higher or lower entry in the posted menu,
|
| 814 |
+
# wrapping around at the ends. Disabled entries are skipped.
|
| 815 |
+
#
|
| 816 |
+
# Arguments:
|
| 817 |
+
# menu - Menu window that received the keystroke.
|
| 818 |
+
# count - 1 means go to the next lower entry,
|
| 819 |
+
# -1 means go to the next higher entry.
|
| 820 |
+
|
| 821 |
+
proc ::tk::MenuNextEntry {menu count} {
|
| 822 |
+
if {[$menu index last] eq "none"} {
|
| 823 |
+
return
|
| 824 |
+
}
|
| 825 |
+
set length [expr {[$menu index last]+1}]
|
| 826 |
+
set quitAfter $length
|
| 827 |
+
set active [$menu index active]
|
| 828 |
+
if {$active eq "none"} {
|
| 829 |
+
set i 0
|
| 830 |
+
} else {
|
| 831 |
+
set i [expr {$active + $count}]
|
| 832 |
+
}
|
| 833 |
+
while {1} {
|
| 834 |
+
if {$quitAfter <= 0} {
|
| 835 |
+
# We've tried every entry in the menu. Either there are
|
| 836 |
+
# none, or they're all disabled. Just give up.
|
| 837 |
+
|
| 838 |
+
return
|
| 839 |
+
}
|
| 840 |
+
while {$i < 0} {
|
| 841 |
+
incr i $length
|
| 842 |
+
}
|
| 843 |
+
while {$i >= $length} {
|
| 844 |
+
incr i -$length
|
| 845 |
+
}
|
| 846 |
+
if {[catch {$menu entrycget $i -state} state] == 0} {
|
| 847 |
+
if {$state ne "disabled" && \
|
| 848 |
+
($i!=0 || [$menu cget -type] ne "tearoff" \
|
| 849 |
+
|| [$menu type 0] ne "tearoff")} {
|
| 850 |
+
break
|
| 851 |
+
}
|
| 852 |
+
}
|
| 853 |
+
if {$i == $active} {
|
| 854 |
+
return
|
| 855 |
+
}
|
| 856 |
+
incr i $count
|
| 857 |
+
incr quitAfter -1
|
| 858 |
+
}
|
| 859 |
+
$menu activate $i
|
| 860 |
+
GenerateMenuSelect $menu
|
| 861 |
+
|
| 862 |
+
if {[$menu type $i] eq "cascade" && [$menu cget -type] eq "menubar"} {
|
| 863 |
+
set cascade [$menu entrycget $i -menu]
|
| 864 |
+
if {$cascade ne ""} {
|
| 865 |
+
# Here we auto-post a cascade. This is necessary when
|
| 866 |
+
# we traverse left/right in the menubar, but undesirable when
|
| 867 |
+
# we traverse up/down in a menu.
|
| 868 |
+
$menu postcascade $i
|
| 869 |
+
MenuFirstEntry $cascade
|
| 870 |
+
}
|
| 871 |
+
}
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
# ::tk::MenuFind --
|
| 875 |
+
# This procedure searches the entire window hierarchy under w for
|
| 876 |
+
# a menubutton that isn't disabled and whose underlined character
|
| 877 |
+
# is "char" or an entry in a menubar that isn't disabled and whose
|
| 878 |
+
# underlined character is "char".
|
| 879 |
+
# It returns the name of that window, if found, or an
|
| 880 |
+
# empty string if no matching window was found. If "char" is an
|
| 881 |
+
# empty string then the procedure returns the name of the first
|
| 882 |
+
# menubutton found that isn't disabled.
|
| 883 |
+
#
|
| 884 |
+
# Arguments:
|
| 885 |
+
# w - Name of window where key was typed.
|
| 886 |
+
# char - Underlined character to search for;
|
| 887 |
+
# may be either upper or lower case, and
|
| 888 |
+
# will match either upper or lower case.
|
| 889 |
+
|
| 890 |
+
proc ::tk::MenuFind {w char} {
|
| 891 |
+
set char [string tolower $char]
|
| 892 |
+
set windowlist [winfo child $w]
|
| 893 |
+
|
| 894 |
+
foreach child $windowlist {
|
| 895 |
+
# Don't descend into other toplevels.
|
| 896 |
+
if {[winfo toplevel $w] ne [winfo toplevel $child]} {
|
| 897 |
+
continue
|
| 898 |
+
}
|
| 899 |
+
if {[winfo class $child] eq "Menu" && \
|
| 900 |
+
[$child cget -type] eq "menubar"} {
|
| 901 |
+
if {$char eq ""} {
|
| 902 |
+
return $child
|
| 903 |
+
}
|
| 904 |
+
set last [$child index last]
|
| 905 |
+
for {set i [$child cget -tearoff]} {$i <= $last} {incr i} {
|
| 906 |
+
if {[$child type $i] eq "separator"} {
|
| 907 |
+
continue
|
| 908 |
+
}
|
| 909 |
+
set char2 [string index [$child entrycget $i -label] \
|
| 910 |
+
[$child entrycget $i -underline]]
|
| 911 |
+
if {$char eq [string tolower $char2] || $char eq ""} {
|
| 912 |
+
if {[$child entrycget $i -state] ne "disabled"} {
|
| 913 |
+
return $child
|
| 914 |
+
}
|
| 915 |
+
}
|
| 916 |
+
}
|
| 917 |
+
}
|
| 918 |
+
}
|
| 919 |
+
|
| 920 |
+
foreach child $windowlist {
|
| 921 |
+
# Don't descend into other toplevels.
|
| 922 |
+
if {[winfo toplevel $w] ne [winfo toplevel $child]} {
|
| 923 |
+
continue
|
| 924 |
+
}
|
| 925 |
+
switch -- [winfo class $child] {
|
| 926 |
+
Menubutton {
|
| 927 |
+
set char2 [string index [$child cget -text] \
|
| 928 |
+
[$child cget -underline]]
|
| 929 |
+
if {$char eq [string tolower $char2] || $char eq ""} {
|
| 930 |
+
if {[$child cget -state] ne "disabled"} {
|
| 931 |
+
return $child
|
| 932 |
+
}
|
| 933 |
+
}
|
| 934 |
+
}
|
| 935 |
+
|
| 936 |
+
default {
|
| 937 |
+
set match [MenuFind $child $char]
|
| 938 |
+
if {$match ne ""} {
|
| 939 |
+
return $match
|
| 940 |
+
}
|
| 941 |
+
}
|
| 942 |
+
}
|
| 943 |
+
}
|
| 944 |
+
return ""
|
| 945 |
+
}
|
| 946 |
+
|
| 947 |
+
# ::tk::TraverseToMenu --
|
| 948 |
+
# This procedure implements keyboard traversal of menus. Given an
|
| 949 |
+
# ASCII character "char", it looks for a menubutton with that character
|
| 950 |
+
# underlined. If one is found, it posts the menubutton's menu
|
| 951 |
+
#
|
| 952 |
+
# Arguments:
|
| 953 |
+
# w - Window in which the key was typed (selects
|
| 954 |
+
# a toplevel window).
|
| 955 |
+
# char - Character that selects a menu. The case
|
| 956 |
+
# is ignored. If an empty string, nothing
|
| 957 |
+
# happens.
|
| 958 |
+
|
| 959 |
+
proc ::tk::TraverseToMenu {w char} {
|
| 960 |
+
variable ::tk::Priv
|
| 961 |
+
if {![winfo exists $w] || $char eq ""} {
|
| 962 |
+
return
|
| 963 |
+
}
|
| 964 |
+
while {[winfo class $w] eq "Menu"} {
|
| 965 |
+
if {[$w cget -type] eq "menubar"} {
|
| 966 |
+
break
|
| 967 |
+
} elseif {$Priv(postedMb) eq ""} {
|
| 968 |
+
return
|
| 969 |
+
}
|
| 970 |
+
set w [winfo parent $w]
|
| 971 |
+
}
|
| 972 |
+
set w [MenuFind [winfo toplevel $w] $char]
|
| 973 |
+
if {$w ne ""} {
|
| 974 |
+
if {[winfo class $w] eq "Menu"} {
|
| 975 |
+
tk_menuSetFocus $w
|
| 976 |
+
set Priv(window) $w
|
| 977 |
+
SaveGrabInfo $w
|
| 978 |
+
grab -global $w
|
| 979 |
+
TraverseWithinMenu $w $char
|
| 980 |
+
} else {
|
| 981 |
+
MbPost $w
|
| 982 |
+
MenuFirstEntry [$w cget -menu]
|
| 983 |
+
}
|
| 984 |
+
}
|
| 985 |
+
}
|
| 986 |
+
|
| 987 |
+
# ::tk::FirstMenu --
|
| 988 |
+
# This procedure traverses to the first menubutton in the toplevel
|
| 989 |
+
# for a given window, and posts that menubutton's menu.
|
| 990 |
+
#
|
| 991 |
+
# Arguments:
|
| 992 |
+
# w - Name of a window. Selects which toplevel
|
| 993 |
+
# to search for menubuttons.
|
| 994 |
+
|
| 995 |
+
proc ::tk::FirstMenu w {
|
| 996 |
+
variable ::tk::Priv
|
| 997 |
+
set w [MenuFind [winfo toplevel $w] ""]
|
| 998 |
+
if {$w ne ""} {
|
| 999 |
+
if {[winfo class $w] eq "Menu"} {
|
| 1000 |
+
tk_menuSetFocus $w
|
| 1001 |
+
set Priv(window) $w
|
| 1002 |
+
SaveGrabInfo $w
|
| 1003 |
+
grab -global $w
|
| 1004 |
+
MenuFirstEntry $w
|
| 1005 |
+
} else {
|
| 1006 |
+
MbPost $w
|
| 1007 |
+
MenuFirstEntry [$w cget -menu]
|
| 1008 |
+
}
|
| 1009 |
+
}
|
| 1010 |
+
}
|
| 1011 |
+
|
| 1012 |
+
# ::tk::TraverseWithinMenu
|
| 1013 |
+
# This procedure implements keyboard traversal within a menu. It
|
| 1014 |
+
# searches for an entry in the menu that has "char" underlined. If
|
| 1015 |
+
# such an entry is found, it is invoked and the menu is unposted.
|
| 1016 |
+
#
|
| 1017 |
+
# Arguments:
|
| 1018 |
+
# w - The name of the menu widget.
|
| 1019 |
+
# char - The character to look for; case is
|
| 1020 |
+
# ignored. If the string is empty then
|
| 1021 |
+
# nothing happens.
|
| 1022 |
+
|
| 1023 |
+
proc ::tk::TraverseWithinMenu {w char} {
|
| 1024 |
+
if {$char eq ""} {
|
| 1025 |
+
return
|
| 1026 |
+
}
|
| 1027 |
+
set char [string tolower $char]
|
| 1028 |
+
set last [$w index last]
|
| 1029 |
+
if {$last eq "none"} {
|
| 1030 |
+
return
|
| 1031 |
+
}
|
| 1032 |
+
for {set i 0} {$i <= $last} {incr i} {
|
| 1033 |
+
if {[catch {set char2 [string index \
|
| 1034 |
+
[$w entrycget $i -label] [$w entrycget $i -underline]]}]} {
|
| 1035 |
+
continue
|
| 1036 |
+
}
|
| 1037 |
+
if {$char eq [string tolower $char2]} {
|
| 1038 |
+
if {[$w type $i] eq "cascade"} {
|
| 1039 |
+
$w activate $i
|
| 1040 |
+
$w postcascade active
|
| 1041 |
+
event generate $w <<MenuSelect>>
|
| 1042 |
+
set m2 [$w entrycget $i -menu]
|
| 1043 |
+
if {$m2 ne ""} {
|
| 1044 |
+
MenuFirstEntry $m2
|
| 1045 |
+
}
|
| 1046 |
+
} else {
|
| 1047 |
+
MenuUnpost $w
|
| 1048 |
+
uplevel #0 [list $w invoke $i]
|
| 1049 |
+
}
|
| 1050 |
+
return
|
| 1051 |
+
}
|
| 1052 |
+
}
|
| 1053 |
+
}
|
| 1054 |
+
|
| 1055 |
+
# ::tk::MenuFirstEntry --
|
| 1056 |
+
# Given a menu, this procedure finds the first entry that isn't
|
| 1057 |
+
# disabled or a tear-off or separator, and activates that entry.
|
| 1058 |
+
# However, if there is already an active entry in the menu (e.g.,
|
| 1059 |
+
# because of a previous call to tk::PostOverPoint) then the active
|
| 1060 |
+
# entry isn't changed. This procedure also sets the input focus
|
| 1061 |
+
# to the menu.
|
| 1062 |
+
#
|
| 1063 |
+
# Arguments:
|
| 1064 |
+
# menu - Name of the menu window (possibly empty).
|
| 1065 |
+
|
| 1066 |
+
proc ::tk::MenuFirstEntry menu {
|
| 1067 |
+
if {$menu eq ""} {
|
| 1068 |
+
return
|
| 1069 |
+
}
|
| 1070 |
+
tk_menuSetFocus $menu
|
| 1071 |
+
if {[$menu index active] ne "none"} {
|
| 1072 |
+
return
|
| 1073 |
+
}
|
| 1074 |
+
set last [$menu index last]
|
| 1075 |
+
if {$last eq "none"} {
|
| 1076 |
+
return
|
| 1077 |
+
}
|
| 1078 |
+
for {set i 0} {$i <= $last} {incr i} {
|
| 1079 |
+
if {([catch {set state [$menu entrycget $i -state]}] == 0) \
|
| 1080 |
+
&& $state ne "disabled" && [$menu type $i] ne "tearoff"} {
|
| 1081 |
+
$menu activate $i
|
| 1082 |
+
GenerateMenuSelect $menu
|
| 1083 |
+
# Only post the cascade if the current menu is a menubar;
|
| 1084 |
+
# otherwise, if the first entry of the cascade is a cascade,
|
| 1085 |
+
# we can get an annoying cascading effect resulting in a bunch of
|
| 1086 |
+
# menus getting posted (bug 676)
|
| 1087 |
+
if {[$menu type $i] eq "cascade" && [$menu cget -type] eq "menubar"} {
|
| 1088 |
+
set cascade [$menu entrycget $i -menu]
|
| 1089 |
+
if {$cascade ne ""} {
|
| 1090 |
+
$menu postcascade $i
|
| 1091 |
+
MenuFirstEntry $cascade
|
| 1092 |
+
}
|
| 1093 |
+
}
|
| 1094 |
+
return
|
| 1095 |
+
}
|
| 1096 |
+
}
|
| 1097 |
+
}
|
| 1098 |
+
|
| 1099 |
+
# ::tk::MenuFindName --
|
| 1100 |
+
# Given a menu and a text string, return the index of the menu entry
|
| 1101 |
+
# that displays the string as its label. If there is no such entry,
|
| 1102 |
+
# return an empty string. This procedure is tricky because some names
|
| 1103 |
+
# like "active" have a special meaning in menu commands, so we can't
|
| 1104 |
+
# always use the "index" widget command.
|
| 1105 |
+
#
|
| 1106 |
+
# Arguments:
|
| 1107 |
+
# menu - Name of the menu widget.
|
| 1108 |
+
# s - String to look for.
|
| 1109 |
+
|
| 1110 |
+
proc ::tk::MenuFindName {menu s} {
|
| 1111 |
+
set i ""
|
| 1112 |
+
if {![regexp {^active$|^last$|^none$|^[0-9]|^@} $s]} {
|
| 1113 |
+
catch {set i [$menu index $s]}
|
| 1114 |
+
return $i
|
| 1115 |
+
}
|
| 1116 |
+
set last [$menu index last]
|
| 1117 |
+
if {$last eq "none"} {
|
| 1118 |
+
return ""
|
| 1119 |
+
}
|
| 1120 |
+
for {set i 0} {$i <= $last} {incr i} {
|
| 1121 |
+
if {![catch {$menu entrycget $i -label} label]} {
|
| 1122 |
+
if {$label eq $s} {
|
| 1123 |
+
return $i
|
| 1124 |
+
}
|
| 1125 |
+
}
|
| 1126 |
+
}
|
| 1127 |
+
return ""
|
| 1128 |
+
}
|
| 1129 |
+
|
| 1130 |
+
# ::tk::PostMenubuttonMenu --
|
| 1131 |
+
#
|
| 1132 |
+
# Given a menubutton and a menu, this procedure posts the menu at the
|
| 1133 |
+
# appropriate location. If the menubutton looks like an option
|
| 1134 |
+
# menubutton, meaning that the indicator is on and the direction is
|
| 1135 |
+
# neither above nor below, then the menu is posted so that the current
|
| 1136 |
+
# entry is vertically aligned with the menubutton. On the Mac this
|
| 1137 |
+
# will expose a small amount of the blue indicator on the right hand
|
| 1138 |
+
# side. On other platforms the entry is centered over the button.
|
| 1139 |
+
|
| 1140 |
+
if {[tk windowingsystem] eq "aqua"} {
|
| 1141 |
+
proc ::tk::PostMenubuttonMenu {button menu} {
|
| 1142 |
+
set entry ""
|
| 1143 |
+
if {[$button cget -indicatoron]} {
|
| 1144 |
+
set entry [MenuFindName $menu [$button cget -text]]
|
| 1145 |
+
if {$entry eq ""} {
|
| 1146 |
+
set entry 0
|
| 1147 |
+
}
|
| 1148 |
+
}
|
| 1149 |
+
set x [winfo rootx $button]
|
| 1150 |
+
set y [expr {2 + [winfo rooty $button]}]
|
| 1151 |
+
switch [$button cget -direction] {
|
| 1152 |
+
above {
|
| 1153 |
+
set entry ""
|
| 1154 |
+
incr y [expr {4 - [winfo reqheight $menu]}]
|
| 1155 |
+
}
|
| 1156 |
+
below {
|
| 1157 |
+
set entry ""
|
| 1158 |
+
incr y [expr {2 + [winfo height $button]}]
|
| 1159 |
+
}
|
| 1160 |
+
left {
|
| 1161 |
+
incr x [expr {-[winfo reqwidth $menu]}]
|
| 1162 |
+
}
|
| 1163 |
+
right {
|
| 1164 |
+
incr x [winfo width $button]
|
| 1165 |
+
}
|
| 1166 |
+
default {
|
| 1167 |
+
incr x [expr {[winfo width $button] - [winfo reqwidth $menu] - 5}]
|
| 1168 |
+
}
|
| 1169 |
+
}
|
| 1170 |
+
PostOverPoint $menu $x $y $entry
|
| 1171 |
+
}
|
| 1172 |
+
} else {
|
| 1173 |
+
proc ::tk::PostMenubuttonMenu {button menu} {
|
| 1174 |
+
set entry ""
|
| 1175 |
+
if {[$button cget -indicatoron]} {
|
| 1176 |
+
set entry [MenuFindName $menu [$button cget -text]]
|
| 1177 |
+
if {$entry eq ""} {
|
| 1178 |
+
set entry 0
|
| 1179 |
+
}
|
| 1180 |
+
}
|
| 1181 |
+
set x [winfo rootx $button]
|
| 1182 |
+
set y [winfo rooty $button]
|
| 1183 |
+
switch [$button cget -direction] {
|
| 1184 |
+
above {
|
| 1185 |
+
incr y [expr {-[winfo reqheight $menu]}]
|
| 1186 |
+
# if we go offscreen to the top, show as 'below'
|
| 1187 |
+
if {$y < [winfo vrooty $button]} {
|
| 1188 |
+
set y [expr {[winfo vrooty $button] + [winfo rooty $button]\
|
| 1189 |
+
+ [winfo reqheight $button]}]
|
| 1190 |
+
}
|
| 1191 |
+
set entry {}
|
| 1192 |
+
}
|
| 1193 |
+
below {
|
| 1194 |
+
incr y [winfo height $button]
|
| 1195 |
+
# if we go offscreen to the bottom, show as 'above'
|
| 1196 |
+
set mh [winfo reqheight $menu]
|
| 1197 |
+
if {($y + $mh) > ([winfo vrooty $button] + [winfo vrootheight $button])} {
|
| 1198 |
+
set y [expr {[winfo vrooty $button] + [winfo vrootheight $button] \
|
| 1199 |
+
+ [winfo rooty $button] - $mh}]
|
| 1200 |
+
}
|
| 1201 |
+
set entry {}
|
| 1202 |
+
}
|
| 1203 |
+
left {
|
| 1204 |
+
# It is not clear why this is needed.
|
| 1205 |
+
if {[tk windowingsystem] eq "win32"} {
|
| 1206 |
+
incr x [expr {-4 - [winfo reqwidth $button] / 2}]
|
| 1207 |
+
}
|
| 1208 |
+
incr x [expr {- [winfo reqwidth $menu]}]
|
| 1209 |
+
}
|
| 1210 |
+
right {
|
| 1211 |
+
incr x [expr {[winfo width $button]}]
|
| 1212 |
+
}
|
| 1213 |
+
default {
|
| 1214 |
+
if {[$button cget -indicatoron]} {
|
| 1215 |
+
incr x [expr {([winfo width $button] - \
|
| 1216 |
+
[winfo reqwidth $menu])/ 2}]
|
| 1217 |
+
} else {
|
| 1218 |
+
incr y [winfo height $button]
|
| 1219 |
+
}
|
| 1220 |
+
}
|
| 1221 |
+
}
|
| 1222 |
+
PostOverPoint $menu $x $y $entry
|
| 1223 |
+
}
|
| 1224 |
+
}
|
| 1225 |
+
|
| 1226 |
+
# ::tk::PostOverPoint --
|
| 1227 |
+
#
|
| 1228 |
+
# This procedure posts a menu on the screen so that a given entry in
|
| 1229 |
+
# the menu is positioned with its upper left corner at a given point
|
| 1230 |
+
# in the root window. The procedure also activates that entry. If no
|
| 1231 |
+
# entry is specified the upper left corner of the entire menu is
|
| 1232 |
+
# placed at the point.
|
| 1233 |
+
#
|
| 1234 |
+
# Arguments:
|
| 1235 |
+
# menu - Menu to post.
|
| 1236 |
+
# x, y - Root coordinates of point.
|
| 1237 |
+
# entry - Index of entry within menu to center over (x,y).
|
| 1238 |
+
# If omitted or specified as {}, then the menu's
|
| 1239 |
+
# upper-left corner goes at (x,y).
|
| 1240 |
+
|
| 1241 |
+
if {[tk windowingsystem] ne "win32"} {
|
| 1242 |
+
proc ::tk::PostOverPoint {menu x y {entry {}}} {
|
| 1243 |
+
if {$entry ne ""} {
|
| 1244 |
+
$menu post $x $y $entry
|
| 1245 |
+
if {[$menu entrycget $entry -state] ne "disabled"} {
|
| 1246 |
+
$menu activate $entry
|
| 1247 |
+
GenerateMenuSelect $menu
|
| 1248 |
+
}
|
| 1249 |
+
} else {
|
| 1250 |
+
$menu post $x $y
|
| 1251 |
+
}
|
| 1252 |
+
return
|
| 1253 |
+
}
|
| 1254 |
+
} else {
|
| 1255 |
+
proc ::tk::PostOverPoint {menu x y {entry {}}} {
|
| 1256 |
+
if {$entry ne ""} {
|
| 1257 |
+
incr y [expr {-[$menu yposition $entry]}]
|
| 1258 |
+
}
|
| 1259 |
+
# osVersion is not available in safe interps
|
| 1260 |
+
set ver 5
|
| 1261 |
+
if {[info exists ::tcl_platform(osVersion)]} {
|
| 1262 |
+
scan $::tcl_platform(osVersion) %d ver
|
| 1263 |
+
}
|
| 1264 |
+
|
| 1265 |
+
# We need to fix some problems with menu posting on Windows,
|
| 1266 |
+
# where, if the menu would overlap top or bottom of screen,
|
| 1267 |
+
# Windows puts it in the wrong place for us. We must also
|
| 1268 |
+
# subtract an extra amount for half the height of the current
|
| 1269 |
+
# entry. To be safe we subtract an extra 10.
|
| 1270 |
+
# NOTE: this issue appears to have been resolved in the Window
|
| 1271 |
+
# manager provided with Vista and Windows 7.
|
| 1272 |
+
if {$ver < 6} {
|
| 1273 |
+
set yoffset [expr {[winfo screenheight $menu] \
|
| 1274 |
+
- $y - [winfo reqheight $menu] - 10}]
|
| 1275 |
+
if {$yoffset < [winfo vrooty $menu]} {
|
| 1276 |
+
# The bottom of the menu is offscreen, so adjust upwards
|
| 1277 |
+
incr y [expr {$yoffset - [winfo vrooty $menu]}]
|
| 1278 |
+
}
|
| 1279 |
+
# If we're off the top of the screen (either because we were
|
| 1280 |
+
# originally or because we just adjusted too far upwards),
|
| 1281 |
+
# then make the menu popup on the top edge.
|
| 1282 |
+
if {$y < [winfo vrooty $menu]} {
|
| 1283 |
+
set y [winfo vrooty $menu]
|
| 1284 |
+
}
|
| 1285 |
+
}
|
| 1286 |
+
$menu post $x $y
|
| 1287 |
+
if {$entry ne "" && [$menu entrycget $entry -state] ne "disabled"} {
|
| 1288 |
+
$menu activate $entry
|
| 1289 |
+
GenerateMenuSelect $menu
|
| 1290 |
+
}
|
| 1291 |
+
}
|
| 1292 |
+
}
|
| 1293 |
+
|
| 1294 |
+
# ::tk::SaveGrabInfo --
|
| 1295 |
+
# Sets the variables tk::Priv(oldGrab) and tk::Priv(grabStatus) to record
|
| 1296 |
+
# the state of any existing grab on the w's display.
|
| 1297 |
+
#
|
| 1298 |
+
# Arguments:
|
| 1299 |
+
# w - Name of a window; used to select the display
|
| 1300 |
+
# whose grab information is to be recorded.
|
| 1301 |
+
|
| 1302 |
+
proc tk::SaveGrabInfo w {
|
| 1303 |
+
variable ::tk::Priv
|
| 1304 |
+
set Priv(oldGrab) [grab current $w]
|
| 1305 |
+
if {$Priv(oldGrab) ne ""} {
|
| 1306 |
+
set Priv(grabStatus) [grab status $Priv(oldGrab)]
|
| 1307 |
+
}
|
| 1308 |
+
}
|
| 1309 |
+
|
| 1310 |
+
# ::tk::RestoreOldGrab --
|
| 1311 |
+
# Restores the grab to what it was before TkSaveGrabInfo was called.
|
| 1312 |
+
#
|
| 1313 |
+
|
| 1314 |
+
proc ::tk::RestoreOldGrab {} {
|
| 1315 |
+
variable ::tk::Priv
|
| 1316 |
+
|
| 1317 |
+
if {$Priv(oldGrab) ne ""} {
|
| 1318 |
+
# Be careful restoring the old grab, since it's window may not
|
| 1319 |
+
# be visible anymore.
|
| 1320 |
+
|
| 1321 |
+
catch {
|
| 1322 |
+
if {$Priv(grabStatus) eq "global"} {
|
| 1323 |
+
grab set -global $Priv(oldGrab)
|
| 1324 |
+
} else {
|
| 1325 |
+
grab set $Priv(oldGrab)
|
| 1326 |
+
}
|
| 1327 |
+
}
|
| 1328 |
+
set Priv(oldGrab) ""
|
| 1329 |
+
}
|
| 1330 |
+
}
|
| 1331 |
+
|
| 1332 |
+
proc ::tk_menuSetFocus {menu} {
|
| 1333 |
+
variable ::tk::Priv
|
| 1334 |
+
if {![info exists Priv(focus)] || $Priv(focus) eq ""} {
|
| 1335 |
+
set Priv(focus) [focus]
|
| 1336 |
+
}
|
| 1337 |
+
focus $menu
|
| 1338 |
+
}
|
| 1339 |
+
|
| 1340 |
+
proc ::tk::GenerateMenuSelect {menu} {
|
| 1341 |
+
variable ::tk::Priv
|
| 1342 |
+
|
| 1343 |
+
if {$Priv(activeMenu) ne $menu \
|
| 1344 |
+
|| $Priv(activeItem) ne [$menu index active]} {
|
| 1345 |
+
set Priv(activeMenu) $menu
|
| 1346 |
+
set Priv(activeItem) [$menu index active]
|
| 1347 |
+
event generate $menu <<MenuSelect>>
|
| 1348 |
+
}
|
| 1349 |
+
}
|
| 1350 |
+
|
| 1351 |
+
# ::tk_popup --
|
| 1352 |
+
# This procedure pops up a menu and sets things up for traversing
|
| 1353 |
+
# the menu and its submenus.
|
| 1354 |
+
#
|
| 1355 |
+
# Arguments:
|
| 1356 |
+
# menu - Name of the menu to be popped up.
|
| 1357 |
+
# x, y - Root coordinates at which to pop up the
|
| 1358 |
+
# menu.
|
| 1359 |
+
# entry - Index of a menu entry to center over (x,y).
|
| 1360 |
+
# If omitted or specified as {}, then menu's
|
| 1361 |
+
# upper-left corner goes at (x,y).
|
| 1362 |
+
|
| 1363 |
+
proc ::tk_popup {menu x y {entry {}}} {
|
| 1364 |
+
variable ::tk::Priv
|
| 1365 |
+
if {$Priv(popup) ne "" || $Priv(postedMb) ne ""} {
|
| 1366 |
+
tk::MenuUnpost {}
|
| 1367 |
+
}
|
| 1368 |
+
tk::PostOverPoint $menu $x $y $entry
|
| 1369 |
+
if {[tk windowingsystem] eq "x11" && [winfo viewable $menu]} {
|
| 1370 |
+
tk::SaveGrabInfo $menu
|
| 1371 |
+
grab -global $menu
|
| 1372 |
+
set Priv(popup) $menu
|
| 1373 |
+
set Priv(window) $menu
|
| 1374 |
+
set Priv(menuActivated) 1
|
| 1375 |
+
tk_menuSetFocus $menu
|
| 1376 |
+
}
|
| 1377 |
+
}
|
shared/package-files/ab/ab671946216f6a0c7f00e0f593412d2c1b877f892f6cb42995861951d42b7657/blob
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import timedelta
|
| 2 |
+
from typing import List
|
| 3 |
+
from torch._C._distributed_rpc import (
|
| 4 |
+
_DEFAULT_INIT_METHOD,
|
| 5 |
+
_DEFAULT_NUM_WORKER_THREADS,
|
| 6 |
+
_DEFAULT_RPC_TIMEOUT_SEC,
|
| 7 |
+
_UNSET_RPC_TIMEOUT,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# For any RpcAgent.
|
| 12 |
+
DEFAULT_RPC_TIMEOUT_SEC: float = _DEFAULT_RPC_TIMEOUT_SEC
|
| 13 |
+
DEFAULT_INIT_METHOD: str = _DEFAULT_INIT_METHOD
|
| 14 |
+
DEFAULT_SHUTDOWN_TIMEOUT: float = 0
|
| 15 |
+
|
| 16 |
+
# For TensorPipeAgent.
|
| 17 |
+
DEFAULT_NUM_WORKER_THREADS: int = _DEFAULT_NUM_WORKER_THREADS
|
| 18 |
+
# Ensure that we don't time out when there are long periods of time without
|
| 19 |
+
# any operations against the underlying ProcessGroup.
|
| 20 |
+
DEFAULT_PROCESS_GROUP_TIMEOUT: timedelta = timedelta(milliseconds=2 ** 31 - 1)
|
| 21 |
+
# Value indicating that timeout is not set for RPC call, and the default should be used.
|
| 22 |
+
UNSET_RPC_TIMEOUT: float = _UNSET_RPC_TIMEOUT
|
| 23 |
+
|
| 24 |
+
__all__: List[str] = []
|
shared/package-files/ab/ab6a5deb5604bd1668a4b19842ba41375b0437020bb288457d4fe439821f3a34/blob
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/linalg_cond_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::linalg_cond(Tensor self, Scalar? p=None) -> Tensor
|
| 26 |
+
inline at::Tensor linalg_cond(const at::Tensor & self, const c10::optional<at::Scalar> & p=c10::nullopt) {
|
| 27 |
+
return at::_ops::linalg_cond::call(self, p);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// aten::linalg_cond.out(Tensor self, Scalar? p=None, *, Tensor(a!) out) -> Tensor(a!)
|
| 31 |
+
inline at::Tensor & linalg_cond_out(at::Tensor & out, const at::Tensor & self, const c10::optional<at::Scalar> & p=c10::nullopt) {
|
| 32 |
+
return at::_ops::linalg_cond_out::call(self, p, out);
|
| 33 |
+
}
|
| 34 |
+
// aten::linalg_cond.out(Tensor self, Scalar? p=None, *, Tensor(a!) out) -> Tensor(a!)
|
| 35 |
+
inline at::Tensor & linalg_cond_outf(const at::Tensor & self, const c10::optional<at::Scalar> & p, at::Tensor & out) {
|
| 36 |
+
return at::_ops::linalg_cond_out::call(self, p, out);
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
// aten::linalg_cond.p_str(Tensor self, str p) -> Tensor
|
| 40 |
+
inline at::Tensor linalg_cond(const at::Tensor & self, c10::string_view p) {
|
| 41 |
+
return at::_ops::linalg_cond_p_str::call(self, p);
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
// aten::linalg_cond.p_str_out(Tensor self, str p, *, Tensor(a!) out) -> Tensor(a!)
|
| 45 |
+
inline at::Tensor & linalg_cond_out(at::Tensor & out, const at::Tensor & self, c10::string_view p) {
|
| 46 |
+
return at::_ops::linalg_cond_p_str_out::call(self, p, out);
|
| 47 |
+
}
|
| 48 |
+
// aten::linalg_cond.p_str_out(Tensor self, str p, *, Tensor(a!) out) -> Tensor(a!)
|
| 49 |
+
inline at::Tensor & linalg_cond_outf(const at::Tensor & self, c10::string_view p, at::Tensor & out) {
|
| 50 |
+
return at::_ops::linalg_cond_p_str_out::call(self, p, out);
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
}
|
shared/package-files/ab/ab70fd0cb7e64c1500a3860c9cd50d5142ab024292c0ce50faf7ac77d03a4994/blob
ADDED
|
Binary file (113 Bytes). View file
|
|
|
shared/package-files/ab/ab72fb26cf95c7c869bb1c0c8bd6073bad2dfecb256be43acb83c3e75280c996/blob
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#----------------------------------------------------------------
|
| 2 |
+
# Generated CMake target import file for configuration "Release".
|
| 3 |
+
#----------------------------------------------------------------
|
| 4 |
+
|
| 5 |
+
# Commands may need to know the format version.
|
| 6 |
+
set(CMAKE_IMPORT_FILE_VERSION 1)
|
| 7 |
+
|
| 8 |
+
# Import target "reproc++" for configuration "Release"
|
| 9 |
+
set_property(TARGET reproc++ APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
|
| 10 |
+
set_target_properties(reproc++ PROPERTIES
|
| 11 |
+
IMPORTED_LINK_DEPENDENT_LIBRARIES_RELEASE "reproc"
|
| 12 |
+
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/libreproc++.so.14.2.4"
|
| 13 |
+
IMPORTED_SONAME_RELEASE "libreproc++.so.14"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
list(APPEND _IMPORT_CHECK_TARGETS reproc++ )
|
| 17 |
+
list(APPEND _IMPORT_CHECK_FILES_FOR_reproc++ "${_IMPORT_PREFIX}/lib/libreproc++.so.14.2.4" )
|
| 18 |
+
|
| 19 |
+
# Commands beyond this point should not need to know the version.
|
| 20 |
+
set(CMAKE_IMPORT_FILE_VERSION)
|
shared/package-files/ab/ab773b1096807853dd50e55e1ceb05da30403097134e233b131eddb41eb4cc68/blob
ADDED
|
@@ -0,0 +1,488 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import bisect
|
| 2 |
+
import itertools
|
| 3 |
+
import math
|
| 4 |
+
import warnings
|
| 5 |
+
from typing import (
|
| 6 |
+
cast,
|
| 7 |
+
Dict,
|
| 8 |
+
Generic,
|
| 9 |
+
Iterable,
|
| 10 |
+
List,
|
| 11 |
+
Optional,
|
| 12 |
+
Sequence,
|
| 13 |
+
Tuple,
|
| 14 |
+
TypeVar,
|
| 15 |
+
Union,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
# No 'default_generator' in torch/__init__.pyi
|
| 19 |
+
from torch import default_generator, randperm
|
| 20 |
+
|
| 21 |
+
from ... import Generator, Tensor
|
| 22 |
+
|
| 23 |
+
__all__ = [
|
| 24 |
+
"Dataset",
|
| 25 |
+
"IterableDataset",
|
| 26 |
+
"TensorDataset",
|
| 27 |
+
"StackDataset",
|
| 28 |
+
"ConcatDataset",
|
| 29 |
+
"ChainDataset",
|
| 30 |
+
"Subset",
|
| 31 |
+
"random_split",
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
T_co = TypeVar("T_co", covariant=True)
|
| 35 |
+
T = TypeVar("T")
|
| 36 |
+
T_dict = Dict[str, T_co]
|
| 37 |
+
T_tuple = Tuple[T_co, ...]
|
| 38 |
+
T_stack = TypeVar("T_stack", T_tuple, T_dict)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Dataset(Generic[T_co]):
|
| 42 |
+
r"""An abstract class representing a :class:`Dataset`.
|
| 43 |
+
|
| 44 |
+
All datasets that represent a map from keys to data samples should subclass
|
| 45 |
+
it. All subclasses should overwrite :meth:`__getitem__`, supporting fetching a
|
| 46 |
+
data sample for a given key. Subclasses could also optionally overwrite
|
| 47 |
+
:meth:`__len__`, which is expected to return the size of the dataset by many
|
| 48 |
+
:class:`~torch.utils.data.Sampler` implementations and the default options
|
| 49 |
+
of :class:`~torch.utils.data.DataLoader`. Subclasses could also
|
| 50 |
+
optionally implement :meth:`__getitems__`, for speedup batched samples
|
| 51 |
+
loading. This method accepts list of indices of samples of batch and returns
|
| 52 |
+
list of samples.
|
| 53 |
+
|
| 54 |
+
.. note::
|
| 55 |
+
:class:`~torch.utils.data.DataLoader` by default constructs an index
|
| 56 |
+
sampler that yields integral indices. To make it work with a map-style
|
| 57 |
+
dataset with non-integral indices/keys, a custom sampler must be provided.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def __getitem__(self, index) -> T_co:
|
| 61 |
+
raise NotImplementedError("Subclasses of Dataset should implement __getitem__.")
|
| 62 |
+
|
| 63 |
+
# def __getitems__(self, indices: List) -> List[T_co]:
|
| 64 |
+
# Not implemented to prevent false-positives in fetcher check in
|
| 65 |
+
# torch.utils.data._utils.fetch._MapDatasetFetcher
|
| 66 |
+
|
| 67 |
+
def __add__(self, other: "Dataset[T_co]") -> "ConcatDataset[T_co]":
|
| 68 |
+
return ConcatDataset([self, other])
|
| 69 |
+
|
| 70 |
+
# No `def __len__(self)` default?
|
| 71 |
+
# See NOTE [ Lack of Default `__len__` in Python Abstract Base Classes ]
|
| 72 |
+
# in pytorch/torch/utils/data/sampler.py
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class IterableDataset(Dataset[T_co], Iterable[T_co]):
|
| 76 |
+
r"""An iterable Dataset.
|
| 77 |
+
|
| 78 |
+
All datasets that represent an iterable of data samples should subclass it.
|
| 79 |
+
Such form of datasets is particularly useful when data come from a stream.
|
| 80 |
+
|
| 81 |
+
All subclasses should overwrite :meth:`__iter__`, which would return an
|
| 82 |
+
iterator of samples in this dataset.
|
| 83 |
+
|
| 84 |
+
When a subclass is used with :class:`~torch.utils.data.DataLoader`, each
|
| 85 |
+
item in the dataset will be yielded from the :class:`~torch.utils.data.DataLoader`
|
| 86 |
+
iterator. When :attr:`num_workers > 0`, each worker process will have a
|
| 87 |
+
different copy of the dataset object, so it is often desired to configure
|
| 88 |
+
each copy independently to avoid having duplicate data returned from the
|
| 89 |
+
workers. :func:`~torch.utils.data.get_worker_info`, when called in a worker
|
| 90 |
+
process, returns information about the worker. It can be used in either the
|
| 91 |
+
dataset's :meth:`__iter__` method or the :class:`~torch.utils.data.DataLoader` 's
|
| 92 |
+
:attr:`worker_init_fn` option to modify each copy's behavior.
|
| 93 |
+
|
| 94 |
+
Example 1: splitting workload across all workers in :meth:`__iter__`::
|
| 95 |
+
|
| 96 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_DATALOADER)
|
| 97 |
+
>>> # xdoctest: +SKIP("Fails on MacOS12")
|
| 98 |
+
>>> class MyIterableDataset(torch.utils.data.IterableDataset):
|
| 99 |
+
... def __init__(self, start, end):
|
| 100 |
+
... super(MyIterableDataset).__init__()
|
| 101 |
+
... assert end > start, "this example code only works with end >= start"
|
| 102 |
+
... self.start = start
|
| 103 |
+
... self.end = end
|
| 104 |
+
...
|
| 105 |
+
... def __iter__(self):
|
| 106 |
+
... worker_info = torch.utils.data.get_worker_info()
|
| 107 |
+
... if worker_info is None: # single-process data loading, return the full iterator
|
| 108 |
+
... iter_start = self.start
|
| 109 |
+
... iter_end = self.end
|
| 110 |
+
... else: # in a worker process
|
| 111 |
+
... # split workload
|
| 112 |
+
... per_worker = int(math.ceil((self.end - self.start) / float(worker_info.num_workers)))
|
| 113 |
+
... worker_id = worker_info.id
|
| 114 |
+
... iter_start = self.start + worker_id * per_worker
|
| 115 |
+
... iter_end = min(iter_start + per_worker, self.end)
|
| 116 |
+
... return iter(range(iter_start, iter_end))
|
| 117 |
+
...
|
| 118 |
+
>>> # should give same set of data as range(3, 7), i.e., [3, 4, 5, 6].
|
| 119 |
+
>>> ds = MyIterableDataset(start=3, end=7)
|
| 120 |
+
|
| 121 |
+
>>> # Single-process loading
|
| 122 |
+
>>> print(list(torch.utils.data.DataLoader(ds, num_workers=0)))
|
| 123 |
+
[tensor([3]), tensor([4]), tensor([5]), tensor([6])]
|
| 124 |
+
|
| 125 |
+
>>> # xdoctest: +REQUIRES(POSIX)
|
| 126 |
+
>>> # Mult-process loading with two worker processes
|
| 127 |
+
>>> # Worker 0 fetched [3, 4]. Worker 1 fetched [5, 6].
|
| 128 |
+
>>> # xdoctest: +IGNORE_WANT("non deterministic")
|
| 129 |
+
>>> print(list(torch.utils.data.DataLoader(ds, num_workers=2)))
|
| 130 |
+
[tensor([3]), tensor([5]), tensor([4]), tensor([6])]
|
| 131 |
+
|
| 132 |
+
>>> # With even more workers
|
| 133 |
+
>>> # xdoctest: +IGNORE_WANT("non deterministic")
|
| 134 |
+
>>> print(list(torch.utils.data.DataLoader(ds, num_workers=12)))
|
| 135 |
+
[tensor([3]), tensor([5]), tensor([4]), tensor([6])]
|
| 136 |
+
|
| 137 |
+
Example 2: splitting workload across all workers using :attr:`worker_init_fn`::
|
| 138 |
+
|
| 139 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_DATALOADER)
|
| 140 |
+
>>> class MyIterableDataset(torch.utils.data.IterableDataset):
|
| 141 |
+
... def __init__(self, start, end):
|
| 142 |
+
... super(MyIterableDataset).__init__()
|
| 143 |
+
... assert end > start, "this example code only works with end >= start"
|
| 144 |
+
... self.start = start
|
| 145 |
+
... self.end = end
|
| 146 |
+
...
|
| 147 |
+
... def __iter__(self):
|
| 148 |
+
... return iter(range(self.start, self.end))
|
| 149 |
+
...
|
| 150 |
+
>>> # should give same set of data as range(3, 7), i.e., [3, 4, 5, 6].
|
| 151 |
+
>>> ds = MyIterableDataset(start=3, end=7)
|
| 152 |
+
|
| 153 |
+
>>> # Single-process loading
|
| 154 |
+
>>> print(list(torch.utils.data.DataLoader(ds, num_workers=0)))
|
| 155 |
+
[3, 4, 5, 6]
|
| 156 |
+
>>>
|
| 157 |
+
>>> # Directly doing multi-process loading yields duplicate data
|
| 158 |
+
>>> print(list(torch.utils.data.DataLoader(ds, num_workers=2)))
|
| 159 |
+
[3, 3, 4, 4, 5, 5, 6, 6]
|
| 160 |
+
|
| 161 |
+
>>> # Define a `worker_init_fn` that configures each dataset copy differently
|
| 162 |
+
>>> def worker_init_fn(worker_id):
|
| 163 |
+
... worker_info = torch.utils.data.get_worker_info()
|
| 164 |
+
... dataset = worker_info.dataset # the dataset copy in this worker process
|
| 165 |
+
... overall_start = dataset.start
|
| 166 |
+
... overall_end = dataset.end
|
| 167 |
+
... # configure the dataset to only process the split workload
|
| 168 |
+
... per_worker = int(math.ceil((overall_end - overall_start) / float(worker_info.num_workers)))
|
| 169 |
+
... worker_id = worker_info.id
|
| 170 |
+
... dataset.start = overall_start + worker_id * per_worker
|
| 171 |
+
... dataset.end = min(dataset.start + per_worker, overall_end)
|
| 172 |
+
...
|
| 173 |
+
|
| 174 |
+
>>> # Mult-process loading with the custom `worker_init_fn`
|
| 175 |
+
>>> # Worker 0 fetched [3, 4]. Worker 1 fetched [5, 6].
|
| 176 |
+
>>> print(list(torch.utils.data.DataLoader(ds, num_workers=2, worker_init_fn=worker_init_fn)))
|
| 177 |
+
[3, 5, 4, 6]
|
| 178 |
+
|
| 179 |
+
>>> # With even more workers
|
| 180 |
+
>>> print(list(torch.utils.data.DataLoader(ds, num_workers=12, worker_init_fn=worker_init_fn)))
|
| 181 |
+
[3, 4, 5, 6]
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
def __add__(self, other: Dataset[T_co]):
|
| 185 |
+
return ChainDataset([self, other])
|
| 186 |
+
|
| 187 |
+
# No `def __len__(self)` default? Subclasses raise `TypeError` when needed.
|
| 188 |
+
# See NOTE [ Lack of Default `__len__` in Python Abstract Base Classes ]
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class TensorDataset(Dataset[Tuple[Tensor, ...]]):
|
| 192 |
+
r"""Dataset wrapping tensors.
|
| 193 |
+
|
| 194 |
+
Each sample will be retrieved by indexing tensors along the first dimension.
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
*tensors (Tensor): tensors that have the same size of the first dimension.
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
tensors: Tuple[Tensor, ...]
|
| 201 |
+
|
| 202 |
+
def __init__(self, *tensors: Tensor) -> None:
|
| 203 |
+
assert all(
|
| 204 |
+
tensors[0].size(0) == tensor.size(0) for tensor in tensors
|
| 205 |
+
), "Size mismatch between tensors"
|
| 206 |
+
self.tensors = tensors
|
| 207 |
+
|
| 208 |
+
def __getitem__(self, index):
|
| 209 |
+
return tuple(tensor[index] for tensor in self.tensors)
|
| 210 |
+
|
| 211 |
+
def __len__(self):
|
| 212 |
+
return self.tensors[0].size(0)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class StackDataset(Dataset[T_stack]):
|
| 216 |
+
r"""Dataset as a stacking of multiple datasets.
|
| 217 |
+
|
| 218 |
+
This class is useful to assemble different parts of complex input data, given as datasets.
|
| 219 |
+
|
| 220 |
+
Example:
|
| 221 |
+
>>> # xdoctest: +SKIP
|
| 222 |
+
>>> images = ImageDataset()
|
| 223 |
+
>>> texts = TextDataset()
|
| 224 |
+
>>> tuple_stack = StackDataset(images, texts)
|
| 225 |
+
>>> tuple_stack[0] == (images[0], texts[0])
|
| 226 |
+
>>> dict_stack = StackDataset(image=images, text=texts)
|
| 227 |
+
>>> dict_stack[0] == {'image': images[0], 'text': texts[0]}
|
| 228 |
+
|
| 229 |
+
Args:
|
| 230 |
+
*args (Dataset): Datasets for stacking returned as tuple.
|
| 231 |
+
**kwargs (Dataset): Datasets for stacking returned as dict.
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
datasets: Union[tuple, dict]
|
| 235 |
+
|
| 236 |
+
def __init__(self, *args: Dataset[T_co], **kwargs: Dataset[T_co]) -> None:
|
| 237 |
+
if args:
|
| 238 |
+
if kwargs:
|
| 239 |
+
raise ValueError(
|
| 240 |
+
"Supported either ``tuple``- (via ``args``) or"
|
| 241 |
+
"``dict``- (via ``kwargs``) like input/output, but both types are given."
|
| 242 |
+
)
|
| 243 |
+
self._length = len(args[0]) # type: ignore[arg-type]
|
| 244 |
+
if any(self._length != len(dataset) for dataset in args): # type: ignore[arg-type]
|
| 245 |
+
raise ValueError("Size mismatch between datasets")
|
| 246 |
+
self.datasets = args
|
| 247 |
+
elif kwargs:
|
| 248 |
+
tmp = list(kwargs.values())
|
| 249 |
+
self._length = len(tmp[0]) # type: ignore[arg-type]
|
| 250 |
+
if any(self._length != len(dataset) for dataset in tmp): # type: ignore[arg-type]
|
| 251 |
+
raise ValueError("Size mismatch between datasets")
|
| 252 |
+
self.datasets = kwargs
|
| 253 |
+
else:
|
| 254 |
+
raise ValueError("At least one dataset should be passed")
|
| 255 |
+
|
| 256 |
+
def __getitem__(self, index):
|
| 257 |
+
if isinstance(self.datasets, dict):
|
| 258 |
+
return {k: dataset[index] for k, dataset in self.datasets.items()}
|
| 259 |
+
return tuple(dataset[index] for dataset in self.datasets)
|
| 260 |
+
|
| 261 |
+
def __getitems__(self, indices: list):
|
| 262 |
+
# add batched sampling support when parent datasets supports it.
|
| 263 |
+
if isinstance(self.datasets, dict):
|
| 264 |
+
dict_batch: List[T_dict] = [{} for _ in indices]
|
| 265 |
+
for k, dataset in self.datasets.items():
|
| 266 |
+
if callable(getattr(dataset, "__getitems__", None)):
|
| 267 |
+
items = dataset.__getitems__(indices) # type: ignore[attr-defined]
|
| 268 |
+
if len(items) != len(indices):
|
| 269 |
+
raise ValueError(
|
| 270 |
+
"Nested dataset's output size mismatch."
|
| 271 |
+
f" Expected {len(indices)}, got {len(items)}"
|
| 272 |
+
)
|
| 273 |
+
for data, d_sample in zip(items, dict_batch):
|
| 274 |
+
d_sample[k] = data
|
| 275 |
+
else:
|
| 276 |
+
for idx, d_sample in zip(indices, dict_batch):
|
| 277 |
+
d_sample[k] = dataset[idx]
|
| 278 |
+
return dict_batch
|
| 279 |
+
|
| 280 |
+
# tuple data
|
| 281 |
+
list_batch: List[list] = [[] for _ in indices]
|
| 282 |
+
for dataset in self.datasets:
|
| 283 |
+
if callable(getattr(dataset, "__getitems__", None)):
|
| 284 |
+
items = dataset.__getitems__(indices) # type: ignore[attr-defined]
|
| 285 |
+
if len(items) != len(indices):
|
| 286 |
+
raise ValueError(
|
| 287 |
+
"Nested dataset's output size mismatch."
|
| 288 |
+
f" Expected {len(indices)}, got {len(items)}"
|
| 289 |
+
)
|
| 290 |
+
for data, t_sample in zip(items, list_batch):
|
| 291 |
+
t_sample.append(data)
|
| 292 |
+
else:
|
| 293 |
+
for idx, t_sample in zip(indices, list_batch):
|
| 294 |
+
t_sample.append(dataset[idx])
|
| 295 |
+
tuple_batch: List[T_tuple] = [tuple(sample) for sample in list_batch]
|
| 296 |
+
return tuple_batch
|
| 297 |
+
|
| 298 |
+
def __len__(self):
|
| 299 |
+
return self._length
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
class ConcatDataset(Dataset[T_co]):
|
| 303 |
+
r"""Dataset as a concatenation of multiple datasets.
|
| 304 |
+
|
| 305 |
+
This class is useful to assemble different existing datasets.
|
| 306 |
+
|
| 307 |
+
Args:
|
| 308 |
+
datasets (sequence): List of datasets to be concatenated
|
| 309 |
+
"""
|
| 310 |
+
|
| 311 |
+
datasets: List[Dataset[T_co]]
|
| 312 |
+
cumulative_sizes: List[int]
|
| 313 |
+
|
| 314 |
+
@staticmethod
|
| 315 |
+
def cumsum(sequence):
|
| 316 |
+
r, s = [], 0
|
| 317 |
+
for e in sequence:
|
| 318 |
+
l = len(e)
|
| 319 |
+
r.append(l + s)
|
| 320 |
+
s += l
|
| 321 |
+
return r
|
| 322 |
+
|
| 323 |
+
def __init__(self, datasets: Iterable[Dataset]) -> None:
|
| 324 |
+
super().__init__()
|
| 325 |
+
self.datasets = list(datasets)
|
| 326 |
+
assert len(self.datasets) > 0, "datasets should not be an empty iterable" # type: ignore[arg-type]
|
| 327 |
+
for d in self.datasets:
|
| 328 |
+
assert not isinstance(
|
| 329 |
+
d, IterableDataset
|
| 330 |
+
), "ConcatDataset does not support IterableDataset"
|
| 331 |
+
self.cumulative_sizes = self.cumsum(self.datasets)
|
| 332 |
+
|
| 333 |
+
def __len__(self):
|
| 334 |
+
return self.cumulative_sizes[-1]
|
| 335 |
+
|
| 336 |
+
def __getitem__(self, idx):
|
| 337 |
+
if idx < 0:
|
| 338 |
+
if -idx > len(self):
|
| 339 |
+
raise ValueError(
|
| 340 |
+
"absolute value of index should not exceed dataset length"
|
| 341 |
+
)
|
| 342 |
+
idx = len(self) + idx
|
| 343 |
+
dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx)
|
| 344 |
+
if dataset_idx == 0:
|
| 345 |
+
sample_idx = idx
|
| 346 |
+
else:
|
| 347 |
+
sample_idx = idx - self.cumulative_sizes[dataset_idx - 1]
|
| 348 |
+
return self.datasets[dataset_idx][sample_idx]
|
| 349 |
+
|
| 350 |
+
@property
|
| 351 |
+
def cummulative_sizes(self):
|
| 352 |
+
warnings.warn(
|
| 353 |
+
"cummulative_sizes attribute is renamed to " "cumulative_sizes",
|
| 354 |
+
DeprecationWarning,
|
| 355 |
+
stacklevel=2,
|
| 356 |
+
)
|
| 357 |
+
return self.cumulative_sizes
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class ChainDataset(IterableDataset):
|
| 361 |
+
r"""Dataset for chaining multiple :class:`IterableDataset` s.
|
| 362 |
+
|
| 363 |
+
This class is useful to assemble different existing dataset streams. The
|
| 364 |
+
chaining operation is done on-the-fly, so concatenating large-scale
|
| 365 |
+
datasets with this class will be efficient.
|
| 366 |
+
|
| 367 |
+
Args:
|
| 368 |
+
datasets (iterable of IterableDataset): datasets to be chained together
|
| 369 |
+
"""
|
| 370 |
+
|
| 371 |
+
def __init__(self, datasets: Iterable[Dataset]) -> None:
|
| 372 |
+
super().__init__()
|
| 373 |
+
self.datasets = datasets
|
| 374 |
+
|
| 375 |
+
def __iter__(self):
|
| 376 |
+
for d in self.datasets:
|
| 377 |
+
assert isinstance(
|
| 378 |
+
d, IterableDataset
|
| 379 |
+
), "ChainDataset only supports IterableDataset"
|
| 380 |
+
yield from d
|
| 381 |
+
|
| 382 |
+
def __len__(self):
|
| 383 |
+
total = 0
|
| 384 |
+
for d in self.datasets:
|
| 385 |
+
assert isinstance(
|
| 386 |
+
d, IterableDataset
|
| 387 |
+
), "ChainDataset only supports IterableDataset"
|
| 388 |
+
total += len(d) # type: ignore[arg-type]
|
| 389 |
+
return total
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
class Subset(Dataset[T_co]):
|
| 393 |
+
r"""
|
| 394 |
+
Subset of a dataset at specified indices.
|
| 395 |
+
|
| 396 |
+
Args:
|
| 397 |
+
dataset (Dataset): The whole Dataset
|
| 398 |
+
indices (sequence): Indices in the whole set selected for subset
|
| 399 |
+
"""
|
| 400 |
+
|
| 401 |
+
dataset: Dataset[T_co]
|
| 402 |
+
indices: Sequence[int]
|
| 403 |
+
|
| 404 |
+
def __init__(self, dataset: Dataset[T_co], indices: Sequence[int]) -> None:
|
| 405 |
+
self.dataset = dataset
|
| 406 |
+
self.indices = indices
|
| 407 |
+
|
| 408 |
+
def __getitem__(self, idx):
|
| 409 |
+
if isinstance(idx, list):
|
| 410 |
+
return self.dataset[[self.indices[i] for i in idx]]
|
| 411 |
+
return self.dataset[self.indices[idx]]
|
| 412 |
+
|
| 413 |
+
def __getitems__(self, indices: List[int]) -> List[T_co]:
|
| 414 |
+
# add batched sampling support when parent dataset supports it.
|
| 415 |
+
# see torch.utils.data._utils.fetch._MapDatasetFetcher
|
| 416 |
+
if callable(getattr(self.dataset, "__getitems__", None)):
|
| 417 |
+
return self.dataset.__getitems__([self.indices[idx] for idx in indices]) # type: ignore[attr-defined]
|
| 418 |
+
else:
|
| 419 |
+
return [self.dataset[self.indices[idx]] for idx in indices]
|
| 420 |
+
|
| 421 |
+
def __len__(self):
|
| 422 |
+
return len(self.indices)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def random_split(
|
| 426 |
+
dataset: Dataset[T],
|
| 427 |
+
lengths: Sequence[Union[int, float]],
|
| 428 |
+
generator: Optional[Generator] = default_generator,
|
| 429 |
+
) -> List[Subset[T]]:
|
| 430 |
+
r"""
|
| 431 |
+
Randomly split a dataset into non-overlapping new datasets of given lengths.
|
| 432 |
+
|
| 433 |
+
If a list of fractions that sum up to 1 is given,
|
| 434 |
+
the lengths will be computed automatically as
|
| 435 |
+
floor(frac * len(dataset)) for each fraction provided.
|
| 436 |
+
|
| 437 |
+
After computing the lengths, if there are any remainders, 1 count will be
|
| 438 |
+
distributed in round-robin fashion to the lengths
|
| 439 |
+
until there are no remainders left.
|
| 440 |
+
|
| 441 |
+
Optionally fix the generator for reproducible results, e.g.:
|
| 442 |
+
|
| 443 |
+
Example:
|
| 444 |
+
>>> # xdoctest: +SKIP
|
| 445 |
+
>>> generator1 = torch.Generator().manual_seed(42)
|
| 446 |
+
>>> generator2 = torch.Generator().manual_seed(42)
|
| 447 |
+
>>> random_split(range(10), [3, 7], generator=generator1)
|
| 448 |
+
>>> random_split(range(30), [0.3, 0.3, 0.4], generator=generator2)
|
| 449 |
+
|
| 450 |
+
Args:
|
| 451 |
+
dataset (Dataset): Dataset to be split
|
| 452 |
+
lengths (sequence): lengths or fractions of splits to be produced
|
| 453 |
+
generator (Generator): Generator used for the random permutation.
|
| 454 |
+
"""
|
| 455 |
+
if math.isclose(sum(lengths), 1) and sum(lengths) <= 1:
|
| 456 |
+
subset_lengths: List[int] = []
|
| 457 |
+
for i, frac in enumerate(lengths):
|
| 458 |
+
if frac < 0 or frac > 1:
|
| 459 |
+
raise ValueError(f"Fraction at index {i} is not between 0 and 1")
|
| 460 |
+
n_items_in_split = int(
|
| 461 |
+
math.floor(len(dataset) * frac) # type: ignore[arg-type]
|
| 462 |
+
)
|
| 463 |
+
subset_lengths.append(n_items_in_split)
|
| 464 |
+
remainder = len(dataset) - sum(subset_lengths) # type: ignore[arg-type]
|
| 465 |
+
# add 1 to all the lengths in round-robin fashion until the remainder is 0
|
| 466 |
+
for i in range(remainder):
|
| 467 |
+
idx_to_add_at = i % len(subset_lengths)
|
| 468 |
+
subset_lengths[idx_to_add_at] += 1
|
| 469 |
+
lengths = subset_lengths
|
| 470 |
+
for i, length in enumerate(lengths):
|
| 471 |
+
if length == 0:
|
| 472 |
+
warnings.warn(
|
| 473 |
+
f"Length of split at index {i} is 0. "
|
| 474 |
+
f"This might result in an empty dataset."
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
# Cannot verify that dataset is Sized
|
| 478 |
+
if sum(lengths) != len(dataset): # type: ignore[arg-type]
|
| 479 |
+
raise ValueError(
|
| 480 |
+
"Sum of input lengths does not equal the length of the input dataset!"
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
indices = randperm(sum(lengths), generator=generator).tolist() # type: ignore[arg-type, call-overload]
|
| 484 |
+
lengths = cast(Sequence[int], lengths)
|
| 485 |
+
return [
|
| 486 |
+
Subset(dataset, indices[offset - length : offset])
|
| 487 |
+
for offset, length in zip(itertools.accumulate(lengths), lengths)
|
| 488 |
+
]
|
shared/package-files/ab/ab77953666d62461bf4b40e2b7f4b7028f2a42acffe4f6135c500a0597b9cabe/blob
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
| 2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
| 3 |
+
# for complete details.
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class InfinityType:
|
| 7 |
+
def __repr__(self) -> str:
|
| 8 |
+
return "Infinity"
|
| 9 |
+
|
| 10 |
+
def __hash__(self) -> int:
|
| 11 |
+
return hash(repr(self))
|
| 12 |
+
|
| 13 |
+
def __lt__(self, other: object) -> bool:
|
| 14 |
+
return False
|
| 15 |
+
|
| 16 |
+
def __le__(self, other: object) -> bool:
|
| 17 |
+
return False
|
| 18 |
+
|
| 19 |
+
def __eq__(self, other: object) -> bool:
|
| 20 |
+
return isinstance(other, self.__class__)
|
| 21 |
+
|
| 22 |
+
def __gt__(self, other: object) -> bool:
|
| 23 |
+
return True
|
| 24 |
+
|
| 25 |
+
def __ge__(self, other: object) -> bool:
|
| 26 |
+
return True
|
| 27 |
+
|
| 28 |
+
def __neg__(self: object) -> "NegativeInfinityType":
|
| 29 |
+
return NegativeInfinity
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
Infinity = InfinityType()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class NegativeInfinityType:
|
| 36 |
+
def __repr__(self) -> str:
|
| 37 |
+
return "-Infinity"
|
| 38 |
+
|
| 39 |
+
def __hash__(self) -> int:
|
| 40 |
+
return hash(repr(self))
|
| 41 |
+
|
| 42 |
+
def __lt__(self, other: object) -> bool:
|
| 43 |
+
return True
|
| 44 |
+
|
| 45 |
+
def __le__(self, other: object) -> bool:
|
| 46 |
+
return True
|
| 47 |
+
|
| 48 |
+
def __eq__(self, other: object) -> bool:
|
| 49 |
+
return isinstance(other, self.__class__)
|
| 50 |
+
|
| 51 |
+
def __gt__(self, other: object) -> bool:
|
| 52 |
+
return False
|
| 53 |
+
|
| 54 |
+
def __ge__(self, other: object) -> bool:
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
def __neg__(self: object) -> InfinityType:
|
| 58 |
+
return Infinity
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
NegativeInfinity = NegativeInfinityType()
|
shared/package-files/ab/ab77a1488a2dd4667a4f23072236e0d2845fe208405eec1b4834985629ba7af8/blob
ADDED
|
Binary file (2.96 kB). View file
|
|
|
shared/package-files/ab/ab78926242b393e09aeb37854f11cce2160cafce02ef713e4aac341abed9b040/blob
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conversion functions between RGB and other color systems.
|
| 2 |
+
|
| 3 |
+
This modules provides two functions for each color system ABC:
|
| 4 |
+
|
| 5 |
+
rgb_to_abc(r, g, b) --> a, b, c
|
| 6 |
+
abc_to_rgb(a, b, c) --> r, g, b
|
| 7 |
+
|
| 8 |
+
All inputs and outputs are triples of floats in the range [0.0...1.0]
|
| 9 |
+
(with the exception of I and Q, which covers a slightly larger range).
|
| 10 |
+
Inputs outside the valid range may cause exceptions or invalid outputs.
|
| 11 |
+
|
| 12 |
+
Supported color systems:
|
| 13 |
+
RGB: Red, Green, Blue components
|
| 14 |
+
YIQ: Luminance, Chrominance (used by composite video signals)
|
| 15 |
+
HLS: Hue, Luminance, Saturation
|
| 16 |
+
HSV: Hue, Saturation, Value
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
# References:
|
| 20 |
+
# http://en.wikipedia.org/wiki/YIQ
|
| 21 |
+
# http://en.wikipedia.org/wiki/HLS_color_space
|
| 22 |
+
# http://en.wikipedia.org/wiki/HSV_color_space
|
| 23 |
+
|
| 24 |
+
__all__ = ["rgb_to_yiq","yiq_to_rgb","rgb_to_hls","hls_to_rgb",
|
| 25 |
+
"rgb_to_hsv","hsv_to_rgb"]
|
| 26 |
+
|
| 27 |
+
# Some floating point constants
|
| 28 |
+
|
| 29 |
+
ONE_THIRD = 1.0/3.0
|
| 30 |
+
ONE_SIXTH = 1.0/6.0
|
| 31 |
+
TWO_THIRD = 2.0/3.0
|
| 32 |
+
|
| 33 |
+
# YIQ: used by composite video signals (linear combinations of RGB)
|
| 34 |
+
# Y: perceived grey level (0.0 == black, 1.0 == white)
|
| 35 |
+
# I, Q: color components
|
| 36 |
+
#
|
| 37 |
+
# There are a great many versions of the constants used in these formulae.
|
| 38 |
+
# The ones in this library uses constants from the FCC version of NTSC.
|
| 39 |
+
|
| 40 |
+
def rgb_to_yiq(r, g, b):
|
| 41 |
+
y = 0.30*r + 0.59*g + 0.11*b
|
| 42 |
+
i = 0.74*(r-y) - 0.27*(b-y)
|
| 43 |
+
q = 0.48*(r-y) + 0.41*(b-y)
|
| 44 |
+
return (y, i, q)
|
| 45 |
+
|
| 46 |
+
def yiq_to_rgb(y, i, q):
|
| 47 |
+
# r = y + (0.27*q + 0.41*i) / (0.74*0.41 + 0.27*0.48)
|
| 48 |
+
# b = y + (0.74*q - 0.48*i) / (0.74*0.41 + 0.27*0.48)
|
| 49 |
+
# g = y - (0.30*(r-y) + 0.11*(b-y)) / 0.59
|
| 50 |
+
|
| 51 |
+
r = y + 0.9468822170900693*i + 0.6235565819861433*q
|
| 52 |
+
g = y - 0.27478764629897834*i - 0.6356910791873801*q
|
| 53 |
+
b = y - 1.1085450346420322*i + 1.7090069284064666*q
|
| 54 |
+
|
| 55 |
+
if r < 0.0:
|
| 56 |
+
r = 0.0
|
| 57 |
+
if g < 0.0:
|
| 58 |
+
g = 0.0
|
| 59 |
+
if b < 0.0:
|
| 60 |
+
b = 0.0
|
| 61 |
+
if r > 1.0:
|
| 62 |
+
r = 1.0
|
| 63 |
+
if g > 1.0:
|
| 64 |
+
g = 1.0
|
| 65 |
+
if b > 1.0:
|
| 66 |
+
b = 1.0
|
| 67 |
+
return (r, g, b)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# HLS: Hue, Luminance, Saturation
|
| 71 |
+
# H: position in the spectrum
|
| 72 |
+
# L: color lightness
|
| 73 |
+
# S: color saturation
|
| 74 |
+
|
| 75 |
+
def rgb_to_hls(r, g, b):
|
| 76 |
+
maxc = max(r, g, b)
|
| 77 |
+
minc = min(r, g, b)
|
| 78 |
+
sumc = (maxc+minc)
|
| 79 |
+
rangec = (maxc-minc)
|
| 80 |
+
l = sumc/2.0
|
| 81 |
+
if minc == maxc:
|
| 82 |
+
return 0.0, l, 0.0
|
| 83 |
+
if l <= 0.5:
|
| 84 |
+
s = rangec / sumc
|
| 85 |
+
else:
|
| 86 |
+
s = rangec / (2.0-sumc)
|
| 87 |
+
rc = (maxc-r) / rangec
|
| 88 |
+
gc = (maxc-g) / rangec
|
| 89 |
+
bc = (maxc-b) / rangec
|
| 90 |
+
if r == maxc:
|
| 91 |
+
h = bc-gc
|
| 92 |
+
elif g == maxc:
|
| 93 |
+
h = 2.0+rc-bc
|
| 94 |
+
else:
|
| 95 |
+
h = 4.0+gc-rc
|
| 96 |
+
h = (h/6.0) % 1.0
|
| 97 |
+
return h, l, s
|
| 98 |
+
|
| 99 |
+
def hls_to_rgb(h, l, s):
|
| 100 |
+
if s == 0.0:
|
| 101 |
+
return l, l, l
|
| 102 |
+
if l <= 0.5:
|
| 103 |
+
m2 = l * (1.0+s)
|
| 104 |
+
else:
|
| 105 |
+
m2 = l+s-(l*s)
|
| 106 |
+
m1 = 2.0*l - m2
|
| 107 |
+
return (_v(m1, m2, h+ONE_THIRD), _v(m1, m2, h), _v(m1, m2, h-ONE_THIRD))
|
| 108 |
+
|
| 109 |
+
def _v(m1, m2, hue):
|
| 110 |
+
hue = hue % 1.0
|
| 111 |
+
if hue < ONE_SIXTH:
|
| 112 |
+
return m1 + (m2-m1)*hue*6.0
|
| 113 |
+
if hue < 0.5:
|
| 114 |
+
return m2
|
| 115 |
+
if hue < TWO_THIRD:
|
| 116 |
+
return m1 + (m2-m1)*(TWO_THIRD-hue)*6.0
|
| 117 |
+
return m1
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# HSV: Hue, Saturation, Value
|
| 121 |
+
# H: position in the spectrum
|
| 122 |
+
# S: color saturation ("purity")
|
| 123 |
+
# V: color brightness
|
| 124 |
+
|
| 125 |
+
def rgb_to_hsv(r, g, b):
|
| 126 |
+
maxc = max(r, g, b)
|
| 127 |
+
minc = min(r, g, b)
|
| 128 |
+
v = maxc
|
| 129 |
+
if minc == maxc:
|
| 130 |
+
return 0.0, 0.0, v
|
| 131 |
+
s = (maxc-minc) / maxc
|
| 132 |
+
rc = (maxc-r) / (maxc-minc)
|
| 133 |
+
gc = (maxc-g) / (maxc-minc)
|
| 134 |
+
bc = (maxc-b) / (maxc-minc)
|
| 135 |
+
if r == maxc:
|
| 136 |
+
h = bc-gc
|
| 137 |
+
elif g == maxc:
|
| 138 |
+
h = 2.0+rc-bc
|
| 139 |
+
else:
|
| 140 |
+
h = 4.0+gc-rc
|
| 141 |
+
h = (h/6.0) % 1.0
|
| 142 |
+
return h, s, v
|
| 143 |
+
|
| 144 |
+
def hsv_to_rgb(h, s, v):
|
| 145 |
+
if s == 0.0:
|
| 146 |
+
return v, v, v
|
| 147 |
+
i = int(h*6.0) # XXX assume int() truncates!
|
| 148 |
+
f = (h*6.0) - i
|
| 149 |
+
p = v*(1.0 - s)
|
| 150 |
+
q = v*(1.0 - s*f)
|
| 151 |
+
t = v*(1.0 - s*(1.0-f))
|
| 152 |
+
i = i%6
|
| 153 |
+
if i == 0:
|
| 154 |
+
return v, t, p
|
| 155 |
+
if i == 1:
|
| 156 |
+
return q, v, p
|
| 157 |
+
if i == 2:
|
| 158 |
+
return p, v, t
|
| 159 |
+
if i == 3:
|
| 160 |
+
return p, q, v
|
| 161 |
+
if i == 4:
|
| 162 |
+
return t, p, v
|
| 163 |
+
if i == 5:
|
| 164 |
+
return v, p, q
|
| 165 |
+
# Cannot get here
|
shared/package-files/ab/ab795b429201a5bb575c6370d5e17090dfcfc317431aa9382f8e881366f43357/blob
ADDED
|
Binary file (48 kB). View file
|
|
|
shared/package-files/ab/ab7c6a6fe1688a764fa48f8e18e5ebb9f150f19e8df09877d52646e5418bc246/blob
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ab7c6a6fe1688a764fa48f8e18e5ebb9f150f19e8df09877d52646e5418bc246
|
| 3 |
+
size 120336
|
shared/package-files/ab/ab7d4f29bebab1fba0832f9ae0d21c962f42822ca882f5a259d12d075cc23f4b/blob
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace compositeexplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor & _standard_gamma_out(at::Tensor & out, const at::Tensor & self, c10::optional<at::Generator> generator=c10::nullopt);
|
| 21 |
+
TORCH_API at::Tensor & _standard_gamma_outf(const at::Tensor & self, c10::optional<at::Generator> generator, at::Tensor & out);
|
| 22 |
+
|
| 23 |
+
} // namespace compositeexplicitautograd
|
| 24 |
+
} // namespace at
|
shared/package-files/ab/ab8132b2d6593d5b283f739c1e70e355b020d885801bf432b28d79dd7800616f/blob
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API _test_check_tensor {
|
| 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::_test_check_tensor")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_test_check_tensor(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 |
+
}} // namespace at::_ops
|
shared/package-files/ab/ab816ed7d7cb7eef4c238da27270f883543bdd06a9bf38f7d039e244486f276e/blob
ADDED
|
@@ -0,0 +1,874 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Robust location and covariance estimators.
|
| 3 |
+
|
| 4 |
+
Here are implemented estimators that are resistant to outliers.
|
| 5 |
+
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
# Authors: The scikit-learn developers
|
| 9 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 10 |
+
|
| 11 |
+
import warnings
|
| 12 |
+
from numbers import Integral, Real
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
from scipy import linalg
|
| 16 |
+
from scipy.stats import chi2
|
| 17 |
+
|
| 18 |
+
from ..base import _fit_context
|
| 19 |
+
from ..utils import check_array, check_random_state
|
| 20 |
+
from ..utils._param_validation import Interval
|
| 21 |
+
from ..utils.extmath import fast_logdet
|
| 22 |
+
from ..utils.validation import validate_data
|
| 23 |
+
from ._empirical_covariance import EmpiricalCovariance, empirical_covariance
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Minimum Covariance Determinant
|
| 27 |
+
# Implementing of an algorithm by Rousseeuw & Van Driessen described in
|
| 28 |
+
# (A Fast Algorithm for the Minimum Covariance Determinant Estimator,
|
| 29 |
+
# 1999, American Statistical Association and the American Society
|
| 30 |
+
# for Quality, TECHNOMETRICS)
|
| 31 |
+
# XXX Is this really a public function? It's not listed in the docs or
|
| 32 |
+
# exported by sklearn.covariance. Deprecate?
|
| 33 |
+
def c_step(
|
| 34 |
+
X,
|
| 35 |
+
n_support,
|
| 36 |
+
remaining_iterations=30,
|
| 37 |
+
initial_estimates=None,
|
| 38 |
+
verbose=False,
|
| 39 |
+
cov_computation_method=empirical_covariance,
|
| 40 |
+
random_state=None,
|
| 41 |
+
):
|
| 42 |
+
"""C_step procedure described in [Rouseeuw1984]_ aiming at computing MCD.
|
| 43 |
+
|
| 44 |
+
Parameters
|
| 45 |
+
----------
|
| 46 |
+
X : array-like of shape (n_samples, n_features)
|
| 47 |
+
Data set in which we look for the n_support observations whose
|
| 48 |
+
scatter matrix has minimum determinant.
|
| 49 |
+
|
| 50 |
+
n_support : int
|
| 51 |
+
Number of observations to compute the robust estimates of location
|
| 52 |
+
and covariance from. This parameter must be greater than
|
| 53 |
+
`n_samples / 2`.
|
| 54 |
+
|
| 55 |
+
remaining_iterations : int, default=30
|
| 56 |
+
Number of iterations to perform.
|
| 57 |
+
According to [Rouseeuw1999]_, two iterations are sufficient to get
|
| 58 |
+
close to the minimum, and we never need more than 30 to reach
|
| 59 |
+
convergence.
|
| 60 |
+
|
| 61 |
+
initial_estimates : tuple of shape (2,), default=None
|
| 62 |
+
Initial estimates of location and shape from which to run the c_step
|
| 63 |
+
procedure:
|
| 64 |
+
- initial_estimates[0]: an initial location estimate
|
| 65 |
+
- initial_estimates[1]: an initial covariance estimate
|
| 66 |
+
|
| 67 |
+
verbose : bool, default=False
|
| 68 |
+
Verbose mode.
|
| 69 |
+
|
| 70 |
+
cov_computation_method : callable, \
|
| 71 |
+
default=:func:`sklearn.covariance.empirical_covariance`
|
| 72 |
+
The function which will be used to compute the covariance.
|
| 73 |
+
Must return array of shape (n_features, n_features).
|
| 74 |
+
|
| 75 |
+
random_state : int, RandomState instance or None, default=None
|
| 76 |
+
Determines the pseudo random number generator for shuffling the data.
|
| 77 |
+
Pass an int for reproducible results across multiple function calls.
|
| 78 |
+
See :term:`Glossary <random_state>`.
|
| 79 |
+
|
| 80 |
+
Returns
|
| 81 |
+
-------
|
| 82 |
+
location : ndarray of shape (n_features,)
|
| 83 |
+
Robust location estimates.
|
| 84 |
+
|
| 85 |
+
covariance : ndarray of shape (n_features, n_features)
|
| 86 |
+
Robust covariance estimates.
|
| 87 |
+
|
| 88 |
+
support : ndarray of shape (n_samples,)
|
| 89 |
+
A mask for the `n_support` observations whose scatter matrix has
|
| 90 |
+
minimum determinant.
|
| 91 |
+
|
| 92 |
+
References
|
| 93 |
+
----------
|
| 94 |
+
.. [Rouseeuw1999] A Fast Algorithm for the Minimum Covariance Determinant
|
| 95 |
+
Estimator, 1999, American Statistical Association and the American
|
| 96 |
+
Society for Quality, TECHNOMETRICS
|
| 97 |
+
"""
|
| 98 |
+
X = np.asarray(X)
|
| 99 |
+
random_state = check_random_state(random_state)
|
| 100 |
+
return _c_step(
|
| 101 |
+
X,
|
| 102 |
+
n_support,
|
| 103 |
+
remaining_iterations=remaining_iterations,
|
| 104 |
+
initial_estimates=initial_estimates,
|
| 105 |
+
verbose=verbose,
|
| 106 |
+
cov_computation_method=cov_computation_method,
|
| 107 |
+
random_state=random_state,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _c_step(
|
| 112 |
+
X,
|
| 113 |
+
n_support,
|
| 114 |
+
random_state,
|
| 115 |
+
remaining_iterations=30,
|
| 116 |
+
initial_estimates=None,
|
| 117 |
+
verbose=False,
|
| 118 |
+
cov_computation_method=empirical_covariance,
|
| 119 |
+
):
|
| 120 |
+
n_samples, n_features = X.shape
|
| 121 |
+
dist = np.inf
|
| 122 |
+
|
| 123 |
+
# Initialisation
|
| 124 |
+
if initial_estimates is None:
|
| 125 |
+
# compute initial robust estimates from a random subset
|
| 126 |
+
support_indices = random_state.permutation(n_samples)[:n_support]
|
| 127 |
+
else:
|
| 128 |
+
# get initial robust estimates from the function parameters
|
| 129 |
+
location = initial_estimates[0]
|
| 130 |
+
covariance = initial_estimates[1]
|
| 131 |
+
# run a special iteration for that case (to get an initial support_indices)
|
| 132 |
+
precision = linalg.pinvh(covariance)
|
| 133 |
+
X_centered = X - location
|
| 134 |
+
dist = (np.dot(X_centered, precision) * X_centered).sum(1)
|
| 135 |
+
# compute new estimates
|
| 136 |
+
support_indices = np.argpartition(dist, n_support - 1)[:n_support]
|
| 137 |
+
|
| 138 |
+
X_support = X[support_indices]
|
| 139 |
+
location = X_support.mean(0)
|
| 140 |
+
covariance = cov_computation_method(X_support)
|
| 141 |
+
|
| 142 |
+
# Iterative procedure for Minimum Covariance Determinant computation
|
| 143 |
+
det = fast_logdet(covariance)
|
| 144 |
+
# If the data already has singular covariance, calculate the precision,
|
| 145 |
+
# as the loop below will not be entered.
|
| 146 |
+
if np.isinf(det):
|
| 147 |
+
precision = linalg.pinvh(covariance)
|
| 148 |
+
|
| 149 |
+
previous_det = np.inf
|
| 150 |
+
while det < previous_det and remaining_iterations > 0 and not np.isinf(det):
|
| 151 |
+
# save old estimates values
|
| 152 |
+
previous_location = location
|
| 153 |
+
previous_covariance = covariance
|
| 154 |
+
previous_det = det
|
| 155 |
+
previous_support_indices = support_indices
|
| 156 |
+
# compute a new support_indices from the full data set mahalanobis distances
|
| 157 |
+
precision = linalg.pinvh(covariance)
|
| 158 |
+
X_centered = X - location
|
| 159 |
+
dist = (np.dot(X_centered, precision) * X_centered).sum(axis=1)
|
| 160 |
+
# compute new estimates
|
| 161 |
+
support_indices = np.argpartition(dist, n_support - 1)[:n_support]
|
| 162 |
+
X_support = X[support_indices]
|
| 163 |
+
location = X_support.mean(axis=0)
|
| 164 |
+
covariance = cov_computation_method(X_support)
|
| 165 |
+
det = fast_logdet(covariance)
|
| 166 |
+
# update remaining iterations for early stopping
|
| 167 |
+
remaining_iterations -= 1
|
| 168 |
+
|
| 169 |
+
previous_dist = dist
|
| 170 |
+
dist = (np.dot(X - location, precision) * (X - location)).sum(axis=1)
|
| 171 |
+
# Check if best fit already found (det => 0, logdet => -inf)
|
| 172 |
+
if np.isinf(det):
|
| 173 |
+
results = location, covariance, det, support_indices, dist
|
| 174 |
+
# Check convergence
|
| 175 |
+
if np.allclose(det, previous_det):
|
| 176 |
+
# c_step procedure converged
|
| 177 |
+
if verbose:
|
| 178 |
+
print(
|
| 179 |
+
"Optimal couple (location, covariance) found before"
|
| 180 |
+
" ending iterations (%d left)" % (remaining_iterations)
|
| 181 |
+
)
|
| 182 |
+
results = location, covariance, det, support_indices, dist
|
| 183 |
+
elif det > previous_det:
|
| 184 |
+
# determinant has increased (should not happen)
|
| 185 |
+
warnings.warn(
|
| 186 |
+
"Determinant has increased; this should not happen: "
|
| 187 |
+
"log(det) > log(previous_det) (%.15f > %.15f). "
|
| 188 |
+
"You may want to try with a higher value of "
|
| 189 |
+
"support_fraction (current value: %.3f)."
|
| 190 |
+
% (det, previous_det, n_support / n_samples),
|
| 191 |
+
RuntimeWarning,
|
| 192 |
+
)
|
| 193 |
+
results = (
|
| 194 |
+
previous_location,
|
| 195 |
+
previous_covariance,
|
| 196 |
+
previous_det,
|
| 197 |
+
previous_support_indices,
|
| 198 |
+
previous_dist,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
# Check early stopping
|
| 202 |
+
if remaining_iterations == 0:
|
| 203 |
+
if verbose:
|
| 204 |
+
print("Maximum number of iterations reached")
|
| 205 |
+
results = location, covariance, det, support_indices, dist
|
| 206 |
+
|
| 207 |
+
location, covariance, det, support_indices, dist = results
|
| 208 |
+
# Convert from list of indices to boolean mask.
|
| 209 |
+
support = np.bincount(support_indices, minlength=n_samples).astype(bool)
|
| 210 |
+
return location, covariance, det, support, dist
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def select_candidates(
|
| 214 |
+
X,
|
| 215 |
+
n_support,
|
| 216 |
+
n_trials,
|
| 217 |
+
select=1,
|
| 218 |
+
n_iter=30,
|
| 219 |
+
verbose=False,
|
| 220 |
+
cov_computation_method=empirical_covariance,
|
| 221 |
+
random_state=None,
|
| 222 |
+
):
|
| 223 |
+
"""Finds the best pure subset of observations to compute MCD from it.
|
| 224 |
+
|
| 225 |
+
The purpose of this function is to find the best sets of n_support
|
| 226 |
+
observations with respect to a minimization of their covariance
|
| 227 |
+
matrix determinant. Equivalently, it removes n_samples-n_support
|
| 228 |
+
observations to construct what we call a pure data set (i.e. not
|
| 229 |
+
containing outliers). The list of the observations of the pure
|
| 230 |
+
data set is referred to as the `support`.
|
| 231 |
+
|
| 232 |
+
Starting from a random support, the pure data set is found by the
|
| 233 |
+
c_step procedure introduced by Rousseeuw and Van Driessen in
|
| 234 |
+
[RV]_.
|
| 235 |
+
|
| 236 |
+
Parameters
|
| 237 |
+
----------
|
| 238 |
+
X : array-like of shape (n_samples, n_features)
|
| 239 |
+
Data (sub)set in which we look for the n_support purest observations.
|
| 240 |
+
|
| 241 |
+
n_support : int
|
| 242 |
+
The number of samples the pure data set must contain.
|
| 243 |
+
This parameter must be in the range `[(n + p + 1)/2] < n_support < n`.
|
| 244 |
+
|
| 245 |
+
n_trials : int or tuple of shape (2,)
|
| 246 |
+
Number of different initial sets of observations from which to
|
| 247 |
+
run the algorithm. This parameter should be a strictly positive
|
| 248 |
+
integer.
|
| 249 |
+
Instead of giving a number of trials to perform, one can provide a
|
| 250 |
+
list of initial estimates that will be used to iteratively run
|
| 251 |
+
c_step procedures. In this case:
|
| 252 |
+
- n_trials[0]: array-like, shape (n_trials, n_features)
|
| 253 |
+
is the list of `n_trials` initial location estimates
|
| 254 |
+
- n_trials[1]: array-like, shape (n_trials, n_features, n_features)
|
| 255 |
+
is the list of `n_trials` initial covariances estimates
|
| 256 |
+
|
| 257 |
+
select : int, default=1
|
| 258 |
+
Number of best candidates results to return. This parameter must be
|
| 259 |
+
a strictly positive integer.
|
| 260 |
+
|
| 261 |
+
n_iter : int, default=30
|
| 262 |
+
Maximum number of iterations for the c_step procedure.
|
| 263 |
+
(2 is enough to be close to the final solution. "Never" exceeds 20).
|
| 264 |
+
This parameter must be a strictly positive integer.
|
| 265 |
+
|
| 266 |
+
verbose : bool, default=False
|
| 267 |
+
Control the output verbosity.
|
| 268 |
+
|
| 269 |
+
cov_computation_method : callable, \
|
| 270 |
+
default=:func:`sklearn.covariance.empirical_covariance`
|
| 271 |
+
The function which will be used to compute the covariance.
|
| 272 |
+
Must return an array of shape (n_features, n_features).
|
| 273 |
+
|
| 274 |
+
random_state : int, RandomState instance or None, default=None
|
| 275 |
+
Determines the pseudo random number generator for shuffling the data.
|
| 276 |
+
Pass an int for reproducible results across multiple function calls.
|
| 277 |
+
See :term:`Glossary <random_state>`.
|
| 278 |
+
|
| 279 |
+
See Also
|
| 280 |
+
---------
|
| 281 |
+
c_step
|
| 282 |
+
|
| 283 |
+
Returns
|
| 284 |
+
-------
|
| 285 |
+
best_locations : ndarray of shape (select, n_features)
|
| 286 |
+
The `select` location estimates computed from the `select` best
|
| 287 |
+
supports found in the data set (`X`).
|
| 288 |
+
|
| 289 |
+
best_covariances : ndarray of shape (select, n_features, n_features)
|
| 290 |
+
The `select` covariance estimates computed from the `select`
|
| 291 |
+
best supports found in the data set (`X`).
|
| 292 |
+
|
| 293 |
+
best_supports : ndarray of shape (select, n_samples)
|
| 294 |
+
The `select` best supports found in the data set (`X`).
|
| 295 |
+
|
| 296 |
+
References
|
| 297 |
+
----------
|
| 298 |
+
.. [RV] A Fast Algorithm for the Minimum Covariance Determinant
|
| 299 |
+
Estimator, 1999, American Statistical Association and the American
|
| 300 |
+
Society for Quality, TECHNOMETRICS
|
| 301 |
+
"""
|
| 302 |
+
random_state = check_random_state(random_state)
|
| 303 |
+
|
| 304 |
+
if isinstance(n_trials, Integral):
|
| 305 |
+
run_from_estimates = False
|
| 306 |
+
elif isinstance(n_trials, tuple):
|
| 307 |
+
run_from_estimates = True
|
| 308 |
+
estimates_list = n_trials
|
| 309 |
+
n_trials = estimates_list[0].shape[0]
|
| 310 |
+
else:
|
| 311 |
+
raise TypeError(
|
| 312 |
+
"Invalid 'n_trials' parameter, expected tuple or integer, got %s (%s)"
|
| 313 |
+
% (n_trials, type(n_trials))
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
# compute `n_trials` location and shape estimates candidates in the subset
|
| 317 |
+
all_estimates = []
|
| 318 |
+
if not run_from_estimates:
|
| 319 |
+
# perform `n_trials` computations from random initial supports
|
| 320 |
+
for j in range(n_trials):
|
| 321 |
+
all_estimates.append(
|
| 322 |
+
_c_step(
|
| 323 |
+
X,
|
| 324 |
+
n_support,
|
| 325 |
+
remaining_iterations=n_iter,
|
| 326 |
+
verbose=verbose,
|
| 327 |
+
cov_computation_method=cov_computation_method,
|
| 328 |
+
random_state=random_state,
|
| 329 |
+
)
|
| 330 |
+
)
|
| 331 |
+
else:
|
| 332 |
+
# perform computations from every given initial estimates
|
| 333 |
+
for j in range(n_trials):
|
| 334 |
+
initial_estimates = (estimates_list[0][j], estimates_list[1][j])
|
| 335 |
+
all_estimates.append(
|
| 336 |
+
_c_step(
|
| 337 |
+
X,
|
| 338 |
+
n_support,
|
| 339 |
+
remaining_iterations=n_iter,
|
| 340 |
+
initial_estimates=initial_estimates,
|
| 341 |
+
verbose=verbose,
|
| 342 |
+
cov_computation_method=cov_computation_method,
|
| 343 |
+
random_state=random_state,
|
| 344 |
+
)
|
| 345 |
+
)
|
| 346 |
+
all_locs_sub, all_covs_sub, all_dets_sub, all_supports_sub, all_ds_sub = zip(
|
| 347 |
+
*all_estimates
|
| 348 |
+
)
|
| 349 |
+
# find the `n_best` best results among the `n_trials` ones
|
| 350 |
+
index_best = np.argsort(all_dets_sub)[:select]
|
| 351 |
+
best_locations = np.asarray(all_locs_sub)[index_best]
|
| 352 |
+
best_covariances = np.asarray(all_covs_sub)[index_best]
|
| 353 |
+
best_supports = np.asarray(all_supports_sub)[index_best]
|
| 354 |
+
best_ds = np.asarray(all_ds_sub)[index_best]
|
| 355 |
+
|
| 356 |
+
return best_locations, best_covariances, best_supports, best_ds
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def fast_mcd(
|
| 360 |
+
X,
|
| 361 |
+
support_fraction=None,
|
| 362 |
+
cov_computation_method=empirical_covariance,
|
| 363 |
+
random_state=None,
|
| 364 |
+
):
|
| 365 |
+
"""Estimate the Minimum Covariance Determinant matrix.
|
| 366 |
+
|
| 367 |
+
Read more in the :ref:`User Guide <robust_covariance>`.
|
| 368 |
+
|
| 369 |
+
Parameters
|
| 370 |
+
----------
|
| 371 |
+
X : array-like of shape (n_samples, n_features)
|
| 372 |
+
The data matrix, with p features and n samples.
|
| 373 |
+
|
| 374 |
+
support_fraction : float, default=None
|
| 375 |
+
The proportion of points to be included in the support of the raw
|
| 376 |
+
MCD estimate. Default is `None`, which implies that the minimum
|
| 377 |
+
value of `support_fraction` will be used within the algorithm:
|
| 378 |
+
`(n_samples + n_features + 1) / 2 * n_samples`. This parameter must be
|
| 379 |
+
in the range (0, 1).
|
| 380 |
+
|
| 381 |
+
cov_computation_method : callable, \
|
| 382 |
+
default=:func:`sklearn.covariance.empirical_covariance`
|
| 383 |
+
The function which will be used to compute the covariance.
|
| 384 |
+
Must return an array of shape (n_features, n_features).
|
| 385 |
+
|
| 386 |
+
random_state : int, RandomState instance or None, default=None
|
| 387 |
+
Determines the pseudo random number generator for shuffling the data.
|
| 388 |
+
Pass an int for reproducible results across multiple function calls.
|
| 389 |
+
See :term:`Glossary <random_state>`.
|
| 390 |
+
|
| 391 |
+
Returns
|
| 392 |
+
-------
|
| 393 |
+
location : ndarray of shape (n_features,)
|
| 394 |
+
Robust location of the data.
|
| 395 |
+
|
| 396 |
+
covariance : ndarray of shape (n_features, n_features)
|
| 397 |
+
Robust covariance of the features.
|
| 398 |
+
|
| 399 |
+
support : ndarray of shape (n_samples,), dtype=bool
|
| 400 |
+
A mask of the observations that have been used to compute
|
| 401 |
+
the robust location and covariance estimates of the data set.
|
| 402 |
+
|
| 403 |
+
Notes
|
| 404 |
+
-----
|
| 405 |
+
The FastMCD algorithm has been introduced by Rousseuw and Van Driessen
|
| 406 |
+
in "A Fast Algorithm for the Minimum Covariance Determinant Estimator,
|
| 407 |
+
1999, American Statistical Association and the American Society
|
| 408 |
+
for Quality, TECHNOMETRICS".
|
| 409 |
+
The principle is to compute robust estimates and random subsets before
|
| 410 |
+
pooling them into a larger subsets, and finally into the full data set.
|
| 411 |
+
Depending on the size of the initial sample, we have one, two or three
|
| 412 |
+
such computation levels.
|
| 413 |
+
|
| 414 |
+
Note that only raw estimates are returned. If one is interested in
|
| 415 |
+
the correction and reweighting steps described in [RouseeuwVan]_,
|
| 416 |
+
see the MinCovDet object.
|
| 417 |
+
|
| 418 |
+
References
|
| 419 |
+
----------
|
| 420 |
+
|
| 421 |
+
.. [RouseeuwVan] A Fast Algorithm for the Minimum Covariance
|
| 422 |
+
Determinant Estimator, 1999, American Statistical Association
|
| 423 |
+
and the American Society for Quality, TECHNOMETRICS
|
| 424 |
+
|
| 425 |
+
.. [Butler1993] R. W. Butler, P. L. Davies and M. Jhun,
|
| 426 |
+
Asymptotics For The Minimum Covariance Determinant Estimator,
|
| 427 |
+
The Annals of Statistics, 1993, Vol. 21, No. 3, 1385-1400
|
| 428 |
+
"""
|
| 429 |
+
random_state = check_random_state(random_state)
|
| 430 |
+
|
| 431 |
+
X = check_array(X, ensure_min_samples=2, estimator="fast_mcd")
|
| 432 |
+
n_samples, n_features = X.shape
|
| 433 |
+
|
| 434 |
+
# minimum breakdown value
|
| 435 |
+
if support_fraction is None:
|
| 436 |
+
n_support = min(int(np.ceil(0.5 * (n_samples + n_features + 1))), n_samples)
|
| 437 |
+
else:
|
| 438 |
+
n_support = int(support_fraction * n_samples)
|
| 439 |
+
|
| 440 |
+
# 1-dimensional case quick computation
|
| 441 |
+
# (Rousseeuw, P. J. and Leroy, A. M. (2005) References, in Robust
|
| 442 |
+
# Regression and Outlier Detection, John Wiley & Sons, chapter 4)
|
| 443 |
+
if n_features == 1:
|
| 444 |
+
if n_support < n_samples:
|
| 445 |
+
# find the sample shortest halves
|
| 446 |
+
X_sorted = np.sort(np.ravel(X))
|
| 447 |
+
diff = X_sorted[n_support:] - X_sorted[: (n_samples - n_support)]
|
| 448 |
+
halves_start = np.where(diff == np.min(diff))[0]
|
| 449 |
+
# take the middle points' mean to get the robust location estimate
|
| 450 |
+
location = (
|
| 451 |
+
0.5
|
| 452 |
+
* (X_sorted[n_support + halves_start] + X_sorted[halves_start]).mean()
|
| 453 |
+
)
|
| 454 |
+
support = np.zeros(n_samples, dtype=bool)
|
| 455 |
+
X_centered = X - location
|
| 456 |
+
support[np.argsort(np.abs(X_centered), 0)[:n_support]] = True
|
| 457 |
+
covariance = np.asarray([[np.var(X[support])]])
|
| 458 |
+
location = np.array([location])
|
| 459 |
+
# get precision matrix in an optimized way
|
| 460 |
+
precision = linalg.pinvh(covariance)
|
| 461 |
+
dist = (np.dot(X_centered, precision) * (X_centered)).sum(axis=1)
|
| 462 |
+
else:
|
| 463 |
+
support = np.ones(n_samples, dtype=bool)
|
| 464 |
+
covariance = np.asarray([[np.var(X)]])
|
| 465 |
+
location = np.asarray([np.mean(X)])
|
| 466 |
+
X_centered = X - location
|
| 467 |
+
# get precision matrix in an optimized way
|
| 468 |
+
precision = linalg.pinvh(covariance)
|
| 469 |
+
dist = (np.dot(X_centered, precision) * (X_centered)).sum(axis=1)
|
| 470 |
+
# Starting FastMCD algorithm for p-dimensional case
|
| 471 |
+
if (n_samples > 500) and (n_features > 1):
|
| 472 |
+
# 1. Find candidate supports on subsets
|
| 473 |
+
# a. split the set in subsets of size ~ 300
|
| 474 |
+
n_subsets = n_samples // 300
|
| 475 |
+
n_samples_subsets = n_samples // n_subsets
|
| 476 |
+
samples_shuffle = random_state.permutation(n_samples)
|
| 477 |
+
h_subset = int(np.ceil(n_samples_subsets * (n_support / float(n_samples))))
|
| 478 |
+
# b. perform a total of 500 trials
|
| 479 |
+
n_trials_tot = 500
|
| 480 |
+
# c. select 10 best (location, covariance) for each subset
|
| 481 |
+
n_best_sub = 10
|
| 482 |
+
n_trials = max(10, n_trials_tot // n_subsets)
|
| 483 |
+
n_best_tot = n_subsets * n_best_sub
|
| 484 |
+
all_best_locations = np.zeros((n_best_tot, n_features))
|
| 485 |
+
try:
|
| 486 |
+
all_best_covariances = np.zeros((n_best_tot, n_features, n_features))
|
| 487 |
+
except MemoryError:
|
| 488 |
+
# The above is too big. Let's try with something much small
|
| 489 |
+
# (and less optimal)
|
| 490 |
+
n_best_tot = 10
|
| 491 |
+
all_best_covariances = np.zeros((n_best_tot, n_features, n_features))
|
| 492 |
+
n_best_sub = 2
|
| 493 |
+
for i in range(n_subsets):
|
| 494 |
+
low_bound = i * n_samples_subsets
|
| 495 |
+
high_bound = low_bound + n_samples_subsets
|
| 496 |
+
current_subset = X[samples_shuffle[low_bound:high_bound]]
|
| 497 |
+
best_locations_sub, best_covariances_sub, _, _ = select_candidates(
|
| 498 |
+
current_subset,
|
| 499 |
+
h_subset,
|
| 500 |
+
n_trials,
|
| 501 |
+
select=n_best_sub,
|
| 502 |
+
n_iter=2,
|
| 503 |
+
cov_computation_method=cov_computation_method,
|
| 504 |
+
random_state=random_state,
|
| 505 |
+
)
|
| 506 |
+
subset_slice = np.arange(i * n_best_sub, (i + 1) * n_best_sub)
|
| 507 |
+
all_best_locations[subset_slice] = best_locations_sub
|
| 508 |
+
all_best_covariances[subset_slice] = best_covariances_sub
|
| 509 |
+
# 2. Pool the candidate supports into a merged set
|
| 510 |
+
# (possibly the full dataset)
|
| 511 |
+
n_samples_merged = min(1500, n_samples)
|
| 512 |
+
h_merged = int(np.ceil(n_samples_merged * (n_support / float(n_samples))))
|
| 513 |
+
if n_samples > 1500:
|
| 514 |
+
n_best_merged = 10
|
| 515 |
+
else:
|
| 516 |
+
n_best_merged = 1
|
| 517 |
+
# find the best couples (location, covariance) on the merged set
|
| 518 |
+
selection = random_state.permutation(n_samples)[:n_samples_merged]
|
| 519 |
+
locations_merged, covariances_merged, supports_merged, d = select_candidates(
|
| 520 |
+
X[selection],
|
| 521 |
+
h_merged,
|
| 522 |
+
n_trials=(all_best_locations, all_best_covariances),
|
| 523 |
+
select=n_best_merged,
|
| 524 |
+
cov_computation_method=cov_computation_method,
|
| 525 |
+
random_state=random_state,
|
| 526 |
+
)
|
| 527 |
+
# 3. Finally get the overall best (locations, covariance) couple
|
| 528 |
+
if n_samples < 1500:
|
| 529 |
+
# directly get the best couple (location, covariance)
|
| 530 |
+
location = locations_merged[0]
|
| 531 |
+
covariance = covariances_merged[0]
|
| 532 |
+
support = np.zeros(n_samples, dtype=bool)
|
| 533 |
+
dist = np.zeros(n_samples)
|
| 534 |
+
support[selection] = supports_merged[0]
|
| 535 |
+
dist[selection] = d[0]
|
| 536 |
+
else:
|
| 537 |
+
# select the best couple on the full dataset
|
| 538 |
+
locations_full, covariances_full, supports_full, d = select_candidates(
|
| 539 |
+
X,
|
| 540 |
+
n_support,
|
| 541 |
+
n_trials=(locations_merged, covariances_merged),
|
| 542 |
+
select=1,
|
| 543 |
+
cov_computation_method=cov_computation_method,
|
| 544 |
+
random_state=random_state,
|
| 545 |
+
)
|
| 546 |
+
location = locations_full[0]
|
| 547 |
+
covariance = covariances_full[0]
|
| 548 |
+
support = supports_full[0]
|
| 549 |
+
dist = d[0]
|
| 550 |
+
elif n_features > 1:
|
| 551 |
+
# 1. Find the 10 best couples (location, covariance)
|
| 552 |
+
# considering two iterations
|
| 553 |
+
n_trials = 30
|
| 554 |
+
n_best = 10
|
| 555 |
+
locations_best, covariances_best, _, _ = select_candidates(
|
| 556 |
+
X,
|
| 557 |
+
n_support,
|
| 558 |
+
n_trials=n_trials,
|
| 559 |
+
select=n_best,
|
| 560 |
+
n_iter=2,
|
| 561 |
+
cov_computation_method=cov_computation_method,
|
| 562 |
+
random_state=random_state,
|
| 563 |
+
)
|
| 564 |
+
# 2. Select the best couple on the full dataset amongst the 10
|
| 565 |
+
locations_full, covariances_full, supports_full, d = select_candidates(
|
| 566 |
+
X,
|
| 567 |
+
n_support,
|
| 568 |
+
n_trials=(locations_best, covariances_best),
|
| 569 |
+
select=1,
|
| 570 |
+
cov_computation_method=cov_computation_method,
|
| 571 |
+
random_state=random_state,
|
| 572 |
+
)
|
| 573 |
+
location = locations_full[0]
|
| 574 |
+
covariance = covariances_full[0]
|
| 575 |
+
support = supports_full[0]
|
| 576 |
+
dist = d[0]
|
| 577 |
+
|
| 578 |
+
return location, covariance, support, dist
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
class MinCovDet(EmpiricalCovariance):
|
| 582 |
+
"""Minimum Covariance Determinant (MCD): robust estimator of covariance.
|
| 583 |
+
|
| 584 |
+
The Minimum Covariance Determinant covariance estimator is to be applied
|
| 585 |
+
on Gaussian-distributed data, but could still be relevant on data
|
| 586 |
+
drawn from a unimodal, symmetric distribution. It is not meant to be used
|
| 587 |
+
with multi-modal data (the algorithm used to fit a MinCovDet object is
|
| 588 |
+
likely to fail in such a case).
|
| 589 |
+
One should consider projection pursuit methods to deal with multi-modal
|
| 590 |
+
datasets.
|
| 591 |
+
|
| 592 |
+
Read more in the :ref:`User Guide <robust_covariance>`.
|
| 593 |
+
|
| 594 |
+
Parameters
|
| 595 |
+
----------
|
| 596 |
+
store_precision : bool, default=True
|
| 597 |
+
Specify if the estimated precision is stored.
|
| 598 |
+
|
| 599 |
+
assume_centered : bool, default=False
|
| 600 |
+
If True, the support of the robust location and the covariance
|
| 601 |
+
estimates is computed, and a covariance estimate is recomputed from
|
| 602 |
+
it, without centering the data.
|
| 603 |
+
Useful to work with data whose mean is significantly equal to
|
| 604 |
+
zero but is not exactly zero.
|
| 605 |
+
If False, the robust location and covariance are directly computed
|
| 606 |
+
with the FastMCD algorithm without additional treatment.
|
| 607 |
+
|
| 608 |
+
support_fraction : float, default=None
|
| 609 |
+
The proportion of points to be included in the support of the raw
|
| 610 |
+
MCD estimate. Default is None, which implies that the minimum
|
| 611 |
+
value of support_fraction will be used within the algorithm:
|
| 612 |
+
`(n_samples + n_features + 1) / 2 * n_samples`. The parameter must be
|
| 613 |
+
in the range (0, 1].
|
| 614 |
+
|
| 615 |
+
random_state : int, RandomState instance or None, default=None
|
| 616 |
+
Determines the pseudo random number generator for shuffling the data.
|
| 617 |
+
Pass an int for reproducible results across multiple function calls.
|
| 618 |
+
See :term:`Glossary <random_state>`.
|
| 619 |
+
|
| 620 |
+
Attributes
|
| 621 |
+
----------
|
| 622 |
+
raw_location_ : ndarray of shape (n_features,)
|
| 623 |
+
The raw robust estimated location before correction and re-weighting.
|
| 624 |
+
|
| 625 |
+
raw_covariance_ : ndarray of shape (n_features, n_features)
|
| 626 |
+
The raw robust estimated covariance before correction and re-weighting.
|
| 627 |
+
|
| 628 |
+
raw_support_ : ndarray of shape (n_samples,)
|
| 629 |
+
A mask of the observations that have been used to compute
|
| 630 |
+
the raw robust estimates of location and shape, before correction
|
| 631 |
+
and re-weighting.
|
| 632 |
+
|
| 633 |
+
location_ : ndarray of shape (n_features,)
|
| 634 |
+
Estimated robust location.
|
| 635 |
+
|
| 636 |
+
For an example of comparing raw robust estimates with
|
| 637 |
+
the true location and covariance, refer to
|
| 638 |
+
:ref:`sphx_glr_auto_examples_covariance_plot_robust_vs_empirical_covariance.py`.
|
| 639 |
+
|
| 640 |
+
covariance_ : ndarray of shape (n_features, n_features)
|
| 641 |
+
Estimated robust covariance matrix.
|
| 642 |
+
|
| 643 |
+
precision_ : ndarray of shape (n_features, n_features)
|
| 644 |
+
Estimated pseudo inverse matrix.
|
| 645 |
+
(stored only if store_precision is True)
|
| 646 |
+
|
| 647 |
+
support_ : ndarray of shape (n_samples,)
|
| 648 |
+
A mask of the observations that have been used to compute
|
| 649 |
+
the robust estimates of location and shape.
|
| 650 |
+
|
| 651 |
+
dist_ : ndarray of shape (n_samples,)
|
| 652 |
+
Mahalanobis distances of the training set (on which :meth:`fit` is
|
| 653 |
+
called) observations.
|
| 654 |
+
|
| 655 |
+
n_features_in_ : int
|
| 656 |
+
Number of features seen during :term:`fit`.
|
| 657 |
+
|
| 658 |
+
.. versionadded:: 0.24
|
| 659 |
+
|
| 660 |
+
feature_names_in_ : ndarray of shape (`n_features_in_`,)
|
| 661 |
+
Names of features seen during :term:`fit`. Defined only when `X`
|
| 662 |
+
has feature names that are all strings.
|
| 663 |
+
|
| 664 |
+
.. versionadded:: 1.0
|
| 665 |
+
|
| 666 |
+
See Also
|
| 667 |
+
--------
|
| 668 |
+
EllipticEnvelope : An object for detecting outliers in
|
| 669 |
+
a Gaussian distributed dataset.
|
| 670 |
+
EmpiricalCovariance : Maximum likelihood covariance estimator.
|
| 671 |
+
GraphicalLasso : Sparse inverse covariance estimation
|
| 672 |
+
with an l1-penalized estimator.
|
| 673 |
+
GraphicalLassoCV : Sparse inverse covariance with cross-validated
|
| 674 |
+
choice of the l1 penalty.
|
| 675 |
+
LedoitWolf : LedoitWolf Estimator.
|
| 676 |
+
OAS : Oracle Approximating Shrinkage Estimator.
|
| 677 |
+
ShrunkCovariance : Covariance estimator with shrinkage.
|
| 678 |
+
|
| 679 |
+
References
|
| 680 |
+
----------
|
| 681 |
+
|
| 682 |
+
.. [Rouseeuw1984] P. J. Rousseeuw. Least median of squares regression.
|
| 683 |
+
J. Am Stat Ass, 79:871, 1984.
|
| 684 |
+
.. [Rousseeuw] A Fast Algorithm for the Minimum Covariance Determinant
|
| 685 |
+
Estimator, 1999, American Statistical Association and the American
|
| 686 |
+
Society for Quality, TECHNOMETRICS
|
| 687 |
+
.. [ButlerDavies] R. W. Butler, P. L. Davies and M. Jhun,
|
| 688 |
+
Asymptotics For The Minimum Covariance Determinant Estimator,
|
| 689 |
+
The Annals of Statistics, 1993, Vol. 21, No. 3, 1385-1400
|
| 690 |
+
|
| 691 |
+
Examples
|
| 692 |
+
--------
|
| 693 |
+
>>> import numpy as np
|
| 694 |
+
>>> from sklearn.covariance import MinCovDet
|
| 695 |
+
>>> from sklearn.datasets import make_gaussian_quantiles
|
| 696 |
+
>>> real_cov = np.array([[.8, .3],
|
| 697 |
+
... [.3, .4]])
|
| 698 |
+
>>> rng = np.random.RandomState(0)
|
| 699 |
+
>>> X = rng.multivariate_normal(mean=[0, 0],
|
| 700 |
+
... cov=real_cov,
|
| 701 |
+
... size=500)
|
| 702 |
+
>>> cov = MinCovDet(random_state=0).fit(X)
|
| 703 |
+
>>> cov.covariance_
|
| 704 |
+
array([[0.7411, 0.2535],
|
| 705 |
+
[0.2535, 0.3053]])
|
| 706 |
+
>>> cov.location_
|
| 707 |
+
array([0.0813 , 0.0427])
|
| 708 |
+
"""
|
| 709 |
+
|
| 710 |
+
_parameter_constraints: dict = {
|
| 711 |
+
**EmpiricalCovariance._parameter_constraints,
|
| 712 |
+
"support_fraction": [Interval(Real, 0, 1, closed="right"), None],
|
| 713 |
+
"random_state": ["random_state"],
|
| 714 |
+
}
|
| 715 |
+
_nonrobust_covariance = staticmethod(empirical_covariance)
|
| 716 |
+
|
| 717 |
+
def __init__(
|
| 718 |
+
self,
|
| 719 |
+
*,
|
| 720 |
+
store_precision=True,
|
| 721 |
+
assume_centered=False,
|
| 722 |
+
support_fraction=None,
|
| 723 |
+
random_state=None,
|
| 724 |
+
):
|
| 725 |
+
self.store_precision = store_precision
|
| 726 |
+
self.assume_centered = assume_centered
|
| 727 |
+
self.support_fraction = support_fraction
|
| 728 |
+
self.random_state = random_state
|
| 729 |
+
|
| 730 |
+
@_fit_context(prefer_skip_nested_validation=True)
|
| 731 |
+
def fit(self, X, y=None):
|
| 732 |
+
"""Fit a Minimum Covariance Determinant with the FastMCD algorithm.
|
| 733 |
+
|
| 734 |
+
Parameters
|
| 735 |
+
----------
|
| 736 |
+
X : array-like of shape (n_samples, n_features)
|
| 737 |
+
Training data, where `n_samples` is the number of samples
|
| 738 |
+
and `n_features` is the number of features.
|
| 739 |
+
|
| 740 |
+
y : Ignored
|
| 741 |
+
Not used, present for API consistency by convention.
|
| 742 |
+
|
| 743 |
+
Returns
|
| 744 |
+
-------
|
| 745 |
+
self : object
|
| 746 |
+
Returns the instance itself.
|
| 747 |
+
"""
|
| 748 |
+
X = validate_data(self, X, ensure_min_samples=2, estimator="MinCovDet")
|
| 749 |
+
random_state = check_random_state(self.random_state)
|
| 750 |
+
n_samples, n_features = X.shape
|
| 751 |
+
# check that the empirical covariance is full rank
|
| 752 |
+
if (linalg.svdvals(np.dot(X.T, X)) > 1e-8).sum() != n_features:
|
| 753 |
+
warnings.warn(
|
| 754 |
+
"The covariance matrix associated to your dataset is not full rank"
|
| 755 |
+
)
|
| 756 |
+
# compute and store raw estimates
|
| 757 |
+
raw_location, raw_covariance, raw_support, raw_dist = fast_mcd(
|
| 758 |
+
X,
|
| 759 |
+
support_fraction=self.support_fraction,
|
| 760 |
+
cov_computation_method=self._nonrobust_covariance,
|
| 761 |
+
random_state=random_state,
|
| 762 |
+
)
|
| 763 |
+
if self.assume_centered:
|
| 764 |
+
raw_location = np.zeros(n_features)
|
| 765 |
+
raw_covariance = self._nonrobust_covariance(
|
| 766 |
+
X[raw_support], assume_centered=True
|
| 767 |
+
)
|
| 768 |
+
# get precision matrix in an optimized way
|
| 769 |
+
precision = linalg.pinvh(raw_covariance)
|
| 770 |
+
raw_dist = np.sum(np.dot(X, precision) * X, 1)
|
| 771 |
+
self.raw_location_ = raw_location
|
| 772 |
+
self.raw_covariance_ = raw_covariance
|
| 773 |
+
self.raw_support_ = raw_support
|
| 774 |
+
self.location_ = raw_location
|
| 775 |
+
self.support_ = raw_support
|
| 776 |
+
self.dist_ = raw_dist
|
| 777 |
+
# obtain consistency at normal models
|
| 778 |
+
self.correct_covariance(X)
|
| 779 |
+
# re-weight estimator
|
| 780 |
+
self.reweight_covariance(X)
|
| 781 |
+
|
| 782 |
+
return self
|
| 783 |
+
|
| 784 |
+
def correct_covariance(self, data):
|
| 785 |
+
"""Apply a correction to raw Minimum Covariance Determinant estimates.
|
| 786 |
+
|
| 787 |
+
Correction using the empirical correction factor suggested
|
| 788 |
+
by Rousseeuw and Van Driessen in [RVD]_.
|
| 789 |
+
|
| 790 |
+
Parameters
|
| 791 |
+
----------
|
| 792 |
+
data : array-like of shape (n_samples, n_features)
|
| 793 |
+
The data matrix, with p features and n samples.
|
| 794 |
+
The data set must be the one which was used to compute
|
| 795 |
+
the raw estimates.
|
| 796 |
+
|
| 797 |
+
Returns
|
| 798 |
+
-------
|
| 799 |
+
covariance_corrected : ndarray of shape (n_features, n_features)
|
| 800 |
+
Corrected robust covariance estimate.
|
| 801 |
+
|
| 802 |
+
References
|
| 803 |
+
----------
|
| 804 |
+
|
| 805 |
+
.. [RVD] A Fast Algorithm for the Minimum Covariance
|
| 806 |
+
Determinant Estimator, 1999, American Statistical Association
|
| 807 |
+
and the American Society for Quality, TECHNOMETRICS
|
| 808 |
+
"""
|
| 809 |
+
|
| 810 |
+
# Check that the covariance of the support data is not equal to 0.
|
| 811 |
+
# Otherwise self.dist_ = 0 and thus correction = 0.
|
| 812 |
+
n_samples = len(self.dist_)
|
| 813 |
+
n_support = np.sum(self.support_)
|
| 814 |
+
if n_support < n_samples and np.allclose(self.raw_covariance_, 0):
|
| 815 |
+
raise ValueError(
|
| 816 |
+
"The covariance matrix of the support data "
|
| 817 |
+
"is equal to 0, try to increase support_fraction"
|
| 818 |
+
)
|
| 819 |
+
correction = np.median(self.dist_) / chi2(data.shape[1]).isf(0.5)
|
| 820 |
+
covariance_corrected = self.raw_covariance_ * correction
|
| 821 |
+
self.dist_ /= correction
|
| 822 |
+
return covariance_corrected
|
| 823 |
+
|
| 824 |
+
def reweight_covariance(self, data):
|
| 825 |
+
"""Re-weight raw Minimum Covariance Determinant estimates.
|
| 826 |
+
|
| 827 |
+
Re-weight observations using Rousseeuw's method (equivalent to
|
| 828 |
+
deleting outlying observations from the data set before
|
| 829 |
+
computing location and covariance estimates) described
|
| 830 |
+
in [RVDriessen]_.
|
| 831 |
+
|
| 832 |
+
Parameters
|
| 833 |
+
----------
|
| 834 |
+
data : array-like of shape (n_samples, n_features)
|
| 835 |
+
The data matrix, with p features and n samples.
|
| 836 |
+
The data set must be the one which was used to compute
|
| 837 |
+
the raw estimates.
|
| 838 |
+
|
| 839 |
+
Returns
|
| 840 |
+
-------
|
| 841 |
+
location_reweighted : ndarray of shape (n_features,)
|
| 842 |
+
Re-weighted robust location estimate.
|
| 843 |
+
|
| 844 |
+
covariance_reweighted : ndarray of shape (n_features, n_features)
|
| 845 |
+
Re-weighted robust covariance estimate.
|
| 846 |
+
|
| 847 |
+
support_reweighted : ndarray of shape (n_samples,), dtype=bool
|
| 848 |
+
A mask of the observations that have been used to compute
|
| 849 |
+
the re-weighted robust location and covariance estimates.
|
| 850 |
+
|
| 851 |
+
References
|
| 852 |
+
----------
|
| 853 |
+
|
| 854 |
+
.. [RVDriessen] A Fast Algorithm for the Minimum Covariance
|
| 855 |
+
Determinant Estimator, 1999, American Statistical Association
|
| 856 |
+
and the American Society for Quality, TECHNOMETRICS
|
| 857 |
+
"""
|
| 858 |
+
n_samples, n_features = data.shape
|
| 859 |
+
mask = self.dist_ < chi2(n_features).isf(0.025)
|
| 860 |
+
if self.assume_centered:
|
| 861 |
+
location_reweighted = np.zeros(n_features)
|
| 862 |
+
else:
|
| 863 |
+
location_reweighted = data[mask].mean(0)
|
| 864 |
+
covariance_reweighted = self._nonrobust_covariance(
|
| 865 |
+
data[mask], assume_centered=self.assume_centered
|
| 866 |
+
)
|
| 867 |
+
support_reweighted = np.zeros(n_samples, dtype=bool)
|
| 868 |
+
support_reweighted[mask] = True
|
| 869 |
+
self._set_covariance(covariance_reweighted)
|
| 870 |
+
self.location_ = location_reweighted
|
| 871 |
+
self.support_ = support_reweighted
|
| 872 |
+
X_centered = data - self.location_
|
| 873 |
+
self.dist_ = np.sum(np.dot(X_centered, self.get_precision()) * X_centered, 1)
|
| 874 |
+
return location_reweighted, covariance_reweighted, support_reweighted
|
shared/package-files/ab/ab82d8897c5fc1651cd62a38bd1541afdbb131a71f75e7cfbdc4656f74ce127c/blob
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test the minimum spanning tree function"""
|
| 2 |
+
import numpy as np
|
| 3 |
+
from numpy.testing import assert_
|
| 4 |
+
import numpy.testing as npt
|
| 5 |
+
from scipy.sparse import csr_array
|
| 6 |
+
from scipy.sparse.csgraph import minimum_spanning_tree
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_minimum_spanning_tree():
|
| 10 |
+
|
| 11 |
+
# Create a graph with two connected components.
|
| 12 |
+
graph = [[0,1,0,0,0],
|
| 13 |
+
[1,0,0,0,0],
|
| 14 |
+
[0,0,0,8,5],
|
| 15 |
+
[0,0,8,0,1],
|
| 16 |
+
[0,0,5,1,0]]
|
| 17 |
+
graph = np.asarray(graph)
|
| 18 |
+
|
| 19 |
+
# Create the expected spanning tree.
|
| 20 |
+
expected = [[0,1,0,0,0],
|
| 21 |
+
[0,0,0,0,0],
|
| 22 |
+
[0,0,0,0,5],
|
| 23 |
+
[0,0,0,0,1],
|
| 24 |
+
[0,0,0,0,0]]
|
| 25 |
+
expected = np.asarray(expected)
|
| 26 |
+
|
| 27 |
+
# Ensure minimum spanning tree code gives this expected output.
|
| 28 |
+
csgraph = csr_array(graph)
|
| 29 |
+
mintree = minimum_spanning_tree(csgraph)
|
| 30 |
+
mintree_array = mintree.toarray()
|
| 31 |
+
npt.assert_array_equal(mintree_array, expected,
|
| 32 |
+
'Incorrect spanning tree found.')
|
| 33 |
+
|
| 34 |
+
# Ensure that the original graph was not modified.
|
| 35 |
+
npt.assert_array_equal(csgraph.toarray(), graph,
|
| 36 |
+
'Original graph was modified.')
|
| 37 |
+
|
| 38 |
+
# Now let the algorithm modify the csgraph in place.
|
| 39 |
+
mintree = minimum_spanning_tree(csgraph, overwrite=True)
|
| 40 |
+
npt.assert_array_equal(mintree.toarray(), expected,
|
| 41 |
+
'Graph was not properly modified to contain MST.')
|
| 42 |
+
|
| 43 |
+
np.random.seed(1234)
|
| 44 |
+
for N in (5, 10, 15, 20):
|
| 45 |
+
|
| 46 |
+
# Create a random graph.
|
| 47 |
+
graph = 3 + np.random.random((N, N))
|
| 48 |
+
csgraph = csr_array(graph)
|
| 49 |
+
|
| 50 |
+
# The spanning tree has at most N - 1 edges.
|
| 51 |
+
mintree = minimum_spanning_tree(csgraph)
|
| 52 |
+
assert_(mintree.nnz < N)
|
| 53 |
+
|
| 54 |
+
# Set the sub diagonal to 1 to create a known spanning tree.
|
| 55 |
+
idx = np.arange(N-1)
|
| 56 |
+
graph[idx,idx+1] = 1
|
| 57 |
+
csgraph = csr_array(graph)
|
| 58 |
+
mintree = minimum_spanning_tree(csgraph)
|
| 59 |
+
|
| 60 |
+
# We expect to see this pattern in the spanning tree and otherwise
|
| 61 |
+
# have this zero.
|
| 62 |
+
expected = np.zeros((N, N))
|
| 63 |
+
expected[idx, idx+1] = 1
|
| 64 |
+
|
| 65 |
+
npt.assert_array_equal(mintree.toarray(), expected,
|
| 66 |
+
'Incorrect spanning tree found.')
|
shared/package-files/ab/ab837b032c5aae84503fc0c733a116a26fd272e90dc4402fa68d3c9e51aed3b0/blob
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The MIT License (MIT)
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2014-2022 Anthon van der Neut, Ruamel bvba
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in
|
| 13 |
+
all copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|