s42chen commited on
Commit
95668df
·
verified ·
1 Parent(s): bc033f8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. shared/package-files/02/02015ddd124031a908e80c420f37ceac68125fb51e023c6f3c7b374739369ece/test_numbers.py +2266 -0
  2. shared/package-files/02/0201abc9e320bf0a23453582581971b0bf4f826a91e4cd1e0b1283ddfe214bf7/is_complex.h +30 -0
  3. shared/package-files/02/0203398ea9789f2c6b4c3e73970d030b5a5138b46d94bdadb5439223407486ac/kernel_approximation.py +1106 -0
  4. shared/package-files/02/020417a134f7c95351600141013eb61c1a2efcaf411dfbad1ffd6554b906be69/frexp_cpu_dispatch.h +24 -0
  5. shared/package-files/02/020861c07567ff026c101068f931e6308293f73afe80126590b4dcb49ad3fde6/factortools.py +1502 -0
  6. shared/package-files/02/020f6b521a01c9253a6dadf014b7ae67258c267cfd56401ff53404cd61b88545/_dataset.pxd +183 -0
  7. shared/package-files/02/02108ef43132cac13e3fe40917daf252d275821538ff498e461009e7da6839b5/shape_base.py +1274 -0
  8. shared/package-files/02/0212b936e3a9743f898c8cd73a5b2c13cfe248bc850001f3c8657fc35053eef0/__init__.pyi +50 -0
  9. shared/package-files/02/02169eb141a5fbd8adeaebc6e9fb053ceafdca716919a4cc938b795d35fb67f4/urls.py +62 -0
  10. shared/package-files/02/0217e96269b35ecf856e039eb6839d9759618f5ab5398df43a0cfceb9a5ee5ac/_upsample_nearest_exact3d_backward_cuda_dispatch.h +28 -0
  11. shared/package-files/02/021afcab2215adef14fc95512c72f405b4a86297498e8d8e51e135503e08d6dc/size_statistics.h +102 -0
  12. shared/package-files/02/021bb387f2f520bdaa862561ad486d626a69305d3e0ebfd485e5c2a6dce6ff0b/mkldnn_rnn_layer_backward_cpu_dispatch.h +23 -0
  13. shared/package-files/02/021e1390d23f09f62a49783b3454ff24e812e665b75d0c72fc2c266781c15c41/quantized_max_pool3d_compositeexplicitautograd_dispatch.h +24 -0
  14. shared/package-files/02/021e1e444979d8be58ce9a7762466ff33564350d73bf7b38f2de2a075753c59a/_masked_scale_native.h +22 -0
  15. shared/package-files/02/021e4cf393e96bccd818eb4b3a2cd6d20ce5b63b376f89c3e7aa8579047bf795/backend_cairo.py +529 -0
  16. shared/package-files/02/021f73fada072546c4f63f8cf18a7181244ce4280b09cc15cc980b2d1176171a/error.py +75 -0
  17. shared/package-files/02/0223395091042ca6c5c86ee83cada3b566d89860bb258b345898f2fb59340836/ntconsole-35-nti +0 -0
  18. shared/package-files/02/0223395091042ca6c5c86ee83cada3b566d89860bb258b345898f2fb59340836/opennt-35-nti +0 -0
  19. shared/package-files/02/02244e7d6c5346b313ef92d9b2b04c25322cde4cbd9f5c779d49d7ccaa5920b3/html.py +646 -0
  20. shared/package-files/02/02273b35c63ac179113f9494ebabc086b716ca5c1ef22efcbb69f37de9e7ec56/webbrowser.pyi +105 -0
  21. shared/package-files/02/0229b075bf5ab357492996853541f63a158854155de9990927f58ae6c358f1c5/enums.py +76 -0
  22. shared/package-files/02/022bbf749fe8c6af98d555e7b39379bb92b55a78368730a04604620e14c08952/interpolate.py +30 -0
  23. shared/package-files/02/022c9bf5cde1ba759ce9b93a4ed8d0ce33c3242be07a965c8168601f8346d63c/test_rotation.py +2188 -0
  24. shared/package-files/02/022dbf37ea549879e024ddeeb2231334eea47cb5855506b758e7addd585e844f/logic.py +427 -0
  25. shared/package-files/02/022e9d78388697050747d995be59086d76335990031ee3cb95a0630cad11db05/test_libfrequencies.py +27 -0
  26. shared/package-files/02/02318a5a89979435f62358c277844e909afc9d1b6bde87e6dcc757447dd84d3a/_utils.py +220 -0
  27. shared/package-files/02/02320a4c11fda2fa2de2aef6eae7132a8bb5cb53acf065ed195a7369572d7b57/fill_ops.h +83 -0
  28. shared/package-files/02/02361b49af673a5bffc9c64e4627dd9bb07e6fd29d282d4757e7062c3b6b27ec/test_multiprocessing.py +46 -0
  29. shared/package-files/02/023872fe9f03a25387cf2c17fc950cf0f990353df66e603c3a1cd3199dbccd86/fix_operator.py +97 -0
  30. shared/package-files/02/023c3bb9dead92eb49f431aadc435a69e5ef7fa8e88e82ad34f426eabf0f0701/fft_fftn_compositeimplicitautograd_dispatch.h +28 -0
  31. shared/package-files/02/023c4e4d6552b9693e65e86713a27315531459a94e8b54493faaca5f5031ce7d/_slow_conv2d_backward_cpu_dispatch.h +28 -0
  32. shared/package-files/02/023d292c442b3477106e4b6755abaed01afc7b80c6878f4084d3478832a140e4/direct_url.json +1 -0
  33. shared/package-files/02/023e5dc747d51d3fc1ecdaa58958424c0f690bf440912ad93eba18eff584d1fd/memory_snapshot.h +27 -0
  34. shared/package-files/02/02400a365357a04774bb02b8365809e39390d72c9c6f1a69bdd60be41923fe9e/import_export_helpers.h +32 -0
  35. shared/package-files/02/024983a51d08171a34adeb7dd6d44f614aab8107d0dfaee8913b7611ed959bad/test_partitions.py +12 -0
  36. shared/package-files/02/024e76301aa38fc4e4c57e4cb51abbccb0d1fe8ddcd3f49d4095d4d550ef6d37/cudnn_convolution_transpose_compositeexplicitautograd_dispatch.h +26 -0
  37. shared/package-files/02/0250ba18275c1b7b4d54a7e5e5b2353d0408b938baae10783661d24123dc31d0/test_register.py +324 -0
  38. shared/package-files/02/0258ffb6181b7487bacc36f2af8c1e88469f25fe6819e5f66167ade2c027eece/_sparse_sum_ops.h +72 -0
  39. shared/package-files/02/025a9531e3046e52d3e039c0be04f9a5a74651d7683a13c7c7ebd4c7dfb5996a/hz.py +39 -0
  40. shared/package-files/02/025b702d601b96948b6bedb82af36ec58c4cd88795979a7677e928cc0f5027ed/test_cluster.py +543 -0
  41. shared/package-files/02/025d4339487853fa1f3144127959734b20f7c7b4948cff5d72149a0541a67968/Perth +0 -0
  42. shared/package-files/02/025d4339487853fa1f3144127959734b20f7c7b4948cff5d72149a0541a67968/West +0 -0
  43. shared/package-files/02/025d8146a57a50508862173f59f39378ccb975b89ef392b45b4bd345cb66b013/test_impute.py +1955 -0
  44. shared/package-files/02/025ded03bcca34b5f15007866b57b59ddb28690b529bca2e3d84fbff389f7a32/mock.pyi +441 -0
  45. shared/package-files/02/025ff8ea6f9aed99288b5e08134d130901b618c4f99511b3a362a36dcdc9e24a/RECORD +8 -0
  46. shared/package-files/02/0260a8adba1cab755fa9526753ac2d5721844a096cd5af9678f3f9065dd58b71/autocomplete.pyi +10 -0
  47. shared/package-files/02/026149be336a491d5dedde9fd3d1620efc18c07141ed8ccece4b80ee7d5ba43a/_triton_ops.py +1928 -0
  48. shared/package-files/02/02626d8a4274da23b9e9b62ac145513df5b0249a905506b9671d8b94a20d5bc8/logaddexp2_ops.h +39 -0
  49. shared/package-files/02/026283dbf8f6ab28f1aede20d07f13ec60653293e7da495eac2fd13aa3f6e289/exceptions.py +58 -0
  50. shared/package-files/02/0265538f01680aa1f77a46a16c0af7dae9629177abaed07bc9c3480de5f7da55/Types.h +13 -0
shared/package-files/02/02015ddd124031a908e80c420f37ceac68125fb51e023c6f3c7b374739369ece/test_numbers.py ADDED
@@ -0,0 +1,2266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numbers as nums
2
+ import decimal
3
+ from sympy.concrete.summations import Sum
4
+ from sympy.core import (EulerGamma, Catalan, TribonacciConstant,
5
+ GoldenRatio)
6
+ from sympy.core.containers import Tuple
7
+ from sympy.core.expr import unchanged
8
+ from sympy.core.logic import fuzzy_not
9
+ from sympy.core.mul import Mul
10
+ from sympy.core.numbers import (mpf_norm, mod_inverse, igcd, seterr,
11
+ igcd_lehmer, Integer, I, pi, comp, ilcm, Rational, E, nan, igcd2,
12
+ oo, AlgebraicNumber, igcdex, Number, Float, zoo, equal_valued)
13
+ from sympy.core.power import Pow
14
+ from sympy.core.relational import Ge, Gt, Le, Lt
15
+ from sympy.core.singleton import S
16
+ from sympy.core.symbol import Dummy, Symbol
17
+ from sympy.core.sympify import sympify
18
+ from sympy.functions.combinatorial.factorials import factorial
19
+ from sympy.functions.elementary.integers import floor
20
+ from sympy.functions.combinatorial.numbers import fibonacci
21
+ from sympy.functions.elementary.exponential import exp, log
22
+ from sympy.functions.elementary.miscellaneous import sqrt, cbrt
23
+ from sympy.functions.elementary.trigonometric import cos, sin
24
+ from sympy.polys.domains.realfield import RealField
25
+ from sympy.printing.latex import latex
26
+ from sympy.printing.repr import srepr
27
+ from sympy.simplify import simplify
28
+ from sympy.core.power import integer_nthroot, isqrt, integer_log
29
+ from sympy.polys.domains.groundtypes import PythonRational
30
+ from sympy.utilities.decorator import conserve_mpmath_dps
31
+ from sympy.utilities.iterables import permutations
32
+ from sympy.testing.pytest import XFAIL, raises, _both_exp_pow
33
+
34
+ from mpmath import mpf
35
+ from mpmath.rational import mpq
36
+ import mpmath
37
+ from sympy.core import numbers
38
+ t = Symbol('t', real=False)
39
+
40
+ _ninf = float(-oo)
41
+ _inf = float(oo)
42
+
43
+
44
+ def same_and_same_prec(a, b):
45
+ # stricter matching for Floats
46
+ return a == b and a._prec == b._prec
47
+
48
+
49
+ def test_seterr():
50
+ seterr(divide=True)
51
+ raises(ValueError, lambda: S.Zero/S.Zero)
52
+ seterr(divide=False)
53
+ assert S.Zero / S.Zero is S.NaN
54
+
55
+
56
+ def test_mod():
57
+ x = S.Half
58
+ y = Rational(3, 4)
59
+ z = Rational(5, 18043)
60
+
61
+ assert x % x == 0
62
+ assert x % y == S.Half
63
+ assert x % z == Rational(3, 36086)
64
+ assert y % x == Rational(1, 4)
65
+ assert y % y == 0
66
+ assert y % z == Rational(9, 72172)
67
+ assert z % x == Rational(5, 18043)
68
+ assert z % y == Rational(5, 18043)
69
+ assert z % z == 0
70
+
71
+ a = Float(2.6)
72
+
73
+ assert (a % .2) == 0.0
74
+ assert (a % 2).round(15) == 0.6
75
+ assert (a % 0.5).round(15) == 0.1
76
+
77
+ p = Symbol('p', infinite=True)
78
+
79
+ assert oo % oo is nan
80
+ assert zoo % oo is nan
81
+ assert 5 % oo is nan
82
+ assert p % 5 is nan
83
+
84
+ # In these two tests, if the precision of m does
85
+ # not match the precision of the ans, then it is
86
+ # likely that the change made now gives an answer
87
+ # with degraded accuracy.
88
+ r = Rational(500, 41)
89
+ f = Float('.36', 3)
90
+ m = r % f
91
+ ans = Float(r % Rational(f), 3)
92
+ assert m == ans and m._prec == ans._prec
93
+ f = Float('8.36', 3)
94
+ m = f % r
95
+ ans = Float(Rational(f) % r, 3)
96
+ assert m == ans and m._prec == ans._prec
97
+
98
+ s = S.Zero
99
+
100
+ assert s % float(1) == 0.0
101
+
102
+ # No rounding required since these numbers can be represented
103
+ # exactly.
104
+ assert Rational(3, 4) % Float(1.1) == 0.75
105
+ assert Float(1.5) % Rational(5, 4) == 0.25
106
+ assert Rational(5, 4).__rmod__(Float('1.5')) == 0.25
107
+ assert Float('1.5').__rmod__(Float('2.75')) == Float('1.25')
108
+ assert 2.75 % Float('1.5') == Float('1.25')
109
+
110
+ a = Integer(7)
111
+ b = Integer(4)
112
+
113
+ assert type(a % b) == Integer
114
+ assert a % b == Integer(3)
115
+ assert Integer(1) % Rational(2, 3) == Rational(1, 3)
116
+ assert Rational(7, 5) % Integer(1) == Rational(2, 5)
117
+ assert Integer(2) % 1.5 == 0.5
118
+
119
+ assert Integer(3).__rmod__(Integer(10)) == Integer(1)
120
+ assert Integer(10) % 4 == Integer(2)
121
+ assert 15 % Integer(4) == Integer(3)
122
+
123
+
124
+ def test_divmod():
125
+ x = Symbol("x")
126
+ assert divmod(S(12), S(8)) == Tuple(1, 4)
127
+ assert divmod(-S(12), S(8)) == Tuple(-2, 4)
128
+ assert divmod(S.Zero, S.One) == Tuple(0, 0)
129
+ raises(ZeroDivisionError, lambda: divmod(S.Zero, S.Zero))
130
+ raises(ZeroDivisionError, lambda: divmod(S.One, S.Zero))
131
+ assert divmod(S(12), 8) == Tuple(1, 4)
132
+ assert divmod(12, S(8)) == Tuple(1, 4)
133
+ assert S(1024)//x == 1024//x == floor(1024/x)
134
+
135
+ assert divmod(S("2"), S("3/2")) == Tuple(S("1"), S("1/2"))
136
+ assert divmod(S("3/2"), S("2")) == Tuple(S("0"), S("3/2"))
137
+ assert divmod(S("2"), S("3.5")) == Tuple(S("0"), S("2"))
138
+ assert divmod(S("3.5"), S("2")) == Tuple(S("1"), S("1.5"))
139
+ assert divmod(S("2"), S("1/3")) == Tuple(S("6"), S("0"))
140
+ assert divmod(S("1/3"), S("2")) == Tuple(S("0"), S("1/3"))
141
+ assert divmod(S("2"), S("1/10")) == Tuple(S("20"), S("0"))
142
+ assert divmod(S("2"), S(".1"))[0] == 19
143
+ assert divmod(S("0.1"), S("2")) == Tuple(S("0"), S("0.1"))
144
+ assert divmod(S("2"), 2) == Tuple(S("1"), S("0"))
145
+ assert divmod(2, S("2")) == Tuple(S("1"), S("0"))
146
+ assert divmod(S("2"), 1.5) == Tuple(S("1"), S("0.5"))
147
+ assert divmod(1.5, S("2")) == Tuple(S("0"), S("1.5"))
148
+ assert divmod(0.3, S("2")) == Tuple(S("0"), S("0.3"))
149
+ assert divmod(S("3/2"), S("3.5")) == Tuple(S("0"), S("3/2"))
150
+ assert divmod(S("3.5"), S("3/2")) == Tuple(S("2"), S("0.5"))
151
+ assert divmod(S("3/2"), S("1/3")) == Tuple(S("4"), S("1/6"))
152
+ assert divmod(S("1/3"), S("3/2")) == Tuple(S("0"), S("1/3"))
153
+ assert divmod(S("3/2"), S("0.1"))[0] == 14
154
+ assert divmod(S("0.1"), S("3/2")) == Tuple(S("0"), S("0.1"))
155
+ assert divmod(S("3/2"), 2) == Tuple(S("0"), S("3/2"))
156
+ assert divmod(2, S("3/2")) == Tuple(S("1"), S("1/2"))
157
+ assert divmod(S("3/2"), 1.5) == Tuple(S("1"), S("0"))
158
+ assert divmod(1.5, S("3/2")) == Tuple(S("1"), S("0"))
159
+ assert divmod(S("3/2"), 0.3) == Tuple(S("5"), S("0"))
160
+ assert divmod(0.3, S("3/2")) == Tuple(S("0"), S("0.3"))
161
+ assert divmod(S("1/3"), S("3.5")) == Tuple(S("0"), S("1/3"))
162
+ assert divmod(S("3.5"), S("0.1")) == Tuple(S("35"), S("0"))
163
+ assert divmod(S("0.1"), S("3.5")) == Tuple(S("0"), S("0.1"))
164
+ assert divmod(S("3.5"), 2) == Tuple(S("1"), S("1.5"))
165
+ assert divmod(2, S("3.5")) == Tuple(S("0"), S("2"))
166
+ assert divmod(S("3.5"), 1.5) == Tuple(S("2"), S("0.5"))
167
+ assert divmod(1.5, S("3.5")) == Tuple(S("0"), S("1.5"))
168
+ assert divmod(0.3, S("3.5")) == Tuple(S("0"), S("0.3"))
169
+ assert divmod(S("0.1"), S("1/3")) == Tuple(S("0"), S("0.1"))
170
+ assert divmod(S("1/3"), 2) == Tuple(S("0"), S("1/3"))
171
+ assert divmod(2, S("1/3")) == Tuple(S("6"), S("0"))
172
+ assert divmod(S("1/3"), 1.5) == Tuple(S("0"), S("1/3"))
173
+ assert divmod(0.3, S("1/3")) == Tuple(S("0"), S("0.3"))
174
+ assert divmod(S("0.1"), 2) == Tuple(S("0"), S("0.1"))
175
+ assert divmod(2, S("0.1"))[0] == 19
176
+ assert divmod(S("0.1"), 1.5) == Tuple(S("0"), S("0.1"))
177
+ assert divmod(1.5, S("0.1")) == Tuple(S("15"), S("0"))
178
+ assert divmod(S("0.1"), 0.3) == Tuple(S("0"), S("0.1"))
179
+
180
+ assert str(divmod(S("2"), 0.3)) == '(6, 0.2)'
181
+ assert str(divmod(S("3.5"), S("1/3"))) == '(10, 0.166666666666667)'
182
+ assert str(divmod(S("3.5"), 0.3)) == '(11, 0.2)'
183
+ assert str(divmod(S("1/3"), S("0.1"))) == '(3, 0.0333333333333333)'
184
+ assert str(divmod(1.5, S("1/3"))) == '(4, 0.166666666666667)'
185
+ assert str(divmod(S("1/3"), 0.3)) == '(1, 0.0333333333333333)'
186
+ assert str(divmod(0.3, S("0.1"))) == '(2, 0.1)'
187
+
188
+ assert divmod(-3, S(2)) == (-2, 1)
189
+ assert divmod(S(-3), S(2)) == (-2, 1)
190
+ assert divmod(S(-3), 2) == (-2, 1)
191
+
192
+ assert divmod(S(4), S(-3.1)) == Tuple(-2, -2.2)
193
+ assert divmod(S(4), S(-2.1)) == divmod(4, -2.1)
194
+ assert divmod(S(-8), S(-2.5) ) == Tuple(3, -0.5)
195
+
196
+ assert divmod(oo, 1) == (S.NaN, S.NaN)
197
+ assert divmod(S.NaN, 1) == (S.NaN, S.NaN)
198
+ assert divmod(1, S.NaN) == (S.NaN, S.NaN)
199
+ ans = [(-1, oo), (-1, oo), (0, 0), (0, 1), (0, 2)]
200
+ OO = float('inf')
201
+ ANS = [tuple(map(float, i)) for i in ans]
202
+ assert [divmod(i, oo) for i in range(-2, 3)] == ans
203
+ ans = [(0, -2), (0, -1), (0, 0), (-1, -oo), (-1, -oo)]
204
+ ANS = [tuple(map(float, i)) for i in ans]
205
+ assert [divmod(i, -oo) for i in range(-2, 3)] == ans
206
+ assert [divmod(i, -OO) for i in range(-2, 3)] == ANS
207
+ assert divmod(S(3.5), S(-2)) == divmod(3.5, -2)
208
+ assert divmod(-S(3.5), S(-2)) == divmod(-3.5, -2)
209
+ assert divmod(S(0.0), S(9)) == divmod(0.0, 9)
210
+ assert divmod(S(0), S(9.0)) == divmod(0, 9.0)
211
+
212
+
213
+ def test_igcd():
214
+ assert igcd(0, 0) == 0
215
+ assert igcd(0, 1) == 1
216
+ assert igcd(1, 0) == 1
217
+ assert igcd(0, 7) == 7
218
+ assert igcd(7, 0) == 7
219
+ assert igcd(7, 1) == 1
220
+ assert igcd(1, 7) == 1
221
+ assert igcd(-1, 0) == 1
222
+ assert igcd(0, -1) == 1
223
+ assert igcd(-1, -1) == 1
224
+ assert igcd(-1, 7) == 1
225
+ assert igcd(7, -1) == 1
226
+ assert igcd(8, 2) == 2
227
+ assert igcd(4, 8) == 4
228
+ assert igcd(8, 16) == 8
229
+ assert igcd(7, -3) == 1
230
+ assert igcd(-7, 3) == 1
231
+ assert igcd(-7, -3) == 1
232
+ assert igcd(*[10, 20, 30]) == 10
233
+ raises(TypeError, lambda: igcd())
234
+ raises(TypeError, lambda: igcd(2))
235
+ raises(ValueError, lambda: igcd(0, None))
236
+ raises(ValueError, lambda: igcd(1, 2.2))
237
+ for args in permutations((45.1, 1, 30)):
238
+ raises(ValueError, lambda: igcd(*args))
239
+ for args in permutations((1, 2, None)):
240
+ raises(ValueError, lambda: igcd(*args))
241
+
242
+
243
+ def test_igcd_lehmer():
244
+ a, b = fibonacci(10001), fibonacci(10000)
245
+ # len(str(a)) == 2090
246
+ # small divisors, long Euclidean sequence
247
+ assert igcd_lehmer(a, b) == 1
248
+ c = fibonacci(100)
249
+ assert igcd_lehmer(a*c, b*c) == c
250
+ # big divisor
251
+ assert igcd_lehmer(a, 10**1000) == 1
252
+ # swapping argument
253
+ assert igcd_lehmer(1, 2) == igcd_lehmer(2, 1)
254
+
255
+
256
+ def test_igcd2():
257
+ # short loop
258
+ assert igcd2(2**100 - 1, 2**99 - 1) == 1
259
+ # Lehmer's algorithm
260
+ a, b = int(fibonacci(10001)), int(fibonacci(10000))
261
+ assert igcd2(a, b) == 1
262
+
263
+
264
+ def test_ilcm():
265
+ assert ilcm(0, 0) == 0
266
+ assert ilcm(1, 0) == 0
267
+ assert ilcm(0, 1) == 0
268
+ assert ilcm(1, 1) == 1
269
+ assert ilcm(2, 1) == 2
270
+ assert ilcm(8, 2) == 8
271
+ assert ilcm(8, 6) == 24
272
+ assert ilcm(8, 7) == 56
273
+ assert ilcm(*[10, 20, 30]) == 60
274
+ raises(ValueError, lambda: ilcm(8.1, 7))
275
+ raises(ValueError, lambda: ilcm(8, 7.1))
276
+ raises(TypeError, lambda: ilcm(8))
277
+
278
+
279
+ def test_igcdex():
280
+ assert igcdex(2, 3) == (-1, 1, 1)
281
+ assert igcdex(10, 12) == (-1, 1, 2)
282
+ assert igcdex(100, 2004) == (-20, 1, 4)
283
+ assert igcdex(0, 0) == (0, 1, 0)
284
+ assert igcdex(1, 0) == (1, 0, 1)
285
+
286
+
287
+ def _strictly_equal(a, b):
288
+ return (a.p, a.q, type(a.p), type(a.q)) == \
289
+ (b.p, b.q, type(b.p), type(b.q))
290
+
291
+
292
+ def _test_rational_new(cls):
293
+ """
294
+ Tests that are common between Integer and Rational.
295
+ """
296
+ assert cls(0) is S.Zero
297
+ assert cls(1) is S.One
298
+ assert cls(-1) is S.NegativeOne
299
+ # These look odd, but are similar to int():
300
+ assert cls('1') is S.One
301
+ assert cls('-1') is S.NegativeOne
302
+
303
+ i = Integer(10)
304
+ assert _strictly_equal(i, cls('10'))
305
+ assert _strictly_equal(i, cls('10'))
306
+ assert _strictly_equal(i, cls(int(10)))
307
+ assert _strictly_equal(i, cls(i))
308
+
309
+ raises(TypeError, lambda: cls(Symbol('x')))
310
+
311
+
312
+ def test_Integer_new():
313
+ """
314
+ Test for Integer constructor
315
+ """
316
+ _test_rational_new(Integer)
317
+
318
+ assert _strictly_equal(Integer(0.9), S.Zero)
319
+ assert _strictly_equal(Integer(10.5), Integer(10))
320
+ raises(ValueError, lambda: Integer("10.5"))
321
+ assert Integer(Rational('1.' + '9'*20)) == 1
322
+
323
+
324
+ def test_Rational_new():
325
+ """"
326
+ Test for Rational constructor
327
+ """
328
+ _test_rational_new(Rational)
329
+
330
+ n1 = S.Half
331
+ assert n1 == Rational(Integer(1), 2)
332
+ assert n1 == Rational(Integer(1), Integer(2))
333
+ assert n1 == Rational(1, Integer(2))
334
+ assert n1 == Rational(S.Half)
335
+ assert 1 == Rational(n1, n1)
336
+ assert Rational(3, 2) == Rational(S.Half, Rational(1, 3))
337
+ assert Rational(3, 1) == Rational(1, Rational(1, 3))
338
+ n3_4 = Rational(3, 4)
339
+ assert Rational('3/4') == n3_4
340
+ assert -Rational('-3/4') == n3_4
341
+ assert Rational('.76').limit_denominator(4) == n3_4
342
+ assert Rational(19, 25).limit_denominator(4) == n3_4
343
+ assert Rational('19/25').limit_denominator(4) == n3_4
344
+ assert Rational(1.0, 3) == Rational(1, 3)
345
+ assert Rational(1, 3.0) == Rational(1, 3)
346
+ assert Rational(Float(0.5)) == S.Half
347
+ assert Rational('1e2/1e-2') == Rational(10000)
348
+ assert Rational('1 234') == Rational(1234)
349
+ assert Rational('1/1 234') == Rational(1, 1234)
350
+ assert Rational(-1, 0) is S.ComplexInfinity
351
+ assert Rational(1, 0) is S.ComplexInfinity
352
+ # Make sure Rational doesn't lose precision on Floats
353
+ assert Rational(pi.evalf(100)).evalf(100) == pi.evalf(100)
354
+ raises(TypeError, lambda: Rational('3**3'))
355
+ raises(TypeError, lambda: Rational('1/2 + 2/3'))
356
+
357
+ # handle fractions.Fraction instances
358
+ try:
359
+ import fractions
360
+ assert Rational(fractions.Fraction(1, 2)) == S.Half
361
+ except ImportError:
362
+ pass
363
+
364
+ assert Rational(mpq(2, 6)) == Rational(1, 3)
365
+ assert Rational(PythonRational(2, 6)) == Rational(1, 3)
366
+
367
+ assert Rational(2, 4, gcd=1).q == 4
368
+ n = Rational(2, -4, gcd=1)
369
+ assert n.q == 4
370
+ assert n.p == -2
371
+
372
+ def test_issue_24543():
373
+ for p in ('1.5', 1.5, 2):
374
+ for q in ('1.5', 1.5, 2):
375
+ assert Rational(p, q).as_numer_denom() == Rational('%s/%s'%(p,q)).as_numer_denom()
376
+
377
+ assert Rational('0.5', '100') == Rational(1, 200)
378
+
379
+
380
+ def test_Number_new():
381
+ """"
382
+ Test for Number constructor
383
+ """
384
+ # Expected behavior on numbers and strings
385
+ assert Number(1) is S.One
386
+ assert Number(2).__class__ is Integer
387
+ assert Number(-622).__class__ is Integer
388
+ assert Number(5, 3).__class__ is Rational
389
+ assert Number(5.3).__class__ is Float
390
+ assert Number('1') is S.One
391
+ assert Number('2').__class__ is Integer
392
+ assert Number('-622').__class__ is Integer
393
+ assert Number('5/3').__class__ is Rational
394
+ assert Number('5.3').__class__ is Float
395
+ raises(ValueError, lambda: Number('cos'))
396
+ raises(TypeError, lambda: Number(cos))
397
+ a = Rational(3, 5)
398
+ assert Number(a) is a # Check idempotence on Numbers
399
+ u = ['inf', '-inf', 'nan', 'iNF', '+inf']
400
+ v = [oo, -oo, nan, oo, oo]
401
+ for i, a in zip(u, v):
402
+ assert Number(i) is a, (i, Number(i), a)
403
+
404
+
405
+ def test_Number_cmp():
406
+ n1 = Number(1)
407
+ n2 = Number(2)
408
+ n3 = Number(-3)
409
+
410
+ assert n1 < n2
411
+ assert n1 <= n2
412
+ assert n3 < n1
413
+ assert n2 > n3
414
+ assert n2 >= n3
415
+
416
+ raises(TypeError, lambda: n1 < S.NaN)
417
+ raises(TypeError, lambda: n1 <= S.NaN)
418
+ raises(TypeError, lambda: n1 > S.NaN)
419
+ raises(TypeError, lambda: n1 >= S.NaN)
420
+
421
+
422
+ def test_Rational_cmp():
423
+ n1 = Rational(1, 4)
424
+ n2 = Rational(1, 3)
425
+ n3 = Rational(2, 4)
426
+ n4 = Rational(2, -4)
427
+ n5 = Rational(0)
428
+ n6 = Rational(1)
429
+ n7 = Rational(3)
430
+ n8 = Rational(-3)
431
+
432
+ assert n8 < n5
433
+ assert n5 < n6
434
+ assert n6 < n7
435
+ assert n8 < n7
436
+ assert n7 > n8
437
+ assert (n1 + 1)**n2 < 2
438
+ assert ((n1 + n6)/n7) < 1
439
+
440
+ assert n4 < n3
441
+ assert n2 < n3
442
+ assert n1 < n2
443
+ assert n3 > n1
444
+ assert not n3 < n1
445
+ assert not (Rational(-1) > 0)
446
+ assert Rational(-1) < 0
447
+
448
+ raises(TypeError, lambda: n1 < S.NaN)
449
+ raises(TypeError, lambda: n1 <= S.NaN)
450
+ raises(TypeError, lambda: n1 > S.NaN)
451
+ raises(TypeError, lambda: n1 >= S.NaN)
452
+
453
+
454
+ def test_Float():
455
+ def eq(a, b):
456
+ t = Float("1.0E-15")
457
+ return (-t < a - b < t)
458
+
459
+ zeros = (0, S.Zero, 0., Float(0))
460
+ for i, j in permutations(zeros, 2):
461
+ assert i == j
462
+ for z in zeros:
463
+ assert z in zeros
464
+ assert S.Zero.is_zero
465
+
466
+ a = Float(2) ** Float(3)
467
+ assert eq(a.evalf(), Float(8))
468
+ assert eq((pi ** -1).evalf(), Float("0.31830988618379067"))
469
+ a = Float(2) ** Float(4)
470
+ assert eq(a.evalf(), Float(16))
471
+ assert (S(.3) == S(.5)) is False
472
+
473
+ mpf = (0, 5404319552844595, -52, 53)
474
+ x_str = Float((0, '13333333333333', -52, 53))
475
+ x_0xstr = Float((0, '0x13333333333333', -52, 53))
476
+ x2_str = Float((0, '26666666666666', -53, 54))
477
+ x_hex = Float((0, int(0x13333333333333), -52, 53))
478
+ x_dec = Float(mpf)
479
+ assert x_str == x_0xstr == x_hex == x_dec == Float(1.2)
480
+ # x2_str was entered slightly malformed in that the mantissa
481
+ # was even -- it should be odd and the even part should be
482
+ # included with the exponent, but this is resolved by normalization
483
+ # ONLY IF REQUIREMENTS of mpf_norm are met: the bitcount must
484
+ # be exact: double the mantissa ==> increase bc by 1
485
+ assert Float(1.2)._mpf_ == mpf
486
+ assert x2_str._mpf_ == mpf
487
+
488
+ assert Float((0, int(0), -123, -1)) is S.NaN
489
+ assert Float((0, int(0), -456, -2)) is S.Infinity
490
+ assert Float((1, int(0), -789, -3)) is S.NegativeInfinity
491
+ # if you don't give the full signature, it's not special
492
+ assert Float((0, int(0), -123)) == Float(0)
493
+ assert Float((0, int(0), -456)) == Float(0)
494
+ assert Float((1, int(0), -789)) == Float(0)
495
+
496
+ raises(ValueError, lambda: Float((0, 7, 1, 3), ''))
497
+
498
+ assert Float('0.0').is_finite is True
499
+ assert Float('0.0').is_negative is False
500
+ assert Float('0.0').is_positive is False
501
+ assert Float('0.0').is_infinite is False
502
+ assert Float('0.0').is_zero is True
503
+
504
+ # rationality properties
505
+ # if the integer test fails then the use of intlike
506
+ # should be removed from gamma_functions.py
507
+ assert Float(1).is_integer is False
508
+ assert Float(1).is_rational is None
509
+ assert Float(1).is_irrational is None
510
+ assert sqrt(2).n(15).is_rational is None
511
+ assert sqrt(2).n(15).is_irrational is None
512
+
513
+ # do not automatically evalf
514
+ def teq(a):
515
+ assert (a.evalf() == a) is False
516
+ assert (a.evalf() != a) is True
517
+ assert (a == a.evalf()) is False
518
+ assert (a != a.evalf()) is True
519
+
520
+ teq(pi)
521
+ teq(2*pi)
522
+ teq(cos(0.1, evaluate=False))
523
+
524
+ # long integer
525
+ i = 12345678901234567890
526
+ assert same_and_same_prec(Float(12, ''), Float('12', ''))
527
+ assert same_and_same_prec(Float(Integer(i), ''), Float(i, ''))
528
+ assert same_and_same_prec(Float(i, ''), Float(str(i), 20))
529
+ assert same_and_same_prec(Float(str(i)), Float(i, ''))
530
+ assert same_and_same_prec(Float(i), Float(i, ''))
531
+
532
+ # inexact floats (repeating binary = denom not multiple of 2)
533
+ # cannot have precision greater than 15
534
+ assert Float(.125, 22) == .125
535
+ assert Float(2.0, 22) == 2
536
+ assert float(Float('.12500000000000001', '')) == .125
537
+ raises(ValueError, lambda: Float(.12500000000000001, ''))
538
+
539
+ # allow spaces
540
+ assert Float('123 456.123 456') == Float('123456.123456')
541
+ assert Integer('123 456') == Integer('123456')
542
+ assert Rational('123 456.123 456') == Rational('123456.123456')
543
+ assert Float(' .3e2') == Float('0.3e2')
544
+
545
+ # allow underscore
546
+ assert Float('1_23.4_56') == Float('123.456')
547
+ assert Float('1_') == Float('1.0')
548
+ assert Float('1_.') == Float('1.0')
549
+ assert Float('1._') == Float('1.0')
550
+ assert Float('1__2') == Float('12.0')
551
+ # assert Float('1_23.4_5_6', 12) == Float('123.456', 12)
552
+ # ...but not in all cases (per Py 3.6)
553
+ raises(ValueError, lambda: Float('_1'))
554
+ raises(ValueError, lambda: Float('_inf'))
555
+
556
+ # allow auto precision detection
557
+ assert Float('.1', '') == Float(.1, 1)
558
+ assert Float('.125', '') == Float(.125, 3)
559
+ assert Float('.100', '') == Float(.1, 3)
560
+ assert Float('2.0', '') == Float('2', 2)
561
+
562
+ raises(ValueError, lambda: Float("12.3d-4", ""))
563
+ raises(ValueError, lambda: Float(12.3, ""))
564
+ raises(ValueError, lambda: Float('.'))
565
+ raises(ValueError, lambda: Float('-.'))
566
+
567
+ zero = Float('0.0')
568
+ assert Float('-0') == zero
569
+ assert Float('.0') == zero
570
+ assert Float('-.0') == zero
571
+ assert Float('-0.0') == zero
572
+ assert Float(0.0) == zero
573
+ assert Float(0) == zero
574
+ assert Float(0, '') == Float('0', '')
575
+ assert Float(1) == Float(1.0)
576
+ assert Float(S.Zero) == zero
577
+ assert Float(S.One) == Float(1.0)
578
+
579
+ assert Float(decimal.Decimal('0.1'), 3) == Float('.1', 3)
580
+ assert Float(decimal.Decimal('nan')) is S.NaN
581
+ assert Float(decimal.Decimal('Infinity')) is S.Infinity
582
+ assert Float(decimal.Decimal('-Infinity')) is S.NegativeInfinity
583
+
584
+ assert '{:.3f}'.format(Float(4.236622)) == '4.237'
585
+ assert '{:.35f}'.format(Float(pi.n(40), 40)) == \
586
+ '3.14159265358979323846264338327950288'
587
+
588
+ # unicode
589
+ assert Float('0.73908513321516064100000000') == \
590
+ Float('0.73908513321516064100000000')
591
+ assert Float('0.73908513321516064100000000', 28) == \
592
+ Float('0.73908513321516064100000000', 28)
593
+
594
+ # binary precision
595
+ # Decimal value 0.1 cannot be expressed precisely as a base 2 fraction
596
+ a = Float(S.One/10, dps=15)
597
+ b = Float(S.One/10, dps=16)
598
+ p = Float(S.One/10, precision=53)
599
+ q = Float(S.One/10, precision=54)
600
+ assert a._mpf_ == p._mpf_
601
+ assert not a._mpf_ == q._mpf_
602
+ assert not b._mpf_ == q._mpf_
603
+
604
+ # Precision specifying errors
605
+ raises(ValueError, lambda: Float("1.23", dps=3, precision=10))
606
+ raises(ValueError, lambda: Float("1.23", dps="", precision=10))
607
+ raises(ValueError, lambda: Float("1.23", dps=3, precision=""))
608
+ raises(ValueError, lambda: Float("1.23", dps="", precision=""))
609
+
610
+ # from NumberSymbol
611
+ assert same_and_same_prec(Float(pi, 32), pi.evalf(32))
612
+ assert same_and_same_prec(Float(Catalan), Catalan.evalf())
613
+
614
+ # oo and nan
615
+ u = ['inf', '-inf', 'nan', 'iNF', '+inf']
616
+ v = [oo, -oo, nan, oo, oo]
617
+ for i, a in zip(u, v):
618
+ assert Float(i) is a
619
+
620
+
621
+ def test_zero_not_false():
622
+ # https://github.com/sympy/sympy/issues/20796
623
+ assert (S(0.0) == S.false) is False
624
+ assert (S.false == S(0.0)) is False
625
+ assert (S(0) == S.false) is False
626
+ assert (S.false == S(0)) is False
627
+
628
+
629
+ @conserve_mpmath_dps
630
+ def test_float_mpf():
631
+ import mpmath
632
+ mpmath.mp.dps = 100
633
+ mp_pi = mpmath.pi()
634
+
635
+ assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100)
636
+
637
+ mpmath.mp.dps = 15
638
+
639
+ assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100)
640
+
641
+
642
+ def test_Float_RealElement():
643
+ repi = RealField(dps=100)(pi.evalf(100))
644
+ # We still have to pass the precision because Float doesn't know what
645
+ # RealElement is, but make sure it keeps full precision from the result.
646
+ assert Float(repi, 100) == pi.evalf(100)
647
+
648
+
649
+ def test_Float_default_to_highprec_from_str():
650
+ s = str(pi.evalf(128))
651
+ assert same_and_same_prec(Float(s), Float(s, ''))
652
+
653
+
654
+ def test_Float_eval():
655
+ a = Float(3.2)
656
+ assert (a**2).is_Float
657
+
658
+
659
+ def test_Float_issue_2107():
660
+ a = Float(0.1, 10)
661
+ b = Float("0.1", 10)
662
+
663
+ assert a - a == 0
664
+ assert a + (-a) == 0
665
+ assert S.Zero + a - a == 0
666
+ assert S.Zero + a + (-a) == 0
667
+
668
+ assert b - b == 0
669
+ assert b + (-b) == 0
670
+ assert S.Zero + b - b == 0
671
+ assert S.Zero + b + (-b) == 0
672
+
673
+
674
+ def test_issue_14289():
675
+ from sympy.polys.numberfields import to_number_field
676
+
677
+ a = 1 - sqrt(2)
678
+ b = to_number_field(a)
679
+ assert b.as_expr() == a
680
+ assert b.minpoly(a).expand() == 0
681
+
682
+
683
+ def test_Float_from_tuple():
684
+ a = Float((0, '1L', 0, 1))
685
+ b = Float((0, '1', 0, 1))
686
+ assert a == b
687
+
688
+
689
+ def test_Infinity():
690
+ assert oo != 1
691
+ assert 1*oo is oo
692
+ assert 1 != oo
693
+ assert oo != -oo
694
+ assert oo != Symbol("x")**3
695
+ assert oo + 1 is oo
696
+ assert 2 + oo is oo
697
+ assert 3*oo + 2 is oo
698
+ assert S.Half**oo == 0
699
+ assert S.Half**(-oo) is oo
700
+ assert -oo*3 is -oo
701
+ assert oo + oo is oo
702
+ assert -oo + oo*(-5) is -oo
703
+ assert 1/oo == 0
704
+ assert 1/(-oo) == 0
705
+ assert 8/oo == 0
706
+ assert oo % 2 is nan
707
+ assert 2 % oo is nan
708
+ assert oo/oo is nan
709
+ assert oo/-oo is nan
710
+ assert -oo/oo is nan
711
+ assert -oo/-oo is nan
712
+ assert oo - oo is nan
713
+ assert oo - -oo is oo
714
+ assert -oo - oo is -oo
715
+ assert -oo - -oo is nan
716
+ assert oo + -oo is nan
717
+ assert -oo + oo is nan
718
+ assert oo + oo is oo
719
+ assert -oo + oo is nan
720
+ assert oo + -oo is nan
721
+ assert -oo + -oo is -oo
722
+ assert oo*oo is oo
723
+ assert -oo*oo is -oo
724
+ assert oo*-oo is -oo
725
+ assert -oo*-oo is oo
726
+ assert oo/0 is oo
727
+ assert -oo/0 is -oo
728
+ assert 0/oo == 0
729
+ assert 0/-oo == 0
730
+ assert oo*0 is nan
731
+ assert -oo*0 is nan
732
+ assert 0*oo is nan
733
+ assert 0*-oo is nan
734
+ assert oo + 0 is oo
735
+ assert -oo + 0 is -oo
736
+ assert 0 + oo is oo
737
+ assert 0 + -oo is -oo
738
+ assert oo - 0 is oo
739
+ assert -oo - 0 is -oo
740
+ assert 0 - oo is -oo
741
+ assert 0 - -oo is oo
742
+ assert oo/2 is oo
743
+ assert -oo/2 is -oo
744
+ assert oo/-2 is -oo
745
+ assert -oo/-2 is oo
746
+ assert oo*2 is oo
747
+ assert -oo*2 is -oo
748
+ assert oo*-2 is -oo
749
+ assert 2/oo == 0
750
+ assert 2/-oo == 0
751
+ assert -2/oo == 0
752
+ assert -2/-oo == 0
753
+ assert 2*oo is oo
754
+ assert 2*-oo is -oo
755
+ assert -2*oo is -oo
756
+ assert -2*-oo is oo
757
+ assert 2 + oo is oo
758
+ assert 2 - oo is -oo
759
+ assert -2 + oo is oo
760
+ assert -2 - oo is -oo
761
+ assert 2 + -oo is -oo
762
+ assert 2 - -oo is oo
763
+ assert -2 + -oo is -oo
764
+ assert -2 - -oo is oo
765
+ assert S(2) + oo is oo
766
+ assert S(2) - oo is -oo
767
+ assert oo/I == -oo*I
768
+ assert -oo/I == oo*I
769
+ assert oo*float(1) == _inf and (oo*float(1)) is oo
770
+ assert -oo*float(1) == _ninf and (-oo*float(1)) is -oo
771
+ assert oo/float(1) == _inf and (oo/float(1)) is oo
772
+ assert -oo/float(1) == _ninf and (-oo/float(1)) is -oo
773
+ assert oo*float(-1) == _ninf and (oo*float(-1)) is -oo
774
+ assert -oo*float(-1) == _inf and (-oo*float(-1)) is oo
775
+ assert oo/float(-1) == _ninf and (oo/float(-1)) is -oo
776
+ assert -oo/float(-1) == _inf and (-oo/float(-1)) is oo
777
+ assert oo + float(1) == _inf and (oo + float(1)) is oo
778
+ assert -oo + float(1) == _ninf and (-oo + float(1)) is -oo
779
+ assert oo - float(1) == _inf and (oo - float(1)) is oo
780
+ assert -oo - float(1) == _ninf and (-oo - float(1)) is -oo
781
+ assert float(1)*oo == _inf and (float(1)*oo) is oo
782
+ assert float(1)*-oo == _ninf and (float(1)*-oo) is -oo
783
+ assert float(1)/oo == 0
784
+ assert float(1)/-oo == 0
785
+ assert float(-1)*oo == _ninf and (float(-1)*oo) is -oo
786
+ assert float(-1)*-oo == _inf and (float(-1)*-oo) is oo
787
+ assert float(-1)/oo == 0
788
+ assert float(-1)/-oo == 0
789
+ assert float(1) + oo is oo
790
+ assert float(1) + -oo is -oo
791
+ assert float(1) - oo is -oo
792
+ assert float(1) - -oo is oo
793
+ assert oo == float(oo)
794
+ assert (oo != float(oo)) is False
795
+ assert type(float(oo)) is float
796
+ assert -oo == float(-oo)
797
+ assert (-oo != float(-oo)) is False
798
+ assert type(float(-oo)) is float
799
+
800
+ assert Float('nan') is nan
801
+ assert nan*1.0 is nan
802
+ assert -1.0*nan is nan
803
+ assert nan*oo is nan
804
+ assert nan*-oo is nan
805
+ assert nan/oo is nan
806
+ assert nan/-oo is nan
807
+ assert nan + oo is nan
808
+ assert nan + -oo is nan
809
+ assert nan - oo is nan
810
+ assert nan - -oo is nan
811
+ assert -oo * S.Zero is nan
812
+
813
+ assert oo*nan is nan
814
+ assert -oo*nan is nan
815
+ assert oo/nan is nan
816
+ assert -oo/nan is nan
817
+ assert oo + nan is nan
818
+ assert -oo + nan is nan
819
+ assert oo - nan is nan
820
+ assert -oo - nan is nan
821
+ assert S.Zero * oo is nan
822
+ assert oo.is_Rational is False
823
+ assert isinstance(oo, Rational) is False
824
+
825
+ assert S.One/oo == 0
826
+ assert -S.One/oo == 0
827
+ assert S.One/-oo == 0
828
+ assert -S.One/-oo == 0
829
+ assert S.One*oo is oo
830
+ assert -S.One*oo is -oo
831
+ assert S.One*-oo is -oo
832
+ assert -S.One*-oo is oo
833
+ assert S.One/nan is nan
834
+ assert S.One - -oo is oo
835
+ assert S.One + nan is nan
836
+ assert S.One - nan is nan
837
+ assert nan - S.One is nan
838
+ assert nan/S.One is nan
839
+ assert -oo - S.One is -oo
840
+
841
+
842
+ def test_Infinity_2():
843
+ x = Symbol('x')
844
+ assert oo*x != oo
845
+ assert oo*(pi - 1) is oo
846
+ assert oo*(1 - pi) is -oo
847
+
848
+ assert (-oo)*x != -oo
849
+ assert (-oo)*(pi - 1) is -oo
850
+ assert (-oo)*(1 - pi) is oo
851
+
852
+ assert (-1)**S.NaN is S.NaN
853
+ assert oo - _inf is S.NaN
854
+ assert oo + _ninf is S.NaN
855
+ assert oo*0 is S.NaN
856
+ assert oo/_inf is S.NaN
857
+ assert oo/_ninf is S.NaN
858
+ assert oo**S.NaN is S.NaN
859
+ assert -oo + _inf is S.NaN
860
+ assert -oo - _ninf is S.NaN
861
+ assert -oo*S.NaN is S.NaN
862
+ assert -oo*0 is S.NaN
863
+ assert -oo/_inf is S.NaN
864
+ assert -oo/_ninf is S.NaN
865
+ assert -oo/S.NaN is S.NaN
866
+ assert abs(-oo) is oo
867
+ assert all((-oo)**i is S.NaN for i in (oo, -oo, S.NaN))
868
+ assert (-oo)**3 is -oo
869
+ assert (-oo)**2 is oo
870
+ assert abs(S.ComplexInfinity) is oo
871
+
872
+
873
+ def test_Mul_Infinity_Zero():
874
+ assert Float(0)*_inf is nan
875
+ assert Float(0)*_ninf is nan
876
+ assert Float(0)*_inf is nan
877
+ assert Float(0)*_ninf is nan
878
+ assert _inf*Float(0) is nan
879
+ assert _ninf*Float(0) is nan
880
+ assert _inf*Float(0) is nan
881
+ assert _ninf*Float(0) is nan
882
+
883
+
884
+ def test_Div_By_Zero():
885
+ assert 1/S.Zero is zoo
886
+ assert 1/Float(0) is zoo
887
+ assert 0/S.Zero is nan
888
+ assert 0/Float(0) is nan
889
+ assert S.Zero/0 is nan
890
+ assert Float(0)/0 is nan
891
+ assert -1/S.Zero is zoo
892
+ assert -1/Float(0) is zoo
893
+
894
+
895
+ @_both_exp_pow
896
+ def test_Infinity_inequations():
897
+ assert oo > pi
898
+ assert not (oo < pi)
899
+ assert exp(-3) < oo
900
+
901
+ assert _inf > pi
902
+ assert not (_inf < pi)
903
+ assert exp(-3) < _inf
904
+
905
+ raises(TypeError, lambda: oo < I)
906
+ raises(TypeError, lambda: oo <= I)
907
+ raises(TypeError, lambda: oo > I)
908
+ raises(TypeError, lambda: oo >= I)
909
+ raises(TypeError, lambda: -oo < I)
910
+ raises(TypeError, lambda: -oo <= I)
911
+ raises(TypeError, lambda: -oo > I)
912
+ raises(TypeError, lambda: -oo >= I)
913
+
914
+ raises(TypeError, lambda: I < oo)
915
+ raises(TypeError, lambda: I <= oo)
916
+ raises(TypeError, lambda: I > oo)
917
+ raises(TypeError, lambda: I >= oo)
918
+ raises(TypeError, lambda: I < -oo)
919
+ raises(TypeError, lambda: I <= -oo)
920
+ raises(TypeError, lambda: I > -oo)
921
+ raises(TypeError, lambda: I >= -oo)
922
+
923
+ assert oo > -oo and oo >= -oo
924
+ assert (oo < -oo) == False and (oo <= -oo) == False
925
+ assert -oo < oo and -oo <= oo
926
+ assert (-oo > oo) == False and (-oo >= oo) == False
927
+
928
+ assert (oo < oo) == False # issue 7775
929
+ assert (oo > oo) == False
930
+ assert (-oo > -oo) == False and (-oo < -oo) == False
931
+ assert oo >= oo and oo <= oo and -oo >= -oo and -oo <= -oo
932
+ assert (-oo < -_inf) == False
933
+ assert (oo > _inf) == False
934
+ assert -oo >= -_inf
935
+ assert oo <= _inf
936
+
937
+ x = Symbol('x')
938
+ b = Symbol('b', finite=True, real=True)
939
+ assert (x < oo) == Lt(x, oo) # issue 7775
940
+ assert b < oo and b > -oo and b <= oo and b >= -oo
941
+ assert oo > b and oo >= b and (oo < b) == False and (oo <= b) == False
942
+ assert (-oo > b) == False and (-oo >= b) == False and -oo < b and -oo <= b
943
+ assert (oo < x) == Lt(oo, x) and (oo > x) == Gt(oo, x)
944
+ assert (oo <= x) == Le(oo, x) and (oo >= x) == Ge(oo, x)
945
+ assert (-oo < x) == Lt(-oo, x) and (-oo > x) == Gt(-oo, x)
946
+ assert (-oo <= x) == Le(-oo, x) and (-oo >= x) == Ge(-oo, x)
947
+
948
+
949
+ def test_NaN():
950
+ assert nan is nan
951
+ assert nan != 1
952
+ assert 1*nan is nan
953
+ assert 1 != nan
954
+ assert -nan is nan
955
+ assert oo != Symbol("x")**3
956
+ assert 2 + nan is nan
957
+ assert 3*nan + 2 is nan
958
+ assert -nan*3 is nan
959
+ assert nan + nan is nan
960
+ assert -nan + nan*(-5) is nan
961
+ assert 8/nan is nan
962
+ raises(TypeError, lambda: nan > 0)
963
+ raises(TypeError, lambda: nan < 0)
964
+ raises(TypeError, lambda: nan >= 0)
965
+ raises(TypeError, lambda: nan <= 0)
966
+ raises(TypeError, lambda: 0 < nan)
967
+ raises(TypeError, lambda: 0 > nan)
968
+ raises(TypeError, lambda: 0 <= nan)
969
+ raises(TypeError, lambda: 0 >= nan)
970
+ assert nan**0 == 1 # as per IEEE 754
971
+ assert 1**nan is nan # IEEE 754 is not the best choice for symbolic work
972
+ # test Pow._eval_power's handling of NaN
973
+ assert Pow(nan, 0, evaluate=False)**2 == 1
974
+ for n in (1, 1., S.One, S.NegativeOne, Float(1)):
975
+ assert n + nan is nan
976
+ assert n - nan is nan
977
+ assert nan + n is nan
978
+ assert nan - n is nan
979
+ assert n/nan is nan
980
+ assert nan/n is nan
981
+
982
+
983
+ def test_special_numbers():
984
+ assert isinstance(S.NaN, Number) is True
985
+ assert isinstance(S.Infinity, Number) is True
986
+ assert isinstance(S.NegativeInfinity, Number) is True
987
+
988
+ assert S.NaN.is_number is True
989
+ assert S.Infinity.is_number is True
990
+ assert S.NegativeInfinity.is_number is True
991
+ assert S.ComplexInfinity.is_number is True
992
+
993
+ assert isinstance(S.NaN, Rational) is False
994
+ assert isinstance(S.Infinity, Rational) is False
995
+ assert isinstance(S.NegativeInfinity, Rational) is False
996
+
997
+ assert S.NaN.is_rational is not True
998
+ assert S.Infinity.is_rational is not True
999
+ assert S.NegativeInfinity.is_rational is not True
1000
+
1001
+
1002
+ def test_powers():
1003
+ assert integer_nthroot(1, 2) == (1, True)
1004
+ assert integer_nthroot(1, 5) == (1, True)
1005
+ assert integer_nthroot(2, 1) == (2, True)
1006
+ assert integer_nthroot(2, 2) == (1, False)
1007
+ assert integer_nthroot(2, 5) == (1, False)
1008
+ assert integer_nthroot(4, 2) == (2, True)
1009
+ assert integer_nthroot(123**25, 25) == (123, True)
1010
+ assert integer_nthroot(123**25 + 1, 25) == (123, False)
1011
+ assert integer_nthroot(123**25 - 1, 25) == (122, False)
1012
+ assert integer_nthroot(1, 1) == (1, True)
1013
+ assert integer_nthroot(0, 1) == (0, True)
1014
+ assert integer_nthroot(0, 3) == (0, True)
1015
+ assert integer_nthroot(10000, 1) == (10000, True)
1016
+ assert integer_nthroot(4, 2) == (2, True)
1017
+ assert integer_nthroot(16, 2) == (4, True)
1018
+ assert integer_nthroot(26, 2) == (5, False)
1019
+ assert integer_nthroot(1234567**7, 7) == (1234567, True)
1020
+ assert integer_nthroot(1234567**7 + 1, 7) == (1234567, False)
1021
+ assert integer_nthroot(1234567**7 - 1, 7) == (1234566, False)
1022
+ b = 25**1000
1023
+ assert integer_nthroot(b, 1000) == (25, True)
1024
+ assert integer_nthroot(b + 1, 1000) == (25, False)
1025
+ assert integer_nthroot(b - 1, 1000) == (24, False)
1026
+ c = 10**400
1027
+ c2 = c**2
1028
+ assert integer_nthroot(c2, 2) == (c, True)
1029
+ assert integer_nthroot(c2 + 1, 2) == (c, False)
1030
+ assert integer_nthroot(c2 - 1, 2) == (c - 1, False)
1031
+ assert integer_nthroot(2, 10**10) == (1, False)
1032
+
1033
+ p, r = integer_nthroot(int(factorial(10000)), 100)
1034
+ assert p % (10**10) == 5322420655
1035
+ assert not r
1036
+
1037
+ # Test that this is fast
1038
+ assert integer_nthroot(2, 10**10) == (1, False)
1039
+
1040
+ # output should be int if possible
1041
+ assert type(integer_nthroot(2**61, 2)[0]) is int
1042
+
1043
+
1044
+ def test_integer_nthroot_overflow():
1045
+ assert integer_nthroot(10**(50*50), 50) == (10**50, True)
1046
+ assert integer_nthroot(10**100000, 10000) == (10**10, True)
1047
+
1048
+
1049
+ def test_integer_log():
1050
+ raises(ValueError, lambda: integer_log(2, 1))
1051
+ raises(ValueError, lambda: integer_log(0, 2))
1052
+ raises(ValueError, lambda: integer_log(1.1, 2))
1053
+ raises(ValueError, lambda: integer_log(1, 2.2))
1054
+
1055
+ assert integer_log(1, 2) == (0, True)
1056
+ assert integer_log(1, 3) == (0, True)
1057
+ assert integer_log(2, 3) == (0, False)
1058
+ assert integer_log(3, 3) == (1, True)
1059
+ assert integer_log(3*2, 3) == (1, False)
1060
+ assert integer_log(3**2, 3) == (2, True)
1061
+ assert integer_log(3*4, 3) == (2, False)
1062
+ assert integer_log(3**3, 3) == (3, True)
1063
+ assert integer_log(27, 5) == (2, False)
1064
+ assert integer_log(2, 3) == (0, False)
1065
+ assert integer_log(-4, -2) == (2, False)
1066
+ assert integer_log(27, -3) == (3, False)
1067
+ assert integer_log(-49, 7) == (0, False)
1068
+ assert integer_log(-49, -7) == (2, False)
1069
+
1070
+
1071
+ def test_isqrt():
1072
+ from math import sqrt as _sqrt
1073
+ limit = 4503599761588223
1074
+ assert int(_sqrt(limit)) == integer_nthroot(limit, 2)[0]
1075
+ assert int(_sqrt(limit + 1)) != integer_nthroot(limit + 1, 2)[0]
1076
+ assert isqrt(limit + 1) == integer_nthroot(limit + 1, 2)[0]
1077
+ assert isqrt(limit + S.Half) == integer_nthroot(limit, 2)[0]
1078
+ assert isqrt(limit + 1 + S.Half) == integer_nthroot(limit + 1, 2)[0]
1079
+ assert isqrt(limit + 2 + S.Half) == integer_nthroot(limit + 2, 2)[0]
1080
+
1081
+ # Regression tests for https://github.com/sympy/sympy/issues/17034
1082
+ assert isqrt(4503599761588224) == 67108864
1083
+ assert isqrt(9999999999999999) == 99999999
1084
+
1085
+ # Other corner cases, especially involving non-integers.
1086
+ raises(ValueError, lambda: isqrt(-1))
1087
+ raises(ValueError, lambda: isqrt(-10**1000))
1088
+ raises(ValueError, lambda: isqrt(Rational(-1, 2)))
1089
+
1090
+ tiny = Rational(1, 10**1000)
1091
+ raises(ValueError, lambda: isqrt(-tiny))
1092
+ assert isqrt(1-tiny) == 0
1093
+ assert isqrt(4503599761588224-tiny) == 67108864
1094
+ assert isqrt(10**100 - tiny) == 10**50 - 1
1095
+
1096
+ # Check that using an inaccurate math.sqrt doesn't affect the results.
1097
+ from sympy.core import power
1098
+ old_sqrt = power._sqrt
1099
+ power._sqrt = lambda x: 2.999999999
1100
+ try:
1101
+ assert isqrt(9) == 3
1102
+ assert isqrt(10000) == 100
1103
+ finally:
1104
+ power._sqrt = old_sqrt
1105
+
1106
+
1107
+ def test_powers_Integer():
1108
+ """Test Integer._eval_power"""
1109
+ # check infinity
1110
+ assert S.One ** S.Infinity is S.NaN
1111
+ assert S.NegativeOne** S.Infinity is S.NaN
1112
+ assert S(2) ** S.Infinity is S.Infinity
1113
+ assert S(-2)** S.Infinity == zoo
1114
+ assert S(0) ** S.Infinity is S.Zero
1115
+
1116
+ # check Nan
1117
+ assert S.One ** S.NaN is S.NaN
1118
+ assert S.NegativeOne ** S.NaN is S.NaN
1119
+
1120
+ # check for exact roots
1121
+ assert S.NegativeOne ** Rational(6, 5) == - (-1)**(S.One/5)
1122
+ assert sqrt(S(4)) == 2
1123
+ assert sqrt(S(-4)) == I * 2
1124
+ assert S(16) ** Rational(1, 4) == 2
1125
+ assert S(-16) ** Rational(1, 4) == 2 * (-1)**Rational(1, 4)
1126
+ assert S(9) ** Rational(3, 2) == 27
1127
+ assert S(-9) ** Rational(3, 2) == -27*I
1128
+ assert S(27) ** Rational(2, 3) == 9
1129
+ assert S(-27) ** Rational(2, 3) == 9 * (S.NegativeOne ** Rational(2, 3))
1130
+ assert (-2) ** Rational(-2, 1) == Rational(1, 4)
1131
+
1132
+ # not exact roots
1133
+ assert sqrt(-3) == I*sqrt(3)
1134
+ assert (3) ** (Rational(3, 2)) == 3 * sqrt(3)
1135
+ assert (-3) ** (Rational(3, 2)) == - 3 * sqrt(-3)
1136
+ assert (-3) ** (Rational(5, 2)) == 9 * I * sqrt(3)
1137
+ assert (-3) ** (Rational(7, 2)) == - I * 27 * sqrt(3)
1138
+ assert (2) ** (Rational(3, 2)) == 2 * sqrt(2)
1139
+ assert (2) ** (Rational(-3, 2)) == sqrt(2) / 4
1140
+ assert (81) ** (Rational(2, 3)) == 9 * (S(3) ** (Rational(2, 3)))
1141
+ assert (-81) ** (Rational(2, 3)) == 9 * (S(-3) ** (Rational(2, 3)))
1142
+ assert (-3) ** Rational(-7, 3) == \
1143
+ -(-1)**Rational(2, 3)*3**Rational(2, 3)/27
1144
+ assert (-3) ** Rational(-2, 3) == \
1145
+ -(-1)**Rational(1, 3)*3**Rational(1, 3)/3
1146
+
1147
+ # join roots
1148
+ assert sqrt(6) + sqrt(24) == 3*sqrt(6)
1149
+ assert sqrt(2) * sqrt(3) == sqrt(6)
1150
+
1151
+ # separate symbols & constansts
1152
+ x = Symbol("x")
1153
+ assert sqrt(49 * x) == 7 * sqrt(x)
1154
+ assert sqrt((3 - sqrt(pi)) ** 2) == 3 - sqrt(pi)
1155
+
1156
+ # check that it is fast for big numbers
1157
+ assert (2**64 + 1) ** Rational(4, 3)
1158
+ assert (2**64 + 1) ** Rational(17, 25)
1159
+
1160
+ # negative rational power and negative base
1161
+ assert (-3) ** Rational(-7, 3) == \
1162
+ -(-1)**Rational(2, 3)*3**Rational(2, 3)/27
1163
+ assert (-3) ** Rational(-2, 3) == \
1164
+ -(-1)**Rational(1, 3)*3**Rational(1, 3)/3
1165
+ assert (-2) ** Rational(-10, 3) == \
1166
+ (-1)**Rational(2, 3)*2**Rational(2, 3)/16
1167
+ assert abs(Pow(-2, Rational(-10, 3)).n() -
1168
+ Pow(-2, Rational(-10, 3), evaluate=False).n()) < 1e-16
1169
+
1170
+ # negative base and rational power with some simplification
1171
+ assert (-8) ** Rational(2, 5) == \
1172
+ 2*(-1)**Rational(2, 5)*2**Rational(1, 5)
1173
+ assert (-4) ** Rational(9, 5) == \
1174
+ -8*(-1)**Rational(4, 5)*2**Rational(3, 5)
1175
+
1176
+ assert S(1234).factors() == {617: 1, 2: 1}
1177
+ assert Rational(2*3, 3*5*7).factors() == {2: 1, 5: -1, 7: -1}
1178
+
1179
+ # test that eval_power factors numbers bigger than
1180
+ # the current limit in factor_trial_division (2**15)
1181
+ from sympy.ntheory.generate import nextprime
1182
+ n = nextprime(2**15)
1183
+ assert sqrt(n**2) == n
1184
+ assert sqrt(n**3) == n*sqrt(n)
1185
+ assert sqrt(4*n) == 2*sqrt(n)
1186
+
1187
+ # check that factors of base with powers sharing gcd with power are removed
1188
+ assert (2**4*3)**Rational(1, 6) == 2**Rational(2, 3)*3**Rational(1, 6)
1189
+ assert (2**4*3)**Rational(5, 6) == 8*2**Rational(1, 3)*3**Rational(5, 6)
1190
+
1191
+ # check that bases sharing a gcd are exptracted
1192
+ assert 2**Rational(1, 3)*3**Rational(1, 4)*6**Rational(1, 5) == \
1193
+ 2**Rational(8, 15)*3**Rational(9, 20)
1194
+ assert sqrt(8)*24**Rational(1, 3)*6**Rational(1, 5) == \
1195
+ 4*2**Rational(7, 10)*3**Rational(8, 15)
1196
+ assert sqrt(8)*(-24)**Rational(1, 3)*(-6)**Rational(1, 5) == \
1197
+ 4*(-3)**Rational(8, 15)*2**Rational(7, 10)
1198
+ assert 2**Rational(1, 3)*2**Rational(8, 9) == 2*2**Rational(2, 9)
1199
+ assert 2**Rational(2, 3)*6**Rational(1, 3) == 2*3**Rational(1, 3)
1200
+ assert 2**Rational(2, 3)*6**Rational(8, 9) == \
1201
+ 2*2**Rational(5, 9)*3**Rational(8, 9)
1202
+ assert (-2)**Rational(2, S(3))*(-4)**Rational(1, S(3)) == -2*2**Rational(1, 3)
1203
+ assert 3*Pow(3, 2, evaluate=False) == 3**3
1204
+ assert 3*Pow(3, Rational(-1, 3), evaluate=False) == 3**Rational(2, 3)
1205
+ assert (-2)**Rational(1, 3)*(-3)**Rational(1, 4)*(-5)**Rational(5, 6) == \
1206
+ -(-1)**Rational(5, 12)*2**Rational(1, 3)*3**Rational(1, 4) * \
1207
+ 5**Rational(5, 6)
1208
+
1209
+ assert Integer(-2)**Symbol('', even=True) == \
1210
+ Integer(2)**Symbol('', even=True)
1211
+ assert (-1)**Float(.5) == 1.0*I
1212
+
1213
+
1214
+ def test_powers_Rational():
1215
+ """Test Rational._eval_power"""
1216
+ # check infinity
1217
+ assert S.Half ** S.Infinity == 0
1218
+ assert Rational(3, 2) ** S.Infinity is S.Infinity
1219
+ assert Rational(-1, 2) ** S.Infinity == 0
1220
+ assert Rational(-3, 2) ** S.Infinity == zoo
1221
+
1222
+ # check Nan
1223
+ assert Rational(3, 4) ** S.NaN is S.NaN
1224
+ assert Rational(-2, 3) ** S.NaN is S.NaN
1225
+
1226
+ # exact roots on numerator
1227
+ assert sqrt(Rational(4, 3)) == 2 * sqrt(3) / 3
1228
+ assert Rational(4, 3) ** Rational(3, 2) == 8 * sqrt(3) / 9
1229
+ assert sqrt(Rational(-4, 3)) == I * 2 * sqrt(3) / 3
1230
+ assert Rational(-4, 3) ** Rational(3, 2) == - I * 8 * sqrt(3) / 9
1231
+ assert Rational(27, 2) ** Rational(1, 3) == 3 * (2 ** Rational(2, 3)) / 2
1232
+ assert Rational(5**3, 8**3) ** Rational(4, 3) == Rational(5**4, 8**4)
1233
+
1234
+ # exact root on denominator
1235
+ assert sqrt(Rational(1, 4)) == S.Half
1236
+ assert sqrt(Rational(1, -4)) == I * S.Half
1237
+ assert sqrt(Rational(3, 4)) == sqrt(3) / 2
1238
+ assert sqrt(Rational(3, -4)) == I * sqrt(3) / 2
1239
+ assert Rational(5, 27) ** Rational(1, 3) == (5 ** Rational(1, 3)) / 3
1240
+
1241
+ # not exact roots
1242
+ assert sqrt(S.Half) == sqrt(2) / 2
1243
+ assert sqrt(Rational(-4, 7)) == I * sqrt(Rational(4, 7))
1244
+ assert Rational(-3, 2)**Rational(-7, 3) == \
1245
+ -4*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/27
1246
+ assert Rational(-3, 2)**Rational(-2, 3) == \
1247
+ -(-1)**Rational(1, 3)*2**Rational(2, 3)*3**Rational(1, 3)/3
1248
+ assert Rational(-3, 2)**Rational(-10, 3) == \
1249
+ 8*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/81
1250
+ assert abs(Pow(Rational(-2, 3), Rational(-7, 4)).n() -
1251
+ Pow(Rational(-2, 3), Rational(-7, 4), evaluate=False).n()) < 1e-16
1252
+
1253
+ # negative integer power and negative rational base
1254
+ assert Rational(-2, 3) ** Rational(-2, 1) == Rational(9, 4)
1255
+
1256
+ a = Rational(1, 10)
1257
+ assert a**Float(a, 2) == Float(a, 2)**Float(a, 2)
1258
+ assert Rational(-2, 3)**Symbol('', even=True) == \
1259
+ Rational(2, 3)**Symbol('', even=True)
1260
+
1261
+
1262
+ def test_powers_Float():
1263
+ assert str((S('-1/10')**S('3/10')).n()) == str(Float(-.1)**(.3))
1264
+
1265
+
1266
+ def test_lshift_Integer():
1267
+ assert Integer(0) << Integer(2) == Integer(0)
1268
+ assert Integer(0) << 2 == Integer(0)
1269
+ assert 0 << Integer(2) == Integer(0)
1270
+
1271
+ assert Integer(0b11) << Integer(0) == Integer(0b11)
1272
+ assert Integer(0b11) << 0 == Integer(0b11)
1273
+ assert 0b11 << Integer(0) == Integer(0b11)
1274
+
1275
+ assert Integer(0b11) << Integer(2) == Integer(0b11 << 2)
1276
+ assert Integer(0b11) << 2 == Integer(0b11 << 2)
1277
+ assert 0b11 << Integer(2) == Integer(0b11 << 2)
1278
+
1279
+ assert Integer(-0b11) << Integer(2) == Integer(-0b11 << 2)
1280
+ assert Integer(-0b11) << 2 == Integer(-0b11 << 2)
1281
+ assert -0b11 << Integer(2) == Integer(-0b11 << 2)
1282
+
1283
+ raises(TypeError, lambda: Integer(2) << 0.0)
1284
+ raises(TypeError, lambda: 0.0 << Integer(2))
1285
+ raises(ValueError, lambda: Integer(1) << Integer(-1))
1286
+
1287
+
1288
+ def test_rshift_Integer():
1289
+ assert Integer(0) >> Integer(2) == Integer(0)
1290
+ assert Integer(0) >> 2 == Integer(0)
1291
+ assert 0 >> Integer(2) == Integer(0)
1292
+
1293
+ assert Integer(0b11) >> Integer(0) == Integer(0b11)
1294
+ assert Integer(0b11) >> 0 == Integer(0b11)
1295
+ assert 0b11 >> Integer(0) == Integer(0b11)
1296
+
1297
+ assert Integer(0b11) >> Integer(2) == Integer(0)
1298
+ assert Integer(0b11) >> 2 == Integer(0)
1299
+ assert 0b11 >> Integer(2) == Integer(0)
1300
+
1301
+ assert Integer(-0b11) >> Integer(2) == Integer(-1)
1302
+ assert Integer(-0b11) >> 2 == Integer(-1)
1303
+ assert -0b11 >> Integer(2) == Integer(-1)
1304
+
1305
+ assert Integer(0b1100) >> Integer(2) == Integer(0b1100 >> 2)
1306
+ assert Integer(0b1100) >> 2 == Integer(0b1100 >> 2)
1307
+ assert 0b1100 >> Integer(2) == Integer(0b1100 >> 2)
1308
+
1309
+ assert Integer(-0b1100) >> Integer(2) == Integer(-0b1100 >> 2)
1310
+ assert Integer(-0b1100) >> 2 == Integer(-0b1100 >> 2)
1311
+ assert -0b1100 >> Integer(2) == Integer(-0b1100 >> 2)
1312
+
1313
+ raises(TypeError, lambda: Integer(0b10) >> 0.0)
1314
+ raises(TypeError, lambda: 0.0 >> Integer(2))
1315
+ raises(ValueError, lambda: Integer(1) >> Integer(-1))
1316
+
1317
+
1318
+ def test_and_Integer():
1319
+ assert Integer(0b01010101) & Integer(0b10101010) == Integer(0)
1320
+ assert Integer(0b01010101) & 0b10101010 == Integer(0)
1321
+ assert 0b01010101 & Integer(0b10101010) == Integer(0)
1322
+
1323
+ assert Integer(0b01010101) & Integer(0b11011011) == Integer(0b01010001)
1324
+ assert Integer(0b01010101) & 0b11011011 == Integer(0b01010001)
1325
+ assert 0b01010101 & Integer(0b11011011) == Integer(0b01010001)
1326
+
1327
+ assert -Integer(0b01010101) & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011)
1328
+ assert Integer(-0b01010101) & 0b11011011 == Integer(-0b01010101 & 0b11011011)
1329
+ assert -0b01010101 & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011)
1330
+
1331
+ assert Integer(0b01010101) & -Integer(0b11011011) == Integer(0b01010101 & -0b11011011)
1332
+ assert Integer(0b01010101) & -0b11011011 == Integer(0b01010101 & -0b11011011)
1333
+ assert 0b01010101 & Integer(-0b11011011) == Integer(0b01010101 & -0b11011011)
1334
+
1335
+ raises(TypeError, lambda: Integer(2) & 0.0)
1336
+ raises(TypeError, lambda: 0.0 & Integer(2))
1337
+
1338
+
1339
+ def test_xor_Integer():
1340
+ assert Integer(0b01010101) ^ Integer(0b11111111) == Integer(0b10101010)
1341
+ assert Integer(0b01010101) ^ 0b11111111 == Integer(0b10101010)
1342
+ assert 0b01010101 ^ Integer(0b11111111) == Integer(0b10101010)
1343
+
1344
+ assert Integer(0b01010101) ^ Integer(0b11011011) == Integer(0b10001110)
1345
+ assert Integer(0b01010101) ^ 0b11011011 == Integer(0b10001110)
1346
+ assert 0b01010101 ^ Integer(0b11011011) == Integer(0b10001110)
1347
+
1348
+ assert -Integer(0b01010101) ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011)
1349
+ assert Integer(-0b01010101) ^ 0b11011011 == Integer(-0b01010101 ^ 0b11011011)
1350
+ assert -0b01010101 ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011)
1351
+
1352
+ assert Integer(0b01010101) ^ -Integer(0b11011011) == Integer(0b01010101 ^ -0b11011011)
1353
+ assert Integer(0b01010101) ^ -0b11011011 == Integer(0b01010101 ^ -0b11011011)
1354
+ assert 0b01010101 ^ Integer(-0b11011011) == Integer(0b01010101 ^ -0b11011011)
1355
+
1356
+ raises(TypeError, lambda: Integer(2) ^ 0.0)
1357
+ raises(TypeError, lambda: 0.0 ^ Integer(2))
1358
+
1359
+
1360
+ def test_or_Integer():
1361
+ assert Integer(0b01010101) | Integer(0b10101010) == Integer(0b11111111)
1362
+ assert Integer(0b01010101) | 0b10101010 == Integer(0b11111111)
1363
+ assert 0b01010101 | Integer(0b10101010) == Integer(0b11111111)
1364
+
1365
+ assert Integer(0b01010101) | Integer(0b11011011) == Integer(0b11011111)
1366
+ assert Integer(0b01010101) | 0b11011011 == Integer(0b11011111)
1367
+ assert 0b01010101 | Integer(0b11011011) == Integer(0b11011111)
1368
+
1369
+ assert -Integer(0b01010101) | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011)
1370
+ assert Integer(-0b01010101) | 0b11011011 == Integer(-0b01010101 | 0b11011011)
1371
+ assert -0b01010101 | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011)
1372
+
1373
+ assert Integer(0b01010101) | -Integer(0b11011011) == Integer(0b01010101 | -0b11011011)
1374
+ assert Integer(0b01010101) | -0b11011011 == Integer(0b01010101 | -0b11011011)
1375
+ assert 0b01010101 | Integer(-0b11011011) == Integer(0b01010101 | -0b11011011)
1376
+
1377
+ raises(TypeError, lambda: Integer(2) | 0.0)
1378
+ raises(TypeError, lambda: 0.0 | Integer(2))
1379
+
1380
+
1381
+ def test_invert_Integer():
1382
+ assert ~Integer(0b01010101) == Integer(-0b01010110)
1383
+ assert ~Integer(0b01010101) == Integer(~0b01010101)
1384
+ assert ~(~Integer(0b01010101)) == Integer(0b01010101)
1385
+
1386
+
1387
+ def test_abs1():
1388
+ assert Rational(1, 6) != Rational(-1, 6)
1389
+ assert abs(Rational(1, 6)) == abs(Rational(-1, 6))
1390
+
1391
+
1392
+ def test_accept_int():
1393
+ assert Float(4) == 4
1394
+
1395
+
1396
+ def test_dont_accept_str():
1397
+ assert Float("0.2") != "0.2"
1398
+ assert not (Float("0.2") == "0.2")
1399
+
1400
+
1401
+ def test_int():
1402
+ a = Rational(5)
1403
+ assert int(a) == 5
1404
+ a = Rational(9, 10)
1405
+ assert int(a) == int(-a) == 0
1406
+ assert 1/(-1)**Rational(2, 3) == -(-1)**Rational(1, 3)
1407
+ # issue 10368
1408
+ a = Rational(32442016954, 78058255275)
1409
+ assert type(int(a)) is type(int(-a)) is int
1410
+
1411
+
1412
+ def test_int_NumberSymbols():
1413
+ assert int(Catalan) == 0
1414
+ assert int(EulerGamma) == 0
1415
+ assert int(pi) == 3
1416
+ assert int(E) == 2
1417
+ assert int(GoldenRatio) == 1
1418
+ assert int(TribonacciConstant) == 1
1419
+ for i in [Catalan, E, EulerGamma, GoldenRatio, TribonacciConstant, pi]:
1420
+ a, b = i.approximation_interval(Integer)
1421
+ ia = int(i)
1422
+ assert ia == a
1423
+ assert isinstance(ia, int)
1424
+ assert b == a + 1
1425
+ assert a.is_Integer and b.is_Integer
1426
+
1427
+
1428
+ def test_real_bug():
1429
+ x = Symbol("x")
1430
+ assert str(2.0*x*x) in ["(2.0*x)*x", "2.0*x**2", "2.00000000000000*x**2"]
1431
+ assert str(2.1*x*x) != "(2.0*x)*x"
1432
+
1433
+
1434
+ def test_bug_sqrt():
1435
+ assert ((sqrt(Rational(2)) + 1)*(sqrt(Rational(2)) - 1)).expand() == 1
1436
+
1437
+
1438
+ def test_pi_Pi():
1439
+ "Test that pi (instance) is imported, but Pi (class) is not"
1440
+ from sympy import pi # noqa
1441
+ with raises(ImportError):
1442
+ from sympy import Pi # noqa
1443
+
1444
+
1445
+ def test_no_len():
1446
+ # there should be no len for numbers
1447
+ raises(TypeError, lambda: len(Rational(2)))
1448
+ raises(TypeError, lambda: len(Rational(2, 3)))
1449
+ raises(TypeError, lambda: len(Integer(2)))
1450
+
1451
+
1452
+ def test_issue_3321():
1453
+ assert sqrt(Rational(1, 5)) == Rational(1, 5)**S.Half
1454
+ assert 5 * sqrt(Rational(1, 5)) == sqrt(5)
1455
+
1456
+
1457
+ def test_issue_3692():
1458
+ assert ((-1)**Rational(1, 6)).expand(complex=True) == I/2 + sqrt(3)/2
1459
+ assert ((-5)**Rational(1, 6)).expand(complex=True) == \
1460
+ 5**Rational(1, 6)*I/2 + 5**Rational(1, 6)*sqrt(3)/2
1461
+ assert ((-64)**Rational(1, 6)).expand(complex=True) == I + sqrt(3)
1462
+
1463
+
1464
+ def test_issue_3423():
1465
+ x = Symbol("x")
1466
+ assert sqrt(x - 1).as_base_exp() == (x - 1, S.Half)
1467
+ assert sqrt(x - 1) != I*sqrt(1 - x)
1468
+
1469
+
1470
+ def test_issue_3449():
1471
+ x = Symbol("x")
1472
+ assert sqrt(x - 1).subs(x, 5) == 2
1473
+
1474
+
1475
+ def test_issue_13890():
1476
+ x = Symbol("x")
1477
+ e = (-x/4 - S.One/12)**x - 1
1478
+ f = simplify(e)
1479
+ a = Rational(9, 5)
1480
+ assert abs(e.subs(x,a).evalf() - f.subs(x,a).evalf()) < 1e-15
1481
+
1482
+
1483
+ def test_Integer_factors():
1484
+ def F(i):
1485
+ return Integer(i).factors()
1486
+
1487
+ assert F(1) == {}
1488
+ assert F(2) == {2: 1}
1489
+ assert F(3) == {3: 1}
1490
+ assert F(4) == {2: 2}
1491
+ assert F(5) == {5: 1}
1492
+ assert F(6) == {2: 1, 3: 1}
1493
+ assert F(7) == {7: 1}
1494
+ assert F(8) == {2: 3}
1495
+ assert F(9) == {3: 2}
1496
+ assert F(10) == {2: 1, 5: 1}
1497
+ assert F(11) == {11: 1}
1498
+ assert F(12) == {2: 2, 3: 1}
1499
+ assert F(13) == {13: 1}
1500
+ assert F(14) == {2: 1, 7: 1}
1501
+ assert F(15) == {3: 1, 5: 1}
1502
+ assert F(16) == {2: 4}
1503
+ assert F(17) == {17: 1}
1504
+ assert F(18) == {2: 1, 3: 2}
1505
+ assert F(19) == {19: 1}
1506
+ assert F(20) == {2: 2, 5: 1}
1507
+ assert F(21) == {3: 1, 7: 1}
1508
+ assert F(22) == {2: 1, 11: 1}
1509
+ assert F(23) == {23: 1}
1510
+ assert F(24) == {2: 3, 3: 1}
1511
+ assert F(25) == {5: 2}
1512
+ assert F(26) == {2: 1, 13: 1}
1513
+ assert F(27) == {3: 3}
1514
+ assert F(28) == {2: 2, 7: 1}
1515
+ assert F(29) == {29: 1}
1516
+ assert F(30) == {2: 1, 3: 1, 5: 1}
1517
+ assert F(31) == {31: 1}
1518
+ assert F(32) == {2: 5}
1519
+ assert F(33) == {3: 1, 11: 1}
1520
+ assert F(34) == {2: 1, 17: 1}
1521
+ assert F(35) == {5: 1, 7: 1}
1522
+ assert F(36) == {2: 2, 3: 2}
1523
+ assert F(37) == {37: 1}
1524
+ assert F(38) == {2: 1, 19: 1}
1525
+ assert F(39) == {3: 1, 13: 1}
1526
+ assert F(40) == {2: 3, 5: 1}
1527
+ assert F(41) == {41: 1}
1528
+ assert F(42) == {2: 1, 3: 1, 7: 1}
1529
+ assert F(43) == {43: 1}
1530
+ assert F(44) == {2: 2, 11: 1}
1531
+ assert F(45) == {3: 2, 5: 1}
1532
+ assert F(46) == {2: 1, 23: 1}
1533
+ assert F(47) == {47: 1}
1534
+ assert F(48) == {2: 4, 3: 1}
1535
+ assert F(49) == {7: 2}
1536
+ assert F(50) == {2: 1, 5: 2}
1537
+ assert F(51) == {3: 1, 17: 1}
1538
+
1539
+
1540
+ def test_Rational_factors():
1541
+ def F(p, q, visual=None):
1542
+ return Rational(p, q).factors(visual=visual)
1543
+
1544
+ assert F(2, 3) == {2: 1, 3: -1}
1545
+ assert F(2, 9) == {2: 1, 3: -2}
1546
+ assert F(2, 15) == {2: 1, 3: -1, 5: -1}
1547
+ assert F(6, 10) == {3: 1, 5: -1}
1548
+
1549
+
1550
+ def test_issue_4107():
1551
+ assert pi*(E + 10) + pi*(-E - 10) != 0
1552
+ assert pi*(E + 10**10) + pi*(-E - 10**10) != 0
1553
+ assert pi*(E + 10**20) + pi*(-E - 10**20) != 0
1554
+ assert pi*(E + 10**80) + pi*(-E - 10**80) != 0
1555
+
1556
+ assert (pi*(E + 10) + pi*(-E - 10)).expand() == 0
1557
+ assert (pi*(E + 10**10) + pi*(-E - 10**10)).expand() == 0
1558
+ assert (pi*(E + 10**20) + pi*(-E - 10**20)).expand() == 0
1559
+ assert (pi*(E + 10**80) + pi*(-E - 10**80)).expand() == 0
1560
+
1561
+
1562
+ def test_IntegerInteger():
1563
+ a = Integer(4)
1564
+ b = Integer(a)
1565
+
1566
+ assert a == b
1567
+
1568
+
1569
+ def test_Rational_gcd_lcm_cofactors():
1570
+ assert Integer(4).gcd(2) == Integer(2)
1571
+ assert Integer(4).lcm(2) == Integer(4)
1572
+ assert Integer(4).gcd(Integer(2)) == Integer(2)
1573
+ assert Integer(4).lcm(Integer(2)) == Integer(4)
1574
+ a, b = 720**99911, 480**12342
1575
+ assert Integer(a).lcm(b) == a*b/Integer(a).gcd(b)
1576
+
1577
+ assert Integer(4).gcd(3) == Integer(1)
1578
+ assert Integer(4).lcm(3) == Integer(12)
1579
+ assert Integer(4).gcd(Integer(3)) == Integer(1)
1580
+ assert Integer(4).lcm(Integer(3)) == Integer(12)
1581
+
1582
+ assert Rational(4, 3).gcd(2) == Rational(2, 3)
1583
+ assert Rational(4, 3).lcm(2) == Integer(4)
1584
+ assert Rational(4, 3).gcd(Integer(2)) == Rational(2, 3)
1585
+ assert Rational(4, 3).lcm(Integer(2)) == Integer(4)
1586
+
1587
+ assert Integer(4).gcd(Rational(2, 9)) == Rational(2, 9)
1588
+ assert Integer(4).lcm(Rational(2, 9)) == Integer(4)
1589
+
1590
+ assert Rational(4, 3).gcd(Rational(2, 9)) == Rational(2, 9)
1591
+ assert Rational(4, 3).lcm(Rational(2, 9)) == Rational(4, 3)
1592
+ assert Rational(4, 5).gcd(Rational(2, 9)) == Rational(2, 45)
1593
+ assert Rational(4, 5).lcm(Rational(2, 9)) == Integer(4)
1594
+ assert Rational(5, 9).lcm(Rational(3, 7)) == Rational(Integer(5).lcm(3),Integer(9).gcd(7))
1595
+
1596
+ assert Integer(4).cofactors(2) == (Integer(2), Integer(2), Integer(1))
1597
+ assert Integer(4).cofactors(Integer(2)) == \
1598
+ (Integer(2), Integer(2), Integer(1))
1599
+
1600
+ assert Integer(4).gcd(Float(2.0)) == Float(1.0)
1601
+ assert Integer(4).lcm(Float(2.0)) == Float(8.0)
1602
+ assert Integer(4).cofactors(Float(2.0)) == (Float(1.0), Float(4.0), Float(2.0))
1603
+
1604
+ assert S.Half.gcd(Float(2.0)) == Float(1.0)
1605
+ assert S.Half.lcm(Float(2.0)) == Float(1.0)
1606
+ assert S.Half.cofactors(Float(2.0)) == \
1607
+ (Float(1.0), Float(0.5), Float(2.0))
1608
+
1609
+
1610
+ def test_Float_gcd_lcm_cofactors():
1611
+ assert Float(2.0).gcd(Integer(4)) == Float(1.0)
1612
+ assert Float(2.0).lcm(Integer(4)) == Float(8.0)
1613
+ assert Float(2.0).cofactors(Integer(4)) == (Float(1.0), Float(2.0), Float(4.0))
1614
+
1615
+ assert Float(2.0).gcd(S.Half) == Float(1.0)
1616
+ assert Float(2.0).lcm(S.Half) == Float(1.0)
1617
+ assert Float(2.0).cofactors(S.Half) == \
1618
+ (Float(1.0), Float(2.0), Float(0.5))
1619
+
1620
+
1621
+ def test_issue_4611():
1622
+ assert abs(pi._evalf(50) - 3.14159265358979) < 1e-10
1623
+ assert abs(E._evalf(50) - 2.71828182845905) < 1e-10
1624
+ assert abs(Catalan._evalf(50) - 0.915965594177219) < 1e-10
1625
+ assert abs(EulerGamma._evalf(50) - 0.577215664901533) < 1e-10
1626
+ assert abs(GoldenRatio._evalf(50) - 1.61803398874989) < 1e-10
1627
+ assert abs(TribonacciConstant._evalf(50) - 1.83928675521416) < 1e-10
1628
+
1629
+ x = Symbol("x")
1630
+ assert (pi + x).evalf() == pi.evalf() + x
1631
+ assert (E + x).evalf() == E.evalf() + x
1632
+ assert (Catalan + x).evalf() == Catalan.evalf() + x
1633
+ assert (EulerGamma + x).evalf() == EulerGamma.evalf() + x
1634
+ assert (GoldenRatio + x).evalf() == GoldenRatio.evalf() + x
1635
+ assert (TribonacciConstant + x).evalf() == TribonacciConstant.evalf() + x
1636
+
1637
+
1638
+ @conserve_mpmath_dps
1639
+ def test_conversion_to_mpmath():
1640
+ assert mpmath.mpmathify(Integer(1)) == mpmath.mpf(1)
1641
+ assert mpmath.mpmathify(S.Half) == mpmath.mpf(0.5)
1642
+ assert mpmath.mpmathify(Float('1.23', 15)) == mpmath.mpf('1.23')
1643
+
1644
+ assert mpmath.mpmathify(I) == mpmath.mpc(1j)
1645
+
1646
+ assert mpmath.mpmathify(1 + 2*I) == mpmath.mpc(1 + 2j)
1647
+ assert mpmath.mpmathify(1.0 + 2*I) == mpmath.mpc(1 + 2j)
1648
+ assert mpmath.mpmathify(1 + 2.0*I) == mpmath.mpc(1 + 2j)
1649
+ assert mpmath.mpmathify(1.0 + 2.0*I) == mpmath.mpc(1 + 2j)
1650
+ assert mpmath.mpmathify(S.Half + S.Half*I) == mpmath.mpc(0.5 + 0.5j)
1651
+
1652
+ assert mpmath.mpmathify(2*I) == mpmath.mpc(2j)
1653
+ assert mpmath.mpmathify(2.0*I) == mpmath.mpc(2j)
1654
+ assert mpmath.mpmathify(S.Half*I) == mpmath.mpc(0.5j)
1655
+
1656
+ mpmath.mp.dps = 100
1657
+ assert mpmath.mpmathify(pi.evalf(100) + pi.evalf(100)*I) == mpmath.pi + mpmath.pi*mpmath.j
1658
+ assert mpmath.mpmathify(pi.evalf(100)*I) == mpmath.pi*mpmath.j
1659
+
1660
+
1661
+ def test_relational():
1662
+ # real
1663
+ x = S(.1)
1664
+ assert (x != cos) is True
1665
+ assert (x == cos) is False
1666
+
1667
+ # rational
1668
+ x = Rational(1, 3)
1669
+ assert (x != cos) is True
1670
+ assert (x == cos) is False
1671
+
1672
+ # integer defers to rational so these tests are omitted
1673
+
1674
+ # number symbol
1675
+ x = pi
1676
+ assert (x != cos) is True
1677
+ assert (x == cos) is False
1678
+
1679
+
1680
+ def test_Integer_as_index():
1681
+ assert 'hello'[Integer(2):] == 'llo'
1682
+
1683
+
1684
+ def test_Rational_int():
1685
+ assert int( Rational(7, 5)) == 1
1686
+ assert int( S.Half) == 0
1687
+ assert int(Rational(-1, 2)) == 0
1688
+ assert int(-Rational(7, 5)) == -1
1689
+
1690
+
1691
+ def test_zoo():
1692
+ b = Symbol('b', finite=True)
1693
+ nz = Symbol('nz', nonzero=True)
1694
+ p = Symbol('p', positive=True)
1695
+ n = Symbol('n', negative=True)
1696
+ im = Symbol('i', imaginary=True)
1697
+ c = Symbol('c', complex=True)
1698
+ pb = Symbol('pb', positive=True)
1699
+ nb = Symbol('nb', negative=True)
1700
+ imb = Symbol('ib', imaginary=True, finite=True)
1701
+ for i in [I, S.Infinity, S.NegativeInfinity, S.Zero, S.One, S.Pi, S.Half, S(3), log(3),
1702
+ b, nz, p, n, im, pb, nb, imb, c]:
1703
+ if i.is_finite and (i.is_real or i.is_imaginary):
1704
+ assert i + zoo is zoo
1705
+ assert i - zoo is zoo
1706
+ assert zoo + i is zoo
1707
+ assert zoo - i is zoo
1708
+ elif i.is_finite is not False:
1709
+ assert (i + zoo).is_Add
1710
+ assert (i - zoo).is_Add
1711
+ assert (zoo + i).is_Add
1712
+ assert (zoo - i).is_Add
1713
+ else:
1714
+ assert (i + zoo) is S.NaN
1715
+ assert (i - zoo) is S.NaN
1716
+ assert (zoo + i) is S.NaN
1717
+ assert (zoo - i) is S.NaN
1718
+
1719
+ if fuzzy_not(i.is_zero) and (i.is_extended_real or i.is_imaginary):
1720
+ assert i*zoo is zoo
1721
+ assert zoo*i is zoo
1722
+ elif i.is_zero:
1723
+ assert i*zoo is S.NaN
1724
+ assert zoo*i is S.NaN
1725
+ else:
1726
+ assert (i*zoo).is_Mul
1727
+ assert (zoo*i).is_Mul
1728
+
1729
+ if fuzzy_not((1/i).is_zero) and (i.is_real or i.is_imaginary):
1730
+ assert zoo/i is zoo
1731
+ elif (1/i).is_zero:
1732
+ assert zoo/i is S.NaN
1733
+ elif i.is_zero:
1734
+ assert zoo/i is zoo
1735
+ else:
1736
+ assert (zoo/i).is_Mul
1737
+
1738
+ assert (I*oo).is_Mul # allow directed infinity
1739
+ assert zoo + zoo is S.NaN
1740
+ assert zoo * zoo is zoo
1741
+ assert zoo - zoo is S.NaN
1742
+ assert zoo/zoo is S.NaN
1743
+ assert zoo**zoo is S.NaN
1744
+ assert zoo**0 is S.One
1745
+ assert zoo**2 is zoo
1746
+ assert 1/zoo is S.Zero
1747
+
1748
+ assert Mul.flatten([S.NegativeOne, oo, S(0)]) == ([S.NaN], [], None)
1749
+
1750
+
1751
+ def test_issue_4122():
1752
+ x = Symbol('x', nonpositive=True)
1753
+ assert oo + x is oo
1754
+ x = Symbol('x', extended_nonpositive=True)
1755
+ assert (oo + x).is_Add
1756
+ x = Symbol('x', finite=True)
1757
+ assert (oo + x).is_Add # x could be imaginary
1758
+ x = Symbol('x', nonnegative=True)
1759
+ assert oo + x is oo
1760
+ x = Symbol('x', extended_nonnegative=True)
1761
+ assert oo + x is oo
1762
+ x = Symbol('x', finite=True, real=True)
1763
+ assert oo + x is oo
1764
+
1765
+ # similarly for negative infinity
1766
+ x = Symbol('x', nonnegative=True)
1767
+ assert -oo + x is -oo
1768
+ x = Symbol('x', extended_nonnegative=True)
1769
+ assert (-oo + x).is_Add
1770
+ x = Symbol('x', finite=True)
1771
+ assert (-oo + x).is_Add
1772
+ x = Symbol('x', nonpositive=True)
1773
+ assert -oo + x is -oo
1774
+ x = Symbol('x', extended_nonpositive=True)
1775
+ assert -oo + x is -oo
1776
+ x = Symbol('x', finite=True, real=True)
1777
+ assert -oo + x is -oo
1778
+
1779
+
1780
+ def test_GoldenRatio_expand():
1781
+ assert GoldenRatio.expand(func=True) == S.Half + sqrt(5)/2
1782
+
1783
+
1784
+ def test_TribonacciConstant_expand():
1785
+ assert TribonacciConstant.expand(func=True) == \
1786
+ (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
1787
+
1788
+
1789
+ def test_as_content_primitive():
1790
+ assert S.Zero.as_content_primitive() == (1, 0)
1791
+ assert S.Half.as_content_primitive() == (S.Half, 1)
1792
+ assert (Rational(-1, 2)).as_content_primitive() == (S.Half, -1)
1793
+ assert S(3).as_content_primitive() == (3, 1)
1794
+ assert S(3.1).as_content_primitive() == (1, 3.1)
1795
+
1796
+
1797
+ def test_hashing_sympy_integers():
1798
+ # Test for issue 5072
1799
+ assert {Integer(3)} == {int(3)}
1800
+ assert hash(Integer(4)) == hash(int(4))
1801
+
1802
+
1803
+ def test_rounding_issue_4172():
1804
+ assert int((E**100).round()) == \
1805
+ 26881171418161354484126255515800135873611119
1806
+ assert int((pi**100).round()) == \
1807
+ 51878483143196131920862615246303013562686760680406
1808
+ assert int((Rational(1)/EulerGamma**100).round()) == \
1809
+ 734833795660954410469466
1810
+
1811
+
1812
+ @XFAIL
1813
+ def test_mpmath_issues():
1814
+ from mpmath.libmp.libmpf import _normalize
1815
+ import mpmath.libmp as mlib
1816
+ rnd = mlib.round_nearest
1817
+ mpf = (0, int(0), -123, -1, 53, rnd) # nan
1818
+ assert _normalize(mpf, 53) != (0, int(0), 0, 0)
1819
+ mpf = (0, int(0), -456, -2, 53, rnd) # +inf
1820
+ assert _normalize(mpf, 53) != (0, int(0), 0, 0)
1821
+ mpf = (1, int(0), -789, -3, 53, rnd) # -inf
1822
+ assert _normalize(mpf, 53) != (0, int(0), 0, 0)
1823
+
1824
+ from mpmath.libmp.libmpf import fnan
1825
+ assert mlib.mpf_eq(fnan, fnan)
1826
+
1827
+
1828
+ def test_Catalan_EulerGamma_prec():
1829
+ n = GoldenRatio
1830
+ f = Float(n.n(), 5)
1831
+ assert f._mpf_ == (0, int(212079), -17, 18)
1832
+ assert f._prec == 20
1833
+ assert n._as_mpf_val(20) == f._mpf_
1834
+
1835
+ n = EulerGamma
1836
+ f = Float(n.n(), 5)
1837
+ assert f._mpf_ == (0, int(302627), -19, 19)
1838
+ assert f._prec == 20
1839
+ assert n._as_mpf_val(20) == f._mpf_
1840
+
1841
+
1842
+ def test_Catalan_rewrite():
1843
+ k = Dummy('k', integer=True, nonnegative=True)
1844
+ assert Catalan.rewrite(Sum).dummy_eq(
1845
+ Sum((-1)**k/(2*k + 1)**2, (k, 0, oo)))
1846
+ assert Catalan.rewrite() == Catalan
1847
+
1848
+
1849
+ def test_bool_eq():
1850
+ assert 0 == False
1851
+ assert S(0) == False
1852
+ assert S(0) != S.false
1853
+ assert 1 == True
1854
+ assert S.One == True
1855
+ assert S.One != S.true
1856
+
1857
+
1858
+ def test_Float_eq():
1859
+ # all .5 values are the same
1860
+ assert Float(.5, 10) == Float(.5, 11) == Float(.5, 1)
1861
+ # but floats that aren't exact in base-2 still
1862
+ # don't compare the same because they have different
1863
+ # underlying mpf values
1864
+ assert Float(.12, 3) != Float(.12, 4)
1865
+ assert Float(.12, 3) != .12
1866
+ assert 0.12 != Float(.12, 3)
1867
+ assert Float('.12', 22) != .12
1868
+ # issue 11707
1869
+ # but Float/Rational -- except for 0 --
1870
+ # are exact so Rational(x) = Float(y) only if
1871
+ # Rational(x) == Rational(Float(y))
1872
+ assert Float('1.1') != Rational(11, 10)
1873
+ assert Rational(11, 10) != Float('1.1')
1874
+ # coverage
1875
+ assert not Float(3) == 2
1876
+ assert not Float(2**2) == S.Half
1877
+ assert Float(2**2) == 4
1878
+ assert not Float(2**-2) == 1
1879
+ assert Float(2**-1) == S.Half
1880
+ assert not Float(2*3) == 3
1881
+ assert not Float(2*3) == S.Half
1882
+ assert Float(2*3) == 6
1883
+ assert not Float(2*3) == 8
1884
+ assert Float(.75) == Rational(3, 4)
1885
+ assert Float(5/18) == 5/18
1886
+ # 4473
1887
+ assert Float(2.) != 3
1888
+ assert Float((0,1,-3)) == S.One/8
1889
+ assert Float((0,1,-3)) != S.One/9
1890
+ # 16196
1891
+ assert 2 == Float(2) # as per Python
1892
+ # but in a computation...
1893
+ assert t**2 != t**2.0
1894
+
1895
+
1896
+ def test_issue_6640():
1897
+ from mpmath.libmp.libmpf import finf, fninf
1898
+ # fnan is not included because Float no longer returns fnan,
1899
+ # but otherwise, the same sort of test could apply
1900
+ assert Float(finf).is_zero is False
1901
+ assert Float(fninf).is_zero is False
1902
+ assert bool(Float(0)) is False
1903
+
1904
+
1905
+ def test_issue_6349():
1906
+ assert Float('23.e3', '')._prec == 10
1907
+ assert Float('23e3', '')._prec == 20
1908
+ assert Float('23000', '')._prec == 20
1909
+ assert Float('-23000', '')._prec == 20
1910
+
1911
+
1912
+ def test_mpf_norm():
1913
+ assert mpf_norm((1, 0, 1, 0), 10) == mpf('0')._mpf_
1914
+ assert Float._new((1, 0, 1, 0), 10)._mpf_ == mpf('0')._mpf_
1915
+
1916
+
1917
+ def test_latex():
1918
+ assert latex(pi) == r"\pi"
1919
+ assert latex(E) == r"e"
1920
+ assert latex(GoldenRatio) == r"\phi"
1921
+ assert latex(TribonacciConstant) == r"\text{TribonacciConstant}"
1922
+ assert latex(EulerGamma) == r"\gamma"
1923
+ assert latex(oo) == r"\infty"
1924
+ assert latex(-oo) == r"-\infty"
1925
+ assert latex(zoo) == r"\tilde{\infty}"
1926
+ assert latex(nan) == r"\text{NaN}"
1927
+ assert latex(I) == r"i"
1928
+
1929
+
1930
+ def test_issue_7742():
1931
+ assert -oo % 1 is nan
1932
+
1933
+
1934
+ def test_simplify_AlgebraicNumber():
1935
+ A = AlgebraicNumber
1936
+ e = 3**(S.One/6)*(3 + (135 + 78*sqrt(3))**Rational(2, 3))/(45 + 26*sqrt(3))**(S.One/3)
1937
+ assert simplify(A(e)) == A(12) # wester test_C20
1938
+
1939
+ e = (41 + 29*sqrt(2))**(S.One/5)
1940
+ assert simplify(A(e)) == A(1 + sqrt(2)) # wester test_C21
1941
+
1942
+ e = (3 + 4*I)**Rational(3, 2)
1943
+ assert simplify(A(e)) == A(2 + 11*I) # issue 4401
1944
+
1945
+
1946
+ def test_Float_idempotence():
1947
+ x = Float('1.23', '')
1948
+ y = Float(x)
1949
+ z = Float(x, 15)
1950
+ assert same_and_same_prec(y, x)
1951
+ assert not same_and_same_prec(z, x)
1952
+ x = Float(10**20)
1953
+ y = Float(x)
1954
+ z = Float(x, 15)
1955
+ assert same_and_same_prec(y, x)
1956
+ assert not same_and_same_prec(z, x)
1957
+
1958
+
1959
+ def test_comp1():
1960
+ # sqrt(2) = 1.414213 5623730950...
1961
+ a = sqrt(2).n(7)
1962
+ assert comp(a, 1.4142129) is False
1963
+ assert comp(a, 1.4142130)
1964
+ # ...
1965
+ assert comp(a, 1.4142141)
1966
+ assert comp(a, 1.4142142) is False
1967
+ assert comp(sqrt(2).n(2), '1.4')
1968
+ assert comp(sqrt(2).n(2), Float(1.4, 2), '')
1969
+ assert comp(sqrt(2).n(2), 1.4, '')
1970
+ assert comp(sqrt(2).n(2), Float(1.4, 3), '') is False
1971
+ assert comp(sqrt(2) + sqrt(3)*I, 1.4 + 1.7*I, .1)
1972
+ assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.89, .1)
1973
+ assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.90, .1)
1974
+ assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.07, .1)
1975
+ assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.08, .1)
1976
+ assert [(i, j)
1977
+ for i in range(130, 150)
1978
+ for j in range(170, 180)
1979
+ if comp((sqrt(2)+ I*sqrt(3)).n(3), i/100. + I*j/100.)] == [
1980
+ (141, 173), (142, 173)]
1981
+ raises(ValueError, lambda: comp(t, '1'))
1982
+ raises(ValueError, lambda: comp(t, 1))
1983
+ assert comp(0, 0.0)
1984
+ assert comp(.5, S.Half)
1985
+ assert comp(2 + sqrt(2), 2.0 + sqrt(2))
1986
+ assert not comp(0, 1)
1987
+ assert not comp(2, sqrt(2))
1988
+ assert not comp(2 + I, 2.0 + sqrt(2))
1989
+ assert not comp(2.0 + sqrt(2), 2 + I)
1990
+ assert not comp(2.0 + sqrt(2), sqrt(3))
1991
+ assert comp(1/pi.n(4), 0.3183, 1e-5)
1992
+ assert not comp(1/pi.n(4), 0.3183, 8e-6)
1993
+
1994
+
1995
+ def test_issue_9491():
1996
+ assert oo**zoo is nan
1997
+
1998
+
1999
+ def test_issue_10063():
2000
+ assert 2**Float(3) == Float(8)
2001
+
2002
+
2003
+ def test_issue_10020():
2004
+ assert oo**I is S.NaN
2005
+ assert oo**(1 + I) is S.ComplexInfinity
2006
+ assert oo**(-1 + I) is S.Zero
2007
+ assert (-oo)**I is S.NaN
2008
+ assert (-oo)**(-1 + I) is S.Zero
2009
+ assert oo**t == Pow(oo, t, evaluate=False)
2010
+ assert (-oo)**t == Pow(-oo, t, evaluate=False)
2011
+
2012
+
2013
+ def test_invert_numbers():
2014
+ assert S(2).invert(5) == 3
2015
+ assert S(2).invert(Rational(5, 2)) == S.Half
2016
+ assert S(2).invert(5.) == S.Half
2017
+ assert S(2).invert(S(5)) == 3
2018
+ assert S(2.).invert(5) == 0.5
2019
+ assert S(sqrt(2)).invert(5) == 1/sqrt(2)
2020
+ assert S(sqrt(2)).invert(sqrt(3)) == 1/sqrt(2)
2021
+
2022
+
2023
+ def test_mod_inverse():
2024
+ assert mod_inverse(3, 11) == 4
2025
+ assert mod_inverse(5, 11) == 9
2026
+ assert mod_inverse(21124921, 521512) == 7713
2027
+ assert mod_inverse(124215421, 5125) == 2981
2028
+ assert mod_inverse(214, 12515) == 1579
2029
+ assert mod_inverse(5823991, 3299) == 1442
2030
+ assert mod_inverse(123, 44) == 39
2031
+ assert mod_inverse(2, 5) == 3
2032
+ assert mod_inverse(-2, 5) == 2
2033
+ assert mod_inverse(2, -5) == -2
2034
+ assert mod_inverse(-2, -5) == -3
2035
+ assert mod_inverse(-3, -7) == -5
2036
+ x = Symbol('x')
2037
+ assert S(2).invert(x) == S.Half
2038
+ raises(TypeError, lambda: mod_inverse(2, x))
2039
+ raises(ValueError, lambda: mod_inverse(2, S.Half))
2040
+ raises(ValueError, lambda: mod_inverse(2, cos(1)**2 + sin(1)**2))
2041
+
2042
+
2043
+ def test_golden_ratio_rewrite_as_sqrt():
2044
+ assert GoldenRatio.rewrite(sqrt) == S.Half + sqrt(5)*S.Half
2045
+
2046
+
2047
+ def test_tribonacci_constant_rewrite_as_sqrt():
2048
+ assert TribonacciConstant.rewrite(sqrt) == \
2049
+ (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
2050
+
2051
+
2052
+ def test_comparisons_with_unknown_type():
2053
+ class Foo:
2054
+ """
2055
+ Class that is unaware of Basic, and relies on both classes returning
2056
+ the NotImplemented singleton for equivalence to evaluate to False.
2057
+
2058
+ """
2059
+
2060
+ ni, nf, nr = Integer(3), Float(1.0), Rational(1, 3)
2061
+ foo = Foo()
2062
+
2063
+ for n in ni, nf, nr, oo, -oo, zoo, nan:
2064
+ assert n != foo
2065
+ assert foo != n
2066
+ assert not n == foo
2067
+ assert not foo == n
2068
+ raises(TypeError, lambda: n < foo)
2069
+ raises(TypeError, lambda: foo > n)
2070
+ raises(TypeError, lambda: n > foo)
2071
+ raises(TypeError, lambda: foo < n)
2072
+ raises(TypeError, lambda: n <= foo)
2073
+ raises(TypeError, lambda: foo >= n)
2074
+ raises(TypeError, lambda: n >= foo)
2075
+ raises(TypeError, lambda: foo <= n)
2076
+
2077
+ class Bar:
2078
+ """
2079
+ Class that considers itself equal to any instance of Number except
2080
+ infinities and nans, and relies on SymPy types returning the
2081
+ NotImplemented singleton for symmetric equality relations.
2082
+
2083
+ """
2084
+ def __eq__(self, other):
2085
+ if other in (oo, -oo, zoo, nan):
2086
+ return False
2087
+ if isinstance(other, Number):
2088
+ return True
2089
+ return NotImplemented
2090
+
2091
+ def __ne__(self, other):
2092
+ return not self == other
2093
+
2094
+ bar = Bar()
2095
+
2096
+ for n in ni, nf, nr:
2097
+ assert n == bar
2098
+ assert bar == n
2099
+ assert not n != bar
2100
+ assert not bar != n
2101
+
2102
+ for n in oo, -oo, zoo, nan:
2103
+ assert n != bar
2104
+ assert bar != n
2105
+ assert not n == bar
2106
+ assert not bar == n
2107
+
2108
+ for n in ni, nf, nr, oo, -oo, zoo, nan:
2109
+ raises(TypeError, lambda: n < bar)
2110
+ raises(TypeError, lambda: bar > n)
2111
+ raises(TypeError, lambda: n > bar)
2112
+ raises(TypeError, lambda: bar < n)
2113
+ raises(TypeError, lambda: n <= bar)
2114
+ raises(TypeError, lambda: bar >= n)
2115
+ raises(TypeError, lambda: n >= bar)
2116
+ raises(TypeError, lambda: bar <= n)
2117
+
2118
+
2119
+ def test_NumberSymbol_comparison():
2120
+ from sympy.core.tests.test_relational import rel_check
2121
+ rpi = Rational('905502432259640373/288230376151711744')
2122
+ fpi = Float(float(pi))
2123
+ assert rel_check(rpi, fpi)
2124
+
2125
+
2126
+ def test_Integer_precision():
2127
+ # Make sure Integer inputs for keyword args work
2128
+ assert Float('1.0', dps=Integer(15))._prec == 53
2129
+ assert Float('1.0', precision=Integer(15))._prec == 15
2130
+ assert type(Float('1.0', precision=Integer(15))._prec) == int
2131
+ assert sympify(srepr(Float('1.0', precision=15))) == Float('1.0', precision=15)
2132
+
2133
+
2134
+ def test_numpy_to_float():
2135
+ from sympy.testing.pytest import skip
2136
+ from sympy.external import import_module
2137
+ np = import_module('numpy')
2138
+ if not np:
2139
+ skip('numpy not installed. Abort numpy tests.')
2140
+
2141
+ def check_prec_and_relerr(npval, ratval):
2142
+ prec = np.finfo(npval).nmant + 1
2143
+ x = Float(npval)
2144
+ assert x._prec == prec
2145
+ y = Float(ratval, precision=prec)
2146
+ assert abs((x - y)/y) < 2**(-(prec + 1))
2147
+
2148
+ check_prec_and_relerr(np.float16(2.0/3), Rational(2, 3))
2149
+ check_prec_and_relerr(np.float32(2.0/3), Rational(2, 3))
2150
+ check_prec_and_relerr(np.float64(2.0/3), Rational(2, 3))
2151
+ # extended precision, on some arch/compilers:
2152
+ x = np.longdouble(2)/3
2153
+ check_prec_and_relerr(x, Rational(2, 3))
2154
+ y = Float(x, precision=10)
2155
+ assert same_and_same_prec(y, Float(Rational(2, 3), precision=10))
2156
+
2157
+ raises(TypeError, lambda: Float(np.complex64(1+2j)))
2158
+ raises(TypeError, lambda: Float(np.complex128(1+2j)))
2159
+
2160
+
2161
+ def test_Integer_ceiling_floor():
2162
+ a = Integer(4)
2163
+
2164
+ assert a.floor() == a
2165
+ assert a.ceiling() == a
2166
+
2167
+
2168
+ def test_ComplexInfinity():
2169
+ assert zoo.floor() is zoo
2170
+ assert zoo.ceiling() is zoo
2171
+ assert zoo**zoo is S.NaN
2172
+
2173
+
2174
+ def test_Infinity_floor_ceiling_power():
2175
+ assert oo.floor() is oo
2176
+ assert oo.ceiling() is oo
2177
+ assert oo**S.NaN is S.NaN
2178
+ assert oo**zoo is S.NaN
2179
+
2180
+
2181
+ def test_One_power():
2182
+ assert S.One**12 is S.One
2183
+ assert S.NegativeOne**S.NaN is S.NaN
2184
+
2185
+
2186
+ def test_NegativeInfinity():
2187
+ assert (-oo).floor() is -oo
2188
+ assert (-oo).ceiling() is -oo
2189
+ assert (-oo)**11 is -oo
2190
+ assert (-oo)**12 is oo
2191
+
2192
+
2193
+ def test_issue_6133():
2194
+ raises(TypeError, lambda: (-oo < None))
2195
+ raises(TypeError, lambda: (S(-2) < None))
2196
+ raises(TypeError, lambda: (oo < None))
2197
+ raises(TypeError, lambda: (oo > None))
2198
+ raises(TypeError, lambda: (S(2) < None))
2199
+
2200
+
2201
+ def test_abc():
2202
+ x = numbers.Float(5)
2203
+ assert(isinstance(x, nums.Number))
2204
+ assert(isinstance(x, numbers.Number))
2205
+ assert(isinstance(x, nums.Real))
2206
+ y = numbers.Rational(1, 3)
2207
+ assert(isinstance(y, nums.Number))
2208
+ assert(y.numerator == 1)
2209
+ assert(y.denominator == 3)
2210
+ assert(isinstance(y, nums.Rational))
2211
+ z = numbers.Integer(3)
2212
+ assert(isinstance(z, nums.Number))
2213
+ assert(isinstance(z, numbers.Number))
2214
+ assert(isinstance(z, nums.Rational))
2215
+ assert(isinstance(z, numbers.Rational))
2216
+ assert(isinstance(z, nums.Integral))
2217
+
2218
+
2219
+ def test_floordiv():
2220
+ assert S(2)//S.Half == 4
2221
+
2222
+
2223
+ def test_negation():
2224
+ assert -S.Zero is S.Zero
2225
+ assert -Float(0) is not S.Zero and -Float(0) == 0.0
2226
+
2227
+
2228
+ def test_exponentiation_of_0():
2229
+ x = Symbol('x')
2230
+ assert 0**-x == zoo**x
2231
+ assert unchanged(Pow, 0, x)
2232
+ x = Symbol('x', zero=True)
2233
+ assert 0**-x == S.One
2234
+ assert 0**x == S.One
2235
+
2236
+
2237
+ def test_equal_valued():
2238
+ x = Symbol('x')
2239
+
2240
+ equal_values = [
2241
+ [1, 1.0, S(1), S(1.0), S(1).n(5)],
2242
+ [2, 2.0, S(2), S(2.0), S(2).n(5)],
2243
+ [-1, -1.0, -S(1), -S(1.0), -S(1).n(5)],
2244
+ [0.5, S(0.5), S(1)/2],
2245
+ [-0.5, -S(0.5), -S(1)/2],
2246
+ [0, 0.0, S(0), S(0.0), S(0).n()],
2247
+ [pi], [pi.n()], # <-- not equal
2248
+ [S(1)/10], [0.1, S(0.1)], # <-- not equal
2249
+ [S(0.1).n(5)],
2250
+ [oo],
2251
+ [cos(x/2)], [cos(0.5*x)], # <-- no recursion
2252
+ ]
2253
+
2254
+ for m, values_m in enumerate(equal_values):
2255
+ for value_i in values_m:
2256
+
2257
+ # All values in same list equal
2258
+ for value_j in values_m:
2259
+ assert equal_valued(value_i, value_j) is True
2260
+
2261
+ # Not equal to anything in any other list:
2262
+ for n, values_n in enumerate(equal_values):
2263
+ if n == m:
2264
+ continue
2265
+ for value_j in values_n:
2266
+ assert equal_valued(value_i, value_j) is False
shared/package-files/02/0201abc9e320bf0a23453582581971b0bf4f826a91e4cd1e0b1283ddfe214bf7/is_complex.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/is_complex_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::is_complex(Tensor self) -> bool
26
+ inline bool __dispatch_is_complex(const at::Tensor & self) {
27
+ return at::_ops::is_complex::call(self);
28
+ }
29
+
30
+ }
shared/package-files/02/0203398ea9789f2c6b4c3e73970d030b5a5138b46d94bdadb5439223407486ac/kernel_approximation.py ADDED
@@ -0,0 +1,1106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Approximate kernel feature maps based on Fourier transforms and count sketches."""
2
+
3
+ # Authors: The scikit-learn developers
4
+ # SPDX-License-Identifier: BSD-3-Clause
5
+
6
+ import warnings
7
+ from numbers import Integral, Real
8
+
9
+ import numpy as np
10
+ import scipy.sparse as sp
11
+ from scipy.fft import fft, ifft
12
+ from scipy.linalg import svd
13
+
14
+ from .base import (
15
+ BaseEstimator,
16
+ ClassNamePrefixFeaturesOutMixin,
17
+ TransformerMixin,
18
+ _fit_context,
19
+ )
20
+ from .metrics.pairwise import KERNEL_PARAMS, PAIRWISE_KERNEL_FUNCTIONS, pairwise_kernels
21
+ from .utils import check_random_state
22
+ from .utils._param_validation import Interval, StrOptions
23
+ from .utils.extmath import safe_sparse_dot
24
+ from .utils.validation import (
25
+ _check_feature_names_in,
26
+ check_is_fitted,
27
+ validate_data,
28
+ )
29
+
30
+
31
+ class PolynomialCountSketch(
32
+ ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator
33
+ ):
34
+ """Polynomial kernel approximation via Tensor Sketch.
35
+
36
+ Implements Tensor Sketch, which approximates the feature map
37
+ of the polynomial kernel::
38
+
39
+ K(X, Y) = (gamma * <X, Y> + coef0)^degree
40
+
41
+ by efficiently computing a Count Sketch of the outer product of a
42
+ vector with itself using Fast Fourier Transforms (FFT). Read more in the
43
+ :ref:`User Guide <polynomial_kernel_approx>`.
44
+
45
+ .. versionadded:: 0.24
46
+
47
+ Parameters
48
+ ----------
49
+ gamma : float, default=1.0
50
+ Parameter of the polynomial kernel whose feature map
51
+ will be approximated.
52
+
53
+ degree : int, default=2
54
+ Degree of the polynomial kernel whose feature map
55
+ will be approximated.
56
+
57
+ coef0 : int, default=0
58
+ Constant term of the polynomial kernel whose feature map
59
+ will be approximated.
60
+
61
+ n_components : int, default=100
62
+ Dimensionality of the output feature space. Usually, `n_components`
63
+ should be greater than the number of features in input samples in
64
+ order to achieve good performance. The optimal score / run time
65
+ balance is typically achieved around `n_components` = 10 * `n_features`,
66
+ but this depends on the specific dataset being used.
67
+
68
+ random_state : int, RandomState instance, default=None
69
+ Determines random number generation for indexHash and bitHash
70
+ initialization. Pass an int for reproducible results across multiple
71
+ function calls. See :term:`Glossary <random_state>`.
72
+
73
+ Attributes
74
+ ----------
75
+ indexHash_ : ndarray of shape (degree, n_features), dtype=int64
76
+ Array of indexes in range [0, n_components) used to represent
77
+ the 2-wise independent hash functions for Count Sketch computation.
78
+
79
+ bitHash_ : ndarray of shape (degree, n_features), dtype=float32
80
+ Array with random entries in {+1, -1}, used to represent
81
+ the 2-wise independent hash functions for Count Sketch computation.
82
+
83
+ n_features_in_ : int
84
+ Number of features seen during :term:`fit`.
85
+
86
+ .. versionadded:: 0.24
87
+
88
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
89
+ Names of features seen during :term:`fit`. Defined only when `X`
90
+ has feature names that are all strings.
91
+
92
+ .. versionadded:: 1.0
93
+
94
+ See Also
95
+ --------
96
+ AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel.
97
+ Nystroem : Approximate a kernel map using a subset of the training data.
98
+ RBFSampler : Approximate a RBF kernel feature map using random Fourier
99
+ features.
100
+ SkewedChi2Sampler : Approximate feature map for "skewed chi-squared" kernel.
101
+ sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.
102
+
103
+ Examples
104
+ --------
105
+ >>> from sklearn.kernel_approximation import PolynomialCountSketch
106
+ >>> from sklearn.linear_model import SGDClassifier
107
+ >>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]
108
+ >>> y = [0, 0, 1, 1]
109
+ >>> ps = PolynomialCountSketch(degree=3, random_state=1)
110
+ >>> X_features = ps.fit_transform(X)
111
+ >>> clf = SGDClassifier(max_iter=10, tol=1e-3)
112
+ >>> clf.fit(X_features, y)
113
+ SGDClassifier(max_iter=10)
114
+ >>> clf.score(X_features, y)
115
+ 1.0
116
+
117
+ For a more detailed example of usage, see
118
+ :ref:`sphx_glr_auto_examples_kernel_approximation_plot_scalable_poly_kernels.py`
119
+ """
120
+
121
+ _parameter_constraints: dict = {
122
+ "gamma": [Interval(Real, 0, None, closed="left")],
123
+ "degree": [Interval(Integral, 1, None, closed="left")],
124
+ "coef0": [Interval(Real, None, None, closed="neither")],
125
+ "n_components": [Interval(Integral, 1, None, closed="left")],
126
+ "random_state": ["random_state"],
127
+ }
128
+
129
+ def __init__(
130
+ self, *, gamma=1.0, degree=2, coef0=0, n_components=100, random_state=None
131
+ ):
132
+ self.gamma = gamma
133
+ self.degree = degree
134
+ self.coef0 = coef0
135
+ self.n_components = n_components
136
+ self.random_state = random_state
137
+
138
+ @_fit_context(prefer_skip_nested_validation=True)
139
+ def fit(self, X, y=None):
140
+ """Fit the model with X.
141
+
142
+ Initializes the internal variables. The method needs no information
143
+ about the distribution of data, so we only care about n_features in X.
144
+
145
+ Parameters
146
+ ----------
147
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
148
+ Training data, where `n_samples` is the number of samples
149
+ and `n_features` is the number of features.
150
+
151
+ y : array-like of shape (n_samples,) or (n_samples, n_outputs), \
152
+ default=None
153
+ Target values (None for unsupervised transformations).
154
+
155
+ Returns
156
+ -------
157
+ self : object
158
+ Returns the instance itself.
159
+ """
160
+ X = validate_data(self, X, accept_sparse="csc")
161
+ random_state = check_random_state(self.random_state)
162
+
163
+ n_features = X.shape[1]
164
+ if self.coef0 != 0:
165
+ n_features += 1
166
+
167
+ self.indexHash_ = random_state.randint(
168
+ 0, high=self.n_components, size=(self.degree, n_features)
169
+ )
170
+
171
+ self.bitHash_ = random_state.choice(a=[-1, 1], size=(self.degree, n_features))
172
+ self._n_features_out = self.n_components
173
+ return self
174
+
175
+ def transform(self, X):
176
+ """Generate the feature map approximation for X.
177
+
178
+ Parameters
179
+ ----------
180
+ X : {array-like}, shape (n_samples, n_features)
181
+ New data, where `n_samples` is the number of samples
182
+ and `n_features` is the number of features.
183
+
184
+ Returns
185
+ -------
186
+ X_new : array-like, shape (n_samples, n_components)
187
+ Returns the instance itself.
188
+ """
189
+
190
+ check_is_fitted(self)
191
+ X = validate_data(self, X, accept_sparse="csc", reset=False)
192
+
193
+ X_gamma = np.sqrt(self.gamma) * X
194
+
195
+ if sp.issparse(X_gamma) and self.coef0 != 0:
196
+ X_gamma = sp.hstack(
197
+ [X_gamma, np.sqrt(self.coef0) * np.ones((X_gamma.shape[0], 1))],
198
+ format="csc",
199
+ )
200
+
201
+ elif not sp.issparse(X_gamma) and self.coef0 != 0:
202
+ X_gamma = np.hstack(
203
+ [X_gamma, np.sqrt(self.coef0) * np.ones((X_gamma.shape[0], 1))]
204
+ )
205
+
206
+ if X_gamma.shape[1] != self.indexHash_.shape[1]:
207
+ raise ValueError(
208
+ "Number of features of test samples does not"
209
+ " match that of training samples."
210
+ )
211
+
212
+ count_sketches = np.zeros((X_gamma.shape[0], self.degree, self.n_components))
213
+
214
+ if sp.issparse(X_gamma):
215
+ for j in range(X_gamma.shape[1]):
216
+ for d in range(self.degree):
217
+ iHashIndex = self.indexHash_[d, j]
218
+ iHashBit = self.bitHash_[d, j]
219
+ count_sketches[:, d, iHashIndex] += (
220
+ (iHashBit * X_gamma[:, [j]]).toarray().ravel()
221
+ )
222
+
223
+ else:
224
+ for j in range(X_gamma.shape[1]):
225
+ for d in range(self.degree):
226
+ iHashIndex = self.indexHash_[d, j]
227
+ iHashBit = self.bitHash_[d, j]
228
+ count_sketches[:, d, iHashIndex] += iHashBit * X_gamma[:, j]
229
+
230
+ # For each same, compute a count sketch of phi(x) using the polynomial
231
+ # multiplication (via FFT) of p count sketches of x.
232
+ count_sketches_fft = fft(count_sketches, axis=2, overwrite_x=True)
233
+ count_sketches_fft_prod = np.prod(count_sketches_fft, axis=1)
234
+ data_sketch = np.real(ifft(count_sketches_fft_prod, overwrite_x=True))
235
+
236
+ return data_sketch
237
+
238
+ def __sklearn_tags__(self):
239
+ tags = super().__sklearn_tags__()
240
+ tags.input_tags.sparse = True
241
+ return tags
242
+
243
+
244
+ class RBFSampler(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator):
245
+ """Approximate a RBF kernel feature map using random Fourier features.
246
+
247
+ It implements a variant of Random Kitchen Sinks.[1]
248
+
249
+ Read more in the :ref:`User Guide <rbf_kernel_approx>`.
250
+
251
+ Parameters
252
+ ----------
253
+ gamma : 'scale' or float, default=1.0
254
+ Parameter of RBF kernel: exp(-gamma * x^2).
255
+ If ``gamma='scale'`` is passed then it uses
256
+ 1 / (n_features * X.var()) as value of gamma.
257
+
258
+ .. versionadded:: 1.2
259
+ The option `"scale"` was added in 1.2.
260
+
261
+ n_components : int, default=100
262
+ Number of Monte Carlo samples per original feature.
263
+ Equals the dimensionality of the computed feature space.
264
+
265
+ random_state : int, RandomState instance or None, default=None
266
+ Pseudo-random number generator to control the generation of the random
267
+ weights and random offset when fitting the training data.
268
+ Pass an int for reproducible output across multiple function calls.
269
+ See :term:`Glossary <random_state>`.
270
+
271
+ Attributes
272
+ ----------
273
+ random_offset_ : ndarray of shape (n_components,), dtype={np.float64, np.float32}
274
+ Random offset used to compute the projection in the `n_components`
275
+ dimensions of the feature space.
276
+
277
+ random_weights_ : ndarray of shape (n_features, n_components),\
278
+ dtype={np.float64, np.float32}
279
+ Random projection directions drawn from the Fourier transform
280
+ of the RBF kernel.
281
+
282
+ n_features_in_ : int
283
+ Number of features seen during :term:`fit`.
284
+
285
+ .. versionadded:: 0.24
286
+
287
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
288
+ Names of features seen during :term:`fit`. Defined only when `X`
289
+ has feature names that are all strings.
290
+
291
+ .. versionadded:: 1.0
292
+
293
+ See Also
294
+ --------
295
+ AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel.
296
+ Nystroem : Approximate a kernel map using a subset of the training data.
297
+ PolynomialCountSketch : Polynomial kernel approximation via Tensor Sketch.
298
+ SkewedChi2Sampler : Approximate feature map for
299
+ "skewed chi-squared" kernel.
300
+ sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.
301
+
302
+ Notes
303
+ -----
304
+ See "Random Features for Large-Scale Kernel Machines" by A. Rahimi and
305
+ Benjamin Recht.
306
+
307
+ [1] "Weighted Sums of Random Kitchen Sinks: Replacing
308
+ minimization with randomization in learning" by A. Rahimi and
309
+ Benjamin Recht.
310
+ (https://people.eecs.berkeley.edu/~brecht/papers/08.rah.rec.nips.pdf)
311
+
312
+ Examples
313
+ --------
314
+ >>> from sklearn.kernel_approximation import RBFSampler
315
+ >>> from sklearn.linear_model import SGDClassifier
316
+ >>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]
317
+ >>> y = [0, 0, 1, 1]
318
+ >>> rbf_feature = RBFSampler(gamma=1, random_state=1)
319
+ >>> X_features = rbf_feature.fit_transform(X)
320
+ >>> clf = SGDClassifier(max_iter=5, tol=1e-3)
321
+ >>> clf.fit(X_features, y)
322
+ SGDClassifier(max_iter=5)
323
+ >>> clf.score(X_features, y)
324
+ 1.0
325
+ """
326
+
327
+ _parameter_constraints: dict = {
328
+ "gamma": [
329
+ StrOptions({"scale"}),
330
+ Interval(Real, 0.0, None, closed="left"),
331
+ ],
332
+ "n_components": [Interval(Integral, 1, None, closed="left")],
333
+ "random_state": ["random_state"],
334
+ }
335
+
336
+ def __init__(self, *, gamma=1.0, n_components=100, random_state=None):
337
+ self.gamma = gamma
338
+ self.n_components = n_components
339
+ self.random_state = random_state
340
+
341
+ @_fit_context(prefer_skip_nested_validation=True)
342
+ def fit(self, X, y=None):
343
+ """Fit the model with X.
344
+
345
+ Samples random projection according to n_features.
346
+
347
+ Parameters
348
+ ----------
349
+ X : {array-like, sparse matrix}, shape (n_samples, n_features)
350
+ Training data, where `n_samples` is the number of samples
351
+ and `n_features` is the number of features.
352
+
353
+ y : array-like, shape (n_samples,) or (n_samples, n_outputs), \
354
+ default=None
355
+ Target values (None for unsupervised transformations).
356
+
357
+ Returns
358
+ -------
359
+ self : object
360
+ Returns the instance itself.
361
+ """
362
+ X = validate_data(self, X, accept_sparse="csr")
363
+ random_state = check_random_state(self.random_state)
364
+ n_features = X.shape[1]
365
+ sparse = sp.issparse(X)
366
+ if self.gamma == "scale":
367
+ # var = E[X^2] - E[X]^2 if sparse
368
+ X_var = (X.multiply(X)).mean() - (X.mean()) ** 2 if sparse else X.var()
369
+ self._gamma = 1.0 / (n_features * X_var) if X_var != 0 else 1.0
370
+ else:
371
+ self._gamma = self.gamma
372
+ self.random_weights_ = (2.0 * self._gamma) ** 0.5 * random_state.normal(
373
+ size=(n_features, self.n_components)
374
+ )
375
+
376
+ self.random_offset_ = random_state.uniform(0, 2 * np.pi, size=self.n_components)
377
+
378
+ if X.dtype == np.float32:
379
+ # Setting the data type of the fitted attribute will ensure the
380
+ # output data type during `transform`.
381
+ self.random_weights_ = self.random_weights_.astype(X.dtype, copy=False)
382
+ self.random_offset_ = self.random_offset_.astype(X.dtype, copy=False)
383
+
384
+ self._n_features_out = self.n_components
385
+ return self
386
+
387
+ def transform(self, X):
388
+ """Apply the approximate feature map to X.
389
+
390
+ Parameters
391
+ ----------
392
+ X : {array-like, sparse matrix}, shape (n_samples, n_features)
393
+ New data, where `n_samples` is the number of samples
394
+ and `n_features` is the number of features.
395
+
396
+ Returns
397
+ -------
398
+ X_new : array-like, shape (n_samples, n_components)
399
+ Returns the instance itself.
400
+ """
401
+ check_is_fitted(self)
402
+
403
+ X = validate_data(self, X, accept_sparse="csr", reset=False)
404
+ projection = safe_sparse_dot(X, self.random_weights_)
405
+ projection += self.random_offset_
406
+ np.cos(projection, projection)
407
+ projection *= (2.0 / self.n_components) ** 0.5
408
+ return projection
409
+
410
+ def __sklearn_tags__(self):
411
+ tags = super().__sklearn_tags__()
412
+ tags.input_tags.sparse = True
413
+ tags.transformer_tags.preserves_dtype = ["float64", "float32"]
414
+ return tags
415
+
416
+
417
+ class SkewedChi2Sampler(
418
+ ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator
419
+ ):
420
+ """Approximate feature map for "skewed chi-squared" kernel.
421
+
422
+ Read more in the :ref:`User Guide <skewed_chi_kernel_approx>`.
423
+
424
+ Parameters
425
+ ----------
426
+ skewedness : float, default=1.0
427
+ "skewedness" parameter of the kernel. Needs to be cross-validated.
428
+
429
+ n_components : int, default=100
430
+ Number of Monte Carlo samples per original feature.
431
+ Equals the dimensionality of the computed feature space.
432
+
433
+ random_state : int, RandomState instance or None, default=None
434
+ Pseudo-random number generator to control the generation of the random
435
+ weights and random offset when fitting the training data.
436
+ Pass an int for reproducible output across multiple function calls.
437
+ See :term:`Glossary <random_state>`.
438
+
439
+ Attributes
440
+ ----------
441
+ random_weights_ : ndarray of shape (n_features, n_components)
442
+ Weight array, sampled from a secant hyperbolic distribution, which will
443
+ be used to linearly transform the log of the data.
444
+
445
+ random_offset_ : ndarray of shape (n_features, n_components)
446
+ Bias term, which will be added to the data. It is uniformly distributed
447
+ between 0 and 2*pi.
448
+
449
+ n_features_in_ : int
450
+ Number of features seen during :term:`fit`.
451
+
452
+ .. versionadded:: 0.24
453
+
454
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
455
+ Names of features seen during :term:`fit`. Defined only when `X`
456
+ has feature names that are all strings.
457
+
458
+ .. versionadded:: 1.0
459
+
460
+ See Also
461
+ --------
462
+ AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel.
463
+ Nystroem : Approximate a kernel map using a subset of the training data.
464
+ RBFSampler : Approximate a RBF kernel feature map using random Fourier
465
+ features.
466
+ SkewedChi2Sampler : Approximate feature map for "skewed chi-squared" kernel.
467
+ sklearn.metrics.pairwise.chi2_kernel : The exact chi squared kernel.
468
+ sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.
469
+
470
+ References
471
+ ----------
472
+ See "Random Fourier Approximations for Skewed Multiplicative Histogram
473
+ Kernels" by Fuxin Li, Catalin Ionescu and Cristian Sminchisescu.
474
+
475
+ Examples
476
+ --------
477
+ >>> from sklearn.kernel_approximation import SkewedChi2Sampler
478
+ >>> from sklearn.linear_model import SGDClassifier
479
+ >>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]
480
+ >>> y = [0, 0, 1, 1]
481
+ >>> chi2_feature = SkewedChi2Sampler(skewedness=.01,
482
+ ... n_components=10,
483
+ ... random_state=0)
484
+ >>> X_features = chi2_feature.fit_transform(X, y)
485
+ >>> clf = SGDClassifier(max_iter=10, tol=1e-3)
486
+ >>> clf.fit(X_features, y)
487
+ SGDClassifier(max_iter=10)
488
+ >>> clf.score(X_features, y)
489
+ 1.0
490
+ """
491
+
492
+ _parameter_constraints: dict = {
493
+ "skewedness": [Interval(Real, None, None, closed="neither")],
494
+ "n_components": [Interval(Integral, 1, None, closed="left")],
495
+ "random_state": ["random_state"],
496
+ }
497
+
498
+ def __init__(self, *, skewedness=1.0, n_components=100, random_state=None):
499
+ self.skewedness = skewedness
500
+ self.n_components = n_components
501
+ self.random_state = random_state
502
+
503
+ @_fit_context(prefer_skip_nested_validation=True)
504
+ def fit(self, X, y=None):
505
+ """Fit the model with X.
506
+
507
+ Samples random projection according to n_features.
508
+
509
+ Parameters
510
+ ----------
511
+ X : array-like, shape (n_samples, n_features)
512
+ Training data, where `n_samples` is the number of samples
513
+ and `n_features` is the number of features.
514
+
515
+ y : array-like, shape (n_samples,) or (n_samples, n_outputs), \
516
+ default=None
517
+ Target values (None for unsupervised transformations).
518
+
519
+ Returns
520
+ -------
521
+ self : object
522
+ Returns the instance itself.
523
+ """
524
+ X = validate_data(self, X)
525
+ random_state = check_random_state(self.random_state)
526
+ n_features = X.shape[1]
527
+ uniform = random_state.uniform(size=(n_features, self.n_components))
528
+ # transform by inverse CDF of sech
529
+ self.random_weights_ = 1.0 / np.pi * np.log(np.tan(np.pi / 2.0 * uniform))
530
+ self.random_offset_ = random_state.uniform(0, 2 * np.pi, size=self.n_components)
531
+
532
+ if X.dtype == np.float32:
533
+ # Setting the data type of the fitted attribute will ensure the
534
+ # output data type during `transform`.
535
+ self.random_weights_ = self.random_weights_.astype(X.dtype, copy=False)
536
+ self.random_offset_ = self.random_offset_.astype(X.dtype, copy=False)
537
+
538
+ self._n_features_out = self.n_components
539
+ return self
540
+
541
+ def transform(self, X):
542
+ """Apply the approximate feature map to X.
543
+
544
+ Parameters
545
+ ----------
546
+ X : array-like, shape (n_samples, n_features)
547
+ New data, where `n_samples` is the number of samples
548
+ and `n_features` is the number of features. All values of X must be
549
+ strictly greater than "-skewedness".
550
+
551
+ Returns
552
+ -------
553
+ X_new : array-like, shape (n_samples, n_components)
554
+ Returns the instance itself.
555
+ """
556
+ check_is_fitted(self)
557
+ X = validate_data(
558
+ self, X, copy=True, dtype=[np.float64, np.float32], reset=False
559
+ )
560
+ if (X <= -self.skewedness).any():
561
+ raise ValueError("X may not contain entries smaller than -skewedness.")
562
+
563
+ X += self.skewedness
564
+ np.log(X, X)
565
+ projection = safe_sparse_dot(X, self.random_weights_)
566
+ projection += self.random_offset_
567
+ np.cos(projection, projection)
568
+ projection *= np.sqrt(2.0) / np.sqrt(self.n_components)
569
+ return projection
570
+
571
+ def __sklearn_tags__(self):
572
+ tags = super().__sklearn_tags__()
573
+ tags.transformer_tags.preserves_dtype = ["float64", "float32"]
574
+ return tags
575
+
576
+
577
+ class AdditiveChi2Sampler(TransformerMixin, BaseEstimator):
578
+ """Approximate feature map for additive chi2 kernel.
579
+
580
+ Uses sampling the fourier transform of the kernel characteristic
581
+ at regular intervals.
582
+
583
+ Since the kernel that is to be approximated is additive, the components of
584
+ the input vectors can be treated separately. Each entry in the original
585
+ space is transformed into 2*sample_steps-1 features, where sample_steps is
586
+ a parameter of the method. Typical values of sample_steps include 1, 2 and
587
+ 3.
588
+
589
+ Optimal choices for the sampling interval for certain data ranges can be
590
+ computed (see the reference). The default values should be reasonable.
591
+
592
+ Read more in the :ref:`User Guide <additive_chi_kernel_approx>`.
593
+
594
+ Parameters
595
+ ----------
596
+ sample_steps : int, default=2
597
+ Gives the number of (complex) sampling points.
598
+
599
+ sample_interval : float, default=None
600
+ Sampling interval. Must be specified when sample_steps not in {1,2,3}.
601
+
602
+ Attributes
603
+ ----------
604
+ n_features_in_ : int
605
+ Number of features seen during :term:`fit`.
606
+
607
+ .. versionadded:: 0.24
608
+
609
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
610
+ Names of features seen during :term:`fit`. Defined only when `X`
611
+ has feature names that are all strings.
612
+
613
+ .. versionadded:: 1.0
614
+
615
+ See Also
616
+ --------
617
+ SkewedChi2Sampler : A Fourier-approximation to a non-additive variant of
618
+ the chi squared kernel.
619
+
620
+ sklearn.metrics.pairwise.chi2_kernel : The exact chi squared kernel.
621
+
622
+ sklearn.metrics.pairwise.additive_chi2_kernel : The exact additive chi
623
+ squared kernel.
624
+
625
+ Notes
626
+ -----
627
+ This estimator approximates a slightly different version of the additive
628
+ chi squared kernel then ``metric.additive_chi2`` computes.
629
+
630
+ This estimator is stateless and does not need to be fitted. However, we
631
+ recommend to call :meth:`fit_transform` instead of :meth:`transform`, as
632
+ parameter validation is only performed in :meth:`fit`.
633
+
634
+ References
635
+ ----------
636
+ See `"Efficient additive kernels via explicit feature maps"
637
+ <http://www.robots.ox.ac.uk/~vedaldi/assets/pubs/vedaldi11efficient.pdf>`_
638
+ A. Vedaldi and A. Zisserman, Pattern Analysis and Machine Intelligence,
639
+ 2011
640
+
641
+ Examples
642
+ --------
643
+ >>> from sklearn.datasets import load_digits
644
+ >>> from sklearn.linear_model import SGDClassifier
645
+ >>> from sklearn.kernel_approximation import AdditiveChi2Sampler
646
+ >>> X, y = load_digits(return_X_y=True)
647
+ >>> chi2sampler = AdditiveChi2Sampler(sample_steps=2)
648
+ >>> X_transformed = chi2sampler.fit_transform(X, y)
649
+ >>> clf = SGDClassifier(max_iter=5, random_state=0, tol=1e-3)
650
+ >>> clf.fit(X_transformed, y)
651
+ SGDClassifier(max_iter=5, random_state=0)
652
+ >>> clf.score(X_transformed, y)
653
+ 0.9499...
654
+ """
655
+
656
+ _parameter_constraints: dict = {
657
+ "sample_steps": [Interval(Integral, 1, None, closed="left")],
658
+ "sample_interval": [Interval(Real, 0, None, closed="left"), None],
659
+ }
660
+
661
+ def __init__(self, *, sample_steps=2, sample_interval=None):
662
+ self.sample_steps = sample_steps
663
+ self.sample_interval = sample_interval
664
+
665
+ @_fit_context(prefer_skip_nested_validation=True)
666
+ def fit(self, X, y=None):
667
+ """Only validates estimator's parameters.
668
+
669
+ This method allows to: (i) validate the estimator's parameters and
670
+ (ii) be consistent with the scikit-learn transformer API.
671
+
672
+ Parameters
673
+ ----------
674
+ X : array-like, shape (n_samples, n_features)
675
+ Training data, where `n_samples` is the number of samples
676
+ and `n_features` is the number of features.
677
+
678
+ y : array-like, shape (n_samples,) or (n_samples, n_outputs), \
679
+ default=None
680
+ Target values (None for unsupervised transformations).
681
+
682
+ Returns
683
+ -------
684
+ self : object
685
+ Returns the transformer.
686
+ """
687
+ X = validate_data(self, X, accept_sparse="csr", ensure_non_negative=True)
688
+
689
+ if self.sample_interval is None and self.sample_steps not in (1, 2, 3):
690
+ raise ValueError(
691
+ "If sample_steps is not in [1, 2, 3],"
692
+ " you need to provide sample_interval"
693
+ )
694
+
695
+ return self
696
+
697
+ def transform(self, X):
698
+ """Apply approximate feature map to X.
699
+
700
+ Parameters
701
+ ----------
702
+ X : {array-like, sparse matrix}, shape (n_samples, n_features)
703
+ Training data, where `n_samples` is the number of samples
704
+ and `n_features` is the number of features.
705
+
706
+ Returns
707
+ -------
708
+ X_new : {ndarray, sparse matrix}, \
709
+ shape = (n_samples, n_features * (2*sample_steps - 1))
710
+ Whether the return value is an array or sparse matrix depends on
711
+ the type of the input X.
712
+ """
713
+ X = validate_data(
714
+ self, X, accept_sparse="csr", reset=False, ensure_non_negative=True
715
+ )
716
+ sparse = sp.issparse(X)
717
+
718
+ if self.sample_interval is None:
719
+ # See figure 2 c) of "Efficient additive kernels via explicit feature maps"
720
+ # <http://www.robots.ox.ac.uk/~vedaldi/assets/pubs/vedaldi11efficient.pdf>
721
+ # A. Vedaldi and A. Zisserman, Pattern Analysis and Machine Intelligence,
722
+ # 2011
723
+ if self.sample_steps == 1:
724
+ sample_interval = 0.8
725
+ elif self.sample_steps == 2:
726
+ sample_interval = 0.5
727
+ elif self.sample_steps == 3:
728
+ sample_interval = 0.4
729
+ else:
730
+ raise ValueError(
731
+ "If sample_steps is not in [1, 2, 3],"
732
+ " you need to provide sample_interval"
733
+ )
734
+ else:
735
+ sample_interval = self.sample_interval
736
+
737
+ # zeroth component
738
+ # 1/cosh = sech
739
+ # cosh(0) = 1.0
740
+ transf = self._transform_sparse if sparse else self._transform_dense
741
+ return transf(X, self.sample_steps, sample_interval)
742
+
743
+ def get_feature_names_out(self, input_features=None):
744
+ """Get output feature names for transformation.
745
+
746
+ Parameters
747
+ ----------
748
+ input_features : array-like of str or None, default=None
749
+ Only used to validate feature names with the names seen in :meth:`fit`.
750
+
751
+ Returns
752
+ -------
753
+ feature_names_out : ndarray of str objects
754
+ Transformed feature names.
755
+ """
756
+ # Note that passing attributes="n_features_in_" forces check_is_fitted
757
+ # to check if the attribute is present. Otherwise it will pass on this
758
+ # stateless estimator (requires_fit=False)
759
+ check_is_fitted(self, attributes="n_features_in_")
760
+ input_features = _check_feature_names_in(
761
+ self, input_features, generate_names=True
762
+ )
763
+ est_name = self.__class__.__name__.lower()
764
+
765
+ names_list = [f"{est_name}_{name}_sqrt" for name in input_features]
766
+
767
+ for j in range(1, self.sample_steps):
768
+ cos_names = [f"{est_name}_{name}_cos{j}" for name in input_features]
769
+ sin_names = [f"{est_name}_{name}_sin{j}" for name in input_features]
770
+ names_list.extend(cos_names + sin_names)
771
+
772
+ return np.asarray(names_list, dtype=object)
773
+
774
+ @staticmethod
775
+ def _transform_dense(X, sample_steps, sample_interval):
776
+ non_zero = X != 0.0
777
+ X_nz = X[non_zero]
778
+
779
+ X_step = np.zeros_like(X)
780
+ X_step[non_zero] = np.sqrt(X_nz * sample_interval)
781
+
782
+ X_new = [X_step]
783
+
784
+ log_step_nz = sample_interval * np.log(X_nz)
785
+ step_nz = 2 * X_nz * sample_interval
786
+
787
+ for j in range(1, sample_steps):
788
+ factor_nz = np.sqrt(step_nz / np.cosh(np.pi * j * sample_interval))
789
+
790
+ X_step = np.zeros_like(X)
791
+ X_step[non_zero] = factor_nz * np.cos(j * log_step_nz)
792
+ X_new.append(X_step)
793
+
794
+ X_step = np.zeros_like(X)
795
+ X_step[non_zero] = factor_nz * np.sin(j * log_step_nz)
796
+ X_new.append(X_step)
797
+
798
+ return np.hstack(X_new)
799
+
800
+ @staticmethod
801
+ def _transform_sparse(X, sample_steps, sample_interval):
802
+ indices = X.indices.copy()
803
+ indptr = X.indptr.copy()
804
+
805
+ data_step = np.sqrt(X.data * sample_interval)
806
+ X_step = sp.csr_matrix(
807
+ (data_step, indices, indptr), shape=X.shape, dtype=X.dtype, copy=False
808
+ )
809
+ X_new = [X_step]
810
+
811
+ log_step_nz = sample_interval * np.log(X.data)
812
+ step_nz = 2 * X.data * sample_interval
813
+
814
+ for j in range(1, sample_steps):
815
+ factor_nz = np.sqrt(step_nz / np.cosh(np.pi * j * sample_interval))
816
+
817
+ data_step = factor_nz * np.cos(j * log_step_nz)
818
+ X_step = sp.csr_matrix(
819
+ (data_step, indices, indptr), shape=X.shape, dtype=X.dtype, copy=False
820
+ )
821
+ X_new.append(X_step)
822
+
823
+ data_step = factor_nz * np.sin(j * log_step_nz)
824
+ X_step = sp.csr_matrix(
825
+ (data_step, indices, indptr), shape=X.shape, dtype=X.dtype, copy=False
826
+ )
827
+ X_new.append(X_step)
828
+
829
+ return sp.hstack(X_new)
830
+
831
+ def __sklearn_tags__(self):
832
+ tags = super().__sklearn_tags__()
833
+ tags.requires_fit = False
834
+ tags.input_tags.positive_only = True
835
+ tags.input_tags.sparse = True
836
+ return tags
837
+
838
+
839
+ class Nystroem(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator):
840
+ """Approximate a kernel map using a subset of the training data.
841
+
842
+ Constructs an approximate feature map for an arbitrary kernel
843
+ using a subset of the data as basis.
844
+
845
+ Read more in the :ref:`User Guide <nystroem_kernel_approx>`.
846
+
847
+ .. versionadded:: 0.13
848
+
849
+ Parameters
850
+ ----------
851
+ kernel : str or callable, default='rbf'
852
+ Kernel map to be approximated. A callable should accept two arguments
853
+ and the keyword arguments passed to this object as `kernel_params`, and
854
+ should return a floating point number.
855
+
856
+ gamma : float, default=None
857
+ Gamma parameter for the RBF, laplacian, polynomial, exponential chi2
858
+ and sigmoid kernels. Interpretation of the default value is left to
859
+ the kernel; see the documentation for sklearn.metrics.pairwise.
860
+ Ignored by other kernels.
861
+
862
+ coef0 : float, default=None
863
+ Zero coefficient for polynomial and sigmoid kernels.
864
+ Ignored by other kernels.
865
+
866
+ degree : float, default=None
867
+ Degree of the polynomial kernel. Ignored by other kernels.
868
+
869
+ kernel_params : dict, default=None
870
+ Additional parameters (keyword arguments) for kernel function passed
871
+ as callable object.
872
+
873
+ n_components : int, default=100
874
+ Number of features to construct.
875
+ How many data points will be used to construct the mapping.
876
+
877
+ random_state : int, RandomState instance or None, default=None
878
+ Pseudo-random number generator to control the uniform sampling without
879
+ replacement of `n_components` of the training data to construct the
880
+ basis kernel.
881
+ Pass an int for reproducible output across multiple function calls.
882
+ See :term:`Glossary <random_state>`.
883
+
884
+ n_jobs : int, default=None
885
+ The number of jobs to use for the computation. This works by breaking
886
+ down the kernel matrix into `n_jobs` even slices and computing them in
887
+ parallel.
888
+
889
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
890
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
891
+ for more details.
892
+
893
+ .. versionadded:: 0.24
894
+
895
+ Attributes
896
+ ----------
897
+ components_ : ndarray of shape (n_components, n_features)
898
+ Subset of training points used to construct the feature map.
899
+
900
+ component_indices_ : ndarray of shape (n_components)
901
+ Indices of ``components_`` in the training set.
902
+
903
+ normalization_ : ndarray of shape (n_components, n_components)
904
+ Normalization matrix needed for embedding.
905
+ Square root of the kernel matrix on ``components_``.
906
+
907
+ n_features_in_ : int
908
+ Number of features seen during :term:`fit`.
909
+
910
+ .. versionadded:: 0.24
911
+
912
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
913
+ Names of features seen during :term:`fit`. Defined only when `X`
914
+ has feature names that are all strings.
915
+
916
+ .. versionadded:: 1.0
917
+
918
+ See Also
919
+ --------
920
+ AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel.
921
+ PolynomialCountSketch : Polynomial kernel approximation via Tensor Sketch.
922
+ RBFSampler : Approximate a RBF kernel feature map using random Fourier
923
+ features.
924
+ SkewedChi2Sampler : Approximate feature map for "skewed chi-squared" kernel.
925
+ sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.
926
+
927
+ References
928
+ ----------
929
+ * Williams, C.K.I. and Seeger, M.
930
+ "Using the Nystroem method to speed up kernel machines",
931
+ Advances in neural information processing systems 2001
932
+
933
+ * T. Yang, Y. Li, M. Mahdavi, R. Jin and Z. Zhou
934
+ "Nystroem Method vs Random Fourier Features: A Theoretical and Empirical
935
+ Comparison",
936
+ Advances in Neural Information Processing Systems 2012
937
+
938
+ Examples
939
+ --------
940
+ >>> from sklearn import datasets, svm
941
+ >>> from sklearn.kernel_approximation import Nystroem
942
+ >>> X, y = datasets.load_digits(n_class=9, return_X_y=True)
943
+ >>> data = X / 16.
944
+ >>> clf = svm.LinearSVC()
945
+ >>> feature_map_nystroem = Nystroem(gamma=.2,
946
+ ... random_state=1,
947
+ ... n_components=300)
948
+ >>> data_transformed = feature_map_nystroem.fit_transform(data)
949
+ >>> clf.fit(data_transformed, y)
950
+ LinearSVC()
951
+ >>> clf.score(data_transformed, y)
952
+ 0.9987...
953
+ """
954
+
955
+ _parameter_constraints: dict = {
956
+ "kernel": [
957
+ StrOptions(set(PAIRWISE_KERNEL_FUNCTIONS.keys()) | {"precomputed"}),
958
+ callable,
959
+ ],
960
+ "gamma": [Interval(Real, 0, None, closed="left"), None],
961
+ "coef0": [Interval(Real, None, None, closed="neither"), None],
962
+ "degree": [Interval(Real, 1, None, closed="left"), None],
963
+ "kernel_params": [dict, None],
964
+ "n_components": [Interval(Integral, 1, None, closed="left")],
965
+ "random_state": ["random_state"],
966
+ "n_jobs": [Integral, None],
967
+ }
968
+
969
+ def __init__(
970
+ self,
971
+ kernel="rbf",
972
+ *,
973
+ gamma=None,
974
+ coef0=None,
975
+ degree=None,
976
+ kernel_params=None,
977
+ n_components=100,
978
+ random_state=None,
979
+ n_jobs=None,
980
+ ):
981
+ self.kernel = kernel
982
+ self.gamma = gamma
983
+ self.coef0 = coef0
984
+ self.degree = degree
985
+ self.kernel_params = kernel_params
986
+ self.n_components = n_components
987
+ self.random_state = random_state
988
+ self.n_jobs = n_jobs
989
+
990
+ @_fit_context(prefer_skip_nested_validation=True)
991
+ def fit(self, X, y=None):
992
+ """Fit estimator to data.
993
+
994
+ Samples a subset of training points, computes kernel
995
+ on these and computes normalization matrix.
996
+
997
+ Parameters
998
+ ----------
999
+ X : array-like, shape (n_samples, n_features)
1000
+ Training data, where `n_samples` is the number of samples
1001
+ and `n_features` is the number of features.
1002
+
1003
+ y : array-like, shape (n_samples,) or (n_samples, n_outputs), \
1004
+ default=None
1005
+ Target values (None for unsupervised transformations).
1006
+
1007
+ Returns
1008
+ -------
1009
+ self : object
1010
+ Returns the instance itself.
1011
+ """
1012
+ X = validate_data(self, X, accept_sparse="csr")
1013
+ rnd = check_random_state(self.random_state)
1014
+ n_samples = X.shape[0]
1015
+
1016
+ # get basis vectors
1017
+ if self.n_components > n_samples:
1018
+ # XXX should we just bail?
1019
+ n_components = n_samples
1020
+ warnings.warn(
1021
+ "n_components > n_samples. This is not possible.\n"
1022
+ "n_components was set to n_samples, which results"
1023
+ " in inefficient evaluation of the full kernel."
1024
+ )
1025
+
1026
+ else:
1027
+ n_components = self.n_components
1028
+ n_components = min(n_samples, n_components)
1029
+ inds = rnd.permutation(n_samples)
1030
+ basis_inds = inds[:n_components]
1031
+ basis = X[basis_inds]
1032
+
1033
+ basis_kernel = pairwise_kernels(
1034
+ basis,
1035
+ metric=self.kernel,
1036
+ filter_params=True,
1037
+ n_jobs=self.n_jobs,
1038
+ **self._get_kernel_params(),
1039
+ )
1040
+
1041
+ # sqrt of kernel matrix on basis vectors
1042
+ U, S, V = svd(basis_kernel)
1043
+ S = np.maximum(S, 1e-12)
1044
+ self.normalization_ = np.dot(U / np.sqrt(S), V)
1045
+ self.components_ = basis
1046
+ self.component_indices_ = basis_inds
1047
+ self._n_features_out = n_components
1048
+ return self
1049
+
1050
+ def transform(self, X):
1051
+ """Apply feature map to X.
1052
+
1053
+ Computes an approximate feature map using the kernel
1054
+ between some training points and X.
1055
+
1056
+ Parameters
1057
+ ----------
1058
+ X : array-like of shape (n_samples, n_features)
1059
+ Data to transform.
1060
+
1061
+ Returns
1062
+ -------
1063
+ X_transformed : ndarray of shape (n_samples, n_components)
1064
+ Transformed data.
1065
+ """
1066
+ check_is_fitted(self)
1067
+ X = validate_data(self, X, accept_sparse="csr", reset=False)
1068
+
1069
+ kernel_params = self._get_kernel_params()
1070
+ embedded = pairwise_kernels(
1071
+ X,
1072
+ self.components_,
1073
+ metric=self.kernel,
1074
+ filter_params=True,
1075
+ n_jobs=self.n_jobs,
1076
+ **kernel_params,
1077
+ )
1078
+ return np.dot(embedded, self.normalization_.T)
1079
+
1080
+ def _get_kernel_params(self):
1081
+ params = self.kernel_params
1082
+ if params is None:
1083
+ params = {}
1084
+ if not callable(self.kernel) and self.kernel != "precomputed":
1085
+ for param in KERNEL_PARAMS[self.kernel]:
1086
+ if getattr(self, param) is not None:
1087
+ params[param] = getattr(self, param)
1088
+ else:
1089
+ if (
1090
+ self.gamma is not None
1091
+ or self.coef0 is not None
1092
+ or self.degree is not None
1093
+ ):
1094
+ raise ValueError(
1095
+ "Don't pass gamma, coef0 or degree to "
1096
+ "Nystroem if using a callable "
1097
+ "or precomputed kernel"
1098
+ )
1099
+
1100
+ return params
1101
+
1102
+ def __sklearn_tags__(self):
1103
+ tags = super().__sklearn_tags__()
1104
+ tags.input_tags.sparse = True
1105
+ tags.transformer_tags.preserves_dtype = ["float64", "float32"]
1106
+ return tags
shared/package-files/02/020417a134f7c95351600141013eb61c1a2efcaf411dfbad1ffd6554b906be69/frexp_cpu_dispatch.h 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 cpu {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> frexp_out(at::Tensor & mantissa, at::Tensor & exponent, const at::Tensor & self);
21
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> frexp_outf(const at::Tensor & self, at::Tensor & mantissa, at::Tensor & exponent);
22
+
23
+ } // namespace cpu
24
+ } // namespace at
shared/package-files/02/020861c07567ff026c101068f931e6308293f73afe80126590b4dcb49ad3fde6/factortools.py ADDED
@@ -0,0 +1,1502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Polynomial factorization routines in characteristic zero. """
2
+
3
+ from sympy.core.random import _randint
4
+
5
+ from sympy.polys.galoistools import (
6
+ gf_from_int_poly, gf_to_int_poly,
7
+ gf_lshift, gf_add_mul, gf_mul,
8
+ gf_div, gf_rem,
9
+ gf_gcdex,
10
+ gf_sqf_p,
11
+ gf_factor_sqf, gf_factor)
12
+
13
+ from sympy.polys.densebasic import (
14
+ dup_LC, dmp_LC, dmp_ground_LC,
15
+ dup_TC,
16
+ dup_convert, dmp_convert,
17
+ dup_degree, dmp_degree,
18
+ dmp_degree_in, dmp_degree_list,
19
+ dmp_from_dict,
20
+ dmp_zero_p,
21
+ dmp_one,
22
+ dmp_nest, dmp_raise,
23
+ dup_strip,
24
+ dmp_ground,
25
+ dup_inflate,
26
+ dmp_exclude, dmp_include,
27
+ dmp_inject, dmp_eject,
28
+ dup_terms_gcd, dmp_terms_gcd)
29
+
30
+ from sympy.polys.densearith import (
31
+ dup_neg, dmp_neg,
32
+ dup_add, dmp_add,
33
+ dup_sub, dmp_sub,
34
+ dup_mul, dmp_mul,
35
+ dup_sqr,
36
+ dmp_pow,
37
+ dup_div, dmp_div,
38
+ dup_quo, dmp_quo,
39
+ dmp_expand,
40
+ dmp_add_mul,
41
+ dup_sub_mul, dmp_sub_mul,
42
+ dup_lshift,
43
+ dup_max_norm, dmp_max_norm,
44
+ dup_l1_norm,
45
+ dup_mul_ground, dmp_mul_ground,
46
+ dup_quo_ground, dmp_quo_ground)
47
+
48
+ from sympy.polys.densetools import (
49
+ dup_clear_denoms, dmp_clear_denoms,
50
+ dup_trunc, dmp_ground_trunc,
51
+ dup_content,
52
+ dup_monic, dmp_ground_monic,
53
+ dup_primitive, dmp_ground_primitive,
54
+ dmp_eval_tail,
55
+ dmp_eval_in, dmp_diff_eval_in,
56
+ dmp_compose,
57
+ dup_shift, dup_mirror)
58
+
59
+ from sympy.polys.euclidtools import (
60
+ dmp_primitive,
61
+ dup_inner_gcd, dmp_inner_gcd)
62
+
63
+ from sympy.polys.sqfreetools import (
64
+ dup_sqf_p,
65
+ dup_sqf_norm, dmp_sqf_norm,
66
+ dup_sqf_part, dmp_sqf_part)
67
+
68
+ from sympy.polys.polyutils import _sort_factors
69
+ from sympy.polys.polyconfig import query
70
+
71
+ from sympy.polys.polyerrors import (
72
+ ExtraneousFactors, DomainError, CoercionFailed, EvaluationFailed)
73
+
74
+ from sympy.utilities import subsets
75
+
76
+ from math import ceil as _ceil, log as _log
77
+
78
+
79
+ def dup_trial_division(f, factors, K):
80
+ """
81
+ Determine multiplicities of factors for a univariate polynomial
82
+ using trial division.
83
+ """
84
+ result = []
85
+
86
+ for factor in factors:
87
+ k = 0
88
+
89
+ while True:
90
+ q, r = dup_div(f, factor, K)
91
+
92
+ if not r:
93
+ f, k = q, k + 1
94
+ else:
95
+ break
96
+
97
+ result.append((factor, k))
98
+
99
+ return _sort_factors(result)
100
+
101
+
102
+ def dmp_trial_division(f, factors, u, K):
103
+ """
104
+ Determine multiplicities of factors for a multivariate polynomial
105
+ using trial division.
106
+ """
107
+ result = []
108
+
109
+ for factor in factors:
110
+ k = 0
111
+
112
+ while True:
113
+ q, r = dmp_div(f, factor, u, K)
114
+
115
+ if dmp_zero_p(r, u):
116
+ f, k = q, k + 1
117
+ else:
118
+ break
119
+
120
+ result.append((factor, k))
121
+
122
+ return _sort_factors(result)
123
+
124
+
125
+ def dup_zz_mignotte_bound(f, K):
126
+ """
127
+ The Knuth-Cohen variant of Mignotte bound for
128
+ univariate polynomials in `K[x]`.
129
+
130
+ Examples
131
+ ========
132
+
133
+ >>> from sympy.polys import ring, ZZ
134
+ >>> R, x = ring("x", ZZ)
135
+
136
+ >>> f = x**3 + 14*x**2 + 56*x + 64
137
+ >>> R.dup_zz_mignotte_bound(f)
138
+ 152
139
+
140
+ By checking `factor(f)` we can see that max coeff is 8
141
+
142
+ Also consider a case that `f` is irreducible for example `f = 2*x**2 + 3*x + 4`
143
+ To avoid a bug for these cases, we return the bound plus the max coefficient of `f`
144
+
145
+ >>> f = 2*x**2 + 3*x + 4
146
+ >>> R.dup_zz_mignotte_bound(f)
147
+ 6
148
+
149
+ Lastly,To see the difference between the new and the old Mignotte bound
150
+ consider the irreducible polynomial::
151
+
152
+ >>> f = 87*x**7 + 4*x**6 + 80*x**5 + 17*x**4 + 9*x**3 + 12*x**2 + 49*x + 26
153
+ >>> R.dup_zz_mignotte_bound(f)
154
+ 744
155
+
156
+ The new Mignotte bound is 744 whereas the old one (SymPy 1.5.1) is 1937664.
157
+
158
+
159
+ References
160
+ ==========
161
+
162
+ ..[1] [Abbott2013]_
163
+
164
+ """
165
+ from sympy.functions.combinatorial.factorials import binomial
166
+ d = dup_degree(f)
167
+ delta = _ceil(d / 2)
168
+ delta2 = _ceil(delta / 2)
169
+
170
+ # euclidean-norm
171
+ eucl_norm = K.sqrt( sum( [cf**2 for cf in f] ) )
172
+
173
+ # biggest values of binomial coefficients (p. 538 of reference)
174
+ t1 = binomial(delta - 1, delta2)
175
+ t2 = binomial(delta - 1, delta2 - 1)
176
+
177
+ lc = K.abs(dup_LC(f, K)) # leading coefficient
178
+ bound = t1 * eucl_norm + t2 * lc # (p. 538 of reference)
179
+ bound += dup_max_norm(f, K) # add max coeff for irreducible polys
180
+ bound = _ceil(bound / 2) * 2 # round up to even integer
181
+
182
+ return bound
183
+
184
+ def dmp_zz_mignotte_bound(f, u, K):
185
+ """Mignotte bound for multivariate polynomials in `K[X]`. """
186
+ a = dmp_max_norm(f, u, K)
187
+ b = abs(dmp_ground_LC(f, u, K))
188
+ n = sum(dmp_degree_list(f, u))
189
+
190
+ return K.sqrt(K(n + 1))*2**n*a*b
191
+
192
+
193
+ def dup_zz_hensel_step(m, f, g, h, s, t, K):
194
+ """
195
+ One step in Hensel lifting in `Z[x]`.
196
+
197
+ Given positive integer `m` and `Z[x]` polynomials `f`, `g`, `h`, `s`
198
+ and `t` such that::
199
+
200
+ f = g*h (mod m)
201
+ s*g + t*h = 1 (mod m)
202
+
203
+ lc(f) is not a zero divisor (mod m)
204
+ lc(h) = 1
205
+
206
+ deg(f) = deg(g) + deg(h)
207
+ deg(s) < deg(h)
208
+ deg(t) < deg(g)
209
+
210
+ returns polynomials `G`, `H`, `S` and `T`, such that::
211
+
212
+ f = G*H (mod m**2)
213
+ S*G + T*H = 1 (mod m**2)
214
+
215
+ References
216
+ ==========
217
+
218
+ .. [1] [Gathen99]_
219
+
220
+ """
221
+ M = m**2
222
+
223
+ e = dup_sub_mul(f, g, h, K)
224
+ e = dup_trunc(e, M, K)
225
+
226
+ q, r = dup_div(dup_mul(s, e, K), h, K)
227
+
228
+ q = dup_trunc(q, M, K)
229
+ r = dup_trunc(r, M, K)
230
+
231
+ u = dup_add(dup_mul(t, e, K), dup_mul(q, g, K), K)
232
+ G = dup_trunc(dup_add(g, u, K), M, K)
233
+ H = dup_trunc(dup_add(h, r, K), M, K)
234
+
235
+ u = dup_add(dup_mul(s, G, K), dup_mul(t, H, K), K)
236
+ b = dup_trunc(dup_sub(u, [K.one], K), M, K)
237
+
238
+ c, d = dup_div(dup_mul(s, b, K), H, K)
239
+
240
+ c = dup_trunc(c, M, K)
241
+ d = dup_trunc(d, M, K)
242
+
243
+ u = dup_add(dup_mul(t, b, K), dup_mul(c, G, K), K)
244
+ S = dup_trunc(dup_sub(s, d, K), M, K)
245
+ T = dup_trunc(dup_sub(t, u, K), M, K)
246
+
247
+ return G, H, S, T
248
+
249
+
250
+ def dup_zz_hensel_lift(p, f, f_list, l, K):
251
+ r"""
252
+ Multifactor Hensel lifting in `Z[x]`.
253
+
254
+ Given a prime `p`, polynomial `f` over `Z[x]` such that `lc(f)`
255
+ is a unit modulo `p`, monic pair-wise coprime polynomials `f_i`
256
+ over `Z[x]` satisfying::
257
+
258
+ f = lc(f) f_1 ... f_r (mod p)
259
+
260
+ and a positive integer `l`, returns a list of monic polynomials
261
+ `F_1,\ F_2,\ \dots,\ F_r` satisfying::
262
+
263
+ f = lc(f) F_1 ... F_r (mod p**l)
264
+
265
+ F_i = f_i (mod p), i = 1..r
266
+
267
+ References
268
+ ==========
269
+
270
+ .. [1] [Gathen99]_
271
+
272
+ """
273
+ r = len(f_list)
274
+ lc = dup_LC(f, K)
275
+
276
+ if r == 1:
277
+ F = dup_mul_ground(f, K.gcdex(lc, p**l)[0], K)
278
+ return [ dup_trunc(F, p**l, K) ]
279
+
280
+ m = p
281
+ k = r // 2
282
+ d = int(_ceil(_log(l, 2)))
283
+
284
+ g = gf_from_int_poly([lc], p)
285
+
286
+ for f_i in f_list[:k]:
287
+ g = gf_mul(g, gf_from_int_poly(f_i, p), p, K)
288
+
289
+ h = gf_from_int_poly(f_list[k], p)
290
+
291
+ for f_i in f_list[k + 1:]:
292
+ h = gf_mul(h, gf_from_int_poly(f_i, p), p, K)
293
+
294
+ s, t, _ = gf_gcdex(g, h, p, K)
295
+
296
+ g = gf_to_int_poly(g, p)
297
+ h = gf_to_int_poly(h, p)
298
+ s = gf_to_int_poly(s, p)
299
+ t = gf_to_int_poly(t, p)
300
+
301
+ for _ in range(1, d + 1):
302
+ (g, h, s, t), m = dup_zz_hensel_step(m, f, g, h, s, t, K), m**2
303
+
304
+ return dup_zz_hensel_lift(p, g, f_list[:k], l, K) \
305
+ + dup_zz_hensel_lift(p, h, f_list[k:], l, K)
306
+
307
+ def _test_pl(fc, q, pl):
308
+ if q > pl // 2:
309
+ q = q - pl
310
+ if not q:
311
+ return True
312
+ return fc % q == 0
313
+
314
+ def dup_zz_zassenhaus(f, K):
315
+ """Factor primitive square-free polynomials in `Z[x]`. """
316
+ n = dup_degree(f)
317
+
318
+ if n == 1:
319
+ return [f]
320
+
321
+ from sympy.ntheory import isprime
322
+
323
+ fc = f[-1]
324
+ A = dup_max_norm(f, K)
325
+ b = dup_LC(f, K)
326
+ B = int(abs(K.sqrt(K(n + 1))*2**n*A*b))
327
+ C = int((n + 1)**(2*n)*A**(2*n - 1))
328
+ gamma = int(_ceil(2*_log(C, 2)))
329
+ bound = int(2*gamma*_log(gamma))
330
+ a = []
331
+ # choose a prime number `p` such that `f` be square free in Z_p
332
+ # if there are many factors in Z_p, choose among a few different `p`
333
+ # the one with fewer factors
334
+ for px in range(3, bound + 1):
335
+ if not isprime(px) or b % px == 0:
336
+ continue
337
+
338
+ px = K.convert(px)
339
+
340
+ F = gf_from_int_poly(f, px)
341
+
342
+ if not gf_sqf_p(F, px, K):
343
+ continue
344
+ fsqfx = gf_factor_sqf(F, px, K)[1]
345
+ a.append((px, fsqfx))
346
+ if len(fsqfx) < 15 or len(a) > 4:
347
+ break
348
+ p, fsqf = min(a, key=lambda x: len(x[1]))
349
+
350
+ l = int(_ceil(_log(2*B + 1, p)))
351
+
352
+ modular = [gf_to_int_poly(ff, p) for ff in fsqf]
353
+
354
+ g = dup_zz_hensel_lift(p, f, modular, l, K)
355
+
356
+ sorted_T = range(len(g))
357
+ T = set(sorted_T)
358
+ factors, s = [], 1
359
+ pl = p**l
360
+
361
+ while 2*s <= len(T):
362
+ for S in subsets(sorted_T, s):
363
+ # lift the constant coefficient of the product `G` of the factors
364
+ # in the subset `S`; if it is does not divide `fc`, `G` does
365
+ # not divide the input polynomial
366
+
367
+ if b == 1:
368
+ q = 1
369
+ for i in S:
370
+ q = q*g[i][-1]
371
+ q = q % pl
372
+ if not _test_pl(fc, q, pl):
373
+ continue
374
+ else:
375
+ G = [b]
376
+ for i in S:
377
+ G = dup_mul(G, g[i], K)
378
+ G = dup_trunc(G, pl, K)
379
+ G = dup_primitive(G, K)[1]
380
+ q = G[-1]
381
+ if q and fc % q != 0:
382
+ continue
383
+
384
+ H = [b]
385
+ S = set(S)
386
+ T_S = T - S
387
+
388
+ if b == 1:
389
+ G = [b]
390
+ for i in S:
391
+ G = dup_mul(G, g[i], K)
392
+ G = dup_trunc(G, pl, K)
393
+
394
+ for i in T_S:
395
+ H = dup_mul(H, g[i], K)
396
+
397
+ H = dup_trunc(H, pl, K)
398
+
399
+ G_norm = dup_l1_norm(G, K)
400
+ H_norm = dup_l1_norm(H, K)
401
+
402
+ if G_norm*H_norm <= B:
403
+ T = T_S
404
+ sorted_T = [i for i in sorted_T if i not in S]
405
+
406
+ G = dup_primitive(G, K)[1]
407
+ f = dup_primitive(H, K)[1]
408
+
409
+ factors.append(G)
410
+ b = dup_LC(f, K)
411
+
412
+ break
413
+ else:
414
+ s += 1
415
+
416
+ return factors + [f]
417
+
418
+
419
+ def dup_zz_irreducible_p(f, K):
420
+ """Test irreducibility using Eisenstein's criterion. """
421
+ lc = dup_LC(f, K)
422
+ tc = dup_TC(f, K)
423
+
424
+ e_fc = dup_content(f[1:], K)
425
+
426
+ if e_fc:
427
+ from sympy.ntheory import factorint
428
+ e_ff = factorint(int(e_fc))
429
+
430
+ for p in e_ff.keys():
431
+ if (lc % p) and (tc % p**2):
432
+ return True
433
+
434
+
435
+ def dup_cyclotomic_p(f, K, irreducible=False):
436
+ """
437
+ Efficiently test if ``f`` is a cyclotomic polynomial.
438
+
439
+ Examples
440
+ ========
441
+
442
+ >>> from sympy.polys import ring, ZZ
443
+ >>> R, x = ring("x", ZZ)
444
+
445
+ >>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1
446
+ >>> R.dup_cyclotomic_p(f)
447
+ False
448
+
449
+ >>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1
450
+ >>> R.dup_cyclotomic_p(g)
451
+ True
452
+
453
+ References
454
+ ==========
455
+
456
+ Bradford, Russell J., and James H. Davenport. "Effective tests for
457
+ cyclotomic polynomials." In International Symposium on Symbolic and
458
+ Algebraic Computation, pp. 244-251. Springer, Berlin, Heidelberg, 1988.
459
+
460
+ """
461
+ if K.is_QQ:
462
+ try:
463
+ K0, K = K, K.get_ring()
464
+ f = dup_convert(f, K0, K)
465
+ except CoercionFailed:
466
+ return False
467
+ elif not K.is_ZZ:
468
+ return False
469
+
470
+ lc = dup_LC(f, K)
471
+ tc = dup_TC(f, K)
472
+
473
+ if lc != 1 or (tc != -1 and tc != 1):
474
+ return False
475
+
476
+ if not irreducible:
477
+ coeff, factors = dup_factor_list(f, K)
478
+
479
+ if coeff != K.one or factors != [(f, 1)]:
480
+ return False
481
+
482
+ n = dup_degree(f)
483
+ g, h = [], []
484
+
485
+ for i in range(n, -1, -2):
486
+ g.insert(0, f[i])
487
+
488
+ for i in range(n - 1, -1, -2):
489
+ h.insert(0, f[i])
490
+
491
+ g = dup_sqr(dup_strip(g), K)
492
+ h = dup_sqr(dup_strip(h), K)
493
+
494
+ F = dup_sub(g, dup_lshift(h, 1, K), K)
495
+
496
+ if K.is_negative(dup_LC(F, K)):
497
+ F = dup_neg(F, K)
498
+
499
+ if F == f:
500
+ return True
501
+
502
+ g = dup_mirror(f, K)
503
+
504
+ if K.is_negative(dup_LC(g, K)):
505
+ g = dup_neg(g, K)
506
+
507
+ if F == g and dup_cyclotomic_p(g, K):
508
+ return True
509
+
510
+ G = dup_sqf_part(F, K)
511
+
512
+ if dup_sqr(G, K) == F and dup_cyclotomic_p(G, K):
513
+ return True
514
+
515
+ return False
516
+
517
+
518
+ def dup_zz_cyclotomic_poly(n, K):
519
+ """Efficiently generate n-th cyclotomic polynomial. """
520
+ from sympy.ntheory import factorint
521
+ h = [K.one, -K.one]
522
+
523
+ for p, k in factorint(n).items():
524
+ h = dup_quo(dup_inflate(h, p, K), h, K)
525
+ h = dup_inflate(h, p**(k - 1), K)
526
+
527
+ return h
528
+
529
+
530
+ def _dup_cyclotomic_decompose(n, K):
531
+ from sympy.ntheory import factorint
532
+
533
+ H = [[K.one, -K.one]]
534
+
535
+ for p, k in factorint(n).items():
536
+ Q = [ dup_quo(dup_inflate(h, p, K), h, K) for h in H ]
537
+ H.extend(Q)
538
+
539
+ for i in range(1, k):
540
+ Q = [ dup_inflate(q, p, K) for q in Q ]
541
+ H.extend(Q)
542
+
543
+ return H
544
+
545
+
546
+ def dup_zz_cyclotomic_factor(f, K):
547
+ """
548
+ Efficiently factor polynomials `x**n - 1` and `x**n + 1` in `Z[x]`.
549
+
550
+ Given a univariate polynomial `f` in `Z[x]` returns a list of factors
551
+ of `f`, provided that `f` is in the form `x**n - 1` or `x**n + 1` for
552
+ `n >= 1`. Otherwise returns None.
553
+
554
+ Factorization is performed using cyclotomic decomposition of `f`,
555
+ which makes this method much faster that any other direct factorization
556
+ approach (e.g. Zassenhaus's).
557
+
558
+ References
559
+ ==========
560
+
561
+ .. [1] [Weisstein09]_
562
+
563
+ """
564
+ lc_f, tc_f = dup_LC(f, K), dup_TC(f, K)
565
+
566
+ if dup_degree(f) <= 0:
567
+ return None
568
+
569
+ if lc_f != 1 or tc_f not in [-1, 1]:
570
+ return None
571
+
572
+ if any(bool(cf) for cf in f[1:-1]):
573
+ return None
574
+
575
+ n = dup_degree(f)
576
+ F = _dup_cyclotomic_decompose(n, K)
577
+
578
+ if not K.is_one(tc_f):
579
+ return F
580
+ else:
581
+ H = []
582
+
583
+ for h in _dup_cyclotomic_decompose(2*n, K):
584
+ if h not in F:
585
+ H.append(h)
586
+
587
+ return H
588
+
589
+
590
+ def dup_zz_factor_sqf(f, K):
591
+ """Factor square-free (non-primitive) polynomials in `Z[x]`. """
592
+ cont, g = dup_primitive(f, K)
593
+
594
+ n = dup_degree(g)
595
+
596
+ if dup_LC(g, K) < 0:
597
+ cont, g = -cont, dup_neg(g, K)
598
+
599
+ if n <= 0:
600
+ return cont, []
601
+ elif n == 1:
602
+ return cont, [g]
603
+
604
+ if query('USE_IRREDUCIBLE_IN_FACTOR'):
605
+ if dup_zz_irreducible_p(g, K):
606
+ return cont, [g]
607
+
608
+ factors = None
609
+
610
+ if query('USE_CYCLOTOMIC_FACTOR'):
611
+ factors = dup_zz_cyclotomic_factor(g, K)
612
+
613
+ if factors is None:
614
+ factors = dup_zz_zassenhaus(g, K)
615
+
616
+ return cont, _sort_factors(factors, multiple=False)
617
+
618
+
619
+ def dup_zz_factor(f, K):
620
+ """
621
+ Factor (non square-free) polynomials in `Z[x]`.
622
+
623
+ Given a univariate polynomial `f` in `Z[x]` computes its complete
624
+ factorization `f_1, ..., f_n` into irreducibles over integers::
625
+
626
+ f = content(f) f_1**k_1 ... f_n**k_n
627
+
628
+ The factorization is computed by reducing the input polynomial
629
+ into a primitive square-free polynomial and factoring it using
630
+ Zassenhaus algorithm. Trial division is used to recover the
631
+ multiplicities of factors.
632
+
633
+ The result is returned as a tuple consisting of::
634
+
635
+ (content(f), [(f_1, k_1), ..., (f_n, k_n))
636
+
637
+ Examples
638
+ ========
639
+
640
+ Consider the polynomial `f = 2*x**4 - 2`::
641
+
642
+ >>> from sympy.polys import ring, ZZ
643
+ >>> R, x = ring("x", ZZ)
644
+
645
+ >>> R.dup_zz_factor(2*x**4 - 2)
646
+ (2, [(x - 1, 1), (x + 1, 1), (x**2 + 1, 1)])
647
+
648
+ In result we got the following factorization::
649
+
650
+ f = 2 (x - 1) (x + 1) (x**2 + 1)
651
+
652
+ Note that this is a complete factorization over integers,
653
+ however over Gaussian integers we can factor the last term.
654
+
655
+ By default, polynomials `x**n - 1` and `x**n + 1` are factored
656
+ using cyclotomic decomposition to speedup computations. To
657
+ disable this behaviour set cyclotomic=False.
658
+
659
+ References
660
+ ==========
661
+
662
+ .. [1] [Gathen99]_
663
+
664
+ """
665
+ cont, g = dup_primitive(f, K)
666
+
667
+ n = dup_degree(g)
668
+
669
+ if dup_LC(g, K) < 0:
670
+ cont, g = -cont, dup_neg(g, K)
671
+
672
+ if n <= 0:
673
+ return cont, []
674
+ elif n == 1:
675
+ return cont, [(g, 1)]
676
+
677
+ if query('USE_IRREDUCIBLE_IN_FACTOR'):
678
+ if dup_zz_irreducible_p(g, K):
679
+ return cont, [(g, 1)]
680
+
681
+ g = dup_sqf_part(g, K)
682
+ H = None
683
+
684
+ if query('USE_CYCLOTOMIC_FACTOR'):
685
+ H = dup_zz_cyclotomic_factor(g, K)
686
+
687
+ if H is None:
688
+ H = dup_zz_zassenhaus(g, K)
689
+
690
+ factors = dup_trial_division(f, H, K)
691
+ return cont, factors
692
+
693
+
694
+ def dmp_zz_wang_non_divisors(E, cs, ct, K):
695
+ """Wang/EEZ: Compute a set of valid divisors. """
696
+ result = [ cs*ct ]
697
+
698
+ for q in E:
699
+ q = abs(q)
700
+
701
+ for r in reversed(result):
702
+ while r != 1:
703
+ r = K.gcd(r, q)
704
+ q = q // r
705
+
706
+ if K.is_one(q):
707
+ return None
708
+
709
+ result.append(q)
710
+
711
+ return result[1:]
712
+
713
+
714
+ def dmp_zz_wang_test_points(f, T, ct, A, u, K):
715
+ """Wang/EEZ: Test evaluation points for suitability. """
716
+ if not dmp_eval_tail(dmp_LC(f, K), A, u - 1, K):
717
+ raise EvaluationFailed('no luck')
718
+
719
+ g = dmp_eval_tail(f, A, u, K)
720
+
721
+ if not dup_sqf_p(g, K):
722
+ raise EvaluationFailed('no luck')
723
+
724
+ c, h = dup_primitive(g, K)
725
+
726
+ if K.is_negative(dup_LC(h, K)):
727
+ c, h = -c, dup_neg(h, K)
728
+
729
+ v = u - 1
730
+
731
+ E = [ dmp_eval_tail(t, A, v, K) for t, _ in T ]
732
+ D = dmp_zz_wang_non_divisors(E, c, ct, K)
733
+
734
+ if D is not None:
735
+ return c, h, E
736
+ else:
737
+ raise EvaluationFailed('no luck')
738
+
739
+
740
+ def dmp_zz_wang_lead_coeffs(f, T, cs, E, H, A, u, K):
741
+ """Wang/EEZ: Compute correct leading coefficients. """
742
+ C, J, v = [], [0]*len(E), u - 1
743
+
744
+ for h in H:
745
+ c = dmp_one(v, K)
746
+ d = dup_LC(h, K)*cs
747
+
748
+ for i in reversed(range(len(E))):
749
+ k, e, (t, _) = 0, E[i], T[i]
750
+
751
+ while not (d % e):
752
+ d, k = d//e, k + 1
753
+
754
+ if k != 0:
755
+ c, J[i] = dmp_mul(c, dmp_pow(t, k, v, K), v, K), 1
756
+
757
+ C.append(c)
758
+
759
+ if not all(J):
760
+ raise ExtraneousFactors # pragma: no cover
761
+
762
+ CC, HH = [], []
763
+
764
+ for c, h in zip(C, H):
765
+ d = dmp_eval_tail(c, A, v, K)
766
+ lc = dup_LC(h, K)
767
+
768
+ if K.is_one(cs):
769
+ cc = lc//d
770
+ else:
771
+ g = K.gcd(lc, d)
772
+ d, cc = d//g, lc//g
773
+ h, cs = dup_mul_ground(h, d, K), cs//d
774
+
775
+ c = dmp_mul_ground(c, cc, v, K)
776
+
777
+ CC.append(c)
778
+ HH.append(h)
779
+
780
+ if K.is_one(cs):
781
+ return f, HH, CC
782
+
783
+ CCC, HHH = [], []
784
+
785
+ for c, h in zip(CC, HH):
786
+ CCC.append(dmp_mul_ground(c, cs, v, K))
787
+ HHH.append(dmp_mul_ground(h, cs, 0, K))
788
+
789
+ f = dmp_mul_ground(f, cs**(len(H) - 1), u, K)
790
+
791
+ return f, HHH, CCC
792
+
793
+
794
+ def dup_zz_diophantine(F, m, p, K):
795
+ """Wang/EEZ: Solve univariate Diophantine equations. """
796
+ if len(F) == 2:
797
+ a, b = F
798
+
799
+ f = gf_from_int_poly(a, p)
800
+ g = gf_from_int_poly(b, p)
801
+
802
+ s, t, G = gf_gcdex(g, f, p, K)
803
+
804
+ s = gf_lshift(s, m, K)
805
+ t = gf_lshift(t, m, K)
806
+
807
+ q, s = gf_div(s, f, p, K)
808
+
809
+ t = gf_add_mul(t, q, g, p, K)
810
+
811
+ s = gf_to_int_poly(s, p)
812
+ t = gf_to_int_poly(t, p)
813
+
814
+ result = [s, t]
815
+ else:
816
+ G = [F[-1]]
817
+
818
+ for f in reversed(F[1:-1]):
819
+ G.insert(0, dup_mul(f, G[0], K))
820
+
821
+ S, T = [], [[1]]
822
+
823
+ for f, g in zip(F, G):
824
+ t, s = dmp_zz_diophantine([g, f], T[-1], [], 0, p, 1, K)
825
+ T.append(t)
826
+ S.append(s)
827
+
828
+ result, S = [], S + [T[-1]]
829
+
830
+ for s, f in zip(S, F):
831
+ s = gf_from_int_poly(s, p)
832
+ f = gf_from_int_poly(f, p)
833
+
834
+ r = gf_rem(gf_lshift(s, m, K), f, p, K)
835
+ s = gf_to_int_poly(r, p)
836
+
837
+ result.append(s)
838
+
839
+ return result
840
+
841
+
842
+ def dmp_zz_diophantine(F, c, A, d, p, u, K):
843
+ """Wang/EEZ: Solve multivariate Diophantine equations. """
844
+ if not A:
845
+ S = [ [] for _ in F ]
846
+ n = dup_degree(c)
847
+
848
+ for i, coeff in enumerate(c):
849
+ if not coeff:
850
+ continue
851
+
852
+ T = dup_zz_diophantine(F, n - i, p, K)
853
+
854
+ for j, (s, t) in enumerate(zip(S, T)):
855
+ t = dup_mul_ground(t, coeff, K)
856
+ S[j] = dup_trunc(dup_add(s, t, K), p, K)
857
+ else:
858
+ n = len(A)
859
+ e = dmp_expand(F, u, K)
860
+
861
+ a, A = A[-1], A[:-1]
862
+ B, G = [], []
863
+
864
+ for f in F:
865
+ B.append(dmp_quo(e, f, u, K))
866
+ G.append(dmp_eval_in(f, a, n, u, K))
867
+
868
+ C = dmp_eval_in(c, a, n, u, K)
869
+
870
+ v = u - 1
871
+
872
+ S = dmp_zz_diophantine(G, C, A, d, p, v, K)
873
+ S = [ dmp_raise(s, 1, v, K) for s in S ]
874
+
875
+ for s, b in zip(S, B):
876
+ c = dmp_sub_mul(c, s, b, u, K)
877
+
878
+ c = dmp_ground_trunc(c, p, u, K)
879
+
880
+ m = dmp_nest([K.one, -a], n, K)
881
+ M = dmp_one(n, K)
882
+
883
+ for k in K.map(range(0, d)):
884
+ if dmp_zero_p(c, u):
885
+ break
886
+
887
+ M = dmp_mul(M, m, u, K)
888
+ C = dmp_diff_eval_in(c, k + 1, a, n, u, K)
889
+
890
+ if not dmp_zero_p(C, v):
891
+ C = dmp_quo_ground(C, K.factorial(k + 1), v, K)
892
+ T = dmp_zz_diophantine(G, C, A, d, p, v, K)
893
+
894
+ for i, t in enumerate(T):
895
+ T[i] = dmp_mul(dmp_raise(t, 1, v, K), M, u, K)
896
+
897
+ for i, (s, t) in enumerate(zip(S, T)):
898
+ S[i] = dmp_add(s, t, u, K)
899
+
900
+ for t, b in zip(T, B):
901
+ c = dmp_sub_mul(c, t, b, u, K)
902
+
903
+ c = dmp_ground_trunc(c, p, u, K)
904
+
905
+ S = [ dmp_ground_trunc(s, p, u, K) for s in S ]
906
+
907
+ return S
908
+
909
+
910
+ def dmp_zz_wang_hensel_lifting(f, H, LC, A, p, u, K):
911
+ """Wang/EEZ: Parallel Hensel lifting algorithm. """
912
+ S, n, v = [f], len(A), u - 1
913
+
914
+ H = list(H)
915
+
916
+ for i, a in enumerate(reversed(A[1:])):
917
+ s = dmp_eval_in(S[0], a, n - i, u - i, K)
918
+ S.insert(0, dmp_ground_trunc(s, p, v - i, K))
919
+
920
+ d = max(dmp_degree_list(f, u)[1:])
921
+
922
+ for j, s, a in zip(range(2, n + 2), S, A):
923
+ G, w = list(H), j - 1
924
+
925
+ I, J = A[:j - 2], A[j - 1:]
926
+
927
+ for i, (h, lc) in enumerate(zip(H, LC)):
928
+ lc = dmp_ground_trunc(dmp_eval_tail(lc, J, v, K), p, w - 1, K)
929
+ H[i] = [lc] + dmp_raise(h[1:], 1, w - 1, K)
930
+
931
+ m = dmp_nest([K.one, -a], w, K)
932
+ M = dmp_one(w, K)
933
+
934
+ c = dmp_sub(s, dmp_expand(H, w, K), w, K)
935
+
936
+ dj = dmp_degree_in(s, w, w)
937
+
938
+ for k in K.map(range(0, dj)):
939
+ if dmp_zero_p(c, w):
940
+ break
941
+
942
+ M = dmp_mul(M, m, w, K)
943
+ C = dmp_diff_eval_in(c, k + 1, a, w, w, K)
944
+
945
+ if not dmp_zero_p(C, w - 1):
946
+ C = dmp_quo_ground(C, K.factorial(k + 1), w - 1, K)
947
+ T = dmp_zz_diophantine(G, C, I, d, p, w - 1, K)
948
+
949
+ for i, (h, t) in enumerate(zip(H, T)):
950
+ h = dmp_add_mul(h, dmp_raise(t, 1, w - 1, K), M, w, K)
951
+ H[i] = dmp_ground_trunc(h, p, w, K)
952
+
953
+ h = dmp_sub(s, dmp_expand(H, w, K), w, K)
954
+ c = dmp_ground_trunc(h, p, w, K)
955
+
956
+ if dmp_expand(H, u, K) != f:
957
+ raise ExtraneousFactors # pragma: no cover
958
+ else:
959
+ return H
960
+
961
+
962
+ def dmp_zz_wang(f, u, K, mod=None, seed=None):
963
+ r"""
964
+ Factor primitive square-free polynomials in `Z[X]`.
965
+
966
+ Given a multivariate polynomial `f` in `Z[x_1,...,x_n]`, which is
967
+ primitive and square-free in `x_1`, computes factorization of `f` into
968
+ irreducibles over integers.
969
+
970
+ The procedure is based on Wang's Enhanced Extended Zassenhaus
971
+ algorithm. The algorithm works by viewing `f` as a univariate polynomial
972
+ in `Z[x_2,...,x_n][x_1]`, for which an evaluation mapping is computed::
973
+
974
+ x_2 -> a_2, ..., x_n -> a_n
975
+
976
+ where `a_i`, for `i = 2, \dots, n`, are carefully chosen integers. The
977
+ mapping is used to transform `f` into a univariate polynomial in `Z[x_1]`,
978
+ which can be factored efficiently using Zassenhaus algorithm. The last
979
+ step is to lift univariate factors to obtain true multivariate
980
+ factors. For this purpose a parallel Hensel lifting procedure is used.
981
+
982
+ The parameter ``seed`` is passed to _randint and can be used to seed randint
983
+ (when an integer) or (for testing purposes) can be a sequence of numbers.
984
+
985
+ References
986
+ ==========
987
+
988
+ .. [1] [Wang78]_
989
+ .. [2] [Geddes92]_
990
+
991
+ """
992
+ from sympy.ntheory import nextprime
993
+
994
+ randint = _randint(seed)
995
+
996
+ ct, T = dmp_zz_factor(dmp_LC(f, K), u - 1, K)
997
+
998
+ b = dmp_zz_mignotte_bound(f, u, K)
999
+ p = K(nextprime(b))
1000
+
1001
+ if mod is None:
1002
+ if u == 1:
1003
+ mod = 2
1004
+ else:
1005
+ mod = 1
1006
+
1007
+ history, configs, A, r = set(), [], [K.zero]*u, None
1008
+
1009
+ try:
1010
+ cs, s, E = dmp_zz_wang_test_points(f, T, ct, A, u, K)
1011
+
1012
+ _, H = dup_zz_factor_sqf(s, K)
1013
+
1014
+ r = len(H)
1015
+
1016
+ if r == 1:
1017
+ return [f]
1018
+
1019
+ configs = [(s, cs, E, H, A)]
1020
+ except EvaluationFailed:
1021
+ pass
1022
+
1023
+ eez_num_configs = query('EEZ_NUMBER_OF_CONFIGS')
1024
+ eez_num_tries = query('EEZ_NUMBER_OF_TRIES')
1025
+ eez_mod_step = query('EEZ_MODULUS_STEP')
1026
+
1027
+ while len(configs) < eez_num_configs:
1028
+ for _ in range(eez_num_tries):
1029
+ A = [ K(randint(-mod, mod)) for _ in range(u) ]
1030
+
1031
+ if tuple(A) not in history:
1032
+ history.add(tuple(A))
1033
+ else:
1034
+ continue
1035
+
1036
+ try:
1037
+ cs, s, E = dmp_zz_wang_test_points(f, T, ct, A, u, K)
1038
+ except EvaluationFailed:
1039
+ continue
1040
+
1041
+ _, H = dup_zz_factor_sqf(s, K)
1042
+
1043
+ rr = len(H)
1044
+
1045
+ if r is not None:
1046
+ if rr != r: # pragma: no cover
1047
+ if rr < r:
1048
+ configs, r = [], rr
1049
+ else:
1050
+ continue
1051
+ else:
1052
+ r = rr
1053
+
1054
+ if r == 1:
1055
+ return [f]
1056
+
1057
+ configs.append((s, cs, E, H, A))
1058
+
1059
+ if len(configs) == eez_num_configs:
1060
+ break
1061
+ else:
1062
+ mod += eez_mod_step
1063
+
1064
+ s_norm, s_arg, i = None, 0, 0
1065
+
1066
+ for s, _, _, _, _ in configs:
1067
+ _s_norm = dup_max_norm(s, K)
1068
+
1069
+ if s_norm is not None:
1070
+ if _s_norm < s_norm:
1071
+ s_norm = _s_norm
1072
+ s_arg = i
1073
+ else:
1074
+ s_norm = _s_norm
1075
+
1076
+ i += 1
1077
+
1078
+ _, cs, E, H, A = configs[s_arg]
1079
+ orig_f = f
1080
+
1081
+ try:
1082
+ f, H, LC = dmp_zz_wang_lead_coeffs(f, T, cs, E, H, A, u, K)
1083
+ factors = dmp_zz_wang_hensel_lifting(f, H, LC, A, p, u, K)
1084
+ except ExtraneousFactors: # pragma: no cover
1085
+ if query('EEZ_RESTART_IF_NEEDED'):
1086
+ return dmp_zz_wang(orig_f, u, K, mod + 1)
1087
+ else:
1088
+ raise ExtraneousFactors(
1089
+ "we need to restart algorithm with better parameters")
1090
+
1091
+ result = []
1092
+
1093
+ for f in factors:
1094
+ _, f = dmp_ground_primitive(f, u, K)
1095
+
1096
+ if K.is_negative(dmp_ground_LC(f, u, K)):
1097
+ f = dmp_neg(f, u, K)
1098
+
1099
+ result.append(f)
1100
+
1101
+ return result
1102
+
1103
+
1104
+ def dmp_zz_factor(f, u, K):
1105
+ r"""
1106
+ Factor (non square-free) polynomials in `Z[X]`.
1107
+
1108
+ Given a multivariate polynomial `f` in `Z[x]` computes its complete
1109
+ factorization `f_1, \dots, f_n` into irreducibles over integers::
1110
+
1111
+ f = content(f) f_1**k_1 ... f_n**k_n
1112
+
1113
+ The factorization is computed by reducing the input polynomial
1114
+ into a primitive square-free polynomial and factoring it using
1115
+ Enhanced Extended Zassenhaus (EEZ) algorithm. Trial division
1116
+ is used to recover the multiplicities of factors.
1117
+
1118
+ The result is returned as a tuple consisting of::
1119
+
1120
+ (content(f), [(f_1, k_1), ..., (f_n, k_n))
1121
+
1122
+ Consider polynomial `f = 2*(x**2 - y**2)`::
1123
+
1124
+ >>> from sympy.polys import ring, ZZ
1125
+ >>> R, x,y = ring("x,y", ZZ)
1126
+
1127
+ >>> R.dmp_zz_factor(2*x**2 - 2*y**2)
1128
+ (2, [(x - y, 1), (x + y, 1)])
1129
+
1130
+ In result we got the following factorization::
1131
+
1132
+ f = 2 (x - y) (x + y)
1133
+
1134
+ References
1135
+ ==========
1136
+
1137
+ .. [1] [Gathen99]_
1138
+
1139
+ """
1140
+ if not u:
1141
+ return dup_zz_factor(f, K)
1142
+
1143
+ if dmp_zero_p(f, u):
1144
+ return K.zero, []
1145
+
1146
+ cont, g = dmp_ground_primitive(f, u, K)
1147
+
1148
+ if dmp_ground_LC(g, u, K) < 0:
1149
+ cont, g = -cont, dmp_neg(g, u, K)
1150
+
1151
+ if all(d <= 0 for d in dmp_degree_list(g, u)):
1152
+ return cont, []
1153
+
1154
+ G, g = dmp_primitive(g, u, K)
1155
+
1156
+ factors = []
1157
+
1158
+ if dmp_degree(g, u) > 0:
1159
+ g = dmp_sqf_part(g, u, K)
1160
+ H = dmp_zz_wang(g, u, K)
1161
+ factors = dmp_trial_division(f, H, u, K)
1162
+
1163
+ for g, k in dmp_zz_factor(G, u - 1, K)[1]:
1164
+ factors.insert(0, ([g], k))
1165
+
1166
+ return cont, _sort_factors(factors)
1167
+
1168
+
1169
+ def dup_qq_i_factor(f, K0):
1170
+ """Factor univariate polynomials into irreducibles in `QQ_I[x]`. """
1171
+ # Factor in QQ<I>
1172
+ K1 = K0.as_AlgebraicField()
1173
+ f = dup_convert(f, K0, K1)
1174
+ coeff, factors = dup_factor_list(f, K1)
1175
+ factors = [(dup_convert(fac, K1, K0), i) for fac, i in factors]
1176
+ coeff = K0.convert(coeff, K1)
1177
+ return coeff, factors
1178
+
1179
+
1180
+ def dup_zz_i_factor(f, K0):
1181
+ """Factor univariate polynomials into irreducibles in `ZZ_I[x]`. """
1182
+ # First factor in QQ_I
1183
+ K1 = K0.get_field()
1184
+ f = dup_convert(f, K0, K1)
1185
+ coeff, factors = dup_qq_i_factor(f, K1)
1186
+
1187
+ new_factors = []
1188
+ for fac, i in factors:
1189
+ # Extract content
1190
+ fac_denom, fac_num = dup_clear_denoms(fac, K1)
1191
+ fac_num_ZZ_I = dup_convert(fac_num, K1, K0)
1192
+ content, fac_prim = dmp_ground_primitive(fac_num_ZZ_I, 0, K1)
1193
+
1194
+ coeff = (coeff * content ** i) // fac_denom ** i
1195
+ new_factors.append((fac_prim, i))
1196
+
1197
+ factors = new_factors
1198
+ coeff = K0.convert(coeff, K1)
1199
+ return coeff, factors
1200
+
1201
+
1202
+ def dmp_qq_i_factor(f, u, K0):
1203
+ """Factor multivariate polynomials into irreducibles in `QQ_I[X]`. """
1204
+ # Factor in QQ<I>
1205
+ K1 = K0.as_AlgebraicField()
1206
+ f = dmp_convert(f, u, K0, K1)
1207
+ coeff, factors = dmp_factor_list(f, u, K1)
1208
+ factors = [(dmp_convert(fac, u, K1, K0), i) for fac, i in factors]
1209
+ coeff = K0.convert(coeff, K1)
1210
+ return coeff, factors
1211
+
1212
+
1213
+ def dmp_zz_i_factor(f, u, K0):
1214
+ """Factor multivariate polynomials into irreducibles in `ZZ_I[X]`. """
1215
+ # First factor in QQ_I
1216
+ K1 = K0.get_field()
1217
+ f = dmp_convert(f, u, K0, K1)
1218
+ coeff, factors = dmp_qq_i_factor(f, u, K1)
1219
+
1220
+ new_factors = []
1221
+ for fac, i in factors:
1222
+ # Extract content
1223
+ fac_denom, fac_num = dmp_clear_denoms(fac, u, K1)
1224
+ fac_num_ZZ_I = dmp_convert(fac_num, u, K1, K0)
1225
+ content, fac_prim = dmp_ground_primitive(fac_num_ZZ_I, u, K1)
1226
+
1227
+ coeff = (coeff * content ** i) // fac_denom ** i
1228
+ new_factors.append((fac_prim, i))
1229
+
1230
+ factors = new_factors
1231
+ coeff = K0.convert(coeff, K1)
1232
+ return coeff, factors
1233
+
1234
+
1235
+ def dup_ext_factor(f, K):
1236
+ """Factor univariate polynomials over algebraic number fields. """
1237
+ n, lc = dup_degree(f), dup_LC(f, K)
1238
+
1239
+ f = dup_monic(f, K)
1240
+
1241
+ if n <= 0:
1242
+ return lc, []
1243
+ if n == 1:
1244
+ return lc, [(f, 1)]
1245
+
1246
+ f, F = dup_sqf_part(f, K), f
1247
+ s, g, r = dup_sqf_norm(f, K)
1248
+
1249
+ factors = dup_factor_list_include(r, K.dom)
1250
+
1251
+ if len(factors) == 1:
1252
+ return lc, [(f, n//dup_degree(f))]
1253
+
1254
+ H = s*K.unit
1255
+
1256
+ for i, (factor, _) in enumerate(factors):
1257
+ h = dup_convert(factor, K.dom, K)
1258
+ h, _, g = dup_inner_gcd(h, g, K)
1259
+ h = dup_shift(h, H, K)
1260
+ factors[i] = h
1261
+
1262
+ factors = dup_trial_division(F, factors, K)
1263
+ return lc, factors
1264
+
1265
+
1266
+ def dmp_ext_factor(f, u, K):
1267
+ """Factor multivariate polynomials over algebraic number fields. """
1268
+ if not u:
1269
+ return dup_ext_factor(f, K)
1270
+
1271
+ lc = dmp_ground_LC(f, u, K)
1272
+ f = dmp_ground_monic(f, u, K)
1273
+
1274
+ if all(d <= 0 for d in dmp_degree_list(f, u)):
1275
+ return lc, []
1276
+
1277
+ f, F = dmp_sqf_part(f, u, K), f
1278
+ s, g, r = dmp_sqf_norm(f, u, K)
1279
+
1280
+ factors = dmp_factor_list_include(r, u, K.dom)
1281
+
1282
+ if len(factors) == 1:
1283
+ factors = [f]
1284
+ else:
1285
+ H = dmp_raise([K.one, s*K.unit], u, 0, K)
1286
+
1287
+ for i, (factor, _) in enumerate(factors):
1288
+ h = dmp_convert(factor, u, K.dom, K)
1289
+ h, _, g = dmp_inner_gcd(h, g, u, K)
1290
+ h = dmp_compose(h, H, u, K)
1291
+ factors[i] = h
1292
+
1293
+ return lc, dmp_trial_division(F, factors, u, K)
1294
+
1295
+
1296
+ def dup_gf_factor(f, K):
1297
+ """Factor univariate polynomials over finite fields. """
1298
+ f = dup_convert(f, K, K.dom)
1299
+
1300
+ coeff, factors = gf_factor(f, K.mod, K.dom)
1301
+
1302
+ for i, (f, k) in enumerate(factors):
1303
+ factors[i] = (dup_convert(f, K.dom, K), k)
1304
+
1305
+ return K.convert(coeff, K.dom), factors
1306
+
1307
+
1308
+ def dmp_gf_factor(f, u, K):
1309
+ """Factor multivariate polynomials over finite fields. """
1310
+ raise NotImplementedError('multivariate polynomials over finite fields')
1311
+
1312
+
1313
+ def dup_factor_list(f, K0):
1314
+ """Factor univariate polynomials into irreducibles in `K[x]`. """
1315
+ j, f = dup_terms_gcd(f, K0)
1316
+ cont, f = dup_primitive(f, K0)
1317
+
1318
+ if K0.is_FiniteField:
1319
+ coeff, factors = dup_gf_factor(f, K0)
1320
+ elif K0.is_Algebraic:
1321
+ coeff, factors = dup_ext_factor(f, K0)
1322
+ elif K0.is_GaussianRing:
1323
+ coeff, factors = dup_zz_i_factor(f, K0)
1324
+ elif K0.is_GaussianField:
1325
+ coeff, factors = dup_qq_i_factor(f, K0)
1326
+ else:
1327
+ if not K0.is_Exact:
1328
+ K0_inexact, K0 = K0, K0.get_exact()
1329
+ f = dup_convert(f, K0_inexact, K0)
1330
+ else:
1331
+ K0_inexact = None
1332
+
1333
+ if K0.is_Field:
1334
+ K = K0.get_ring()
1335
+
1336
+ denom, f = dup_clear_denoms(f, K0, K)
1337
+ f = dup_convert(f, K0, K)
1338
+ else:
1339
+ K = K0
1340
+
1341
+ if K.is_ZZ:
1342
+ coeff, factors = dup_zz_factor(f, K)
1343
+ elif K.is_Poly:
1344
+ f, u = dmp_inject(f, 0, K)
1345
+
1346
+ coeff, factors = dmp_factor_list(f, u, K.dom)
1347
+
1348
+ for i, (f, k) in enumerate(factors):
1349
+ factors[i] = (dmp_eject(f, u, K), k)
1350
+
1351
+ coeff = K.convert(coeff, K.dom)
1352
+ else: # pragma: no cover
1353
+ raise DomainError('factorization not supported over %s' % K0)
1354
+
1355
+ if K0.is_Field:
1356
+ for i, (f, k) in enumerate(factors):
1357
+ factors[i] = (dup_convert(f, K, K0), k)
1358
+
1359
+ coeff = K0.convert(coeff, K)
1360
+ coeff = K0.quo(coeff, denom)
1361
+
1362
+ if K0_inexact:
1363
+ for i, (f, k) in enumerate(factors):
1364
+ max_norm = dup_max_norm(f, K0)
1365
+ f = dup_quo_ground(f, max_norm, K0)
1366
+ f = dup_convert(f, K0, K0_inexact)
1367
+ factors[i] = (f, k)
1368
+ coeff = K0.mul(coeff, K0.pow(max_norm, k))
1369
+
1370
+ coeff = K0_inexact.convert(coeff, K0)
1371
+ K0 = K0_inexact
1372
+
1373
+ if j:
1374
+ factors.insert(0, ([K0.one, K0.zero], j))
1375
+
1376
+ return coeff*cont, _sort_factors(factors)
1377
+
1378
+
1379
+ def dup_factor_list_include(f, K):
1380
+ """Factor univariate polynomials into irreducibles in `K[x]`. """
1381
+ coeff, factors = dup_factor_list(f, K)
1382
+
1383
+ if not factors:
1384
+ return [(dup_strip([coeff]), 1)]
1385
+ else:
1386
+ g = dup_mul_ground(factors[0][0], coeff, K)
1387
+ return [(g, factors[0][1])] + factors[1:]
1388
+
1389
+
1390
+ def dmp_factor_list(f, u, K0):
1391
+ """Factor multivariate polynomials into irreducibles in `K[X]`. """
1392
+ if not u:
1393
+ return dup_factor_list(f, K0)
1394
+
1395
+ J, f = dmp_terms_gcd(f, u, K0)
1396
+ cont, f = dmp_ground_primitive(f, u, K0)
1397
+
1398
+ if K0.is_FiniteField: # pragma: no cover
1399
+ coeff, factors = dmp_gf_factor(f, u, K0)
1400
+ elif K0.is_Algebraic:
1401
+ coeff, factors = dmp_ext_factor(f, u, K0)
1402
+ elif K0.is_GaussianRing:
1403
+ coeff, factors = dmp_zz_i_factor(f, u, K0)
1404
+ elif K0.is_GaussianField:
1405
+ coeff, factors = dmp_qq_i_factor(f, u, K0)
1406
+ else:
1407
+ if not K0.is_Exact:
1408
+ K0_inexact, K0 = K0, K0.get_exact()
1409
+ f = dmp_convert(f, u, K0_inexact, K0)
1410
+ else:
1411
+ K0_inexact = None
1412
+
1413
+ if K0.is_Field:
1414
+ K = K0.get_ring()
1415
+
1416
+ denom, f = dmp_clear_denoms(f, u, K0, K)
1417
+ f = dmp_convert(f, u, K0, K)
1418
+ else:
1419
+ K = K0
1420
+
1421
+ if K.is_ZZ:
1422
+ levels, f, v = dmp_exclude(f, u, K)
1423
+ coeff, factors = dmp_zz_factor(f, v, K)
1424
+
1425
+ for i, (f, k) in enumerate(factors):
1426
+ factors[i] = (dmp_include(f, levels, v, K), k)
1427
+ elif K.is_Poly:
1428
+ f, v = dmp_inject(f, u, K)
1429
+
1430
+ coeff, factors = dmp_factor_list(f, v, K.dom)
1431
+
1432
+ for i, (f, k) in enumerate(factors):
1433
+ factors[i] = (dmp_eject(f, v, K), k)
1434
+
1435
+ coeff = K.convert(coeff, K.dom)
1436
+ else: # pragma: no cover
1437
+ raise DomainError('factorization not supported over %s' % K0)
1438
+
1439
+ if K0.is_Field:
1440
+ for i, (f, k) in enumerate(factors):
1441
+ factors[i] = (dmp_convert(f, u, K, K0), k)
1442
+
1443
+ coeff = K0.convert(coeff, K)
1444
+ coeff = K0.quo(coeff, denom)
1445
+
1446
+ if K0_inexact:
1447
+ for i, (f, k) in enumerate(factors):
1448
+ max_norm = dmp_max_norm(f, u, K0)
1449
+ f = dmp_quo_ground(f, max_norm, u, K0)
1450
+ f = dmp_convert(f, u, K0, K0_inexact)
1451
+ factors[i] = (f, k)
1452
+ coeff = K0.mul(coeff, K0.pow(max_norm, k))
1453
+
1454
+ coeff = K0_inexact.convert(coeff, K0)
1455
+ K0 = K0_inexact
1456
+
1457
+ for i, j in enumerate(reversed(J)):
1458
+ if not j:
1459
+ continue
1460
+
1461
+ term = {(0,)*(u - i) + (1,) + (0,)*i: K0.one}
1462
+ factors.insert(0, (dmp_from_dict(term, u, K0), j))
1463
+
1464
+ return coeff*cont, _sort_factors(factors)
1465
+
1466
+
1467
+ def dmp_factor_list_include(f, u, K):
1468
+ """Factor multivariate polynomials into irreducibles in `K[X]`. """
1469
+ if not u:
1470
+ return dup_factor_list_include(f, K)
1471
+
1472
+ coeff, factors = dmp_factor_list(f, u, K)
1473
+
1474
+ if not factors:
1475
+ return [(dmp_ground(coeff, u), 1)]
1476
+ else:
1477
+ g = dmp_mul_ground(factors[0][0], coeff, u, K)
1478
+ return [(g, factors[0][1])] + factors[1:]
1479
+
1480
+
1481
+ def dup_irreducible_p(f, K):
1482
+ """
1483
+ Returns ``True`` if a univariate polynomial ``f`` has no factors
1484
+ over its domain.
1485
+ """
1486
+ return dmp_irreducible_p(f, 0, K)
1487
+
1488
+
1489
+ def dmp_irreducible_p(f, u, K):
1490
+ """
1491
+ Returns ``True`` if a multivariate polynomial ``f`` has no factors
1492
+ over its domain.
1493
+ """
1494
+ _, factors = dmp_factor_list(f, u, K)
1495
+
1496
+ if not factors:
1497
+ return True
1498
+ elif len(factors) > 1:
1499
+ return False
1500
+ else:
1501
+ _, k = factors[0]
1502
+ return k == 1
shared/package-files/02/020f6b521a01c9253a6dadf014b7ae67258c267cfd56401ff53404cd61b88545/_dataset.pxd ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: language_level = 3
19
+
20
+ """Dataset is currently unstable. APIs subject to change without notice."""
21
+
22
+ from pyarrow.includes.common cimport *
23
+ from pyarrow.includes.libarrow_dataset cimport *
24
+ from pyarrow.lib cimport *
25
+ from pyarrow._fs cimport FileSystem, FileInfo
26
+
27
+
28
+ cdef CFileSource _make_file_source(object file, FileSystem filesystem=*, object file_size=*)
29
+
30
+ cdef class DatasetFactory(_Weakrefable):
31
+
32
+ cdef:
33
+ SharedPtrNoGIL[CDatasetFactory] wrapped
34
+ CDatasetFactory* factory
35
+
36
+ cdef init(self, const shared_ptr[CDatasetFactory]& sp)
37
+
38
+ @staticmethod
39
+ cdef wrap(const shared_ptr[CDatasetFactory]& sp)
40
+
41
+ cdef inline shared_ptr[CDatasetFactory] unwrap(self) nogil
42
+
43
+
44
+ cdef class Dataset(_Weakrefable):
45
+
46
+ cdef:
47
+ SharedPtrNoGIL[CDataset] wrapped
48
+ CDataset* dataset
49
+ public dict _scan_options
50
+
51
+ cdef void init(self, const shared_ptr[CDataset]& sp)
52
+
53
+ @staticmethod
54
+ cdef wrap(const shared_ptr[CDataset]& sp)
55
+
56
+ cdef shared_ptr[CDataset] unwrap(self) nogil
57
+
58
+
59
+ cdef class Scanner(_Weakrefable):
60
+ cdef:
61
+ SharedPtrNoGIL[CScanner] wrapped
62
+ CScanner* scanner
63
+
64
+ cdef void init(self, const shared_ptr[CScanner]& sp)
65
+
66
+ @staticmethod
67
+ cdef wrap(const shared_ptr[CScanner]& sp)
68
+
69
+ cdef shared_ptr[CScanner] unwrap(self)
70
+
71
+ @staticmethod
72
+ cdef shared_ptr[CScanOptions] _make_scan_options(Dataset dataset, dict py_scanoptions) except *
73
+
74
+
75
+ cdef class FragmentScanOptions(_Weakrefable):
76
+
77
+ cdef:
78
+ shared_ptr[CFragmentScanOptions] wrapped
79
+
80
+ cdef void init(self, const shared_ptr[CFragmentScanOptions]& sp)
81
+
82
+ @staticmethod
83
+ cdef wrap(const shared_ptr[CFragmentScanOptions]& sp)
84
+
85
+
86
+ cdef class FileFormat(_Weakrefable):
87
+
88
+ cdef:
89
+ shared_ptr[CFileFormat] wrapped
90
+ CFileFormat* format
91
+
92
+ cdef void init(self, const shared_ptr[CFileFormat]& sp)
93
+
94
+ @staticmethod
95
+ cdef wrap(const shared_ptr[CFileFormat]& sp)
96
+
97
+ cdef inline shared_ptr[CFileFormat] unwrap(self)
98
+
99
+ cdef _set_default_fragment_scan_options(self, FragmentScanOptions options)
100
+
101
+ # Return a WrittenFile after a file was written.
102
+ # May be overridden by subclasses, e.g. to add metadata.
103
+ cdef WrittenFile _finish_write(self, path, base_dir,
104
+ CFileWriter* file_writer)
105
+
106
+
107
+ cdef class FileWriteOptions(_Weakrefable):
108
+
109
+ cdef:
110
+ shared_ptr[CFileWriteOptions] wrapped
111
+ CFileWriteOptions* c_options
112
+
113
+ cdef void init(self, const shared_ptr[CFileWriteOptions]& sp)
114
+
115
+ @staticmethod
116
+ cdef wrap(const shared_ptr[CFileWriteOptions]& sp)
117
+
118
+ cdef inline shared_ptr[CFileWriteOptions] unwrap(self)
119
+
120
+
121
+ cdef class Fragment(_Weakrefable):
122
+
123
+ cdef:
124
+ SharedPtrNoGIL[CFragment] wrapped
125
+ CFragment* fragment
126
+
127
+ cdef void init(self, const shared_ptr[CFragment]& sp)
128
+
129
+ @staticmethod
130
+ cdef wrap(const shared_ptr[CFragment]& sp)
131
+
132
+ cdef inline shared_ptr[CFragment] unwrap(self)
133
+
134
+
135
+ cdef class FileFragment(Fragment):
136
+
137
+ cdef:
138
+ CFileFragment* file_fragment
139
+
140
+ cdef void init(self, const shared_ptr[CFragment]& sp)
141
+
142
+
143
+ cdef class Partitioning(_Weakrefable):
144
+
145
+ cdef:
146
+ shared_ptr[CPartitioning] wrapped
147
+ CPartitioning* partitioning
148
+
149
+ cdef init(self, const shared_ptr[CPartitioning]& sp)
150
+
151
+ @staticmethod
152
+ cdef wrap(const shared_ptr[CPartitioning]& sp)
153
+
154
+ cdef inline shared_ptr[CPartitioning] unwrap(self)
155
+
156
+
157
+ cdef class PartitioningFactory(_Weakrefable):
158
+
159
+ cdef:
160
+ shared_ptr[CPartitioningFactory] wrapped
161
+ CPartitioningFactory* factory
162
+ object constructor
163
+ object options
164
+
165
+ cdef init(self, const shared_ptr[CPartitioningFactory]& sp)
166
+
167
+ @staticmethod
168
+ cdef wrap(const shared_ptr[CPartitioningFactory]& sp,
169
+ object constructor, object options)
170
+
171
+ cdef inline shared_ptr[CPartitioningFactory] unwrap(self)
172
+
173
+
174
+ cdef class WrittenFile(_Weakrefable):
175
+
176
+ # The full path to the created file
177
+ cdef public str path
178
+ # Optional Parquet metadata
179
+ # This metadata will have the file path attribute set to the path of
180
+ # the written file.
181
+ cdef public object metadata
182
+ # The size of the file in bytes
183
+ cdef public int64_t size
shared/package-files/02/02108ef43132cac13e3fe40917daf252d275821538ff498e461009e7da6839b5/shape_base.py ADDED
@@ -0,0 +1,1274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+
3
+ import numpy.core.numeric as _nx
4
+ from numpy.core.numeric import asarray, zeros, array, asanyarray
5
+ from numpy.core.fromnumeric import reshape, transpose
6
+ from numpy.core.multiarray import normalize_axis_index
7
+ from numpy.core import overrides
8
+ from numpy.core import vstack, atleast_3d
9
+ from numpy.core.numeric import normalize_axis_tuple
10
+ from numpy.core.shape_base import _arrays_for_stack_dispatcher
11
+ from numpy.lib.index_tricks import ndindex
12
+ from numpy.matrixlib.defmatrix import matrix # this raises all the right alarm bells
13
+
14
+
15
+ __all__ = [
16
+ 'column_stack', 'row_stack', 'dstack', 'array_split', 'split',
17
+ 'hsplit', 'vsplit', 'dsplit', 'apply_over_axes', 'expand_dims',
18
+ 'apply_along_axis', 'kron', 'tile', 'get_array_wrap', 'take_along_axis',
19
+ 'put_along_axis'
20
+ ]
21
+
22
+
23
+ array_function_dispatch = functools.partial(
24
+ overrides.array_function_dispatch, module='numpy')
25
+
26
+
27
+ def _make_along_axis_idx(arr_shape, indices, axis):
28
+ # compute dimensions to iterate over
29
+ if not _nx.issubdtype(indices.dtype, _nx.integer):
30
+ raise IndexError('`indices` must be an integer array')
31
+ if len(arr_shape) != indices.ndim:
32
+ raise ValueError(
33
+ "`indices` and `arr` must have the same number of dimensions")
34
+ shape_ones = (1,) * indices.ndim
35
+ dest_dims = list(range(axis)) + [None] + list(range(axis+1, indices.ndim))
36
+
37
+ # build a fancy index, consisting of orthogonal aranges, with the
38
+ # requested index inserted at the right location
39
+ fancy_index = []
40
+ for dim, n in zip(dest_dims, arr_shape):
41
+ if dim is None:
42
+ fancy_index.append(indices)
43
+ else:
44
+ ind_shape = shape_ones[:dim] + (-1,) + shape_ones[dim+1:]
45
+ fancy_index.append(_nx.arange(n).reshape(ind_shape))
46
+
47
+ return tuple(fancy_index)
48
+
49
+
50
+ def _take_along_axis_dispatcher(arr, indices, axis):
51
+ return (arr, indices)
52
+
53
+
54
+ @array_function_dispatch(_take_along_axis_dispatcher)
55
+ def take_along_axis(arr, indices, axis):
56
+ """
57
+ Take values from the input array by matching 1d index and data slices.
58
+
59
+ This iterates over matching 1d slices oriented along the specified axis in
60
+ the index and data arrays, and uses the former to look up values in the
61
+ latter. These slices can be different lengths.
62
+
63
+ Functions returning an index along an axis, like `argsort` and
64
+ `argpartition`, produce suitable indices for this function.
65
+
66
+ .. versionadded:: 1.15.0
67
+
68
+ Parameters
69
+ ----------
70
+ arr : ndarray (Ni..., M, Nk...)
71
+ Source array
72
+ indices : ndarray (Ni..., J, Nk...)
73
+ Indices to take along each 1d slice of `arr`. This must match the
74
+ dimension of arr, but dimensions Ni and Nj only need to broadcast
75
+ against `arr`.
76
+ axis : int
77
+ The axis to take 1d slices along. If axis is None, the input array is
78
+ treated as if it had first been flattened to 1d, for consistency with
79
+ `sort` and `argsort`.
80
+
81
+ Returns
82
+ -------
83
+ out: ndarray (Ni..., J, Nk...)
84
+ The indexed result.
85
+
86
+ Notes
87
+ -----
88
+ This is equivalent to (but faster than) the following use of `ndindex` and
89
+ `s_`, which sets each of ``ii`` and ``kk`` to a tuple of indices::
90
+
91
+ Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:]
92
+ J = indices.shape[axis] # Need not equal M
93
+ out = np.empty(Ni + (J,) + Nk)
94
+
95
+ for ii in ndindex(Ni):
96
+ for kk in ndindex(Nk):
97
+ a_1d = a [ii + s_[:,] + kk]
98
+ indices_1d = indices[ii + s_[:,] + kk]
99
+ out_1d = out [ii + s_[:,] + kk]
100
+ for j in range(J):
101
+ out_1d[j] = a_1d[indices_1d[j]]
102
+
103
+ Equivalently, eliminating the inner loop, the last two lines would be::
104
+
105
+ out_1d[:] = a_1d[indices_1d]
106
+
107
+ See Also
108
+ --------
109
+ take : Take along an axis, using the same indices for every 1d slice
110
+ put_along_axis :
111
+ Put values into the destination array by matching 1d index and data slices
112
+
113
+ Examples
114
+ --------
115
+
116
+ For this sample array
117
+
118
+ >>> a = np.array([[10, 30, 20], [60, 40, 50]])
119
+
120
+ We can sort either by using sort directly, or argsort and this function
121
+
122
+ >>> np.sort(a, axis=1)
123
+ array([[10, 20, 30],
124
+ [40, 50, 60]])
125
+ >>> ai = np.argsort(a, axis=1)
126
+ >>> ai
127
+ array([[0, 2, 1],
128
+ [1, 2, 0]])
129
+ >>> np.take_along_axis(a, ai, axis=1)
130
+ array([[10, 20, 30],
131
+ [40, 50, 60]])
132
+
133
+ The same works for max and min, if you maintain the trivial dimension
134
+ with ``keepdims``:
135
+
136
+ >>> np.max(a, axis=1, keepdims=True)
137
+ array([[30],
138
+ [60]])
139
+ >>> ai = np.argmax(a, axis=1, keepdims=True)
140
+ >>> ai
141
+ array([[1],
142
+ [0]])
143
+ >>> np.take_along_axis(a, ai, axis=1)
144
+ array([[30],
145
+ [60]])
146
+
147
+ If we want to get the max and min at the same time, we can stack the
148
+ indices first
149
+
150
+ >>> ai_min = np.argmin(a, axis=1, keepdims=True)
151
+ >>> ai_max = np.argmax(a, axis=1, keepdims=True)
152
+ >>> ai = np.concatenate([ai_min, ai_max], axis=1)
153
+ >>> ai
154
+ array([[0, 1],
155
+ [1, 0]])
156
+ >>> np.take_along_axis(a, ai, axis=1)
157
+ array([[10, 30],
158
+ [40, 60]])
159
+ """
160
+ # normalize inputs
161
+ if axis is None:
162
+ arr = arr.flat
163
+ arr_shape = (len(arr),) # flatiter has no .shape
164
+ axis = 0
165
+ else:
166
+ axis = normalize_axis_index(axis, arr.ndim)
167
+ arr_shape = arr.shape
168
+
169
+ # use the fancy index
170
+ return arr[_make_along_axis_idx(arr_shape, indices, axis)]
171
+
172
+
173
+ def _put_along_axis_dispatcher(arr, indices, values, axis):
174
+ return (arr, indices, values)
175
+
176
+
177
+ @array_function_dispatch(_put_along_axis_dispatcher)
178
+ def put_along_axis(arr, indices, values, axis):
179
+ """
180
+ Put values into the destination array by matching 1d index and data slices.
181
+
182
+ This iterates over matching 1d slices oriented along the specified axis in
183
+ the index and data arrays, and uses the former to place values into the
184
+ latter. These slices can be different lengths.
185
+
186
+ Functions returning an index along an axis, like `argsort` and
187
+ `argpartition`, produce suitable indices for this function.
188
+
189
+ .. versionadded:: 1.15.0
190
+
191
+ Parameters
192
+ ----------
193
+ arr : ndarray (Ni..., M, Nk...)
194
+ Destination array.
195
+ indices : ndarray (Ni..., J, Nk...)
196
+ Indices to change along each 1d slice of `arr`. This must match the
197
+ dimension of arr, but dimensions in Ni and Nj may be 1 to broadcast
198
+ against `arr`.
199
+ values : array_like (Ni..., J, Nk...)
200
+ values to insert at those indices. Its shape and dimension are
201
+ broadcast to match that of `indices`.
202
+ axis : int
203
+ The axis to take 1d slices along. If axis is None, the destination
204
+ array is treated as if a flattened 1d view had been created of it.
205
+
206
+ Notes
207
+ -----
208
+ This is equivalent to (but faster than) the following use of `ndindex` and
209
+ `s_`, which sets each of ``ii`` and ``kk`` to a tuple of indices::
210
+
211
+ Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:]
212
+ J = indices.shape[axis] # Need not equal M
213
+
214
+ for ii in ndindex(Ni):
215
+ for kk in ndindex(Nk):
216
+ a_1d = a [ii + s_[:,] + kk]
217
+ indices_1d = indices[ii + s_[:,] + kk]
218
+ values_1d = values [ii + s_[:,] + kk]
219
+ for j in range(J):
220
+ a_1d[indices_1d[j]] = values_1d[j]
221
+
222
+ Equivalently, eliminating the inner loop, the last two lines would be::
223
+
224
+ a_1d[indices_1d] = values_1d
225
+
226
+ See Also
227
+ --------
228
+ take_along_axis :
229
+ Take values from the input array by matching 1d index and data slices
230
+
231
+ Examples
232
+ --------
233
+
234
+ For this sample array
235
+
236
+ >>> a = np.array([[10, 30, 20], [60, 40, 50]])
237
+
238
+ We can replace the maximum values with:
239
+
240
+ >>> ai = np.argmax(a, axis=1, keepdims=True)
241
+ >>> ai
242
+ array([[1],
243
+ [0]])
244
+ >>> np.put_along_axis(a, ai, 99, axis=1)
245
+ >>> a
246
+ array([[10, 99, 20],
247
+ [99, 40, 50]])
248
+
249
+ """
250
+ # normalize inputs
251
+ if axis is None:
252
+ arr = arr.flat
253
+ axis = 0
254
+ arr_shape = (len(arr),) # flatiter has no .shape
255
+ else:
256
+ axis = normalize_axis_index(axis, arr.ndim)
257
+ arr_shape = arr.shape
258
+
259
+ # use the fancy index
260
+ arr[_make_along_axis_idx(arr_shape, indices, axis)] = values
261
+
262
+
263
+ def _apply_along_axis_dispatcher(func1d, axis, arr, *args, **kwargs):
264
+ return (arr,)
265
+
266
+
267
+ @array_function_dispatch(_apply_along_axis_dispatcher)
268
+ def apply_along_axis(func1d, axis, arr, *args, **kwargs):
269
+ """
270
+ Apply a function to 1-D slices along the given axis.
271
+
272
+ Execute `func1d(a, *args, **kwargs)` where `func1d` operates on 1-D arrays
273
+ and `a` is a 1-D slice of `arr` along `axis`.
274
+
275
+ This is equivalent to (but faster than) the following use of `ndindex` and
276
+ `s_`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of indices::
277
+
278
+ Ni, Nk = a.shape[:axis], a.shape[axis+1:]
279
+ for ii in ndindex(Ni):
280
+ for kk in ndindex(Nk):
281
+ f = func1d(arr[ii + s_[:,] + kk])
282
+ Nj = f.shape
283
+ for jj in ndindex(Nj):
284
+ out[ii + jj + kk] = f[jj]
285
+
286
+ Equivalently, eliminating the inner loop, this can be expressed as::
287
+
288
+ Ni, Nk = a.shape[:axis], a.shape[axis+1:]
289
+ for ii in ndindex(Ni):
290
+ for kk in ndindex(Nk):
291
+ out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk])
292
+
293
+ Parameters
294
+ ----------
295
+ func1d : function (M,) -> (Nj...)
296
+ This function should accept 1-D arrays. It is applied to 1-D
297
+ slices of `arr` along the specified axis.
298
+ axis : integer
299
+ Axis along which `arr` is sliced.
300
+ arr : ndarray (Ni..., M, Nk...)
301
+ Input array.
302
+ args : any
303
+ Additional arguments to `func1d`.
304
+ kwargs : any
305
+ Additional named arguments to `func1d`.
306
+
307
+ .. versionadded:: 1.9.0
308
+
309
+
310
+ Returns
311
+ -------
312
+ out : ndarray (Ni..., Nj..., Nk...)
313
+ The output array. The shape of `out` is identical to the shape of
314
+ `arr`, except along the `axis` dimension. This axis is removed, and
315
+ replaced with new dimensions equal to the shape of the return value
316
+ of `func1d`. So if `func1d` returns a scalar `out` will have one
317
+ fewer dimensions than `arr`.
318
+
319
+ See Also
320
+ --------
321
+ apply_over_axes : Apply a function repeatedly over multiple axes.
322
+
323
+ Examples
324
+ --------
325
+ >>> def my_func(a):
326
+ ... \"\"\"Average first and last element of a 1-D array\"\"\"
327
+ ... return (a[0] + a[-1]) * 0.5
328
+ >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
329
+ >>> np.apply_along_axis(my_func, 0, b)
330
+ array([4., 5., 6.])
331
+ >>> np.apply_along_axis(my_func, 1, b)
332
+ array([2., 5., 8.])
333
+
334
+ For a function that returns a 1D array, the number of dimensions in
335
+ `outarr` is the same as `arr`.
336
+
337
+ >>> b = np.array([[8,1,7], [4,3,9], [5,2,6]])
338
+ >>> np.apply_along_axis(sorted, 1, b)
339
+ array([[1, 7, 8],
340
+ [3, 4, 9],
341
+ [2, 5, 6]])
342
+
343
+ For a function that returns a higher dimensional array, those dimensions
344
+ are inserted in place of the `axis` dimension.
345
+
346
+ >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
347
+ >>> np.apply_along_axis(np.diag, -1, b)
348
+ array([[[1, 0, 0],
349
+ [0, 2, 0],
350
+ [0, 0, 3]],
351
+ [[4, 0, 0],
352
+ [0, 5, 0],
353
+ [0, 0, 6]],
354
+ [[7, 0, 0],
355
+ [0, 8, 0],
356
+ [0, 0, 9]]])
357
+ """
358
+ # handle negative axes
359
+ arr = asanyarray(arr)
360
+ nd = arr.ndim
361
+ axis = normalize_axis_index(axis, nd)
362
+
363
+ # arr, with the iteration axis at the end
364
+ in_dims = list(range(nd))
365
+ inarr_view = transpose(arr, in_dims[:axis] + in_dims[axis+1:] + [axis])
366
+
367
+ # compute indices for the iteration axes, and append a trailing ellipsis to
368
+ # prevent 0d arrays decaying to scalars, which fixes gh-8642
369
+ inds = ndindex(inarr_view.shape[:-1])
370
+ inds = (ind + (Ellipsis,) for ind in inds)
371
+
372
+ # invoke the function on the first item
373
+ try:
374
+ ind0 = next(inds)
375
+ except StopIteration:
376
+ raise ValueError(
377
+ 'Cannot apply_along_axis when any iteration dimensions are 0'
378
+ ) from None
379
+ res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs))
380
+
381
+ # build a buffer for storing evaluations of func1d.
382
+ # remove the requested axis, and add the new ones on the end.
383
+ # laid out so that each write is contiguous.
384
+ # for a tuple index inds, buff[inds] = func1d(inarr_view[inds])
385
+ buff = zeros(inarr_view.shape[:-1] + res.shape, res.dtype)
386
+
387
+ # permutation of axes such that out = buff.transpose(buff_permute)
388
+ buff_dims = list(range(buff.ndim))
389
+ buff_permute = (
390
+ buff_dims[0 : axis] +
391
+ buff_dims[buff.ndim-res.ndim : buff.ndim] +
392
+ buff_dims[axis : buff.ndim-res.ndim]
393
+ )
394
+
395
+ # matrices have a nasty __array_prepare__ and __array_wrap__
396
+ if not isinstance(res, matrix):
397
+ buff = res.__array_prepare__(buff)
398
+
399
+ # save the first result, then compute and save all remaining results
400
+ buff[ind0] = res
401
+ for ind in inds:
402
+ buff[ind] = asanyarray(func1d(inarr_view[ind], *args, **kwargs))
403
+
404
+ if not isinstance(res, matrix):
405
+ # wrap the array, to preserve subclasses
406
+ buff = res.__array_wrap__(buff)
407
+
408
+ # finally, rotate the inserted axes back to where they belong
409
+ return transpose(buff, buff_permute)
410
+
411
+ else:
412
+ # matrices have to be transposed first, because they collapse dimensions!
413
+ out_arr = transpose(buff, buff_permute)
414
+ return res.__array_wrap__(out_arr)
415
+
416
+
417
+ def _apply_over_axes_dispatcher(func, a, axes):
418
+ return (a,)
419
+
420
+
421
+ @array_function_dispatch(_apply_over_axes_dispatcher)
422
+ def apply_over_axes(func, a, axes):
423
+ """
424
+ Apply a function repeatedly over multiple axes.
425
+
426
+ `func` is called as `res = func(a, axis)`, where `axis` is the first
427
+ element of `axes`. The result `res` of the function call must have
428
+ either the same dimensions as `a` or one less dimension. If `res`
429
+ has one less dimension than `a`, a dimension is inserted before
430
+ `axis`. The call to `func` is then repeated for each axis in `axes`,
431
+ with `res` as the first argument.
432
+
433
+ Parameters
434
+ ----------
435
+ func : function
436
+ This function must take two arguments, `func(a, axis)`.
437
+ a : array_like
438
+ Input array.
439
+ axes : array_like
440
+ Axes over which `func` is applied; the elements must be integers.
441
+
442
+ Returns
443
+ -------
444
+ apply_over_axis : ndarray
445
+ The output array. The number of dimensions is the same as `a`,
446
+ but the shape can be different. This depends on whether `func`
447
+ changes the shape of its output with respect to its input.
448
+
449
+ See Also
450
+ --------
451
+ apply_along_axis :
452
+ Apply a function to 1-D slices of an array along the given axis.
453
+
454
+ Notes
455
+ -----
456
+ This function is equivalent to tuple axis arguments to reorderable ufuncs
457
+ with keepdims=True. Tuple axis arguments to ufuncs have been available since
458
+ version 1.7.0.
459
+
460
+ Examples
461
+ --------
462
+ >>> a = np.arange(24).reshape(2,3,4)
463
+ >>> a
464
+ array([[[ 0, 1, 2, 3],
465
+ [ 4, 5, 6, 7],
466
+ [ 8, 9, 10, 11]],
467
+ [[12, 13, 14, 15],
468
+ [16, 17, 18, 19],
469
+ [20, 21, 22, 23]]])
470
+
471
+ Sum over axes 0 and 2. The result has same number of dimensions
472
+ as the original array:
473
+
474
+ >>> np.apply_over_axes(np.sum, a, [0,2])
475
+ array([[[ 60],
476
+ [ 92],
477
+ [124]]])
478
+
479
+ Tuple axis arguments to ufuncs are equivalent:
480
+
481
+ >>> np.sum(a, axis=(0,2), keepdims=True)
482
+ array([[[ 60],
483
+ [ 92],
484
+ [124]]])
485
+
486
+ """
487
+ val = asarray(a)
488
+ N = a.ndim
489
+ if array(axes).ndim == 0:
490
+ axes = (axes,)
491
+ for axis in axes:
492
+ if axis < 0:
493
+ axis = N + axis
494
+ args = (val, axis)
495
+ res = func(*args)
496
+ if res.ndim == val.ndim:
497
+ val = res
498
+ else:
499
+ res = expand_dims(res, axis)
500
+ if res.ndim == val.ndim:
501
+ val = res
502
+ else:
503
+ raise ValueError("function is not returning "
504
+ "an array of the correct shape")
505
+ return val
506
+
507
+
508
+ def _expand_dims_dispatcher(a, axis):
509
+ return (a,)
510
+
511
+
512
+ @array_function_dispatch(_expand_dims_dispatcher)
513
+ def expand_dims(a, axis):
514
+ """
515
+ Expand the shape of an array.
516
+
517
+ Insert a new axis that will appear at the `axis` position in the expanded
518
+ array shape.
519
+
520
+ Parameters
521
+ ----------
522
+ a : array_like
523
+ Input array.
524
+ axis : int or tuple of ints
525
+ Position in the expanded axes where the new axis (or axes) is placed.
526
+
527
+ .. deprecated:: 1.13.0
528
+ Passing an axis where ``axis > a.ndim`` will be treated as
529
+ ``axis == a.ndim``, and passing ``axis < -a.ndim - 1`` will
530
+ be treated as ``axis == 0``. This behavior is deprecated.
531
+
532
+ .. versionchanged:: 1.18.0
533
+ A tuple of axes is now supported. Out of range axes as
534
+ described above are now forbidden and raise an `AxisError`.
535
+
536
+ Returns
537
+ -------
538
+ result : ndarray
539
+ View of `a` with the number of dimensions increased.
540
+
541
+ See Also
542
+ --------
543
+ squeeze : The inverse operation, removing singleton dimensions
544
+ reshape : Insert, remove, and combine dimensions, and resize existing ones
545
+ doc.indexing, atleast_1d, atleast_2d, atleast_3d
546
+
547
+ Examples
548
+ --------
549
+ >>> x = np.array([1, 2])
550
+ >>> x.shape
551
+ (2,)
552
+
553
+ The following is equivalent to ``x[np.newaxis, :]`` or ``x[np.newaxis]``:
554
+
555
+ >>> y = np.expand_dims(x, axis=0)
556
+ >>> y
557
+ array([[1, 2]])
558
+ >>> y.shape
559
+ (1, 2)
560
+
561
+ The following is equivalent to ``x[:, np.newaxis]``:
562
+
563
+ >>> y = np.expand_dims(x, axis=1)
564
+ >>> y
565
+ array([[1],
566
+ [2]])
567
+ >>> y.shape
568
+ (2, 1)
569
+
570
+ ``axis`` may also be a tuple:
571
+
572
+ >>> y = np.expand_dims(x, axis=(0, 1))
573
+ >>> y
574
+ array([[[1, 2]]])
575
+
576
+ >>> y = np.expand_dims(x, axis=(2, 0))
577
+ >>> y
578
+ array([[[1],
579
+ [2]]])
580
+
581
+ Note that some examples may use ``None`` instead of ``np.newaxis``. These
582
+ are the same objects:
583
+
584
+ >>> np.newaxis is None
585
+ True
586
+
587
+ """
588
+ if isinstance(a, matrix):
589
+ a = asarray(a)
590
+ else:
591
+ a = asanyarray(a)
592
+
593
+ if type(axis) not in (tuple, list):
594
+ axis = (axis,)
595
+
596
+ out_ndim = len(axis) + a.ndim
597
+ axis = normalize_axis_tuple(axis, out_ndim)
598
+
599
+ shape_it = iter(a.shape)
600
+ shape = [1 if ax in axis else next(shape_it) for ax in range(out_ndim)]
601
+
602
+ return a.reshape(shape)
603
+
604
+
605
+ row_stack = vstack
606
+
607
+
608
+ def _column_stack_dispatcher(tup):
609
+ return _arrays_for_stack_dispatcher(tup)
610
+
611
+
612
+ @array_function_dispatch(_column_stack_dispatcher)
613
+ def column_stack(tup):
614
+ """
615
+ Stack 1-D arrays as columns into a 2-D array.
616
+
617
+ Take a sequence of 1-D arrays and stack them as columns
618
+ to make a single 2-D array. 2-D arrays are stacked as-is,
619
+ just like with `hstack`. 1-D arrays are turned into 2-D columns
620
+ first.
621
+
622
+ Parameters
623
+ ----------
624
+ tup : sequence of 1-D or 2-D arrays.
625
+ Arrays to stack. All of them must have the same first dimension.
626
+
627
+ Returns
628
+ -------
629
+ stacked : 2-D array
630
+ The array formed by stacking the given arrays.
631
+
632
+ See Also
633
+ --------
634
+ stack, hstack, vstack, concatenate
635
+
636
+ Examples
637
+ --------
638
+ >>> a = np.array((1,2,3))
639
+ >>> b = np.array((2,3,4))
640
+ >>> np.column_stack((a,b))
641
+ array([[1, 2],
642
+ [2, 3],
643
+ [3, 4]])
644
+
645
+ """
646
+ arrays = []
647
+ for v in tup:
648
+ arr = asanyarray(v)
649
+ if arr.ndim < 2:
650
+ arr = array(arr, copy=False, subok=True, ndmin=2).T
651
+ arrays.append(arr)
652
+ return _nx.concatenate(arrays, 1)
653
+
654
+
655
+ def _dstack_dispatcher(tup):
656
+ return _arrays_for_stack_dispatcher(tup)
657
+
658
+
659
+ @array_function_dispatch(_dstack_dispatcher)
660
+ def dstack(tup):
661
+ """
662
+ Stack arrays in sequence depth wise (along third axis).
663
+
664
+ This is equivalent to concatenation along the third axis after 2-D arrays
665
+ of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape
666
+ `(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by
667
+ `dsplit`.
668
+
669
+ This function makes most sense for arrays with up to 3 dimensions. For
670
+ instance, for pixel-data with a height (first axis), width (second axis),
671
+ and r/g/b channels (third axis). The functions `concatenate`, `stack` and
672
+ `block` provide more general stacking and concatenation operations.
673
+
674
+ Parameters
675
+ ----------
676
+ tup : sequence of arrays
677
+ The arrays must have the same shape along all but the third axis.
678
+ 1-D or 2-D arrays must have the same shape.
679
+
680
+ Returns
681
+ -------
682
+ stacked : ndarray
683
+ The array formed by stacking the given arrays, will be at least 3-D.
684
+
685
+ See Also
686
+ --------
687
+ concatenate : Join a sequence of arrays along an existing axis.
688
+ stack : Join a sequence of arrays along a new axis.
689
+ block : Assemble an nd-array from nested lists of blocks.
690
+ vstack : Stack arrays in sequence vertically (row wise).
691
+ hstack : Stack arrays in sequence horizontally (column wise).
692
+ column_stack : Stack 1-D arrays as columns into a 2-D array.
693
+ dsplit : Split array along third axis.
694
+
695
+ Examples
696
+ --------
697
+ >>> a = np.array((1,2,3))
698
+ >>> b = np.array((2,3,4))
699
+ >>> np.dstack((a,b))
700
+ array([[[1, 2],
701
+ [2, 3],
702
+ [3, 4]]])
703
+
704
+ >>> a = np.array([[1],[2],[3]])
705
+ >>> b = np.array([[2],[3],[4]])
706
+ >>> np.dstack((a,b))
707
+ array([[[1, 2]],
708
+ [[2, 3]],
709
+ [[3, 4]]])
710
+
711
+ """
712
+ arrs = atleast_3d(*tup)
713
+ if not isinstance(arrs, list):
714
+ arrs = [arrs]
715
+ return _nx.concatenate(arrs, 2)
716
+
717
+
718
+ def _replace_zero_by_x_arrays(sub_arys):
719
+ for i in range(len(sub_arys)):
720
+ if _nx.ndim(sub_arys[i]) == 0:
721
+ sub_arys[i] = _nx.empty(0, dtype=sub_arys[i].dtype)
722
+ elif _nx.sometrue(_nx.equal(_nx.shape(sub_arys[i]), 0)):
723
+ sub_arys[i] = _nx.empty(0, dtype=sub_arys[i].dtype)
724
+ return sub_arys
725
+
726
+
727
+ def _array_split_dispatcher(ary, indices_or_sections, axis=None):
728
+ return (ary, indices_or_sections)
729
+
730
+
731
+ @array_function_dispatch(_array_split_dispatcher)
732
+ def array_split(ary, indices_or_sections, axis=0):
733
+ """
734
+ Split an array into multiple sub-arrays.
735
+
736
+ Please refer to the ``split`` documentation. The only difference
737
+ between these functions is that ``array_split`` allows
738
+ `indices_or_sections` to be an integer that does *not* equally
739
+ divide the axis. For an array of length l that should be split
740
+ into n sections, it returns l % n sub-arrays of size l//n + 1
741
+ and the rest of size l//n.
742
+
743
+ See Also
744
+ --------
745
+ split : Split array into multiple sub-arrays of equal size.
746
+
747
+ Examples
748
+ --------
749
+ >>> x = np.arange(8.0)
750
+ >>> np.array_split(x, 3)
751
+ [array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7.])]
752
+
753
+ >>> x = np.arange(9)
754
+ >>> np.array_split(x, 4)
755
+ [array([0, 1, 2]), array([3, 4]), array([5, 6]), array([7, 8])]
756
+
757
+ """
758
+ try:
759
+ Ntotal = ary.shape[axis]
760
+ except AttributeError:
761
+ Ntotal = len(ary)
762
+ try:
763
+ # handle array case.
764
+ Nsections = len(indices_or_sections) + 1
765
+ div_points = [0] + list(indices_or_sections) + [Ntotal]
766
+ except TypeError:
767
+ # indices_or_sections is a scalar, not an array.
768
+ Nsections = int(indices_or_sections)
769
+ if Nsections <= 0:
770
+ raise ValueError('number sections must be larger than 0.') from None
771
+ Neach_section, extras = divmod(Ntotal, Nsections)
772
+ section_sizes = ([0] +
773
+ extras * [Neach_section+1] +
774
+ (Nsections-extras) * [Neach_section])
775
+ div_points = _nx.array(section_sizes, dtype=_nx.intp).cumsum()
776
+
777
+ sub_arys = []
778
+ sary = _nx.swapaxes(ary, axis, 0)
779
+ for i in range(Nsections):
780
+ st = div_points[i]
781
+ end = div_points[i + 1]
782
+ sub_arys.append(_nx.swapaxes(sary[st:end], axis, 0))
783
+
784
+ return sub_arys
785
+
786
+
787
+ def _split_dispatcher(ary, indices_or_sections, axis=None):
788
+ return (ary, indices_or_sections)
789
+
790
+
791
+ @array_function_dispatch(_split_dispatcher)
792
+ def split(ary, indices_or_sections, axis=0):
793
+ """
794
+ Split an array into multiple sub-arrays as views into `ary`.
795
+
796
+ Parameters
797
+ ----------
798
+ ary : ndarray
799
+ Array to be divided into sub-arrays.
800
+ indices_or_sections : int or 1-D array
801
+ If `indices_or_sections` is an integer, N, the array will be divided
802
+ into N equal arrays along `axis`. If such a split is not possible,
803
+ an error is raised.
804
+
805
+ If `indices_or_sections` is a 1-D array of sorted integers, the entries
806
+ indicate where along `axis` the array is split. For example,
807
+ ``[2, 3]`` would, for ``axis=0``, result in
808
+
809
+ - ary[:2]
810
+ - ary[2:3]
811
+ - ary[3:]
812
+
813
+ If an index exceeds the dimension of the array along `axis`,
814
+ an empty sub-array is returned correspondingly.
815
+ axis : int, optional
816
+ The axis along which to split, default is 0.
817
+
818
+ Returns
819
+ -------
820
+ sub-arrays : list of ndarrays
821
+ A list of sub-arrays as views into `ary`.
822
+
823
+ Raises
824
+ ------
825
+ ValueError
826
+ If `indices_or_sections` is given as an integer, but
827
+ a split does not result in equal division.
828
+
829
+ See Also
830
+ --------
831
+ array_split : Split an array into multiple sub-arrays of equal or
832
+ near-equal size. Does not raise an exception if
833
+ an equal division cannot be made.
834
+ hsplit : Split array into multiple sub-arrays horizontally (column-wise).
835
+ vsplit : Split array into multiple sub-arrays vertically (row wise).
836
+ dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
837
+ concatenate : Join a sequence of arrays along an existing axis.
838
+ stack : Join a sequence of arrays along a new axis.
839
+ hstack : Stack arrays in sequence horizontally (column wise).
840
+ vstack : Stack arrays in sequence vertically (row wise).
841
+ dstack : Stack arrays in sequence depth wise (along third dimension).
842
+
843
+ Examples
844
+ --------
845
+ >>> x = np.arange(9.0)
846
+ >>> np.split(x, 3)
847
+ [array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7., 8.])]
848
+
849
+ >>> x = np.arange(8.0)
850
+ >>> np.split(x, [3, 5, 6, 10])
851
+ [array([0., 1., 2.]),
852
+ array([3., 4.]),
853
+ array([5.]),
854
+ array([6., 7.]),
855
+ array([], dtype=float64)]
856
+
857
+ """
858
+ try:
859
+ len(indices_or_sections)
860
+ except TypeError:
861
+ sections = indices_or_sections
862
+ N = ary.shape[axis]
863
+ if N % sections:
864
+ raise ValueError(
865
+ 'array split does not result in an equal division') from None
866
+ return array_split(ary, indices_or_sections, axis)
867
+
868
+
869
+ def _hvdsplit_dispatcher(ary, indices_or_sections):
870
+ return (ary, indices_or_sections)
871
+
872
+
873
+ @array_function_dispatch(_hvdsplit_dispatcher)
874
+ def hsplit(ary, indices_or_sections):
875
+ """
876
+ Split an array into multiple sub-arrays horizontally (column-wise).
877
+
878
+ Please refer to the `split` documentation. `hsplit` is equivalent
879
+ to `split` with ``axis=1``, the array is always split along the second
880
+ axis except for 1-D arrays, where it is split at ``axis=0``.
881
+
882
+ See Also
883
+ --------
884
+ split : Split an array into multiple sub-arrays of equal size.
885
+
886
+ Examples
887
+ --------
888
+ >>> x = np.arange(16.0).reshape(4, 4)
889
+ >>> x
890
+ array([[ 0., 1., 2., 3.],
891
+ [ 4., 5., 6., 7.],
892
+ [ 8., 9., 10., 11.],
893
+ [12., 13., 14., 15.]])
894
+ >>> np.hsplit(x, 2)
895
+ [array([[ 0., 1.],
896
+ [ 4., 5.],
897
+ [ 8., 9.],
898
+ [12., 13.]]),
899
+ array([[ 2., 3.],
900
+ [ 6., 7.],
901
+ [10., 11.],
902
+ [14., 15.]])]
903
+ >>> np.hsplit(x, np.array([3, 6]))
904
+ [array([[ 0., 1., 2.],
905
+ [ 4., 5., 6.],
906
+ [ 8., 9., 10.],
907
+ [12., 13., 14.]]),
908
+ array([[ 3.],
909
+ [ 7.],
910
+ [11.],
911
+ [15.]]),
912
+ array([], shape=(4, 0), dtype=float64)]
913
+
914
+ With a higher dimensional array the split is still along the second axis.
915
+
916
+ >>> x = np.arange(8.0).reshape(2, 2, 2)
917
+ >>> x
918
+ array([[[0., 1.],
919
+ [2., 3.]],
920
+ [[4., 5.],
921
+ [6., 7.]]])
922
+ >>> np.hsplit(x, 2)
923
+ [array([[[0., 1.]],
924
+ [[4., 5.]]]),
925
+ array([[[2., 3.]],
926
+ [[6., 7.]]])]
927
+
928
+ With a 1-D array, the split is along axis 0.
929
+
930
+ >>> x = np.array([0, 1, 2, 3, 4, 5])
931
+ >>> np.hsplit(x, 2)
932
+ [array([0, 1, 2]), array([3, 4, 5])]
933
+
934
+ """
935
+ if _nx.ndim(ary) == 0:
936
+ raise ValueError('hsplit only works on arrays of 1 or more dimensions')
937
+ if ary.ndim > 1:
938
+ return split(ary, indices_or_sections, 1)
939
+ else:
940
+ return split(ary, indices_or_sections, 0)
941
+
942
+
943
+ @array_function_dispatch(_hvdsplit_dispatcher)
944
+ def vsplit(ary, indices_or_sections):
945
+ """
946
+ Split an array into multiple sub-arrays vertically (row-wise).
947
+
948
+ Please refer to the ``split`` documentation. ``vsplit`` is equivalent
949
+ to ``split`` with `axis=0` (default), the array is always split along the
950
+ first axis regardless of the array dimension.
951
+
952
+ See Also
953
+ --------
954
+ split : Split an array into multiple sub-arrays of equal size.
955
+
956
+ Examples
957
+ --------
958
+ >>> x = np.arange(16.0).reshape(4, 4)
959
+ >>> x
960
+ array([[ 0., 1., 2., 3.],
961
+ [ 4., 5., 6., 7.],
962
+ [ 8., 9., 10., 11.],
963
+ [12., 13., 14., 15.]])
964
+ >>> np.vsplit(x, 2)
965
+ [array([[0., 1., 2., 3.],
966
+ [4., 5., 6., 7.]]), array([[ 8., 9., 10., 11.],
967
+ [12., 13., 14., 15.]])]
968
+ >>> np.vsplit(x, np.array([3, 6]))
969
+ [array([[ 0., 1., 2., 3.],
970
+ [ 4., 5., 6., 7.],
971
+ [ 8., 9., 10., 11.]]), array([[12., 13., 14., 15.]]), array([], shape=(0, 4), dtype=float64)]
972
+
973
+ With a higher dimensional array the split is still along the first axis.
974
+
975
+ >>> x = np.arange(8.0).reshape(2, 2, 2)
976
+ >>> x
977
+ array([[[0., 1.],
978
+ [2., 3.]],
979
+ [[4., 5.],
980
+ [6., 7.]]])
981
+ >>> np.vsplit(x, 2)
982
+ [array([[[0., 1.],
983
+ [2., 3.]]]), array([[[4., 5.],
984
+ [6., 7.]]])]
985
+
986
+ """
987
+ if _nx.ndim(ary) < 2:
988
+ raise ValueError('vsplit only works on arrays of 2 or more dimensions')
989
+ return split(ary, indices_or_sections, 0)
990
+
991
+
992
+ @array_function_dispatch(_hvdsplit_dispatcher)
993
+ def dsplit(ary, indices_or_sections):
994
+ """
995
+ Split array into multiple sub-arrays along the 3rd axis (depth).
996
+
997
+ Please refer to the `split` documentation. `dsplit` is equivalent
998
+ to `split` with ``axis=2``, the array is always split along the third
999
+ axis provided the array dimension is greater than or equal to 3.
1000
+
1001
+ See Also
1002
+ --------
1003
+ split : Split an array into multiple sub-arrays of equal size.
1004
+
1005
+ Examples
1006
+ --------
1007
+ >>> x = np.arange(16.0).reshape(2, 2, 4)
1008
+ >>> x
1009
+ array([[[ 0., 1., 2., 3.],
1010
+ [ 4., 5., 6., 7.]],
1011
+ [[ 8., 9., 10., 11.],
1012
+ [12., 13., 14., 15.]]])
1013
+ >>> np.dsplit(x, 2)
1014
+ [array([[[ 0., 1.],
1015
+ [ 4., 5.]],
1016
+ [[ 8., 9.],
1017
+ [12., 13.]]]), array([[[ 2., 3.],
1018
+ [ 6., 7.]],
1019
+ [[10., 11.],
1020
+ [14., 15.]]])]
1021
+ >>> np.dsplit(x, np.array([3, 6]))
1022
+ [array([[[ 0., 1., 2.],
1023
+ [ 4., 5., 6.]],
1024
+ [[ 8., 9., 10.],
1025
+ [12., 13., 14.]]]),
1026
+ array([[[ 3.],
1027
+ [ 7.]],
1028
+ [[11.],
1029
+ [15.]]]),
1030
+ array([], shape=(2, 2, 0), dtype=float64)]
1031
+ """
1032
+ if _nx.ndim(ary) < 3:
1033
+ raise ValueError('dsplit only works on arrays of 3 or more dimensions')
1034
+ return split(ary, indices_or_sections, 2)
1035
+
1036
+
1037
+ def get_array_prepare(*args):
1038
+ """Find the wrapper for the array with the highest priority.
1039
+
1040
+ In case of ties, leftmost wins. If no wrapper is found, return None
1041
+ """
1042
+ wrappers = sorted((getattr(x, '__array_priority__', 0), -i,
1043
+ x.__array_prepare__) for i, x in enumerate(args)
1044
+ if hasattr(x, '__array_prepare__'))
1045
+ if wrappers:
1046
+ return wrappers[-1][-1]
1047
+ return None
1048
+
1049
+
1050
+ def get_array_wrap(*args):
1051
+ """Find the wrapper for the array with the highest priority.
1052
+
1053
+ In case of ties, leftmost wins. If no wrapper is found, return None
1054
+ """
1055
+ wrappers = sorted((getattr(x, '__array_priority__', 0), -i,
1056
+ x.__array_wrap__) for i, x in enumerate(args)
1057
+ if hasattr(x, '__array_wrap__'))
1058
+ if wrappers:
1059
+ return wrappers[-1][-1]
1060
+ return None
1061
+
1062
+
1063
+ def _kron_dispatcher(a, b):
1064
+ return (a, b)
1065
+
1066
+
1067
+ @array_function_dispatch(_kron_dispatcher)
1068
+ def kron(a, b):
1069
+ """
1070
+ Kronecker product of two arrays.
1071
+
1072
+ Computes the Kronecker product, a composite array made of blocks of the
1073
+ second array scaled by the first.
1074
+
1075
+ Parameters
1076
+ ----------
1077
+ a, b : array_like
1078
+
1079
+ Returns
1080
+ -------
1081
+ out : ndarray
1082
+
1083
+ See Also
1084
+ --------
1085
+ outer : The outer product
1086
+
1087
+ Notes
1088
+ -----
1089
+ The function assumes that the number of dimensions of `a` and `b`
1090
+ are the same, if necessary prepending the smallest with ones.
1091
+ If ``a.shape = (r0,r1,..,rN)`` and ``b.shape = (s0,s1,...,sN)``,
1092
+ the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``.
1093
+ The elements are products of elements from `a` and `b`, organized
1094
+ explicitly by::
1095
+
1096
+ kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
1097
+
1098
+ where::
1099
+
1100
+ kt = it * st + jt, t = 0,...,N
1101
+
1102
+ In the common 2-D case (N=1), the block structure can be visualized::
1103
+
1104
+ [[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ],
1105
+ [ ... ... ],
1106
+ [ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]]
1107
+
1108
+
1109
+ Examples
1110
+ --------
1111
+ >>> np.kron([1,10,100], [5,6,7])
1112
+ array([ 5, 6, 7, ..., 500, 600, 700])
1113
+ >>> np.kron([5,6,7], [1,10,100])
1114
+ array([ 5, 50, 500, ..., 7, 70, 700])
1115
+
1116
+ >>> np.kron(np.eye(2), np.ones((2,2)))
1117
+ array([[1., 1., 0., 0.],
1118
+ [1., 1., 0., 0.],
1119
+ [0., 0., 1., 1.],
1120
+ [0., 0., 1., 1.]])
1121
+
1122
+ >>> a = np.arange(100).reshape((2,5,2,5))
1123
+ >>> b = np.arange(24).reshape((2,3,4))
1124
+ >>> c = np.kron(a,b)
1125
+ >>> c.shape
1126
+ (2, 10, 6, 20)
1127
+ >>> I = (1,3,0,2)
1128
+ >>> J = (0,2,1)
1129
+ >>> J1 = (0,) + J # extend to ndim=4
1130
+ >>> S1 = (1,) + b.shape
1131
+ >>> K = tuple(np.array(I) * np.array(S1) + np.array(J1))
1132
+ >>> c[K] == a[I]*b[J]
1133
+ True
1134
+
1135
+ """
1136
+ # Working:
1137
+ # 1. Equalise the shapes by prepending smaller array with 1s
1138
+ # 2. Expand shapes of both the arrays by adding new axes at
1139
+ # odd positions for 1st array and even positions for 2nd
1140
+ # 3. Compute the product of the modified array
1141
+ # 4. The inner most array elements now contain the rows of
1142
+ # the Kronecker product
1143
+ # 5. Reshape the result to kron's shape, which is same as
1144
+ # product of shapes of the two arrays.
1145
+ b = asanyarray(b)
1146
+ a = array(a, copy=False, subok=True, ndmin=b.ndim)
1147
+ is_any_mat = isinstance(a, matrix) or isinstance(b, matrix)
1148
+ ndb, nda = b.ndim, a.ndim
1149
+ nd = max(ndb, nda)
1150
+
1151
+ if (nda == 0 or ndb == 0):
1152
+ return _nx.multiply(a, b)
1153
+
1154
+ as_ = a.shape
1155
+ bs = b.shape
1156
+ if not a.flags.contiguous:
1157
+ a = reshape(a, as_)
1158
+ if not b.flags.contiguous:
1159
+ b = reshape(b, bs)
1160
+
1161
+ # Equalise the shapes by prepending smaller one with 1s
1162
+ as_ = (1,)*max(0, ndb-nda) + as_
1163
+ bs = (1,)*max(0, nda-ndb) + bs
1164
+
1165
+ # Insert empty dimensions
1166
+ a_arr = expand_dims(a, axis=tuple(range(ndb-nda)))
1167
+ b_arr = expand_dims(b, axis=tuple(range(nda-ndb)))
1168
+
1169
+ # Compute the product
1170
+ a_arr = expand_dims(a_arr, axis=tuple(range(1, nd*2, 2)))
1171
+ b_arr = expand_dims(b_arr, axis=tuple(range(0, nd*2, 2)))
1172
+ # In case of `mat`, convert result to `array`
1173
+ result = _nx.multiply(a_arr, b_arr, subok=(not is_any_mat))
1174
+
1175
+ # Reshape back
1176
+ result = result.reshape(_nx.multiply(as_, bs))
1177
+
1178
+ return result if not is_any_mat else matrix(result, copy=False)
1179
+
1180
+
1181
+ def _tile_dispatcher(A, reps):
1182
+ return (A, reps)
1183
+
1184
+
1185
+ @array_function_dispatch(_tile_dispatcher)
1186
+ def tile(A, reps):
1187
+ """
1188
+ Construct an array by repeating A the number of times given by reps.
1189
+
1190
+ If `reps` has length ``d``, the result will have dimension of
1191
+ ``max(d, A.ndim)``.
1192
+
1193
+ If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
1194
+ axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication,
1195
+ or shape (1, 1, 3) for 3-D replication. If this is not the desired
1196
+ behavior, promote `A` to d-dimensions manually before calling this
1197
+ function.
1198
+
1199
+ If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it.
1200
+ Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as
1201
+ (1, 1, 2, 2).
1202
+
1203
+ Note : Although tile may be used for broadcasting, it is strongly
1204
+ recommended to use numpy's broadcasting operations and functions.
1205
+
1206
+ Parameters
1207
+ ----------
1208
+ A : array_like
1209
+ The input array.
1210
+ reps : array_like
1211
+ The number of repetitions of `A` along each axis.
1212
+
1213
+ Returns
1214
+ -------
1215
+ c : ndarray
1216
+ The tiled output array.
1217
+
1218
+ See Also
1219
+ --------
1220
+ repeat : Repeat elements of an array.
1221
+ broadcast_to : Broadcast an array to a new shape
1222
+
1223
+ Examples
1224
+ --------
1225
+ >>> a = np.array([0, 1, 2])
1226
+ >>> np.tile(a, 2)
1227
+ array([0, 1, 2, 0, 1, 2])
1228
+ >>> np.tile(a, (2, 2))
1229
+ array([[0, 1, 2, 0, 1, 2],
1230
+ [0, 1, 2, 0, 1, 2]])
1231
+ >>> np.tile(a, (2, 1, 2))
1232
+ array([[[0, 1, 2, 0, 1, 2]],
1233
+ [[0, 1, 2, 0, 1, 2]]])
1234
+
1235
+ >>> b = np.array([[1, 2], [3, 4]])
1236
+ >>> np.tile(b, 2)
1237
+ array([[1, 2, 1, 2],
1238
+ [3, 4, 3, 4]])
1239
+ >>> np.tile(b, (2, 1))
1240
+ array([[1, 2],
1241
+ [3, 4],
1242
+ [1, 2],
1243
+ [3, 4]])
1244
+
1245
+ >>> c = np.array([1,2,3,4])
1246
+ >>> np.tile(c,(4,1))
1247
+ array([[1, 2, 3, 4],
1248
+ [1, 2, 3, 4],
1249
+ [1, 2, 3, 4],
1250
+ [1, 2, 3, 4]])
1251
+ """
1252
+ try:
1253
+ tup = tuple(reps)
1254
+ except TypeError:
1255
+ tup = (reps,)
1256
+ d = len(tup)
1257
+ if all(x == 1 for x in tup) and isinstance(A, _nx.ndarray):
1258
+ # Fixes the problem that the function does not make a copy if A is a
1259
+ # numpy array and the repetitions are 1 in all dimensions
1260
+ return _nx.array(A, copy=True, subok=True, ndmin=d)
1261
+ else:
1262
+ # Note that no copy of zero-sized arrays is made. However since they
1263
+ # have no data there is no risk of an inadvertent overwrite.
1264
+ c = _nx.array(A, copy=False, subok=True, ndmin=d)
1265
+ if (d < c.ndim):
1266
+ tup = (1,)*(c.ndim-d) + tup
1267
+ shape_out = tuple(s*t for s, t in zip(c.shape, tup))
1268
+ n = c.size
1269
+ if n > 0:
1270
+ for dim_in, nrep in zip(c.shape, tup):
1271
+ if nrep != 1:
1272
+ c = c.reshape(-1, n).repeat(nrep, 0)
1273
+ n //= dim_in
1274
+ return c.reshape(shape_out)
shared/package-files/02/0212b936e3a9743f898c8cd73a5b2c13cfe248bc850001f3c8657fc35053eef0/__init__.pyi ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy._pytesttester import PytestTester
2
+
3
+ from unittest import (
4
+ TestCase as TestCase,
5
+ )
6
+
7
+ from numpy.testing._private.utils import (
8
+ assert_equal as assert_equal,
9
+ assert_almost_equal as assert_almost_equal,
10
+ assert_approx_equal as assert_approx_equal,
11
+ assert_array_equal as assert_array_equal,
12
+ assert_array_less as assert_array_less,
13
+ assert_string_equal as assert_string_equal,
14
+ assert_array_almost_equal as assert_array_almost_equal,
15
+ assert_raises as assert_raises,
16
+ build_err_msg as build_err_msg,
17
+ decorate_methods as decorate_methods,
18
+ jiffies as jiffies,
19
+ memusage as memusage,
20
+ print_assert_equal as print_assert_equal,
21
+ rundocs as rundocs,
22
+ runstring as runstring,
23
+ verbose as verbose,
24
+ measure as measure,
25
+ assert_ as assert_,
26
+ assert_array_almost_equal_nulp as assert_array_almost_equal_nulp,
27
+ assert_raises_regex as assert_raises_regex,
28
+ assert_array_max_ulp as assert_array_max_ulp,
29
+ assert_warns as assert_warns,
30
+ assert_no_warnings as assert_no_warnings,
31
+ assert_allclose as assert_allclose,
32
+ IgnoreException as IgnoreException,
33
+ clear_and_catch_warnings as clear_and_catch_warnings,
34
+ SkipTest as SkipTest,
35
+ KnownFailureException as KnownFailureException,
36
+ temppath as temppath,
37
+ tempdir as tempdir,
38
+ IS_PYPY as IS_PYPY,
39
+ IS_PYSTON as IS_PYSTON,
40
+ HAS_REFCOUNT as HAS_REFCOUNT,
41
+ suppress_warnings as suppress_warnings,
42
+ assert_array_compare as assert_array_compare,
43
+ assert_no_gc_cycles as assert_no_gc_cycles,
44
+ break_cycles as break_cycles,
45
+ HAS_LAPACK64 as HAS_LAPACK64,
46
+ )
47
+
48
+ __all__: list[str]
49
+ __path__: list[str]
50
+ test: PytestTester
shared/package-files/02/02169eb141a5fbd8adeaebc6e9fb053ceafdca716919a4cc938b795d35fb67f4/urls.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import string
3
+ import urllib.parse
4
+ import urllib.request
5
+ from typing import Optional
6
+
7
+ from .compat import WINDOWS
8
+
9
+
10
+ def get_url_scheme(url: str) -> Optional[str]:
11
+ if ":" not in url:
12
+ return None
13
+ return url.split(":", 1)[0].lower()
14
+
15
+
16
+ def path_to_url(path: str) -> str:
17
+ """
18
+ Convert a path to a file: URL. The path will be made absolute and have
19
+ quoted path parts.
20
+ """
21
+ path = os.path.normpath(os.path.abspath(path))
22
+ url = urllib.parse.urljoin("file:", urllib.request.pathname2url(path))
23
+ return url
24
+
25
+
26
+ def url_to_path(url: str) -> str:
27
+ """
28
+ Convert a file: URL to a path.
29
+ """
30
+ assert url.startswith(
31
+ "file:"
32
+ ), f"You can only turn file: urls into filenames (not {url!r})"
33
+
34
+ _, netloc, path, _, _ = urllib.parse.urlsplit(url)
35
+
36
+ if not netloc or netloc == "localhost":
37
+ # According to RFC 8089, same as empty authority.
38
+ netloc = ""
39
+ elif WINDOWS:
40
+ # If we have a UNC path, prepend UNC share notation.
41
+ netloc = "\\\\" + netloc
42
+ else:
43
+ raise ValueError(
44
+ f"non-local file URIs are not supported on this platform: {url!r}"
45
+ )
46
+
47
+ path = urllib.request.url2pathname(netloc + path)
48
+
49
+ # On Windows, urlsplit parses the path as something like "/C:/Users/foo".
50
+ # This creates issues for path-related functions like io.open(), so we try
51
+ # to detect and strip the leading slash.
52
+ if (
53
+ WINDOWS
54
+ and not netloc # Not UNC.
55
+ and len(path) >= 3
56
+ and path[0] == "/" # Leading slash to strip.
57
+ and path[1] in string.ascii_letters # Drive letter.
58
+ and path[2:4] in (":", ":/") # Colon + end of string, or colon + absolute path.
59
+ ):
60
+ path = path[1:]
61
+
62
+ return path
shared/package-files/02/0217e96269b35ecf856e039eb6839d9759618f5ab5398df43a0cfceb9a5ee5ac/_upsample_nearest_exact3d_backward_cuda_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor _upsample_nearest_exact3d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional<double> scales_d=c10::nullopt, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt);
21
+ TORCH_API at::Tensor _upsample_nearest_exact3d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional<double> scales_d=c10::nullopt, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt);
22
+ TORCH_API at::Tensor & _upsample_nearest_exact3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional<double> scales_d=c10::nullopt, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt);
23
+ TORCH_API at::Tensor & _upsample_nearest_exact3d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional<double> scales_d, c10::optional<double> scales_h, c10::optional<double> scales_w, at::Tensor & grad_input);
24
+ TORCH_API at::Tensor & _upsample_nearest_exact3d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional<double> scales_d=c10::nullopt, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt);
25
+ TORCH_API at::Tensor & _upsample_nearest_exact3d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional<double> scales_d, c10::optional<double> scales_h, c10::optional<double> scales_w, at::Tensor & grad_input);
26
+
27
+ } // namespace cuda
28
+ } // namespace at
shared/package-files/02/021afcab2215adef14fc95512c72f405b4a86297498e8d8e51e135503e08d6dc/size_statistics.h ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <cstdint>
21
+ #include <iosfwd>
22
+ #include <optional>
23
+ #include <vector>
24
+
25
+ #include "arrow/util/span.h"
26
+ #include "parquet/platform.h"
27
+ #include "parquet/type_fwd.h"
28
+
29
+ namespace parquet {
30
+
31
+ /// A structure for capturing metadata for estimating the unencoded,
32
+ /// uncompressed size of data written. This is useful for readers to estimate
33
+ /// how much memory is needed to reconstruct data in their memory model and for
34
+ /// fine-grained filter push down on nested structures (the histograms contained
35
+ /// in this structure can help determine the number of nulls at a particular
36
+ /// nesting level and maximum length of lists).
37
+ struct PARQUET_EXPORT SizeStatistics {
38
+ /// When present, there is expected to be one element corresponding to each
39
+ /// definition (i.e. size=max definition+1) where each element
40
+ /// represents the number of times the definition level was observed in the
41
+ /// data.
42
+ ///
43
+ /// This field may be omitted (a.k.a. zero-length vector) if max_definition_level
44
+ /// is 0 without loss of information.
45
+ std::vector<int64_t> definition_level_histogram;
46
+
47
+ /// Same as definition_level_histogram except for repetition levels.
48
+ ///
49
+ /// This field may be omitted (a.k.a. zero-length vector) if max_repetition_level
50
+ /// is 0 without loss of information.
51
+ std::vector<int64_t> repetition_level_histogram;
52
+
53
+ /// The number of physical bytes stored for BYTE_ARRAY data values assuming
54
+ /// no encoding. This is exclusive of the bytes needed to store the length of
55
+ /// each byte array. In other words, this field is equivalent to the `(size
56
+ /// of PLAIN-ENCODING the byte array values) - (4 bytes * number of values
57
+ /// written)`. To determine unencoded sizes of other types readers can use
58
+ /// schema information multiplied by the number of non-null and null values.
59
+ /// The number of null/non-null values can be inferred from the histograms
60
+ /// below.
61
+ ///
62
+ /// For example, if a column chunk is dictionary-encoded with dictionary
63
+ /// ["a", "bc", "cde"], and a data page contains the indices [0, 0, 1, 2],
64
+ /// then this value for that data page should be 7 (1 + 1 + 2 + 3).
65
+ ///
66
+ /// This field should only be set for types that use BYTE_ARRAY as their
67
+ /// physical type.
68
+ std::optional<int64_t> unencoded_byte_array_data_bytes;
69
+
70
+ /// \brief Check if the SizeStatistics is set.
71
+ bool is_set() const {
72
+ return !repetition_level_histogram.empty() || !definition_level_histogram.empty() ||
73
+ unencoded_byte_array_data_bytes.has_value();
74
+ }
75
+
76
+ /// \brief Increment the unencoded byte array data bytes.
77
+ void IncrementUnencodedByteArrayDataBytes(int64_t value);
78
+
79
+ /// \brief Merge two SizeStatistics.
80
+ /// \throws ParquetException if SizeStatistics to merge is not compatible.
81
+ void Merge(const SizeStatistics& other);
82
+
83
+ /// \brief Validate the SizeStatistics
84
+ /// \throws ParquetException if the histograms don't have the right length,
85
+ /// or if unencoded_byte_array_data_bytes is present for a non-BYTE_ARRAY column.
86
+ void Validate(const ColumnDescriptor* descr) const;
87
+
88
+ /// \brief Reset the SizeStatistics to be empty.
89
+ void Reset();
90
+
91
+ /// \brief Make an empty SizeStatistics object for specific type.
92
+ static std::unique_ptr<SizeStatistics> Make(const ColumnDescriptor* descr);
93
+ };
94
+
95
+ PARQUET_EXPORT
96
+ std::ostream& operator<<(std::ostream&, const SizeStatistics&);
97
+
98
+ PARQUET_EXPORT
99
+ void UpdateLevelHistogram(::arrow::util::span<const int16_t> levels,
100
+ ::arrow::util::span<int64_t> histogram);
101
+
102
+ } // namespace parquet
shared/package-files/02/021bb387f2f520bdaa862561ad486d626a69305d3e0ebfd485e5c2a6dce6ff0b/mkldnn_rnn_layer_backward_cpu_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> mkldnn_rnn_layer_backward(const at::Tensor & input, const at::Tensor & weight1, const at::Tensor & weight2, const at::Tensor & weight3, const at::Tensor & weight4, const at::Tensor & hx_, const at::Tensor & cx_tmp, const at::Tensor & output, const at::Tensor & hy_, const at::Tensor & cy_, const c10::optional<at::Tensor> & grad_output, const c10::optional<at::Tensor> & grad_hy, const c10::optional<at::Tensor> & grad_cy, bool reverse, int64_t mode, int64_t hidden_size, int64_t num_layers, bool has_biases, bool train, bool bidirectional, at::IntArrayRef batch_sizes, bool batch_first, const at::Tensor & workspace);
21
+
22
+ } // namespace cpu
23
+ } // namespace at
shared/package-files/02/021e1390d23f09f62a49783b3454ff24e812e665b75d0c72fc2c266781c15c41/quantized_max_pool3d_compositeexplicitautograd_dispatch.h 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 & quantized_max_pool3d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride={}, at::IntArrayRef padding=0, at::IntArrayRef dilation=1, bool ceil_mode=false);
21
+ TORCH_API at::Tensor & quantized_max_pool3d_outf(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, at::Tensor & out);
22
+
23
+ } // namespace compositeexplicitautograd
24
+ } // namespace at
shared/package-files/02/021e1e444979d8be58ce9a7762466ff33564350d73bf7b38f2de2a075753c59a/_masked_scale_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor & _masked_scale_out(const at::Tensor & self, const at::Tensor & mask, double scale, at::Tensor & out);
20
+ TORCH_API at::Tensor masked_scale_cuda(const at::Tensor & self, const at::Tensor & mask, double scale);
21
+ } // namespace native
22
+ } // namespace at
shared/package-files/02/021e4cf393e96bccd818eb4b3a2cd6d20ce5b63b376f89c3e7aa8579047bf795/backend_cairo.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A Cairo backend for Matplotlib
3
+ ==============================
4
+ :Author: Steve Chaplin and others
5
+
6
+ This backend depends on cairocffi or pycairo.
7
+ """
8
+
9
+ import functools
10
+ import gzip
11
+ import math
12
+
13
+ import numpy as np
14
+
15
+ try:
16
+ import cairo
17
+ if cairo.version_info < (1, 14, 0): # Introduced set_device_scale.
18
+ raise ImportError(f"Cairo backend requires cairo>=1.14.0, "
19
+ f"but only {cairo.version_info} is available")
20
+ except ImportError:
21
+ try:
22
+ import cairocffi as cairo
23
+ except ImportError as err:
24
+ raise ImportError(
25
+ "cairo backend requires that pycairo>=1.14.0 or cairocffi "
26
+ "is installed") from err
27
+
28
+ from .. import _api, cbook, font_manager
29
+ from matplotlib.backend_bases import (
30
+ _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,
31
+ RendererBase)
32
+ from matplotlib.font_manager import ttfFontProperty
33
+ from matplotlib.path import Path
34
+ from matplotlib.transforms import Affine2D
35
+
36
+
37
+ def _set_rgba(ctx, color, alpha, forced_alpha):
38
+ if len(color) == 3 or forced_alpha:
39
+ ctx.set_source_rgba(*color[:3], alpha)
40
+ else:
41
+ ctx.set_source_rgba(*color)
42
+
43
+
44
+ def _append_path(ctx, path, transform, clip=None):
45
+ for points, code in path.iter_segments(
46
+ transform, remove_nans=True, clip=clip):
47
+ if code == Path.MOVETO:
48
+ ctx.move_to(*points)
49
+ elif code == Path.CLOSEPOLY:
50
+ ctx.close_path()
51
+ elif code == Path.LINETO:
52
+ ctx.line_to(*points)
53
+ elif code == Path.CURVE3:
54
+ cur = np.asarray(ctx.get_current_point())
55
+ a = points[:2]
56
+ b = points[-2:]
57
+ ctx.curve_to(*(cur / 3 + a * 2 / 3), *(a * 2 / 3 + b / 3), *b)
58
+ elif code == Path.CURVE4:
59
+ ctx.curve_to(*points)
60
+
61
+
62
+ def _cairo_font_args_from_font_prop(prop):
63
+ """
64
+ Convert a `.FontProperties` or a `.FontEntry` to arguments that can be
65
+ passed to `.Context.select_font_face`.
66
+ """
67
+ def attr(field):
68
+ try:
69
+ return getattr(prop, f"get_{field}")()
70
+ except AttributeError:
71
+ return getattr(prop, field)
72
+
73
+ name = attr("name")
74
+ slant = getattr(cairo, f"FONT_SLANT_{attr('style').upper()}")
75
+ weight = attr("weight")
76
+ weight = (cairo.FONT_WEIGHT_NORMAL
77
+ if font_manager.weight_dict.get(weight, weight) < 550
78
+ else cairo.FONT_WEIGHT_BOLD)
79
+ return name, slant, weight
80
+
81
+
82
+ class RendererCairo(RendererBase):
83
+ def __init__(self, dpi):
84
+ self.dpi = dpi
85
+ self.gc = GraphicsContextCairo(renderer=self)
86
+ self.width = None
87
+ self.height = None
88
+ self.text_ctx = cairo.Context(
89
+ cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
90
+ super().__init__()
91
+
92
+ def set_context(self, ctx):
93
+ surface = ctx.get_target()
94
+ if hasattr(surface, "get_width") and hasattr(surface, "get_height"):
95
+ size = surface.get_width(), surface.get_height()
96
+ elif hasattr(surface, "get_extents"): # GTK4 RecordingSurface.
97
+ ext = surface.get_extents()
98
+ size = ext.width, ext.height
99
+ else: # vector surfaces.
100
+ ctx.save()
101
+ ctx.reset_clip()
102
+ rect, *rest = ctx.copy_clip_rectangle_list()
103
+ if rest:
104
+ raise TypeError("Cannot infer surface size")
105
+ _, _, *size = rect
106
+ ctx.restore()
107
+ self.gc.ctx = ctx
108
+ self.width, self.height = size
109
+
110
+ @staticmethod
111
+ def _fill_and_stroke(ctx, fill_c, alpha, alpha_overrides):
112
+ if fill_c is not None:
113
+ ctx.save()
114
+ _set_rgba(ctx, fill_c, alpha, alpha_overrides)
115
+ ctx.fill_preserve()
116
+ ctx.restore()
117
+ ctx.stroke()
118
+
119
+ def draw_path(self, gc, path, transform, rgbFace=None):
120
+ # docstring inherited
121
+ ctx = gc.ctx
122
+ # Clip the path to the actual rendering extents if it isn't filled.
123
+ clip = (ctx.clip_extents()
124
+ if rgbFace is None and gc.get_hatch() is None
125
+ else None)
126
+ transform = (transform
127
+ + Affine2D().scale(1, -1).translate(0, self.height))
128
+ ctx.new_path()
129
+ _append_path(ctx, path, transform, clip)
130
+ if rgbFace is not None:
131
+ ctx.save()
132
+ _set_rgba(ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha())
133
+ ctx.fill_preserve()
134
+ ctx.restore()
135
+ hatch_path = gc.get_hatch_path()
136
+ if hatch_path:
137
+ dpi = int(self.dpi)
138
+ hatch_surface = ctx.get_target().create_similar(
139
+ cairo.Content.COLOR_ALPHA, dpi, dpi)
140
+ hatch_ctx = cairo.Context(hatch_surface)
141
+ _append_path(hatch_ctx, hatch_path,
142
+ Affine2D().scale(dpi, -dpi).translate(0, dpi),
143
+ None)
144
+ hatch_ctx.set_line_width(self.points_to_pixels(gc.get_hatch_linewidth()))
145
+ hatch_ctx.set_source_rgba(*gc.get_hatch_color())
146
+ hatch_ctx.fill_preserve()
147
+ hatch_ctx.stroke()
148
+ hatch_pattern = cairo.SurfacePattern(hatch_surface)
149
+ hatch_pattern.set_extend(cairo.Extend.REPEAT)
150
+ ctx.save()
151
+ ctx.set_source(hatch_pattern)
152
+ ctx.fill_preserve()
153
+ ctx.restore()
154
+ ctx.stroke()
155
+
156
+ def draw_markers(self, gc, marker_path, marker_trans, path, transform,
157
+ rgbFace=None):
158
+ # docstring inherited
159
+
160
+ ctx = gc.ctx
161
+ ctx.new_path()
162
+ # Create the path for the marker; it needs to be flipped here already!
163
+ _append_path(ctx, marker_path, marker_trans + Affine2D().scale(1, -1))
164
+ marker_path = ctx.copy_path_flat()
165
+
166
+ # Figure out whether the path has a fill
167
+ x1, y1, x2, y2 = ctx.fill_extents()
168
+ if x1 == 0 and y1 == 0 and x2 == 0 and y2 == 0:
169
+ filled = False
170
+ # No fill, just unset this (so we don't try to fill it later on)
171
+ rgbFace = None
172
+ else:
173
+ filled = True
174
+
175
+ transform = (transform
176
+ + Affine2D().scale(1, -1).translate(0, self.height))
177
+
178
+ ctx.new_path()
179
+ for i, (vertices, codes) in enumerate(
180
+ path.iter_segments(transform, simplify=False)):
181
+ if len(vertices):
182
+ x, y = vertices[-2:]
183
+ ctx.save()
184
+
185
+ # Translate and apply path
186
+ ctx.translate(x, y)
187
+ ctx.append_path(marker_path)
188
+
189
+ ctx.restore()
190
+
191
+ # Slower code path if there is a fill; we need to draw
192
+ # the fill and stroke for each marker at the same time.
193
+ # Also flush out the drawing every once in a while to
194
+ # prevent the paths from getting way too long.
195
+ if filled or i % 1000 == 0:
196
+ self._fill_and_stroke(
197
+ ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha())
198
+
199
+ # Fast path, if there is no fill, draw everything in one step
200
+ if not filled:
201
+ self._fill_and_stroke(
202
+ ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha())
203
+
204
+ def draw_image(self, gc, x, y, im):
205
+ im = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(im[::-1])
206
+ surface = cairo.ImageSurface.create_for_data(
207
+ im.ravel().data, cairo.FORMAT_ARGB32,
208
+ im.shape[1], im.shape[0], im.shape[1] * 4)
209
+ ctx = gc.ctx
210
+ y = self.height - y - im.shape[0]
211
+
212
+ ctx.save()
213
+ ctx.set_source_surface(surface, float(x), float(y))
214
+ ctx.paint()
215
+ ctx.restore()
216
+
217
+ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
218
+ # docstring inherited
219
+
220
+ # Note: (x, y) are device/display coords, not user-coords, unlike other
221
+ # draw_* methods
222
+ if ismath:
223
+ self._draw_mathtext(gc, x, y, s, prop, angle)
224
+
225
+ else:
226
+ ctx = gc.ctx
227
+ ctx.new_path()
228
+ ctx.move_to(x, y)
229
+
230
+ ctx.save()
231
+ ctx.select_font_face(*_cairo_font_args_from_font_prop(prop))
232
+ ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points()))
233
+ opts = cairo.FontOptions()
234
+ opts.set_antialias(gc.get_antialiased())
235
+ ctx.set_font_options(opts)
236
+ if angle:
237
+ ctx.rotate(np.deg2rad(-angle))
238
+ ctx.show_text(s)
239
+ ctx.restore()
240
+
241
+ def _draw_mathtext(self, gc, x, y, s, prop, angle):
242
+ ctx = gc.ctx
243
+ width, height, descent, glyphs, rects = \
244
+ self._text2path.mathtext_parser.parse(s, self.dpi, prop)
245
+
246
+ ctx.save()
247
+ ctx.translate(x, y)
248
+ if angle:
249
+ ctx.rotate(np.deg2rad(-angle))
250
+
251
+ for font, fontsize, idx, ox, oy in glyphs:
252
+ ctx.new_path()
253
+ ctx.move_to(ox, -oy)
254
+ ctx.select_font_face(
255
+ *_cairo_font_args_from_font_prop(ttfFontProperty(font)))
256
+ ctx.set_font_size(self.points_to_pixels(fontsize))
257
+ ctx.show_text(chr(idx))
258
+
259
+ for ox, oy, w, h in rects:
260
+ ctx.new_path()
261
+ ctx.rectangle(ox, -oy, w, -h)
262
+ ctx.set_source_rgb(0, 0, 0)
263
+ ctx.fill_preserve()
264
+
265
+ ctx.restore()
266
+
267
+ def get_canvas_width_height(self):
268
+ # docstring inherited
269
+ return self.width, self.height
270
+
271
+ def get_text_width_height_descent(self, s, prop, ismath):
272
+ # docstring inherited
273
+
274
+ if ismath == 'TeX':
275
+ return super().get_text_width_height_descent(s, prop, ismath)
276
+
277
+ if ismath:
278
+ width, height, descent, *_ = \
279
+ self._text2path.mathtext_parser.parse(s, self.dpi, prop)
280
+ return width, height, descent
281
+
282
+ ctx = self.text_ctx
283
+ # problem - scale remembers last setting and font can become
284
+ # enormous causing program to crash
285
+ # save/restore prevents the problem
286
+ ctx.save()
287
+ ctx.select_font_face(*_cairo_font_args_from_font_prop(prop))
288
+ ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points()))
289
+
290
+ y_bearing, w, h = ctx.text_extents(s)[1:4]
291
+ ctx.restore()
292
+
293
+ return w, h, h + y_bearing
294
+
295
+ def new_gc(self):
296
+ # docstring inherited
297
+ self.gc.ctx.save()
298
+ # FIXME: The following doesn't properly implement a stack-like behavior
299
+ # and relies instead on the (non-guaranteed) fact that artists never
300
+ # rely on nesting gc states, so directly resetting the attributes (IOW
301
+ # a single-level stack) is enough.
302
+ self.gc._alpha = 1
303
+ self.gc._forced_alpha = False # if True, _alpha overrides A from RGBA
304
+ self.gc._hatch = None
305
+ return self.gc
306
+
307
+ def points_to_pixels(self, points):
308
+ # docstring inherited
309
+ return points / 72 * self.dpi
310
+
311
+
312
+ class GraphicsContextCairo(GraphicsContextBase):
313
+ _joind = {
314
+ 'bevel': cairo.LINE_JOIN_BEVEL,
315
+ 'miter': cairo.LINE_JOIN_MITER,
316
+ 'round': cairo.LINE_JOIN_ROUND,
317
+ }
318
+
319
+ _capd = {
320
+ 'butt': cairo.LINE_CAP_BUTT,
321
+ 'projecting': cairo.LINE_CAP_SQUARE,
322
+ 'round': cairo.LINE_CAP_ROUND,
323
+ }
324
+
325
+ def __init__(self, renderer):
326
+ super().__init__()
327
+ self.renderer = renderer
328
+
329
+ def restore(self):
330
+ self.ctx.restore()
331
+
332
+ def set_alpha(self, alpha):
333
+ super().set_alpha(alpha)
334
+ _set_rgba(
335
+ self.ctx, self._rgb, self.get_alpha(), self.get_forced_alpha())
336
+
337
+ def set_antialiased(self, b):
338
+ self.ctx.set_antialias(
339
+ cairo.ANTIALIAS_DEFAULT if b else cairo.ANTIALIAS_NONE)
340
+
341
+ def get_antialiased(self):
342
+ return self.ctx.get_antialias()
343
+
344
+ def set_capstyle(self, cs):
345
+ self.ctx.set_line_cap(_api.check_getitem(self._capd, capstyle=cs))
346
+ self._capstyle = cs
347
+
348
+ def set_clip_rectangle(self, rectangle):
349
+ if not rectangle:
350
+ return
351
+ x, y, w, h = np.round(rectangle.bounds)
352
+ ctx = self.ctx
353
+ ctx.new_path()
354
+ ctx.rectangle(x, self.renderer.height - h - y, w, h)
355
+ ctx.clip()
356
+
357
+ def set_clip_path(self, path):
358
+ if not path:
359
+ return
360
+ tpath, affine = path.get_transformed_path_and_affine()
361
+ ctx = self.ctx
362
+ ctx.new_path()
363
+ affine = (affine
364
+ + Affine2D().scale(1, -1).translate(0, self.renderer.height))
365
+ _append_path(ctx, tpath, affine)
366
+ ctx.clip()
367
+
368
+ def set_dashes(self, offset, dashes):
369
+ self._dashes = offset, dashes
370
+ if dashes is None:
371
+ self.ctx.set_dash([], 0) # switch dashes off
372
+ else:
373
+ self.ctx.set_dash(
374
+ list(self.renderer.points_to_pixels(np.asarray(dashes))),
375
+ offset)
376
+
377
+ def set_foreground(self, fg, isRGBA=None):
378
+ super().set_foreground(fg, isRGBA)
379
+ if len(self._rgb) == 3:
380
+ self.ctx.set_source_rgb(*self._rgb)
381
+ else:
382
+ self.ctx.set_source_rgba(*self._rgb)
383
+
384
+ def get_rgb(self):
385
+ return self.ctx.get_source().get_rgba()[:3]
386
+
387
+ def set_joinstyle(self, js):
388
+ self.ctx.set_line_join(_api.check_getitem(self._joind, joinstyle=js))
389
+ self._joinstyle = js
390
+
391
+ def set_linewidth(self, w):
392
+ self._linewidth = float(w)
393
+ self.ctx.set_line_width(self.renderer.points_to_pixels(w))
394
+
395
+
396
+ class _CairoRegion:
397
+ def __init__(self, slices, data):
398
+ self._slices = slices
399
+ self._data = data
400
+
401
+
402
+ class FigureCanvasCairo(FigureCanvasBase):
403
+ @property
404
+ def _renderer(self):
405
+ # In theory, _renderer should be set in __init__, but GUI canvas
406
+ # subclasses (FigureCanvasFooCairo) don't always interact well with
407
+ # multiple inheritance (FigureCanvasFoo inits but doesn't super-init
408
+ # FigureCanvasCairo), so initialize it in the getter instead.
409
+ if not hasattr(self, "_cached_renderer"):
410
+ self._cached_renderer = RendererCairo(self.figure.dpi)
411
+ return self._cached_renderer
412
+
413
+ def get_renderer(self):
414
+ return self._renderer
415
+
416
+ def copy_from_bbox(self, bbox):
417
+ surface = self._renderer.gc.ctx.get_target()
418
+ if not isinstance(surface, cairo.ImageSurface):
419
+ raise RuntimeError(
420
+ "copy_from_bbox only works when rendering to an ImageSurface")
421
+ sw = surface.get_width()
422
+ sh = surface.get_height()
423
+ x0 = math.ceil(bbox.x0)
424
+ x1 = math.floor(bbox.x1)
425
+ y0 = math.ceil(sh - bbox.y1)
426
+ y1 = math.floor(sh - bbox.y0)
427
+ if not (0 <= x0 and x1 <= sw and bbox.x0 <= bbox.x1
428
+ and 0 <= y0 and y1 <= sh and bbox.y0 <= bbox.y1):
429
+ raise ValueError("Invalid bbox")
430
+ sls = slice(y0, y0 + max(y1 - y0, 0)), slice(x0, x0 + max(x1 - x0, 0))
431
+ data = (np.frombuffer(surface.get_data(), np.uint32)
432
+ .reshape((sh, sw))[sls].copy())
433
+ return _CairoRegion(sls, data)
434
+
435
+ def restore_region(self, region):
436
+ surface = self._renderer.gc.ctx.get_target()
437
+ if not isinstance(surface, cairo.ImageSurface):
438
+ raise RuntimeError(
439
+ "restore_region only works when rendering to an ImageSurface")
440
+ surface.flush()
441
+ sw = surface.get_width()
442
+ sh = surface.get_height()
443
+ sly, slx = region._slices
444
+ (np.frombuffer(surface.get_data(), np.uint32)
445
+ .reshape((sh, sw))[sly, slx]) = region._data
446
+ surface.mark_dirty_rectangle(
447
+ slx.start, sly.start, slx.stop - slx.start, sly.stop - sly.start)
448
+
449
+ def print_png(self, fobj):
450
+ self._get_printed_image_surface().write_to_png(fobj)
451
+
452
+ def print_rgba(self, fobj):
453
+ width, height = self.get_width_height()
454
+ buf = self._get_printed_image_surface().get_data()
455
+ fobj.write(cbook._premultiplied_argb32_to_unmultiplied_rgba8888(
456
+ np.asarray(buf).reshape((width, height, 4))))
457
+
458
+ print_raw = print_rgba
459
+
460
+ def _get_printed_image_surface(self):
461
+ self._renderer.dpi = self.figure.dpi
462
+ width, height = self.get_width_height()
463
+ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
464
+ self._renderer.set_context(cairo.Context(surface))
465
+ self.figure.draw(self._renderer)
466
+ return surface
467
+
468
+ def _save(self, fmt, fobj, *, orientation='portrait'):
469
+ # save PDF/PS/SVG
470
+
471
+ dpi = 72
472
+ self.figure.dpi = dpi
473
+ w_in, h_in = self.figure.get_size_inches()
474
+ width_in_points, height_in_points = w_in * dpi, h_in * dpi
475
+
476
+ if orientation == 'landscape':
477
+ width_in_points, height_in_points = (
478
+ height_in_points, width_in_points)
479
+
480
+ if fmt == 'ps':
481
+ if not hasattr(cairo, 'PSSurface'):
482
+ raise RuntimeError('cairo has not been compiled with PS '
483
+ 'support enabled')
484
+ surface = cairo.PSSurface(fobj, width_in_points, height_in_points)
485
+ elif fmt == 'pdf':
486
+ if not hasattr(cairo, 'PDFSurface'):
487
+ raise RuntimeError('cairo has not been compiled with PDF '
488
+ 'support enabled')
489
+ surface = cairo.PDFSurface(fobj, width_in_points, height_in_points)
490
+ elif fmt in ('svg', 'svgz'):
491
+ if not hasattr(cairo, 'SVGSurface'):
492
+ raise RuntimeError('cairo has not been compiled with SVG '
493
+ 'support enabled')
494
+ if fmt == 'svgz':
495
+ if isinstance(fobj, str):
496
+ fobj = gzip.GzipFile(fobj, 'wb')
497
+ else:
498
+ fobj = gzip.GzipFile(None, 'wb', fileobj=fobj)
499
+ surface = cairo.SVGSurface(fobj, width_in_points, height_in_points)
500
+ else:
501
+ raise ValueError(f"Unknown format: {fmt!r}")
502
+
503
+ self._renderer.dpi = self.figure.dpi
504
+ self._renderer.set_context(cairo.Context(surface))
505
+ ctx = self._renderer.gc.ctx
506
+
507
+ if orientation == 'landscape':
508
+ ctx.rotate(np.pi / 2)
509
+ ctx.translate(0, -height_in_points)
510
+ # Perhaps add an '%%Orientation: Landscape' comment?
511
+
512
+ self.figure.draw(self._renderer)
513
+
514
+ ctx.show_page()
515
+ surface.finish()
516
+ if fmt == 'svgz':
517
+ fobj.close()
518
+
519
+ print_pdf = functools.partialmethod(_save, "pdf")
520
+ print_ps = functools.partialmethod(_save, "ps")
521
+ print_svg = functools.partialmethod(_save, "svg")
522
+ print_svgz = functools.partialmethod(_save, "svgz")
523
+
524
+
525
+ @_Backend.export
526
+ class _BackendCairo(_Backend):
527
+ backend_version = cairo.version
528
+ FigureCanvas = FigureCanvasCairo
529
+ FigureManager = FigureManagerBase
shared/package-files/02/021f73fada072546c4f63f8cf18a7181244ce4280b09cc15cc980b2d1176171a/error.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ __all__ = ['Mark', 'YAMLError', 'MarkedYAMLError']
3
+
4
+ class Mark:
5
+
6
+ def __init__(self, name, index, line, column, buffer, pointer):
7
+ self.name = name
8
+ self.index = index
9
+ self.line = line
10
+ self.column = column
11
+ self.buffer = buffer
12
+ self.pointer = pointer
13
+
14
+ def get_snippet(self, indent=4, max_length=75):
15
+ if self.buffer is None:
16
+ return None
17
+ head = ''
18
+ start = self.pointer
19
+ while start > 0 and self.buffer[start-1] not in '\0\r\n\x85\u2028\u2029':
20
+ start -= 1
21
+ if self.pointer-start > max_length/2-1:
22
+ head = ' ... '
23
+ start += 5
24
+ break
25
+ tail = ''
26
+ end = self.pointer
27
+ while end < len(self.buffer) and self.buffer[end] not in '\0\r\n\x85\u2028\u2029':
28
+ end += 1
29
+ if end-self.pointer > max_length/2-1:
30
+ tail = ' ... '
31
+ end -= 5
32
+ break
33
+ snippet = self.buffer[start:end]
34
+ return ' '*indent + head + snippet + tail + '\n' \
35
+ + ' '*(indent+self.pointer-start+len(head)) + '^'
36
+
37
+ def __str__(self):
38
+ snippet = self.get_snippet()
39
+ where = " in \"%s\", line %d, column %d" \
40
+ % (self.name, self.line+1, self.column+1)
41
+ if snippet is not None:
42
+ where += ":\n"+snippet
43
+ return where
44
+
45
+ class YAMLError(Exception):
46
+ pass
47
+
48
+ class MarkedYAMLError(YAMLError):
49
+
50
+ def __init__(self, context=None, context_mark=None,
51
+ problem=None, problem_mark=None, note=None):
52
+ self.context = context
53
+ self.context_mark = context_mark
54
+ self.problem = problem
55
+ self.problem_mark = problem_mark
56
+ self.note = note
57
+
58
+ def __str__(self):
59
+ lines = []
60
+ if self.context is not None:
61
+ lines.append(self.context)
62
+ if self.context_mark is not None \
63
+ and (self.problem is None or self.problem_mark is None
64
+ or self.context_mark.name != self.problem_mark.name
65
+ or self.context_mark.line != self.problem_mark.line
66
+ or self.context_mark.column != self.problem_mark.column):
67
+ lines.append(str(self.context_mark))
68
+ if self.problem is not None:
69
+ lines.append(self.problem)
70
+ if self.problem_mark is not None:
71
+ lines.append(str(self.problem_mark))
72
+ if self.note is not None:
73
+ lines.append(self.note)
74
+ return '\n'.join(lines)
75
+
shared/package-files/02/0223395091042ca6c5c86ee83cada3b566d89860bb258b345898f2fb59340836/ntconsole-35-nti ADDED
Binary file (1.45 kB). View file
 
shared/package-files/02/0223395091042ca6c5c86ee83cada3b566d89860bb258b345898f2fb59340836/opennt-35-nti ADDED
Binary file (1.45 kB). View file
 
shared/package-files/02/02244e7d6c5346b313ef92d9b2b04c25322cde4cbd9f5c779d49d7ccaa5920b3/html.py ADDED
@@ -0,0 +1,646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module for formatting output data in HTML.
3
+ """
4
+ from __future__ import annotations
5
+
6
+ from textwrap import dedent
7
+ from typing import (
8
+ TYPE_CHECKING,
9
+ Any,
10
+ Final,
11
+ cast,
12
+ )
13
+
14
+ from pandas._config import get_option
15
+
16
+ from pandas._libs import lib
17
+
18
+ from pandas import (
19
+ MultiIndex,
20
+ option_context,
21
+ )
22
+
23
+ from pandas.io.common import is_url
24
+ from pandas.io.formats.format import (
25
+ DataFrameFormatter,
26
+ get_level_lengths,
27
+ )
28
+ from pandas.io.formats.printing import pprint_thing
29
+
30
+ if TYPE_CHECKING:
31
+ from collections.abc import (
32
+ Hashable,
33
+ Iterable,
34
+ Mapping,
35
+ )
36
+
37
+
38
+ class HTMLFormatter:
39
+ """
40
+ Internal class for formatting output data in html.
41
+ This class is intended for shared functionality between
42
+ DataFrame.to_html() and DataFrame._repr_html_().
43
+ Any logic in common with other output formatting methods
44
+ should ideally be inherited from classes in format.py
45
+ and this class responsible for only producing html markup.
46
+ """
47
+
48
+ indent_delta: Final = 2
49
+
50
+ def __init__(
51
+ self,
52
+ formatter: DataFrameFormatter,
53
+ classes: str | list[str] | tuple[str, ...] | None = None,
54
+ border: int | bool | None = None,
55
+ table_id: str | None = None,
56
+ render_links: bool = False,
57
+ ) -> None:
58
+ self.fmt = formatter
59
+ self.classes = classes
60
+
61
+ self.frame = self.fmt.frame
62
+ self.columns = self.fmt.tr_frame.columns
63
+ self.elements: list[str] = []
64
+ self.bold_rows = self.fmt.bold_rows
65
+ self.escape = self.fmt.escape
66
+ self.show_dimensions = self.fmt.show_dimensions
67
+ if border is None or border is True:
68
+ border = cast(int, get_option("display.html.border"))
69
+ elif not border:
70
+ border = None
71
+
72
+ self.border = border
73
+ self.table_id = table_id
74
+ self.render_links = render_links
75
+
76
+ self.col_space = {}
77
+ is_multi_index = isinstance(self.columns, MultiIndex)
78
+ for column, value in self.fmt.col_space.items():
79
+ col_space_value = f"{value}px" if isinstance(value, int) else value
80
+ self.col_space[column] = col_space_value
81
+ # GH 53885: Handling case where column is index
82
+ # Flatten the data in the multi index and add in the map
83
+ if is_multi_index and isinstance(column, tuple):
84
+ for column_index in column:
85
+ self.col_space[str(column_index)] = col_space_value
86
+
87
+ def to_string(self) -> str:
88
+ lines = self.render()
89
+ if any(isinstance(x, str) for x in lines):
90
+ lines = [str(x) for x in lines]
91
+ return "\n".join(lines)
92
+
93
+ def render(self) -> list[str]:
94
+ self._write_table()
95
+
96
+ if self.should_show_dimensions:
97
+ by = chr(215) # × # noqa: RUF003
98
+ self.write(
99
+ f"<p>{len(self.frame)} rows {by} {len(self.frame.columns)} columns</p>"
100
+ )
101
+
102
+ return self.elements
103
+
104
+ @property
105
+ def should_show_dimensions(self) -> bool:
106
+ return self.fmt.should_show_dimensions
107
+
108
+ @property
109
+ def show_row_idx_names(self) -> bool:
110
+ return self.fmt.show_row_idx_names
111
+
112
+ @property
113
+ def show_col_idx_names(self) -> bool:
114
+ return self.fmt.show_col_idx_names
115
+
116
+ @property
117
+ def row_levels(self) -> int:
118
+ if self.fmt.index:
119
+ # showing (row) index
120
+ return self.frame.index.nlevels
121
+ elif self.show_col_idx_names:
122
+ # see gh-22579
123
+ # Column misalignment also occurs for
124
+ # a standard index when the columns index is named.
125
+ # If the row index is not displayed a column of
126
+ # blank cells need to be included before the DataFrame values.
127
+ return 1
128
+ # not showing (row) index
129
+ return 0
130
+
131
+ def _get_columns_formatted_values(self) -> Iterable:
132
+ return self.columns
133
+
134
+ @property
135
+ def is_truncated(self) -> bool:
136
+ return self.fmt.is_truncated
137
+
138
+ @property
139
+ def ncols(self) -> int:
140
+ return len(self.fmt.tr_frame.columns)
141
+
142
+ def write(self, s: Any, indent: int = 0) -> None:
143
+ rs = pprint_thing(s)
144
+ self.elements.append(" " * indent + rs)
145
+
146
+ def write_th(
147
+ self, s: Any, header: bool = False, indent: int = 0, tags: str | None = None
148
+ ) -> None:
149
+ """
150
+ Method for writing a formatted <th> cell.
151
+
152
+ If col_space is set on the formatter then that is used for
153
+ the value of min-width.
154
+
155
+ Parameters
156
+ ----------
157
+ s : object
158
+ The data to be written inside the cell.
159
+ header : bool, default False
160
+ Set to True if the <th> is for use inside <thead>. This will
161
+ cause min-width to be set if there is one.
162
+ indent : int, default 0
163
+ The indentation level of the cell.
164
+ tags : str, default None
165
+ Tags to include in the cell.
166
+
167
+ Returns
168
+ -------
169
+ A written <th> cell.
170
+ """
171
+ col_space = self.col_space.get(s, None)
172
+
173
+ if header and col_space is not None:
174
+ tags = tags or ""
175
+ tags += f'style="min-width: {col_space};"'
176
+
177
+ self._write_cell(s, kind="th", indent=indent, tags=tags)
178
+
179
+ def write_td(self, s: Any, indent: int = 0, tags: str | None = None) -> None:
180
+ self._write_cell(s, kind="td", indent=indent, tags=tags)
181
+
182
+ def _write_cell(
183
+ self, s: Any, kind: str = "td", indent: int = 0, tags: str | None = None
184
+ ) -> None:
185
+ if tags is not None:
186
+ start_tag = f"<{kind} {tags}>"
187
+ else:
188
+ start_tag = f"<{kind}>"
189
+
190
+ if self.escape:
191
+ # escape & first to prevent double escaping of &
192
+ esc = {"&": r"&amp;", "<": r"&lt;", ">": r"&gt;"}
193
+ else:
194
+ esc = {}
195
+
196
+ rs = pprint_thing(s, escape_chars=esc).strip()
197
+
198
+ if self.render_links and is_url(rs):
199
+ rs_unescaped = pprint_thing(s, escape_chars={}).strip()
200
+ start_tag += f'<a href="{rs_unescaped}" target="_blank">'
201
+ end_a = "</a>"
202
+ else:
203
+ end_a = ""
204
+
205
+ self.write(f"{start_tag}{rs}{end_a}</{kind}>", indent)
206
+
207
+ def write_tr(
208
+ self,
209
+ line: Iterable,
210
+ indent: int = 0,
211
+ indent_delta: int = 0,
212
+ header: bool = False,
213
+ align: str | None = None,
214
+ tags: dict[int, str] | None = None,
215
+ nindex_levels: int = 0,
216
+ ) -> None:
217
+ if tags is None:
218
+ tags = {}
219
+
220
+ if align is None:
221
+ self.write("<tr>", indent)
222
+ else:
223
+ self.write(f'<tr style="text-align: {align};">', indent)
224
+ indent += indent_delta
225
+
226
+ for i, s in enumerate(line):
227
+ val_tag = tags.get(i, None)
228
+ if header or (self.bold_rows and i < nindex_levels):
229
+ self.write_th(s, indent=indent, header=header, tags=val_tag)
230
+ else:
231
+ self.write_td(s, indent, tags=val_tag)
232
+
233
+ indent -= indent_delta
234
+ self.write("</tr>", indent)
235
+
236
+ def _write_table(self, indent: int = 0) -> None:
237
+ _classes = ["dataframe"] # Default class.
238
+ use_mathjax = get_option("display.html.use_mathjax")
239
+ if not use_mathjax:
240
+ _classes.append("tex2jax_ignore")
241
+ if self.classes is not None:
242
+ if isinstance(self.classes, str):
243
+ self.classes = self.classes.split()
244
+ if not isinstance(self.classes, (list, tuple)):
245
+ raise TypeError(
246
+ "classes must be a string, list, "
247
+ f"or tuple, not {type(self.classes)}"
248
+ )
249
+ _classes.extend(self.classes)
250
+
251
+ if self.table_id is None:
252
+ id_section = ""
253
+ else:
254
+ id_section = f' id="{self.table_id}"'
255
+
256
+ if self.border is None:
257
+ border_attr = ""
258
+ else:
259
+ border_attr = f' border="{self.border}"'
260
+
261
+ self.write(
262
+ f'<table{border_attr} class="{" ".join(_classes)}"{id_section}>',
263
+ indent,
264
+ )
265
+
266
+ if self.fmt.header or self.show_row_idx_names:
267
+ self._write_header(indent + self.indent_delta)
268
+
269
+ self._write_body(indent + self.indent_delta)
270
+
271
+ self.write("</table>", indent)
272
+
273
+ def _write_col_header(self, indent: int) -> None:
274
+ row: list[Hashable]
275
+ is_truncated_horizontally = self.fmt.is_truncated_horizontally
276
+ if isinstance(self.columns, MultiIndex):
277
+ template = 'colspan="{span:d}" halign="left"'
278
+
279
+ sentinel: lib.NoDefault | bool
280
+ if self.fmt.sparsify:
281
+ # GH3547
282
+ sentinel = lib.no_default
283
+ else:
284
+ sentinel = False
285
+ levels = self.columns._format_multi(sparsify=sentinel, include_names=False)
286
+ level_lengths = get_level_lengths(levels, sentinel)
287
+ inner_lvl = len(level_lengths) - 1
288
+ for lnum, (records, values) in enumerate(zip(level_lengths, levels)):
289
+ if is_truncated_horizontally:
290
+ # modify the header lines
291
+ ins_col = self.fmt.tr_col_num
292
+ if self.fmt.sparsify:
293
+ recs_new = {}
294
+ # Increment tags after ... col.
295
+ for tag, span in list(records.items()):
296
+ if tag >= ins_col:
297
+ recs_new[tag + 1] = span
298
+ elif tag + span > ins_col:
299
+ recs_new[tag] = span + 1
300
+ if lnum == inner_lvl:
301
+ values = (
302
+ values[:ins_col] + ("...",) + values[ins_col:]
303
+ )
304
+ else:
305
+ # sparse col headers do not receive a ...
306
+ values = (
307
+ values[:ins_col]
308
+ + (values[ins_col - 1],)
309
+ + values[ins_col:]
310
+ )
311
+ else:
312
+ recs_new[tag] = span
313
+ # if ins_col lies between tags, all col headers
314
+ # get ...
315
+ if tag + span == ins_col:
316
+ recs_new[ins_col] = 1
317
+ values = values[:ins_col] + ("...",) + values[ins_col:]
318
+ records = recs_new
319
+ inner_lvl = len(level_lengths) - 1
320
+ if lnum == inner_lvl:
321
+ records[ins_col] = 1
322
+ else:
323
+ recs_new = {}
324
+ for tag, span in list(records.items()):
325
+ if tag >= ins_col:
326
+ recs_new[tag + 1] = span
327
+ else:
328
+ recs_new[tag] = span
329
+ recs_new[ins_col] = 1
330
+ records = recs_new
331
+ values = values[:ins_col] + ["..."] + values[ins_col:]
332
+
333
+ # see gh-22579
334
+ # Column Offset Bug with to_html(index=False) with
335
+ # MultiIndex Columns and Index.
336
+ # Initially fill row with blank cells before column names.
337
+ # TODO: Refactor to remove code duplication with code
338
+ # block below for standard columns index.
339
+ row = [""] * (self.row_levels - 1)
340
+ if self.fmt.index or self.show_col_idx_names:
341
+ # see gh-22747
342
+ # If to_html(index_names=False) do not show columns
343
+ # index names.
344
+ # TODO: Refactor to use _get_column_name_list from
345
+ # DataFrameFormatter class and create a
346
+ # _get_formatted_column_labels function for code
347
+ # parity with DataFrameFormatter class.
348
+ if self.fmt.show_index_names:
349
+ name = self.columns.names[lnum]
350
+ row.append(pprint_thing(name or ""))
351
+ else:
352
+ row.append("")
353
+
354
+ tags = {}
355
+ j = len(row)
356
+ for i, v in enumerate(values):
357
+ if i in records:
358
+ if records[i] > 1:
359
+ tags[j] = template.format(span=records[i])
360
+ else:
361
+ continue
362
+ j += 1
363
+ row.append(v)
364
+ self.write_tr(row, indent, self.indent_delta, tags=tags, header=True)
365
+ else:
366
+ # see gh-22579
367
+ # Column misalignment also occurs for
368
+ # a standard index when the columns index is named.
369
+ # Initially fill row with blank cells before column names.
370
+ # TODO: Refactor to remove code duplication with code block
371
+ # above for columns MultiIndex.
372
+ row = [""] * (self.row_levels - 1)
373
+ if self.fmt.index or self.show_col_idx_names:
374
+ # see gh-22747
375
+ # If to_html(index_names=False) do not show columns
376
+ # index names.
377
+ # TODO: Refactor to use _get_column_name_list from
378
+ # DataFrameFormatter class.
379
+ if self.fmt.show_index_names:
380
+ row.append(self.columns.name or "")
381
+ else:
382
+ row.append("")
383
+ row.extend(self._get_columns_formatted_values())
384
+ align = self.fmt.justify
385
+
386
+ if is_truncated_horizontally:
387
+ ins_col = self.row_levels + self.fmt.tr_col_num
388
+ row.insert(ins_col, "...")
389
+
390
+ self.write_tr(row, indent, self.indent_delta, header=True, align=align)
391
+
392
+ def _write_row_header(self, indent: int) -> None:
393
+ is_truncated_horizontally = self.fmt.is_truncated_horizontally
394
+ row = [x if x is not None else "" for x in self.frame.index.names] + [""] * (
395
+ self.ncols + (1 if is_truncated_horizontally else 0)
396
+ )
397
+ self.write_tr(row, indent, self.indent_delta, header=True)
398
+
399
+ def _write_header(self, indent: int) -> None:
400
+ self.write("<thead>", indent)
401
+
402
+ if self.fmt.header:
403
+ self._write_col_header(indent + self.indent_delta)
404
+
405
+ if self.show_row_idx_names:
406
+ self._write_row_header(indent + self.indent_delta)
407
+
408
+ self.write("</thead>", indent)
409
+
410
+ def _get_formatted_values(self) -> dict[int, list[str]]:
411
+ with option_context("display.max_colwidth", None):
412
+ fmt_values = {i: self.fmt.format_col(i) for i in range(self.ncols)}
413
+ return fmt_values
414
+
415
+ def _write_body(self, indent: int) -> None:
416
+ self.write("<tbody>", indent)
417
+ fmt_values = self._get_formatted_values()
418
+
419
+ # write values
420
+ if self.fmt.index and isinstance(self.frame.index, MultiIndex):
421
+ self._write_hierarchical_rows(fmt_values, indent + self.indent_delta)
422
+ else:
423
+ self._write_regular_rows(fmt_values, indent + self.indent_delta)
424
+
425
+ self.write("</tbody>", indent)
426
+
427
+ def _write_regular_rows(
428
+ self, fmt_values: Mapping[int, list[str]], indent: int
429
+ ) -> None:
430
+ is_truncated_horizontally = self.fmt.is_truncated_horizontally
431
+ is_truncated_vertically = self.fmt.is_truncated_vertically
432
+
433
+ nrows = len(self.fmt.tr_frame)
434
+
435
+ if self.fmt.index:
436
+ fmt = self.fmt._get_formatter("__index__")
437
+ if fmt is not None:
438
+ index_values = self.fmt.tr_frame.index.map(fmt)
439
+ else:
440
+ # only reached with non-Multi index
441
+ index_values = self.fmt.tr_frame.index._format_flat(include_name=False)
442
+
443
+ row: list[str] = []
444
+ for i in range(nrows):
445
+ if is_truncated_vertically and i == (self.fmt.tr_row_num):
446
+ str_sep_row = ["..."] * len(row)
447
+ self.write_tr(
448
+ str_sep_row,
449
+ indent,
450
+ self.indent_delta,
451
+ tags=None,
452
+ nindex_levels=self.row_levels,
453
+ )
454
+
455
+ row = []
456
+ if self.fmt.index:
457
+ row.append(index_values[i])
458
+ # see gh-22579
459
+ # Column misalignment also occurs for
460
+ # a standard index when the columns index is named.
461
+ # Add blank cell before data cells.
462
+ elif self.show_col_idx_names:
463
+ row.append("")
464
+ row.extend(fmt_values[j][i] for j in range(self.ncols))
465
+
466
+ if is_truncated_horizontally:
467
+ dot_col_ix = self.fmt.tr_col_num + self.row_levels
468
+ row.insert(dot_col_ix, "...")
469
+ self.write_tr(
470
+ row, indent, self.indent_delta, tags=None, nindex_levels=self.row_levels
471
+ )
472
+
473
+ def _write_hierarchical_rows(
474
+ self, fmt_values: Mapping[int, list[str]], indent: int
475
+ ) -> None:
476
+ template = 'rowspan="{span}" valign="top"'
477
+
478
+ is_truncated_horizontally = self.fmt.is_truncated_horizontally
479
+ is_truncated_vertically = self.fmt.is_truncated_vertically
480
+ frame = self.fmt.tr_frame
481
+ nrows = len(frame)
482
+
483
+ assert isinstance(frame.index, MultiIndex)
484
+ idx_values = frame.index._format_multi(sparsify=False, include_names=False)
485
+ idx_values = list(zip(*idx_values))
486
+
487
+ if self.fmt.sparsify:
488
+ # GH3547
489
+ sentinel = lib.no_default
490
+ levels = frame.index._format_multi(sparsify=sentinel, include_names=False)
491
+
492
+ level_lengths = get_level_lengths(levels, sentinel)
493
+ inner_lvl = len(level_lengths) - 1
494
+ if is_truncated_vertically:
495
+ # Insert ... row and adjust idx_values and
496
+ # level_lengths to take this into account.
497
+ ins_row = self.fmt.tr_row_num
498
+ inserted = False
499
+ for lnum, records in enumerate(level_lengths):
500
+ rec_new = {}
501
+ for tag, span in list(records.items()):
502
+ if tag >= ins_row:
503
+ rec_new[tag + 1] = span
504
+ elif tag + span > ins_row:
505
+ rec_new[tag] = span + 1
506
+
507
+ # GH 14882 - Make sure insertion done once
508
+ if not inserted:
509
+ dot_row = list(idx_values[ins_row - 1])
510
+ dot_row[-1] = "..."
511
+ idx_values.insert(ins_row, tuple(dot_row))
512
+ inserted = True
513
+ else:
514
+ dot_row = list(idx_values[ins_row])
515
+ dot_row[inner_lvl - lnum] = "..."
516
+ idx_values[ins_row] = tuple(dot_row)
517
+ else:
518
+ rec_new[tag] = span
519
+ # If ins_row lies between tags, all cols idx cols
520
+ # receive ...
521
+ if tag + span == ins_row:
522
+ rec_new[ins_row] = 1
523
+ if lnum == 0:
524
+ idx_values.insert(
525
+ ins_row, tuple(["..."] * len(level_lengths))
526
+ )
527
+
528
+ # GH 14882 - Place ... in correct level
529
+ elif inserted:
530
+ dot_row = list(idx_values[ins_row])
531
+ dot_row[inner_lvl - lnum] = "..."
532
+ idx_values[ins_row] = tuple(dot_row)
533
+ level_lengths[lnum] = rec_new
534
+
535
+ level_lengths[inner_lvl][ins_row] = 1
536
+ for ix_col in fmt_values:
537
+ fmt_values[ix_col].insert(ins_row, "...")
538
+ nrows += 1
539
+
540
+ for i in range(nrows):
541
+ row = []
542
+ tags = {}
543
+
544
+ sparse_offset = 0
545
+ j = 0
546
+ for records, v in zip(level_lengths, idx_values[i]):
547
+ if i in records:
548
+ if records[i] > 1:
549
+ tags[j] = template.format(span=records[i])
550
+ else:
551
+ sparse_offset += 1
552
+ continue
553
+
554
+ j += 1
555
+ row.append(v)
556
+
557
+ row.extend(fmt_values[j][i] for j in range(self.ncols))
558
+ if is_truncated_horizontally:
559
+ row.insert(
560
+ self.row_levels - sparse_offset + self.fmt.tr_col_num, "..."
561
+ )
562
+ self.write_tr(
563
+ row,
564
+ indent,
565
+ self.indent_delta,
566
+ tags=tags,
567
+ nindex_levels=len(levels) - sparse_offset,
568
+ )
569
+ else:
570
+ row = []
571
+ for i in range(len(frame)):
572
+ if is_truncated_vertically and i == (self.fmt.tr_row_num):
573
+ str_sep_row = ["..."] * len(row)
574
+ self.write_tr(
575
+ str_sep_row,
576
+ indent,
577
+ self.indent_delta,
578
+ tags=None,
579
+ nindex_levels=self.row_levels,
580
+ )
581
+
582
+ idx_values = list(
583
+ zip(*frame.index._format_multi(sparsify=False, include_names=False))
584
+ )
585
+ row = []
586
+ row.extend(idx_values[i])
587
+ row.extend(fmt_values[j][i] for j in range(self.ncols))
588
+ if is_truncated_horizontally:
589
+ row.insert(self.row_levels + self.fmt.tr_col_num, "...")
590
+ self.write_tr(
591
+ row,
592
+ indent,
593
+ self.indent_delta,
594
+ tags=None,
595
+ nindex_levels=frame.index.nlevels,
596
+ )
597
+
598
+
599
+ class NotebookFormatter(HTMLFormatter):
600
+ """
601
+ Internal class for formatting output data in html for display in Jupyter
602
+ Notebooks. This class is intended for functionality specific to
603
+ DataFrame._repr_html_() and DataFrame.to_html(notebook=True)
604
+ """
605
+
606
+ def _get_formatted_values(self) -> dict[int, list[str]]:
607
+ return {i: self.fmt.format_col(i) for i in range(self.ncols)}
608
+
609
+ def _get_columns_formatted_values(self) -> list[str]:
610
+ # only reached with non-Multi Index
611
+ return self.columns._format_flat(include_name=False)
612
+
613
+ def write_style(self) -> None:
614
+ # We use the "scoped" attribute here so that the desired
615
+ # style properties for the data frame are not then applied
616
+ # throughout the entire notebook.
617
+ template_first = """\
618
+ <style scoped>"""
619
+ template_last = """\
620
+ </style>"""
621
+ template_select = """\
622
+ .dataframe %s {
623
+ %s: %s;
624
+ }"""
625
+ element_props = [
626
+ ("tbody tr th:only-of-type", "vertical-align", "middle"),
627
+ ("tbody tr th", "vertical-align", "top"),
628
+ ]
629
+ if isinstance(self.columns, MultiIndex):
630
+ element_props.append(("thead tr th", "text-align", "left"))
631
+ if self.show_row_idx_names:
632
+ element_props.append(
633
+ ("thead tr:last-of-type th", "text-align", "right")
634
+ )
635
+ else:
636
+ element_props.append(("thead th", "text-align", "right"))
637
+ template_mid = "\n\n".join(template_select % t for t in element_props)
638
+ template = dedent(f"{template_first}\n{template_mid}\n{template_last}")
639
+ self.write(template)
640
+
641
+ def render(self) -> list[str]:
642
+ self.write("<div>")
643
+ self.write_style()
644
+ super().render()
645
+ self.write("</div>")
646
+ return self.elements
shared/package-files/02/02273b35c63ac179113f9494ebabc086b716ca5c1ef22efcbb69f37de9e7ec56/webbrowser.pyi ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import Callable, List, Optional, Sequence, Text, Union
3
+
4
+ class Error(Exception): ...
5
+
6
+ if sys.version_info >= (3, 7):
7
+ def register(
8
+ name: Text, klass: Optional[Callable[[], BaseBrowser]], instance: Optional[BaseBrowser] = ..., *, preferred: bool = ...
9
+ ) -> None: ...
10
+
11
+ else:
12
+ def register(
13
+ name: Text, klass: Optional[Callable[[], BaseBrowser]], instance: Optional[BaseBrowser] = ..., update_tryorder: int = ...
14
+ ) -> None: ...
15
+
16
+ def get(using: Optional[Text] = ...) -> BaseBrowser: ...
17
+ def open(url: Text, new: int = ..., autoraise: bool = ...) -> bool: ...
18
+ def open_new(url: Text) -> bool: ...
19
+ def open_new_tab(url: Text) -> bool: ...
20
+
21
+ class BaseBrowser:
22
+ args: List[str]
23
+ name: str
24
+ basename: str
25
+ def __init__(self, name: Text = ...) -> None: ...
26
+ def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ...
27
+ def open_new(self, url: Text) -> bool: ...
28
+ def open_new_tab(self, url: Text) -> bool: ...
29
+
30
+ class GenericBrowser(BaseBrowser):
31
+ args: List[str]
32
+ name: str
33
+ basename: str
34
+ def __init__(self, name: Union[Text, Sequence[Text]]) -> None: ...
35
+ def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ...
36
+
37
+ class BackgroundBrowser(GenericBrowser):
38
+ def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ...
39
+
40
+ class UnixBrowser(BaseBrowser):
41
+ raise_opts: List[str]
42
+ background: bool
43
+ redirect_stdout: bool
44
+ remote_args: List[str]
45
+ remote_action: str
46
+ remote_action_newwin: str
47
+ remote_action_newtab: str
48
+ def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ...
49
+
50
+ class Mozilla(UnixBrowser):
51
+ raise_opts: List[str]
52
+ remote_args: List[str]
53
+ remote_action: str
54
+ remote_action_newwin: str
55
+ remote_action_newtab: str
56
+ background: bool
57
+
58
+ class Galeon(UnixBrowser):
59
+ raise_opts: List[str]
60
+ remote_args: List[str]
61
+ remote_action: str
62
+ remote_action_newwin: str
63
+ background: bool
64
+
65
+ class Chrome(UnixBrowser):
66
+ remote_args: List[str]
67
+ remote_action: str
68
+ remote_action_newwin: str
69
+ remote_action_newtab: str
70
+ background: bool
71
+
72
+ class Opera(UnixBrowser):
73
+ raise_opts: List[str]
74
+ remote_args: List[str]
75
+ remote_action: str
76
+ remote_action_newwin: str
77
+ remote_action_newtab: str
78
+ background: bool
79
+
80
+ class Elinks(UnixBrowser):
81
+ remote_args: List[str]
82
+ remote_action: str
83
+ remote_action_newwin: str
84
+ remote_action_newtab: str
85
+ background: bool
86
+ redirect_stdout: bool
87
+
88
+ class Konqueror(BaseBrowser):
89
+ def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ...
90
+
91
+ class Grail(BaseBrowser):
92
+ def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ...
93
+
94
+ if sys.platform == "win32":
95
+ class WindowsDefault(BaseBrowser):
96
+ def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ...
97
+
98
+ if sys.platform == "darwin":
99
+ class MacOSX(BaseBrowser):
100
+ name: str
101
+ def __init__(self, name: Text) -> None: ...
102
+ def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ...
103
+ class MacOSXOSAScript(BaseBrowser):
104
+ def __init__(self, name: Text) -> None: ...
105
+ def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ...
shared/package-files/02/0229b075bf5ab357492996853541f63a158854155de9990927f58ae6c358f1c5/enums.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ All of the Enums that are used throughout the chardet package.
3
+
4
+ :author: Dan Blanchard (dan.blanchard@gmail.com)
5
+ """
6
+
7
+
8
+ class InputState(object):
9
+ """
10
+ This enum represents the different states a universal detector can be in.
11
+ """
12
+ PURE_ASCII = 0
13
+ ESC_ASCII = 1
14
+ HIGH_BYTE = 2
15
+
16
+
17
+ class LanguageFilter(object):
18
+ """
19
+ This enum represents the different language filters we can apply to a
20
+ ``UniversalDetector``.
21
+ """
22
+ CHINESE_SIMPLIFIED = 0x01
23
+ CHINESE_TRADITIONAL = 0x02
24
+ JAPANESE = 0x04
25
+ KOREAN = 0x08
26
+ NON_CJK = 0x10
27
+ ALL = 0x1F
28
+ CHINESE = CHINESE_SIMPLIFIED | CHINESE_TRADITIONAL
29
+ CJK = CHINESE | JAPANESE | KOREAN
30
+
31
+
32
+ class ProbingState(object):
33
+ """
34
+ This enum represents the different states a prober can be in.
35
+ """
36
+ DETECTING = 0
37
+ FOUND_IT = 1
38
+ NOT_ME = 2
39
+
40
+
41
+ class MachineState(object):
42
+ """
43
+ This enum represents the different states a state machine can be in.
44
+ """
45
+ START = 0
46
+ ERROR = 1
47
+ ITS_ME = 2
48
+
49
+
50
+ class SequenceLikelihood(object):
51
+ """
52
+ This enum represents the likelihood of a character following the previous one.
53
+ """
54
+ NEGATIVE = 0
55
+ UNLIKELY = 1
56
+ LIKELY = 2
57
+ POSITIVE = 3
58
+
59
+ @classmethod
60
+ def get_num_categories(cls):
61
+ """:returns: The number of likelihood categories in the enum."""
62
+ return 4
63
+
64
+
65
+ class CharacterCategory(object):
66
+ """
67
+ This enum represents the different categories language models for
68
+ ``SingleByteCharsetProber`` put characters into.
69
+
70
+ Anything less than CONTROL is considered a letter.
71
+ """
72
+ UNDEFINED = 255
73
+ LINE_BREAK = 254
74
+ SYMBOL = 253
75
+ DIGIT = 252
76
+ CONTROL = 251
shared/package-files/02/022bbf749fe8c6af98d555e7b39379bb92b55a78368730a04604620e14c08952/interpolate.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.interpolate` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'BPoly',
10
+ 'BSpline',
11
+ 'NdPPoly',
12
+ 'PPoly',
13
+ 'RectBivariateSpline',
14
+ 'RegularGridInterpolator',
15
+ 'interp1d',
16
+ 'interp2d',
17
+ 'interpn',
18
+ 'lagrange',
19
+ 'make_interp_spline',
20
+ ]
21
+
22
+
23
+ def __dir__():
24
+ return __all__
25
+
26
+
27
+ def __getattr__(name):
28
+ return _sub_module_deprecation(sub_package="interpolate", module="interpolate",
29
+ private_modules=["_interpolate", "fitpack2", "_rgi"],
30
+ all=__all__, attribute=name)
shared/package-files/02/022c9bf5cde1ba759ce9b93a4ed8d0ce33c3242be07a965c8168601f8346d63c/test_rotation.py ADDED
@@ -0,0 +1,2188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import numpy as np
4
+ from numpy.testing import assert_equal, assert_array_almost_equal
5
+ from numpy.testing import assert_allclose
6
+ from scipy.spatial.transform import Rotation, Slerp
7
+ from scipy.stats import special_ortho_group
8
+ from itertools import permutations
9
+
10
+ import pickle
11
+ import copy
12
+
13
+ def basis_vec(axis):
14
+ if axis == 'x':
15
+ return [1, 0, 0]
16
+ elif axis == 'y':
17
+ return [0, 1, 0]
18
+ elif axis == 'z':
19
+ return [0, 0, 1]
20
+
21
+ def test_generic_quat_matrix():
22
+ x = np.array([[3, 4, 0, 0], [5, 12, 0, 0]])
23
+ r = Rotation.from_quat(x)
24
+ expected_quat = x / np.array([[5], [13]])
25
+ assert_array_almost_equal(r.as_quat(), expected_quat)
26
+
27
+
28
+ def test_from_single_1d_quaternion():
29
+ x = np.array([3, 4, 0, 0])
30
+ r = Rotation.from_quat(x)
31
+ expected_quat = x / 5
32
+ assert_array_almost_equal(r.as_quat(), expected_quat)
33
+
34
+
35
+ def test_from_single_2d_quaternion():
36
+ x = np.array([[3, 4, 0, 0]])
37
+ r = Rotation.from_quat(x)
38
+ expected_quat = x / 5
39
+ assert_array_almost_equal(r.as_quat(), expected_quat)
40
+
41
+
42
+ def test_from_quat_scalar_first():
43
+ rng = np.random.RandomState(0)
44
+
45
+ r = Rotation.from_quat([1, 0, 0, 0], scalar_first=True)
46
+ assert_allclose(r.as_matrix(), np.eye(3), rtol=1e-15, atol=1e-16)
47
+
48
+ r = Rotation.from_quat(np.tile([1, 0, 0, 0], (10, 1)), scalar_first=True)
49
+ assert_allclose(r.as_matrix(), np.tile(np.eye(3), (10, 1, 1)),
50
+ rtol=1e-15, atol=1e-16)
51
+
52
+ q = rng.randn(100, 4)
53
+ q /= np.linalg.norm(q, axis=1)[:, None]
54
+ for qi in q:
55
+ r = Rotation.from_quat(qi, scalar_first=True)
56
+ assert_allclose(np.roll(r.as_quat(), 1), qi, rtol=1e-15)
57
+
58
+ r = Rotation.from_quat(q, scalar_first=True)
59
+ assert_allclose(np.roll(r.as_quat(), 1, axis=1), q, rtol=1e-15)
60
+
61
+
62
+ def test_as_quat_scalar_first():
63
+ rng = np.random.RandomState(0)
64
+
65
+ r = Rotation.from_euler('xyz', np.zeros(3))
66
+ assert_allclose(r.as_quat(scalar_first=True), [1, 0, 0, 0],
67
+ rtol=1e-15, atol=1e-16)
68
+
69
+ r = Rotation.from_euler('xyz', np.zeros((10, 3)))
70
+ assert_allclose(r.as_quat(scalar_first=True),
71
+ np.tile([1, 0, 0, 0], (10, 1)), rtol=1e-15, atol=1e-16)
72
+
73
+ q = rng.randn(100, 4)
74
+ q /= np.linalg.norm(q, axis=1)[:, None]
75
+ for qi in q:
76
+ r = Rotation.from_quat(qi)
77
+ assert_allclose(r.as_quat(scalar_first=True), np.roll(qi, 1),
78
+ rtol=1e-15)
79
+
80
+ assert_allclose(r.as_quat(canonical=True, scalar_first=True),
81
+ np.roll(r.as_quat(canonical=True), 1),
82
+ rtol=1e-15)
83
+
84
+ r = Rotation.from_quat(q)
85
+ assert_allclose(r.as_quat(scalar_first=True), np.roll(q, 1, axis=1),
86
+ rtol=1e-15)
87
+
88
+ assert_allclose(r.as_quat(canonical=True, scalar_first=True),
89
+ np.roll(r.as_quat(canonical=True), 1, axis=1), rtol=1e-15)
90
+
91
+
92
+ def test_from_square_quat_matrix():
93
+ # Ensure proper norm array broadcasting
94
+ x = np.array([
95
+ [3, 0, 0, 4],
96
+ [5, 0, 12, 0],
97
+ [0, 0, 0, 1],
98
+ [-1, -1, -1, 1],
99
+ [0, 0, 0, -1], # Check double cover
100
+ [-1, -1, -1, -1] # Check double cover
101
+ ])
102
+ r = Rotation.from_quat(x)
103
+ expected_quat = x / np.array([[5], [13], [1], [2], [1], [2]])
104
+ assert_array_almost_equal(r.as_quat(), expected_quat)
105
+
106
+
107
+ def test_quat_double_to_canonical_single_cover():
108
+ x = np.array([
109
+ [-1, 0, 0, 0],
110
+ [0, -1, 0, 0],
111
+ [0, 0, -1, 0],
112
+ [0, 0, 0, -1],
113
+ [-1, -1, -1, -1]
114
+ ])
115
+ r = Rotation.from_quat(x)
116
+ expected_quat = np.abs(x) / np.linalg.norm(x, axis=1)[:, None]
117
+ assert_allclose(r.as_quat(canonical=True), expected_quat)
118
+
119
+
120
+ def test_quat_double_cover():
121
+ # See the Rotation.from_quat() docstring for scope of the quaternion
122
+ # double cover property.
123
+ # Check from_quat and as_quat(canonical=False)
124
+ q = np.array([0, 0, 0, -1])
125
+ r = Rotation.from_quat(q)
126
+ assert_equal(q, r.as_quat(canonical=False))
127
+
128
+ # Check composition and inverse
129
+ q = np.array([1, 0, 0, 1])/np.sqrt(2) # 90 deg rotation about x
130
+ r = Rotation.from_quat(q)
131
+ r3 = r*r*r
132
+ assert_allclose(r.as_quat(canonical=False)*np.sqrt(2),
133
+ [1, 0, 0, 1])
134
+ assert_allclose(r.inv().as_quat(canonical=False)*np.sqrt(2),
135
+ [-1, 0, 0, 1])
136
+ assert_allclose(r3.as_quat(canonical=False)*np.sqrt(2),
137
+ [1, 0, 0, -1])
138
+ assert_allclose(r3.inv().as_quat(canonical=False)*np.sqrt(2),
139
+ [-1, 0, 0, -1])
140
+
141
+ # More sanity checks
142
+ assert_allclose((r*r.inv()).as_quat(canonical=False),
143
+ [0, 0, 0, 1], atol=2e-16)
144
+ assert_allclose((r3*r3.inv()).as_quat(canonical=False),
145
+ [0, 0, 0, 1], atol=2e-16)
146
+ assert_allclose((r*r3).as_quat(canonical=False),
147
+ [0, 0, 0, -1], atol=2e-16)
148
+ assert_allclose((r.inv()*r3.inv()).as_quat(canonical=False),
149
+ [0, 0, 0, -1], atol=2e-16)
150
+
151
+
152
+ def test_from_quat_wrong_shape():
153
+ # Wrong shape 1d array
154
+ with pytest.raises(ValueError, match='Expected `quat` to have shape'):
155
+ Rotation.from_quat(np.array([1, 2, 3]))
156
+
157
+ # Wrong shape 2d array
158
+ with pytest.raises(ValueError, match='Expected `quat` to have shape'):
159
+ Rotation.from_quat(np.array([
160
+ [1, 2, 3, 4, 5],
161
+ [4, 5, 6, 7, 8]
162
+ ]))
163
+
164
+ # 3d array
165
+ with pytest.raises(ValueError, match='Expected `quat` to have shape'):
166
+ Rotation.from_quat(np.array([
167
+ [[1, 2, 3, 4]],
168
+ [[4, 5, 6, 7]]
169
+ ]))
170
+
171
+
172
+ def test_zero_norms_from_quat():
173
+ x = np.array([
174
+ [3, 4, 0, 0],
175
+ [0, 0, 0, 0],
176
+ [5, 0, 12, 0]
177
+ ])
178
+ with pytest.raises(ValueError):
179
+ Rotation.from_quat(x)
180
+
181
+
182
+ def test_as_matrix_single_1d_quaternion():
183
+ quat = [0, 0, 0, 1]
184
+ mat = Rotation.from_quat(quat).as_matrix()
185
+ # mat.shape == (3,3) due to 1d input
186
+ assert_array_almost_equal(mat, np.eye(3))
187
+
188
+
189
+ def test_as_matrix_single_2d_quaternion():
190
+ quat = [[0, 0, 1, 1]]
191
+ mat = Rotation.from_quat(quat).as_matrix()
192
+ assert_equal(mat.shape, (1, 3, 3))
193
+ expected_mat = np.array([
194
+ [0, -1, 0],
195
+ [1, 0, 0],
196
+ [0, 0, 1]
197
+ ])
198
+ assert_array_almost_equal(mat[0], expected_mat)
199
+
200
+
201
+ def test_as_matrix_from_square_input():
202
+ quats = [
203
+ [0, 0, 1, 1],
204
+ [0, 1, 0, 1],
205
+ [0, 0, 0, 1],
206
+ [0, 0, 0, -1]
207
+ ]
208
+ mat = Rotation.from_quat(quats).as_matrix()
209
+ assert_equal(mat.shape, (4, 3, 3))
210
+
211
+ expected0 = np.array([
212
+ [0, -1, 0],
213
+ [1, 0, 0],
214
+ [0, 0, 1]
215
+ ])
216
+ assert_array_almost_equal(mat[0], expected0)
217
+
218
+ expected1 = np.array([
219
+ [0, 0, 1],
220
+ [0, 1, 0],
221
+ [-1, 0, 0]
222
+ ])
223
+ assert_array_almost_equal(mat[1], expected1)
224
+
225
+ assert_array_almost_equal(mat[2], np.eye(3))
226
+ assert_array_almost_equal(mat[3], np.eye(3))
227
+
228
+
229
+ def test_as_matrix_from_generic_input():
230
+ quats = [
231
+ [0, 0, 1, 1],
232
+ [0, 1, 0, 1],
233
+ [1, 2, 3, 4]
234
+ ]
235
+ mat = Rotation.from_quat(quats).as_matrix()
236
+ assert_equal(mat.shape, (3, 3, 3))
237
+
238
+ expected0 = np.array([
239
+ [0, -1, 0],
240
+ [1, 0, 0],
241
+ [0, 0, 1]
242
+ ])
243
+ assert_array_almost_equal(mat[0], expected0)
244
+
245
+ expected1 = np.array([
246
+ [0, 0, 1],
247
+ [0, 1, 0],
248
+ [-1, 0, 0]
249
+ ])
250
+ assert_array_almost_equal(mat[1], expected1)
251
+
252
+ expected2 = np.array([
253
+ [0.4, -2, 2.2],
254
+ [2.8, 1, 0.4],
255
+ [-1, 2, 2]
256
+ ]) / 3
257
+ assert_array_almost_equal(mat[2], expected2)
258
+
259
+
260
+ def test_from_single_2d_matrix():
261
+ mat = [
262
+ [0, 0, 1],
263
+ [1, 0, 0],
264
+ [0, 1, 0]
265
+ ]
266
+ expected_quat = [0.5, 0.5, 0.5, 0.5]
267
+ assert_array_almost_equal(
268
+ Rotation.from_matrix(mat).as_quat(),
269
+ expected_quat)
270
+
271
+
272
+ def test_from_single_3d_matrix():
273
+ mat = np.array([
274
+ [0, 0, 1],
275
+ [1, 0, 0],
276
+ [0, 1, 0]
277
+ ]).reshape((1, 3, 3))
278
+ expected_quat = np.array([0.5, 0.5, 0.5, 0.5]).reshape((1, 4))
279
+ assert_array_almost_equal(
280
+ Rotation.from_matrix(mat).as_quat(),
281
+ expected_quat)
282
+
283
+
284
+ def test_from_matrix_calculation():
285
+ expected_quat = np.array([1, 1, 6, 1]) / np.sqrt(39)
286
+ mat = np.array([
287
+ [-0.8974359, -0.2564103, 0.3589744],
288
+ [0.3589744, -0.8974359, 0.2564103],
289
+ [0.2564103, 0.3589744, 0.8974359]
290
+ ])
291
+ assert_array_almost_equal(
292
+ Rotation.from_matrix(mat).as_quat(),
293
+ expected_quat)
294
+ assert_array_almost_equal(
295
+ Rotation.from_matrix(mat.reshape((1, 3, 3))).as_quat(),
296
+ expected_quat.reshape((1, 4)))
297
+
298
+
299
+ def test_matrix_calculation_pipeline():
300
+ mat = special_ortho_group.rvs(3, size=10, random_state=0)
301
+ assert_array_almost_equal(Rotation.from_matrix(mat).as_matrix(), mat)
302
+
303
+
304
+ def test_from_matrix_ortho_output():
305
+ rnd = np.random.RandomState(0)
306
+ mat = rnd.random_sample((100, 3, 3))
307
+ dets = np.linalg.det(mat)
308
+ for i in range(len(dets)):
309
+ # Make sure we have a right-handed rotation matrix
310
+ if dets[i] < 0:
311
+ mat[i] = -mat[i]
312
+ ortho_mat = Rotation.from_matrix(mat).as_matrix()
313
+
314
+ mult_result = np.einsum('...ij,...jk->...ik', ortho_mat,
315
+ ortho_mat.transpose((0, 2, 1)))
316
+
317
+ eye3d = np.zeros((100, 3, 3))
318
+ for i in range(3):
319
+ eye3d[:, i, i] = 1.0
320
+
321
+ assert_array_almost_equal(mult_result, eye3d)
322
+
323
+
324
+ def test_from_matrix_normalize():
325
+ mat = np.array([
326
+ [1, 1, 0],
327
+ [0, 1, 0],
328
+ [0, 0, 1]])
329
+ expected = np.array([[ 0.894427, 0.447214, 0.0],
330
+ [-0.447214, 0.894427, 0.0],
331
+ [ 0.0, 0.0, 1.0]])
332
+ assert_allclose(Rotation.from_matrix(mat).as_matrix(), expected, atol=1e-6)
333
+
334
+ mat = np.array([
335
+ [0, -0.5, 0 ],
336
+ [0.5, 0 , 0 ],
337
+ [0, 0 , 0.5]])
338
+ expected = np.array([[ 0, -1, 0],
339
+ [ 1, 0, 0],
340
+ [ 0, 0, 1]])
341
+ assert_allclose(Rotation.from_matrix(mat).as_matrix(), expected, atol=1e-6)
342
+
343
+
344
+ def test_from_matrix_non_positive_determinant():
345
+ mat = np.eye(3)
346
+ mat[0, 0] = 0
347
+ with pytest.raises(ValueError, match='Non-positive determinant'):
348
+ Rotation.from_matrix(mat)
349
+
350
+ mat[0, 0] = -1
351
+ with pytest.raises(ValueError, match='Non-positive determinant'):
352
+ Rotation.from_matrix(mat)
353
+
354
+
355
+ def test_from_1d_single_rotvec():
356
+ rotvec = [1, 0, 0]
357
+ expected_quat = np.array([0.4794255, 0, 0, 0.8775826])
358
+ result = Rotation.from_rotvec(rotvec)
359
+ assert_array_almost_equal(result.as_quat(), expected_quat)
360
+
361
+
362
+ def test_from_2d_single_rotvec():
363
+ rotvec = [[1, 0, 0]]
364
+ expected_quat = np.array([[0.4794255, 0, 0, 0.8775826]])
365
+ result = Rotation.from_rotvec(rotvec)
366
+ assert_array_almost_equal(result.as_quat(), expected_quat)
367
+
368
+
369
+ def test_from_generic_rotvec():
370
+ rotvec = [
371
+ [1, 2, 2],
372
+ [1, -1, 0.5],
373
+ [0, 0, 0]
374
+ ]
375
+ expected_quat = np.array([
376
+ [0.3324983, 0.6649967, 0.6649967, 0.0707372],
377
+ [0.4544258, -0.4544258, 0.2272129, 0.7316889],
378
+ [0, 0, 0, 1]
379
+ ])
380
+ assert_array_almost_equal(
381
+ Rotation.from_rotvec(rotvec).as_quat(),
382
+ expected_quat)
383
+
384
+
385
+ def test_from_rotvec_small_angle():
386
+ rotvec = np.array([
387
+ [5e-4 / np.sqrt(3), -5e-4 / np.sqrt(3), 5e-4 / np.sqrt(3)],
388
+ [0.2, 0.3, 0.4],
389
+ [0, 0, 0]
390
+ ])
391
+
392
+ quat = Rotation.from_rotvec(rotvec).as_quat()
393
+ # cos(theta/2) ~~ 1 for small theta
394
+ assert_allclose(quat[0, 3], 1)
395
+ # sin(theta/2) / theta ~~ 0.5 for small theta
396
+ assert_allclose(quat[0, :3], rotvec[0] * 0.5)
397
+
398
+ assert_allclose(quat[1, 3], 0.9639685)
399
+ assert_allclose(
400
+ quat[1, :3],
401
+ np.array([
402
+ 0.09879603932153465,
403
+ 0.14819405898230198,
404
+ 0.19759207864306931
405
+ ]))
406
+
407
+ assert_equal(quat[2], np.array([0, 0, 0, 1]))
408
+
409
+
410
+ def test_degrees_from_rotvec():
411
+ rotvec1 = [1.0 / np.cbrt(3), 1.0 / np.cbrt(3), 1.0 / np.cbrt(3)]
412
+ rot1 = Rotation.from_rotvec(rotvec1, degrees=True)
413
+ quat1 = rot1.as_quat()
414
+
415
+ rotvec2 = np.deg2rad(rotvec1)
416
+ rot2 = Rotation.from_rotvec(rotvec2)
417
+ quat2 = rot2.as_quat()
418
+
419
+ assert_allclose(quat1, quat2)
420
+
421
+
422
+ def test_malformed_1d_from_rotvec():
423
+ with pytest.raises(ValueError, match='Expected `rot_vec` to have shape'):
424
+ Rotation.from_rotvec([1, 2])
425
+
426
+
427
+ def test_malformed_2d_from_rotvec():
428
+ with pytest.raises(ValueError, match='Expected `rot_vec` to have shape'):
429
+ Rotation.from_rotvec([
430
+ [1, 2, 3, 4],
431
+ [5, 6, 7, 8]
432
+ ])
433
+
434
+
435
+ def test_as_generic_rotvec():
436
+ quat = np.array([
437
+ [1, 2, -1, 0.5],
438
+ [1, -1, 1, 0.0003],
439
+ [0, 0, 0, 1]
440
+ ])
441
+ quat /= np.linalg.norm(quat, axis=1)[:, None]
442
+
443
+ rotvec = Rotation.from_quat(quat).as_rotvec()
444
+ angle = np.linalg.norm(rotvec, axis=1)
445
+
446
+ assert_allclose(quat[:, 3], np.cos(angle/2))
447
+ assert_allclose(np.cross(rotvec, quat[:, :3]), np.zeros((3, 3)))
448
+
449
+
450
+ def test_as_rotvec_single_1d_input():
451
+ quat = np.array([1, 2, -3, 2])
452
+ expected_rotvec = np.array([0.5772381, 1.1544763, -1.7317144])
453
+
454
+ actual_rotvec = Rotation.from_quat(quat).as_rotvec()
455
+
456
+ assert_equal(actual_rotvec.shape, (3,))
457
+ assert_allclose(actual_rotvec, expected_rotvec)
458
+
459
+
460
+ def test_as_rotvec_single_2d_input():
461
+ quat = np.array([[1, 2, -3, 2]])
462
+ expected_rotvec = np.array([[0.5772381, 1.1544763, -1.7317144]])
463
+
464
+ actual_rotvec = Rotation.from_quat(quat).as_rotvec()
465
+
466
+ assert_equal(actual_rotvec.shape, (1, 3))
467
+ assert_allclose(actual_rotvec, expected_rotvec)
468
+
469
+
470
+ def test_as_rotvec_degrees():
471
+ # x->y, y->z, z->x
472
+ mat = [[0, 0, 1], [1, 0, 0], [0, 1, 0]]
473
+ rot = Rotation.from_matrix(mat)
474
+ rotvec = rot.as_rotvec(degrees=True)
475
+ angle = np.linalg.norm(rotvec)
476
+ assert_allclose(angle, 120.0)
477
+ assert_allclose(rotvec[0], rotvec[1])
478
+ assert_allclose(rotvec[1], rotvec[2])
479
+
480
+
481
+ def test_rotvec_calc_pipeline():
482
+ # Include small angles
483
+ rotvec = np.array([
484
+ [0, 0, 0],
485
+ [1, -1, 2],
486
+ [-3e-4, 3.5e-4, 7.5e-5]
487
+ ])
488
+ assert_allclose(Rotation.from_rotvec(rotvec).as_rotvec(), rotvec)
489
+ assert_allclose(Rotation.from_rotvec(rotvec, degrees=True).as_rotvec(degrees=True),
490
+ rotvec)
491
+
492
+
493
+ def test_from_1d_single_mrp():
494
+ mrp = [0, 0, 1.0]
495
+ expected_quat = np.array([0, 0, 1, 0])
496
+ result = Rotation.from_mrp(mrp)
497
+ assert_array_almost_equal(result.as_quat(), expected_quat)
498
+
499
+
500
+ def test_from_2d_single_mrp():
501
+ mrp = [[0, 0, 1.0]]
502
+ expected_quat = np.array([[0, 0, 1, 0]])
503
+ result = Rotation.from_mrp(mrp)
504
+ assert_array_almost_equal(result.as_quat(), expected_quat)
505
+
506
+
507
+ def test_from_generic_mrp():
508
+ mrp = np.array([
509
+ [1, 2, 2],
510
+ [1, -1, 0.5],
511
+ [0, 0, 0]])
512
+ expected_quat = np.array([
513
+ [0.2, 0.4, 0.4, -0.8],
514
+ [0.61538462, -0.61538462, 0.30769231, -0.38461538],
515
+ [0, 0, 0, 1]])
516
+ assert_array_almost_equal(Rotation.from_mrp(mrp).as_quat(), expected_quat)
517
+
518
+
519
+ def test_malformed_1d_from_mrp():
520
+ with pytest.raises(ValueError, match='Expected `mrp` to have shape'):
521
+ Rotation.from_mrp([1, 2])
522
+
523
+
524
+ def test_malformed_2d_from_mrp():
525
+ with pytest.raises(ValueError, match='Expected `mrp` to have shape'):
526
+ Rotation.from_mrp([
527
+ [1, 2, 3, 4],
528
+ [5, 6, 7, 8]
529
+ ])
530
+
531
+
532
+ def test_as_generic_mrp():
533
+ quat = np.array([
534
+ [1, 2, -1, 0.5],
535
+ [1, -1, 1, 0.0003],
536
+ [0, 0, 0, 1]])
537
+ quat /= np.linalg.norm(quat, axis=1)[:, None]
538
+
539
+ expected_mrp = np.array([
540
+ [0.33333333, 0.66666667, -0.33333333],
541
+ [0.57725028, -0.57725028, 0.57725028],
542
+ [0, 0, 0]])
543
+ assert_array_almost_equal(Rotation.from_quat(quat).as_mrp(), expected_mrp)
544
+
545
+ def test_past_180_degree_rotation():
546
+ # ensure that a > 180 degree rotation is returned as a <180 rotation in MRPs
547
+ # in this case 270 should be returned as -90
548
+ expected_mrp = np.array([-np.tan(np.pi/2/4), 0.0, 0])
549
+ assert_array_almost_equal(
550
+ Rotation.from_euler('xyz', [270, 0, 0], degrees=True).as_mrp(),
551
+ expected_mrp
552
+ )
553
+
554
+
555
+ def test_as_mrp_single_1d_input():
556
+ quat = np.array([1, 2, -3, 2])
557
+ expected_mrp = np.array([0.16018862, 0.32037724, -0.48056586])
558
+
559
+ actual_mrp = Rotation.from_quat(quat).as_mrp()
560
+
561
+ assert_equal(actual_mrp.shape, (3,))
562
+ assert_allclose(actual_mrp, expected_mrp)
563
+
564
+
565
+ def test_as_mrp_single_2d_input():
566
+ quat = np.array([[1, 2, -3, 2]])
567
+ expected_mrp = np.array([[0.16018862, 0.32037724, -0.48056586]])
568
+
569
+ actual_mrp = Rotation.from_quat(quat).as_mrp()
570
+
571
+ assert_equal(actual_mrp.shape, (1, 3))
572
+ assert_allclose(actual_mrp, expected_mrp)
573
+
574
+
575
+ def test_mrp_calc_pipeline():
576
+ actual_mrp = np.array([
577
+ [0, 0, 0],
578
+ [1, -1, 2],
579
+ [0.41421356, 0, 0],
580
+ [0.1, 0.2, 0.1]])
581
+ expected_mrp = np.array([
582
+ [0, 0, 0],
583
+ [-0.16666667, 0.16666667, -0.33333333],
584
+ [0.41421356, 0, 0],
585
+ [0.1, 0.2, 0.1]])
586
+ assert_allclose(Rotation.from_mrp(actual_mrp).as_mrp(), expected_mrp)
587
+
588
+
589
+ def test_from_euler_single_rotation():
590
+ quat = Rotation.from_euler('z', 90, degrees=True).as_quat()
591
+ expected_quat = np.array([0, 0, 1, 1]) / np.sqrt(2)
592
+ assert_allclose(quat, expected_quat)
593
+
594
+
595
+ def test_single_intrinsic_extrinsic_rotation():
596
+ extrinsic = Rotation.from_euler('z', 90, degrees=True).as_matrix()
597
+ intrinsic = Rotation.from_euler('Z', 90, degrees=True).as_matrix()
598
+ assert_allclose(extrinsic, intrinsic)
599
+
600
+
601
+ def test_from_euler_rotation_order():
602
+ # Intrinsic rotation is same as extrinsic with order reversed
603
+ rnd = np.random.RandomState(0)
604
+ a = rnd.randint(low=0, high=180, size=(6, 3))
605
+ b = a[:, ::-1]
606
+ x = Rotation.from_euler('xyz', a, degrees=True).as_quat()
607
+ y = Rotation.from_euler('ZYX', b, degrees=True).as_quat()
608
+ assert_allclose(x, y)
609
+
610
+
611
+ def test_from_euler_elementary_extrinsic_rotation():
612
+ # Simple test to check if extrinsic rotations are implemented correctly
613
+ mat = Rotation.from_euler('zx', [90, 90], degrees=True).as_matrix()
614
+ expected_mat = np.array([
615
+ [0, -1, 0],
616
+ [0, 0, -1],
617
+ [1, 0, 0]
618
+ ])
619
+ assert_array_almost_equal(mat, expected_mat)
620
+
621
+
622
+ def test_from_euler_intrinsic_rotation_312():
623
+ angles = [
624
+ [30, 60, 45],
625
+ [30, 60, 30],
626
+ [45, 30, 60]
627
+ ]
628
+ mat = Rotation.from_euler('ZXY', angles, degrees=True).as_matrix()
629
+
630
+ assert_array_almost_equal(mat[0], np.array([
631
+ [0.3061862, -0.2500000, 0.9185587],
632
+ [0.8838835, 0.4330127, -0.1767767],
633
+ [-0.3535534, 0.8660254, 0.3535534]
634
+ ]))
635
+
636
+ assert_array_almost_equal(mat[1], np.array([
637
+ [0.5334936, -0.2500000, 0.8080127],
638
+ [0.8080127, 0.4330127, -0.3995191],
639
+ [-0.2500000, 0.8660254, 0.4330127]
640
+ ]))
641
+
642
+ assert_array_almost_equal(mat[2], np.array([
643
+ [0.0473672, -0.6123725, 0.7891491],
644
+ [0.6597396, 0.6123725, 0.4355958],
645
+ [-0.7500000, 0.5000000, 0.4330127]
646
+ ]))
647
+
648
+
649
+ def test_from_euler_intrinsic_rotation_313():
650
+ angles = [
651
+ [30, 60, 45],
652
+ [30, 60, 30],
653
+ [45, 30, 60]
654
+ ]
655
+ mat = Rotation.from_euler('ZXZ', angles, degrees=True).as_matrix()
656
+
657
+ assert_array_almost_equal(mat[0], np.array([
658
+ [0.43559574, -0.78914913, 0.4330127],
659
+ [0.65973961, -0.04736717, -0.750000],
660
+ [0.61237244, 0.61237244, 0.500000]
661
+ ]))
662
+
663
+ assert_array_almost_equal(mat[1], np.array([
664
+ [0.6250000, -0.64951905, 0.4330127],
665
+ [0.64951905, 0.1250000, -0.750000],
666
+ [0.4330127, 0.750000, 0.500000]
667
+ ]))
668
+
669
+ assert_array_almost_equal(mat[2], np.array([
670
+ [-0.1767767, -0.91855865, 0.35355339],
671
+ [0.88388348, -0.30618622, -0.35355339],
672
+ [0.4330127, 0.25000000, 0.8660254]
673
+ ]))
674
+
675
+
676
+ def test_from_euler_extrinsic_rotation_312():
677
+ angles = [
678
+ [30, 60, 45],
679
+ [30, 60, 30],
680
+ [45, 30, 60]
681
+ ]
682
+ mat = Rotation.from_euler('zxy', angles, degrees=True).as_matrix()
683
+
684
+ assert_array_almost_equal(mat[0], np.array([
685
+ [0.91855865, 0.1767767, 0.35355339],
686
+ [0.25000000, 0.4330127, -0.8660254],
687
+ [-0.30618622, 0.88388348, 0.35355339]
688
+ ]))
689
+
690
+ assert_array_almost_equal(mat[1], np.array([
691
+ [0.96650635, -0.0580127, 0.2500000],
692
+ [0.25000000, 0.4330127, -0.8660254],
693
+ [-0.0580127, 0.89951905, 0.4330127]
694
+ ]))
695
+
696
+ assert_array_almost_equal(mat[2], np.array([
697
+ [0.65973961, -0.04736717, 0.7500000],
698
+ [0.61237244, 0.61237244, -0.5000000],
699
+ [-0.43559574, 0.78914913, 0.4330127]
700
+ ]))
701
+
702
+
703
+ def test_from_euler_extrinsic_rotation_313():
704
+ angles = [
705
+ [30, 60, 45],
706
+ [30, 60, 30],
707
+ [45, 30, 60]
708
+ ]
709
+ mat = Rotation.from_euler('zxz', angles, degrees=True).as_matrix()
710
+
711
+ assert_array_almost_equal(mat[0], np.array([
712
+ [0.43559574, -0.65973961, 0.61237244],
713
+ [0.78914913, -0.04736717, -0.61237244],
714
+ [0.4330127, 0.75000000, 0.500000]
715
+ ]))
716
+
717
+ assert_array_almost_equal(mat[1], np.array([
718
+ [0.62500000, -0.64951905, 0.4330127],
719
+ [0.64951905, 0.12500000, -0.750000],
720
+ [0.4330127, 0.75000000, 0.500000]
721
+ ]))
722
+
723
+ assert_array_almost_equal(mat[2], np.array([
724
+ [-0.1767767, -0.88388348, 0.4330127],
725
+ [0.91855865, -0.30618622, -0.250000],
726
+ [0.35355339, 0.35355339, 0.8660254]
727
+ ]))
728
+
729
+
730
+ @pytest.mark.parametrize("seq_tuple", permutations("xyz"))
731
+ @pytest.mark.parametrize("intrinsic", (False, True))
732
+ def test_as_euler_asymmetric_axes(seq_tuple, intrinsic):
733
+ # helper function for mean error tests
734
+ def test_stats(error, mean_max, rms_max):
735
+ mean = np.mean(error, axis=0)
736
+ std = np.std(error, axis=0)
737
+ rms = np.hypot(mean, std)
738
+ assert np.all(np.abs(mean) < mean_max)
739
+ assert np.all(rms < rms_max)
740
+
741
+ rnd = np.random.RandomState(0)
742
+ n = 1000
743
+ angles = np.empty((n, 3))
744
+ angles[:, 0] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,))
745
+ angles[:, 1] = rnd.uniform(low=-np.pi / 2, high=np.pi / 2, size=(n,))
746
+ angles[:, 2] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,))
747
+
748
+ seq = "".join(seq_tuple)
749
+ if intrinsic:
750
+ # Extrinsic rotation (wrt to global world) at lower case
751
+ # intrinsic (WRT the object itself) lower case.
752
+ seq = seq.upper()
753
+ rotation = Rotation.from_euler(seq, angles)
754
+ angles_quat = rotation.as_euler(seq)
755
+ angles_mat = rotation._as_euler_from_matrix(seq)
756
+ assert_allclose(angles, angles_quat, atol=0, rtol=1e-12)
757
+ assert_allclose(angles, angles_mat, atol=0, rtol=1e-12)
758
+ test_stats(angles_quat - angles, 1e-15, 1e-14)
759
+ test_stats(angles_mat - angles, 1e-15, 1e-14)
760
+
761
+
762
+
763
+ @pytest.mark.parametrize("seq_tuple", permutations("xyz"))
764
+ @pytest.mark.parametrize("intrinsic", (False, True))
765
+ def test_as_euler_symmetric_axes(seq_tuple, intrinsic):
766
+ # helper function for mean error tests
767
+ def test_stats(error, mean_max, rms_max):
768
+ mean = np.mean(error, axis=0)
769
+ std = np.std(error, axis=0)
770
+ rms = np.hypot(mean, std)
771
+ assert np.all(np.abs(mean) < mean_max)
772
+ assert np.all(rms < rms_max)
773
+
774
+ rnd = np.random.RandomState(0)
775
+ n = 1000
776
+ angles = np.empty((n, 3))
777
+ angles[:, 0] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,))
778
+ angles[:, 1] = rnd.uniform(low=0, high=np.pi, size=(n,))
779
+ angles[:, 2] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,))
780
+
781
+ # Rotation of the form A/B/A are rotation around symmetric axes
782
+ seq = "".join([seq_tuple[0], seq_tuple[1], seq_tuple[0]])
783
+ if intrinsic:
784
+ seq = seq.upper()
785
+ rotation = Rotation.from_euler(seq, angles)
786
+ angles_quat = rotation.as_euler(seq)
787
+ angles_mat = rotation._as_euler_from_matrix(seq)
788
+ assert_allclose(angles, angles_quat, atol=0, rtol=1e-13)
789
+ assert_allclose(angles, angles_mat, atol=0, rtol=1e-9)
790
+ test_stats(angles_quat - angles, 1e-16, 1e-14)
791
+ test_stats(angles_mat - angles, 1e-15, 1e-13)
792
+
793
+
794
+ @pytest.mark.thread_unsafe
795
+ @pytest.mark.parametrize("seq_tuple", permutations("xyz"))
796
+ @pytest.mark.parametrize("intrinsic", (False, True))
797
+ def test_as_euler_degenerate_asymmetric_axes(seq_tuple, intrinsic):
798
+ # Since we cannot check for angle equality, we check for rotation matrix
799
+ # equality
800
+ angles = np.array([
801
+ [45, 90, 35],
802
+ [35, -90, 20],
803
+ [35, 90, 25],
804
+ [25, -90, 15]])
805
+
806
+ seq = "".join(seq_tuple)
807
+ if intrinsic:
808
+ # Extrinsic rotation (wrt to global world) at lower case
809
+ # Intrinsic (WRT the object itself) upper case.
810
+ seq = seq.upper()
811
+ rotation = Rotation.from_euler(seq, angles, degrees=True)
812
+ mat_expected = rotation.as_matrix()
813
+
814
+ with pytest.warns(UserWarning, match="Gimbal lock"):
815
+ angle_estimates = rotation.as_euler(seq, degrees=True)
816
+ mat_estimated = Rotation.from_euler(seq, angle_estimates, degrees=True).as_matrix()
817
+
818
+ assert_array_almost_equal(mat_expected, mat_estimated)
819
+
820
+
821
+ @pytest.mark.thread_unsafe
822
+ @pytest.mark.parametrize("seq_tuple", permutations("xyz"))
823
+ @pytest.mark.parametrize("intrinsic", (False, True))
824
+ def test_as_euler_degenerate_symmetric_axes(seq_tuple, intrinsic):
825
+ # Since we cannot check for angle equality, we check for rotation matrix
826
+ # equality
827
+ angles = np.array([
828
+ [15, 0, 60],
829
+ [35, 0, 75],
830
+ [60, 180, 35],
831
+ [15, -180, 25]])
832
+
833
+ # Rotation of the form A/B/A are rotation around symmetric axes
834
+ seq = "".join([seq_tuple[0], seq_tuple[1], seq_tuple[0]])
835
+ if intrinsic:
836
+ # Extrinsic rotation (wrt to global world) at lower case
837
+ # Intrinsic (WRT the object itself) upper case.
838
+ seq = seq.upper()
839
+ rotation = Rotation.from_euler(seq, angles, degrees=True)
840
+ mat_expected = rotation.as_matrix()
841
+
842
+ with pytest.warns(UserWarning, match="Gimbal lock"):
843
+ angle_estimates = rotation.as_euler(seq, degrees=True)
844
+ mat_estimated = Rotation.from_euler(seq, angle_estimates, degrees=True).as_matrix()
845
+
846
+ assert_array_almost_equal(mat_expected, mat_estimated)
847
+
848
+
849
+ @pytest.mark.thread_unsafe
850
+ @pytest.mark.parametrize("seq_tuple", permutations("xyz"))
851
+ @pytest.mark.parametrize("intrinsic", (False, True))
852
+ def test_as_euler_degenerate_compare_algorithms(seq_tuple, intrinsic):
853
+ # this test makes sure that both algorithms are doing the same choices
854
+ # in degenerate cases
855
+
856
+ # asymmetric axes
857
+ angles = np.array([
858
+ [45, 90, 35],
859
+ [35, -90, 20],
860
+ [35, 90, 25],
861
+ [25, -90, 15]])
862
+
863
+ seq = "".join(seq_tuple)
864
+ if intrinsic:
865
+ # Extrinsic rotation (wrt to global world at lower case
866
+ # Intrinsic (WRT the object itself) upper case.
867
+ seq = seq.upper()
868
+
869
+ rot = Rotation.from_euler(seq, angles, degrees=True)
870
+ with pytest.warns(UserWarning, match="Gimbal lock"):
871
+ estimates_matrix = rot._as_euler_from_matrix(seq, degrees=True)
872
+ with pytest.warns(UserWarning, match="Gimbal lock"):
873
+ estimates_quat = rot.as_euler(seq, degrees=True)
874
+ assert_allclose(
875
+ estimates_matrix[:, [0, 2]], estimates_quat[:, [0, 2]], atol=0, rtol=1e-12
876
+ )
877
+ assert_allclose(estimates_matrix[:, 1], estimates_quat[:, 1], atol=0, rtol=1e-7)
878
+
879
+ # symmetric axes
880
+ # Absolute error tolerance must be looser to directly compare the results
881
+ # from both algorithms, because of numerical loss of precision for the
882
+ # method _as_euler_from_matrix near a zero angle value
883
+
884
+ angles = np.array([
885
+ [15, 0, 60],
886
+ [35, 0, 75],
887
+ [60, 180, 35],
888
+ [15, -180, 25]])
889
+
890
+ idx = angles[:, 1] == 0 # find problematic angles indices
891
+
892
+ # Rotation of the form A/B/A are rotation around symmetric axes
893
+ seq = "".join([seq_tuple[0], seq_tuple[1], seq_tuple[0]])
894
+ if intrinsic:
895
+ # Extrinsic rotation (wrt to global world) at lower case
896
+ # Intrinsic (WRT the object itself) upper case.
897
+ seq = seq.upper()
898
+
899
+ rot = Rotation.from_euler(seq, angles, degrees=True)
900
+ with pytest.warns(UserWarning, match="Gimbal lock"):
901
+ estimates_matrix = rot._as_euler_from_matrix(seq, degrees=True)
902
+ with pytest.warns(UserWarning, match="Gimbal lock"):
903
+ estimates_quat = rot.as_euler(seq, degrees=True)
904
+ assert_allclose(
905
+ estimates_matrix[:, [0, 2]], estimates_quat[:, [0, 2]], atol=0, rtol=1e-12
906
+ )
907
+
908
+ assert_allclose(
909
+ estimates_matrix[~idx, 1], estimates_quat[~idx, 1], atol=0, rtol=1e-7
910
+ )
911
+
912
+ assert_allclose(
913
+ estimates_matrix[idx, 1], estimates_quat[idx, 1], atol=1e-6
914
+ ) # problematic, angles[1] = 0
915
+
916
+
917
+ def test_inv():
918
+ rnd = np.random.RandomState(0)
919
+ n = 10
920
+ # preserve use of old random_state during SPEC 7 transition
921
+ p = Rotation.random(num=n, random_state=rnd)
922
+ q = p.inv()
923
+
924
+ p_mat = p.as_matrix()
925
+ q_mat = q.as_matrix()
926
+ result1 = np.einsum('...ij,...jk->...ik', p_mat, q_mat)
927
+ result2 = np.einsum('...ij,...jk->...ik', q_mat, p_mat)
928
+
929
+ eye3d = np.empty((n, 3, 3))
930
+ eye3d[:] = np.eye(3)
931
+
932
+ assert_array_almost_equal(result1, eye3d)
933
+ assert_array_almost_equal(result2, eye3d)
934
+
935
+
936
+ def test_inv_single_rotation():
937
+ rng = np.random.default_rng(146972845698875399755764481408308808739)
938
+ p = Rotation.random(rng=rng)
939
+ q = p.inv()
940
+
941
+ p_mat = p.as_matrix()
942
+ q_mat = q.as_matrix()
943
+ res1 = np.dot(p_mat, q_mat)
944
+ res2 = np.dot(q_mat, p_mat)
945
+
946
+ eye = np.eye(3)
947
+
948
+ assert_array_almost_equal(res1, eye)
949
+ assert_array_almost_equal(res2, eye)
950
+
951
+ x = Rotation.random(num=1, rng=rng)
952
+ y = x.inv()
953
+
954
+ x_matrix = x.as_matrix()
955
+ y_matrix = y.as_matrix()
956
+ result1 = np.einsum('...ij,...jk->...ik', x_matrix, y_matrix)
957
+ result2 = np.einsum('...ij,...jk->...ik', y_matrix, x_matrix)
958
+
959
+ eye3d = np.empty((1, 3, 3))
960
+ eye3d[:] = np.eye(3)
961
+
962
+ assert_array_almost_equal(result1, eye3d)
963
+ assert_array_almost_equal(result2, eye3d)
964
+
965
+
966
+ def test_identity_magnitude():
967
+ n = 10
968
+ assert_allclose(Rotation.identity(n).magnitude(), 0)
969
+ assert_allclose(Rotation.identity(n).inv().magnitude(), 0)
970
+
971
+
972
+ def test_single_identity_magnitude():
973
+ assert Rotation.identity().magnitude() == 0
974
+ assert Rotation.identity().inv().magnitude() == 0
975
+
976
+
977
+ def test_identity_invariance():
978
+ n = 10
979
+ p = Rotation.random(n, rng=0)
980
+
981
+ result = p * Rotation.identity(n)
982
+ assert_array_almost_equal(p.as_quat(), result.as_quat())
983
+
984
+ result = result * p.inv()
985
+ assert_array_almost_equal(result.magnitude(), np.zeros(n))
986
+
987
+
988
+ def test_single_identity_invariance():
989
+ n = 10
990
+ p = Rotation.random(n, rng=0)
991
+
992
+ result = p * Rotation.identity()
993
+ assert_array_almost_equal(p.as_quat(), result.as_quat())
994
+
995
+ result = result * p.inv()
996
+ assert_array_almost_equal(result.magnitude(), np.zeros(n))
997
+
998
+
999
+ def test_magnitude():
1000
+ r = Rotation.from_quat(np.eye(4))
1001
+ result = r.magnitude()
1002
+ assert_array_almost_equal(result, [np.pi, np.pi, np.pi, 0])
1003
+
1004
+ r = Rotation.from_quat(-np.eye(4))
1005
+ result = r.magnitude()
1006
+ assert_array_almost_equal(result, [np.pi, np.pi, np.pi, 0])
1007
+
1008
+
1009
+ def test_magnitude_single_rotation():
1010
+ r = Rotation.from_quat(np.eye(4))
1011
+ result1 = r[0].magnitude()
1012
+ assert_allclose(result1, np.pi)
1013
+
1014
+ result2 = r[3].magnitude()
1015
+ assert_allclose(result2, 0)
1016
+
1017
+
1018
+ def test_approx_equal():
1019
+ rng = np.random.default_rng(146972845698875399755764481408308808739)
1020
+ p = Rotation.random(10, rng=rng)
1021
+ q = Rotation.random(10, rng=rng)
1022
+ r = p * q.inv()
1023
+ r_mag = r.magnitude()
1024
+ atol = np.median(r_mag) # ensure we get mix of Trues and Falses
1025
+ assert_equal(p.approx_equal(q, atol), (r_mag < atol))
1026
+
1027
+
1028
+ @pytest.mark.thread_unsafe
1029
+ def test_approx_equal_single_rotation():
1030
+ # also tests passing single argument to approx_equal
1031
+ p = Rotation.from_rotvec([0, 0, 1e-9]) # less than default atol of 1e-8
1032
+ q = Rotation.from_quat(np.eye(4))
1033
+ assert p.approx_equal(q[3])
1034
+ assert not p.approx_equal(q[0])
1035
+
1036
+ # test passing atol and using degrees
1037
+ assert not p.approx_equal(q[3], atol=1e-10)
1038
+ assert not p.approx_equal(q[3], atol=1e-8, degrees=True)
1039
+ with pytest.warns(UserWarning, match="atol must be set"):
1040
+ assert p.approx_equal(q[3], degrees=True)
1041
+
1042
+
1043
+ def test_mean():
1044
+ axes = np.concatenate((-np.eye(3), np.eye(3)))
1045
+ thetas = np.linspace(0, np.pi / 2, 100)
1046
+ for t in thetas:
1047
+ r = Rotation.from_rotvec(t * axes)
1048
+ assert_allclose(r.mean().magnitude(), 0, atol=1E-10)
1049
+
1050
+
1051
+ def test_weighted_mean():
1052
+ # test that doubling a weight is equivalent to including a rotation twice.
1053
+ axes = np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0]])
1054
+ thetas = np.linspace(0, np.pi / 2, 100)
1055
+ for t in thetas:
1056
+ rw = Rotation.from_rotvec(t * axes[:2])
1057
+ mw = rw.mean(weights=[1, 2])
1058
+
1059
+ r = Rotation.from_rotvec(t * axes)
1060
+ m = r.mean()
1061
+ assert_allclose((m * mw.inv()).magnitude(), 0, atol=1E-10)
1062
+
1063
+
1064
+ def test_mean_invalid_weights():
1065
+ with pytest.raises(ValueError, match="non-negative"):
1066
+ r = Rotation.from_quat(np.eye(4))
1067
+ r.mean(weights=-np.ones(4))
1068
+
1069
+
1070
+ def test_reduction_no_indices():
1071
+ result = Rotation.identity().reduce(return_indices=False)
1072
+ assert isinstance(result, Rotation)
1073
+
1074
+
1075
+ def test_reduction_none_indices():
1076
+ result = Rotation.identity().reduce(return_indices=True)
1077
+ assert type(result) is tuple
1078
+ assert len(result) == 3
1079
+
1080
+ reduced, left_best, right_best = result
1081
+ assert left_best is None
1082
+ assert right_best is None
1083
+
1084
+
1085
+ def test_reduction_scalar_calculation():
1086
+ rng = np.random.default_rng(146972845698875399755764481408308808739)
1087
+ l = Rotation.random(5, rng=rng)
1088
+ r = Rotation.random(10, rng=rng)
1089
+ p = Rotation.random(7, rng=rng)
1090
+ reduced, left_best, right_best = p.reduce(l, r, return_indices=True)
1091
+
1092
+ # Loop implementation of the vectorized calculation in Rotation.reduce
1093
+ scalars = np.zeros((len(l), len(p), len(r)))
1094
+ for i, li in enumerate(l):
1095
+ for j, pj in enumerate(p):
1096
+ for k, rk in enumerate(r):
1097
+ scalars[i, j, k] = np.abs((li * pj * rk).as_quat()[3])
1098
+ scalars = np.reshape(np.moveaxis(scalars, 1, 0), (scalars.shape[1], -1))
1099
+
1100
+ max_ind = np.argmax(np.reshape(scalars, (len(p), -1)), axis=1)
1101
+ left_best_check = max_ind // len(r)
1102
+ right_best_check = max_ind % len(r)
1103
+ assert (left_best == left_best_check).all()
1104
+ assert (right_best == right_best_check).all()
1105
+
1106
+ reduced_check = l[left_best_check] * p * r[right_best_check]
1107
+ mag = (reduced.inv() * reduced_check).magnitude()
1108
+ assert_array_almost_equal(mag, np.zeros(len(p)))
1109
+
1110
+
1111
+ def test_apply_single_rotation_single_point():
1112
+ mat = np.array([
1113
+ [0, -1, 0],
1114
+ [1, 0, 0],
1115
+ [0, 0, 1]
1116
+ ])
1117
+ r_1d = Rotation.from_matrix(mat)
1118
+ r_2d = Rotation.from_matrix(np.expand_dims(mat, axis=0))
1119
+
1120
+ v_1d = np.array([1, 2, 3])
1121
+ v_2d = np.expand_dims(v_1d, axis=0)
1122
+ v1d_rotated = np.array([-2, 1, 3])
1123
+ v2d_rotated = np.expand_dims(v1d_rotated, axis=0)
1124
+
1125
+ assert_allclose(r_1d.apply(v_1d), v1d_rotated)
1126
+ assert_allclose(r_1d.apply(v_2d), v2d_rotated)
1127
+ assert_allclose(r_2d.apply(v_1d), v2d_rotated)
1128
+ assert_allclose(r_2d.apply(v_2d), v2d_rotated)
1129
+
1130
+ v1d_inverse = np.array([2, -1, 3])
1131
+ v2d_inverse = np.expand_dims(v1d_inverse, axis=0)
1132
+
1133
+ assert_allclose(r_1d.apply(v_1d, inverse=True), v1d_inverse)
1134
+ assert_allclose(r_1d.apply(v_2d, inverse=True), v2d_inverse)
1135
+ assert_allclose(r_2d.apply(v_1d, inverse=True), v2d_inverse)
1136
+ assert_allclose(r_2d.apply(v_2d, inverse=True), v2d_inverse)
1137
+
1138
+
1139
+ def test_apply_single_rotation_multiple_points():
1140
+ mat = np.array([
1141
+ [0, -1, 0],
1142
+ [1, 0, 0],
1143
+ [0, 0, 1]
1144
+ ])
1145
+ r1 = Rotation.from_matrix(mat)
1146
+ r2 = Rotation.from_matrix(np.expand_dims(mat, axis=0))
1147
+
1148
+ v = np.array([[1, 2, 3], [4, 5, 6]])
1149
+ v_rotated = np.array([[-2, 1, 3], [-5, 4, 6]])
1150
+
1151
+ assert_allclose(r1.apply(v), v_rotated)
1152
+ assert_allclose(r2.apply(v), v_rotated)
1153
+
1154
+ v_inverse = np.array([[2, -1, 3], [5, -4, 6]])
1155
+
1156
+ assert_allclose(r1.apply(v, inverse=True), v_inverse)
1157
+ assert_allclose(r2.apply(v, inverse=True), v_inverse)
1158
+
1159
+
1160
+ def test_apply_multiple_rotations_single_point():
1161
+ mat = np.empty((2, 3, 3))
1162
+ mat[0] = np.array([
1163
+ [0, -1, 0],
1164
+ [1, 0, 0],
1165
+ [0, 0, 1]
1166
+ ])
1167
+ mat[1] = np.array([
1168
+ [1, 0, 0],
1169
+ [0, 0, -1],
1170
+ [0, 1, 0]
1171
+ ])
1172
+ r = Rotation.from_matrix(mat)
1173
+
1174
+ v1 = np.array([1, 2, 3])
1175
+ v2 = np.expand_dims(v1, axis=0)
1176
+
1177
+ v_rotated = np.array([[-2, 1, 3], [1, -3, 2]])
1178
+
1179
+ assert_allclose(r.apply(v1), v_rotated)
1180
+ assert_allclose(r.apply(v2), v_rotated)
1181
+
1182
+ v_inverse = np.array([[2, -1, 3], [1, 3, -2]])
1183
+
1184
+ assert_allclose(r.apply(v1, inverse=True), v_inverse)
1185
+ assert_allclose(r.apply(v2, inverse=True), v_inverse)
1186
+
1187
+
1188
+ def test_apply_multiple_rotations_multiple_points():
1189
+ mat = np.empty((2, 3, 3))
1190
+ mat[0] = np.array([
1191
+ [0, -1, 0],
1192
+ [1, 0, 0],
1193
+ [0, 0, 1]
1194
+ ])
1195
+ mat[1] = np.array([
1196
+ [1, 0, 0],
1197
+ [0, 0, -1],
1198
+ [0, 1, 0]
1199
+ ])
1200
+ r = Rotation.from_matrix(mat)
1201
+
1202
+ v = np.array([[1, 2, 3], [4, 5, 6]])
1203
+ v_rotated = np.array([[-2, 1, 3], [4, -6, 5]])
1204
+ assert_allclose(r.apply(v), v_rotated)
1205
+
1206
+ v_inverse = np.array([[2, -1, 3], [4, 6, -5]])
1207
+ assert_allclose(r.apply(v, inverse=True), v_inverse)
1208
+
1209
+
1210
+ def test_getitem():
1211
+ mat = np.empty((2, 3, 3))
1212
+ mat[0] = np.array([
1213
+ [0, -1, 0],
1214
+ [1, 0, 0],
1215
+ [0, 0, 1]
1216
+ ])
1217
+ mat[1] = np.array([
1218
+ [1, 0, 0],
1219
+ [0, 0, -1],
1220
+ [0, 1, 0]
1221
+ ])
1222
+ r = Rotation.from_matrix(mat)
1223
+
1224
+ assert_allclose(r[0].as_matrix(), mat[0], atol=1e-15)
1225
+ assert_allclose(r[1].as_matrix(), mat[1], atol=1e-15)
1226
+ assert_allclose(r[:-1].as_matrix(), np.expand_dims(mat[0], axis=0), atol=1e-15)
1227
+
1228
+
1229
+ def test_getitem_single():
1230
+ with pytest.raises(TypeError, match='not subscriptable'):
1231
+ Rotation.identity()[0]
1232
+
1233
+
1234
+ def test_setitem_single():
1235
+ r = Rotation.identity()
1236
+ with pytest.raises(TypeError, match='not subscriptable'):
1237
+ r[0] = Rotation.identity()
1238
+
1239
+
1240
+ def test_setitem_slice():
1241
+ rng = np.random.default_rng(146972845698875399755764481408308808739)
1242
+ r1 = Rotation.random(10, rng=rng)
1243
+ r2 = Rotation.random(5, rng=rng)
1244
+ r1[1:6] = r2
1245
+ assert_equal(r1[1:6].as_quat(), r2.as_quat())
1246
+
1247
+
1248
+ def test_setitem_integer():
1249
+ rng = np.random.default_rng(146972845698875399755764481408308808739)
1250
+ r1 = Rotation.random(10, rng=rng)
1251
+ r2 = Rotation.random(rng=rng)
1252
+ r1[1] = r2
1253
+ assert_equal(r1[1].as_quat(), r2.as_quat())
1254
+
1255
+
1256
+ def test_setitem_wrong_type():
1257
+ r = Rotation.random(10, rng=0)
1258
+ with pytest.raises(TypeError, match='Rotation object'):
1259
+ r[0] = 1
1260
+
1261
+
1262
+ def test_n_rotations():
1263
+ mat = np.empty((2, 3, 3))
1264
+ mat[0] = np.array([
1265
+ [0, -1, 0],
1266
+ [1, 0, 0],
1267
+ [0, 0, 1]
1268
+ ])
1269
+ mat[1] = np.array([
1270
+ [1, 0, 0],
1271
+ [0, 0, -1],
1272
+ [0, 1, 0]
1273
+ ])
1274
+ r = Rotation.from_matrix(mat)
1275
+
1276
+ assert_equal(len(r), 2)
1277
+ assert_equal(len(r[:-1]), 1)
1278
+
1279
+
1280
+ def test_random_rotation_shape():
1281
+ rng = np.random.default_rng(146972845698875399755764481408308808739)
1282
+ assert_equal(Rotation.random(rng=rng).as_quat().shape, (4,))
1283
+ assert_equal(Rotation.random(None, rng=rng).as_quat().shape, (4,))
1284
+
1285
+ assert_equal(Rotation.random(1, rng=rng).as_quat().shape, (1, 4))
1286
+ assert_equal(Rotation.random(5, rng=rng).as_quat().shape, (5, 4))
1287
+
1288
+
1289
+ def test_align_vectors_no_rotation():
1290
+ x = np.array([[1, 2, 3], [4, 5, 6]])
1291
+ y = x.copy()
1292
+
1293
+ r, rssd = Rotation.align_vectors(x, y)
1294
+ assert_array_almost_equal(r.as_matrix(), np.eye(3))
1295
+ assert_allclose(rssd, 0, atol=1e-6)
1296
+
1297
+
1298
+ def test_align_vectors_no_noise():
1299
+ rng = np.random.default_rng(14697284569885399755764481408308808739)
1300
+ c = Rotation.random(rng=rng)
1301
+ b = rng.normal(size=(5, 3))
1302
+ a = c.apply(b)
1303
+
1304
+ est, rssd = Rotation.align_vectors(a, b)
1305
+ assert_allclose(c.as_quat(), est.as_quat())
1306
+ assert_allclose(rssd, 0, atol=1e-7)
1307
+
1308
+
1309
+ def test_align_vectors_improper_rotation():
1310
+ # Tests correct logic for issue #10444
1311
+ x = np.array([[0.89299824, -0.44372674, 0.0752378],
1312
+ [0.60221789, -0.47564102, -0.6411702]])
1313
+ y = np.array([[0.02386536, -0.82176463, 0.5693271],
1314
+ [-0.27654929, -0.95191427, -0.1318321]])
1315
+
1316
+ est, rssd = Rotation.align_vectors(x, y)
1317
+ assert_allclose(x, est.apply(y), atol=1e-6)
1318
+ assert_allclose(rssd, 0, atol=1e-7)
1319
+
1320
+
1321
+ def test_align_vectors_rssd_sensitivity():
1322
+ rssd_expected = 0.141421356237308
1323
+ sens_expected = np.array([[0.2, 0. , 0.],
1324
+ [0. , 1.5, 1.],
1325
+ [0. , 1. , 1.]])
1326
+ atol = 1e-6
1327
+ a = [[0, 1, 0], [0, 1, 1], [0, 1, 1]]
1328
+ b = [[1, 0, 0], [1, 1.1, 0], [1, 0.9, 0]]
1329
+ rot, rssd, sens = Rotation.align_vectors(a, b, return_sensitivity=True)
1330
+ assert np.isclose(rssd, rssd_expected, atol=atol)
1331
+ assert np.allclose(sens, sens_expected, atol=atol)
1332
+
1333
+
1334
+ def test_align_vectors_scaled_weights():
1335
+ n = 10
1336
+ a = Rotation.random(n, rng=0).apply([1, 0, 0])
1337
+ b = Rotation.random(n, rng=1).apply([1, 0, 0])
1338
+ scale = 2
1339
+
1340
+ est1, rssd1, cov1 = Rotation.align_vectors(a, b, np.ones(n), True)
1341
+ est2, rssd2, cov2 = Rotation.align_vectors(a, b, scale * np.ones(n), True)
1342
+
1343
+ assert_allclose(est1.as_matrix(), est2.as_matrix())
1344
+ assert_allclose(np.sqrt(scale) * rssd1, rssd2, atol=1e-6)
1345
+ assert_allclose(cov1, cov2)
1346
+
1347
+
1348
+ def test_align_vectors_noise():
1349
+ rng = np.random.default_rng(146972845698875399755764481408308808739)
1350
+ n_vectors = 100
1351
+ rot = Rotation.random(rng=rng)
1352
+ vectors = rng.normal(size=(n_vectors, 3))
1353
+ result = rot.apply(vectors)
1354
+
1355
+ # The paper adds noise as independently distributed angular errors
1356
+ sigma = np.deg2rad(1)
1357
+ tolerance = 1.5 * sigma
1358
+ noise = Rotation.from_rotvec(
1359
+ rng.normal(
1360
+ size=(n_vectors, 3),
1361
+ scale=sigma
1362
+ )
1363
+ )
1364
+
1365
+ # Attitude errors must preserve norm. Hence apply individual random
1366
+ # rotations to each vector.
1367
+ noisy_result = noise.apply(result)
1368
+
1369
+ est, rssd, cov = Rotation.align_vectors(noisy_result, vectors,
1370
+ return_sensitivity=True)
1371
+
1372
+ # Use rotation compositions to find out closeness
1373
+ error_vector = (rot * est.inv()).as_rotvec()
1374
+ assert_allclose(error_vector[0], 0, atol=tolerance)
1375
+ assert_allclose(error_vector[1], 0, atol=tolerance)
1376
+ assert_allclose(error_vector[2], 0, atol=tolerance)
1377
+
1378
+ # Check error bounds using covariance matrix
1379
+ cov *= sigma
1380
+ assert_allclose(cov[0, 0], 0, atol=tolerance)
1381
+ assert_allclose(cov[1, 1], 0, atol=tolerance)
1382
+ assert_allclose(cov[2, 2], 0, atol=tolerance)
1383
+
1384
+ assert_allclose(rssd, np.sum((noisy_result - est.apply(vectors))**2)**0.5)
1385
+
1386
+
1387
+ def test_align_vectors_invalid_input():
1388
+ with pytest.raises(ValueError, match="Expected input `a` to have shape"):
1389
+ Rotation.align_vectors([1, 2, 3, 4], [1, 2, 3])
1390
+
1391
+ with pytest.raises(ValueError, match="Expected input `b` to have shape"):
1392
+ Rotation.align_vectors([1, 2, 3], [1, 2, 3, 4])
1393
+
1394
+ with pytest.raises(ValueError, match="Expected inputs `a` and `b` "
1395
+ "to have same shapes"):
1396
+ Rotation.align_vectors([[1, 2, 3],[4, 5, 6]], [[1, 2, 3]])
1397
+
1398
+ with pytest.raises(ValueError,
1399
+ match="Expected `weights` to be 1 dimensional"):
1400
+ Rotation.align_vectors([[1, 2, 3]], [[1, 2, 3]], weights=[[1]])
1401
+
1402
+ with pytest.raises(ValueError,
1403
+ match="Expected `weights` to have number of values"):
1404
+ Rotation.align_vectors([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]],
1405
+ weights=[1, 2, 3])
1406
+
1407
+ with pytest.raises(ValueError,
1408
+ match="`weights` may not contain negative values"):
1409
+ Rotation.align_vectors([[1, 2, 3]], [[1, 2, 3]], weights=[-1])
1410
+
1411
+ with pytest.raises(ValueError,
1412
+ match="Only one infinite weight is allowed"):
1413
+ Rotation.align_vectors([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]],
1414
+ weights=[np.inf, np.inf])
1415
+
1416
+ with pytest.raises(ValueError,
1417
+ match="Cannot align zero length primary vectors"):
1418
+ Rotation.align_vectors([[0, 0, 0]], [[1, 2, 3]])
1419
+
1420
+ with pytest.raises(ValueError,
1421
+ match="Cannot return sensitivity matrix"):
1422
+ Rotation.align_vectors([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]],
1423
+ return_sensitivity=True, weights=[np.inf, 1])
1424
+
1425
+ with pytest.raises(ValueError,
1426
+ match="Cannot return sensitivity matrix"):
1427
+ Rotation.align_vectors([[1, 2, 3]], [[1, 2, 3]],
1428
+ return_sensitivity=True)
1429
+
1430
+
1431
+ def test_align_vectors_align_constrain():
1432
+ # Align the primary +X B axis with the primary +Y A axis, and rotate about
1433
+ # it such that the +Y B axis (residual of the [1, 1, 0] secondary b vector)
1434
+ # is aligned with the +Z A axis (residual of the [0, 1, 1] secondary a
1435
+ # vector)
1436
+ atol = 1e-12
1437
+ b = [[1, 0, 0], [1, 1, 0]]
1438
+ a = [[0, 1, 0], [0, 1, 1]]
1439
+ m_expected = np.array([[0, 0, 1],
1440
+ [1, 0, 0],
1441
+ [0, 1, 0]])
1442
+ R, rssd = Rotation.align_vectors(a, b, weights=[np.inf, 1])
1443
+ assert_allclose(R.as_matrix(), m_expected, atol=atol)
1444
+ assert_allclose(R.apply(b), a, atol=atol) # Pri and sec align exactly
1445
+ assert np.isclose(rssd, 0, atol=atol)
1446
+
1447
+ # Do the same but with an inexact secondary rotation
1448
+ b = [[1, 0, 0], [1, 2, 0]]
1449
+ rssd_expected = 1.0
1450
+ R, rssd = Rotation.align_vectors(a, b, weights=[np.inf, 1])
1451
+ assert_allclose(R.as_matrix(), m_expected, atol=atol)
1452
+ assert_allclose(R.apply(b)[0], a[0], atol=atol) # Only pri aligns exactly
1453
+ assert np.isclose(rssd, rssd_expected, atol=atol)
1454
+ a_expected = [[0, 1, 0], [0, 1, 2]]
1455
+ assert_allclose(R.apply(b), a_expected, atol=atol)
1456
+
1457
+ # Check random vectors
1458
+ b = [[1, 2, 3], [-2, 3, -1]]
1459
+ a = [[-1, 3, 2], [1, -1, 2]]
1460
+ rssd_expected = 1.3101595297515016
1461
+ R, rssd = Rotation.align_vectors(a, b, weights=[np.inf, 1])
1462
+ assert_allclose(R.apply(b)[0], a[0], atol=atol) # Only pri aligns exactly
1463
+ assert np.isclose(rssd, rssd_expected, atol=atol)
1464
+
1465
+
1466
+ def test_align_vectors_near_inf():
1467
+ # align_vectors should return near the same result for high weights as for
1468
+ # infinite weights. rssd will be different with floating point error on the
1469
+ # exactly aligned vector being multiplied by a large non-infinite weight
1470
+ n = 100
1471
+ mats = []
1472
+ for i in range(6):
1473
+ mats.append(Rotation.random(n, rng=10 + i).as_matrix())
1474
+
1475
+ for i in range(n):
1476
+ # Get random pairs of 3-element vectors
1477
+ a = [1*mats[0][i][0], 2*mats[1][i][0]]
1478
+ b = [3*mats[2][i][0], 4*mats[3][i][0]]
1479
+
1480
+ R, _ = Rotation.align_vectors(a, b, weights=[1e10, 1])
1481
+ R2, _ = Rotation.align_vectors(a, b, weights=[np.inf, 1])
1482
+ assert_allclose(R.as_matrix(), R2.as_matrix(), atol=1e-4)
1483
+
1484
+ for i in range(n):
1485
+ # Get random triplets of 3-element vectors
1486
+ a = [1*mats[0][i][0], 2*mats[1][i][0], 3*mats[2][i][0]]
1487
+ b = [4*mats[3][i][0], 5*mats[4][i][0], 6*mats[5][i][0]]
1488
+
1489
+ R, _ = Rotation.align_vectors(a, b, weights=[1e10, 2, 1])
1490
+ R2, _ = Rotation.align_vectors(a, b, weights=[np.inf, 2, 1])
1491
+ assert_allclose(R.as_matrix(), R2.as_matrix(), atol=1e-4)
1492
+
1493
+
1494
+ def test_align_vectors_parallel():
1495
+ atol = 1e-12
1496
+ a = [[1, 0, 0], [0, 1, 0]]
1497
+ b = [[0, 1, 0], [0, 1, 0]]
1498
+ m_expected = np.array([[0, 1, 0],
1499
+ [-1, 0, 0],
1500
+ [0, 0, 1]])
1501
+ R, _ = Rotation.align_vectors(a, b, weights=[np.inf, 1])
1502
+ assert_allclose(R.as_matrix(), m_expected, atol=atol)
1503
+ R, _ = Rotation.align_vectors(a[0], b[0])
1504
+ assert_allclose(R.as_matrix(), m_expected, atol=atol)
1505
+ assert_allclose(R.apply(b[0]), a[0], atol=atol)
1506
+
1507
+ b = [[1, 0, 0], [1, 0, 0]]
1508
+ m_expected = np.array([[1, 0, 0],
1509
+ [0, 1, 0],
1510
+ [0, 0, 1]])
1511
+ R, _ = Rotation.align_vectors(a, b, weights=[np.inf, 1])
1512
+ assert_allclose(R.as_matrix(), m_expected, atol=atol)
1513
+ R, _ = Rotation.align_vectors(a[0], b[0])
1514
+ assert_allclose(R.as_matrix(), m_expected, atol=atol)
1515
+ assert_allclose(R.apply(b[0]), a[0], atol=atol)
1516
+
1517
+
1518
+ def test_align_vectors_antiparallel():
1519
+ # Test exact 180 deg rotation
1520
+ atol = 1e-12
1521
+ as_to_test = np.array([[[1, 0, 0], [0, 1, 0]],
1522
+ [[0, 1, 0], [1, 0, 0]],
1523
+ [[0, 0, 1], [0, 1, 0]]])
1524
+ bs_to_test = [[-a[0], a[1]] for a in as_to_test]
1525
+ for a, b in zip(as_to_test, bs_to_test):
1526
+ R, _ = Rotation.align_vectors(a, b, weights=[np.inf, 1])
1527
+ assert_allclose(R.magnitude(), np.pi, atol=atol)
1528
+ assert_allclose(R.apply(b[0]), a[0], atol=atol)
1529
+
1530
+ # Test exact rotations near 180 deg
1531
+ Rs = Rotation.random(100, rng=0)
1532
+ dRs = Rotation.from_rotvec(Rs.as_rotvec()*1e-4) # scale down to small angle
1533
+ a = [[ 1, 0, 0], [0, 1, 0]]
1534
+ b = [[-1, 0, 0], [0, 1, 0]]
1535
+ as_to_test = []
1536
+ for dR in dRs:
1537
+ as_to_test.append([dR.apply(a[0]), a[1]])
1538
+ for a in as_to_test:
1539
+ R, _ = Rotation.align_vectors(a, b, weights=[np.inf, 1])
1540
+ R2, _ = Rotation.align_vectors(a, b, weights=[1e10, 1])
1541
+ assert_allclose(R.as_matrix(), R2.as_matrix(), atol=atol)
1542
+
1543
+
1544
+ def test_align_vectors_primary_only():
1545
+ atol = 1e-12
1546
+ mats_a = Rotation.random(100, rng=0).as_matrix()
1547
+ mats_b = Rotation.random(100, rng=1).as_matrix()
1548
+ for mat_a, mat_b in zip(mats_a, mats_b):
1549
+ # Get random 3-element unit vectors
1550
+ a = mat_a[0]
1551
+ b = mat_b[0]
1552
+
1553
+ # Compare to align_vectors with primary only
1554
+ R, rssd = Rotation.align_vectors(a, b)
1555
+ assert_allclose(R.apply(b), a, atol=atol)
1556
+ assert np.isclose(rssd, 0, atol=atol)
1557
+
1558
+
1559
+ def test_slerp():
1560
+ rnd = np.random.RandomState(0)
1561
+
1562
+ key_rots = Rotation.from_quat(rnd.uniform(size=(5, 4)))
1563
+ key_quats = key_rots.as_quat()
1564
+
1565
+ key_times = [0, 1, 2, 3, 4]
1566
+ interpolator = Slerp(key_times, key_rots)
1567
+
1568
+ times = [0, 0.5, 0.25, 1, 1.5, 2, 2.75, 3, 3.25, 3.60, 4]
1569
+ interp_rots = interpolator(times)
1570
+ interp_quats = interp_rots.as_quat()
1571
+
1572
+ # Dot products are affected by sign of quaternions
1573
+ interp_quats[interp_quats[:, -1] < 0] *= -1
1574
+ # Checking for quaternion equality, perform same operation
1575
+ key_quats[key_quats[:, -1] < 0] *= -1
1576
+
1577
+ # Equality at keyframes, including both endpoints
1578
+ assert_allclose(interp_quats[0], key_quats[0])
1579
+ assert_allclose(interp_quats[3], key_quats[1])
1580
+ assert_allclose(interp_quats[5], key_quats[2])
1581
+ assert_allclose(interp_quats[7], key_quats[3])
1582
+ assert_allclose(interp_quats[10], key_quats[4])
1583
+
1584
+ # Constant angular velocity between keyframes. Check by equating
1585
+ # cos(theta) between quaternion pairs with equal time difference.
1586
+ cos_theta1 = np.sum(interp_quats[0] * interp_quats[2])
1587
+ cos_theta2 = np.sum(interp_quats[2] * interp_quats[1])
1588
+ assert_allclose(cos_theta1, cos_theta2)
1589
+
1590
+ cos_theta4 = np.sum(interp_quats[3] * interp_quats[4])
1591
+ cos_theta5 = np.sum(interp_quats[4] * interp_quats[5])
1592
+ assert_allclose(cos_theta4, cos_theta5)
1593
+
1594
+ # theta1: 0 -> 0.25, theta3 : 0.5 -> 1
1595
+ # Use double angle formula for double the time difference
1596
+ cos_theta3 = np.sum(interp_quats[1] * interp_quats[3])
1597
+ assert_allclose(cos_theta3, 2 * (cos_theta1**2) - 1)
1598
+
1599
+ # Miscellaneous checks
1600
+ assert_equal(len(interp_rots), len(times))
1601
+
1602
+
1603
+ def test_slerp_rot_is_rotation():
1604
+ with pytest.raises(TypeError, match="must be a `Rotation` instance"):
1605
+ r = np.array([[1,2,3,4],
1606
+ [0,0,0,1]])
1607
+ t = np.array([0, 1])
1608
+ Slerp(t, r)
1609
+
1610
+ SLERP_EXCEPTION_MESSAGE = "must be a sequence of at least 2 rotations"
1611
+
1612
+ def test_slerp_single_rot():
1613
+ r = Rotation.from_quat([1, 2, 3, 4])
1614
+ with pytest.raises(ValueError, match=SLERP_EXCEPTION_MESSAGE):
1615
+ Slerp([1], r)
1616
+
1617
+
1618
+ def test_slerp_rot_len0():
1619
+ r = Rotation.random()
1620
+ with pytest.raises(ValueError, match=SLERP_EXCEPTION_MESSAGE):
1621
+ Slerp([], r)
1622
+
1623
+
1624
+ def test_slerp_rot_len1():
1625
+ r = Rotation.random(1)
1626
+ with pytest.raises(ValueError, match=SLERP_EXCEPTION_MESSAGE):
1627
+ Slerp([1], r)
1628
+
1629
+
1630
+ def test_slerp_time_dim_mismatch():
1631
+ with pytest.raises(ValueError,
1632
+ match="times to be specified in a 1 dimensional array"):
1633
+ rnd = np.random.RandomState(0)
1634
+ r = Rotation.from_quat(rnd.uniform(size=(2, 4)))
1635
+ t = np.array([[1],
1636
+ [2]])
1637
+ Slerp(t, r)
1638
+
1639
+
1640
+ def test_slerp_num_rotations_mismatch():
1641
+ with pytest.raises(ValueError, match="number of rotations to be equal to "
1642
+ "number of timestamps"):
1643
+ rnd = np.random.RandomState(0)
1644
+ r = Rotation.from_quat(rnd.uniform(size=(5, 4)))
1645
+ t = np.arange(7)
1646
+ Slerp(t, r)
1647
+
1648
+
1649
+ def test_slerp_equal_times():
1650
+ with pytest.raises(ValueError, match="strictly increasing order"):
1651
+ rnd = np.random.RandomState(0)
1652
+ r = Rotation.from_quat(rnd.uniform(size=(5, 4)))
1653
+ t = [0, 1, 2, 2, 4]
1654
+ Slerp(t, r)
1655
+
1656
+
1657
+ def test_slerp_decreasing_times():
1658
+ with pytest.raises(ValueError, match="strictly increasing order"):
1659
+ rnd = np.random.RandomState(0)
1660
+ r = Rotation.from_quat(rnd.uniform(size=(5, 4)))
1661
+ t = [0, 1, 3, 2, 4]
1662
+ Slerp(t, r)
1663
+
1664
+
1665
+ def test_slerp_call_time_dim_mismatch():
1666
+ rnd = np.random.RandomState(0)
1667
+ r = Rotation.from_quat(rnd.uniform(size=(5, 4)))
1668
+ t = np.arange(5)
1669
+ s = Slerp(t, r)
1670
+
1671
+ with pytest.raises(ValueError,
1672
+ match="`times` must be at most 1-dimensional."):
1673
+ interp_times = np.array([[3.5],
1674
+ [4.2]])
1675
+ s(interp_times)
1676
+
1677
+
1678
+ def test_slerp_call_time_out_of_range():
1679
+ rnd = np.random.RandomState(0)
1680
+ r = Rotation.from_quat(rnd.uniform(size=(5, 4)))
1681
+ t = np.arange(5) + 1
1682
+ s = Slerp(t, r)
1683
+
1684
+ with pytest.raises(ValueError, match="times must be within the range"):
1685
+ s([0, 1, 2])
1686
+ with pytest.raises(ValueError, match="times must be within the range"):
1687
+ s([1, 2, 6])
1688
+
1689
+
1690
+ def test_slerp_call_scalar_time():
1691
+ r = Rotation.from_euler('X', [0, 80], degrees=True)
1692
+ s = Slerp([0, 1], r)
1693
+
1694
+ r_interpolated = s(0.25)
1695
+ r_interpolated_expected = Rotation.from_euler('X', 20, degrees=True)
1696
+
1697
+ delta = r_interpolated * r_interpolated_expected.inv()
1698
+
1699
+ assert_allclose(delta.magnitude(), 0, atol=1e-16)
1700
+
1701
+
1702
+ def test_multiplication_stability():
1703
+ qs = Rotation.random(50, rng=0)
1704
+ rs = Rotation.random(1000, rng=1)
1705
+ for q in qs:
1706
+ rs *= q * rs
1707
+ assert_allclose(np.linalg.norm(rs.as_quat(), axis=1), 1)
1708
+
1709
+
1710
+ def test_pow():
1711
+ atol = 1e-14
1712
+ p = Rotation.random(10, rng=0)
1713
+ p_inv = p.inv()
1714
+ # Test the short-cuts and other integers
1715
+ for n in [-5, -2, -1, 0, 1, 2, 5]:
1716
+ # Test accuracy
1717
+ q = p ** n
1718
+ r = Rotation.identity(10)
1719
+ for _ in range(abs(n)):
1720
+ if n > 0:
1721
+ r = r * p
1722
+ else:
1723
+ r = r * p_inv
1724
+ ang = (q * r.inv()).magnitude()
1725
+ assert np.all(ang < atol)
1726
+
1727
+ # Test shape preservation
1728
+ r = Rotation.from_quat([0, 0, 0, 1])
1729
+ assert (r**n).as_quat().shape == (4,)
1730
+ r = Rotation.from_quat([[0, 0, 0, 1]])
1731
+ assert (r**n).as_quat().shape == (1, 4)
1732
+
1733
+ # Large angle fractional
1734
+ for n in [-1.5, -0.5, -0.0, 0.0, 0.5, 1.5]:
1735
+ q = p ** n
1736
+ r = Rotation.from_rotvec(n * p.as_rotvec())
1737
+ assert_allclose(q.as_quat(), r.as_quat(), atol=atol)
1738
+
1739
+ # Small angle
1740
+ p = Rotation.from_rotvec([1e-12, 0, 0])
1741
+ n = 3
1742
+ q = p ** n
1743
+ r = Rotation.from_rotvec(n * p.as_rotvec())
1744
+ assert_allclose(q.as_quat(), r.as_quat(), atol=atol)
1745
+
1746
+
1747
+ def test_pow_errors():
1748
+ p = Rotation.random(rng=0)
1749
+ with pytest.raises(NotImplementedError, match='modulus not supported'):
1750
+ pow(p, 1, 1)
1751
+
1752
+
1753
+ def test_rotation_within_numpy_array():
1754
+ single = Rotation.random(rng=0)
1755
+ multiple = Rotation.random(2, rng=1)
1756
+
1757
+ array = np.array(single)
1758
+ assert_equal(array.shape, ())
1759
+
1760
+ array = np.array(multiple)
1761
+ assert_equal(array.shape, (2,))
1762
+ assert_allclose(array[0].as_matrix(), multiple[0].as_matrix())
1763
+ assert_allclose(array[1].as_matrix(), multiple[1].as_matrix())
1764
+
1765
+ array = np.array([single])
1766
+ assert_equal(array.shape, (1,))
1767
+ assert_equal(array[0], single)
1768
+
1769
+ array = np.array([multiple])
1770
+ assert_equal(array.shape, (1, 2))
1771
+ assert_allclose(array[0, 0].as_matrix(), multiple[0].as_matrix())
1772
+ assert_allclose(array[0, 1].as_matrix(), multiple[1].as_matrix())
1773
+
1774
+ array = np.array([single, multiple], dtype=object)
1775
+ assert_equal(array.shape, (2,))
1776
+ assert_equal(array[0], single)
1777
+ assert_equal(array[1], multiple)
1778
+
1779
+ array = np.array([multiple, multiple, multiple])
1780
+ assert_equal(array.shape, (3, 2))
1781
+
1782
+
1783
+ def test_pickling():
1784
+ r = Rotation.from_quat([0, 0, np.sin(np.pi/4), np.cos(np.pi/4)])
1785
+ pkl = pickle.dumps(r)
1786
+ unpickled = pickle.loads(pkl)
1787
+ assert_allclose(r.as_matrix(), unpickled.as_matrix(), atol=1e-15)
1788
+
1789
+
1790
+ def test_deepcopy():
1791
+ r = Rotation.from_quat([0, 0, np.sin(np.pi/4), np.cos(np.pi/4)])
1792
+ r1 = copy.deepcopy(r)
1793
+ assert_allclose(r.as_matrix(), r1.as_matrix(), atol=1e-15)
1794
+
1795
+
1796
+ def test_as_euler_contiguous():
1797
+ r = Rotation.from_quat([0, 0, 0, 1])
1798
+ e1 = r.as_euler('xyz') # extrinsic euler rotation
1799
+ e2 = r.as_euler('XYZ') # intrinsic
1800
+ assert e1.flags['C_CONTIGUOUS'] is True
1801
+ assert e2.flags['C_CONTIGUOUS'] is True
1802
+ assert all(i >= 0 for i in e1.strides)
1803
+ assert all(i >= 0 for i in e2.strides)
1804
+
1805
+
1806
+ def test_concatenate():
1807
+ rotation = Rotation.random(10, rng=0)
1808
+ sizes = [1, 2, 3, 1, 3]
1809
+ starts = [0] + list(np.cumsum(sizes))
1810
+ split = [rotation[i:i + n] for i, n in zip(starts, sizes)]
1811
+ result = Rotation.concatenate(split)
1812
+ assert_equal(rotation.as_quat(), result.as_quat())
1813
+
1814
+ # Test Rotation input for multiple rotations
1815
+ result = Rotation.concatenate(rotation)
1816
+ assert_equal(rotation.as_quat(), result.as_quat())
1817
+
1818
+ # Test that a copy is returned
1819
+ assert rotation is not result
1820
+
1821
+ # Test Rotation input for single rotations
1822
+ result = Rotation.concatenate(Rotation.identity())
1823
+ assert_equal(Rotation.identity().as_quat(), result.as_quat())
1824
+
1825
+
1826
+ def test_concatenate_wrong_type():
1827
+ with pytest.raises(TypeError, match='Rotation objects only'):
1828
+ Rotation.concatenate([Rotation.identity(), 1, None])
1829
+
1830
+
1831
+ # Regression test for gh-16663
1832
+ def test_len_and_bool():
1833
+ rotation_multi_one = Rotation([[0, 0, 0, 1]])
1834
+ rotation_multi = Rotation([[0, 0, 0, 1], [0, 0, 0, 1]])
1835
+ rotation_single = Rotation([0, 0, 0, 1])
1836
+
1837
+ assert len(rotation_multi_one) == 1
1838
+ assert len(rotation_multi) == 2
1839
+ with pytest.raises(TypeError, match="Single rotation has no len()."):
1840
+ len(rotation_single)
1841
+
1842
+ # Rotation should always be truthy. See gh-16663
1843
+ assert rotation_multi_one
1844
+ assert rotation_multi
1845
+ assert rotation_single
1846
+
1847
+
1848
+ def test_from_davenport_single_rotation():
1849
+ axis = [0, 0, 1]
1850
+ quat = Rotation.from_davenport(axis, 'extrinsic', 90,
1851
+ degrees=True).as_quat()
1852
+ expected_quat = np.array([0, 0, 1, 1]) / np.sqrt(2)
1853
+ assert_allclose(quat, expected_quat)
1854
+
1855
+
1856
+ def test_from_davenport_one_or_two_axes():
1857
+ ez = [0, 0, 1]
1858
+ ey = [0, 1, 0]
1859
+
1860
+ # Single rotation, single axis, axes.shape == (3, )
1861
+ rot = Rotation.from_rotvec(np.array(ez) * np.pi/4)
1862
+ rot_dav = Rotation.from_davenport(ez, 'e', np.pi/4)
1863
+ assert_allclose(rot.as_quat(canonical=True),
1864
+ rot_dav.as_quat(canonical=True))
1865
+
1866
+ # Single rotation, single axis, axes.shape == (1, 3)
1867
+ rot = Rotation.from_rotvec([np.array(ez) * np.pi/4])
1868
+ rot_dav = Rotation.from_davenport([ez], 'e', [np.pi/4])
1869
+ assert_allclose(rot.as_quat(canonical=True),
1870
+ rot_dav.as_quat(canonical=True))
1871
+
1872
+ # Single rotation, two axes, axes.shape == (2, 3)
1873
+ rot = Rotation.from_rotvec([np.array(ez) * np.pi/4,
1874
+ np.array(ey) * np.pi/6])
1875
+ rot = rot[0] * rot[1]
1876
+ rot_dav = Rotation.from_davenport([ey, ez], 'e', [np.pi/6, np.pi/4])
1877
+ assert_allclose(rot.as_quat(canonical=True),
1878
+ rot_dav.as_quat(canonical=True))
1879
+
1880
+ # Two rotations, single axis, axes.shape == (3, )
1881
+ rot = Rotation.from_rotvec([np.array(ez) * np.pi/6,
1882
+ np.array(ez) * np.pi/4])
1883
+ rot_dav = Rotation.from_davenport([ez], 'e', [np.pi/6, np.pi/4])
1884
+ assert_allclose(rot.as_quat(canonical=True),
1885
+ rot_dav.as_quat(canonical=True))
1886
+
1887
+
1888
+ def test_from_davenport_invalid_input():
1889
+ ez = [0, 0, 1]
1890
+ ey = [0, 1, 0]
1891
+ ezy = [0, 1, 1]
1892
+ with pytest.raises(ValueError, match="must be orthogonal"):
1893
+ Rotation.from_davenport([ez, ezy], 'e', [0, 0])
1894
+ with pytest.raises(ValueError, match="must be orthogonal"):
1895
+ Rotation.from_davenport([ez, ey, ezy], 'e', [0, 0, 0])
1896
+ with pytest.raises(ValueError, match="order should be"):
1897
+ Rotation.from_davenport([ez], 'xyz', [0])
1898
+ with pytest.raises(ValueError, match="Expected `angles`"):
1899
+ Rotation.from_davenport([ez, ey, ez], 'e', [0, 1, 2, 3])
1900
+
1901
+
1902
+ def test_as_davenport():
1903
+ rnd = np.random.RandomState(0)
1904
+ n = 100
1905
+ angles = np.empty((n, 3))
1906
+ angles[:, 0] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,))
1907
+ angles_middle = rnd.uniform(low=0, high=np.pi, size=(n,))
1908
+ angles[:, 2] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,))
1909
+ lambdas = rnd.uniform(low=0, high=np.pi, size=(20,))
1910
+
1911
+ e1 = np.array([1, 0, 0])
1912
+ e2 = np.array([0, 1, 0])
1913
+
1914
+ for lamb in lambdas:
1915
+ ax_lamb = [e1, e2, Rotation.from_rotvec(lamb*e2).apply(e1)]
1916
+ angles[:, 1] = angles_middle - lamb
1917
+ for order in ['extrinsic', 'intrinsic']:
1918
+ ax = ax_lamb if order == 'intrinsic' else ax_lamb[::-1]
1919
+ rot = Rotation.from_davenport(ax, order, angles)
1920
+ angles_dav = rot.as_davenport(ax, order)
1921
+ assert_allclose(angles_dav, angles)
1922
+
1923
+
1924
+ @pytest.mark.thread_unsafe
1925
+ def test_as_davenport_degenerate():
1926
+ # Since we cannot check for angle equality, we check for rotation matrix
1927
+ # equality
1928
+ rnd = np.random.RandomState(0)
1929
+ n = 5
1930
+ angles = np.empty((n, 3))
1931
+
1932
+ # symmetric sequences
1933
+ angles[:, 0] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,))
1934
+ angles_middle = [rnd.choice([0, np.pi]) for i in range(n)]
1935
+ angles[:, 2] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,))
1936
+ lambdas = rnd.uniform(low=0, high=np.pi, size=(5,))
1937
+
1938
+ e1 = np.array([1, 0, 0])
1939
+ e2 = np.array([0, 1, 0])
1940
+
1941
+ for lamb in lambdas:
1942
+ ax_lamb = [e1, e2, Rotation.from_rotvec(lamb*e2).apply(e1)]
1943
+ angles[:, 1] = angles_middle - lamb
1944
+ for order in ['extrinsic', 'intrinsic']:
1945
+ ax = ax_lamb if order == 'intrinsic' else ax_lamb[::-1]
1946
+ rot = Rotation.from_davenport(ax, order, angles)
1947
+ with pytest.warns(UserWarning, match="Gimbal lock"):
1948
+ angles_dav = rot.as_davenport(ax, order)
1949
+ mat_expected = rot.as_matrix()
1950
+ mat_estimated = Rotation.from_davenport(ax, order, angles_dav).as_matrix()
1951
+ assert_array_almost_equal(mat_expected, mat_estimated)
1952
+
1953
+
1954
+ def test_compare_from_davenport_from_euler():
1955
+ rnd = np.random.RandomState(0)
1956
+ n = 100
1957
+ angles = np.empty((n, 3))
1958
+
1959
+ # symmetric sequences
1960
+ angles[:, 0] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,))
1961
+ angles[:, 1] = rnd.uniform(low=0, high=np.pi, size=(n,))
1962
+ angles[:, 2] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,))
1963
+ for order in ['extrinsic', 'intrinsic']:
1964
+ for seq_tuple in permutations('xyz'):
1965
+ seq = ''.join([seq_tuple[0], seq_tuple[1], seq_tuple[0]])
1966
+ ax = [basis_vec(i) for i in seq]
1967
+ if order == 'intrinsic':
1968
+ seq = seq.upper()
1969
+ eul = Rotation.from_euler(seq, angles)
1970
+ dav = Rotation.from_davenport(ax, order, angles)
1971
+ assert_allclose(eul.as_quat(canonical=True), dav.as_quat(canonical=True),
1972
+ rtol=1e-12)
1973
+
1974
+ # asymmetric sequences
1975
+ angles[:, 1] -= np.pi / 2
1976
+ for order in ['extrinsic', 'intrinsic']:
1977
+ for seq_tuple in permutations('xyz'):
1978
+ seq = ''.join(seq_tuple)
1979
+ ax = [basis_vec(i) for i in seq]
1980
+ if order == 'intrinsic':
1981
+ seq = seq.upper()
1982
+ eul = Rotation.from_euler(seq, angles)
1983
+ dav = Rotation.from_davenport(ax, order, angles)
1984
+ assert_allclose(eul.as_quat(), dav.as_quat(), rtol=1e-12)
1985
+
1986
+
1987
+ def test_compare_as_davenport_as_euler():
1988
+ rnd = np.random.RandomState(0)
1989
+ n = 100
1990
+ angles = np.empty((n, 3))
1991
+
1992
+ # symmetric sequences
1993
+ angles[:, 0] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,))
1994
+ angles[:, 1] = rnd.uniform(low=0, high=np.pi, size=(n,))
1995
+ angles[:, 2] = rnd.uniform(low=-np.pi, high=np.pi, size=(n,))
1996
+ for order in ['extrinsic', 'intrinsic']:
1997
+ for seq_tuple in permutations('xyz'):
1998
+ seq = ''.join([seq_tuple[0], seq_tuple[1], seq_tuple[0]])
1999
+ ax = [basis_vec(i) for i in seq]
2000
+ if order == 'intrinsic':
2001
+ seq = seq.upper()
2002
+ rot = Rotation.from_euler(seq, angles)
2003
+ eul = rot.as_euler(seq)
2004
+ dav = rot.as_davenport(ax, order)
2005
+ assert_allclose(eul, dav, rtol=1e-12)
2006
+
2007
+ # asymmetric sequences
2008
+ angles[:, 1] -= np.pi / 2
2009
+ for order in ['extrinsic', 'intrinsic']:
2010
+ for seq_tuple in permutations('xyz'):
2011
+ seq = ''.join(seq_tuple)
2012
+ ax = [basis_vec(i) for i in seq]
2013
+ if order == 'intrinsic':
2014
+ seq = seq.upper()
2015
+ rot = Rotation.from_euler(seq, angles)
2016
+ eul = rot.as_euler(seq)
2017
+ dav = rot.as_davenport(ax, order)
2018
+ assert_allclose(eul, dav, rtol=1e-12)
2019
+
2020
+
2021
+ def test_zero_rotation_construction():
2022
+ r = Rotation.random(num=0)
2023
+ assert len(r) == 0
2024
+
2025
+ r_ide = Rotation.identity(num=0)
2026
+ assert len(r_ide) == 0
2027
+
2028
+ r_get = Rotation.random(num=3)[[]]
2029
+ assert len(r_get) == 0
2030
+
2031
+ r_quat = Rotation.from_quat(np.zeros((0, 4)))
2032
+ assert len(r_quat) == 0
2033
+
2034
+ r_matrix = Rotation.from_matrix(np.zeros((0, 3, 3)))
2035
+ assert len(r_matrix) == 0
2036
+
2037
+ r_euler = Rotation.from_euler("xyz", np.zeros((0, 3)))
2038
+ assert len(r_euler) == 0
2039
+
2040
+ r_vec = Rotation.from_rotvec(np.zeros((0, 3)))
2041
+ assert len(r_vec) == 0
2042
+
2043
+ r_dav = Rotation.from_davenport(np.eye(3), "extrinsic", np.zeros((0, 3)))
2044
+ assert len(r_dav) == 0
2045
+
2046
+ r_mrp = Rotation.from_mrp(np.zeros((0, 3)))
2047
+ assert len(r_mrp) == 0
2048
+
2049
+
2050
+ def test_zero_rotation_representation():
2051
+ r = Rotation.random(num=0)
2052
+ assert r.as_quat().shape == (0, 4)
2053
+ assert r.as_matrix().shape == (0, 3, 3)
2054
+ assert r.as_euler("xyz").shape == (0, 3)
2055
+ assert r.as_rotvec().shape == (0, 3)
2056
+ assert r.as_mrp().shape == (0, 3)
2057
+ assert r.as_davenport(np.eye(3), "extrinsic").shape == (0, 3)
2058
+
2059
+
2060
+ def test_zero_rotation_array_rotation():
2061
+ r = Rotation.random(num=0)
2062
+
2063
+ v = np.array([1, 2, 3])
2064
+ v_rotated = r.apply(v)
2065
+ assert v_rotated.shape == (0, 3)
2066
+
2067
+ v0 = np.zeros((0, 3))
2068
+ v0_rot = r.apply(v0)
2069
+ assert v0_rot.shape == (0, 3)
2070
+
2071
+ v2 = np.ones((2, 3))
2072
+ with pytest.raises(
2073
+ ValueError, match="Expected equal numbers of rotations and vectors"):
2074
+ r.apply(v2)
2075
+
2076
+
2077
+ def test_zero_rotation_multiplication():
2078
+ r = Rotation.random(num=0)
2079
+
2080
+ r_single = Rotation.random()
2081
+ r_mult_left = r * r_single
2082
+ assert len(r_mult_left) == 0
2083
+
2084
+ r_mult_right = r_single * r
2085
+ assert len(r_mult_right) == 0
2086
+
2087
+ r0 = Rotation.random(0)
2088
+ r_mult = r * r0
2089
+ assert len(r_mult) == 0
2090
+
2091
+ msg_rotation_error = "Expected equal number of rotations"
2092
+ r2 = Rotation.random(2)
2093
+ with pytest.raises(ValueError, match=msg_rotation_error):
2094
+ r0 * r2
2095
+
2096
+ with pytest.raises(ValueError, match=msg_rotation_error):
2097
+ r2 * r0
2098
+
2099
+
2100
+ def test_zero_rotation_concatentation():
2101
+ r = Rotation.random(num=0)
2102
+
2103
+ r0 = Rotation.concatenate([r, r])
2104
+ assert len(r0) == 0
2105
+
2106
+ r1 = r.concatenate([Rotation.random(), r])
2107
+ assert len(r1) == 1
2108
+
2109
+ r3 = r.concatenate([Rotation.random(3), r])
2110
+ assert len(r3) == 3
2111
+
2112
+ r4 = r.concatenate([r, Rotation.random(4)])
2113
+ assert len(r4) == 4
2114
+
2115
+
2116
+ def test_zero_rotation_power():
2117
+ r = Rotation.random(num=0)
2118
+ for pp in [-1.5, -1, 0, 1, 1.5]:
2119
+ pow0 = r**pp
2120
+ assert len(pow0) == 0
2121
+
2122
+
2123
+ def test_zero_rotation_inverse():
2124
+ r = Rotation.random(num=0)
2125
+ r_inv = r.inv()
2126
+ assert len(r_inv) == 0
2127
+
2128
+
2129
+ def test_zero_rotation_magnitude():
2130
+ r = Rotation.random(num=0)
2131
+ magnitude = r.magnitude()
2132
+ assert magnitude.shape == (0,)
2133
+
2134
+
2135
+ def test_zero_rotation_mean():
2136
+ r = Rotation.random(num=0)
2137
+ with pytest.raises(ValueError, match="Mean of an empty rotation set is undefined."):
2138
+ r.mean()
2139
+
2140
+
2141
+ def test_zero_rotation_approx_equal():
2142
+ r = Rotation.random(0)
2143
+ assert r.approx_equal(Rotation.random(0)).shape == (0,)
2144
+ assert r.approx_equal(Rotation.random()).shape == (0,)
2145
+ assert Rotation.random().approx_equal(r).shape == (0,)
2146
+
2147
+ approx_msg = "Expected equal number of rotations"
2148
+ r3 = Rotation.random(2)
2149
+ with pytest.raises(ValueError, match=approx_msg):
2150
+ r.approx_equal(r3)
2151
+
2152
+ with pytest.raises(ValueError, match=approx_msg):
2153
+ r3.approx_equal(r)
2154
+
2155
+
2156
+ def test_zero_rotation_get_set():
2157
+ r = Rotation.random(0)
2158
+
2159
+ r_get = r[[]]
2160
+ assert len(r_get) == 0
2161
+
2162
+ r_slice = r[:0]
2163
+ assert len(r_slice) == 0
2164
+
2165
+ with pytest.raises(IndexError):
2166
+ r[[0]]
2167
+
2168
+ with pytest.raises(IndexError):
2169
+ r[[True]]
2170
+
2171
+ with pytest.raises(IndexError):
2172
+ r[0] = Rotation.random()
2173
+
2174
+
2175
+ def test_boolean_indexes():
2176
+ r = Rotation.random(3)
2177
+
2178
+ r0 = r[[False, False, False]]
2179
+ assert len(r0) == 0
2180
+
2181
+ r1 = r[[False, True, False]]
2182
+ assert len(r1) == 1
2183
+
2184
+ r3 = r[[True, True, True]]
2185
+ assert len(r3) == 3
2186
+
2187
+ with pytest.raises(IndexError):
2188
+ r[[True, True]]
shared/package-files/02/022dbf37ea549879e024ddeeb2231334eea47cb5855506b758e7addd585e844f/logic.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logic expressions handling
2
+
3
+ NOTE
4
+ ----
5
+
6
+ at present this is mainly needed for facts.py, feel free however to improve
7
+ this stuff for general purpose.
8
+ """
9
+
10
+ from __future__ import annotations
11
+ from typing import Optional
12
+
13
+ # Type of a fuzzy bool
14
+ FuzzyBool = Optional[bool]
15
+
16
+
17
+ def _torf(args):
18
+ """Return True if all args are True, False if they
19
+ are all False, else None.
20
+
21
+ >>> from sympy.core.logic import _torf
22
+ >>> _torf((True, True))
23
+ True
24
+ >>> _torf((False, False))
25
+ False
26
+ >>> _torf((True, False))
27
+ """
28
+ sawT = sawF = False
29
+ for a in args:
30
+ if a is True:
31
+ if sawF:
32
+ return
33
+ sawT = True
34
+ elif a is False:
35
+ if sawT:
36
+ return
37
+ sawF = True
38
+ else:
39
+ return
40
+ return sawT
41
+
42
+
43
+ def _fuzzy_group(args, quick_exit=False):
44
+ """Return True if all args are True, None if there is any None else False
45
+ unless ``quick_exit`` is True (then return None as soon as a second False
46
+ is seen.
47
+
48
+ ``_fuzzy_group`` is like ``fuzzy_and`` except that it is more
49
+ conservative in returning a False, waiting to make sure that all
50
+ arguments are True or False and returning None if any arguments are
51
+ None. It also has the capability of permiting only a single False and
52
+ returning None if more than one is seen. For example, the presence of a
53
+ single transcendental amongst rationals would indicate that the group is
54
+ no longer rational; but a second transcendental in the group would make the
55
+ determination impossible.
56
+
57
+
58
+ Examples
59
+ ========
60
+
61
+ >>> from sympy.core.logic import _fuzzy_group
62
+
63
+ By default, multiple Falses mean the group is broken:
64
+
65
+ >>> _fuzzy_group([False, False, True])
66
+ False
67
+
68
+ If multiple Falses mean the group status is unknown then set
69
+ `quick_exit` to True so None can be returned when the 2nd False is seen:
70
+
71
+ >>> _fuzzy_group([False, False, True], quick_exit=True)
72
+
73
+ But if only a single False is seen then the group is known to
74
+ be broken:
75
+
76
+ >>> _fuzzy_group([False, True, True], quick_exit=True)
77
+ False
78
+
79
+ """
80
+ saw_other = False
81
+ for a in args:
82
+ if a is True:
83
+ continue
84
+ if a is None:
85
+ return
86
+ if quick_exit and saw_other:
87
+ return
88
+ saw_other = True
89
+ return not saw_other
90
+
91
+
92
+ def fuzzy_bool(x):
93
+ """Return True, False or None according to x.
94
+
95
+ Whereas bool(x) returns True or False, fuzzy_bool allows
96
+ for the None value and non-false values (which become None), too.
97
+
98
+ Examples
99
+ ========
100
+
101
+ >>> from sympy.core.logic import fuzzy_bool
102
+ >>> from sympy.abc import x
103
+ >>> fuzzy_bool(x), fuzzy_bool(None)
104
+ (None, None)
105
+ >>> bool(x), bool(None)
106
+ (True, False)
107
+
108
+ """
109
+ if x is None:
110
+ return None
111
+ if x in (True, False):
112
+ return bool(x)
113
+
114
+
115
+ def fuzzy_and(args):
116
+ """Return True (all True), False (any False) or None.
117
+
118
+ Examples
119
+ ========
120
+
121
+ >>> from sympy.core.logic import fuzzy_and
122
+ >>> from sympy import Dummy
123
+
124
+ If you had a list of objects to test the commutivity of
125
+ and you want the fuzzy_and logic applied, passing an
126
+ iterator will allow the commutativity to only be computed
127
+ as many times as necessary. With this list, False can be
128
+ returned after analyzing the first symbol:
129
+
130
+ >>> syms = [Dummy(commutative=False), Dummy()]
131
+ >>> fuzzy_and(s.is_commutative for s in syms)
132
+ False
133
+
134
+ That False would require less work than if a list of pre-computed
135
+ items was sent:
136
+
137
+ >>> fuzzy_and([s.is_commutative for s in syms])
138
+ False
139
+ """
140
+
141
+ rv = True
142
+ for ai in args:
143
+ ai = fuzzy_bool(ai)
144
+ if ai is False:
145
+ return False
146
+ if rv: # this will stop updating if a None is ever trapped
147
+ rv = ai
148
+ return rv
149
+
150
+
151
+ def fuzzy_not(v):
152
+ """
153
+ Not in fuzzy logic
154
+
155
+ Return None if `v` is None else `not v`.
156
+
157
+ Examples
158
+ ========
159
+
160
+ >>> from sympy.core.logic import fuzzy_not
161
+ >>> fuzzy_not(True)
162
+ False
163
+ >>> fuzzy_not(None)
164
+ >>> fuzzy_not(False)
165
+ True
166
+
167
+ """
168
+ if v is None:
169
+ return v
170
+ else:
171
+ return not v
172
+
173
+
174
+ def fuzzy_or(args):
175
+ """
176
+ Or in fuzzy logic. Returns True (any True), False (all False), or None
177
+
178
+ See the docstrings of fuzzy_and and fuzzy_not for more info. fuzzy_or is
179
+ related to the two by the standard De Morgan's law.
180
+
181
+ >>> from sympy.core.logic import fuzzy_or
182
+ >>> fuzzy_or([True, False])
183
+ True
184
+ >>> fuzzy_or([True, None])
185
+ True
186
+ >>> fuzzy_or([False, False])
187
+ False
188
+ >>> print(fuzzy_or([False, None]))
189
+ None
190
+
191
+ """
192
+ rv = False
193
+ for ai in args:
194
+ ai = fuzzy_bool(ai)
195
+ if ai is True:
196
+ return True
197
+ if rv is False: # this will stop updating if a None is ever trapped
198
+ rv = ai
199
+ return rv
200
+
201
+
202
+ def fuzzy_xor(args):
203
+ """Return None if any element of args is not True or False, else
204
+ True (if there are an odd number of True elements), else False."""
205
+ t = f = 0
206
+ for a in args:
207
+ ai = fuzzy_bool(a)
208
+ if ai:
209
+ t += 1
210
+ elif ai is False:
211
+ f += 1
212
+ else:
213
+ return
214
+ return t % 2 == 1
215
+
216
+
217
+ def fuzzy_nand(args):
218
+ """Return False if all args are True, True if they are all False,
219
+ else None."""
220
+ return fuzzy_not(fuzzy_and(args))
221
+
222
+
223
+ class Logic:
224
+ """Logical expression"""
225
+ # {} 'op' -> LogicClass
226
+ op_2class: dict[str, type[Logic]] = {}
227
+
228
+ def __new__(cls, *args):
229
+ obj = object.__new__(cls)
230
+ obj.args = args
231
+ return obj
232
+
233
+ def __getnewargs__(self):
234
+ return self.args
235
+
236
+ def __hash__(self):
237
+ return hash((type(self).__name__,) + tuple(self.args))
238
+
239
+ def __eq__(a, b):
240
+ if not isinstance(b, type(a)):
241
+ return False
242
+ else:
243
+ return a.args == b.args
244
+
245
+ def __ne__(a, b):
246
+ if not isinstance(b, type(a)):
247
+ return True
248
+ else:
249
+ return a.args != b.args
250
+
251
+ def __lt__(self, other):
252
+ if self.__cmp__(other) == -1:
253
+ return True
254
+ return False
255
+
256
+ def __cmp__(self, other):
257
+ if type(self) is not type(other):
258
+ a = str(type(self))
259
+ b = str(type(other))
260
+ else:
261
+ a = self.args
262
+ b = other.args
263
+ return (a > b) - (a < b)
264
+
265
+ def __str__(self):
266
+ return '%s(%s)' % (self.__class__.__name__,
267
+ ', '.join(str(a) for a in self.args))
268
+
269
+ __repr__ = __str__
270
+
271
+ @staticmethod
272
+ def fromstring(text):
273
+ """Logic from string with space around & and | but none after !.
274
+
275
+ e.g.
276
+
277
+ !a & b | c
278
+ """
279
+ lexpr = None # current logical expression
280
+ schedop = None # scheduled operation
281
+ for term in text.split():
282
+ # operation symbol
283
+ if term in '&|':
284
+ if schedop is not None:
285
+ raise ValueError(
286
+ 'double op forbidden: "%s %s"' % (term, schedop))
287
+ if lexpr is None:
288
+ raise ValueError(
289
+ '%s cannot be in the beginning of expression' % term)
290
+ schedop = term
291
+ continue
292
+ if '&' in term or '|' in term:
293
+ raise ValueError('& and | must have space around them')
294
+ if term[0] == '!':
295
+ if len(term) == 1:
296
+ raise ValueError('do not include space after "!"')
297
+ term = Not(term[1:])
298
+
299
+ # already scheduled operation, e.g. '&'
300
+ if schedop:
301
+ lexpr = Logic.op_2class[schedop](lexpr, term)
302
+ schedop = None
303
+ continue
304
+
305
+ # this should be atom
306
+ if lexpr is not None:
307
+ raise ValueError(
308
+ 'missing op between "%s" and "%s"' % (lexpr, term))
309
+
310
+ lexpr = term
311
+
312
+ # let's check that we ended up in correct state
313
+ if schedop is not None:
314
+ raise ValueError('premature end-of-expression in "%s"' % text)
315
+ if lexpr is None:
316
+ raise ValueError('"%s" is empty' % text)
317
+
318
+ # everything looks good now
319
+ return lexpr
320
+
321
+
322
+ class AndOr_Base(Logic):
323
+
324
+ def __new__(cls, *args):
325
+ bargs = []
326
+ for a in args:
327
+ if a == cls.op_x_notx:
328
+ return a
329
+ elif a == (not cls.op_x_notx):
330
+ continue # skip this argument
331
+ bargs.append(a)
332
+
333
+ args = sorted(set(cls.flatten(bargs)), key=hash)
334
+
335
+ for a in args:
336
+ if Not(a) in args:
337
+ return cls.op_x_notx
338
+
339
+ if len(args) == 1:
340
+ return args.pop()
341
+ elif len(args) == 0:
342
+ return not cls.op_x_notx
343
+
344
+ return Logic.__new__(cls, *args)
345
+
346
+ @classmethod
347
+ def flatten(cls, args):
348
+ # quick-n-dirty flattening for And and Or
349
+ args_queue = list(args)
350
+ res = []
351
+
352
+ while True:
353
+ try:
354
+ arg = args_queue.pop(0)
355
+ except IndexError:
356
+ break
357
+ if isinstance(arg, Logic):
358
+ if isinstance(arg, cls):
359
+ args_queue.extend(arg.args)
360
+ continue
361
+ res.append(arg)
362
+
363
+ args = tuple(res)
364
+ return args
365
+
366
+
367
+ class And(AndOr_Base):
368
+ op_x_notx = False
369
+
370
+ def _eval_propagate_not(self):
371
+ # !(a&b&c ...) == !a | !b | !c ...
372
+ return Or(*[Not(a) for a in self.args])
373
+
374
+ # (a|b|...) & c == (a&c) | (b&c) | ...
375
+ def expand(self):
376
+
377
+ # first locate Or
378
+ for i, arg in enumerate(self.args):
379
+ if isinstance(arg, Or):
380
+ arest = self.args[:i] + self.args[i + 1:]
381
+
382
+ orterms = [And(*(arest + (a,))) for a in arg.args]
383
+ for j in range(len(orterms)):
384
+ if isinstance(orterms[j], Logic):
385
+ orterms[j] = orterms[j].expand()
386
+
387
+ res = Or(*orterms)
388
+ return res
389
+
390
+ return self
391
+
392
+
393
+ class Or(AndOr_Base):
394
+ op_x_notx = True
395
+
396
+ def _eval_propagate_not(self):
397
+ # !(a|b|c ...) == !a & !b & !c ...
398
+ return And(*[Not(a) for a in self.args])
399
+
400
+
401
+ class Not(Logic):
402
+
403
+ def __new__(cls, arg):
404
+ if isinstance(arg, str):
405
+ return Logic.__new__(cls, arg)
406
+
407
+ elif isinstance(arg, bool):
408
+ return not arg
409
+ elif isinstance(arg, Not):
410
+ return arg.args[0]
411
+
412
+ elif isinstance(arg, Logic):
413
+ # XXX this is a hack to expand right from the beginning
414
+ arg = arg._eval_propagate_not()
415
+ return arg
416
+
417
+ else:
418
+ raise ValueError('Not: unknown argument %r' % (arg,))
419
+
420
+ @property
421
+ def arg(self):
422
+ return self.args[0]
423
+
424
+
425
+ Logic.op_2class['&'] = And
426
+ Logic.op_2class['|'] = Or
427
+ Logic.op_2class['!'] = Not
shared/package-files/02/022e9d78388697050747d995be59086d76335990031ee3cb95a0630cad11db05/test_libfrequencies.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from pandas._libs.tslibs.parsing import get_rule_month
4
+
5
+ from pandas.tseries import offsets
6
+
7
+
8
+ @pytest.mark.parametrize(
9
+ "obj,expected",
10
+ [
11
+ ("W", "DEC"),
12
+ (offsets.Week().freqstr, "DEC"),
13
+ ("D", "DEC"),
14
+ (offsets.Day().freqstr, "DEC"),
15
+ ("Q", "DEC"),
16
+ (offsets.QuarterEnd(startingMonth=12).freqstr, "DEC"),
17
+ ("Q-JAN", "JAN"),
18
+ (offsets.QuarterEnd(startingMonth=1).freqstr, "JAN"),
19
+ ("Y-DEC", "DEC"),
20
+ (offsets.YearEnd().freqstr, "DEC"),
21
+ ("Y-MAY", "MAY"),
22
+ (offsets.YearEnd(month=5).freqstr, "MAY"),
23
+ ],
24
+ )
25
+ def test_get_rule_month(obj, expected):
26
+ result = get_rule_month(obj)
27
+ assert result == expected
shared/package-files/02/02318a5a89979435f62358c277844e909afc9d1b6bde87e6dcc757447dd84d3a/_utils.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections.abc
4
+ import numbers
5
+ from contextlib import suppress
6
+
7
+ from typing import Any, Callable, Dict, List, Literal, Sequence, Tuple, Type, Union
8
+
9
+ import PIL.Image
10
+ import torch
11
+
12
+ from torchvision import tv_tensors
13
+
14
+ from torchvision._utils import sequence_to_str
15
+
16
+ from torchvision.transforms.transforms import _check_sequence_input, _setup_angle, _setup_size # noqa: F401
17
+ from torchvision.transforms.v2.functional import get_dimensions, get_size, is_pure_tensor
18
+ from torchvision.transforms.v2.functional._utils import _FillType, _FillTypeJIT
19
+
20
+
21
+ def _setup_number_or_seq(arg: Union[int, float, Sequence[Union[int, float]]], name: str) -> Sequence[float]:
22
+ if not isinstance(arg, (int, float, Sequence)):
23
+ raise TypeError(f"{name} should be a number or a sequence of numbers. Got {type(arg)}")
24
+ if isinstance(arg, Sequence) and len(arg) not in (1, 2):
25
+ raise ValueError(f"If {name} is a sequence its length should be 1 or 2. Got {len(arg)}")
26
+ if isinstance(arg, Sequence):
27
+ for element in arg:
28
+ if not isinstance(element, (int, float)):
29
+ raise ValueError(f"{name} should be a sequence of numbers. Got {type(element)}")
30
+
31
+ if isinstance(arg, (int, float)):
32
+ arg = [float(arg), float(arg)]
33
+ elif isinstance(arg, Sequence):
34
+ if len(arg) == 1:
35
+ arg = [float(arg[0]), float(arg[0])]
36
+ else:
37
+ arg = [float(arg[0]), float(arg[1])]
38
+ return arg
39
+
40
+
41
+ def _check_fill_arg(fill: Union[_FillType, Dict[Union[Type, str], _FillType]]) -> None:
42
+ if isinstance(fill, dict):
43
+ for value in fill.values():
44
+ _check_fill_arg(value)
45
+ else:
46
+ if fill is not None and not isinstance(fill, (numbers.Number, tuple, list)):
47
+ raise TypeError("Got inappropriate fill arg, only Numbers, tuples, lists and dicts are allowed.")
48
+
49
+
50
+ def _convert_fill_arg(fill: _FillType) -> _FillTypeJIT:
51
+ # Fill = 0 is not equivalent to None, https://github.com/pytorch/vision/issues/6517
52
+ # So, we can't reassign fill to 0
53
+ # if fill is None:
54
+ # fill = 0
55
+ if fill is None:
56
+ return fill
57
+
58
+ if not isinstance(fill, (int, float)):
59
+ fill = [float(v) for v in list(fill)]
60
+ return fill # type: ignore[return-value]
61
+
62
+
63
+ def _setup_fill_arg(fill: Union[_FillType, Dict[Union[Type, str], _FillType]]) -> Dict[Union[Type, str], _FillTypeJIT]:
64
+ _check_fill_arg(fill)
65
+
66
+ if isinstance(fill, dict):
67
+ for k, v in fill.items():
68
+ fill[k] = _convert_fill_arg(v)
69
+ return fill # type: ignore[return-value]
70
+ else:
71
+ return {"others": _convert_fill_arg(fill)}
72
+
73
+
74
+ def _get_fill(fill_dict, inpt_type):
75
+ if inpt_type in fill_dict:
76
+ return fill_dict[inpt_type]
77
+ elif "others" in fill_dict:
78
+ return fill_dict["others"]
79
+ else:
80
+ RuntimeError("This should never happen, please open an issue on the torchvision repo if you hit this.")
81
+
82
+
83
+ def _check_padding_arg(padding: Union[int, Sequence[int]]) -> None:
84
+ if not isinstance(padding, (numbers.Number, tuple, list)):
85
+ raise TypeError("Got inappropriate padding arg")
86
+
87
+ if isinstance(padding, (tuple, list)) and len(padding) not in [1, 2, 4]:
88
+ raise ValueError(f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple")
89
+
90
+
91
+ # TODO: let's use torchvision._utils.StrEnum to have the best of both worlds (strings and enums)
92
+ # https://github.com/pytorch/vision/issues/6250
93
+ def _check_padding_mode_arg(padding_mode: Literal["constant", "edge", "reflect", "symmetric"]) -> None:
94
+ if padding_mode not in ["constant", "edge", "reflect", "symmetric"]:
95
+ raise ValueError("Padding mode should be either constant, edge, reflect or symmetric")
96
+
97
+
98
+ def _find_labels_default_heuristic(inputs: Any) -> torch.Tensor:
99
+ """
100
+ This heuristic covers three cases:
101
+
102
+ 1. The input is tuple or list whose second item is a labels tensor. This happens for already batched
103
+ classification inputs for MixUp and CutMix (typically after the Dataloder).
104
+ 2. The input is a tuple or list whose second item is a dictionary that contains the labels tensor
105
+ under a label-like (see below) key. This happens for the inputs of detection models.
106
+ 3. The input is a dictionary that is structured as the one from 2.
107
+
108
+ What is "label-like" key? We first search for an case-insensitive match of 'labels' inside the keys of the
109
+ dictionary. This is the name our detection models expect. If we can't find that, we look for a case-insensitive
110
+ match of the term 'label' anywhere inside the key, i.e. 'FooLaBeLBar'. If we can't find that either, the dictionary
111
+ contains no "label-like" key.
112
+ """
113
+
114
+ if isinstance(inputs, (tuple, list)):
115
+ inputs = inputs[1]
116
+
117
+ # MixUp, CutMix
118
+ if is_pure_tensor(inputs):
119
+ return inputs
120
+
121
+ if not isinstance(inputs, collections.abc.Mapping):
122
+ raise ValueError(
123
+ f"When using the default labels_getter, the input passed to forward must be a dictionary or a two-tuple "
124
+ f"whose second item is a dictionary or a tensor, but got {inputs} instead."
125
+ )
126
+
127
+ candidate_key = None
128
+ with suppress(StopIteration):
129
+ candidate_key = next(key for key in inputs.keys() if key.lower() == "labels")
130
+ if candidate_key is None:
131
+ with suppress(StopIteration):
132
+ candidate_key = next(key for key in inputs.keys() if "label" in key.lower())
133
+ if candidate_key is None:
134
+ raise ValueError(
135
+ "Could not infer where the labels are in the sample. Try passing a callable as the labels_getter parameter?"
136
+ "If there are no labels in the sample by design, pass labels_getter=None."
137
+ )
138
+
139
+ return inputs[candidate_key]
140
+
141
+
142
+ def _parse_labels_getter(labels_getter: Union[str, Callable[[Any], Any], None]) -> Callable[[Any], Any]:
143
+ if labels_getter == "default":
144
+ return _find_labels_default_heuristic
145
+ elif callable(labels_getter):
146
+ return labels_getter
147
+ elif labels_getter is None:
148
+ return lambda _: None
149
+ else:
150
+ raise ValueError(f"labels_getter should either be 'default', a callable, or None, but got {labels_getter}.")
151
+
152
+
153
+ def get_bounding_boxes(flat_inputs: List[Any]) -> tv_tensors.BoundingBoxes:
154
+ # This assumes there is only one bbox per sample as per the general convention
155
+ try:
156
+ return next(inpt for inpt in flat_inputs if isinstance(inpt, tv_tensors.BoundingBoxes))
157
+ except StopIteration:
158
+ raise ValueError("No bounding boxes were found in the sample")
159
+
160
+
161
+ def query_chw(flat_inputs: List[Any]) -> Tuple[int, int, int]:
162
+ chws = {
163
+ tuple(get_dimensions(inpt))
164
+ for inpt in flat_inputs
165
+ if check_type(inpt, (is_pure_tensor, tv_tensors.Image, PIL.Image.Image, tv_tensors.Video))
166
+ }
167
+ if not chws:
168
+ raise TypeError("No image or video was found in the sample")
169
+ elif len(chws) > 1:
170
+ raise ValueError(f"Found multiple CxHxW dimensions in the sample: {sequence_to_str(sorted(chws))}")
171
+ c, h, w = chws.pop()
172
+ return c, h, w
173
+
174
+
175
+ def query_size(flat_inputs: List[Any]) -> Tuple[int, int]:
176
+ sizes = {
177
+ tuple(get_size(inpt))
178
+ for inpt in flat_inputs
179
+ if check_type(
180
+ inpt,
181
+ (
182
+ is_pure_tensor,
183
+ tv_tensors.Image,
184
+ PIL.Image.Image,
185
+ tv_tensors.Video,
186
+ tv_tensors.Mask,
187
+ tv_tensors.BoundingBoxes,
188
+ ),
189
+ )
190
+ }
191
+ if not sizes:
192
+ raise TypeError("No image, video, mask or bounding box was found in the sample")
193
+ elif len(sizes) > 1:
194
+ raise ValueError(f"Found multiple HxW dimensions in the sample: {sequence_to_str(sorted(sizes))}")
195
+ h, w = sizes.pop()
196
+ return h, w
197
+
198
+
199
+ def check_type(obj: Any, types_or_checks: Tuple[Union[Type, Callable[[Any], bool]], ...]) -> bool:
200
+ for type_or_check in types_or_checks:
201
+ if isinstance(obj, type_or_check) if isinstance(type_or_check, type) else type_or_check(obj):
202
+ return True
203
+ return False
204
+
205
+
206
+ def has_any(flat_inputs: List[Any], *types_or_checks: Union[Type, Callable[[Any], bool]]) -> bool:
207
+ for inpt in flat_inputs:
208
+ if check_type(inpt, types_or_checks):
209
+ return True
210
+ return False
211
+
212
+
213
+ def has_all(flat_inputs: List[Any], *types_or_checks: Union[Type, Callable[[Any], bool]]) -> bool:
214
+ for type_or_check in types_or_checks:
215
+ for inpt in flat_inputs:
216
+ if isinstance(inpt, type_or_check) if isinstance(type_or_check, type) else type_or_check(inpt):
217
+ break
218
+ else:
219
+ return False
220
+ return True
shared/package-files/02/02320a4c11fda2fa2de2aef6eae7132a8bb5cb53acf065ed195a7369572d7b57/fill_ops.h ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 fill_Scalar {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Scalar &);
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::fill")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fill.Scalar(Tensor self, Scalar value) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, const at::Scalar & value);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & value);
26
+ };
27
+
28
+ struct TORCH_API fill_Tensor {
29
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::fill")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fill.Tensor(Tensor self, Tensor value) -> Tensor")
35
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & value);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & value);
37
+ };
38
+
39
+ struct TORCH_API fill__Scalar {
40
+ using schema = at::Tensor & (at::Tensor &, const at::Scalar &);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::fill_")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fill_.Scalar(Tensor(a!) self, Scalar value) -> Tensor(a!)")
46
+ static at::Tensor & call(at::Tensor & self, const at::Scalar & value);
47
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & value);
48
+ };
49
+
50
+ struct TORCH_API fill__Tensor {
51
+ using schema = at::Tensor & (at::Tensor &, const at::Tensor &);
52
+ using ptr_schema = schema*;
53
+ // See Note [static constexpr char* members for windows NVCC]
54
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::fill_")
55
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
56
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fill_.Tensor(Tensor(a!) self, Tensor value) -> Tensor(a!)")
57
+ static at::Tensor & call(at::Tensor & self, const at::Tensor & value);
58
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & value);
59
+ };
60
+
61
+ struct TORCH_API fill_Scalar_out {
62
+ using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, at::Tensor &);
63
+ using ptr_schema = schema*;
64
+ // See Note [static constexpr char* members for windows NVCC]
65
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::fill")
66
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out")
67
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fill.Scalar_out(Tensor self, Scalar value, *, Tensor(a!) out) -> Tensor(a!)")
68
+ static at::Tensor & call(const at::Tensor & self, const at::Scalar & value, at::Tensor & out);
69
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & value, at::Tensor & out);
70
+ };
71
+
72
+ struct TORCH_API fill_Tensor_out {
73
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &);
74
+ using ptr_schema = schema*;
75
+ // See Note [static constexpr char* members for windows NVCC]
76
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::fill")
77
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out")
78
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fill.Tensor_out(Tensor self, Tensor value, *, Tensor(a!) out) -> Tensor(a!)")
79
+ static at::Tensor & call(const at::Tensor & self, const at::Tensor & value, at::Tensor & out);
80
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & value, at::Tensor & out);
81
+ };
82
+
83
+ }} // namespace at::_ops
shared/package-files/02/02361b49af673a5bffc9c64e4627dd9bb07e6fd29d282d4757e7062c3b6b27ec/test_multiprocessing.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import multiprocessing as mp
3
+
4
+ import numpy as np
5
+
6
+ from numba import cuda
7
+ from numba.cuda.testing import skip_on_cudasim, CUDATestCase
8
+ import unittest
9
+
10
+ has_mp_get_context = hasattr(mp, 'get_context')
11
+ is_unix = os.name == 'posix'
12
+
13
+
14
+ def fork_test(q):
15
+ from numba.cuda.cudadrv.error import CudaDriverError
16
+ try:
17
+ cuda.to_device(np.arange(1))
18
+ except CudaDriverError as e:
19
+ q.put(e)
20
+ else:
21
+ q.put(None)
22
+
23
+
24
+ @skip_on_cudasim('disabled for cudasim')
25
+ class TestMultiprocessing(CUDATestCase):
26
+ @unittest.skipUnless(has_mp_get_context, 'requires mp.get_context')
27
+ @unittest.skipUnless(is_unix, 'requires Unix')
28
+ def test_fork(self):
29
+ """
30
+ Test fork detection.
31
+ """
32
+ cuda.current_context() # force cuda initialize
33
+ # fork in process that also uses CUDA
34
+ ctx = mp.get_context('fork')
35
+ q = ctx.Queue()
36
+ proc = ctx.Process(target=fork_test, args=[q])
37
+ proc.start()
38
+ exc = q.get()
39
+ proc.join()
40
+ # there should be an exception raised in the child process
41
+ self.assertIsNotNone(exc)
42
+ self.assertIn('CUDA initialized before forking', str(exc))
43
+
44
+
45
+ if __name__ == '__main__':
46
+ unittest.main()
shared/package-files/02/023872fe9f03a25387cf2c17fc950cf0f990353df66e603c3a1cd3199dbccd86/fix_operator.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer for operator functions.
2
+
3
+ operator.isCallable(obj) -> callable(obj)
4
+ operator.sequenceIncludes(obj) -> operator.contains(obj)
5
+ operator.isSequenceType(obj) -> isinstance(obj, collections.abc.Sequence)
6
+ operator.isMappingType(obj) -> isinstance(obj, collections.abc.Mapping)
7
+ operator.isNumberType(obj) -> isinstance(obj, numbers.Number)
8
+ operator.repeat(obj, n) -> operator.mul(obj, n)
9
+ operator.irepeat(obj, n) -> operator.imul(obj, n)
10
+ """
11
+
12
+ import collections.abc
13
+
14
+ # Local imports
15
+ from lib2to3 import fixer_base
16
+ from lib2to3.fixer_util import Call, Name, String, touch_import
17
+
18
+
19
+ def invocation(s):
20
+ def dec(f):
21
+ f.invocation = s
22
+ return f
23
+ return dec
24
+
25
+
26
+ class FixOperator(fixer_base.BaseFix):
27
+ BM_compatible = True
28
+ order = "pre"
29
+
30
+ methods = """
31
+ method=('isCallable'|'sequenceIncludes'
32
+ |'isSequenceType'|'isMappingType'|'isNumberType'
33
+ |'repeat'|'irepeat')
34
+ """
35
+ obj = "'(' obj=any ')'"
36
+ PATTERN = """
37
+ power< module='operator'
38
+ trailer< '.' %(methods)s > trailer< %(obj)s > >
39
+ |
40
+ power< %(methods)s trailer< %(obj)s > >
41
+ """ % dict(methods=methods, obj=obj)
42
+
43
+ def transform(self, node, results):
44
+ method = self._check_method(node, results)
45
+ if method is not None:
46
+ return method(node, results)
47
+
48
+ @invocation("operator.contains(%s)")
49
+ def _sequenceIncludes(self, node, results):
50
+ return self._handle_rename(node, results, "contains")
51
+
52
+ @invocation("callable(%s)")
53
+ def _isCallable(self, node, results):
54
+ obj = results["obj"]
55
+ return Call(Name("callable"), [obj.clone()], prefix=node.prefix)
56
+
57
+ @invocation("operator.mul(%s)")
58
+ def _repeat(self, node, results):
59
+ return self._handle_rename(node, results, "mul")
60
+
61
+ @invocation("operator.imul(%s)")
62
+ def _irepeat(self, node, results):
63
+ return self._handle_rename(node, results, "imul")
64
+
65
+ @invocation("isinstance(%s, collections.abc.Sequence)")
66
+ def _isSequenceType(self, node, results):
67
+ return self._handle_type2abc(node, results, "collections.abc", "Sequence")
68
+
69
+ @invocation("isinstance(%s, collections.abc.Mapping)")
70
+ def _isMappingType(self, node, results):
71
+ return self._handle_type2abc(node, results, "collections.abc", "Mapping")
72
+
73
+ @invocation("isinstance(%s, numbers.Number)")
74
+ def _isNumberType(self, node, results):
75
+ return self._handle_type2abc(node, results, "numbers", "Number")
76
+
77
+ def _handle_rename(self, node, results, name):
78
+ method = results["method"][0]
79
+ method.value = name
80
+ method.changed()
81
+
82
+ def _handle_type2abc(self, node, results, module, abc):
83
+ touch_import(None, module, node)
84
+ obj = results["obj"]
85
+ args = [obj.clone(), String(", " + ".".join([module, abc]))]
86
+ return Call(Name("isinstance"), args, prefix=node.prefix)
87
+
88
+ def _check_method(self, node, results):
89
+ method = getattr(self, "_" + results["method"][0].value)
90
+ if isinstance(method, collections.abc.Callable):
91
+ if "module" in results:
92
+ return method
93
+ else:
94
+ sub = (str(results["obj"]),)
95
+ invocation_str = method.invocation % sub
96
+ self.warning(node, "You should use '%s' here." % invocation_str)
97
+ return None
shared/package-files/02/023c3bb9dead92eb49f431aadc435a69e5ef7fa8e88e82ad34f426eabf0f0701/fft_fftn_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor fft_fftn(const at::Tensor & self, at::OptionalIntArrayRef s=c10::nullopt, at::OptionalIntArrayRef dim=c10::nullopt, c10::optional<c10::string_view> norm=c10::nullopt);
21
+ TORCH_API at::Tensor fft_fftn_symint(const at::Tensor & self, at::OptionalSymIntArrayRef s=c10::nullopt, at::OptionalIntArrayRef dim=c10::nullopt, c10::optional<c10::string_view> norm=c10::nullopt);
22
+ TORCH_API at::Tensor & fft_fftn_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=c10::nullopt, at::OptionalIntArrayRef dim=c10::nullopt, c10::optional<c10::string_view> norm=c10::nullopt);
23
+ TORCH_API at::Tensor & fft_fftn_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::OptionalIntArrayRef dim, c10::optional<c10::string_view> norm, at::Tensor & out);
24
+ TORCH_API at::Tensor & fft_fftn_symint_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=c10::nullopt, at::OptionalIntArrayRef dim=c10::nullopt, c10::optional<c10::string_view> norm=c10::nullopt);
25
+ TORCH_API at::Tensor & fft_fftn_symint_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::OptionalIntArrayRef dim, c10::optional<c10::string_view> norm, at::Tensor & out);
26
+
27
+ } // namespace compositeimplicitautograd
28
+ } // namespace at
shared/package-files/02/023c4e4d6552b9693e65e86713a27315531459a94e8b54493faaca5f5031ce7d/_slow_conv2d_backward_cpu_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _slow_conv2d_backward_out(at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding);
21
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _slow_conv2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias);
22
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _slow_conv2d_backward_symint_out(at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding);
23
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _slow_conv2d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, at::Tensor & grad_input, at::Tensor & grad_weight, at::Tensor & grad_bias);
24
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _slow_conv2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, ::std::array<bool,3> output_mask);
25
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _slow_conv2d_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, ::std::array<bool,3> output_mask);
26
+
27
+ } // namespace cpu
28
+ } // namespace at
shared/package-files/02/023d292c442b3477106e4b6755abaed01afc7b80c6878f4084d3478832a140e4/direct_url.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"dir_info": {}, "url": "file:///croot/pytz_1695131579487/work"}
shared/package-files/02/023e5dc747d51d3fc1ecdaa58958424c0f690bf440912ad93eba18eff584d1fd/memory_snapshot.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/Optional.h>
4
+ #include <torch/csrc/Export.h>
5
+ #include <cstdint>
6
+ #include <string>
7
+
8
+ namespace torch::cuda {
9
+
10
+ // C++-only versions of these, for python use
11
+ // those defined in cuda/Module.cpp which also record python state.
12
+ TORCH_CUDA_CU_API void _record_memory_history(
13
+ bool enabled,
14
+ bool record_context = true,
15
+ int64_t trace_alloc_max_entries = 1,
16
+ bool trace_alloc_record_context = false,
17
+ bool record_cpp_context = false);
18
+
19
+ TORCH_CUDA_CU_API void _record_memory_history(
20
+ c10::optional<std::string> enabled = "all",
21
+ c10::optional<std::string> context = "all",
22
+ const std::string& stacks = "all",
23
+ size_t max_entries = SIZE_MAX);
24
+
25
+ TORCH_CUDA_CU_API std::string _memory_snapshot_pickled();
26
+
27
+ } // namespace torch::cuda
shared/package-files/02/02400a365357a04774bb02b8365809e39390d72c9c6f1a69bdd60be41923fe9e/import_export_helpers.h ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <memory>
4
+ #include <string>
5
+
6
+ namespace caffe2 {
7
+ namespace serialize {
8
+ class PyTorchStreamReader;
9
+ }
10
+ } // namespace caffe2
11
+
12
+ namespace torch {
13
+ namespace jit {
14
+
15
+ struct Source;
16
+
17
+ // Convert a class type's qualifier name to the corresponding path the source
18
+ // file it should be written to.
19
+ //
20
+ // Qualifier is like: foo.bar.baz
21
+ // Returns: libs/foo/bar/baz.py
22
+ std::string qualifierToArchivePath(
23
+ const std::string& qualifier,
24
+ const std::string& export_prefix);
25
+
26
+ std::shared_ptr<Source> findSourceInArchiveFromQualifier(
27
+ caffe2::serialize::PyTorchStreamReader& reader,
28
+ const std::string& export_prefix,
29
+ const std::string& qualifier);
30
+
31
+ } // namespace jit
32
+ } // namespace torch
shared/package-files/02/024983a51d08171a34adeb7dd6d44f614aab8107d0dfaee8913b7611ed959bad/test_partitions.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.ntheory import npartitions
2
+
3
+
4
+ def test_partitions():
5
+ assert [npartitions(k) for k in range(13)] == \
6
+ [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77]
7
+ assert npartitions(100) == 190569292
8
+ assert npartitions(200) == 3972999029388
9
+ assert npartitions(1000) == 24061467864032622473692149727991
10
+ assert npartitions(2000) == 4720819175619413888601432406799959512200344166
11
+ assert npartitions(10000) % 10**10 == 6916435144
12
+ assert npartitions(100000) % 10**10 == 9421098519
shared/package-files/02/024e76301aa38fc4e4c57e4cb51abbccb0d1fe8ddcd3f49d4095d4d550ef6d37/cudnn_convolution_transpose_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & cudnn_convolution_transpose_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef padding, at::IntArrayRef output_padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, bool benchmark, bool deterministic, bool allow_tf32);
21
+ TORCH_API at::Tensor & cudnn_convolution_transpose_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef padding, at::IntArrayRef output_padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, bool benchmark, bool deterministic, bool allow_tf32, at::Tensor & out);
22
+ TORCH_API at::Tensor & cudnn_convolution_transpose_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef output_padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic, bool allow_tf32);
23
+ TORCH_API at::Tensor & cudnn_convolution_transpose_symint_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef output_padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic, bool allow_tf32, at::Tensor & out);
24
+
25
+ } // namespace compositeexplicitautograd
26
+ } // namespace at
shared/package-files/02/0250ba18275c1b7b4d54a7e5e5b2353d0408b938baae10783661d24123dc31d0/test_register.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for distutils.command.register."""
2
+ import os
3
+ import unittest
4
+ import getpass
5
+ import urllib
6
+ import warnings
7
+
8
+ from test.support import run_unittest
9
+ from test.support.warnings_helper import check_warnings
10
+
11
+ from distutils.command import register as register_module
12
+ from distutils.command.register import register
13
+ from distutils.errors import DistutilsSetupError
14
+ from distutils.log import INFO
15
+
16
+ from distutils.tests.test_config import BasePyPIRCCommandTestCase
17
+
18
+ try:
19
+ import docutils
20
+ except ImportError:
21
+ docutils = None
22
+
23
+ PYPIRC_NOPASSWORD = """\
24
+ [distutils]
25
+
26
+ index-servers =
27
+ server1
28
+
29
+ [server1]
30
+ username:me
31
+ """
32
+
33
+ WANTED_PYPIRC = """\
34
+ [distutils]
35
+ index-servers =
36
+ pypi
37
+
38
+ [pypi]
39
+ username:tarek
40
+ password:password
41
+ """
42
+
43
+ class Inputs(object):
44
+ """Fakes user inputs."""
45
+ def __init__(self, *answers):
46
+ self.answers = answers
47
+ self.index = 0
48
+
49
+ def __call__(self, prompt=''):
50
+ try:
51
+ return self.answers[self.index]
52
+ finally:
53
+ self.index += 1
54
+
55
+ class FakeOpener(object):
56
+ """Fakes a PyPI server"""
57
+ def __init__(self):
58
+ self.reqs = []
59
+
60
+ def __call__(self, *args):
61
+ return self
62
+
63
+ def open(self, req, data=None, timeout=None):
64
+ self.reqs.append(req)
65
+ return self
66
+
67
+ def read(self):
68
+ return b'xxx'
69
+
70
+ def getheader(self, name, default=None):
71
+ return {
72
+ 'content-type': 'text/plain; charset=utf-8',
73
+ }.get(name.lower(), default)
74
+
75
+
76
+ class RegisterTestCase(BasePyPIRCCommandTestCase):
77
+
78
+ def setUp(self):
79
+ super(RegisterTestCase, self).setUp()
80
+ # patching the password prompt
81
+ self._old_getpass = getpass.getpass
82
+ def _getpass(prompt):
83
+ return 'password'
84
+ getpass.getpass = _getpass
85
+ urllib.request._opener = None
86
+ self.old_opener = urllib.request.build_opener
87
+ self.conn = urllib.request.build_opener = FakeOpener()
88
+
89
+ def tearDown(self):
90
+ getpass.getpass = self._old_getpass
91
+ urllib.request._opener = None
92
+ urllib.request.build_opener = self.old_opener
93
+ super(RegisterTestCase, self).tearDown()
94
+
95
+ def _get_cmd(self, metadata=None):
96
+ if metadata is None:
97
+ metadata = {'url': 'xxx', 'author': 'xxx',
98
+ 'author_email': 'xxx',
99
+ 'name': 'xxx', 'version': 'xxx'}
100
+ pkg_info, dist = self.create_dist(**metadata)
101
+ return register(dist)
102
+
103
+ def test_create_pypirc(self):
104
+ # this test makes sure a .pypirc file
105
+ # is created when requested.
106
+
107
+ # let's create a register instance
108
+ cmd = self._get_cmd()
109
+
110
+ # we shouldn't have a .pypirc file yet
111
+ self.assertFalse(os.path.exists(self.rc))
112
+
113
+ # patching input and getpass.getpass
114
+ # so register gets happy
115
+ #
116
+ # Here's what we are faking :
117
+ # use your existing login (choice 1.)
118
+ # Username : 'tarek'
119
+ # Password : 'password'
120
+ # Save your login (y/N)? : 'y'
121
+ inputs = Inputs('1', 'tarek', 'y')
122
+ register_module.input = inputs.__call__
123
+ # let's run the command
124
+ try:
125
+ cmd.run()
126
+ finally:
127
+ del register_module.input
128
+
129
+ # we should have a brand new .pypirc file
130
+ self.assertTrue(os.path.exists(self.rc))
131
+
132
+ # with the content similar to WANTED_PYPIRC
133
+ f = open(self.rc)
134
+ try:
135
+ content = f.read()
136
+ self.assertEqual(content, WANTED_PYPIRC)
137
+ finally:
138
+ f.close()
139
+
140
+ # now let's make sure the .pypirc file generated
141
+ # really works : we shouldn't be asked anything
142
+ # if we run the command again
143
+ def _no_way(prompt=''):
144
+ raise AssertionError(prompt)
145
+ register_module.input = _no_way
146
+
147
+ cmd.show_response = 1
148
+ cmd.run()
149
+
150
+ # let's see what the server received : we should
151
+ # have 2 similar requests
152
+ self.assertEqual(len(self.conn.reqs), 2)
153
+ req1 = dict(self.conn.reqs[0].headers)
154
+ req2 = dict(self.conn.reqs[1].headers)
155
+
156
+ self.assertEqual(req1['Content-length'], '1374')
157
+ self.assertEqual(req2['Content-length'], '1374')
158
+ self.assertIn(b'xxx', self.conn.reqs[1].data)
159
+
160
+ def test_password_not_in_file(self):
161
+
162
+ self.write_file(self.rc, PYPIRC_NOPASSWORD)
163
+ cmd = self._get_cmd()
164
+ cmd._set_config()
165
+ cmd.finalize_options()
166
+ cmd.send_metadata()
167
+
168
+ # dist.password should be set
169
+ # therefore used afterwards by other commands
170
+ self.assertEqual(cmd.distribution.password, 'password')
171
+
172
+ def test_registering(self):
173
+ # this test runs choice 2
174
+ cmd = self._get_cmd()
175
+ inputs = Inputs('2', 'tarek', 'tarek@ziade.org')
176
+ register_module.input = inputs.__call__
177
+ try:
178
+ # let's run the command
179
+ cmd.run()
180
+ finally:
181
+ del register_module.input
182
+
183
+ # we should have send a request
184
+ self.assertEqual(len(self.conn.reqs), 1)
185
+ req = self.conn.reqs[0]
186
+ headers = dict(req.headers)
187
+ self.assertEqual(headers['Content-length'], '608')
188
+ self.assertIn(b'tarek', req.data)
189
+
190
+ def test_password_reset(self):
191
+ # this test runs choice 3
192
+ cmd = self._get_cmd()
193
+ inputs = Inputs('3', 'tarek@ziade.org')
194
+ register_module.input = inputs.__call__
195
+ try:
196
+ # let's run the command
197
+ cmd.run()
198
+ finally:
199
+ del register_module.input
200
+
201
+ # we should have send a request
202
+ self.assertEqual(len(self.conn.reqs), 1)
203
+ req = self.conn.reqs[0]
204
+ headers = dict(req.headers)
205
+ self.assertEqual(headers['Content-length'], '290')
206
+ self.assertIn(b'tarek', req.data)
207
+
208
+ @unittest.skipUnless(docutils is not None, 'needs docutils')
209
+ def test_strict(self):
210
+ # testing the script option
211
+ # when on, the register command stops if
212
+ # the metadata is incomplete or if
213
+ # long_description is not reSt compliant
214
+
215
+ # empty metadata
216
+ cmd = self._get_cmd({})
217
+ cmd.ensure_finalized()
218
+ cmd.strict = 1
219
+ self.assertRaises(DistutilsSetupError, cmd.run)
220
+
221
+ # metadata are OK but long_description is broken
222
+ metadata = {'url': 'xxx', 'author': 'xxx',
223
+ 'author_email': 'éxéxé',
224
+ 'name': 'xxx', 'version': 'xxx',
225
+ 'long_description': 'title\n==\n\ntext'}
226
+
227
+ cmd = self._get_cmd(metadata)
228
+ cmd.ensure_finalized()
229
+ cmd.strict = 1
230
+ self.assertRaises(DistutilsSetupError, cmd.run)
231
+
232
+ # now something that works
233
+ metadata['long_description'] = 'title\n=====\n\ntext'
234
+ cmd = self._get_cmd(metadata)
235
+ cmd.ensure_finalized()
236
+ cmd.strict = 1
237
+ inputs = Inputs('1', 'tarek', 'y')
238
+ register_module.input = inputs.__call__
239
+ # let's run the command
240
+ try:
241
+ cmd.run()
242
+ finally:
243
+ del register_module.input
244
+
245
+ # strict is not by default
246
+ cmd = self._get_cmd()
247
+ cmd.ensure_finalized()
248
+ inputs = Inputs('1', 'tarek', 'y')
249
+ register_module.input = inputs.__call__
250
+ # let's run the command
251
+ try:
252
+ cmd.run()
253
+ finally:
254
+ del register_module.input
255
+
256
+ # and finally a Unicode test (bug #12114)
257
+ metadata = {'url': 'xxx', 'author': '\u00c9ric',
258
+ 'author_email': 'xxx', 'name': 'xxx',
259
+ 'version': 'xxx',
260
+ 'description': 'Something about esszet \u00df',
261
+ 'long_description': 'More things about esszet \u00df'}
262
+
263
+ cmd = self._get_cmd(metadata)
264
+ cmd.ensure_finalized()
265
+ cmd.strict = 1
266
+ inputs = Inputs('1', 'tarek', 'y')
267
+ register_module.input = inputs.__call__
268
+ # let's run the command
269
+ try:
270
+ cmd.run()
271
+ finally:
272
+ del register_module.input
273
+
274
+ @unittest.skipUnless(docutils is not None, 'needs docutils')
275
+ def test_register_invalid_long_description(self):
276
+ description = ':funkie:`str`' # mimic Sphinx-specific markup
277
+ metadata = {'url': 'xxx', 'author': 'xxx',
278
+ 'author_email': 'xxx',
279
+ 'name': 'xxx', 'version': 'xxx',
280
+ 'long_description': description}
281
+ cmd = self._get_cmd(metadata)
282
+ cmd.ensure_finalized()
283
+ cmd.strict = True
284
+ inputs = Inputs('2', 'tarek', 'tarek@ziade.org')
285
+ register_module.input = inputs
286
+ self.addCleanup(delattr, register_module, 'input')
287
+
288
+ self.assertRaises(DistutilsSetupError, cmd.run)
289
+
290
+ def test_check_metadata_deprecated(self):
291
+ # makes sure make_metadata is deprecated
292
+ cmd = self._get_cmd()
293
+ with check_warnings() as w:
294
+ warnings.simplefilter("always")
295
+ cmd.check_metadata()
296
+ self.assertEqual(len(w.warnings), 1)
297
+
298
+ def test_list_classifiers(self):
299
+ cmd = self._get_cmd()
300
+ cmd.list_classifiers = 1
301
+ cmd.run()
302
+ results = self.get_logs(INFO)
303
+ self.assertEqual(results, ['running check', 'xxx'])
304
+
305
+ def test_show_response(self):
306
+ # test that the --show-response option return a well formatted response
307
+ cmd = self._get_cmd()
308
+ inputs = Inputs('1', 'tarek', 'y')
309
+ register_module.input = inputs.__call__
310
+ cmd.show_response = 1
311
+ try:
312
+ cmd.run()
313
+ finally:
314
+ del register_module.input
315
+
316
+ results = self.get_logs(INFO)
317
+ self.assertEqual(results[3], 75 * '-' + '\nxxx\n' + 75 * '-')
318
+
319
+
320
+ def test_suite():
321
+ return unittest.makeSuite(RegisterTestCase)
322
+
323
+ if __name__ == "__main__":
324
+ run_unittest(test_suite())
shared/package-files/02/0258ffb6181b7487bacc36f2af8c1e88469f25fe6819e5f66167ade2c027eece/_sparse_sum_ops.h ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 _sparse_sum {
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::_sparse_sum")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_sum(Tensor self) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
26
+ };
27
+
28
+ struct TORCH_API _sparse_sum_dtype {
29
+ using schema = at::Tensor (const at::Tensor &, at::ScalarType);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_sum")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dtype")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_sum.dtype(Tensor self, *, ScalarType dtype) -> Tensor")
35
+ static at::Tensor call(const at::Tensor & self, at::ScalarType dtype);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::ScalarType dtype);
37
+ };
38
+
39
+ struct TORCH_API _sparse_sum_dim {
40
+ using schema = at::Tensor (const at::Tensor &, at::IntArrayRef);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_sum")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_sum.dim(Tensor self, int[1] dim) -> Tensor")
46
+ static at::Tensor call(const at::Tensor & self, at::IntArrayRef dim);
47
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim);
48
+ };
49
+
50
+ struct TORCH_API _sparse_sum_dim_dtype {
51
+ using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, at::ScalarType);
52
+ using ptr_schema = schema*;
53
+ // See Note [static constexpr char* members for windows NVCC]
54
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_sum")
55
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim_dtype")
56
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_sum.dim_dtype(Tensor self, int[1] dim, *, ScalarType dtype) -> Tensor")
57
+ static at::Tensor call(const at::Tensor & self, at::IntArrayRef dim, at::ScalarType dtype);
58
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim, at::ScalarType dtype);
59
+ };
60
+
61
+ struct TORCH_API _sparse_sum_dim_out {
62
+ using schema = at::Tensor & (const at::Tensor &, at::IntArrayRef, at::Tensor &);
63
+ using ptr_schema = schema*;
64
+ // See Note [static constexpr char* members for windows NVCC]
65
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_sum")
66
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim_out")
67
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_sum.dim_out(Tensor self, int[1] dim, *, Tensor(a!) out) -> Tensor(a!)")
68
+ static at::Tensor & call(const at::Tensor & self, at::IntArrayRef dim, at::Tensor & out);
69
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim, at::Tensor & out);
70
+ };
71
+
72
+ }} // namespace at::_ops
shared/package-files/02/025a9531e3046e52d3e039c0be04f9a5a74651d7683a13c7c7ebd4c7dfb5996a/hz.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # hz.py: Python Unicode Codec for HZ
3
+ #
4
+ # Written by Hye-Shik Chang <perky@FreeBSD.org>
5
+ #
6
+
7
+ import _codecs_cn, codecs
8
+ import _multibytecodec as mbc
9
+
10
+ codec = _codecs_cn.getcodec('hz')
11
+
12
+ class Codec(codecs.Codec):
13
+ encode = codec.encode
14
+ decode = codec.decode
15
+
16
+ class IncrementalEncoder(mbc.MultibyteIncrementalEncoder,
17
+ codecs.IncrementalEncoder):
18
+ codec = codec
19
+
20
+ class IncrementalDecoder(mbc.MultibyteIncrementalDecoder,
21
+ codecs.IncrementalDecoder):
22
+ codec = codec
23
+
24
+ class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):
25
+ codec = codec
26
+
27
+ class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):
28
+ codec = codec
29
+
30
+ def getregentry():
31
+ return codecs.CodecInfo(
32
+ name='hz',
33
+ encode=Codec().encode,
34
+ decode=Codec().decode,
35
+ incrementalencoder=IncrementalEncoder,
36
+ incrementaldecoder=IncrementalDecoder,
37
+ streamreader=StreamReader,
38
+ streamwriter=StreamWriter,
39
+ )
shared/package-files/02/025b702d601b96948b6bedb82af36ec58c4cd88795979a7677e928cc0f5027ed/test_cluster.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestTriangles:
7
+ def test_empty(self):
8
+ G = nx.Graph()
9
+ assert list(nx.triangles(G).values()) == []
10
+
11
+ def test_path(self):
12
+ G = nx.path_graph(10)
13
+ assert list(nx.triangles(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
14
+ assert nx.triangles(G) == {
15
+ 0: 0,
16
+ 1: 0,
17
+ 2: 0,
18
+ 3: 0,
19
+ 4: 0,
20
+ 5: 0,
21
+ 6: 0,
22
+ 7: 0,
23
+ 8: 0,
24
+ 9: 0,
25
+ }
26
+
27
+ def test_cubical(self):
28
+ G = nx.cubical_graph()
29
+ assert list(nx.triangles(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0]
30
+ assert nx.triangles(G, 1) == 0
31
+ assert list(nx.triangles(G, [1, 2]).values()) == [0, 0]
32
+ assert nx.triangles(G, 1) == 0
33
+ assert nx.triangles(G, [1, 2]) == {1: 0, 2: 0}
34
+
35
+ def test_k5(self):
36
+ G = nx.complete_graph(5)
37
+ assert list(nx.triangles(G).values()) == [6, 6, 6, 6, 6]
38
+ assert sum(nx.triangles(G).values()) / 3 == 10
39
+ assert nx.triangles(G, 1) == 6
40
+ G.remove_edge(1, 2)
41
+ assert list(nx.triangles(G).values()) == [5, 3, 3, 5, 5]
42
+ assert nx.triangles(G, 1) == 3
43
+ G.add_edge(3, 3) # ignore self-edges
44
+ assert list(nx.triangles(G).values()) == [5, 3, 3, 5, 5]
45
+ assert nx.triangles(G, 3) == 5
46
+
47
+
48
+ class TestDirectedClustering:
49
+ def test_clustering(self):
50
+ G = nx.DiGraph()
51
+ assert list(nx.clustering(G).values()) == []
52
+ assert nx.clustering(G) == {}
53
+
54
+ def test_path(self):
55
+ G = nx.path_graph(10, create_using=nx.DiGraph())
56
+ assert list(nx.clustering(G).values()) == [
57
+ 0,
58
+ 0,
59
+ 0,
60
+ 0,
61
+ 0,
62
+ 0,
63
+ 0,
64
+ 0,
65
+ 0,
66
+ 0,
67
+ ]
68
+ assert nx.clustering(G) == {
69
+ 0: 0,
70
+ 1: 0,
71
+ 2: 0,
72
+ 3: 0,
73
+ 4: 0,
74
+ 5: 0,
75
+ 6: 0,
76
+ 7: 0,
77
+ 8: 0,
78
+ 9: 0,
79
+ }
80
+ assert nx.clustering(G, 0) == 0
81
+
82
+ def test_k5(self):
83
+ G = nx.complete_graph(5, create_using=nx.DiGraph())
84
+ assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
85
+ assert nx.average_clustering(G) == 1
86
+ G.remove_edge(1, 2)
87
+ assert list(nx.clustering(G).values()) == [
88
+ 11 / 12,
89
+ 1,
90
+ 1,
91
+ 11 / 12,
92
+ 11 / 12,
93
+ ]
94
+ assert nx.clustering(G, [1, 4]) == {1: 1, 4: 11 / 12}
95
+ G.remove_edge(2, 1)
96
+ assert list(nx.clustering(G).values()) == [
97
+ 5 / 6,
98
+ 1,
99
+ 1,
100
+ 5 / 6,
101
+ 5 / 6,
102
+ ]
103
+ assert nx.clustering(G, [1, 4]) == {1: 1, 4: 0.83333333333333337}
104
+ assert nx.clustering(G, 4) == 5 / 6
105
+
106
+ def test_triangle_and_edge(self):
107
+ G = nx.cycle_graph(3, create_using=nx.DiGraph())
108
+ G.add_edge(0, 4)
109
+ assert nx.clustering(G)[0] == 1 / 6
110
+
111
+
112
+ class TestDirectedWeightedClustering:
113
+ @classmethod
114
+ def setup_class(cls):
115
+ global np
116
+ np = pytest.importorskip("numpy")
117
+
118
+ def test_clustering(self):
119
+ G = nx.DiGraph()
120
+ assert list(nx.clustering(G, weight="weight").values()) == []
121
+ assert nx.clustering(G) == {}
122
+
123
+ def test_path(self):
124
+ G = nx.path_graph(10, create_using=nx.DiGraph())
125
+ assert list(nx.clustering(G, weight="weight").values()) == [
126
+ 0,
127
+ 0,
128
+ 0,
129
+ 0,
130
+ 0,
131
+ 0,
132
+ 0,
133
+ 0,
134
+ 0,
135
+ 0,
136
+ ]
137
+ assert nx.clustering(G, weight="weight") == {
138
+ 0: 0,
139
+ 1: 0,
140
+ 2: 0,
141
+ 3: 0,
142
+ 4: 0,
143
+ 5: 0,
144
+ 6: 0,
145
+ 7: 0,
146
+ 8: 0,
147
+ 9: 0,
148
+ }
149
+
150
+ def test_k5(self):
151
+ G = nx.complete_graph(5, create_using=nx.DiGraph())
152
+ assert list(nx.clustering(G, weight="weight").values()) == [1, 1, 1, 1, 1]
153
+ assert nx.average_clustering(G, weight="weight") == 1
154
+ G.remove_edge(1, 2)
155
+ assert list(nx.clustering(G, weight="weight").values()) == [
156
+ 11 / 12,
157
+ 1,
158
+ 1,
159
+ 11 / 12,
160
+ 11 / 12,
161
+ ]
162
+ assert nx.clustering(G, [1, 4], weight="weight") == {1: 1, 4: 11 / 12}
163
+ G.remove_edge(2, 1)
164
+ assert list(nx.clustering(G, weight="weight").values()) == [
165
+ 5 / 6,
166
+ 1,
167
+ 1,
168
+ 5 / 6,
169
+ 5 / 6,
170
+ ]
171
+ assert nx.clustering(G, [1, 4], weight="weight") == {
172
+ 1: 1,
173
+ 4: 0.83333333333333337,
174
+ }
175
+
176
+ def test_triangle_and_edge(self):
177
+ G = nx.cycle_graph(3, create_using=nx.DiGraph())
178
+ G.add_edge(0, 4, weight=2)
179
+ assert nx.clustering(G)[0] == 1 / 6
180
+ # Relaxed comparisons to allow graphblas-algorithms to pass tests
181
+ np.testing.assert_allclose(nx.clustering(G, weight="weight")[0], 1 / 12)
182
+ np.testing.assert_allclose(nx.clustering(G, 0, weight="weight"), 1 / 12)
183
+
184
+
185
+ class TestWeightedClustering:
186
+ @classmethod
187
+ def setup_class(cls):
188
+ global np
189
+ np = pytest.importorskip("numpy")
190
+
191
+ def test_clustering(self):
192
+ G = nx.Graph()
193
+ assert list(nx.clustering(G, weight="weight").values()) == []
194
+ assert nx.clustering(G) == {}
195
+
196
+ def test_path(self):
197
+ G = nx.path_graph(10)
198
+ assert list(nx.clustering(G, weight="weight").values()) == [
199
+ 0,
200
+ 0,
201
+ 0,
202
+ 0,
203
+ 0,
204
+ 0,
205
+ 0,
206
+ 0,
207
+ 0,
208
+ 0,
209
+ ]
210
+ assert nx.clustering(G, weight="weight") == {
211
+ 0: 0,
212
+ 1: 0,
213
+ 2: 0,
214
+ 3: 0,
215
+ 4: 0,
216
+ 5: 0,
217
+ 6: 0,
218
+ 7: 0,
219
+ 8: 0,
220
+ 9: 0,
221
+ }
222
+
223
+ def test_cubical(self):
224
+ G = nx.cubical_graph()
225
+ assert list(nx.clustering(G, weight="weight").values()) == [
226
+ 0,
227
+ 0,
228
+ 0,
229
+ 0,
230
+ 0,
231
+ 0,
232
+ 0,
233
+ 0,
234
+ ]
235
+ assert nx.clustering(G, 1) == 0
236
+ assert list(nx.clustering(G, [1, 2], weight="weight").values()) == [0, 0]
237
+ assert nx.clustering(G, 1, weight="weight") == 0
238
+ assert nx.clustering(G, [1, 2], weight="weight") == {1: 0, 2: 0}
239
+
240
+ def test_k5(self):
241
+ G = nx.complete_graph(5)
242
+ assert list(nx.clustering(G, weight="weight").values()) == [1, 1, 1, 1, 1]
243
+ assert nx.average_clustering(G, weight="weight") == 1
244
+ G.remove_edge(1, 2)
245
+ assert list(nx.clustering(G, weight="weight").values()) == [
246
+ 5 / 6,
247
+ 1,
248
+ 1,
249
+ 5 / 6,
250
+ 5 / 6,
251
+ ]
252
+ assert nx.clustering(G, [1, 4], weight="weight") == {
253
+ 1: 1,
254
+ 4: 0.83333333333333337,
255
+ }
256
+
257
+ def test_triangle_and_edge(self):
258
+ G = nx.cycle_graph(3)
259
+ G.add_edge(0, 4, weight=2)
260
+ assert nx.clustering(G)[0] == 1 / 3
261
+ np.testing.assert_allclose(nx.clustering(G, weight="weight")[0], 1 / 6)
262
+ np.testing.assert_allclose(nx.clustering(G, 0, weight="weight"), 1 / 6)
263
+
264
+ def test_triangle_and_signed_edge(self):
265
+ G = nx.cycle_graph(3)
266
+ G.add_edge(0, 1, weight=-1)
267
+ G.add_edge(3, 0, weight=0)
268
+ assert nx.clustering(G)[0] == 1 / 3
269
+ assert nx.clustering(G, weight="weight")[0] == -1 / 3
270
+
271
+
272
+ class TestClustering:
273
+ @classmethod
274
+ def setup_class(cls):
275
+ pytest.importorskip("numpy")
276
+
277
+ def test_clustering(self):
278
+ G = nx.Graph()
279
+ assert list(nx.clustering(G).values()) == []
280
+ assert nx.clustering(G) == {}
281
+
282
+ def test_path(self):
283
+ G = nx.path_graph(10)
284
+ assert list(nx.clustering(G).values()) == [
285
+ 0,
286
+ 0,
287
+ 0,
288
+ 0,
289
+ 0,
290
+ 0,
291
+ 0,
292
+ 0,
293
+ 0,
294
+ 0,
295
+ ]
296
+ assert nx.clustering(G) == {
297
+ 0: 0,
298
+ 1: 0,
299
+ 2: 0,
300
+ 3: 0,
301
+ 4: 0,
302
+ 5: 0,
303
+ 6: 0,
304
+ 7: 0,
305
+ 8: 0,
306
+ 9: 0,
307
+ }
308
+
309
+ def test_cubical(self):
310
+ G = nx.cubical_graph()
311
+ assert list(nx.clustering(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0]
312
+ assert nx.clustering(G, 1) == 0
313
+ assert list(nx.clustering(G, [1, 2]).values()) == [0, 0]
314
+ assert nx.clustering(G, 1) == 0
315
+ assert nx.clustering(G, [1, 2]) == {1: 0, 2: 0}
316
+
317
+ def test_k5(self):
318
+ G = nx.complete_graph(5)
319
+ assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
320
+ assert nx.average_clustering(G) == 1
321
+ G.remove_edge(1, 2)
322
+ assert list(nx.clustering(G).values()) == [
323
+ 5 / 6,
324
+ 1,
325
+ 1,
326
+ 5 / 6,
327
+ 5 / 6,
328
+ ]
329
+ assert nx.clustering(G, [1, 4]) == {1: 1, 4: 0.83333333333333337}
330
+
331
+ def test_k5_signed(self):
332
+ G = nx.complete_graph(5)
333
+ assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1]
334
+ assert nx.average_clustering(G) == 1
335
+ G.remove_edge(1, 2)
336
+ G.add_edge(0, 1, weight=-1)
337
+ assert list(nx.clustering(G, weight="weight").values()) == [
338
+ 1 / 6,
339
+ -1 / 3,
340
+ 1,
341
+ 3 / 6,
342
+ 3 / 6,
343
+ ]
344
+
345
+
346
+ class TestTransitivity:
347
+ def test_transitivity(self):
348
+ G = nx.Graph()
349
+ assert nx.transitivity(G) == 0
350
+
351
+ def test_path(self):
352
+ G = nx.path_graph(10)
353
+ assert nx.transitivity(G) == 0
354
+
355
+ def test_cubical(self):
356
+ G = nx.cubical_graph()
357
+ assert nx.transitivity(G) == 0
358
+
359
+ def test_k5(self):
360
+ G = nx.complete_graph(5)
361
+ assert nx.transitivity(G) == 1
362
+ G.remove_edge(1, 2)
363
+ assert nx.transitivity(G) == 0.875
364
+
365
+
366
+ class TestSquareClustering:
367
+ def test_clustering(self):
368
+ G = nx.Graph()
369
+ assert list(nx.square_clustering(G).values()) == []
370
+ assert nx.square_clustering(G) == {}
371
+
372
+ def test_path(self):
373
+ G = nx.path_graph(10)
374
+ assert list(nx.square_clustering(G).values()) == [
375
+ 0,
376
+ 0,
377
+ 0,
378
+ 0,
379
+ 0,
380
+ 0,
381
+ 0,
382
+ 0,
383
+ 0,
384
+ 0,
385
+ ]
386
+ assert nx.square_clustering(G) == {
387
+ 0: 0,
388
+ 1: 0,
389
+ 2: 0,
390
+ 3: 0,
391
+ 4: 0,
392
+ 5: 0,
393
+ 6: 0,
394
+ 7: 0,
395
+ 8: 0,
396
+ 9: 0,
397
+ }
398
+
399
+ def test_cubical(self):
400
+ G = nx.cubical_graph()
401
+ assert list(nx.square_clustering(G).values()) == [
402
+ 1 / 3,
403
+ 1 / 3,
404
+ 1 / 3,
405
+ 1 / 3,
406
+ 1 / 3,
407
+ 1 / 3,
408
+ 1 / 3,
409
+ 1 / 3,
410
+ ]
411
+ assert list(nx.square_clustering(G, [1, 2]).values()) == [1 / 3, 1 / 3]
412
+ assert nx.square_clustering(G, [1])[1] == 1 / 3
413
+ assert nx.square_clustering(G, 1) == 1 / 3
414
+ assert nx.square_clustering(G, [1, 2]) == {1: 1 / 3, 2: 1 / 3}
415
+
416
+ def test_k5(self):
417
+ G = nx.complete_graph(5)
418
+ assert list(nx.square_clustering(G).values()) == [1, 1, 1, 1, 1]
419
+
420
+ def test_bipartite_k5(self):
421
+ G = nx.complete_bipartite_graph(5, 5)
422
+ assert list(nx.square_clustering(G).values()) == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
423
+
424
+ def test_lind_square_clustering(self):
425
+ """Test C4 for figure 1 Lind et al (2005)"""
426
+ G = nx.Graph(
427
+ [
428
+ (1, 2),
429
+ (1, 3),
430
+ (1, 6),
431
+ (1, 7),
432
+ (2, 4),
433
+ (2, 5),
434
+ (3, 4),
435
+ (3, 5),
436
+ (6, 7),
437
+ (7, 8),
438
+ (6, 8),
439
+ (7, 9),
440
+ (7, 10),
441
+ (6, 11),
442
+ (6, 12),
443
+ (2, 13),
444
+ (2, 14),
445
+ (3, 15),
446
+ (3, 16),
447
+ ]
448
+ )
449
+ G1 = G.subgraph([1, 2, 3, 4, 5, 13, 14, 15, 16])
450
+ G2 = G.subgraph([1, 6, 7, 8, 9, 10, 11, 12])
451
+ assert nx.square_clustering(G, [1])[1] == 3 / 43
452
+ assert nx.square_clustering(G1, [1])[1] == 2 / 6
453
+ assert nx.square_clustering(G2, [1])[1] == 1 / 5
454
+
455
+ def test_peng_square_clustering(self):
456
+ """Test eq2 for figure 1 Peng et al (2008)"""
457
+ G = nx.Graph([(1, 2), (1, 3), (2, 4), (3, 4), (3, 5), (3, 6)])
458
+ assert nx.square_clustering(G, [1])[1] == 1 / 3
459
+
460
+
461
+ class TestAverageClustering:
462
+ @classmethod
463
+ def setup_class(cls):
464
+ pytest.importorskip("numpy")
465
+
466
+ def test_empty(self):
467
+ G = nx.Graph()
468
+ with pytest.raises(ZeroDivisionError):
469
+ nx.average_clustering(G)
470
+
471
+ def test_average_clustering(self):
472
+ G = nx.cycle_graph(3)
473
+ G.add_edge(2, 3)
474
+ assert nx.average_clustering(G) == (1 + 1 + 1 / 3) / 4
475
+ assert nx.average_clustering(G, count_zeros=True) == (1 + 1 + 1 / 3) / 4
476
+ assert nx.average_clustering(G, count_zeros=False) == (1 + 1 + 1 / 3) / 3
477
+ assert nx.average_clustering(G, [1, 2, 3]) == (1 + 1 / 3) / 3
478
+ assert nx.average_clustering(G, [1, 2, 3], count_zeros=True) == (1 + 1 / 3) / 3
479
+ assert nx.average_clustering(G, [1, 2, 3], count_zeros=False) == (1 + 1 / 3) / 2
480
+
481
+ def test_average_clustering_signed(self):
482
+ G = nx.cycle_graph(3)
483
+ G.add_edge(2, 3)
484
+ G.add_edge(0, 1, weight=-1)
485
+ assert nx.average_clustering(G, weight="weight") == (-1 - 1 - 1 / 3) / 4
486
+ assert (
487
+ nx.average_clustering(G, weight="weight", count_zeros=True)
488
+ == (-1 - 1 - 1 / 3) / 4
489
+ )
490
+ assert (
491
+ nx.average_clustering(G, weight="weight", count_zeros=False)
492
+ == (-1 - 1 - 1 / 3) / 3
493
+ )
494
+
495
+
496
+ class TestDirectedAverageClustering:
497
+ @classmethod
498
+ def setup_class(cls):
499
+ pytest.importorskip("numpy")
500
+
501
+ def test_empty(self):
502
+ G = nx.DiGraph()
503
+ with pytest.raises(ZeroDivisionError):
504
+ nx.average_clustering(G)
505
+
506
+ def test_average_clustering(self):
507
+ G = nx.cycle_graph(3, create_using=nx.DiGraph())
508
+ G.add_edge(2, 3)
509
+ assert nx.average_clustering(G) == (1 + 1 + 1 / 3) / 8
510
+ assert nx.average_clustering(G, count_zeros=True) == (1 + 1 + 1 / 3) / 8
511
+ assert nx.average_clustering(G, count_zeros=False) == (1 + 1 + 1 / 3) / 6
512
+ assert nx.average_clustering(G, [1, 2, 3]) == (1 + 1 / 3) / 6
513
+ assert nx.average_clustering(G, [1, 2, 3], count_zeros=True) == (1 + 1 / 3) / 6
514
+ assert nx.average_clustering(G, [1, 2, 3], count_zeros=False) == (1 + 1 / 3) / 4
515
+
516
+
517
+ class TestGeneralizedDegree:
518
+ def test_generalized_degree(self):
519
+ G = nx.Graph()
520
+ assert nx.generalized_degree(G) == {}
521
+
522
+ def test_path(self):
523
+ G = nx.path_graph(5)
524
+ assert nx.generalized_degree(G, 0) == {0: 1}
525
+ assert nx.generalized_degree(G, 1) == {0: 2}
526
+
527
+ def test_cubical(self):
528
+ G = nx.cubical_graph()
529
+ assert nx.generalized_degree(G, 0) == {0: 3}
530
+
531
+ def test_k5(self):
532
+ G = nx.complete_graph(5)
533
+ assert nx.generalized_degree(G, 0) == {3: 4}
534
+ G.remove_edge(0, 1)
535
+ assert nx.generalized_degree(G, 0) == {2: 3}
536
+ assert nx.generalized_degree(G, [1, 2]) == {1: {2: 3}, 2: {2: 2, 3: 2}}
537
+ assert nx.generalized_degree(G) == {
538
+ 0: {2: 3},
539
+ 1: {2: 3},
540
+ 2: {2: 2, 3: 2},
541
+ 3: {2: 2, 3: 2},
542
+ 4: {2: 2, 3: 2},
543
+ }
shared/package-files/02/025d4339487853fa1f3144127959734b20f7c7b4948cff5d72149a0541a67968/Perth ADDED
Binary file (446 Bytes). View file
 
shared/package-files/02/025d4339487853fa1f3144127959734b20f7c7b4948cff5d72149a0541a67968/West ADDED
Binary file (446 Bytes). View file
 
shared/package-files/02/025d8146a57a50508862173f59f39378ccb975b89ef392b45b4bd345cb66b013/test_impute.py ADDED
@@ -0,0 +1,1955 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import re
3
+ import warnings
4
+ from itertools import product
5
+
6
+ import numpy as np
7
+ import pytest
8
+ from scipy import sparse
9
+ from scipy.stats import kstest
10
+
11
+ from sklearn import tree
12
+ from sklearn.datasets import load_diabetes
13
+ from sklearn.dummy import DummyRegressor
14
+ from sklearn.exceptions import ConvergenceWarning
15
+
16
+ # make IterativeImputer available
17
+ from sklearn.experimental import enable_iterative_imputer # noqa: F401
18
+ from sklearn.impute import IterativeImputer, KNNImputer, MissingIndicator, SimpleImputer
19
+ from sklearn.impute._base import _most_frequent
20
+ from sklearn.linear_model import ARDRegression, BayesianRidge, RidgeCV
21
+ from sklearn.model_selection import GridSearchCV
22
+ from sklearn.pipeline import Pipeline, make_union
23
+ from sklearn.random_projection import _sparse_random_matrix
24
+ from sklearn.utils._testing import (
25
+ _convert_container,
26
+ assert_allclose,
27
+ assert_allclose_dense_sparse,
28
+ assert_array_almost_equal,
29
+ assert_array_equal,
30
+ )
31
+ from sklearn.utils.fixes import (
32
+ BSR_CONTAINERS,
33
+ COO_CONTAINERS,
34
+ CSC_CONTAINERS,
35
+ CSR_CONTAINERS,
36
+ LIL_CONTAINERS,
37
+ )
38
+
39
+
40
+ def _assert_array_equal_and_same_dtype(x, y):
41
+ assert_array_equal(x, y)
42
+ assert x.dtype == y.dtype
43
+
44
+
45
+ def _assert_allclose_and_same_dtype(x, y):
46
+ assert_allclose(x, y)
47
+ assert x.dtype == y.dtype
48
+
49
+
50
+ def _check_statistics(
51
+ X, X_true, strategy, statistics, missing_values, sparse_container
52
+ ):
53
+ """Utility function for testing imputation for a given strategy.
54
+
55
+ Test with dense and sparse arrays
56
+
57
+ Check that:
58
+ - the statistics (mean, median, mode) are correct
59
+ - the missing values are imputed correctly"""
60
+
61
+ err_msg = "Parameters: strategy = %s, missing_values = %s, sparse = {0}" % (
62
+ strategy,
63
+ missing_values,
64
+ )
65
+
66
+ assert_ae = assert_array_equal
67
+
68
+ if X.dtype.kind == "f" or X_true.dtype.kind == "f":
69
+ assert_ae = assert_array_almost_equal
70
+
71
+ # Normal matrix
72
+ imputer = SimpleImputer(missing_values=missing_values, strategy=strategy)
73
+ X_trans = imputer.fit(X).transform(X.copy())
74
+ assert_ae(imputer.statistics_, statistics, err_msg=err_msg.format(False))
75
+ assert_ae(X_trans, X_true, err_msg=err_msg.format(False))
76
+
77
+ # Sparse matrix
78
+ imputer = SimpleImputer(missing_values=missing_values, strategy=strategy)
79
+ imputer.fit(sparse_container(X))
80
+ X_trans = imputer.transform(sparse_container(X.copy()))
81
+
82
+ if sparse.issparse(X_trans):
83
+ X_trans = X_trans.toarray()
84
+
85
+ assert_ae(imputer.statistics_, statistics, err_msg=err_msg.format(True))
86
+ assert_ae(X_trans, X_true, err_msg=err_msg.format(True))
87
+
88
+
89
+ @pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent", "constant"])
90
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
91
+ def test_imputation_shape(strategy, csr_container):
92
+ # Verify the shapes of the imputed matrix for different strategies.
93
+ X = np.random.randn(10, 2)
94
+ X[::2] = np.nan
95
+
96
+ imputer = SimpleImputer(strategy=strategy)
97
+ X_imputed = imputer.fit_transform(csr_container(X))
98
+ assert X_imputed.shape == (10, 2)
99
+ X_imputed = imputer.fit_transform(X)
100
+ assert X_imputed.shape == (10, 2)
101
+
102
+ iterative_imputer = IterativeImputer(initial_strategy=strategy)
103
+ X_imputed = iterative_imputer.fit_transform(X)
104
+ assert X_imputed.shape == (10, 2)
105
+
106
+
107
+ @pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent"])
108
+ def test_imputation_deletion_warning(strategy):
109
+ X = np.ones((3, 5))
110
+ X[:, 0] = np.nan
111
+ imputer = SimpleImputer(strategy=strategy).fit(X)
112
+
113
+ with pytest.warns(UserWarning, match="Skipping"):
114
+ imputer.transform(X)
115
+
116
+
117
+ @pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent"])
118
+ def test_imputation_deletion_warning_feature_names(strategy):
119
+ pd = pytest.importorskip("pandas")
120
+
121
+ missing_values = np.nan
122
+ feature_names = np.array(["a", "b", "c", "d"], dtype=object)
123
+ X = pd.DataFrame(
124
+ [
125
+ [missing_values, missing_values, 1, missing_values],
126
+ [4, missing_values, 2, 10],
127
+ ],
128
+ columns=feature_names,
129
+ )
130
+
131
+ imputer = SimpleImputer(strategy=strategy).fit(X)
132
+
133
+ # check SimpleImputer returning feature name attribute correctly
134
+ assert_array_equal(imputer.feature_names_in_, feature_names)
135
+
136
+ # ensure that skipped feature warning includes feature name
137
+ with pytest.warns(
138
+ UserWarning, match=r"Skipping features without any observed values: \['b'\]"
139
+ ):
140
+ imputer.transform(X)
141
+
142
+
143
+ @pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent", "constant"])
144
+ @pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
145
+ def test_imputation_error_sparse_0(strategy, csc_container):
146
+ # check that error are raised when missing_values = 0 and input is sparse
147
+ X = np.ones((3, 5))
148
+ X[0] = 0
149
+ X = csc_container(X)
150
+
151
+ imputer = SimpleImputer(strategy=strategy, missing_values=0)
152
+ with pytest.raises(ValueError, match="Provide a dense array"):
153
+ imputer.fit(X)
154
+
155
+ imputer.fit(X.toarray())
156
+ with pytest.raises(ValueError, match="Provide a dense array"):
157
+ imputer.transform(X)
158
+
159
+
160
+ def safe_median(arr, *args, **kwargs):
161
+ # np.median([]) raises a TypeError for numpy >= 1.10.1
162
+ length = arr.size if hasattr(arr, "size") else len(arr)
163
+ return np.nan if length == 0 else np.median(arr, *args, **kwargs)
164
+
165
+
166
+ def safe_mean(arr, *args, **kwargs):
167
+ # np.mean([]) raises a RuntimeWarning for numpy >= 1.10.1
168
+ length = arr.size if hasattr(arr, "size") else len(arr)
169
+ return np.nan if length == 0 else np.mean(arr, *args, **kwargs)
170
+
171
+
172
+ @pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
173
+ def test_imputation_mean_median(csc_container):
174
+ # Test imputation using the mean and median strategies, when
175
+ # missing_values != 0.
176
+ rng = np.random.RandomState(0)
177
+
178
+ dim = 10
179
+ dec = 10
180
+ shape = (dim * dim, dim + dec)
181
+
182
+ zeros = np.zeros(shape[0])
183
+ values = np.arange(1, shape[0] + 1)
184
+ values[4::2] = -values[4::2]
185
+
186
+ tests = [
187
+ ("mean", np.nan, lambda z, v, p: safe_mean(np.hstack((z, v)))),
188
+ ("median", np.nan, lambda z, v, p: safe_median(np.hstack((z, v)))),
189
+ ]
190
+
191
+ for strategy, test_missing_values, true_value_fun in tests:
192
+ X = np.empty(shape)
193
+ X_true = np.empty(shape)
194
+ true_statistics = np.empty(shape[1])
195
+
196
+ # Create a matrix X with columns
197
+ # - with only zeros,
198
+ # - with only missing values
199
+ # - with zeros, missing values and values
200
+ # And a matrix X_true containing all true values
201
+ for j in range(shape[1]):
202
+ nb_zeros = (j - dec + 1 > 0) * (j - dec + 1) * (j - dec + 1)
203
+ nb_missing_values = max(shape[0] + dec * dec - (j + dec) * (j + dec), 0)
204
+ nb_values = shape[0] - nb_zeros - nb_missing_values
205
+
206
+ z = zeros[:nb_zeros]
207
+ p = np.repeat(test_missing_values, nb_missing_values)
208
+ v = values[rng.permutation(len(values))[:nb_values]]
209
+
210
+ true_statistics[j] = true_value_fun(z, v, p)
211
+
212
+ # Create the columns
213
+ X[:, j] = np.hstack((v, z, p))
214
+
215
+ if 0 == test_missing_values:
216
+ # XXX unreached code as of v0.22
217
+ X_true[:, j] = np.hstack(
218
+ (v, np.repeat(true_statistics[j], nb_missing_values + nb_zeros))
219
+ )
220
+ else:
221
+ X_true[:, j] = np.hstack(
222
+ (v, z, np.repeat(true_statistics[j], nb_missing_values))
223
+ )
224
+
225
+ # Shuffle them the same way
226
+ np.random.RandomState(j).shuffle(X[:, j])
227
+ np.random.RandomState(j).shuffle(X_true[:, j])
228
+
229
+ # Mean doesn't support columns containing NaNs, median does
230
+ if strategy == "median":
231
+ cols_to_keep = ~np.isnan(X_true).any(axis=0)
232
+ else:
233
+ cols_to_keep = ~np.isnan(X_true).all(axis=0)
234
+
235
+ X_true = X_true[:, cols_to_keep]
236
+
237
+ _check_statistics(
238
+ X, X_true, strategy, true_statistics, test_missing_values, csc_container
239
+ )
240
+
241
+
242
+ @pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
243
+ def test_imputation_median_special_cases(csc_container):
244
+ # Test median imputation with sparse boundary cases
245
+ X = np.array(
246
+ [
247
+ [0, np.nan, np.nan], # odd: implicit zero
248
+ [5, np.nan, np.nan], # odd: explicit nonzero
249
+ [0, 0, np.nan], # even: average two zeros
250
+ [-5, 0, np.nan], # even: avg zero and neg
251
+ [0, 5, np.nan], # even: avg zero and pos
252
+ [4, 5, np.nan], # even: avg nonzeros
253
+ [-4, -5, np.nan], # even: avg negatives
254
+ [-1, 2, np.nan], # even: crossing neg and pos
255
+ ]
256
+ ).transpose()
257
+
258
+ X_imputed_median = np.array(
259
+ [
260
+ [0, 0, 0],
261
+ [5, 5, 5],
262
+ [0, 0, 0],
263
+ [-5, 0, -2.5],
264
+ [0, 5, 2.5],
265
+ [4, 5, 4.5],
266
+ [-4, -5, -4.5],
267
+ [-1, 2, 0.5],
268
+ ]
269
+ ).transpose()
270
+ statistics_median = [0, 5, 0, -2.5, 2.5, 4.5, -4.5, 0.5]
271
+
272
+ _check_statistics(
273
+ X, X_imputed_median, "median", statistics_median, np.nan, csc_container
274
+ )
275
+
276
+
277
+ @pytest.mark.parametrize("strategy", ["mean", "median"])
278
+ @pytest.mark.parametrize("dtype", [None, object, str])
279
+ def test_imputation_mean_median_error_invalid_type(strategy, dtype):
280
+ X = np.array([["a", "b", 3], [4, "e", 6], ["g", "h", 9]], dtype=dtype)
281
+ msg = "non-numeric data:\ncould not convert string to float:"
282
+ with pytest.raises(ValueError, match=msg):
283
+ imputer = SimpleImputer(strategy=strategy)
284
+ imputer.fit_transform(X)
285
+
286
+
287
+ @pytest.mark.parametrize("strategy", ["mean", "median"])
288
+ @pytest.mark.parametrize("type", ["list", "dataframe"])
289
+ def test_imputation_mean_median_error_invalid_type_list_pandas(strategy, type):
290
+ X = [["a", "b", 3], [4, "e", 6], ["g", "h", 9]]
291
+ if type == "dataframe":
292
+ pd = pytest.importorskip("pandas")
293
+ X = pd.DataFrame(X)
294
+ msg = "non-numeric data:\ncould not convert string to float:"
295
+ with pytest.raises(ValueError, match=msg):
296
+ imputer = SimpleImputer(strategy=strategy)
297
+ imputer.fit_transform(X)
298
+
299
+
300
+ @pytest.mark.parametrize("strategy", ["constant", "most_frequent"])
301
+ @pytest.mark.parametrize("dtype", [str, np.dtype("U"), np.dtype("S")])
302
+ def test_imputation_const_mostf_error_invalid_types(strategy, dtype):
303
+ # Test imputation on non-numeric data using "most_frequent" and "constant"
304
+ # strategy
305
+ X = np.array(
306
+ [
307
+ [np.nan, np.nan, "a", "f"],
308
+ [np.nan, "c", np.nan, "d"],
309
+ [np.nan, "b", "d", np.nan],
310
+ [np.nan, "c", "d", "h"],
311
+ ],
312
+ dtype=dtype,
313
+ )
314
+
315
+ err_msg = "SimpleImputer does not support data"
316
+ with pytest.raises(ValueError, match=err_msg):
317
+ imputer = SimpleImputer(strategy=strategy)
318
+ imputer.fit(X).transform(X)
319
+
320
+
321
+ @pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
322
+ def test_imputation_most_frequent(csc_container):
323
+ # Test imputation using the most-frequent strategy.
324
+ X = np.array(
325
+ [
326
+ [-1, -1, 0, 5],
327
+ [-1, 2, -1, 3],
328
+ [-1, 1, 3, -1],
329
+ [-1, 2, 3, 7],
330
+ ]
331
+ )
332
+
333
+ X_true = np.array(
334
+ [
335
+ [2, 0, 5],
336
+ [2, 3, 3],
337
+ [1, 3, 3],
338
+ [2, 3, 7],
339
+ ]
340
+ )
341
+
342
+ # scipy.stats.mode, used in SimpleImputer, doesn't return the first most
343
+ # frequent as promised in the doc but the lowest most frequent. When this
344
+ # test will fail after an update of scipy, SimpleImputer will need to be
345
+ # updated to be consistent with the new (correct) behaviour
346
+ _check_statistics(X, X_true, "most_frequent", [np.nan, 2, 3, 3], -1, csc_container)
347
+
348
+
349
+ @pytest.mark.parametrize("marker", [None, np.nan, "NAN", "", 0])
350
+ def test_imputation_most_frequent_objects(marker):
351
+ # Test imputation using the most-frequent strategy.
352
+ X = np.array(
353
+ [
354
+ [marker, marker, "a", "f"],
355
+ [marker, "c", marker, "d"],
356
+ [marker, "b", "d", marker],
357
+ [marker, "c", "d", "h"],
358
+ ],
359
+ dtype=object,
360
+ )
361
+
362
+ X_true = np.array(
363
+ [
364
+ ["c", "a", "f"],
365
+ ["c", "d", "d"],
366
+ ["b", "d", "d"],
367
+ ["c", "d", "h"],
368
+ ],
369
+ dtype=object,
370
+ )
371
+
372
+ imputer = SimpleImputer(missing_values=marker, strategy="most_frequent")
373
+ X_trans = imputer.fit(X).transform(X)
374
+
375
+ assert_array_equal(X_trans, X_true)
376
+
377
+
378
+ @pytest.mark.parametrize("dtype", [object, "category"])
379
+ def test_imputation_most_frequent_pandas(dtype):
380
+ # Test imputation using the most frequent strategy on pandas df
381
+ pd = pytest.importorskip("pandas")
382
+
383
+ f = io.StringIO("Cat1,Cat2,Cat3,Cat4\n,i,x,\na,,y,\na,j,,\nb,j,x,")
384
+
385
+ df = pd.read_csv(f, dtype=dtype)
386
+
387
+ X_true = np.array(
388
+ [["a", "i", "x"], ["a", "j", "y"], ["a", "j", "x"], ["b", "j", "x"]],
389
+ dtype=object,
390
+ )
391
+
392
+ imputer = SimpleImputer(strategy="most_frequent")
393
+ X_trans = imputer.fit_transform(df)
394
+
395
+ assert_array_equal(X_trans, X_true)
396
+
397
+
398
+ @pytest.mark.parametrize("X_data, missing_value", [(1, 0), (1.0, np.nan)])
399
+ def test_imputation_constant_error_invalid_type(X_data, missing_value):
400
+ # Verify that exceptions are raised on invalid fill_value type
401
+ X = np.full((3, 5), X_data, dtype=float)
402
+ X[0, 0] = missing_value
403
+
404
+ fill_value = "x"
405
+ err_msg = f"fill_value={fill_value!r} (of type {type(fill_value)!r}) cannot be cast"
406
+ with pytest.raises(ValueError, match=re.escape(err_msg)):
407
+ imputer = SimpleImputer(
408
+ missing_values=missing_value, strategy="constant", fill_value=fill_value
409
+ )
410
+ imputer.fit_transform(X)
411
+
412
+
413
+ # TODO (1.8): check that `keep_empty_features=False` drop the
414
+ # empty features due to the behaviour change.
415
+ def test_imputation_constant_integer():
416
+ # Test imputation using the constant strategy on integers
417
+ X = np.array([[-1, 2, 3, -1], [4, -1, 5, -1], [6, 7, -1, -1], [8, 9, 0, -1]])
418
+
419
+ X_true = np.array([[0, 2, 3, 0], [4, 0, 5, 0], [6, 7, 0, 0], [8, 9, 0, 0]])
420
+
421
+ imputer = SimpleImputer(
422
+ missing_values=-1, strategy="constant", fill_value=0, keep_empty_features=True
423
+ )
424
+ X_trans = imputer.fit_transform(X)
425
+
426
+ assert_array_equal(X_trans, X_true)
427
+
428
+
429
+ # TODO (1.8): check that `keep_empty_features=False` drop the
430
+ # empty features due to the behaviour change.
431
+ @pytest.mark.parametrize("array_constructor", CSR_CONTAINERS + [np.asarray])
432
+ def test_imputation_constant_float(array_constructor):
433
+ # Test imputation using the constant strategy on floats
434
+ X = np.array(
435
+ [
436
+ [np.nan, 1.1, 0, np.nan],
437
+ [1.2, np.nan, 1.3, np.nan],
438
+ [0, 0, np.nan, np.nan],
439
+ [1.4, 1.5, 0, np.nan],
440
+ ]
441
+ )
442
+
443
+ X_true = np.array(
444
+ [[-1, 1.1, 0, -1], [1.2, -1, 1.3, -1], [0, 0, -1, -1], [1.4, 1.5, 0, -1]]
445
+ )
446
+
447
+ X = array_constructor(X)
448
+
449
+ X_true = array_constructor(X_true)
450
+
451
+ imputer = SimpleImputer(
452
+ strategy="constant", fill_value=-1, keep_empty_features=True
453
+ )
454
+ X_trans = imputer.fit_transform(X)
455
+
456
+ assert_allclose_dense_sparse(X_trans, X_true)
457
+
458
+
459
+ # TODO (1.8): check that `keep_empty_features=False` drop the
460
+ # empty features due to the behaviour change.
461
+ @pytest.mark.parametrize("marker", [None, np.nan, "NAN", "", 0])
462
+ def test_imputation_constant_object(marker):
463
+ # Test imputation using the constant strategy on objects
464
+ X = np.array(
465
+ [
466
+ [marker, "a", "b", marker],
467
+ ["c", marker, "d", marker],
468
+ ["e", "f", marker, marker],
469
+ ["g", "h", "i", marker],
470
+ ],
471
+ dtype=object,
472
+ )
473
+
474
+ X_true = np.array(
475
+ [
476
+ ["missing", "a", "b", "missing"],
477
+ ["c", "missing", "d", "missing"],
478
+ ["e", "f", "missing", "missing"],
479
+ ["g", "h", "i", "missing"],
480
+ ],
481
+ dtype=object,
482
+ )
483
+
484
+ imputer = SimpleImputer(
485
+ missing_values=marker,
486
+ strategy="constant",
487
+ fill_value="missing",
488
+ keep_empty_features=True,
489
+ )
490
+ X_trans = imputer.fit_transform(X)
491
+
492
+ assert_array_equal(X_trans, X_true)
493
+
494
+
495
+ # TODO (1.8): check that `keep_empty_features=False` drop the
496
+ # empty features due to the behaviour change.
497
+ @pytest.mark.parametrize("dtype", [object, "category"])
498
+ def test_imputation_constant_pandas(dtype):
499
+ # Test imputation using the constant strategy on pandas df
500
+ pd = pytest.importorskip("pandas")
501
+
502
+ f = io.StringIO("Cat1,Cat2,Cat3,Cat4\n,i,x,\na,,y,\na,j,,\nb,j,x,")
503
+
504
+ df = pd.read_csv(f, dtype=dtype)
505
+
506
+ X_true = np.array(
507
+ [
508
+ ["missing_value", "i", "x", "missing_value"],
509
+ ["a", "missing_value", "y", "missing_value"],
510
+ ["a", "j", "missing_value", "missing_value"],
511
+ ["b", "j", "x", "missing_value"],
512
+ ],
513
+ dtype=object,
514
+ )
515
+
516
+ imputer = SimpleImputer(strategy="constant", keep_empty_features=True)
517
+ X_trans = imputer.fit_transform(df)
518
+
519
+ assert_array_equal(X_trans, X_true)
520
+
521
+
522
+ @pytest.mark.parametrize("X", [[[1], [2]], [[1], [np.nan]]])
523
+ def test_iterative_imputer_one_feature(X):
524
+ # check we exit early when there is a single feature
525
+ imputer = IterativeImputer().fit(X)
526
+ assert imputer.n_iter_ == 0
527
+ imputer = IterativeImputer()
528
+ imputer.fit([[1], [2]])
529
+ assert imputer.n_iter_ == 0
530
+ imputer.fit([[1], [np.nan]])
531
+ assert imputer.n_iter_ == 0
532
+
533
+
534
+ def test_imputation_pipeline_grid_search():
535
+ # Test imputation within a pipeline + gridsearch.
536
+ X = _sparse_random_matrix(100, 100, density=0.10)
537
+ missing_values = X.data[0]
538
+
539
+ pipeline = Pipeline(
540
+ [
541
+ ("imputer", SimpleImputer(missing_values=missing_values)),
542
+ ("tree", tree.DecisionTreeRegressor(random_state=0)),
543
+ ]
544
+ )
545
+
546
+ parameters = {"imputer__strategy": ["mean", "median", "most_frequent"]}
547
+
548
+ Y = _sparse_random_matrix(100, 1, density=0.10).toarray()
549
+ gs = GridSearchCV(pipeline, parameters)
550
+ gs.fit(X, Y)
551
+
552
+
553
+ def test_imputation_copy():
554
+ # Test imputation with copy
555
+ X_orig = _sparse_random_matrix(5, 5, density=0.75, random_state=0)
556
+
557
+ # copy=True, dense => copy
558
+ X = X_orig.copy().toarray()
559
+ imputer = SimpleImputer(missing_values=0, strategy="mean", copy=True)
560
+ Xt = imputer.fit(X).transform(X)
561
+ Xt[0, 0] = -1
562
+ assert not np.all(X == Xt)
563
+
564
+ # copy=True, sparse csr => copy
565
+ X = X_orig.copy()
566
+ imputer = SimpleImputer(missing_values=X.data[0], strategy="mean", copy=True)
567
+ Xt = imputer.fit(X).transform(X)
568
+ Xt.data[0] = -1
569
+ assert not np.all(X.data == Xt.data)
570
+
571
+ # copy=False, dense => no copy
572
+ X = X_orig.copy().toarray()
573
+ imputer = SimpleImputer(missing_values=0, strategy="mean", copy=False)
574
+ Xt = imputer.fit(X).transform(X)
575
+ Xt[0, 0] = -1
576
+ assert_array_almost_equal(X, Xt)
577
+
578
+ # copy=False, sparse csc => no copy
579
+ X = X_orig.copy().tocsc()
580
+ imputer = SimpleImputer(missing_values=X.data[0], strategy="mean", copy=False)
581
+ Xt = imputer.fit(X).transform(X)
582
+ Xt.data[0] = -1
583
+ assert_array_almost_equal(X.data, Xt.data)
584
+
585
+ # copy=False, sparse csr => copy
586
+ X = X_orig.copy()
587
+ imputer = SimpleImputer(missing_values=X.data[0], strategy="mean", copy=False)
588
+ Xt = imputer.fit(X).transform(X)
589
+ Xt.data[0] = -1
590
+ assert not np.all(X.data == Xt.data)
591
+
592
+ # Note: If X is sparse and if missing_values=0, then a (dense) copy of X is
593
+ # made, even if copy=False.
594
+
595
+
596
+ def test_iterative_imputer_zero_iters():
597
+ rng = np.random.RandomState(0)
598
+
599
+ n = 100
600
+ d = 10
601
+ X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray()
602
+ missing_flag = X == 0
603
+ X[missing_flag] = np.nan
604
+
605
+ imputer = IterativeImputer(max_iter=0)
606
+ X_imputed = imputer.fit_transform(X)
607
+ # with max_iter=0, only initial imputation is performed
608
+ assert_allclose(X_imputed, imputer.initial_imputer_.transform(X))
609
+
610
+ # repeat but force n_iter_ to 0
611
+ imputer = IterativeImputer(max_iter=5).fit(X)
612
+ # transformed should not be equal to initial imputation
613
+ assert not np.all(imputer.transform(X) == imputer.initial_imputer_.transform(X))
614
+
615
+ imputer.n_iter_ = 0
616
+ # now they should be equal as only initial imputation is done
617
+ assert_allclose(imputer.transform(X), imputer.initial_imputer_.transform(X))
618
+
619
+
620
+ def test_iterative_imputer_verbose():
621
+ rng = np.random.RandomState(0)
622
+
623
+ n = 100
624
+ d = 3
625
+ X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray()
626
+ imputer = IterativeImputer(missing_values=0, max_iter=1, verbose=1)
627
+ imputer.fit(X)
628
+ imputer.transform(X)
629
+ imputer = IterativeImputer(missing_values=0, max_iter=1, verbose=2)
630
+ imputer.fit(X)
631
+ imputer.transform(X)
632
+
633
+
634
+ def test_iterative_imputer_all_missing():
635
+ n = 100
636
+ d = 3
637
+ X = np.zeros((n, d))
638
+ imputer = IterativeImputer(missing_values=0, max_iter=1)
639
+ X_imputed = imputer.fit_transform(X)
640
+ assert_allclose(X_imputed, imputer.initial_imputer_.transform(X))
641
+
642
+
643
+ @pytest.mark.parametrize(
644
+ "imputation_order", ["random", "roman", "ascending", "descending", "arabic"]
645
+ )
646
+ def test_iterative_imputer_imputation_order(imputation_order):
647
+ rng = np.random.RandomState(0)
648
+ n = 100
649
+ d = 10
650
+ max_iter = 2
651
+ X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray()
652
+ X[:, 0] = 1 # this column should not be discarded by IterativeImputer
653
+
654
+ imputer = IterativeImputer(
655
+ missing_values=0,
656
+ max_iter=max_iter,
657
+ n_nearest_features=5,
658
+ sample_posterior=False,
659
+ skip_complete=True,
660
+ min_value=0,
661
+ max_value=1,
662
+ verbose=1,
663
+ imputation_order=imputation_order,
664
+ random_state=rng,
665
+ )
666
+ imputer.fit_transform(X)
667
+ ordered_idx = [i.feat_idx for i in imputer.imputation_sequence_]
668
+
669
+ assert len(ordered_idx) // imputer.n_iter_ == imputer.n_features_with_missing_
670
+
671
+ if imputation_order == "roman":
672
+ assert np.all(ordered_idx[: d - 1] == np.arange(1, d))
673
+ elif imputation_order == "arabic":
674
+ assert np.all(ordered_idx[: d - 1] == np.arange(d - 1, 0, -1))
675
+ elif imputation_order == "random":
676
+ ordered_idx_round_1 = ordered_idx[: d - 1]
677
+ ordered_idx_round_2 = ordered_idx[d - 1 :]
678
+ assert ordered_idx_round_1 != ordered_idx_round_2
679
+ elif "ending" in imputation_order:
680
+ assert len(ordered_idx) == max_iter * (d - 1)
681
+
682
+
683
+ @pytest.mark.parametrize(
684
+ "estimator", [None, DummyRegressor(), BayesianRidge(), ARDRegression(), RidgeCV()]
685
+ )
686
+ def test_iterative_imputer_estimators(estimator):
687
+ rng = np.random.RandomState(0)
688
+
689
+ n = 100
690
+ d = 10
691
+ X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray()
692
+
693
+ imputer = IterativeImputer(
694
+ missing_values=0, max_iter=1, estimator=estimator, random_state=rng
695
+ )
696
+ imputer.fit_transform(X)
697
+
698
+ # check that types are correct for estimators
699
+ hashes = []
700
+ for triplet in imputer.imputation_sequence_:
701
+ expected_type = (
702
+ type(estimator) if estimator is not None else type(BayesianRidge())
703
+ )
704
+ assert isinstance(triplet.estimator, expected_type)
705
+ hashes.append(id(triplet.estimator))
706
+
707
+ # check that each estimator is unique
708
+ assert len(set(hashes)) == len(hashes)
709
+
710
+
711
+ def test_iterative_imputer_clip():
712
+ rng = np.random.RandomState(0)
713
+ n = 100
714
+ d = 10
715
+ X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray()
716
+
717
+ imputer = IterativeImputer(
718
+ missing_values=0, max_iter=1, min_value=0.1, max_value=0.2, random_state=rng
719
+ )
720
+
721
+ Xt = imputer.fit_transform(X)
722
+ assert_allclose(np.min(Xt[X == 0]), 0.1)
723
+ assert_allclose(np.max(Xt[X == 0]), 0.2)
724
+ assert_allclose(Xt[X != 0], X[X != 0])
725
+
726
+
727
+ def test_iterative_imputer_clip_truncnorm():
728
+ rng = np.random.RandomState(0)
729
+ n = 100
730
+ d = 10
731
+ X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray()
732
+ X[:, 0] = 1
733
+
734
+ imputer = IterativeImputer(
735
+ missing_values=0,
736
+ max_iter=2,
737
+ n_nearest_features=5,
738
+ sample_posterior=True,
739
+ min_value=0.1,
740
+ max_value=0.2,
741
+ verbose=1,
742
+ imputation_order="random",
743
+ random_state=rng,
744
+ )
745
+ Xt = imputer.fit_transform(X)
746
+ assert_allclose(np.min(Xt[X == 0]), 0.1)
747
+ assert_allclose(np.max(Xt[X == 0]), 0.2)
748
+ assert_allclose(Xt[X != 0], X[X != 0])
749
+
750
+
751
+ def test_iterative_imputer_truncated_normal_posterior():
752
+ # test that the values that are imputed using `sample_posterior=True`
753
+ # with boundaries (`min_value` and `max_value` are not None) are drawn
754
+ # from a distribution that looks gaussian via the Kolmogorov Smirnov test.
755
+ # note that starting from the wrong random seed will make this test fail
756
+ # because random sampling doesn't occur at all when the imputation
757
+ # is outside of the (min_value, max_value) range
758
+ rng = np.random.RandomState(42)
759
+
760
+ X = rng.normal(size=(5, 5))
761
+ X[0][0] = np.nan
762
+
763
+ imputer = IterativeImputer(
764
+ min_value=0, max_value=0.5, sample_posterior=True, random_state=rng
765
+ )
766
+
767
+ imputer.fit_transform(X)
768
+ # generate multiple imputations for the single missing value
769
+ imputations = np.array([imputer.transform(X)[0][0] for _ in range(100)])
770
+
771
+ assert all(imputations >= 0)
772
+ assert all(imputations <= 0.5)
773
+
774
+ mu, sigma = imputations.mean(), imputations.std()
775
+ ks_statistic, p_value = kstest((imputations - mu) / sigma, "norm")
776
+ if sigma == 0:
777
+ sigma += 1e-12
778
+ ks_statistic, p_value = kstest((imputations - mu) / sigma, "norm")
779
+ # we want to fail to reject null hypothesis
780
+ # null hypothesis: distributions are the same
781
+ assert ks_statistic < 0.2 or p_value > 0.1, "The posterior does appear to be normal"
782
+
783
+
784
+ @pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent"])
785
+ def test_iterative_imputer_missing_at_transform(strategy):
786
+ rng = np.random.RandomState(0)
787
+ n = 100
788
+ d = 10
789
+ X_train = rng.randint(low=0, high=3, size=(n, d))
790
+ X_test = rng.randint(low=0, high=3, size=(n, d))
791
+
792
+ X_train[:, 0] = 1 # definitely no missing values in 0th column
793
+ X_test[0, 0] = 0 # definitely missing value in 0th column
794
+
795
+ imputer = IterativeImputer(
796
+ missing_values=0, max_iter=1, initial_strategy=strategy, random_state=rng
797
+ ).fit(X_train)
798
+ initial_imputer = SimpleImputer(missing_values=0, strategy=strategy).fit(X_train)
799
+
800
+ # if there were no missing values at time of fit, then imputer will
801
+ # only use the initial imputer for that feature at transform
802
+ assert_allclose(
803
+ imputer.transform(X_test)[:, 0], initial_imputer.transform(X_test)[:, 0]
804
+ )
805
+
806
+
807
+ def test_iterative_imputer_transform_stochasticity():
808
+ rng1 = np.random.RandomState(0)
809
+ rng2 = np.random.RandomState(1)
810
+ n = 100
811
+ d = 10
812
+ X = _sparse_random_matrix(n, d, density=0.10, random_state=rng1).toarray()
813
+
814
+ # when sample_posterior=True, two transforms shouldn't be equal
815
+ imputer = IterativeImputer(
816
+ missing_values=0, max_iter=1, sample_posterior=True, random_state=rng1
817
+ )
818
+ imputer.fit(X)
819
+
820
+ X_fitted_1 = imputer.transform(X)
821
+ X_fitted_2 = imputer.transform(X)
822
+
823
+ # sufficient to assert that the means are not the same
824
+ assert np.mean(X_fitted_1) != pytest.approx(np.mean(X_fitted_2))
825
+
826
+ # when sample_posterior=False, and n_nearest_features=None
827
+ # and imputation_order is not random
828
+ # the two transforms should be identical even if rng are different
829
+ imputer1 = IterativeImputer(
830
+ missing_values=0,
831
+ max_iter=1,
832
+ sample_posterior=False,
833
+ n_nearest_features=None,
834
+ imputation_order="ascending",
835
+ random_state=rng1,
836
+ )
837
+
838
+ imputer2 = IterativeImputer(
839
+ missing_values=0,
840
+ max_iter=1,
841
+ sample_posterior=False,
842
+ n_nearest_features=None,
843
+ imputation_order="ascending",
844
+ random_state=rng2,
845
+ )
846
+ imputer1.fit(X)
847
+ imputer2.fit(X)
848
+
849
+ X_fitted_1a = imputer1.transform(X)
850
+ X_fitted_1b = imputer1.transform(X)
851
+ X_fitted_2 = imputer2.transform(X)
852
+
853
+ assert_allclose(X_fitted_1a, X_fitted_1b)
854
+ assert_allclose(X_fitted_1a, X_fitted_2)
855
+
856
+
857
+ def test_iterative_imputer_no_missing():
858
+ rng = np.random.RandomState(0)
859
+ X = rng.rand(100, 100)
860
+ X[:, 0] = np.nan
861
+ m1 = IterativeImputer(max_iter=10, random_state=rng)
862
+ m2 = IterativeImputer(max_iter=10, random_state=rng)
863
+ pred1 = m1.fit(X).transform(X)
864
+ pred2 = m2.fit_transform(X)
865
+ # should exclude the first column entirely
866
+ assert_allclose(X[:, 1:], pred1)
867
+ # fit and fit_transform should both be identical
868
+ assert_allclose(pred1, pred2)
869
+
870
+
871
+ def test_iterative_imputer_rank_one():
872
+ rng = np.random.RandomState(0)
873
+ d = 50
874
+ A = rng.rand(d, 1)
875
+ B = rng.rand(1, d)
876
+ X = np.dot(A, B)
877
+ nan_mask = rng.rand(d, d) < 0.5
878
+ X_missing = X.copy()
879
+ X_missing[nan_mask] = np.nan
880
+
881
+ imputer = IterativeImputer(max_iter=5, verbose=1, random_state=rng)
882
+ X_filled = imputer.fit_transform(X_missing)
883
+ assert_allclose(X_filled, X, atol=0.02)
884
+
885
+
886
+ @pytest.mark.parametrize("rank", [3, 5])
887
+ def test_iterative_imputer_transform_recovery(rank):
888
+ rng = np.random.RandomState(0)
889
+ n = 70
890
+ d = 70
891
+ A = rng.rand(n, rank)
892
+ B = rng.rand(rank, d)
893
+ X_filled = np.dot(A, B)
894
+ nan_mask = rng.rand(n, d) < 0.5
895
+ X_missing = X_filled.copy()
896
+ X_missing[nan_mask] = np.nan
897
+
898
+ # split up data in half
899
+ n = n // 2
900
+ X_train = X_missing[:n]
901
+ X_test_filled = X_filled[n:]
902
+ X_test = X_missing[n:]
903
+
904
+ imputer = IterativeImputer(
905
+ max_iter=5, imputation_order="descending", verbose=1, random_state=rng
906
+ ).fit(X_train)
907
+ X_test_est = imputer.transform(X_test)
908
+ assert_allclose(X_test_filled, X_test_est, atol=0.1)
909
+
910
+
911
+ def test_iterative_imputer_additive_matrix():
912
+ rng = np.random.RandomState(0)
913
+ n = 100
914
+ d = 10
915
+ A = rng.randn(n, d)
916
+ B = rng.randn(n, d)
917
+ X_filled = np.zeros(A.shape)
918
+ for i in range(d):
919
+ for j in range(d):
920
+ X_filled[:, (i + j) % d] += (A[:, i] + B[:, j]) / 2
921
+ # a quarter is randomly missing
922
+ nan_mask = rng.rand(n, d) < 0.25
923
+ X_missing = X_filled.copy()
924
+ X_missing[nan_mask] = np.nan
925
+
926
+ # split up data
927
+ n = n // 2
928
+ X_train = X_missing[:n]
929
+ X_test_filled = X_filled[n:]
930
+ X_test = X_missing[n:]
931
+
932
+ imputer = IterativeImputer(max_iter=10, verbose=1, random_state=rng).fit(X_train)
933
+ X_test_est = imputer.transform(X_test)
934
+ assert_allclose(X_test_filled, X_test_est, rtol=1e-3, atol=0.01)
935
+
936
+
937
+ def test_iterative_imputer_early_stopping():
938
+ rng = np.random.RandomState(0)
939
+ n = 50
940
+ d = 5
941
+ A = rng.rand(n, 1)
942
+ B = rng.rand(1, d)
943
+ X = np.dot(A, B)
944
+ nan_mask = rng.rand(n, d) < 0.5
945
+ X_missing = X.copy()
946
+ X_missing[nan_mask] = np.nan
947
+
948
+ imputer = IterativeImputer(
949
+ max_iter=100, tol=1e-2, sample_posterior=False, verbose=1, random_state=rng
950
+ )
951
+ X_filled_100 = imputer.fit_transform(X_missing)
952
+ assert len(imputer.imputation_sequence_) == d * imputer.n_iter_
953
+
954
+ imputer = IterativeImputer(
955
+ max_iter=imputer.n_iter_, sample_posterior=False, verbose=1, random_state=rng
956
+ )
957
+ X_filled_early = imputer.fit_transform(X_missing)
958
+ assert_allclose(X_filled_100, X_filled_early, atol=1e-7)
959
+
960
+ imputer = IterativeImputer(
961
+ max_iter=100, tol=0, sample_posterior=False, verbose=1, random_state=rng
962
+ )
963
+ imputer.fit(X_missing)
964
+ assert imputer.n_iter_ == imputer.max_iter
965
+
966
+
967
+ def test_iterative_imputer_catch_warning():
968
+ # check that we catch a RuntimeWarning due to a division by zero when a
969
+ # feature is constant in the dataset
970
+ X, y = load_diabetes(return_X_y=True)
971
+ n_samples, n_features = X.shape
972
+
973
+ # simulate that a feature only contain one category during fit
974
+ X[:, 3] = 1
975
+
976
+ # add some missing values
977
+ rng = np.random.RandomState(0)
978
+ missing_rate = 0.15
979
+ for feat in range(n_features):
980
+ sample_idx = rng.choice(
981
+ np.arange(n_samples), size=int(n_samples * missing_rate), replace=False
982
+ )
983
+ X[sample_idx, feat] = np.nan
984
+
985
+ imputer = IterativeImputer(n_nearest_features=5, sample_posterior=True)
986
+ with warnings.catch_warnings():
987
+ warnings.simplefilter("error", RuntimeWarning)
988
+ X_fill = imputer.fit_transform(X, y)
989
+ assert not np.any(np.isnan(X_fill))
990
+
991
+
992
+ @pytest.mark.parametrize(
993
+ "min_value, max_value, correct_output",
994
+ [
995
+ (0, 100, np.array([[0] * 3, [100] * 3])),
996
+ (None, None, np.array([[-np.inf] * 3, [np.inf] * 3])),
997
+ (-np.inf, np.inf, np.array([[-np.inf] * 3, [np.inf] * 3])),
998
+ ([-5, 5, 10], [100, 200, 300], np.array([[-5, 5, 10], [100, 200, 300]])),
999
+ (
1000
+ [-5, -np.inf, 10],
1001
+ [100, 200, np.inf],
1002
+ np.array([[-5, -np.inf, 10], [100, 200, np.inf]]),
1003
+ ),
1004
+ ],
1005
+ ids=["scalars", "None-default", "inf", "lists", "lists-with-inf"],
1006
+ )
1007
+ def test_iterative_imputer_min_max_array_like(min_value, max_value, correct_output):
1008
+ # check that passing scalar or array-like
1009
+ # for min_value and max_value in IterativeImputer works
1010
+ X = np.random.RandomState(0).randn(10, 3)
1011
+ imputer = IterativeImputer(min_value=min_value, max_value=max_value)
1012
+ imputer.fit(X)
1013
+
1014
+ assert isinstance(imputer._min_value, np.ndarray) and isinstance(
1015
+ imputer._max_value, np.ndarray
1016
+ )
1017
+ assert (imputer._min_value.shape[0] == X.shape[1]) and (
1018
+ imputer._max_value.shape[0] == X.shape[1]
1019
+ )
1020
+
1021
+ assert_allclose(correct_output[0, :], imputer._min_value)
1022
+ assert_allclose(correct_output[1, :], imputer._max_value)
1023
+
1024
+
1025
+ @pytest.mark.parametrize(
1026
+ "min_value, max_value, err_msg",
1027
+ [
1028
+ (100, 0, "min_value >= max_value."),
1029
+ (np.inf, -np.inf, "min_value >= max_value."),
1030
+ ([-5, 5], [100, 200, 0], "_value' should be of shape"),
1031
+ ([-5, 5, 5], [100, 200], "_value' should be of shape"),
1032
+ ],
1033
+ )
1034
+ def test_iterative_imputer_catch_min_max_error(min_value, max_value, err_msg):
1035
+ # check that passing scalar or array-like
1036
+ # for min_value and max_value in IterativeImputer works
1037
+ X = np.random.random((10, 3))
1038
+ imputer = IterativeImputer(min_value=min_value, max_value=max_value)
1039
+ with pytest.raises(ValueError, match=err_msg):
1040
+ imputer.fit(X)
1041
+
1042
+
1043
+ @pytest.mark.parametrize(
1044
+ "min_max_1, min_max_2",
1045
+ [([None, None], [-np.inf, np.inf]), ([-10, 10], [[-10] * 4, [10] * 4])],
1046
+ ids=["None-vs-inf", "Scalar-vs-vector"],
1047
+ )
1048
+ def test_iterative_imputer_min_max_array_like_imputation(min_max_1, min_max_2):
1049
+ # Test that None/inf and scalar/vector give the same imputation
1050
+ X_train = np.array(
1051
+ [
1052
+ [np.nan, 2, 2, 1],
1053
+ [10, np.nan, np.nan, 7],
1054
+ [3, 1, np.nan, 1],
1055
+ [np.nan, 4, 2, np.nan],
1056
+ ]
1057
+ )
1058
+ X_test = np.array(
1059
+ [[np.nan, 2, np.nan, 5], [2, 4, np.nan, np.nan], [np.nan, 1, 10, 1]]
1060
+ )
1061
+ imputer1 = IterativeImputer(
1062
+ min_value=min_max_1[0], max_value=min_max_1[1], random_state=0
1063
+ )
1064
+ imputer2 = IterativeImputer(
1065
+ min_value=min_max_2[0], max_value=min_max_2[1], random_state=0
1066
+ )
1067
+ X_test_imputed1 = imputer1.fit(X_train).transform(X_test)
1068
+ X_test_imputed2 = imputer2.fit(X_train).transform(X_test)
1069
+ assert_allclose(X_test_imputed1[:, 0], X_test_imputed2[:, 0])
1070
+
1071
+
1072
+ @pytest.mark.parametrize("skip_complete", [True, False])
1073
+ def test_iterative_imputer_skip_non_missing(skip_complete):
1074
+ # check the imputing strategy when missing data are present in the
1075
+ # testing set only.
1076
+ # taken from: https://github.com/scikit-learn/scikit-learn/issues/14383
1077
+ rng = np.random.RandomState(0)
1078
+ X_train = np.array([[5, 2, 2, 1], [10, 1, 2, 7], [3, 1, 1, 1], [8, 4, 2, 2]])
1079
+ X_test = np.array([[np.nan, 2, 4, 5], [np.nan, 4, 1, 2], [np.nan, 1, 10, 1]])
1080
+ imputer = IterativeImputer(
1081
+ initial_strategy="mean", skip_complete=skip_complete, random_state=rng
1082
+ )
1083
+ X_test_est = imputer.fit(X_train).transform(X_test)
1084
+ if skip_complete:
1085
+ # impute with the initial strategy: 'mean'
1086
+ assert_allclose(X_test_est[:, 0], np.mean(X_train[:, 0]))
1087
+ else:
1088
+ assert_allclose(X_test_est[:, 0], [11, 7, 12], rtol=1e-4)
1089
+
1090
+
1091
+ @pytest.mark.parametrize("rs_imputer", [None, 1, np.random.RandomState(seed=1)])
1092
+ @pytest.mark.parametrize("rs_estimator", [None, 1, np.random.RandomState(seed=1)])
1093
+ def test_iterative_imputer_dont_set_random_state(rs_imputer, rs_estimator):
1094
+ class ZeroEstimator:
1095
+ def __init__(self, random_state):
1096
+ self.random_state = random_state
1097
+
1098
+ def fit(self, *args, **kgards):
1099
+ return self
1100
+
1101
+ def predict(self, X):
1102
+ return np.zeros(X.shape[0])
1103
+
1104
+ estimator = ZeroEstimator(random_state=rs_estimator)
1105
+ imputer = IterativeImputer(random_state=rs_imputer)
1106
+ X_train = np.zeros((10, 3))
1107
+ imputer.fit(X_train)
1108
+ assert estimator.random_state == rs_estimator
1109
+
1110
+
1111
+ @pytest.mark.parametrize(
1112
+ "X_fit, X_trans, params, msg_err",
1113
+ [
1114
+ (
1115
+ np.array([[-1, 1], [1, 2]]),
1116
+ np.array([[-1, 1], [1, -1]]),
1117
+ {"features": "missing-only", "sparse": "auto"},
1118
+ "have missing values in transform but have no missing values in fit",
1119
+ ),
1120
+ (
1121
+ np.array([["a", "b"], ["c", "a"]], dtype=str),
1122
+ np.array([["a", "b"], ["c", "a"]], dtype=str),
1123
+ {},
1124
+ "MissingIndicator does not support data with dtype",
1125
+ ),
1126
+ ],
1127
+ )
1128
+ def test_missing_indicator_error(X_fit, X_trans, params, msg_err):
1129
+ indicator = MissingIndicator(missing_values=-1)
1130
+ indicator.set_params(**params)
1131
+ with pytest.raises(ValueError, match=msg_err):
1132
+ indicator.fit(X_fit).transform(X_trans)
1133
+
1134
+
1135
+ def _generate_missing_indicator_cases():
1136
+ missing_values_dtypes = [(0, np.int32), (np.nan, np.float64), (-1, np.int32)]
1137
+ arr_types = (
1138
+ [np.array]
1139
+ + CSC_CONTAINERS
1140
+ + CSR_CONTAINERS
1141
+ + COO_CONTAINERS
1142
+ + LIL_CONTAINERS
1143
+ + BSR_CONTAINERS
1144
+ )
1145
+ return [
1146
+ (arr_type, missing_values, dtype)
1147
+ for arr_type, (missing_values, dtype) in product(
1148
+ arr_types, missing_values_dtypes
1149
+ )
1150
+ if not (missing_values == 0 and arr_type is not np.array)
1151
+ ]
1152
+
1153
+
1154
+ @pytest.mark.parametrize(
1155
+ "arr_type, missing_values, dtype", _generate_missing_indicator_cases()
1156
+ )
1157
+ @pytest.mark.parametrize(
1158
+ "param_features, n_features, features_indices",
1159
+ [("missing-only", 3, np.array([0, 1, 2])), ("all", 3, np.array([0, 1, 2]))],
1160
+ )
1161
+ def test_missing_indicator_new(
1162
+ missing_values, arr_type, dtype, param_features, n_features, features_indices
1163
+ ):
1164
+ X_fit = np.array([[missing_values, missing_values, 1], [4, 2, missing_values]])
1165
+ X_trans = np.array([[missing_values, missing_values, 1], [4, 12, 10]])
1166
+ X_fit_expected = np.array([[1, 1, 0], [0, 0, 1]])
1167
+ X_trans_expected = np.array([[1, 1, 0], [0, 0, 0]])
1168
+
1169
+ # convert the input to the right array format and right dtype
1170
+ X_fit = arr_type(X_fit).astype(dtype)
1171
+ X_trans = arr_type(X_trans).astype(dtype)
1172
+ X_fit_expected = X_fit_expected.astype(dtype)
1173
+ X_trans_expected = X_trans_expected.astype(dtype)
1174
+
1175
+ indicator = MissingIndicator(
1176
+ missing_values=missing_values, features=param_features, sparse=False
1177
+ )
1178
+ X_fit_mask = indicator.fit_transform(X_fit)
1179
+ X_trans_mask = indicator.transform(X_trans)
1180
+
1181
+ assert X_fit_mask.shape[1] == n_features
1182
+ assert X_trans_mask.shape[1] == n_features
1183
+
1184
+ assert_array_equal(indicator.features_, features_indices)
1185
+ assert_allclose(X_fit_mask, X_fit_expected[:, features_indices])
1186
+ assert_allclose(X_trans_mask, X_trans_expected[:, features_indices])
1187
+
1188
+ assert X_fit_mask.dtype == bool
1189
+ assert X_trans_mask.dtype == bool
1190
+ assert isinstance(X_fit_mask, np.ndarray)
1191
+ assert isinstance(X_trans_mask, np.ndarray)
1192
+
1193
+ indicator.set_params(sparse=True)
1194
+ X_fit_mask_sparse = indicator.fit_transform(X_fit)
1195
+ X_trans_mask_sparse = indicator.transform(X_trans)
1196
+
1197
+ assert X_fit_mask_sparse.dtype == bool
1198
+ assert X_trans_mask_sparse.dtype == bool
1199
+ assert X_fit_mask_sparse.format == "csc"
1200
+ assert X_trans_mask_sparse.format == "csc"
1201
+ assert_allclose(X_fit_mask_sparse.toarray(), X_fit_mask)
1202
+ assert_allclose(X_trans_mask_sparse.toarray(), X_trans_mask)
1203
+
1204
+
1205
+ @pytest.mark.parametrize(
1206
+ "arr_type",
1207
+ CSC_CONTAINERS + CSR_CONTAINERS + COO_CONTAINERS + LIL_CONTAINERS + BSR_CONTAINERS,
1208
+ )
1209
+ def test_missing_indicator_raise_on_sparse_with_missing_0(arr_type):
1210
+ # test for sparse input and missing_value == 0
1211
+
1212
+ missing_values = 0
1213
+ X_fit = np.array([[missing_values, missing_values, 1], [4, missing_values, 2]])
1214
+ X_trans = np.array([[missing_values, missing_values, 1], [4, 12, 10]])
1215
+
1216
+ # convert the input to the right array format
1217
+ X_fit_sparse = arr_type(X_fit)
1218
+ X_trans_sparse = arr_type(X_trans)
1219
+
1220
+ indicator = MissingIndicator(missing_values=missing_values)
1221
+
1222
+ with pytest.raises(ValueError, match="Sparse input with missing_values=0"):
1223
+ indicator.fit_transform(X_fit_sparse)
1224
+
1225
+ indicator.fit_transform(X_fit)
1226
+ with pytest.raises(ValueError, match="Sparse input with missing_values=0"):
1227
+ indicator.transform(X_trans_sparse)
1228
+
1229
+
1230
+ @pytest.mark.parametrize("param_sparse", [True, False, "auto"])
1231
+ @pytest.mark.parametrize(
1232
+ "arr_type, missing_values",
1233
+ [(np.array, 0)]
1234
+ + list(
1235
+ product(
1236
+ CSC_CONTAINERS
1237
+ + CSR_CONTAINERS
1238
+ + COO_CONTAINERS
1239
+ + LIL_CONTAINERS
1240
+ + BSR_CONTAINERS,
1241
+ [np.nan],
1242
+ )
1243
+ ),
1244
+ )
1245
+ def test_missing_indicator_sparse_param(arr_type, missing_values, param_sparse):
1246
+ # check the format of the output with different sparse parameter
1247
+ X_fit = np.array([[missing_values, missing_values, 1], [4, missing_values, 2]])
1248
+ X_trans = np.array([[missing_values, missing_values, 1], [4, 12, 10]])
1249
+ X_fit = arr_type(X_fit).astype(np.float64)
1250
+ X_trans = arr_type(X_trans).astype(np.float64)
1251
+
1252
+ indicator = MissingIndicator(missing_values=missing_values, sparse=param_sparse)
1253
+ X_fit_mask = indicator.fit_transform(X_fit)
1254
+ X_trans_mask = indicator.transform(X_trans)
1255
+
1256
+ if param_sparse is True:
1257
+ assert X_fit_mask.format == "csc"
1258
+ assert X_trans_mask.format == "csc"
1259
+ elif param_sparse == "auto" and missing_values == 0:
1260
+ assert isinstance(X_fit_mask, np.ndarray)
1261
+ assert isinstance(X_trans_mask, np.ndarray)
1262
+ elif param_sparse is False:
1263
+ assert isinstance(X_fit_mask, np.ndarray)
1264
+ assert isinstance(X_trans_mask, np.ndarray)
1265
+ else:
1266
+ if sparse.issparse(X_fit):
1267
+ assert X_fit_mask.format == "csc"
1268
+ assert X_trans_mask.format == "csc"
1269
+ else:
1270
+ assert isinstance(X_fit_mask, np.ndarray)
1271
+ assert isinstance(X_trans_mask, np.ndarray)
1272
+
1273
+
1274
+ def test_missing_indicator_string():
1275
+ X = np.array([["a", "b", "c"], ["b", "c", "a"]], dtype=object)
1276
+ indicator = MissingIndicator(missing_values="a", features="all")
1277
+ X_trans = indicator.fit_transform(X)
1278
+ assert_array_equal(X_trans, np.array([[True, False, False], [False, False, True]]))
1279
+
1280
+
1281
+ @pytest.mark.parametrize(
1282
+ "X, missing_values, X_trans_exp",
1283
+ [
1284
+ (
1285
+ np.array([["a", "b"], ["b", "a"]], dtype=object),
1286
+ "a",
1287
+ np.array([["b", "b", True, False], ["b", "b", False, True]], dtype=object),
1288
+ ),
1289
+ (
1290
+ np.array([[np.nan, 1.0], [1.0, np.nan]]),
1291
+ np.nan,
1292
+ np.array([[1.0, 1.0, True, False], [1.0, 1.0, False, True]]),
1293
+ ),
1294
+ (
1295
+ np.array([[np.nan, "b"], ["b", np.nan]], dtype=object),
1296
+ np.nan,
1297
+ np.array([["b", "b", True, False], ["b", "b", False, True]], dtype=object),
1298
+ ),
1299
+ (
1300
+ np.array([[None, "b"], ["b", None]], dtype=object),
1301
+ None,
1302
+ np.array([["b", "b", True, False], ["b", "b", False, True]], dtype=object),
1303
+ ),
1304
+ ],
1305
+ )
1306
+ def test_missing_indicator_with_imputer(X, missing_values, X_trans_exp):
1307
+ trans = make_union(
1308
+ SimpleImputer(missing_values=missing_values, strategy="most_frequent"),
1309
+ MissingIndicator(missing_values=missing_values),
1310
+ )
1311
+ X_trans = trans.fit_transform(X)
1312
+ assert_array_equal(X_trans, X_trans_exp)
1313
+
1314
+
1315
+ @pytest.mark.parametrize("imputer_constructor", [SimpleImputer, IterativeImputer])
1316
+ @pytest.mark.parametrize(
1317
+ "imputer_missing_values, missing_value, err_msg",
1318
+ [
1319
+ ("NaN", np.nan, "Input X contains NaN"),
1320
+ ("-1", -1, "types are expected to be both numerical."),
1321
+ ],
1322
+ )
1323
+ def test_inconsistent_dtype_X_missing_values(
1324
+ imputer_constructor, imputer_missing_values, missing_value, err_msg
1325
+ ):
1326
+ # regression test for issue #11390. Comparison between incoherent dtype
1327
+ # for X and missing_values was not raising a proper error.
1328
+ rng = np.random.RandomState(42)
1329
+ X = rng.randn(10, 10)
1330
+ X[0, 0] = missing_value
1331
+
1332
+ imputer = imputer_constructor(missing_values=imputer_missing_values)
1333
+
1334
+ with pytest.raises(ValueError, match=err_msg):
1335
+ imputer.fit_transform(X)
1336
+
1337
+
1338
+ def test_missing_indicator_no_missing():
1339
+ # check that all features are dropped if there are no missing values when
1340
+ # features='missing-only' (#13491)
1341
+ X = np.array([[1, 1], [1, 1]])
1342
+
1343
+ mi = MissingIndicator(features="missing-only", missing_values=-1)
1344
+ Xt = mi.fit_transform(X)
1345
+
1346
+ assert Xt.shape[1] == 0
1347
+
1348
+
1349
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
1350
+ def test_missing_indicator_sparse_no_explicit_zeros(csr_container):
1351
+ # Check that non missing values don't become explicit zeros in the mask
1352
+ # generated by missing indicator when X is sparse. (#13491)
1353
+ X = csr_container([[0, 1, 2], [1, 2, 0], [2, 0, 1]])
1354
+
1355
+ mi = MissingIndicator(features="all", missing_values=1)
1356
+ Xt = mi.fit_transform(X)
1357
+
1358
+ assert Xt.nnz == Xt.sum()
1359
+
1360
+
1361
+ @pytest.mark.parametrize("imputer_constructor", [SimpleImputer, IterativeImputer])
1362
+ def test_imputer_without_indicator(imputer_constructor):
1363
+ X = np.array([[1, 1], [1, 1]])
1364
+ imputer = imputer_constructor()
1365
+ imputer.fit(X)
1366
+
1367
+ assert imputer.indicator_ is None
1368
+
1369
+
1370
+ @pytest.mark.parametrize(
1371
+ "arr_type",
1372
+ CSC_CONTAINERS + CSR_CONTAINERS + COO_CONTAINERS + LIL_CONTAINERS + BSR_CONTAINERS,
1373
+ )
1374
+ def test_simple_imputation_add_indicator_sparse_matrix(arr_type):
1375
+ X_sparse = arr_type([[np.nan, 1, 5], [2, np.nan, 1], [6, 3, np.nan], [1, 2, 9]])
1376
+ X_true = np.array(
1377
+ [
1378
+ [3.0, 1.0, 5.0, 1.0, 0.0, 0.0],
1379
+ [2.0, 2.0, 1.0, 0.0, 1.0, 0.0],
1380
+ [6.0, 3.0, 5.0, 0.0, 0.0, 1.0],
1381
+ [1.0, 2.0, 9.0, 0.0, 0.0, 0.0],
1382
+ ]
1383
+ )
1384
+
1385
+ imputer = SimpleImputer(missing_values=np.nan, add_indicator=True)
1386
+ X_trans = imputer.fit_transform(X_sparse)
1387
+
1388
+ assert sparse.issparse(X_trans)
1389
+ assert X_trans.shape == X_true.shape
1390
+ assert_allclose(X_trans.toarray(), X_true)
1391
+
1392
+
1393
+ @pytest.mark.parametrize(
1394
+ "strategy, expected", [("most_frequent", "b"), ("constant", "missing_value")]
1395
+ )
1396
+ def test_simple_imputation_string_list(strategy, expected):
1397
+ X = [["a", "b"], ["c", np.nan]]
1398
+
1399
+ X_true = np.array([["a", "b"], ["c", expected]], dtype=object)
1400
+
1401
+ imputer = SimpleImputer(strategy=strategy)
1402
+ X_trans = imputer.fit_transform(X)
1403
+
1404
+ assert_array_equal(X_trans, X_true)
1405
+
1406
+
1407
+ @pytest.mark.parametrize(
1408
+ "order, idx_order",
1409
+ [("ascending", [3, 4, 2, 0, 1]), ("descending", [1, 0, 2, 4, 3])],
1410
+ )
1411
+ def test_imputation_order(order, idx_order):
1412
+ # regression test for #15393
1413
+ rng = np.random.RandomState(42)
1414
+ X = rng.rand(100, 5)
1415
+ X[:50, 1] = np.nan
1416
+ X[:30, 0] = np.nan
1417
+ X[:20, 2] = np.nan
1418
+ X[:10, 4] = np.nan
1419
+
1420
+ with pytest.warns(ConvergenceWarning):
1421
+ trs = IterativeImputer(max_iter=1, imputation_order=order, random_state=0).fit(
1422
+ X
1423
+ )
1424
+ idx = [x.feat_idx for x in trs.imputation_sequence_]
1425
+ assert idx == idx_order
1426
+
1427
+
1428
+ @pytest.mark.parametrize("missing_value", [-1, np.nan])
1429
+ def test_simple_imputation_inverse_transform(missing_value):
1430
+ # Test inverse_transform feature for np.nan
1431
+ X_1 = np.array(
1432
+ [
1433
+ [9, missing_value, 3, -1],
1434
+ [4, -1, 5, 4],
1435
+ [6, 7, missing_value, -1],
1436
+ [8, 9, 0, missing_value],
1437
+ ]
1438
+ )
1439
+
1440
+ X_2 = np.array(
1441
+ [
1442
+ [5, 4, 2, 1],
1443
+ [2, 1, missing_value, 3],
1444
+ [9, missing_value, 7, 1],
1445
+ [6, 4, 2, missing_value],
1446
+ ]
1447
+ )
1448
+
1449
+ X_3 = np.array(
1450
+ [
1451
+ [1, missing_value, 5, 9],
1452
+ [missing_value, 4, missing_value, missing_value],
1453
+ [2, missing_value, 7, missing_value],
1454
+ [missing_value, 3, missing_value, 8],
1455
+ ]
1456
+ )
1457
+
1458
+ X_4 = np.array(
1459
+ [
1460
+ [1, 1, 1, 3],
1461
+ [missing_value, 2, missing_value, 1],
1462
+ [2, 3, 3, 4],
1463
+ [missing_value, 4, missing_value, 2],
1464
+ ]
1465
+ )
1466
+
1467
+ imputer = SimpleImputer(
1468
+ missing_values=missing_value, strategy="mean", add_indicator=True
1469
+ )
1470
+
1471
+ X_1_trans = imputer.fit_transform(X_1)
1472
+ X_1_inv_trans = imputer.inverse_transform(X_1_trans)
1473
+
1474
+ X_2_trans = imputer.transform(X_2) # test on new data
1475
+ X_2_inv_trans = imputer.inverse_transform(X_2_trans)
1476
+
1477
+ assert_array_equal(X_1_inv_trans, X_1)
1478
+ assert_array_equal(X_2_inv_trans, X_2)
1479
+
1480
+ for X in [X_3, X_4]:
1481
+ X_trans = imputer.fit_transform(X)
1482
+ X_inv_trans = imputer.inverse_transform(X_trans)
1483
+ assert_array_equal(X_inv_trans, X)
1484
+
1485
+
1486
+ @pytest.mark.parametrize("missing_value", [-1, np.nan])
1487
+ def test_simple_imputation_inverse_transform_exceptions(missing_value):
1488
+ X_1 = np.array(
1489
+ [
1490
+ [9, missing_value, 3, -1],
1491
+ [4, -1, 5, 4],
1492
+ [6, 7, missing_value, -1],
1493
+ [8, 9, 0, missing_value],
1494
+ ]
1495
+ )
1496
+
1497
+ imputer = SimpleImputer(missing_values=missing_value, strategy="mean")
1498
+ X_1_trans = imputer.fit_transform(X_1)
1499
+ with pytest.raises(
1500
+ ValueError, match=f"Got 'add_indicator={imputer.add_indicator}'"
1501
+ ):
1502
+ imputer.inverse_transform(X_1_trans)
1503
+
1504
+
1505
+ @pytest.mark.parametrize(
1506
+ "expected,array,dtype,extra_value,n_repeat",
1507
+ [
1508
+ # array of object dtype
1509
+ ("extra_value", ["a", "b", "c"], object, "extra_value", 2),
1510
+ (
1511
+ "most_frequent_value",
1512
+ ["most_frequent_value", "most_frequent_value", "value"],
1513
+ object,
1514
+ "extra_value",
1515
+ 1,
1516
+ ),
1517
+ ("a", ["min_value", "min_valuevalue"], object, "a", 2),
1518
+ ("min_value", ["min_value", "min_value", "value"], object, "z", 2),
1519
+ # array of numeric dtype
1520
+ (10, [1, 2, 3], int, 10, 2),
1521
+ (1, [1, 1, 2], int, 10, 1),
1522
+ (10, [20, 20, 1], int, 10, 2),
1523
+ (1, [1, 1, 20], int, 10, 2),
1524
+ ],
1525
+ )
1526
+ def test_most_frequent(expected, array, dtype, extra_value, n_repeat):
1527
+ assert expected == _most_frequent(
1528
+ np.array(array, dtype=dtype), extra_value, n_repeat
1529
+ )
1530
+
1531
+
1532
+ @pytest.mark.parametrize(
1533
+ "expected,array",
1534
+ [
1535
+ ("a", ["a", "b"]),
1536
+ (1, [1, 2]),
1537
+ (None, [None, "a"]),
1538
+ (None, [None, 1]),
1539
+ (None, [None, "a", 1]),
1540
+ (1, [1, "1"]),
1541
+ (1, ["1", 1]),
1542
+ ],
1543
+ )
1544
+ def test_most_frequent_tie_object(expected, array):
1545
+ """Check the tie breaking behavior of the most frequent strategy.
1546
+
1547
+ Non-regression test for issue #31717.
1548
+ """
1549
+ assert expected == _most_frequent(np.array(array, dtype=object), None, 0)
1550
+
1551
+
1552
+ @pytest.mark.parametrize(
1553
+ "initial_strategy", ["mean", "median", "most_frequent", "constant"]
1554
+ )
1555
+ def test_iterative_imputer_keep_empty_features(initial_strategy):
1556
+ """Check the behaviour of the iterative imputer with different initial strategy
1557
+ and keeping empty features (i.e. features containing only missing values).
1558
+ """
1559
+ X = np.array([[1, np.nan, 2], [3, np.nan, np.nan]])
1560
+
1561
+ imputer = IterativeImputer(
1562
+ initial_strategy=initial_strategy, keep_empty_features=True
1563
+ )
1564
+ X_imputed = imputer.fit_transform(X)
1565
+ assert_allclose(X_imputed[:, 1], 0)
1566
+ X_imputed = imputer.transform(X)
1567
+ assert_allclose(X_imputed[:, 1], 0)
1568
+
1569
+
1570
+ # TODO (1.8): check that `keep_empty_features=False` drop the
1571
+ # empty features due to the behaviour change.
1572
+ def test_iterative_imputer_constant_fill_value():
1573
+ """Check that we propagate properly the parameter `fill_value`."""
1574
+ X = np.array([[-1, 2, 3, -1], [4, -1, 5, -1], [6, 7, -1, -1], [8, 9, 0, -1]])
1575
+
1576
+ fill_value = 100
1577
+ imputer = IterativeImputer(
1578
+ missing_values=-1,
1579
+ initial_strategy="constant",
1580
+ fill_value=fill_value,
1581
+ max_iter=0,
1582
+ keep_empty_features=True,
1583
+ )
1584
+ imputer.fit_transform(X)
1585
+ assert_array_equal(imputer.initial_imputer_.statistics_, fill_value)
1586
+
1587
+
1588
+ def test_iterative_imputer_min_max_value_remove_empty():
1589
+ """Check that we properly apply the empty feature mask to `min_value` and
1590
+ `max_value`.
1591
+
1592
+ Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/29355
1593
+ """
1594
+ # Intentionally make column 2 as a missing column, then the bound of the imputed
1595
+ # value of column 3 should be (4, 5)
1596
+ X = np.array(
1597
+ [
1598
+ [1, 2, np.nan, np.nan],
1599
+ [4, 5, np.nan, 6],
1600
+ [7, 8, np.nan, np.nan],
1601
+ [10, 11, np.nan, 12],
1602
+ ]
1603
+ )
1604
+ min_value = [-np.inf, -np.inf, -np.inf, 4]
1605
+ max_value = [np.inf, np.inf, np.inf, 5]
1606
+
1607
+ X_imputed = IterativeImputer(
1608
+ min_value=min_value,
1609
+ max_value=max_value,
1610
+ keep_empty_features=False,
1611
+ ).fit_transform(X)
1612
+
1613
+ X_without_missing_column = np.delete(X, 2, axis=1)
1614
+ assert X_imputed.shape == X_without_missing_column.shape
1615
+ assert np.min(X_imputed[np.isnan(X_without_missing_column)]) == pytest.approx(4)
1616
+ assert np.max(X_imputed[np.isnan(X_without_missing_column)]) == pytest.approx(5)
1617
+
1618
+ # Intentionally make column 3 as a missing column, then the bound of the imputed
1619
+ # value of column 2 should be (3.5, 6)
1620
+ X = np.array(
1621
+ [
1622
+ [1, 2, np.nan, np.nan],
1623
+ [4, 5, 6, np.nan],
1624
+ [7, 8, np.nan, np.nan],
1625
+ [10, 11, 12, np.nan],
1626
+ ]
1627
+ )
1628
+ min_value = [-np.inf, -np.inf, 3.5, -np.inf]
1629
+ max_value = [np.inf, np.inf, 6, np.inf]
1630
+
1631
+ X_imputed = IterativeImputer(
1632
+ min_value=min_value,
1633
+ max_value=max_value,
1634
+ keep_empty_features=False,
1635
+ ).fit_transform(X)
1636
+
1637
+ X_without_missing_column = X[:, :3]
1638
+ assert X_imputed.shape == X_without_missing_column.shape
1639
+ assert np.min(X_imputed[np.isnan(X_without_missing_column)]) == pytest.approx(3.5)
1640
+ assert np.max(X_imputed[np.isnan(X_without_missing_column)]) == pytest.approx(6)
1641
+
1642
+
1643
+ @pytest.mark.parametrize("keep_empty_features", [True, False])
1644
+ def test_knn_imputer_keep_empty_features(keep_empty_features):
1645
+ """Check the behaviour of `keep_empty_features` for `KNNImputer`."""
1646
+ X = np.array([[1, np.nan, 2], [3, np.nan, np.nan]])
1647
+
1648
+ imputer = KNNImputer(keep_empty_features=keep_empty_features)
1649
+
1650
+ for method in ["fit_transform", "transform"]:
1651
+ X_imputed = getattr(imputer, method)(X)
1652
+ if keep_empty_features:
1653
+ assert X_imputed.shape == X.shape
1654
+ assert_array_equal(X_imputed[:, 1], 0)
1655
+ else:
1656
+ assert X_imputed.shape == (X.shape[0], X.shape[1] - 1)
1657
+
1658
+
1659
+ def test_simple_impute_pd_na():
1660
+ pd = pytest.importorskip("pandas")
1661
+
1662
+ # Impute pandas array of string types.
1663
+ df = pd.DataFrame({"feature": pd.Series(["abc", None, "de"], dtype="string")})
1664
+ imputer = SimpleImputer(missing_values=pd.NA, strategy="constant", fill_value="na")
1665
+ _assert_array_equal_and_same_dtype(
1666
+ imputer.fit_transform(df), np.array([["abc"], ["na"], ["de"]], dtype=object)
1667
+ )
1668
+
1669
+ # Impute pandas array of string types without any missing values.
1670
+ df = pd.DataFrame({"feature": pd.Series(["abc", "de", "fgh"], dtype="string")})
1671
+ imputer = SimpleImputer(fill_value="ok", strategy="constant")
1672
+ _assert_array_equal_and_same_dtype(
1673
+ imputer.fit_transform(df), np.array([["abc"], ["de"], ["fgh"]], dtype=object)
1674
+ )
1675
+
1676
+ # Impute pandas array of integer types.
1677
+ df = pd.DataFrame({"feature": pd.Series([1, None, 3], dtype="Int64")})
1678
+ imputer = SimpleImputer(missing_values=pd.NA, strategy="constant", fill_value=-1)
1679
+ _assert_allclose_and_same_dtype(
1680
+ imputer.fit_transform(df), np.array([[1], [-1], [3]], dtype="float64")
1681
+ )
1682
+
1683
+ # Use `np.nan` also works.
1684
+ imputer = SimpleImputer(missing_values=np.nan, strategy="constant", fill_value=-1)
1685
+ _assert_allclose_and_same_dtype(
1686
+ imputer.fit_transform(df), np.array([[1], [-1], [3]], dtype="float64")
1687
+ )
1688
+
1689
+ # Impute pandas array of integer types with 'median' strategy.
1690
+ df = pd.DataFrame({"feature": pd.Series([1, None, 2, 3], dtype="Int64")})
1691
+ imputer = SimpleImputer(missing_values=pd.NA, strategy="median")
1692
+ _assert_allclose_and_same_dtype(
1693
+ imputer.fit_transform(df), np.array([[1], [2], [2], [3]], dtype="float64")
1694
+ )
1695
+
1696
+ # Impute pandas array of integer types with 'mean' strategy.
1697
+ df = pd.DataFrame({"feature": pd.Series([1, None, 2], dtype="Int64")})
1698
+ imputer = SimpleImputer(missing_values=pd.NA, strategy="mean")
1699
+ _assert_allclose_and_same_dtype(
1700
+ imputer.fit_transform(df), np.array([[1], [1.5], [2]], dtype="float64")
1701
+ )
1702
+
1703
+ # Impute pandas array of float types.
1704
+ df = pd.DataFrame({"feature": pd.Series([1.0, None, 3.0], dtype="float64")})
1705
+ imputer = SimpleImputer(missing_values=pd.NA, strategy="constant", fill_value=-2.0)
1706
+ _assert_allclose_and_same_dtype(
1707
+ imputer.fit_transform(df), np.array([[1.0], [-2.0], [3.0]], dtype="float64")
1708
+ )
1709
+
1710
+ # Impute pandas array of float types with 'median' strategy.
1711
+ df = pd.DataFrame({"feature": pd.Series([1.0, None, 2.0, 3.0], dtype="float64")})
1712
+ imputer = SimpleImputer(missing_values=pd.NA, strategy="median")
1713
+ _assert_allclose_and_same_dtype(
1714
+ imputer.fit_transform(df),
1715
+ np.array([[1.0], [2.0], [2.0], [3.0]], dtype="float64"),
1716
+ )
1717
+
1718
+
1719
+ def test_missing_indicator_feature_names_out():
1720
+ """Check that missing indicator return the feature names with a prefix."""
1721
+ pd = pytest.importorskip("pandas")
1722
+
1723
+ missing_values = np.nan
1724
+ X = pd.DataFrame(
1725
+ [
1726
+ [missing_values, missing_values, 1, missing_values],
1727
+ [4, missing_values, 2, 10],
1728
+ ],
1729
+ columns=["a", "b", "c", "d"],
1730
+ )
1731
+
1732
+ indicator = MissingIndicator(missing_values=missing_values).fit(X)
1733
+ feature_names = indicator.get_feature_names_out()
1734
+ expected_names = ["missingindicator_a", "missingindicator_b", "missingindicator_d"]
1735
+ assert_array_equal(expected_names, feature_names)
1736
+
1737
+
1738
+ def test_imputer_lists_fit_transform():
1739
+ """Check transform uses object dtype when fitted on an object dtype.
1740
+
1741
+ Non-regression test for #19572.
1742
+ """
1743
+
1744
+ X = [["a", "b"], ["c", "b"], ["a", "a"]]
1745
+ imp_frequent = SimpleImputer(strategy="most_frequent").fit(X)
1746
+ X_trans = imp_frequent.transform([[np.nan, np.nan]])
1747
+ assert X_trans.dtype == object
1748
+ assert_array_equal(X_trans, [["a", "b"]])
1749
+
1750
+
1751
+ @pytest.mark.parametrize("dtype_test", [np.float32, np.float64])
1752
+ def test_imputer_transform_preserves_numeric_dtype(dtype_test):
1753
+ """Check transform preserves numeric dtype independent of fit dtype."""
1754
+ X = np.asarray(
1755
+ [[1.2, 3.4, np.nan], [np.nan, 1.2, 1.3], [4.2, 2, 1]], dtype=np.float64
1756
+ )
1757
+ imp = SimpleImputer().fit(X)
1758
+
1759
+ X_test = np.asarray([[np.nan, np.nan, np.nan]], dtype=dtype_test)
1760
+ X_trans = imp.transform(X_test)
1761
+ assert X_trans.dtype == dtype_test
1762
+
1763
+
1764
+ @pytest.mark.parametrize("array_type", ["array", "sparse"])
1765
+ @pytest.mark.parametrize("keep_empty_features", [True, False])
1766
+ def test_simple_imputer_constant_keep_empty_features(array_type, keep_empty_features):
1767
+ """Check the behaviour of `keep_empty_features` with `strategy='constant'.
1768
+ For backward compatibility, a column full of missing values will always be
1769
+ fill and never dropped.
1770
+ """
1771
+ X = np.array([[np.nan, 2], [np.nan, 3], [np.nan, 6]])
1772
+ X = _convert_container(X, array_type)
1773
+ fill_value = 10
1774
+ imputer = SimpleImputer(
1775
+ strategy="constant",
1776
+ fill_value=fill_value,
1777
+ keep_empty_features=keep_empty_features,
1778
+ )
1779
+
1780
+ for method in ["fit_transform", "transform"]:
1781
+ # TODO(1.8): Remove the condition and still call getattr(imputer, method)(X)
1782
+ if method.startswith("fit") and not keep_empty_features:
1783
+ warn_msg = '`strategy="constant"`, empty features are not dropped. '
1784
+ with pytest.warns(FutureWarning, match=warn_msg):
1785
+ X_imputed = getattr(imputer, method)(X)
1786
+ else:
1787
+ X_imputed = getattr(imputer, method)(X)
1788
+ assert X_imputed.shape == X.shape
1789
+ constant_feature = (
1790
+ X_imputed[:, 0].toarray() if array_type == "sparse" else X_imputed[:, 0]
1791
+ )
1792
+ assert_array_equal(constant_feature, fill_value)
1793
+
1794
+
1795
+ @pytest.mark.parametrize("array_type", ["array", "sparse"])
1796
+ @pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent"])
1797
+ @pytest.mark.parametrize("keep_empty_features", [True, False])
1798
+ def test_simple_imputer_keep_empty_features(strategy, array_type, keep_empty_features):
1799
+ """Check the behaviour of `keep_empty_features` with all strategies but
1800
+ 'constant'.
1801
+ """
1802
+ X = np.array([[np.nan, 2], [np.nan, 3], [np.nan, 6]])
1803
+ X = _convert_container(X, array_type)
1804
+ imputer = SimpleImputer(strategy=strategy, keep_empty_features=keep_empty_features)
1805
+
1806
+ for method in ["fit_transform", "transform"]:
1807
+ X_imputed = getattr(imputer, method)(X)
1808
+ if keep_empty_features:
1809
+ assert X_imputed.shape == X.shape
1810
+ constant_feature = (
1811
+ X_imputed[:, 0].toarray() if array_type == "sparse" else X_imputed[:, 0]
1812
+ )
1813
+ assert_array_equal(constant_feature, 0)
1814
+ else:
1815
+ assert X_imputed.shape == (X.shape[0], X.shape[1] - 1)
1816
+
1817
+
1818
+ @pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
1819
+ def test_imputation_custom(csc_container):
1820
+ X = np.array(
1821
+ [
1822
+ [1.1, 1.1, 1.1],
1823
+ [3.9, 1.2, np.nan],
1824
+ [np.nan, 1.3, np.nan],
1825
+ [0.1, 1.4, 1.4],
1826
+ [4.9, 1.5, 1.5],
1827
+ [np.nan, 1.6, 1.6],
1828
+ ]
1829
+ )
1830
+
1831
+ X_true = np.array(
1832
+ [
1833
+ [1.1, 1.1, 1.1],
1834
+ [3.9, 1.2, 1.1],
1835
+ [0.1, 1.3, 1.1],
1836
+ [0.1, 1.4, 1.4],
1837
+ [4.9, 1.5, 1.5],
1838
+ [0.1, 1.6, 1.6],
1839
+ ]
1840
+ )
1841
+
1842
+ imputer = SimpleImputer(missing_values=np.nan, strategy=np.min)
1843
+ X_trans = imputer.fit_transform(X)
1844
+ assert_array_equal(X_trans, X_true)
1845
+
1846
+ # Sparse matrix
1847
+ imputer = SimpleImputer(missing_values=np.nan, strategy=np.min)
1848
+ X_trans = imputer.fit_transform(csc_container(X))
1849
+ assert_array_equal(X_trans.toarray(), X_true)
1850
+
1851
+
1852
+ def test_simple_imputer_constant_fill_value_casting():
1853
+ """Check that we raise a proper error message when we cannot cast the fill value
1854
+ to the input data type. Otherwise, check that the casting is done properly.
1855
+
1856
+ Non-regression test for:
1857
+ https://github.com/scikit-learn/scikit-learn/issues/28309
1858
+ """
1859
+ # cannot cast fill_value at fit
1860
+ fill_value = 1.5
1861
+ X_int64 = np.array([[1, 2, 3], [2, 3, 4]], dtype=np.int64)
1862
+ imputer = SimpleImputer(
1863
+ strategy="constant", fill_value=fill_value, missing_values=2
1864
+ )
1865
+ err_msg = f"fill_value={fill_value!r} (of type {type(fill_value)!r}) cannot be cast"
1866
+ with pytest.raises(ValueError, match=re.escape(err_msg)):
1867
+ imputer.fit(X_int64)
1868
+
1869
+ # cannot cast fill_value at transform
1870
+ X_float64 = np.array([[1, 2, 3], [2, 3, 4]], dtype=np.float64)
1871
+ imputer.fit(X_float64)
1872
+ err_msg = (
1873
+ f"The dtype of the filling value (i.e. {imputer.statistics_.dtype!r}) "
1874
+ "cannot be cast"
1875
+ )
1876
+ with pytest.raises(ValueError, match=re.escape(err_msg)):
1877
+ imputer.transform(X_int64)
1878
+
1879
+ # check that no error is raised when having the same kind of dtype
1880
+ fill_value_list = [np.float64(1.5), 1.5, 1]
1881
+ X_float32 = X_float64.astype(np.float32)
1882
+
1883
+ for fill_value in fill_value_list:
1884
+ imputer = SimpleImputer(
1885
+ strategy="constant", fill_value=fill_value, missing_values=2
1886
+ )
1887
+ X_trans = imputer.fit_transform(X_float32)
1888
+ assert X_trans.dtype == X_float32.dtype
1889
+
1890
+
1891
+ @pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent", "constant"])
1892
+ def test_iterative_imputer_no_empty_features(strategy):
1893
+ """Check the behaviour of `keep_empty_features` with no empty features.
1894
+
1895
+ With no-empty features, we should get the same imputation whatever the
1896
+ parameter `keep_empty_features`.
1897
+
1898
+ Non-regression test for:
1899
+ https://github.com/scikit-learn/scikit-learn/issues/29375
1900
+ """
1901
+ X = np.array([[np.nan, 0, 1], [2, np.nan, 3], [4, 5, np.nan]])
1902
+
1903
+ imputer_drop_empty_features = IterativeImputer(
1904
+ initial_strategy=strategy, fill_value=1, keep_empty_features=False
1905
+ )
1906
+
1907
+ imputer_keep_empty_features = IterativeImputer(
1908
+ initial_strategy=strategy, fill_value=1, keep_empty_features=True
1909
+ )
1910
+
1911
+ assert_allclose(
1912
+ imputer_drop_empty_features.fit_transform(X),
1913
+ imputer_keep_empty_features.fit_transform(X),
1914
+ )
1915
+
1916
+
1917
+ @pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent", "constant"])
1918
+ @pytest.mark.parametrize(
1919
+ "X_test",
1920
+ [
1921
+ np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), # without empty feature
1922
+ np.array([[np.nan, 2, 3, 4], [np.nan, 6, 7, 8]]), # empty feature at column 0
1923
+ np.array([[1, 2, 3, np.nan], [5, 6, 7, np.nan]]), # empty feature at column 3
1924
+ ],
1925
+ )
1926
+ def test_iterative_imputer_with_empty_features(strategy, X_test):
1927
+ """Check the behaviour of `keep_empty_features` in the presence of empty features.
1928
+
1929
+ With `keep_empty_features=True`, the empty feature will be imputed with the value
1930
+ defined by the initial imputation.
1931
+
1932
+ Non-regression test for:
1933
+ https://github.com/scikit-learn/scikit-learn/issues/29375
1934
+ """
1935
+ X_train = np.array(
1936
+ [[np.nan, np.nan, 0, 1], [np.nan, 2, np.nan, 3], [np.nan, 4, 5, np.nan]]
1937
+ )
1938
+
1939
+ imputer_drop_empty_features = IterativeImputer(
1940
+ initial_strategy=strategy, fill_value=0, keep_empty_features=False
1941
+ )
1942
+ X_train_drop_empty_features = imputer_drop_empty_features.fit_transform(X_train)
1943
+ X_test_drop_empty_features = imputer_drop_empty_features.transform(X_test)
1944
+
1945
+ imputer_keep_empty_features = IterativeImputer(
1946
+ initial_strategy=strategy, fill_value=0, keep_empty_features=True
1947
+ )
1948
+ X_train_keep_empty_features = imputer_keep_empty_features.fit_transform(X_train)
1949
+ X_test_keep_empty_features = imputer_keep_empty_features.transform(X_test)
1950
+
1951
+ assert_allclose(X_train_drop_empty_features, X_train_keep_empty_features[:, 1:])
1952
+ assert_allclose(X_train_keep_empty_features[:, 0], 0)
1953
+
1954
+ assert X_train_drop_empty_features.shape[1] == X_test_drop_empty_features.shape[1]
1955
+ assert X_train_keep_empty_features.shape[1] == X_test_keep_empty_features.shape[1]
shared/package-files/02/025ded03bcca34b5f15007866b57b59ddb28690b529bca2e3d84fbff389f7a32/mock.pyi ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import Any, Callable, Generic, List, Mapping, Optional, Sequence, Text, Tuple, Type, TypeVar, Union, overload
3
+
4
+ _F = TypeVar("_F", bound=Callable[..., Any])
5
+ _T = TypeVar("_T")
6
+ _TT = TypeVar("_TT", bound=Type[Any])
7
+ _R = TypeVar("_R")
8
+
9
+ __all__ = [
10
+ "Mock",
11
+ "MagicMock",
12
+ "patch",
13
+ "sentinel",
14
+ "DEFAULT",
15
+ "ANY",
16
+ "call",
17
+ "create_autospec",
18
+ "AsyncMock",
19
+ "FILTER_DIR",
20
+ "NonCallableMock",
21
+ "NonCallableMagicMock",
22
+ "mock_open",
23
+ "PropertyMock",
24
+ "seal",
25
+ ]
26
+ __version__: str
27
+
28
+ FILTER_DIR: Any
29
+
30
+ class _slotted: ...
31
+
32
+ class _SentinelObject:
33
+ name: Any
34
+ def __init__(self, name: Any) -> None: ...
35
+
36
+ class _Sentinel:
37
+ def __init__(self) -> None: ...
38
+ def __getattr__(self, name: str) -> Any: ...
39
+
40
+ sentinel: Any
41
+ DEFAULT: Any
42
+
43
+ class _Call(Tuple[Any, ...]):
44
+ def __new__(
45
+ cls, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ...
46
+ ) -> Any: ...
47
+ name: Any
48
+ parent: Any
49
+ from_kall: Any
50
+ def __init__(
51
+ self, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ...
52
+ ) -> None: ...
53
+ def __eq__(self, other: Any) -> bool: ...
54
+ __ne__: Any
55
+ def __call__(self, *args: Any, **kwargs: Any) -> _Call: ...
56
+ def __getattr__(self, attr: Any) -> Any: ...
57
+ def count(self, *args: Any, **kwargs: Any) -> Any: ...
58
+ def index(self, *args: Any, **kwargs: Any) -> Any: ...
59
+ def call_list(self) -> Any: ...
60
+
61
+ call: _Call
62
+
63
+ class _CallList(List[_Call]):
64
+ def __contains__(self, value: Any) -> bool: ...
65
+
66
+ class _MockIter:
67
+ obj: Any
68
+ def __init__(self, obj: Any) -> None: ...
69
+ def __iter__(self) -> Any: ...
70
+ def __next__(self) -> Any: ...
71
+
72
+ class Base:
73
+ def __init__(self, *args: Any, **kwargs: Any) -> None: ...
74
+
75
+ class NonCallableMock(Base, Any): # type: ignore
76
+ def __new__(__cls, *args: Any, **kw: Any) -> NonCallableMock: ...
77
+ def __init__(
78
+ self,
79
+ spec: Union[List[str], object, Type[object], None] = ...,
80
+ wraps: Optional[Any] = ...,
81
+ name: Optional[str] = ...,
82
+ spec_set: Union[List[str], object, Type[object], None] = ...,
83
+ parent: Optional[NonCallableMock] = ...,
84
+ _spec_state: Optional[Any] = ...,
85
+ _new_name: str = ...,
86
+ _new_parent: Optional[NonCallableMock] = ...,
87
+ _spec_as_instance: bool = ...,
88
+ _eat_self: Optional[bool] = ...,
89
+ unsafe: bool = ...,
90
+ **kwargs: Any,
91
+ ) -> None: ...
92
+ def __getattr__(self, name: str) -> Any: ...
93
+ if sys.version_info >= (3, 8):
94
+ def _calls_repr(self, prefix: str = ...) -> str: ...
95
+ def assert_called_with(self, *args: Any, **kwargs: Any) -> None: ...
96
+ def assert_not_called(self) -> None: ...
97
+ def assert_called_once_with(self, *args: Any, **kwargs: Any) -> None: ...
98
+ def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = ...) -> str: ...
99
+ elif sys.version_info >= (3, 5):
100
+ def assert_called_with(_mock_self, *args: Any, **kwargs: Any) -> None: ...
101
+ def assert_not_called(_mock_self) -> None: ...
102
+ def assert_called_once_with(_mock_self, *args: Any, **kwargs: Any) -> None: ...
103
+ def _format_mock_failure_message(self, args: Any, kwargs: Any) -> str: ...
104
+ if sys.version_info >= (3, 8):
105
+ def assert_called(self) -> None: ...
106
+ def assert_called_once(self) -> None: ...
107
+ elif sys.version_info >= (3, 6):
108
+ def assert_called(_mock_self) -> None: ...
109
+ def assert_called_once(_mock_self) -> None: ...
110
+ if sys.version_info >= (3, 6):
111
+ def reset_mock(self, visited: Any = ..., *, return_value: bool = ..., side_effect: bool = ...) -> None: ...
112
+ elif sys.version_info >= (3, 5):
113
+ def reset_mock(self, visited: Any = ...) -> None: ...
114
+ if sys.version_info >= (3, 7):
115
+ def _extract_mock_name(self) -> str: ...
116
+ def _get_call_signature_from_name(self, name: str) -> Any: ...
117
+ def assert_any_call(self, *args: Any, **kwargs: Any) -> None: ...
118
+ def assert_has_calls(self, calls: Sequence[_Call], any_order: bool = ...) -> None: ...
119
+ def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ...
120
+ def _mock_add_spec(self, spec: Any, spec_set: bool, _spec_as_instance: bool = ..., _eat_self: bool = ...) -> None: ...
121
+ def attach_mock(self, mock: NonCallableMock, attribute: str) -> None: ...
122
+ def configure_mock(self, **kwargs: Any) -> None: ...
123
+ return_value: Any
124
+ side_effect: Any
125
+ called: bool
126
+ call_count: int
127
+ call_args: Any
128
+ call_args_list: _CallList
129
+ mock_calls: _CallList
130
+ def _format_mock_call_signature(self, args: Any, kwargs: Any) -> str: ...
131
+ def _call_matcher(self, _call: Tuple[_Call, ...]) -> _Call: ...
132
+ def _get_child_mock(self, **kw: Any) -> NonCallableMock: ...
133
+
134
+ class CallableMixin(Base):
135
+ side_effect: Any
136
+ def __init__(
137
+ self,
138
+ spec: Optional[Any] = ...,
139
+ side_effect: Optional[Any] = ...,
140
+ return_value: Any = ...,
141
+ wraps: Optional[Any] = ...,
142
+ name: Optional[Any] = ...,
143
+ spec_set: Optional[Any] = ...,
144
+ parent: Optional[Any] = ...,
145
+ _spec_state: Optional[Any] = ...,
146
+ _new_name: Any = ...,
147
+ _new_parent: Optional[Any] = ...,
148
+ **kwargs: Any,
149
+ ) -> None: ...
150
+ def __call__(_mock_self, *args: Any, **kwargs: Any) -> Any: ...
151
+
152
+ class Mock(CallableMixin, NonCallableMock): ...
153
+
154
+ class _patch(Generic[_T]):
155
+ attribute_name: Any
156
+ getter: Callable[[], Any]
157
+ attribute: str
158
+ new: _T
159
+ new_callable: Any
160
+ spec: Any
161
+ create: bool
162
+ has_local: Any
163
+ spec_set: Any
164
+ autospec: Any
165
+ kwargs: Mapping[str, Any]
166
+ additional_patchers: Any
167
+ if sys.version_info >= (3, 8):
168
+ @overload
169
+ def __init__(
170
+ self: _patch[Union[MagicMock, AsyncMock]],
171
+ getter: Callable[[], Any],
172
+ attribute: str,
173
+ *,
174
+ spec: Optional[Any],
175
+ create: bool,
176
+ spec_set: Optional[Any],
177
+ autospec: Optional[Any],
178
+ new_callable: Optional[Any],
179
+ kwargs: Mapping[str, Any],
180
+ ) -> None: ...
181
+ # This overload also covers the case, where new==DEFAULT. In this case, self is _patch[Any].
182
+ # Ideally we'd be able to add an overload for it so that self is _patch[MagicMock],
183
+ # but that's impossible with the current type system.
184
+ @overload
185
+ def __init__(
186
+ self: _patch[_T],
187
+ getter: Callable[[], Any],
188
+ attribute: str,
189
+ new: _T,
190
+ spec: Optional[Any],
191
+ create: bool,
192
+ spec_set: Optional[Any],
193
+ autospec: Optional[Any],
194
+ new_callable: Optional[Any],
195
+ kwargs: Mapping[str, Any],
196
+ ) -> None: ...
197
+ else:
198
+ @overload
199
+ def __init__(
200
+ self: _patch[MagicMock],
201
+ getter: Callable[[], Any],
202
+ attribute: str,
203
+ *,
204
+ spec: Optional[Any],
205
+ create: bool,
206
+ spec_set: Optional[Any],
207
+ autospec: Optional[Any],
208
+ new_callable: Optional[Any],
209
+ kwargs: Mapping[str, Any],
210
+ ) -> None: ...
211
+ @overload
212
+ def __init__(
213
+ self: _patch[_T],
214
+ getter: Callable[[], Any],
215
+ attribute: str,
216
+ new: _T,
217
+ spec: Optional[Any],
218
+ create: bool,
219
+ spec_set: Optional[Any],
220
+ autospec: Optional[Any],
221
+ new_callable: Optional[Any],
222
+ kwargs: Mapping[str, Any],
223
+ ) -> None: ...
224
+ def copy(self) -> _patch[_T]: ...
225
+ def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ...
226
+ def decorate_class(self, klass: _TT) -> _TT: ...
227
+ def decorate_callable(self, func: _F) -> _F: ...
228
+ def get_original(self) -> Tuple[Any, bool]: ...
229
+ target: Any
230
+ temp_original: Any
231
+ is_local: bool
232
+ def __enter__(self) -> _T: ...
233
+ def __exit__(self, *exc_info: Any) -> None: ...
234
+ def start(self) -> _T: ...
235
+ def stop(self) -> None: ...
236
+
237
+ class _patch_dict:
238
+ in_dict: Any
239
+ values: Any
240
+ clear: Any
241
+ def __init__(self, in_dict: Any, values: Any = ..., clear: Any = ..., **kwargs: Any) -> None: ...
242
+ def __call__(self, f: Any) -> Any: ...
243
+ def decorate_class(self, klass: Any) -> Any: ...
244
+ def __enter__(self) -> Any: ...
245
+ def __exit__(self, *args: Any) -> Any: ...
246
+ start: Any
247
+ stop: Any
248
+
249
+ class _patcher:
250
+ TEST_PREFIX: str
251
+ dict: Type[_patch_dict]
252
+ if sys.version_info >= (3, 8):
253
+ @overload
254
+ def __call__( # type: ignore
255
+ self,
256
+ target: Any,
257
+ *,
258
+ spec: Optional[Any] = ...,
259
+ create: bool = ...,
260
+ spec_set: Optional[Any] = ...,
261
+ autospec: Optional[Any] = ...,
262
+ new_callable: Optional[Any] = ...,
263
+ **kwargs: Any,
264
+ ) -> _patch[Union[MagicMock, AsyncMock]]: ...
265
+ # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any].
266
+ # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock],
267
+ # but that's impossible with the current type system.
268
+ @overload
269
+ def __call__(
270
+ self,
271
+ target: Any,
272
+ new: _T,
273
+ spec: Optional[Any] = ...,
274
+ create: bool = ...,
275
+ spec_set: Optional[Any] = ...,
276
+ autospec: Optional[Any] = ...,
277
+ new_callable: Optional[Any] = ...,
278
+ **kwargs: Any,
279
+ ) -> _patch[_T]: ...
280
+ else:
281
+ @overload
282
+ def __call__( # type: ignore
283
+ self,
284
+ target: Any,
285
+ *,
286
+ spec: Optional[Any] = ...,
287
+ create: bool = ...,
288
+ spec_set: Optional[Any] = ...,
289
+ autospec: Optional[Any] = ...,
290
+ new_callable: Optional[Any] = ...,
291
+ **kwargs: Any,
292
+ ) -> _patch[MagicMock]: ...
293
+ @overload
294
+ def __call__(
295
+ self,
296
+ target: Any,
297
+ new: _T,
298
+ spec: Optional[Any] = ...,
299
+ create: bool = ...,
300
+ spec_set: Optional[Any] = ...,
301
+ autospec: Optional[Any] = ...,
302
+ new_callable: Optional[Any] = ...,
303
+ **kwargs: Any,
304
+ ) -> _patch[_T]: ...
305
+ if sys.version_info >= (3, 8):
306
+ @overload
307
+ def object( # type: ignore
308
+ self,
309
+ target: Any,
310
+ attribute: Text,
311
+ *,
312
+ spec: Optional[Any] = ...,
313
+ create: bool = ...,
314
+ spec_set: Optional[Any] = ...,
315
+ autospec: Optional[Any] = ...,
316
+ new_callable: Optional[Any] = ...,
317
+ **kwargs: Any,
318
+ ) -> _patch[Union[MagicMock, AsyncMock]]: ...
319
+ @overload
320
+ def object(
321
+ self,
322
+ target: Any,
323
+ attribute: Text,
324
+ new: _T = ...,
325
+ spec: Optional[Any] = ...,
326
+ create: bool = ...,
327
+ spec_set: Optional[Any] = ...,
328
+ autospec: Optional[Any] = ...,
329
+ new_callable: Optional[Any] = ...,
330
+ **kwargs: Any,
331
+ ) -> _patch[_T]: ...
332
+ else:
333
+ @overload
334
+ def object( # type: ignore
335
+ self,
336
+ target: Any,
337
+ attribute: Text,
338
+ *,
339
+ spec: Optional[Any] = ...,
340
+ create: bool = ...,
341
+ spec_set: Optional[Any] = ...,
342
+ autospec: Optional[Any] = ...,
343
+ new_callable: Optional[Any] = ...,
344
+ **kwargs: Any,
345
+ ) -> _patch[MagicMock]: ...
346
+ @overload
347
+ def object(
348
+ self,
349
+ target: Any,
350
+ attribute: Text,
351
+ new: _T = ...,
352
+ spec: Optional[Any] = ...,
353
+ create: bool = ...,
354
+ spec_set: Optional[Any] = ...,
355
+ autospec: Optional[Any] = ...,
356
+ new_callable: Optional[Any] = ...,
357
+ **kwargs: Any,
358
+ ) -> _patch[_T]: ...
359
+ def multiple(
360
+ self,
361
+ target: Any,
362
+ spec: Optional[Any] = ...,
363
+ create: bool = ...,
364
+ spec_set: Optional[Any] = ...,
365
+ autospec: Optional[Any] = ...,
366
+ new_callable: Optional[Any] = ...,
367
+ **kwargs: _T,
368
+ ) -> _patch[_T]: ...
369
+ def stopall(self) -> None: ...
370
+
371
+ patch: _patcher
372
+
373
+ class MagicMixin:
374
+ def __init__(self, *args: Any, **kw: Any) -> None: ...
375
+
376
+ class NonCallableMagicMock(MagicMixin, NonCallableMock):
377
+ def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ...
378
+
379
+ class MagicMock(MagicMixin, Mock):
380
+ def mock_add_spec(self, spec: Any, spec_set: bool = ...) -> None: ...
381
+
382
+ if sys.version_info >= (3, 8):
383
+ class AsyncMockMixin(Base):
384
+ def __init__(self, *args: Any, **kwargs: Any) -> None: ...
385
+ async def _execute_mock_call(self, *args: Any, **kwargs: Any) -> Any: ...
386
+ def assert_awaited(self) -> None: ...
387
+ def assert_awaited_once(self) -> None: ...
388
+ def assert_awaited_with(self, *args: Any, **kwargs: Any) -> None: ...
389
+ def assert_awaited_once_with(self, *args: Any, **kwargs: Any) -> None: ...
390
+ def assert_any_await(self, *args: Any, **kwargs: Any) -> None: ...
391
+ def assert_has_awaits(self, calls: _CallList, any_order: bool = ...) -> None: ...
392
+ def assert_not_awaited(self) -> None: ...
393
+ def reset_mock(self, *args, **kwargs) -> None: ...
394
+ await_count: int
395
+ await_args: Optional[_Call]
396
+ await_args_list: _CallList
397
+ class AsyncMagicMixin(MagicMixin):
398
+ def __init__(self, *args: Any, **kw: Any) -> None: ...
399
+ class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): ...
400
+
401
+ class MagicProxy:
402
+ name: Any
403
+ parent: Any
404
+ def __init__(self, name: Any, parent: Any) -> None: ...
405
+ def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
406
+ def create_mock(self) -> Any: ...
407
+ def __get__(self, obj: Any, _type: Optional[Any] = ...) -> Any: ...
408
+
409
+ class _ANY:
410
+ def __eq__(self, other: Any) -> bool: ...
411
+ def __ne__(self, other: Any) -> bool: ...
412
+
413
+ ANY: Any
414
+
415
+ def create_autospec(
416
+ spec: Any, spec_set: Any = ..., instance: Any = ..., _parent: Optional[Any] = ..., _name: Optional[Any] = ..., **kwargs: Any
417
+ ) -> Any: ...
418
+
419
+ class _SpecState:
420
+ spec: Any
421
+ ids: Any
422
+ spec_set: Any
423
+ parent: Any
424
+ instance: Any
425
+ name: Any
426
+ def __init__(
427
+ self,
428
+ spec: Any,
429
+ spec_set: Any = ...,
430
+ parent: Optional[Any] = ...,
431
+ name: Optional[Any] = ...,
432
+ ids: Optional[Any] = ...,
433
+ instance: Any = ...,
434
+ ) -> None: ...
435
+
436
+ def mock_open(mock: Optional[Any] = ..., read_data: Any = ...) -> Any: ...
437
+
438
+ PropertyMock = Any
439
+
440
+ if sys.version_info >= (3, 7):
441
+ def seal(mock: Any) -> None: ...
shared/package-files/02/025ff8ea6f9aed99288b5e08134d130901b618c4f99511b3a362a36dcdc9e24a/RECORD ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ dataclasses-stubs/METADATA.toml,sha256=JjTFy_QNEkWvIlz9vpt31Xc3KZzezZGnvaZONQr7aCg,41
2
+ dataclasses-stubs/__init__.pyi,sha256=NuLHZD_EMBmcw4fwKbl3Y91kgyCnYYTMNf5Z2ktGcm0,2673
3
+ types_dataclasses-0.6.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
4
+ types_dataclasses-0.6.6.dist-info/METADATA,sha256=0N7UcFhQ9fS3oOnLGnNxDlsHjgDm31QwXZjIPDBluwU,1290
5
+ types_dataclasses-0.6.6.dist-info/RECORD,,
6
+ types_dataclasses-0.6.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ types_dataclasses-0.6.6.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
8
+ types_dataclasses-0.6.6.dist-info/top_level.txt,sha256=bvzFv5M-GN5qFBod3DjQDX3DvorwTP9CCs6Dq-3j3Vg,18
shared/package-files/02/0260a8adba1cab755fa9526753ac2d5721844a096cd5af9678f3f9065dd58b71/autocomplete.pyi ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from django.contrib.admin.options import ModelAdmin
4
+ from django.core.handlers.wsgi import WSGIRequest
5
+ from django.views.generic.list import BaseListView
6
+
7
+ class AutocompleteJsonView(BaseListView):
8
+ model_admin: ModelAdmin = ...
9
+ term: Any = ...
10
+ def has_perm(self, request: WSGIRequest, obj: None = ...) -> bool: ...
shared/package-files/02/026149be336a491d5dedde9fd3d1620efc18c07141ed8ccece4b80ee7d5ba43a/_triton_ops.py ADDED
@@ -0,0 +1,1928 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import torch
4
+ import weakref
5
+ from functools import lru_cache
6
+ from torch.utils._triton import has_triton
7
+ from ._triton_ops_meta import get_meta
8
+ from typing import Optional, Tuple
9
+
10
+ TORCH_SPARSE_BSR_SCATTER_MM_LRU_CACHE_SIZE = int(os.getenv('TORCH_SPARSE_BSR_SCATTER_MM_LRU_CACHE_SIZE', 2))
11
+
12
+
13
+ def check(cond, msg):
14
+ if not cond:
15
+ raise ValueError(msg)
16
+
17
+
18
+ def check_bsr_layout(f_name, t):
19
+ check(
20
+ t.layout == torch.sparse_bsr,
21
+ f"{f_name}(): only BSR sparse format is supported for the sparse argument.",
22
+ )
23
+
24
+
25
+ def check_device(f_name, t, device):
26
+ check(
27
+ t.device == device and t.device.type == "cuda",
28
+ f"{f_name}(): all inputs are expected to be on the same GPU device.",
29
+ )
30
+
31
+
32
+ def check_mm_compatible_shapes(f_name, lhs, rhs):
33
+ check(
34
+ lhs.dim() >= 2 and rhs.dim() >= 2,
35
+ f"{f_name}(): all inputs involved in the matrix product are expected to be at least 2D, "
36
+ f"but got lhs.dim() == {lhs.dim()} and rhs.dim() == {rhs.dim()}."
37
+ )
38
+
39
+ m, kl = lhs.shape[-2:]
40
+ kr, n = rhs.shape[-2:]
41
+
42
+ check(
43
+ kl == kr,
44
+ f"{f_name}(): arguments' sizes involved in the matrix product are not compatible for matrix multiplication, "
45
+ f"got lhs.shape[-1] == {kl} which is not equal to rhs.shape[-2] == {kr}.",
46
+ )
47
+
48
+
49
+ def check_dtype(f_name, t, dtype, *additional_dtypes):
50
+ check(
51
+ t.dtype == dtype
52
+ and t.dtype in ((torch.half, torch.bfloat16, torch.float) + tuple(*additional_dtypes)),
53
+ f"{f_name}(): all inputs are expected to be of the same dtype "
54
+ f"and one of (half, bfloat16, float32) or {additional_dtypes}, "
55
+ f"but got dtype == {t.dtype}.",
56
+ )
57
+
58
+
59
+ def check_blocksize(f_name, blocksize):
60
+ assert len(blocksize) == 2
61
+
62
+ def is_power_of_two(v):
63
+ return not (v & (v - 1))
64
+
65
+ def is_compatible_blocksize(b):
66
+ res = True
67
+ for blocksize in b:
68
+ # Triton loads only blocks which are at least 16 and powers of 2.
69
+ res = (blocksize >= 16 and is_power_of_two(blocksize)) and res
70
+ return res
71
+
72
+ check(
73
+ is_compatible_blocksize(blocksize),
74
+ f"{f_name}(): sparse inputs' blocksize ({blocksize[0]}, {blocksize[1]}) "
75
+ "should be at least 16 and a power of 2 in each dimension.",
76
+ )
77
+
78
+
79
+ def make_triton_contiguous(t):
80
+ """Return input as a triton-contiguous tensor.
81
+
82
+ A triton-contiguous tensor is defined as a tensor that has strides
83
+ with minimal value equal to 1.
84
+
85
+ While triton kernels support triton-non-contiguous tensors (all
86
+ strides being greater than 1 or having 0 strides) arguments, a
87
+ considerable slow-down occurs because tensor data is copied
88
+ element-wise rather than chunk-wise.
89
+ """
90
+ if min(t.stride()) != 1:
91
+ # TODO: investigate if contiguity along other axes than the
92
+ # last one can be beneficial for performance
93
+ return t.contiguous()
94
+ else:
95
+ return t
96
+
97
+
98
+ def broadcast_batch_dims(f_name, *tensors):
99
+ try:
100
+ return torch.broadcast_shapes(*(t.shape[:-2] for t in tensors))
101
+ except Exception:
102
+ check(False, f"{f_name}(): inputs' batch dimensions are not broadcastable!")
103
+
104
+
105
+ def slicer(dim, slice_range, *tensors):
106
+ for t in tensors:
107
+ slices = [slice(None)] * t.dim()
108
+ slices[dim] = slice_range
109
+ yield t[slices]
110
+
111
+
112
+ def multidim_slicer(dims, slices, *tensors):
113
+ for t in tensors:
114
+ s = [slice(None)] * t.dim()
115
+ for d, d_slice in zip(dims, slices):
116
+ if d is not None:
117
+ s[d] = d_slice
118
+ yield t[s]
119
+
120
+
121
+ def ptr_stride_extractor(*tensors):
122
+ for t in tensors:
123
+ yield t
124
+ yield from t.stride()
125
+
126
+
127
+ def grid_partitioner(full_grid, grid_blocks, tensor_dims_map):
128
+ assert 0 <= len(full_grid) <= 3
129
+ assert 0 <= len(grid_blocks) <= 3
130
+
131
+ import itertools
132
+
133
+ def generate_grid_points():
134
+ for fg, mg in zip(full_grid, grid_blocks):
135
+ yield range(0, fg, mg)
136
+
137
+ def generate_sliced_tensors(slices):
138
+ for t, t_dims in tensor_dims_map.items():
139
+ yield next(multidim_slicer(t_dims, slices, t))
140
+
141
+ for grid_point in itertools.product(*generate_grid_points()):
142
+ grid = [min(fg - gp, mg) for fg, gp, mg in zip(full_grid, grid_point, grid_blocks)]
143
+ slices = [slice(gp, gp + g) for gp, g in zip(grid_point, grid)]
144
+ # grid_points are iterated in a "contiguous" order, i.e.
145
+ # left dimensions traversed slower than right dimensions.
146
+ # This order is reversed for CUDA grids.
147
+ yield grid[::-1], *generate_sliced_tensors(slices)
148
+
149
+
150
+ def launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks=None):
151
+ # cuda_max_grid = (2 ** 31 - 1, 2 ** 16 - 1, 2 ** 16 - 1)
152
+ cuda_max_grid = (2147483647, 65535, 65535)[::-1]
153
+ if grid_blocks is None:
154
+ grid_blocks = cuda_max_grid
155
+ else:
156
+
157
+ def valid_grid_dim(g, mg):
158
+ if g is None:
159
+ return mg
160
+ else:
161
+ # grid must be at least 1 and no greater than mg
162
+ return max(1, min(g, mg))
163
+
164
+ grid_blocks = tuple(
165
+ valid_grid_dim(g, mg) for g, mg in zip(grid_blocks, cuda_max_grid)
166
+ ) # type: ignore[assignment]
167
+
168
+ for grid, *sliced_tensors in grid_partitioner(full_grid, grid_blocks, tensor_dims_map):
169
+ kernel(grid, *sliced_tensors)
170
+
171
+
172
+ def prepare_inputs(bsr, *dense_tensors):
173
+ # Introduce fake batch dimension if not present for convenience.
174
+ crow_indices = bsr.crow_indices().unsqueeze(0)
175
+ col_indices = bsr.col_indices().unsqueeze(0)
176
+ values = make_triton_contiguous(bsr.values().unsqueeze(0))
177
+ tensors = [make_triton_contiguous(t.unsqueeze(0)) for t in dense_tensors]
178
+
179
+ # Compute broadcasted batch dimension
180
+ batch_dims_broadcasted = torch.broadcast_shapes(values.shape[:-3], *(t.shape[:-2] for t in tensors))
181
+
182
+ # Broadcast batch dimensions and squash.
183
+ # The result can be either a view or a copy.
184
+ def batch_broadcast_and_squash(t, batch_dims, invariant_dims):
185
+ return t.broadcast_to(batch_dims + invariant_dims).flatten(
186
+ 0, len(batch_dims) - 1
187
+ )
188
+
189
+ crow_indices = batch_broadcast_and_squash(
190
+ crow_indices, batch_dims_broadcasted, (-1,)
191
+ )
192
+
193
+ col_indices = batch_broadcast_and_squash(
194
+ col_indices, batch_dims_broadcasted, (-1,)
195
+ )
196
+ values = batch_broadcast_and_squash(
197
+ values, batch_dims_broadcasted, values.shape[-3:]
198
+ )
199
+ tensors = [
200
+ batch_broadcast_and_squash(t, batch_dims_broadcasted, t.shape[-2:]) for t in tensors
201
+ ]
202
+
203
+ return crow_indices, col_indices, values, *tensors
204
+
205
+
206
+ def broadcast_batch_dims_bsr(f_name, bsr, *tensors):
207
+ batch_shape = broadcast_batch_dims(f_name, bsr, *tensors)
208
+
209
+ crow_indices = bsr.crow_indices().broadcast_to(batch_shape + (-1,))
210
+ col_indices = bsr.col_indices().broadcast_to(batch_shape + (-1,))
211
+ values = bsr.values().broadcast_to(batch_shape + bsr.values().shape[-3:])
212
+ size = batch_shape + bsr.shape[-2:]
213
+ return torch.sparse_compressed_tensor(crow_indices, col_indices, values, size=size, layout=bsr.layout)
214
+
215
+
216
+ # NOTE: this function will ALWAYS create a view
217
+ def tile_to_blocksize(t, blocksize):
218
+ *rest, m, n = t.shape
219
+ new_shape = rest + [
220
+ m // blocksize[0],
221
+ blocksize[0],
222
+ n // blocksize[1],
223
+ blocksize[1],
224
+ ]
225
+ # using .view instead of .reshape to ensure that the result is
226
+ # indeed a view:
227
+ return t.view(new_shape).transpose(-3, -2)
228
+
229
+
230
+ def as1Dbatch(tensor):
231
+ """Return tensor as 3D tensor by either prepending new dimensions to
232
+ the tensor shape (when ``tensor.ndim < 3``), or by collapsing
233
+ starting dimensions into the first dimension (when ``tensor.ndim >
234
+ 3``).
235
+ """
236
+ while tensor.ndim < 3:
237
+ tensor = tensor.unsqueeze(0)
238
+ if tensor.ndim > 3:
239
+ tensor = tensor.flatten(0, tensor.ndim - 3)
240
+ assert tensor.ndim == 3, tensor.shape
241
+ return tensor
242
+
243
+
244
+ def scatter_mm(blocks, others, indices_data, *, accumulators=None):
245
+ """Scattered matrix multiplication of tensors.
246
+
247
+ A scattered matrix multiplication is defined as a series of matrix
248
+ multiplications applied to input tensors according to the input
249
+ and output mappings specified by indices data.
250
+
251
+ The following indices data formats are supported for defining a
252
+ scattered matrix multiplication operation (:attr:`indices_data[0]`
253
+ holds the name of the indices data format as specified below):
254
+
255
+ - ``"scatter_mm"`` - matrix multiplications scattered in batches
256
+ of tensors.
257
+
258
+ If :attr:`blocks` is a :math:`(* \times M \times K) tensor,
259
+ :attr:`others` is a :math:`(* \times K \times N)` tensor,
260
+ :attr:`accumulators` is a :math:`(* \times M \times N)` tensor,
261
+ and :attr:`indices = indices_data['indices']` is a :math:`(*
262
+ \times 3)` tensor, then the operation is equivalent to the
263
+ following code::
264
+
265
+ c_offsets, pq = indices_data[1:]
266
+ for r in range(len(c_offsets) - 1):
267
+ for g in range(c_offsets[r], c_offsets[r + 1]):
268
+ p, q = pq[g]
269
+ accumulators[r] += blocks[p] @ others[q]
270
+
271
+ - ``"bsr_strided_mm"`` - matrix multiplications scattered in
272
+ batches of tensors and a tensor.
273
+
274
+ If :attr:`blocks` is a :math:`(Ms \times Ks) tensor,
275
+ :attr:`others` is a :math:`(* \times K \times N)` tensor,
276
+ :attr:`accumulators` is a :math:`(* \times M \times N)` tensor, then
277
+ the operation is equivalent to the following code::
278
+
279
+ c_indices, r_offsets, p_offsets, q_offsets, meta = indices_data[1:]
280
+ for b in range(nbatches):
281
+ for i, r in enumerate(r_offsets):
282
+ r0, r1 = divmod(r, N)
283
+ acc = accumulators[b, r0:r0 + Ms, r1:r1 + Ns]
284
+ for g in range(c_indices[i], c_indices[i+1]):
285
+ p = p_offsets[g]
286
+ q0, q1 = divmod(q_offsets[g], N)
287
+ acc += blocks[p] @ others[b, q0:q0 + Ks, q1:q1 + Ns]
288
+
289
+ where ``Ns = N // meta['SPLIT_N']``, and ``M`` and ``K`` are
290
+ integer multiples of ``Ms`` and ``Ks``, respectively.
291
+
292
+ - ``"bsr_strided_mm_compressed"`` - matrix multiplications
293
+ scattered in batches of tensors and a tensor. A memory and
294
+ processor efficient version of ``"bsr_strided_mm"`` format. If
295
+ :attr:`blocks` is a :math:`(Ms \times Ks) tensor, :attr:`others`
296
+ is a :math:`(* \times K \times N)` tensor, :attr:`accumulators`
297
+ is a :math:`(* \times M \times N)` tensor, then the operation is
298
+ equivalent to the following code::
299
+
300
+ c_indices, r_offsets, q_offsets, meta = indices_data[1:]
301
+ for b in range(nbatches):
302
+ for r in r_offsets:
303
+ m = (r // N) // Ms
304
+ n = (r % N) // Ns
305
+ r0, r1 = divmod(r, N)
306
+ c0, c1 = c_indices[m], c_indices[m + 1]
307
+ acc = accumulators[b, r0:r0 + Ms, r1:r1 + Ns]
308
+ for i, p in enumerate(range(c0, c1)):
309
+ q = q_offsets[n * c1 + (SPLIT_N - n) * c0 + i]
310
+ q0, q1 = divmod(q, N)
311
+ acc += blocks[p] @ others[b, q0:q0 + Ks, q1:q1 + Ns]
312
+
313
+ where ``Ns = N // meta['SPLIT_N']``, and ``M`` and ``K`` are
314
+ integer multiples of ``Ms`` and ``Ks``, respectively.
315
+
316
+ Notice that the order of ``r_offsets`` items can be arbitrary;
317
+ this property enables defining swizzle operators via
318
+ rearrangements of ``r_offsets`` items..
319
+
320
+ Auxilary functions are provided for pre-computing
321
+ :attr:`indices_data`. For example,
322
+ :func:`bsr_scatter_mm_indices_data` is used to define indices data
323
+ for matrix multiplication of BSR and strided tensors.
324
+
325
+ Parameters
326
+ ----------
327
+ blocks (Tensor): a 3-D tensor of first matrices to be multiplied
328
+
329
+ others (Tensor): a tensor of second matrices to be multiplied. If
330
+ ``indices_data[0]=="scatter_mm"``, the tensor is a 1-D batch
331
+ tensor of second input matrices to be multiplied. Otherwise, the
332
+ second input matrices are slices of the :attr:`others` tensor.
333
+ indices_data (tuple): a format data that defines the inputs and
334
+ outputs of scattered matrix multiplications.
335
+
336
+ Keyword arguments
337
+ -----------------
338
+
339
+ accumulators (Tensor, optional): a tensor of matrix product
340
+ accumulators. If ``indices_data[0]=="scatter_mm"``, the tensor
341
+ is a 1-D batch tensor of output matrices. Otherwise, output
342
+ matrices are slices of the :attr:`accumulators` tensor.
343
+ """
344
+ indices_format = indices_data[0]
345
+
346
+ assert blocks.ndim == 3
347
+ P, Ms, Ks = blocks.shape
348
+
349
+ if indices_format == 'scatter_mm':
350
+ c_offsets, pq = indices_data[1:]
351
+
352
+ assert others.ndim == 3
353
+ Q, Ks_, Ns = others.shape
354
+ assert Ks == Ks_
355
+
356
+ if accumulators is None:
357
+ R = c_offsets.shape[0] - 1
358
+ accumulators = torch.zeros((R, Ms, Ns), dtype=blocks.dtype, device=blocks.device)
359
+ else:
360
+ R, Ms_, Ns_ = accumulators.shape
361
+ assert Ms_ == Ms
362
+ assert Ns_ == Ns
363
+
364
+ if Ms % 16 or Ks % 16 or Ns % 16 or _scatter_mm2 is None:
365
+ for r in range(c_offsets.shape[0] - 1):
366
+ g0 = c_offsets[r]
367
+ g1 = c_offsets[r + 1]
368
+ for g in range(g0, g1):
369
+ p, q = pq[g]
370
+ accumulators[r] += blocks[p] @ others[q]
371
+ else:
372
+ _scatter_mm2(blocks, others, c_offsets, pq, accumulators)
373
+ return accumulators
374
+
375
+ elif indices_format == 'bsr_strided_mm':
376
+ others_shape = others.shape
377
+ others = as1Dbatch(others)
378
+
379
+ B, K, N = others.shape
380
+ assert K % Ks == 0
381
+
382
+ c_indices, r_offsets, p_offsets, q_offsets, meta = indices_data[1:]
383
+ SPLIT_N = meta['SPLIT_N']
384
+
385
+ if accumulators is None:
386
+ M = Ms + (r_offsets.max().item() + 1) // N
387
+ accumulators = torch.zeros((*others_shape[:-2], M, N), dtype=blocks.dtype, device=blocks.device)
388
+ else:
389
+ M, N_ = accumulators.shape[-2:]
390
+ assert N_ == N
391
+
392
+ accumulators_shape = accumulators.shape
393
+ accumulators = as1Dbatch(accumulators)
394
+
395
+ Ns = N // SPLIT_N
396
+
397
+ if Ms % 16 or Ks % 16 or Ns % 16 or _scatter_mm6 is None:
398
+ accumulators.zero_()
399
+ for b in range(B):
400
+ for r in range(r_offsets.shape[0]):
401
+ r_ = r_offsets[r].item()
402
+ g0 = c_indices[r].item()
403
+ g1 = c_indices[r + 1].item()
404
+ r0, r1 = divmod(r_, N)
405
+ acc = accumulators[b, r0:r0 + Ms, r1:r1 + Ns]
406
+ for g in range(g0, g1):
407
+ p, q = p_offsets[g], q_offsets[g]
408
+ q0, q1 = divmod(q.item(), N)
409
+ acc += blocks[p] @ others[b, q0:q0 + Ks, q1:q1 + Ns]
410
+ else:
411
+ _scatter_mm6(blocks, others, c_indices, r_offsets, p_offsets, q_offsets, meta, accumulators)
412
+ return accumulators.view(accumulators_shape)
413
+
414
+ elif indices_format == 'bsr_strided_mm_compressed':
415
+ others_shape = others.shape
416
+ others = as1Dbatch(others)
417
+
418
+ B, K, N = others.shape
419
+ assert K % Ks == 0
420
+
421
+ c_indices, r_offsets, q_offsets, meta = indices_data[1:]
422
+ SPLIT_N = meta['SPLIT_N']
423
+
424
+ if accumulators is None:
425
+ M = Ms + (r_offsets.max().item() + 1) // N
426
+ accumulators = torch.zeros((*others_shape[:-2], M, N), dtype=blocks.dtype, device=blocks.device)
427
+ else:
428
+ M, N_ = accumulators.shape[-2:]
429
+ assert N_ == N
430
+
431
+ accumulators_shape = accumulators.shape
432
+ accumulators = as1Dbatch(accumulators)
433
+
434
+ Ns = N // SPLIT_N
435
+
436
+ if Ms % 16 or Ks % 16 or Ns % 16 or _scatter_mm6 is None:
437
+ for b in range(B):
438
+ for j in range(len(r_offsets)):
439
+ r0, r1 = divmod(r_offsets[j].item(), N)
440
+ m = r0 // Ms
441
+ n = r1 // Ns
442
+ c0 = c_indices[m].item()
443
+ c1 = c_indices[m + 1].item()
444
+ acc = accumulators[b, r0:r0 + Ms, r1:r1 + Ns]
445
+ for i, p in enumerate(range(c0, c1)):
446
+ q = q_offsets[n * c1 + (SPLIT_N - n) * c0 + i].item()
447
+ q0, q1 = divmod(q, N)
448
+ acc += blocks[p] @ others[b, q0:q0 + Ks, q1:q1 + Ns]
449
+ else:
450
+ p_offsets = torch.empty((0, ), dtype=q_offsets.dtype, device=q_offsets.device)
451
+ _scatter_mm6(blocks, others, c_indices, r_offsets, p_offsets, q_offsets, meta, accumulators)
452
+ return accumulators.view(accumulators_shape)
453
+
454
+ else:
455
+ raise NotImplementedError(indices_format)
456
+
457
+
458
+ def scatter_mm_meta(M, K, N, Ms, Ks,
459
+ GROUP_SIZE=None, TILE_M=None, TILE_N=None, SPLIT_N=None, num_warps=None, num_stages=None, **extra):
460
+ if {TILE_M, TILE_N, SPLIT_N, num_warps, num_stages, GROUP_SIZE} == {None}:
461
+ device_name = torch.cuda.get_device_name()
462
+ meta = get_meta('scatter_mm', (M, K, N, Ms, Ks), device_name,
463
+ version=(0, torch.float16, 0.5))
464
+ if meta is not None:
465
+ meta.update(**extra)
466
+ return meta
467
+ # The following parameters are optimized for the performance
468
+ # equilibrium points of bsr-dense and dense-dense matrix
469
+ # multiplications when using GPU card NVIDIA GeForce RTX 2060
470
+ # SUPER. For points far from the performance equilibrium
471
+ # points as well as for other GPU cards, the optimal
472
+ # parameters are likely different from what specified below.
473
+ if (M, K, N) == (256,) * 3:
474
+ if (Ms, Ks) == (16, 16):
475
+ SPLIT_N=1;TILE_M=16;TILE_N=16;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702
476
+ elif (Ms, Ks) == (32, 32):
477
+ SPLIT_N=2;TILE_M=32;TILE_N=16;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702
478
+ elif (Ms, Ks) == (64, 64):
479
+ SPLIT_N=1;TILE_M=32;TILE_N=32;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702
480
+ elif (Ms, Ks) == (128, 128):
481
+ SPLIT_N=1;TILE_M=32;TILE_N=32;GROUP_SIZE=2;num_stages=1;num_warps=4 # noqa: E225,E231,E702
482
+ elif (M, K, N) == (512,) * 3:
483
+ if (Ms, Ks) == (16, 16):
484
+ SPLIT_N=8;TILE_M=16;TILE_N=64;GROUP_SIZE=2;num_stages=1;num_warps=2 # noqa: E225,E231,E702
485
+ elif (Ms, Ks) == (32, 32):
486
+ SPLIT_N=8;TILE_M=32;TILE_N=64;GROUP_SIZE=4;num_stages=1;num_warps=2 # noqa: E225,E231,E702
487
+ elif (Ms, Ks) == (64, 64):
488
+ SPLIT_N=4;TILE_M=32;TILE_N=128;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702
489
+ elif (Ms, Ks) == (128, 128):
490
+ SPLIT_N=8;TILE_M=64;TILE_N=64;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702
491
+ elif (M, K, N) == (1024,) * 3:
492
+ if (Ms, Ks) == (16, 16):
493
+ SPLIT_N=4;TILE_M=16;TILE_N=128;GROUP_SIZE=2;num_stages=1;num_warps=1 # noqa: E225,E231,E702
494
+ elif (Ms, Ks) == (32, 32):
495
+ SPLIT_N=8;TILE_M=32;TILE_N=64;GROUP_SIZE=2;num_stages=1;num_warps=1 # noqa: E225,E231,E702
496
+ elif (Ms, Ks) == (64, 64):
497
+ SPLIT_N=16;TILE_M=64;TILE_N=64;GROUP_SIZE=4;num_stages=1;num_warps=2 # noqa: E225,E231,E702
498
+ elif (Ms, Ks) == (128, 128):
499
+ SPLIT_N=16;TILE_M=64;TILE_N=64;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702
500
+ elif (Ms, Ks) == (256, 256):
501
+ SPLIT_N=16;TILE_M=64;TILE_N=64;GROUP_SIZE=2;num_stages=1;num_warps=4 # noqa: E225,E231,E702
502
+ elif (M, K, N) == (2048,) * 3:
503
+ if (Ms, Ks) == (16, 16):
504
+ SPLIT_N=4;TILE_M=16;TILE_N=128;GROUP_SIZE=8;num_stages=1;num_warps=1 # noqa: E225,E231,E702
505
+ elif (Ms, Ks) == (32, 32):
506
+ SPLIT_N=4;TILE_M=32;TILE_N=64;GROUP_SIZE=4;num_stages=1;num_warps=1 # noqa: E225,E231,E702
507
+ elif (Ms, Ks) == (64, 64):
508
+ SPLIT_N=4;TILE_M=64;TILE_N=128;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702
509
+ elif (Ms, Ks) == (128, 128):
510
+ SPLIT_N=8;TILE_M=64;TILE_N=64;GROUP_SIZE=4;num_stages=1;num_warps=4 # noqa: E225,E231,E702
511
+ elif (Ms, Ks) == (256, 256):
512
+ SPLIT_N=4;TILE_M=64;TILE_N=64;GROUP_SIZE=2;num_stages=1;num_warps=4 # noqa: E225,E231,E702
513
+ elif (M, K, N) == (4096,) * 3:
514
+ if (Ms, Ks) == (16, 16):
515
+ SPLIT_N=2;TILE_M=16;TILE_N=256;GROUP_SIZE=2;num_stages=1;num_warps=2 # noqa: E225,E231,E702
516
+ elif (Ms, Ks) == (32, 32):
517
+ SPLIT_N=2;TILE_M=32;TILE_N=64;GROUP_SIZE=2;num_stages=1;num_warps=1 # noqa: E225,E231,E702
518
+ elif (Ms, Ks) == (64, 64):
519
+ SPLIT_N=2;TILE_M=64;TILE_N=128;GROUP_SIZE=2;num_stages=1;num_warps=4 # noqa: E225,E231,E702
520
+
521
+ if SPLIT_N is None:
522
+ # Assume NVIDIA GeForce RTX 2060 SUPER:
523
+ # With the probality of 92% (99.9% when N > 512), the
524
+ # performance will not be worse more than 2% from the
525
+ # performance when using an optimal value. Otherwise, when N
526
+ # <= 512, using the following heuristics may give upto 15%
527
+ # lower performance.
528
+ SPLIT_N = {16: 1, 32: 2, 64: 4, 128: 8, 256: 16, 512: 8, 1024: 16, 4096: 32, 8192: 64}.get(N, 16)
529
+ if Ms >= 512 and N >= 2048:
530
+ SPLIT_N = 1
531
+ Ns = N // SPLIT_N
532
+ if TILE_M is None:
533
+ TILE_M = min(64 if Ns < 512 else 32, Ms)
534
+ if TILE_N is None:
535
+ TILE_N = min(64 if Ns < 512 else 32, Ns)
536
+ num_stages = num_stages or 1
537
+ if num_warps is None:
538
+ if min(M, N) > 1024:
539
+ num_warps = {16: 1, 32: 1, 64: 2}.get(Ms, 4)
540
+ elif min(M, N) == 1024:
541
+ num_warps = {16: 1, 32: 1, 64: 2}.get(Ms, 4)
542
+ elif min(M, N) == 256:
543
+ num_warps = {16: 1, 32: 4}.get(Ms, 4)
544
+ else:
545
+ num_warps = {16: 1, 32: 2}.get(Ms, 4)
546
+ GROUP_SIZE = GROUP_SIZE or 4
547
+
548
+ assert TILE_M <= Ms, dict(TILE_M=TILE_M, Ms=Ms)
549
+ assert TILE_N <= Ns, dict(TILE_N=TILE_N, Ns=Ns)
550
+ assert Ms <= M, dict(M=M, Ms=Ms)
551
+ assert Ns <= N, dict(N=N, Ns=Ns)
552
+ assert Ks <= K, dict(K=K, Ks=Ks)
553
+
554
+ return dict(TILE_M=TILE_M, TILE_N=TILE_N, GROUP_SIZE=GROUP_SIZE,
555
+ num_stages=num_stages, num_warps=num_warps, SPLIT_N=SPLIT_N, **extra)
556
+
557
+
558
+ def bsr_dense_addmm_meta(M, K, N, Ms, Ks, beta, alpha,
559
+ SPLIT_N=None, GROUP_SIZE_ROW=None, num_warps=None, num_stages=None, sparsity=None, dtype=None, **extra):
560
+ if dtype is None:
561
+ dtype = torch.float16
562
+ if sparsity is None:
563
+ sparsity = 0.5
564
+ if {SPLIT_N, num_warps, num_stages, GROUP_SIZE_ROW} == {None}:
565
+ device_name = torch.cuda.get_device_name()
566
+ key = (M, K, N, Ms, Ks, beta == 0, beta == 1, alpha == 1)
567
+ meta = get_meta('bsr_dense_addmm', key,
568
+ device_name, version=(0, dtype, sparsity))
569
+ if meta is None and sparsity != 0.5:
570
+ meta = get_meta('bsr_dense_addmm', key,
571
+ device_name, version=(0, dtype, 0.5))
572
+ if meta is not None:
573
+ meta.update(**extra)
574
+ return meta
575
+ SPLIT_N = SPLIT_N or max(N // Ms, 1)
576
+ GROUP_SIZE_ROW = GROUP_SIZE_ROW or 4
577
+ num_stages = num_stages or 1
578
+ num_warps = num_warps or 4
579
+ return dict(SPLIT_N=SPLIT_N, GROUP_SIZE_ROW=GROUP_SIZE_ROW, num_stages=num_stages, num_warps=num_warps, **extra)
580
+
581
+
582
+ class TensorAsKey:
583
+ """A light-weight wrapper of a tensor that enables storing tensors as
584
+ keys with efficient memory reference based comparision as an
585
+ approximation to data equality based keys.
586
+
587
+ Motivation: the hash value of a torch tensor is tensor instance
588
+ based that does not use data equality and makes the usage of
589
+ tensors as keys less useful. For instance, the result of
590
+ ``len({a.crow_indices(), a.crow_indices()})`` is `2`, although,
591
+ the tensor results from `crow_indices` method call are equal, in
592
+ fact, these share the same data storage.
593
+ On the other hand, for efficient caching of tensors we want to
594
+ avoid calling torch.equal that compares tensors item-wise.
595
+
596
+ TensorAsKey offers a compromise in that it guarantees key equality
597
+ of tensors that references data in the same storage in the same
598
+ manner and without accessing underlying data. However, this
599
+ approach does not always guarantee correctness. For instance, for
600
+ a complex tensor ``x``, we have ``TensorAsKey(x) ==
601
+ TensorAsKey(x.conj())`` while ``torch.equal(x, x.conj())`` would
602
+ return False.
603
+ """
604
+
605
+ def __init__(self, obj):
606
+
607
+ def get_tensor_key(obj):
608
+ # Warning: TensorAsKey does not track negative nor
609
+ # conjugate bits of its input object because in the use
610
+ # case of wrapping compressed/plain indices of compressed
611
+ # sparse tensors (that are always integer tensors with
612
+ # non-negative items) these bits are never set. However,
613
+ # when extending the use of TensorAsKey to float or
614
+ # complex tensors, the values of these bits (see is_neg
615
+ # and is_conj methods) must be included in the key as
616
+ # well.
617
+ assert not (obj.dtype.is_floating_point or obj.dtype.is_complex), obj.dtype
618
+ return (obj.data_ptr(), obj.storage_offset(), obj.shape, obj.stride(), obj.dtype)
619
+
620
+ self._obj_ref = weakref.ref(obj)
621
+ if obj.layout is torch.strided:
622
+ self.key = get_tensor_key(obj)
623
+ elif obj.layout in {torch.sparse_csr, torch.sparse_bsr}:
624
+ self.key = (get_tensor_key(obj.crow_indices()), get_tensor_key(obj.col_indices()))
625
+ elif obj.layout in {torch.sparse_csc, torch.sparse_bsc}:
626
+ self.key = (get_tensor_key(obj.ccol_indices()), get_tensor_key(obj.row_indices()))
627
+ else:
628
+ raise NotImplementedError(obj.layout)
629
+ self._hash = hash(self.key)
630
+
631
+ def __hash__(self):
632
+ return self._hash
633
+
634
+ def __eq__(self, other):
635
+ if not isinstance(other, TensorAsKey):
636
+ return False
637
+ if self.obj is None or other.obj is None:
638
+ # dead objects always compare unequal unless these are
639
+ # same objects
640
+ return self is other
641
+ return self.key == other.key
642
+
643
+ @property
644
+ def obj(self):
645
+ """Return object if alive, otherwise None."""
646
+ return self._obj_ref()
647
+
648
+
649
+ @lru_cache(maxsize=TORCH_SPARSE_BSR_SCATTER_MM_LRU_CACHE_SIZE)
650
+ def _bsr_scatter_mm_indices_data(indices_format, M, K, N, Ms, Ks, nbatches, SPLIT_N, compressed_sparse_tensor_as_key):
651
+ bsr = compressed_sparse_tensor_as_key.obj
652
+ assert bsr is not None
653
+ crow_indices, col_indices = bsr.crow_indices(), bsr.col_indices()
654
+ device = crow_indices.device
655
+ indices_dtype = torch.int32
656
+
657
+ if indices_format == 'bsr_strided_mm_compressed':
658
+ Ns = N // SPLIT_N
659
+ q_offsets_lst = []
660
+ b = torch.arange(SPLIT_N, dtype=indices_dtype, device=device) * Ns
661
+ for m in range(M // Ms):
662
+ r0 = crow_indices[m].item()
663
+ r1 = crow_indices[m + 1].item()
664
+ if r1 == r0:
665
+ continue
666
+ q_offsets_lst.append((col_indices[r0:r1] * (Ks * N)).repeat(SPLIT_N) + b.repeat_interleave(r1 - r0))
667
+ q_offsets = torch.cat(q_offsets_lst)
668
+ crow_indices_diff = crow_indices.diff()
669
+ non_zero_row_indices = crow_indices_diff.nonzero()
670
+ a = non_zero_row_indices * (Ms * N)
671
+ r_offsets = (a + b).view(-1)
672
+ c_indices = crow_indices
673
+ # swizzle operation: mm elements with longer sums are computed first:
674
+ nnz_per_row = crow_indices_diff[non_zero_row_indices].repeat_interleave(SPLIT_N)
675
+ nnz_per_row, indices = nnz_per_row.sort(descending=True, stable=True)
676
+ r_offsets = r_offsets[indices]
677
+ return (indices_format, c_indices, r_offsets, q_offsets)
678
+
679
+ elif indices_format == 'bsr_strided_mm':
680
+ Ns = N // SPLIT_N
681
+ p_offsets_lst = []
682
+ q_offsets_lst = []
683
+ b = torch.arange(SPLIT_N, dtype=indices_dtype, device=device) * Ns
684
+ for m in range(M // Ms):
685
+ r0 = crow_indices[m].item()
686
+ r1 = crow_indices[m + 1].item()
687
+ if r1 == r0:
688
+ continue
689
+ p_offsets_lst.append(torch.arange(r0, r1, dtype=indices_dtype, device=device).repeat(SPLIT_N))
690
+ q_offsets_lst.append((col_indices[r0:r1] * (Ks * N)).repeat(SPLIT_N) + b.repeat_interleave(r1 - r0))
691
+ q_offsets = torch.cat(q_offsets_lst)
692
+ crow_indices_diff = crow_indices.diff()
693
+ non_zero_row_indices = crow_indices_diff.nonzero()
694
+ a = non_zero_row_indices * (Ms * N)
695
+ r_offsets = (a + b).view(-1)
696
+ c_indices = torch.cat((crow_indices[:1],
697
+ torch.cumsum(crow_indices_diff[non_zero_row_indices].repeat_interleave(SPLIT_N), 0)))
698
+ p_offsets = torch.cat(p_offsets_lst)
699
+ return (indices_format, c_indices, r_offsets, p_offsets, q_offsets)
700
+
701
+ elif indices_format == 'scatter_mm':
702
+ Ns = Ms
703
+ c_indices = [0]
704
+ pq_offsets = []
705
+ # todo: eliminate inner for-loops for efficiency
706
+ for b in range(nbatches):
707
+ for m in range(M // Ms):
708
+ r0 = crow_indices[m].item()
709
+ r1 = crow_indices[m + 1].item()
710
+ for n in range(N // Ns):
711
+ c_indices.append(c_indices[-1] + r1 - r0)
712
+ for t in range(r1 - r0):
713
+ p = r0 + t
714
+ q = (col_indices[p].item() + b * (K // Ks)) * (N // Ns) + n
715
+ pq_offsets.append([p, q])
716
+
717
+ return (indices_format,
718
+ torch.tensor(c_indices, dtype=indices_dtype, device=device),
719
+ torch.tensor(pq_offsets, dtype=indices_dtype, device=device))
720
+
721
+ else:
722
+ raise ValueError(f'Invalid {indices_format=}. Expected bsr_strided_mm_compressed|bsr_strided_mm|scatter_mm')
723
+
724
+
725
+ def bsr_scatter_mm_indices_data(bsr, other, indices_format='bsr_strided_mm_compressed', **meta_input):
726
+ """Computes indices data for :func:`scatter_mm` used in BSR and
727
+ strided tensor matrix multiplication.
728
+ """
729
+ assert bsr.dense_dim() == 0
730
+ assert bsr.ndim == 2 # no batch dims
731
+ crow_indices = bsr.crow_indices()
732
+ col_indices = bsr.col_indices()
733
+ blocksize = bsr.values().shape[-2:]
734
+ M, K = bsr.shape
735
+ Ms, Ks = blocksize
736
+ K_, N = other.shape[-2:]
737
+ assert K_ == K
738
+ nbatches = other.shape[:-2].numel()
739
+
740
+ meta = scatter_mm_meta(M, K, N, Ms, Ks, **meta_input)
741
+ if 'allow_tf32' not in meta_input:
742
+ meta.update(allow_tf32=bsr.dtype in {torch.float16, torch.bfloat16})
743
+ SPLIT_N = meta['SPLIT_N']
744
+ indices_data = _bsr_scatter_mm_indices_data(
745
+ indices_format, M, K, N, Ms, Ks, nbatches, SPLIT_N, TensorAsKey(bsr))
746
+
747
+ if indices_format == 'bsr_strided_mm_compressed':
748
+ meta.update(is_compressed=True)
749
+ return indices_data + (meta,)
750
+ elif indices_format == 'bsr_strided_mm':
751
+ meta.update(is_compressed=False)
752
+ return indices_data + (meta,)
753
+ else:
754
+ return indices_data
755
+
756
+
757
+ def bsr_scatter_mm(bsr, other, indices_data=None, out=None):
758
+ """BSR @ strided -> strided
759
+ """
760
+
761
+ assert bsr.ndim == 2
762
+ assert other.ndim >= 2
763
+
764
+ Ms, Ks, Ns = bsr.shape[-2], bsr.shape[-1], other.shape[-1]
765
+ blocksize = bsr.values().shape[-2:]
766
+
767
+ if indices_data is None:
768
+ indices_data = bsr_scatter_mm_indices_data(bsr, other, indices_format='bsr_strided_mm_compressed')
769
+
770
+ indices_format = indices_data[0]
771
+
772
+ if out is None:
773
+ out = torch.empty((*other.shape[:-2], Ms, Ns), dtype=bsr.dtype, device=bsr.device)
774
+ out_shape = out.shape
775
+ out = as1Dbatch(out)
776
+
777
+ if bsr._nnz() == 0:
778
+ out.zero_()
779
+ elif indices_format in {'bsr_strided_mm_compressed', 'bsr_strided_mm'}:
780
+ out.zero_()
781
+ scatter_mm(bsr.values(), other, indices_data, accumulators=out)
782
+ elif indices_format == 'scatter_mm':
783
+ nbatches = other.shape[:-2].numel()
784
+ accumulators = torch.zeros((nbatches * Ms // blocksize[0] * Ns // blocksize[0], blocksize[0], blocksize[0]),
785
+ dtype=bsr.dtype, device=bsr.device)
786
+ others = (as1Dbatch(other)
787
+ .transpose(-2, -1)
788
+ .view(nbatches, Ns // blocksize[0], blocksize[0], Ks // blocksize[1], blocksize[1])
789
+ .movedim((3, 1, 4, 2), (1, 2, 3, 4)) # equivalent to .transpose(-3, -2).transpose(-2, -1).transpose(-4, -3)
790
+ .flatten(0, 2)
791
+ )
792
+ scatter_mm(bsr.values(), others, indices_data, accumulators=accumulators)
793
+ out.copy_(accumulators
794
+ .unflatten(0, (nbatches, Ms // blocksize[0], Ns // blocksize[0]))
795
+ .movedim((1, 2, 3, 4), (3, 1, 4, 2)) # equivalent to .transpose(-4, -3).transpose(-2, -1).transpose(-3, -2)
796
+ .reshape(nbatches, Ns, Ms)
797
+ .transpose(-2, -1))
798
+ else:
799
+ raise NotImplementedError(indices_format)
800
+
801
+ return out.view(out_shape)
802
+
803
+
804
+ def bsr_dense_addmm(
805
+ input: torch.Tensor,
806
+ bsr: torch.Tensor,
807
+ dense: torch.Tensor,
808
+ *,
809
+ beta=1,
810
+ alpha=1,
811
+ out: Optional[torch.Tensor] = None,
812
+ skip_checks: bool = False,
813
+ max_grid: Optional[Tuple[Optional[int], Optional[int], Optional[int]]] = None,
814
+ meta: Optional[dict] = None):
815
+ f_name = 'bsr_dense_addmm'
816
+ values = bsr.values()
817
+ crow_indices = bsr.crow_indices()
818
+ col_indices = bsr.col_indices()
819
+ batch_ndim = crow_indices.dim() - 1
820
+ M, K = bsr.shape[batch_ndim:batch_ndim + 2]
821
+ blocksize = values.shape[batch_ndim + 1:batch_ndim + 3]
822
+ N = dense.shape[-1]
823
+
824
+ # todo: implement checks
825
+
826
+ if out is None:
827
+ original_batch_dims_broadcasted = broadcast_batch_dims(f_name, bsr, dense)
828
+ out = dense.new_empty(original_batch_dims_broadcasted + (M, N))
829
+
830
+ if bsr._nnz() == 0 or alpha == 0 or N == 0 or M == 0 or K == 0:
831
+ if beta == 0:
832
+ out.zero_()
833
+ else:
834
+ out.copy_(input)
835
+ if beta != 1:
836
+ out.mul_(beta)
837
+ return out
838
+
839
+ if meta is None:
840
+ sparsity = round(1 - bsr._nnz() * blocksize[0] * blocksize[1] / (M * K), 2)
841
+ meta = bsr_dense_addmm_meta(M, K, N, blocksize[0], blocksize[1], beta, alpha, sparsity=sparsity, dtype=out.dtype)
842
+ out_backup = out
843
+
844
+ crow_indices, col_indices, values, input, dense, out = prepare_inputs(bsr, input, dense, out)
845
+
846
+ BM, BK = blocksize
847
+ SPLIT_N = meta.get('SPLIT_N', N // BM)
848
+ BN = N // SPLIT_N
849
+
850
+ out_untiled = out
851
+ out = tile_to_blocksize(out, (BM, BN))
852
+ dense = tile_to_blocksize(dense, (BK, BN))
853
+ input = tile_to_blocksize(input, (BM, BN))
854
+
855
+ dot_out_dtype = {torch.float16: tl.float32,
856
+ torch.bfloat16: tl.float32,
857
+ torch.float32: tl.float64,
858
+ torch.float64: tl.float64}[out.dtype]
859
+
860
+ n_batches = dense.size(0)
861
+ n_block_rows = crow_indices.size(-1) - 1
862
+ n_block_cols = dense.size(-3)
863
+
864
+ full_grid = (n_batches, n_block_cols, n_block_rows)
865
+ if max_grid is not None:
866
+ grid_blocks = tuple(max_grid[:3][::-1]) + (None,) * (3 - len(max_grid[:3]))
867
+ else:
868
+ grid_blocks = None
869
+
870
+ tensor_dims_map = {
871
+ values: (0, None, None),
872
+ crow_indices: (0, None, -1),
873
+ col_indices: (0, None, None),
874
+ input: (0, -3, -4),
875
+ dense: (0, -3, None),
876
+ out: (0, -3, -4),
877
+ }
878
+
879
+ assert alpha != 0
880
+
881
+ def kernel(grid, *sliced_tensors):
882
+ _bsr_strided_addmm_kernel[grid](
883
+ *ptr_stride_extractor(*sliced_tensors),
884
+ beta, alpha,
885
+ beta_is_one=beta == 1,
886
+ beta_is_nonzero=beta != 0,
887
+ alpha_is_one=alpha == 1,
888
+ BLOCKSIZE_ROW=BM,
889
+ BLOCKSIZE_INNER=BK,
890
+ BLOCKSIZE_COL=BN,
891
+ allow_tf32=dot_out_dtype == tl.float32,
892
+ acc_dtype=dot_out_dtype,
893
+ **meta)
894
+
895
+ launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks)
896
+
897
+ if out.data_ptr() != out_backup.data_ptr():
898
+ # prepare_inputs has made a copy of out, copy its content back
899
+ # to out_backup:
900
+ out_backup.copy_(out_untiled.view(out_backup.shape))
901
+
902
+ return out_backup
903
+
904
+
905
+ if has_triton():
906
+ import triton
907
+ import triton.language as tl
908
+
909
+ @triton.jit
910
+ def _sampled_addmm_kernel(
911
+ alpha,
912
+ beta,
913
+ IS_BETA_ZERO: tl.constexpr,
914
+ BLOCKSIZE_ROW: tl.constexpr,
915
+ BLOCKSIZE_COL: tl.constexpr,
916
+ k,
917
+ TILE_K: tl.constexpr,
918
+ values_ptr,
919
+ values_batch_stride,
920
+ values_nnz_stride,
921
+ values_row_block_stride,
922
+ values_col_block_stride,
923
+ crow_indices_ptr,
924
+ crow_indices_batch_stride,
925
+ crow_indices_stride,
926
+ col_indices_ptr,
927
+ col_indices_batch_stride,
928
+ col_indices_stride,
929
+ mat1_ptr,
930
+ mat1_batch_stride,
931
+ mat1_tiled_row_stride,
932
+ mat1_tiled_col_stride,
933
+ mat1_row_block_stride,
934
+ mat1_col_block_stride,
935
+ mat2_ptr,
936
+ mat2_batch_stride,
937
+ mat2_tiled_row_stride,
938
+ mat2_tiled_col_stride,
939
+ mat2_row_block_stride,
940
+ mat2_col_block_stride,
941
+ acc_dtype: tl.constexpr,
942
+ allow_tf32: tl.constexpr,
943
+ ):
944
+ batch_pid = tl.program_id(axis=1)
945
+ row_block_pid = tl.program_id(axis=0)
946
+
947
+ crow_indices_offset_ptr = (
948
+ crow_indices_ptr
949
+ + crow_indices_batch_stride * batch_pid
950
+ + crow_indices_stride * row_block_pid
951
+ )
952
+ nnz_offset = tl.load(crow_indices_offset_ptr)
953
+ nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride)
954
+
955
+ # Compute nnz for the row with number row_block_pid.
956
+ # If it is zero, skip the row.
957
+ row_nnz = nnz_offset_next - nnz_offset
958
+ if row_nnz == 0:
959
+ return
960
+
961
+ row_block_arange = tl.arange(0, BLOCKSIZE_ROW)
962
+ col_block_arange = tl.arange(0, BLOCKSIZE_COL)
963
+
964
+ # Pointers are set to the first block of the current row.
965
+ values_block_ptrs = (
966
+ values_ptr
967
+ + values_batch_stride * batch_pid
968
+ + values_nnz_stride * nnz_offset
969
+ + values_row_block_stride * row_block_arange[:, None]
970
+ + values_col_block_stride * col_block_arange[None, :]
971
+ )
972
+
973
+ col_index_nnz_ptr = (
974
+ col_indices_ptr
975
+ + col_indices_batch_stride * batch_pid
976
+ + col_indices_stride * nnz_offset
977
+ )
978
+
979
+ # Advance mat1 to the current tiled row, ignore columns.
980
+ mat1_block_ptrs = (
981
+ mat1_ptr
982
+ + mat1_batch_stride * batch_pid
983
+ + mat1_tiled_row_stride * row_block_pid
984
+ + mat1_row_block_stride * row_block_arange[:, None]
985
+ )
986
+
987
+ # Advance mat2 in batch and block col dimension.
988
+ mat2_block_ptrs = (
989
+ mat2_ptr
990
+ + mat2_batch_stride * batch_pid
991
+ + mat2_col_block_stride * col_block_arange[None, :]
992
+ )
993
+
994
+ k_tile_arange = tl.arange(0, TILE_K)
995
+ for _ in range(row_nnz):
996
+ acc_block = tl.zeros((BLOCKSIZE_ROW, BLOCKSIZE_COL), dtype=acc_dtype)
997
+
998
+ # find column block index
999
+ col_block = tl.load(col_index_nnz_ptr)
1000
+
1001
+ for k_tile in range(0, k, TILE_K):
1002
+ k_offsets = k_tile + k_tile_arange
1003
+ mask_k = k_offsets < k
1004
+
1005
+ mat1_block = tl.load(
1006
+ mat1_block_ptrs
1007
+ + mat1_col_block_stride * k_offsets[None, :],
1008
+ mask=mask_k[None, :], other=0.0
1009
+ )
1010
+
1011
+ mat2_block = tl.load(
1012
+ mat2_block_ptrs
1013
+ + mat2_tiled_col_stride * col_block
1014
+ + mat2_row_block_stride * k_offsets[:, None],
1015
+ mask=mask_k[:, None], other=0.0
1016
+ )
1017
+
1018
+ acc_block += tl.dot(mat1_block, mat2_block, allow_tf32=allow_tf32, out_dtype=acc_dtype)
1019
+
1020
+ if IS_BETA_ZERO:
1021
+ acc_block *= alpha
1022
+ else:
1023
+ acc_block = alpha * acc_block + beta * tl.load(values_block_ptrs)
1024
+
1025
+ # write result
1026
+ tl.store(values_block_ptrs, acc_block.to(values_ptr.dtype.element_ty))
1027
+
1028
+ # advance val/col_index ptrs to the next block in the row.
1029
+ values_block_ptrs += values_nnz_stride
1030
+ col_index_nnz_ptr += col_indices_stride
1031
+
1032
+ @triton.jit
1033
+ def _bsr_strided_dense_rowspace_kernel(
1034
+ # values prologue
1035
+ values_ptr,
1036
+ values_batch_stride,
1037
+ values_nnz_stride,
1038
+ values_row_block_stride,
1039
+ values_col_block_stride,
1040
+ # values epilogue
1041
+ # crow_indices prologue
1042
+ crow_indices_ptr,
1043
+ crow_indices_batch_stride,
1044
+ crow_indices_stride,
1045
+ # crow_indices epilogue
1046
+ # col_indices prologue
1047
+ col_indices_ptr,
1048
+ col_indices_batch_stride,
1049
+ col_indices_stride,
1050
+ # col_indices epilogue
1051
+ # dense prologue
1052
+ dense_ptr,
1053
+ dense_batch_stride,
1054
+ dense_tiled_row_stride,
1055
+ dense_tiled_col_stride,
1056
+ dense_row_block_stride,
1057
+ dense_col_block_stride,
1058
+ # dense epilogue
1059
+ # output prologue
1060
+ output_ptr,
1061
+ output_batch_stride,
1062
+ output_tiled_row_stride,
1063
+ output_tiled_col_stride,
1064
+ output_row_block_stride,
1065
+ output_col_block_stride,
1066
+ # output epilogue
1067
+ #
1068
+ # gh-113754: Always keep all constexpr arguments at the end of
1069
+ # triton kernel arguments list because with triton 2.1 or
1070
+ # earlier non-contiguous outputs will corrupt CUDA state due
1071
+ # to a triton bug (fixed in openai/triton#2262).
1072
+ BLOCKSIZE_ROW: tl.constexpr,
1073
+ BLOCKSIZE_COL: tl.constexpr,
1074
+ acc_dtype: tl.constexpr,
1075
+ allow_tf32: tl.constexpr,
1076
+ GROUP_SIZE_ROW: tl.constexpr,
1077
+ ):
1078
+ batch_pid = tl.program_id(axis=2)
1079
+ row_block_pid = tl.program_id(axis=0)
1080
+ col_block_pid = tl.program_id(axis=1)
1081
+ n_block_rows = tl.num_programs(axis=0)
1082
+ n_block_cols = tl.num_programs(axis=1)
1083
+
1084
+ row_block_pid, col_block_pid = tl.swizzle2d(
1085
+ row_block_pid, col_block_pid, n_block_rows, n_block_cols, GROUP_SIZE_ROW
1086
+ )
1087
+
1088
+ crow_indices_offset_ptr = (
1089
+ crow_indices_ptr
1090
+ + crow_indices_batch_stride * batch_pid
1091
+ + crow_indices_stride * row_block_pid
1092
+ )
1093
+ nnz_offset = tl.load(crow_indices_offset_ptr)
1094
+ nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride)
1095
+
1096
+ # Compute nnz for the row with number row_block_pid.
1097
+ # If it is zero, skip the row.
1098
+ row_nnz = nnz_offset_next - nnz_offset
1099
+ if row_nnz == 0:
1100
+ return
1101
+
1102
+ row_block_arange = tl.arange(0, BLOCKSIZE_ROW)
1103
+ col_block_arange = tl.arange(0, BLOCKSIZE_COL)
1104
+
1105
+ # Pointers are set to the first block of the current row.
1106
+ values_block_ptrs = (
1107
+ values_ptr
1108
+ + values_batch_stride * batch_pid
1109
+ + values_nnz_stride * nnz_offset
1110
+ + values_row_block_stride * row_block_arange[:, None]
1111
+ + values_col_block_stride * col_block_arange[None, :]
1112
+ )
1113
+
1114
+ # NOTE: dense is advanced into all dimensions but the tiled row one.
1115
+ # That will be advanced in the loop according to values in col_indices.
1116
+ dense_block_ptrs = (
1117
+ dense_ptr
1118
+ + dense_batch_stride * batch_pid
1119
+ + dense_tiled_col_stride * col_block_pid
1120
+ + dense_row_block_stride * col_block_arange[:, None]
1121
+ + dense_col_block_stride * row_block_arange[None, :]
1122
+ )
1123
+
1124
+ # Pointers are set to exact write-to locations
1125
+ output_ptrs = (
1126
+ output_ptr
1127
+ + output_batch_stride * batch_pid
1128
+ + output_tiled_row_stride * row_block_pid
1129
+ + output_tiled_col_stride * col_block_pid
1130
+ + output_row_block_stride * row_block_arange[:, None]
1131
+ + output_col_block_stride * row_block_arange[None, :]
1132
+ )
1133
+
1134
+ # Set pointer to the first nonzero element in the current row
1135
+ col_index_nnz_ptr = (
1136
+ col_indices_ptr
1137
+ + col_indices_batch_stride * batch_pid
1138
+ + col_indices_stride * nnz_offset
1139
+ )
1140
+
1141
+ output_acc_block = tl.zeros((BLOCKSIZE_ROW, BLOCKSIZE_COL), dtype=acc_dtype)
1142
+ for _ in range(row_nnz):
1143
+ values_block = tl.load(values_block_ptrs)
1144
+
1145
+ # find which row of dense needs to get loaded
1146
+ # for multiplication with values_block.
1147
+ dense_row_idx = tl.load(col_index_nnz_ptr)
1148
+ dense_block = tl.load(dense_block_ptrs + dense_tiled_row_stride * dense_row_idx)
1149
+
1150
+ # do block mm
1151
+ output_acc_block += tl.dot(values_block, dense_block, allow_tf32=allow_tf32, out_dtype=acc_dtype)
1152
+
1153
+ # move val/col_index ptrs to the next block in the row
1154
+ values_block_ptrs += values_nnz_stride
1155
+ col_index_nnz_ptr += col_indices_stride
1156
+
1157
+ # write back the result
1158
+ tl.store(output_ptrs, output_acc_block.to(output_ptr.dtype.element_ty))
1159
+
1160
+
1161
+ def _run_sampled_addmm_kernel(
1162
+ alpha, beta, is_beta_zero,
1163
+ blocksize, k, tile_k,
1164
+ values, crow_indices, col_indices,
1165
+ mat1, mat2,
1166
+ max_grid
1167
+ ):
1168
+ n_batches = values.size(0)
1169
+ n_block_rows = crow_indices.size(-1) - 1
1170
+
1171
+ full_grid = (n_batches, n_block_rows)
1172
+ if max_grid is not None:
1173
+ grid_blocks = tuple(max_grid[:2][::-1]) + (None,) * (2 - len(max_grid[:2]))
1174
+ else:
1175
+ grid_blocks = None
1176
+ tensor_dims_map = {
1177
+ values: (0, None),
1178
+ crow_indices: (0, -1),
1179
+ col_indices: (0, None),
1180
+ mat1: (0, -4),
1181
+ mat2: (0, None),
1182
+ }
1183
+ if values.dtype in (torch.half, torch.bfloat16):
1184
+ acc_dtype = tl.float32
1185
+ allow_tf32 = True
1186
+ else:
1187
+ acc_dtype = tl.float64
1188
+ allow_tf32 = False
1189
+
1190
+ def kernel(grid, *sliced_tensors):
1191
+ _sampled_addmm_kernel[grid](
1192
+ alpha, beta, is_beta_zero,
1193
+ *blocksize, k, tile_k,
1194
+ *ptr_stride_extractor(*sliced_tensors),
1195
+ acc_dtype=acc_dtype,
1196
+ allow_tf32=allow_tf32,
1197
+ num_stages=1,
1198
+ num_warps=4
1199
+ )
1200
+
1201
+ launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks)
1202
+
1203
+
1204
+ def sampled_addmm(
1205
+ input: torch.Tensor,
1206
+ mat1: torch.Tensor,
1207
+ mat2: torch.Tensor,
1208
+ *,
1209
+ beta=1.0,
1210
+ alpha=1.0,
1211
+ out: Optional[torch.Tensor] = None,
1212
+ skip_checks: bool = False,
1213
+ max_grid: Optional[Tuple[Optional[int], Optional[int], Optional[int]]] = None,
1214
+ ):
1215
+ f_name = "sampled_addmm"
1216
+
1217
+ check_bsr_layout(f_name, input)
1218
+ input_broadcasted = broadcast_batch_dims_bsr(f_name, input, mat1, mat2)
1219
+
1220
+ if not skip_checks:
1221
+ check_device(f_name, mat1, input.device)
1222
+ check_device(f_name, mat2, input.device)
1223
+ if beta != 0.0 and input.dtype is torch.bool:
1224
+ check(
1225
+ False,
1226
+ f"{f_name}(): having beta == {beta} not equal to 0.0 with boolean mask is not allowed."
1227
+ )
1228
+ if input.dtype is not torch.bool:
1229
+ check_dtype(f_name, mat1, input.dtype)
1230
+ check_dtype(f_name, mat2, input.dtype)
1231
+ else:
1232
+ check_dtype(f_name, mat1, mat2.dtype)
1233
+ check_mm_compatible_shapes(f_name, mat1, mat2)
1234
+ if out is not None:
1235
+ check_bsr_layout(f_name, out)
1236
+ check_device(f_name, out, mat1.device)
1237
+ check_dtype(f_name, out, input.dtype)
1238
+ check(
1239
+ out.shape == input_broadcasted.shape
1240
+ and out._nnz() == input._nnz(),
1241
+ f"{f_name}(): Expects `out` to be of shape {input_broadcasted.shape} "
1242
+ f"and with nnz equal to {input_broadcasted._nnz()} "
1243
+ f"but got out.shape = {out.shape} and out.nnz = {out._nnz()}"
1244
+ )
1245
+
1246
+ if out is None:
1247
+ out = input_broadcasted.to(mat1.dtype, copy=True)
1248
+ else:
1249
+ out.copy_(input_broadcasted)
1250
+
1251
+ if out.numel() == 0 or out._nnz() == 0:
1252
+ return out
1253
+
1254
+ blocksize = out.values().shape[-2:]
1255
+ m = mat1.size(-2)
1256
+ n = mat2.size(-1)
1257
+ k = mat1.size(-1)
1258
+
1259
+ # NOTE: (m, 0) @ (0, n) == zeros(m, n)
1260
+ if alpha == 0.0 or k == 0:
1261
+ out.values().mul_(beta)
1262
+ return out
1263
+
1264
+ # prepare inputs by reshaping them to be kernel-compatible
1265
+ out_backup = out
1266
+ crow_indices, col_indices, values, mat1, mat2 = prepare_inputs(out, mat1, mat2)
1267
+
1268
+ mat1 = tile_to_blocksize(mat1, (blocksize[0], k))
1269
+ mat2 = tile_to_blocksize(mat2, (k, blocksize[1]))
1270
+ tile_k = max(*blocksize)
1271
+
1272
+ _run_sampled_addmm_kernel(
1273
+ alpha, beta, beta == 0.0,
1274
+ blocksize, k, tile_k,
1275
+ values, crow_indices, col_indices,
1276
+ mat1, mat2,
1277
+ max_grid
1278
+ )
1279
+
1280
+ # If nnz x block strides are not the same in out_backup.values and values,
1281
+ # it means that out_backup.values and values are not the views of each other,
1282
+ # so we have to copy.
1283
+ if out_backup.values().stride()[-3:] != values.stride()[-3:]:
1284
+ out_backup.values().copy_(values.reshape(out_backup.values().shape))
1285
+ return out_backup
1286
+
1287
+
1288
+ def bsr_dense_mm(
1289
+ bsr: torch.Tensor,
1290
+ dense: torch.Tensor,
1291
+ *,
1292
+ out: Optional[torch.Tensor] = None,
1293
+ skip_checks: bool = False,
1294
+ max_grid: Optional[Tuple[Optional[int], Optional[int], Optional[int]]] = None,
1295
+ meta: Optional[dict] = None
1296
+ ):
1297
+ f_name = "bsr_dense_mm"
1298
+ m, kl = bsr.shape[-2:]
1299
+ if not skip_checks:
1300
+ check_bsr_layout(f_name, bsr)
1301
+ check_device(f_name, bsr, dense.device)
1302
+ check_dtype(f_name, bsr, dense.dtype)
1303
+ check_mm_compatible_shapes(f_name, bsr, dense)
1304
+
1305
+ n = dense.size(-1)
1306
+ row_block, col_block = bsr.values().shape[-2:]
1307
+ check_blocksize(f_name, (row_block, col_block))
1308
+ check(
1309
+ not n % 16,
1310
+ f"{f_name}(): dense.size(-1) == {n} should be divisible by 16"
1311
+ )
1312
+ else:
1313
+ kr, n = dense.shape[-2:]
1314
+
1315
+ original_batch_dims_broadcasted = broadcast_batch_dims(f_name, bsr, dense)
1316
+
1317
+ if out is not None and not skip_checks:
1318
+ expected_out_shape = original_batch_dims_broadcasted + (m, n)
1319
+ check(
1320
+ out.shape == expected_out_shape,
1321
+ "bsr_dense_mm(): `out` argument has wrong shape, "
1322
+ f"expected {expected_out_shape}, but got {out.shape}.",
1323
+ )
1324
+ check(
1325
+ out.is_contiguous() or out.transpose(-2, -1).is_contiguous(),
1326
+ "bsr_dense_mm(): only row-major/col-major `out` arguments are supported, "
1327
+ "i.e. (out.is_contiguous() or out.transpose(-2, -1).is_contiguous()) "
1328
+ "should be True.",
1329
+ )
1330
+
1331
+ # Allocate out
1332
+ if out is None:
1333
+ out = dense.new_empty(original_batch_dims_broadcasted + (m, n))
1334
+
1335
+ # Short circuit if lhs is zero
1336
+ if bsr._nnz() == 0:
1337
+ return out.zero_()
1338
+
1339
+ # with beta==0, addmm ignores input content, so we can use out
1340
+ # as a placeholder for input because their shapes match:
1341
+ return bsr_dense_addmm(out, bsr, dense, alpha=1, beta=0, out=out)
1342
+
1343
+
1344
+ @triton.jit
1345
+ def _bsr_softmax_kernel(
1346
+ crow_indices_ptr,
1347
+ crow_indices_batch_stride,
1348
+ crow_indices_stride,
1349
+ values_ptr,
1350
+ values_batch_stride,
1351
+ values_row_block_stride,
1352
+ values_nnz_col_block_stride,
1353
+ row_block, col_block,
1354
+ MAX_ROW_NNZ: tl.constexpr,
1355
+ TILE: tl.constexpr
1356
+ ):
1357
+ batch_pid = tl.program_id(axis=2)
1358
+ row_block_offset_pid = tl.program_id(axis=1)
1359
+ row_block_pid = tl.program_id(axis=0)
1360
+
1361
+ crow_indices_offset_ptr = (
1362
+ crow_indices_ptr
1363
+ + crow_indices_batch_stride * batch_pid
1364
+ + crow_indices_stride * row_block_pid
1365
+ )
1366
+ nnz_offset = tl.load(crow_indices_offset_ptr)
1367
+ nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride)
1368
+
1369
+ # Compute nnz for the row with number row_block_pid.
1370
+ # If it is zero, skip the row.
1371
+ row_nnz = nnz_offset_next - nnz_offset
1372
+ if row_nnz == 0:
1373
+ return
1374
+
1375
+ row_arange = tl.arange(0, TILE)
1376
+ mask = row_arange < row_nnz * col_block
1377
+
1378
+ curr_row_values_ptrs = (
1379
+ values_ptr
1380
+ + values_batch_stride * batch_pid
1381
+ + values_row_block_stride * row_block_offset_pid
1382
+ + nnz_offset * col_block
1383
+ )
1384
+
1385
+ # find max in the row
1386
+ row_tile = tl.load(curr_row_values_ptrs + row_arange, mask=mask, other=-float('inf')).to(tl.float32)
1387
+ max_row_value = tl.max(row_tile, axis=0)
1388
+ for _ in range(TILE, MAX_ROW_NNZ, TILE):
1389
+ row_arange += TILE
1390
+ mask = row_arange < row_nnz * col_block
1391
+ row_tile = tl.load(curr_row_values_ptrs + row_arange, mask=mask, other=-float('inf')).to(tl.float32)
1392
+ curr_max_row_value = tl.max(row_tile, axis=0)
1393
+ max_row_value = tl.where(max_row_value > curr_max_row_value, max_row_value, curr_max_row_value)
1394
+
1395
+ # find denominator for stable softmax
1396
+ num = tl.exp(row_tile - max_row_value)
1397
+ denom = tl.sum(num, axis=0)
1398
+ for _ in range(TILE, MAX_ROW_NNZ, TILE):
1399
+ row_arange -= TILE
1400
+ mask = row_arange < row_nnz * col_block
1401
+ row_tile = tl.load(curr_row_values_ptrs + row_arange, mask=mask, other=-float('inf')).to(tl.float32)
1402
+ num = tl.exp(row_tile - max_row_value)
1403
+ denom += tl.sum(num, axis=0)
1404
+
1405
+ # populate output
1406
+ tl.store(curr_row_values_ptrs + row_arange, (num / denom).to(values_ptr.dtype.element_ty), mask=mask)
1407
+ for _ in range(TILE, MAX_ROW_NNZ, TILE):
1408
+ row_arange += TILE
1409
+ mask = row_arange < row_nnz * col_block
1410
+ row_tile = tl.load(curr_row_values_ptrs + row_arange, mask=mask, other=-float('inf')).to(tl.float32)
1411
+ num = tl.exp(row_tile - max_row_value)
1412
+ tl.store(curr_row_values_ptrs + row_arange, (num / denom).to(values_ptr.dtype.element_ty), mask=mask)
1413
+
1414
+
1415
+ def bsr_softmax(input, max_row_nnz=None):
1416
+ f_name = "bsr_softmax"
1417
+
1418
+ check_bsr_layout(f_name, input)
1419
+ check_dtype(f_name, input, input.dtype)
1420
+
1421
+ if input._nnz() == 0 or input.numel() == 0:
1422
+ return input.clone()
1423
+
1424
+ m, n = input.shape[-2:]
1425
+ nnz = input._nnz()
1426
+ row_block, col_block = input.values().shape[-2:]
1427
+
1428
+ if max_row_nnz is None:
1429
+ max_row_nnz = triton.next_power_of_2(n)
1430
+ else:
1431
+ max_row_nnz = triton.next_power_of_2(max_row_nnz)
1432
+
1433
+ crow_indices = input.crow_indices().unsqueeze(0).flatten(0, -2)
1434
+ # reshape values from
1435
+ # (b1, ..., bn, nnz, row_block, col_block) to
1436
+ # (b1 * ... * bn, row_block, nnz * col_block).
1437
+ # This simplifies batch dim manipulation and unlocks
1438
+ # the possibility to access all nnzs in any given row.
1439
+ if input.values().transpose(-3, -2).is_contiguous():
1440
+ # Need to clone to avoid `contiguous` returning a view.
1441
+ values = input.values().clone()
1442
+ else:
1443
+ values = input.values()
1444
+ values = values.transpose(-3, -2).contiguous().unsqueeze(0).flatten(0, -4).reshape(-1, row_block, nnz * col_block)
1445
+ full_grid = (values.shape[0], row_block, m // row_block)
1446
+ grid_blocks = None
1447
+ tensor_dims_map = {
1448
+ # We span nnz number of blocks, not nnz + 1,
1449
+ # hence crow_indices[..., :-1]
1450
+ crow_indices[..., :-1]: (0, None, -1),
1451
+ values: (0, None, None),
1452
+ }
1453
+
1454
+ def kernel(grid, *sliced_tensors):
1455
+ _bsr_softmax_kernel[grid](
1456
+ *ptr_stride_extractor(*sliced_tensors),
1457
+ row_block, col_block,
1458
+ max_row_nnz,
1459
+ # Triton's max numel is bounded by 2 ** 17.
1460
+ min(2 ** 17, max_row_nnz)
1461
+ )
1462
+
1463
+ launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks)
1464
+
1465
+ values = values.reshape(-1, row_block, nnz, col_block).transpose(-3, -2).reshape(*input.values().shape)
1466
+
1467
+ return torch.sparse_compressed_tensor(
1468
+ input.crow_indices().clone(),
1469
+ input.col_indices().clone(),
1470
+ values,
1471
+ size=input.shape,
1472
+ layout=input.layout
1473
+ )
1474
+
1475
+ def _scaled_dot_product_attention(
1476
+ query: torch.Tensor,
1477
+ key: torch.Tensor,
1478
+ value: torch.Tensor,
1479
+ attn_mask: Optional[torch.Tensor],
1480
+ dropout_p: float = 0.0,
1481
+ is_causal: bool = False,
1482
+ scale: Optional[float] = None
1483
+ ):
1484
+ f_name = "_scaled_dot_product_attention"
1485
+ check(
1486
+ not is_causal,
1487
+ f"{f_name}(): is_causal == True is not supported."
1488
+ )
1489
+ check(
1490
+ attn_mask is not None,
1491
+ f"{f_name}(): attn_mask == None is not supported."
1492
+ )
1493
+ assert attn_mask is not None
1494
+
1495
+ check(
1496
+ attn_mask.layout == torch.sparse_bsr,
1497
+ f"{f_name}(): "
1498
+ f"attn_mask.layout must be {torch.sparse_bsr}, but got "
1499
+ f"attn_mask.layout == {attn_mask.layout}."
1500
+ )
1501
+
1502
+ check_device(f_name, key, query.device)
1503
+ check_device(f_name, value, query.device)
1504
+ check_device(f_name, attn_mask, query.device)
1505
+
1506
+ check_dtype(f_name, key, query.dtype)
1507
+ check_dtype(f_name, value, query.dtype)
1508
+ if attn_mask.dtype is not torch.bool:
1509
+ check_dtype(f_name, attn_mask, query.dtype)
1510
+
1511
+ sdpa = sampled_addmm(attn_mask, query, key.transpose(-2, -1), beta=0.0, skip_checks=False)
1512
+ if scale is None and query.size(-1) == 0 or scale == 0.0:
1513
+ check(
1514
+ False,
1515
+ f"{f_name}(): current value of scale == {scale} "
1516
+ "results in division by zero."
1517
+ )
1518
+ scale_factor = 1 / math.sqrt(query.size(-1)) if scale is None else scale
1519
+ sdpa.values().mul_(scale_factor)
1520
+ sdpa = bsr_softmax(sdpa)
1521
+ torch.nn.functional.dropout(sdpa.values(), p=dropout_p, inplace=True)
1522
+ sdpa = bsr_dense_mm(sdpa, value)
1523
+ return sdpa
1524
+
1525
+ @triton.jit
1526
+ def _scatter_mm2_kernel(
1527
+ M: tl.constexpr, K: tl.constexpr, N: tl.constexpr,
1528
+ blocks_ptr, blocks_stride_P, blocks_stride_M, blocks_stride_K,
1529
+ others_ptr, others_stride_Q, others_stride_K, others_stride_N,
1530
+ accumulators_ptr, accumulators_stride_R, accumulators_stride_M, accumulators_stride_N,
1531
+ pq_offsets_ptr, pq_offsets_stride,
1532
+ pq_ptr, pq_stride_T, pq_stride_1,
1533
+ dot_out_dtype: tl.constexpr,
1534
+ TILE_M: tl.constexpr,
1535
+ TILE_N: tl.constexpr,
1536
+ allow_tf32: tl.constexpr):
1537
+
1538
+ Ms = M // TILE_M
1539
+ Ns = N // TILE_N
1540
+
1541
+ pid_t = tl.program_id(axis=0)
1542
+
1543
+ pid = tl.program_id(axis=1)
1544
+ pid_m = pid // Ms
1545
+ pid_n = pid % Ms
1546
+
1547
+ rm = (pid_m * TILE_M + tl.arange(0, TILE_M))
1548
+ rn = (pid_n * TILE_N + tl.arange(0, TILE_N))
1549
+ rk = tl.arange(0, K)
1550
+
1551
+ A_ptr = blocks_ptr + (rm[:, None] * blocks_stride_M + rk[None, :] * blocks_stride_K)
1552
+ B_ptr = others_ptr + (rk[:, None] * others_stride_K + rn[None, :] * others_stride_N)
1553
+
1554
+ g0 = tl.load(pq_offsets_ptr + pid_t * pq_offsets_stride)
1555
+ g1 = tl.load(pq_offsets_ptr + (pid_t + 1) * pq_offsets_stride)
1556
+
1557
+ if g0 == g1:
1558
+ return
1559
+
1560
+ acc_block = tl.zeros((TILE_M, TILE_N), dtype=dot_out_dtype)
1561
+
1562
+ for i in range(g0, g1):
1563
+ p = tl.load(pq_ptr + i * pq_stride_T)
1564
+ q = tl.load(pq_ptr + i * pq_stride_T + pq_stride_1)
1565
+ A = tl.load(A_ptr + p * blocks_stride_P)
1566
+ B = tl.load(B_ptr + q * others_stride_Q)
1567
+ acc_block += tl.dot(A, B, out_dtype=dot_out_dtype, allow_tf32=allow_tf32)
1568
+
1569
+ C_ptr = accumulators_ptr + pid_t * accumulators_stride_R + (
1570
+ rm[:, None] * accumulators_stride_M + rn[None, :] * accumulators_stride_N)
1571
+ tl.store(C_ptr, acc_block.to(accumulators_ptr.dtype.element_ty))
1572
+
1573
+ def _scatter_mm2(
1574
+ blocks: torch.Tensor,
1575
+ others: torch.Tensor,
1576
+ pq_offsets: torch.Tensor,
1577
+ pq_indices: torch.Tensor,
1578
+ accumulators: torch.Tensor
1579
+ ):
1580
+ P, M, K = blocks.shape
1581
+ Q, _, N = others.shape
1582
+ R, _, _ = accumulators.shape
1583
+
1584
+ meta = dict(TILE_M=max(16, M // 4), TILE_N=max(16, N // 4), num_stages=1, num_warps=2)
1585
+
1586
+ def grid(META):
1587
+ return (pq_offsets.shape[0] - 1, triton.cdiv(M, META['TILE_M']) * triton.cdiv(N, META['TILE_N']), 1)
1588
+
1589
+ dot_out_dtype = {torch.float16: tl.float32,
1590
+ torch.bfloat16: tl.float32,
1591
+ torch.float32: tl.float64,
1592
+ torch.float64: tl.float64}[accumulators.dtype]
1593
+ if 'allow_tf32' not in meta:
1594
+ meta.update(allow_tf32=dot_out_dtype == tl.float32)
1595
+ _scatter_mm2_kernel[grid](
1596
+ M, K, N,
1597
+ blocks, blocks.stride(0), blocks.stride(1), blocks.stride(2),
1598
+ others, others.stride(0), others.stride(1), others.stride(2),
1599
+ accumulators, accumulators.stride(0), accumulators.stride(1), accumulators.stride(2),
1600
+ pq_offsets, pq_offsets.stride(0),
1601
+ pq_indices, pq_indices.stride(0), pq_indices.stride(1),
1602
+ dot_out_dtype=dot_out_dtype,
1603
+ **meta
1604
+ )
1605
+
1606
+ @triton.jit
1607
+ def _scatter_mm6_kernel(
1608
+ nbatches, Ms, Ks: tl.constexpr, N,
1609
+ blocks_ptr, blocks_stride_P, blocks_stride_M, blocks_stride_K,
1610
+ others_ptr, others_stride_B, others_stride_K, others_stride_N,
1611
+ accumulators_ptr, accumulators_stride_B, accumulators_stride_M, accumulators_stride_N,
1612
+ c_indices_ptr, r_offsets_ptr,
1613
+ p_offsets_ptr, q_offsets_ptr,
1614
+ is_compressed: tl.constexpr,
1615
+ dot_out_dtype: tl.constexpr,
1616
+ SPLIT_N: tl.constexpr,
1617
+ TILE_M: tl.constexpr,
1618
+ TILE_N: tl.constexpr,
1619
+ GROUP_SIZE: tl.constexpr,
1620
+ allow_tf32: tl.constexpr):
1621
+ Ns = N // SPLIT_N
1622
+ BLOCKS_M = Ms // TILE_M
1623
+ BLOCKS_N = Ns // TILE_N
1624
+
1625
+ pid_t_ = tl.program_id(axis=0)
1626
+ pid = tl.program_id(axis=1)
1627
+ pid_b = pid_t_ % nbatches
1628
+ pid_t = pid_t_ // nbatches
1629
+
1630
+ num_pid_in_group = GROUP_SIZE * BLOCKS_N
1631
+ group_id = pid // num_pid_in_group
1632
+ first_pid_m = group_id * GROUP_SIZE
1633
+ group_size_m = min(BLOCKS_M - first_pid_m, GROUP_SIZE)
1634
+ pid_m = first_pid_m + (pid % group_size_m)
1635
+ pid_n = (pid % num_pid_in_group) // group_size_m
1636
+
1637
+ rm = (pid_m * TILE_M + tl.arange(0, TILE_M))
1638
+ rn = (pid_n * TILE_N + tl.arange(0, TILE_N))
1639
+ rk = tl.arange(0, Ks)
1640
+ A_ptr = blocks_ptr + (rm[:, None] * blocks_stride_M + rk[None, :] * blocks_stride_K)
1641
+ B_ptr = others_ptr + pid_b * others_stride_B + (rk[:, None] * others_stride_K + rn[None, :] * others_stride_N)
1642
+
1643
+ # When is_compressed is True, r is the only variable that
1644
+ # depends on pid_t. This property allows sorting r values
1645
+ # before calling the kernel. The sorting of r is equivalent to
1646
+ # defining swizzle operator outside of the kernel.
1647
+ r = tl.load(r_offsets_ptr + pid_t)
1648
+
1649
+ if is_compressed:
1650
+ m = (r // N) // Ms
1651
+ n = (r % N) // Ns
1652
+ r0 = tl.load(c_indices_ptr + m)
1653
+ r1 = tl.load(c_indices_ptr + m + 1)
1654
+ g0 = n * r1 + (SPLIT_N - n) * r0
1655
+ nnz = r1 - r0
1656
+ else:
1657
+ g0 = tl.load(c_indices_ptr + pid_t)
1658
+ g1 = tl.load(c_indices_ptr + pid_t + 1)
1659
+ nnz = g1 - g0
1660
+
1661
+ q_ptr = q_offsets_ptr + g0
1662
+ acc_block = tl.zeros((TILE_M, TILE_N), dtype=dot_out_dtype)
1663
+
1664
+ if is_compressed:
1665
+ A_ptr += r0 * blocks_stride_P # type: ignore[possibly-undefined]
1666
+ for _ in range(nnz):
1667
+ q = tl.load(q_ptr)
1668
+ B = tl.load(B_ptr + q)
1669
+ A = tl.load(A_ptr)
1670
+ acc_block += tl.dot(A, B, out_dtype=dot_out_dtype, allow_tf32=allow_tf32)
1671
+ A_ptr += blocks_stride_P
1672
+ q_ptr += 1
1673
+ else:
1674
+ p_ptr = p_offsets_ptr + g0
1675
+ for _ in range(nnz):
1676
+ q = tl.load(q_ptr)
1677
+ B = tl.load(B_ptr + q)
1678
+ p = tl.load(p_ptr)
1679
+ A = tl.load(A_ptr + p * blocks_stride_P)
1680
+ p_ptr += 1
1681
+ q_ptr += 1
1682
+ acc_block += tl.dot(A, B, out_dtype=dot_out_dtype, allow_tf32=allow_tf32)
1683
+
1684
+ C_ptr = accumulators_ptr + r + pid_b * accumulators_stride_B + (
1685
+ rm[:, None] * accumulators_stride_M + rn[None, :] * accumulators_stride_N)
1686
+ tl.store(C_ptr, acc_block.to(accumulators_ptr.dtype.element_ty))
1687
+
1688
+ def _scatter_mm6(
1689
+ blocks: torch.Tensor,
1690
+ others: torch.Tensor,
1691
+ c_indices: torch.Tensor,
1692
+ r_offsets: torch.Tensor,
1693
+ p_offsets: torch.Tensor,
1694
+ q_offsets: torch.Tensor,
1695
+ meta: dict,
1696
+ accumulators: torch.Tensor,
1697
+ force_contiguous: bool = True,
1698
+ ):
1699
+ SPLIT_N = meta['SPLIT_N']
1700
+ P, Ms, Ks = blocks.shape
1701
+ B, K_, N = others.shape
1702
+ B_, M, N_ = accumulators.shape
1703
+ assert N_ == N
1704
+ Ns = N // SPLIT_N
1705
+ assert B_ == B
1706
+
1707
+ def grid(META):
1708
+ return (r_offsets.shape[0] * B, triton.cdiv(Ms, META['TILE_M']) * triton.cdiv(Ns, META['TILE_N']))
1709
+
1710
+ dot_out_dtype = {torch.float16: tl.float32,
1711
+ torch.bfloat16: tl.float32,
1712
+ torch.float32: tl.float64,
1713
+ torch.float64: tl.float64}[accumulators.dtype]
1714
+ if 'allow_tf32' not in meta:
1715
+ meta.update(allow_tf32=dot_out_dtype == tl.float32)
1716
+
1717
+ assert c_indices.stride(0) == 1
1718
+ assert r_offsets.stride(0) == 1
1719
+ assert p_offsets.stride(0) == 1
1720
+ assert q_offsets.stride(0) == 1
1721
+
1722
+ # Re non-contiguous tensor arguments. Sometimes triton kernel
1723
+ # launches may fail with
1724
+ #
1725
+ # RuntimeError: Triton Error [CUDA]: an illegal memory access was encountered
1726
+ #
1727
+ # that appears to be case when the size of a non-contiguous
1728
+ # tensor argument is larger than a certain threshold. Could
1729
+ # this be related to shared memory or L1 cache size of a GPU
1730
+ # card? In anycase, ensuring that tensor arguments are
1731
+ # contiguous seems to avoid the above exception. So, in the
1732
+ # following we'll always convert tensor arguments to
1733
+ # C-contiguous tensors.
1734
+
1735
+ if force_contiguous:
1736
+ blocks = blocks.contiguous()
1737
+ others = others.contiguous()
1738
+ if not accumulators.is_contiguous():
1739
+ accumulators_ = accumulators.contiguous()
1740
+ else:
1741
+ accumulators_ = accumulators
1742
+ else:
1743
+ accumulators_ = accumulators
1744
+
1745
+ _scatter_mm6_kernel[grid](
1746
+ B, Ms, Ks, N,
1747
+ blocks, blocks.stride(0), blocks.stride(1), blocks.stride(2),
1748
+ others, others.stride(0), others.stride(1), others.stride(2),
1749
+ accumulators_, accumulators_.stride(0), accumulators_.stride(1), accumulators_.stride(2),
1750
+ c_indices,
1751
+ r_offsets,
1752
+ p_offsets,
1753
+ q_offsets,
1754
+ dot_out_dtype=dot_out_dtype,
1755
+ **meta
1756
+ )
1757
+
1758
+ if force_contiguous and not accumulators.is_contiguous():
1759
+ accumulators.copy_(accumulators_)
1760
+
1761
+ @triton.jit
1762
+ def _bsr_strided_addmm_kernel(
1763
+ # values prologue
1764
+ values_ptr,
1765
+ values_batch_stride,
1766
+ values_nnz_stride,
1767
+ values_row_block_stride,
1768
+ values_col_block_stride,
1769
+ # values epilogue
1770
+ # crow_indices prologue
1771
+ crow_indices_ptr,
1772
+ crow_indices_batch_stride,
1773
+ crow_indices_stride,
1774
+ # crow_indices epilogue
1775
+ # col_indices prologue
1776
+ col_indices_ptr,
1777
+ col_indices_batch_stride,
1778
+ col_indices_stride,
1779
+ # col_indices epilogue
1780
+ # input prologue
1781
+ input_ptr,
1782
+ input_batch_stride,
1783
+ input_tiled_row_stride,
1784
+ input_tiled_col_stride,
1785
+ input_row_block_stride,
1786
+ input_col_block_stride,
1787
+ # input epilogue
1788
+ # dense prologue
1789
+ dense_ptr,
1790
+ dense_batch_stride,
1791
+ dense_tiled_row_stride,
1792
+ dense_tiled_col_stride,
1793
+ dense_row_block_stride,
1794
+ dense_col_block_stride,
1795
+ # dense epilogue
1796
+ # output prologue
1797
+ output_ptr,
1798
+ output_batch_stride,
1799
+ output_tiled_row_stride,
1800
+ output_tiled_col_stride,
1801
+ output_row_block_stride,
1802
+ output_col_block_stride,
1803
+ # output epilogue
1804
+ beta,
1805
+ alpha,
1806
+ beta_is_one: tl.constexpr,
1807
+ beta_is_nonzero: tl.constexpr,
1808
+ alpha_is_one: tl.constexpr,
1809
+ BLOCKSIZE_ROW: tl.constexpr,
1810
+ BLOCKSIZE_COL: tl.constexpr,
1811
+ BLOCKSIZE_INNER: tl.constexpr,
1812
+ acc_dtype: tl.constexpr,
1813
+ allow_tf32: tl.constexpr,
1814
+ GROUP_SIZE_ROW: tl.constexpr,
1815
+ SPLIT_N: tl.constexpr
1816
+ ):
1817
+
1818
+ batch_pid = tl.program_id(axis=2)
1819
+ row_block_pid = tl.program_id(axis=0)
1820
+ col_block_pid = tl.program_id(axis=1)
1821
+ n_block_rows = tl.num_programs(axis=0)
1822
+ n_block_cols = tl.num_programs(axis=1)
1823
+
1824
+ row_block_pid, col_block_pid = tl.swizzle2d(
1825
+ row_block_pid, col_block_pid, n_block_rows, n_block_cols, GROUP_SIZE_ROW
1826
+ )
1827
+
1828
+ crow_indices_offset_ptr = (
1829
+ crow_indices_ptr
1830
+ + crow_indices_batch_stride * batch_pid
1831
+ + crow_indices_stride * row_block_pid
1832
+ )
1833
+ nnz_offset = tl.load(crow_indices_offset_ptr)
1834
+ nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride)
1835
+
1836
+ # Compute nnz for the row with number row_block_pid.
1837
+ row_nnz = nnz_offset_next - nnz_offset
1838
+
1839
+ row_block_arange = tl.arange(0, BLOCKSIZE_ROW)
1840
+ inner_block_arange = tl.arange(0, BLOCKSIZE_INNER)
1841
+ col_block_arange = tl.arange(0, BLOCKSIZE_COL)
1842
+
1843
+ if beta_is_nonzero:
1844
+ # Pointers are set to exact write-to locations
1845
+ input_ptrs = (
1846
+ input_ptr
1847
+ + input_batch_stride * batch_pid
1848
+ + input_tiled_row_stride * row_block_pid
1849
+ + input_tiled_col_stride * col_block_pid
1850
+ + input_row_block_stride * row_block_arange[:, None]
1851
+ + input_col_block_stride * col_block_arange[None, :]
1852
+ )
1853
+
1854
+ # Pointers are set to the first block of the current row.
1855
+ values_block_ptrs = (
1856
+ values_ptr
1857
+ + values_batch_stride * batch_pid
1858
+ + values_nnz_stride * nnz_offset
1859
+ + values_row_block_stride * row_block_arange[:, None]
1860
+ + values_col_block_stride * inner_block_arange[None, :]
1861
+ )
1862
+
1863
+ # NOTE: dense is advanced into all dimensions but the tiled row one.
1864
+ # That will be advanced in the loop according to values in col_indices.
1865
+ dense_block_ptrs = (
1866
+ dense_ptr
1867
+ + dense_batch_stride * batch_pid
1868
+ + dense_tiled_col_stride * col_block_pid
1869
+ + dense_row_block_stride * inner_block_arange[:, None]
1870
+ + dense_col_block_stride * col_block_arange[None, :]
1871
+ )
1872
+
1873
+ # Pointers are set to exact write-to locations
1874
+ output_ptrs = (
1875
+ output_ptr
1876
+ + output_batch_stride * batch_pid
1877
+ + output_tiled_row_stride * row_block_pid
1878
+ + output_tiled_col_stride * col_block_pid
1879
+ + output_row_block_stride * row_block_arange[:, None]
1880
+ + output_col_block_stride * col_block_arange[None, :]
1881
+ )
1882
+
1883
+ # Set pointer to the first nonzero element in the current row
1884
+ col_index_nnz_ptr = (
1885
+ col_indices_ptr
1886
+ + col_indices_batch_stride * batch_pid
1887
+ + col_indices_stride * nnz_offset
1888
+ )
1889
+
1890
+ # alpha is never 0
1891
+ if beta_is_nonzero:
1892
+ output_acc_block = tl.load(input_ptrs).to(acc_dtype) # type: ignore[possibly-undefined]
1893
+ if not (beta_is_one and alpha_is_one):
1894
+ beta_alpha = beta / alpha
1895
+ output_acc_block *= beta_alpha
1896
+ else:
1897
+ output_acc_block = tl.zeros((BLOCKSIZE_ROW, BLOCKSIZE_COL), dtype=acc_dtype)
1898
+
1899
+ for _ in range(row_nnz):
1900
+ values_block = tl.load(values_block_ptrs)
1901
+
1902
+ # find which row of dense needs to get loaded
1903
+ # for multiplication with values_block.
1904
+ dense_row_idx = tl.load(col_index_nnz_ptr)
1905
+ dense_block = tl.load(dense_block_ptrs + dense_tiled_row_stride * dense_row_idx)
1906
+
1907
+ # do block mm
1908
+ output_acc_block += tl.dot(values_block, dense_block, allow_tf32=allow_tf32, out_dtype=acc_dtype)
1909
+
1910
+ # move val/col_index ptrs to the next block in the row
1911
+ values_block_ptrs += values_nnz_stride
1912
+ col_index_nnz_ptr += col_indices_stride
1913
+
1914
+ if not alpha_is_one:
1915
+ output_acc_block *= alpha
1916
+
1917
+ # write back the result
1918
+ tl.store(output_ptrs, output_acc_block.to(output_ptr.dtype.element_ty))
1919
+
1920
+
1921
+ else:
1922
+ bsr_softmax = None # type: ignore[assignment]
1923
+ bsr_dense_mm = None # type: ignore[assignment]
1924
+ sampled_addmm = None # type: ignore[assignment]
1925
+ _scaled_dot_product_attention = None # type: ignore[assignment]
1926
+ _scatter_mm2 = None # type: ignore[assignment]
1927
+ _scatter_mm6 = None # type: ignore[assignment]
1928
+ _bsr_strided_addmm_kernel = None # type: ignore[assignment]
shared/package-files/02/02626d8a4274da23b9e9b62ac145513df5b0249a905506b9671d8b94a20d5bc8/logaddexp2_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API logaddexp2_out {
18
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logaddexp2")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logaddexp2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)")
24
+ static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
25
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
26
+ };
27
+
28
+ struct TORCH_API logaddexp2 {
29
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logaddexp2")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logaddexp2(Tensor self, Tensor other) -> Tensor")
35
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & other);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other);
37
+ };
38
+
39
+ }} // namespace at::_ops
shared/package-files/02/026283dbf8f6ab28f1aede20d07f13ec60653293e7da495eac2fd13aa3f6e289/exceptions.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """asyncio exceptions."""
2
+
3
+
4
+ __all__ = ('CancelledError', 'InvalidStateError', 'TimeoutError',
5
+ 'IncompleteReadError', 'LimitOverrunError',
6
+ 'SendfileNotAvailableError')
7
+
8
+
9
+ class CancelledError(BaseException):
10
+ """The Future or Task was cancelled."""
11
+
12
+
13
+ class TimeoutError(Exception):
14
+ """The operation exceeded the given deadline."""
15
+
16
+
17
+ class InvalidStateError(Exception):
18
+ """The operation is not allowed in this state."""
19
+
20
+
21
+ class SendfileNotAvailableError(RuntimeError):
22
+ """Sendfile syscall is not available.
23
+
24
+ Raised if OS does not support sendfile syscall for given socket or
25
+ file type.
26
+ """
27
+
28
+
29
+ class IncompleteReadError(EOFError):
30
+ """
31
+ Incomplete read error. Attributes:
32
+
33
+ - partial: read bytes string before the end of stream was reached
34
+ - expected: total number of expected bytes (or None if unknown)
35
+ """
36
+ def __init__(self, partial, expected):
37
+ r_expected = 'undefined' if expected is None else repr(expected)
38
+ super().__init__(f'{len(partial)} bytes read on a total of '
39
+ f'{r_expected} expected bytes')
40
+ self.partial = partial
41
+ self.expected = expected
42
+
43
+ def __reduce__(self):
44
+ return type(self), (self.partial, self.expected)
45
+
46
+
47
+ class LimitOverrunError(Exception):
48
+ """Reached the buffer limit while looking for a separator.
49
+
50
+ Attributes:
51
+ - consumed: total number of to be consumed bytes.
52
+ """
53
+ def __init__(self, message, consumed):
54
+ super().__init__(message)
55
+ self.consumed = consumed
56
+
57
+ def __reduce__(self):
58
+ return type(self), (self.args[0], self.consumed)
shared/package-files/02/0265538f01680aa1f77a46a16c0af7dae9629177abaed07bc9c3480de5f7da55/Types.h ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef THP_TYPES_INC
2
+ #define THP_TYPES_INC
3
+
4
+ #include <cstddef>
5
+
6
+ #ifndef INT64_MAX
7
+ #include <cstdint>
8
+ #endif
9
+
10
+ template <typename T>
11
+ struct THPTypeInfo {};
12
+
13
+ #endif