s42chen commited on
Commit
670b77e
·
verified ·
1 Parent(s): 4b936ae

Publish 11 evaluated Astra histories with reproducible checkpoint artifacts (part 3)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +7 -0
  2. shared/package-files/01/01f51cec2ddb3057ee8ba3c04318d33499fed576abcadc04cad9cbef9f6bfa8a/blob +24 -0
  3. shared/package-files/01/01f9e409ec619d27cda7b4fb0af70eaf386508800ba04184f0d828e4e1b384b4/blob +506 -0
  4. shared/package-files/01/01fc50fc2e0170a1bcabdc1ea72825cc879bcc3fe93e91913d1e1da2f97a251e/blob +491 -0
  5. shared/package-files/01/01fd8c8411cabda54d218e5b1517d899c375bb3b789f060570f81876cc62b4dd/blob +83 -0
  6. shared/package-files/01/01fdabaa17050a45975f62886e1522651c38eda28e0731ea559a1293abed319c/blob +125 -0
  7. shared/package-files/01/01ff193dff9cea1784e8d9a785c2d9473a7362d76d8565495256412afafcc095/blob +3 -0
  8. shared/package-files/02/02015ddd124031a908e80c420f37ceac68125fb51e023c6f3c7b374739369ece/blob +2266 -0
  9. shared/package-files/02/0201abc9e320bf0a23453582581971b0bf4f826a91e4cd1e0b1283ddfe214bf7/blob +30 -0
  10. shared/package-files/02/0203398ea9789f2c6b4c3e73970d030b5a5138b46d94bdadb5439223407486ac/blob +1106 -0
  11. shared/package-files/02/020417a134f7c95351600141013eb61c1a2efcaf411dfbad1ffd6554b906be69/blob +24 -0
  12. shared/package-files/02/020861c07567ff026c101068f931e6308293f73afe80126590b4dcb49ad3fde6/blob +1502 -0
  13. shared/package-files/02/020f6b521a01c9253a6dadf014b7ae67258c267cfd56401ff53404cd61b88545/blob +183 -0
  14. shared/package-files/02/02108ef43132cac13e3fe40917daf252d275821538ff498e461009e7da6839b5/blob +1274 -0
  15. shared/package-files/02/0212b936e3a9743f898c8cd73a5b2c13cfe248bc850001f3c8657fc35053eef0/blob +50 -0
  16. shared/package-files/02/02169eb141a5fbd8adeaebc6e9fb053ceafdca716919a4cc938b795d35fb67f4/blob +62 -0
  17. shared/package-files/02/0217e96269b35ecf856e039eb6839d9759618f5ab5398df43a0cfceb9a5ee5ac/blob +28 -0
  18. shared/package-files/02/021afcab2215adef14fc95512c72f405b4a86297498e8d8e51e135503e08d6dc/blob +102 -0
  19. shared/package-files/02/021bb387f2f520bdaa862561ad486d626a69305d3e0ebfd485e5c2a6dce6ff0b/blob +23 -0
  20. shared/package-files/02/021e1390d23f09f62a49783b3454ff24e812e665b75d0c72fc2c266781c15c41/blob +24 -0
  21. shared/package-files/02/021e1e444979d8be58ce9a7762466ff33564350d73bf7b38f2de2a075753c59a/blob +22 -0
  22. shared/package-files/02/021e4cf393e96bccd818eb4b3a2cd6d20ce5b63b376f89c3e7aa8579047bf795/blob +529 -0
  23. shared/package-files/02/021f73fada072546c4f63f8cf18a7181244ce4280b09cc15cc980b2d1176171a/blob +75 -0
  24. shared/package-files/02/0223395091042ca6c5c86ee83cada3b566d89860bb258b345898f2fb59340836/blob +0 -0
  25. shared/package-files/02/02244e7d6c5346b313ef92d9b2b04c25322cde4cbd9f5c779d49d7ccaa5920b3/blob +646 -0
  26. shared/package-files/02/02273b35c63ac179113f9494ebabc086b716ca5c1ef22efcbb69f37de9e7ec56/blob +105 -0
  27. shared/package-files/02/0229b075bf5ab357492996853541f63a158854155de9990927f58ae6c358f1c5/blob +76 -0
  28. shared/package-files/02/022bbf749fe8c6af98d555e7b39379bb92b55a78368730a04604620e14c08952/blob +30 -0
  29. shared/package-files/02/022c9bf5cde1ba759ce9b93a4ed8d0ce33c3242be07a965c8168601f8346d63c/blob +2188 -0
  30. shared/package-files/02/022dbf37ea549879e024ddeeb2231334eea47cb5855506b758e7addd585e844f/blob +427 -0
  31. shared/package-files/02/022e9d78388697050747d995be59086d76335990031ee3cb95a0630cad11db05/blob +27 -0
  32. shared/package-files/02/02318a5a89979435f62358c277844e909afc9d1b6bde87e6dcc757447dd84d3a/blob +220 -0
  33. shared/package-files/02/02320a4c11fda2fa2de2aef6eae7132a8bb5cb53acf065ed195a7369572d7b57/blob +83 -0
  34. shared/package-files/02/02361b49af673a5bffc9c64e4627dd9bb07e6fd29d282d4757e7062c3b6b27ec/blob +46 -0
  35. shared/package-files/02/023872fe9f03a25387cf2c17fc950cf0f990353df66e603c3a1cd3199dbccd86/blob +97 -0
  36. shared/package-files/02/023c3bb9dead92eb49f431aadc435a69e5ef7fa8e88e82ad34f426eabf0f0701/blob +28 -0
  37. shared/package-files/02/023c4e4d6552b9693e65e86713a27315531459a94e8b54493faaca5f5031ce7d/blob +28 -0
  38. shared/package-files/02/023d292c442b3477106e4b6755abaed01afc7b80c6878f4084d3478832a140e4/blob +1 -0
  39. shared/package-files/02/023e5dc747d51d3fc1ecdaa58958424c0f690bf440912ad93eba18eff584d1fd/blob +27 -0
  40. shared/package-files/02/02400a365357a04774bb02b8365809e39390d72c9c6f1a69bdd60be41923fe9e/blob +32 -0
  41. shared/package-files/02/0244e03291702df45024dcb5cacbc4f3d4cb30d72dfa7fd371c4ac61c42b4fbf/blob +0 -0
  42. shared/package-files/02/024944e5509d3fea002765b01b71a37e24e992ca1652e9ea40d0f121a2d8fdc3/EXPERIMENTS.md +75 -0
  43. shared/package-files/02/024983a51d08171a34adeb7dd6d44f614aab8107d0dfaee8913b7611ed959bad/blob +12 -0
  44. shared/package-files/02/024e76301aa38fc4e4c57e4cb51abbccb0d1fe8ddcd3f49d4095d4d550ef6d37/blob +26 -0
  45. shared/package-files/02/0250ba18275c1b7b4d54a7e5e5b2353d0408b938baae10783661d24123dc31d0/blob +324 -0
  46. shared/package-files/02/0258ffb6181b7487bacc36f2af8c1e88469f25fe6819e5f66167ade2c027eece/blob +72 -0
  47. shared/package-files/02/025a9531e3046e52d3e039c0be04f9a5a74651d7683a13c7c7ebd4c7dfb5996a/blob +39 -0
  48. shared/package-files/02/025abe9933a2b39873cf2aaa1790ce80eb9811aaa71086f504d32963a330ba53/blob +3 -0
  49. shared/package-files/02/025b702d601b96948b6bedb82af36ec58c4cd88795979a7677e928cc0f5027ed/blob +543 -0
  50. shared/package-files/02/025d4339487853fa1f3144127959734b20f7c7b4948cff5d72149a0541a67968/blob +0 -0
.gitattributes CHANGED
@@ -64,3 +64,10 @@ shared/package-files/00/007c7273f4f4d627c319bd19a7be1e7c291bf3de21e62e9ea14cb159
64
  shared/package-files/00/00a16df76cb2ba5d643c2536ffa3a63735da528cc101cbfd3f87ec553ae37efe/blob filter=lfs diff=lfs merge=lfs -text
65
  shared/package-files/01/01b20c23e9ca7c868b86b6bd109e153f4e21bd6aeec88522ef93976c6f4c2e7d/blob filter=lfs diff=lfs merge=lfs -text
66
  shared/package-files/01/01e0d376352c8f8de9e5e13cf97756480f3a3a3244ea4d681b96c966af352e17/blob filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
64
  shared/package-files/00/00a16df76cb2ba5d643c2536ffa3a63735da528cc101cbfd3f87ec553ae37efe/blob filter=lfs diff=lfs merge=lfs -text
65
  shared/package-files/01/01b20c23e9ca7c868b86b6bd109e153f4e21bd6aeec88522ef93976c6f4c2e7d/blob filter=lfs diff=lfs merge=lfs -text
66
  shared/package-files/01/01e0d376352c8f8de9e5e13cf97756480f3a3a3244ea4d681b96c966af352e17/blob filter=lfs diff=lfs merge=lfs -text
67
+ shared/package-files/01/01ff193dff9cea1784e8d9a785c2d9473a7362d76d8565495256412afafcc095/blob filter=lfs diff=lfs merge=lfs -text
68
+ shared/package-files/02/025abe9933a2b39873cf2aaa1790ce80eb9811aaa71086f504d32963a330ba53/blob filter=lfs diff=lfs merge=lfs -text
69
+ shared/package-files/02/027c9c728d0243cebc5db47a08653f57ef38a350ff6dc16b4432e6dce96db448/blob filter=lfs diff=lfs merge=lfs -text
70
+ shared/package-files/02/02932abef1b428fe1a063c4fe041cc8cdea63144a451b55b9713ae641557f546/blob filter=lfs diff=lfs merge=lfs -text
71
+ shared/package-files/02/02a09039e6e3d3872e8e9923e36d33d3dfe01972a11cce041a605fdea8efcc1d/blob filter=lfs diff=lfs merge=lfs -text
72
+ shared/package-files/03/0357322acd874a150831377106766c671fff671116bf5da477dd2ae6008b3563/blob filter=lfs diff=lfs merge=lfs -text
73
+ shared/package-files/03/03c8665837572b27a909b6fe91a1a565294425387f454e28276d1ab1c8a3929a/blob filter=lfs diff=lfs merge=lfs -text
shared/package-files/01/01f51cec2ddb3057ee8ba3c04318d33499fed576abcadc04cad9cbef9f6bfa8a/blob ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor upsample_trilinear3d(const at::Tensor & input, at::OptionalIntArrayRef output_size, bool align_corners, c10::optional<at::ArrayRef<double>> scale_factors);
21
+ TORCH_API at::Tensor upsample_trilinear3d_symint(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, bool align_corners, c10::optional<at::ArrayRef<double>> scale_factors);
22
+
23
+ } // namespace compositeimplicitautograd
24
+ } // namespace at
shared/package-files/01/01f9e409ec619d27cda7b4fb0af70eaf386508800ba04184f0d828e4e1b384b4/blob ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+
3
+ from typing import Any, cast, Dict, List, NamedTuple, Optional, Set, Tuple
4
+
5
+ import torch
6
+ import torch.distributed as dist
7
+ import torch.nn as nn
8
+
9
+ from torch.autograd.graph import Node
10
+ from torch.distributed.fsdp._common_utils import _named_parameters_with_duplicates
11
+ from torch.utils._pytree import tree_flatten, tree_unflatten
12
+ from torch.utils.hooks import RemovableHandle
13
+ from ._fsdp_api import MixedPrecisionPolicy
14
+ from ._fsdp_collectives import (
15
+ AllGatherResult,
16
+ foreach_all_gather,
17
+ foreach_all_gather_copy_out,
18
+ foreach_reduce_scatter,
19
+ )
20
+ from ._fsdp_common import FSDPMeshInfo, HSDPMeshInfo, TrainingState
21
+ from ._fsdp_param import FSDPParam, ParamModuleInfo, ShardedState
22
+
23
+ _ModuleToHandleDict = Dict[nn.Module, RemovableHandle] # for state dict
24
+
25
+
26
+ """
27
+ [Note: Overlapping all-gather copy-in and all-gather]
28
+ For implicit forward prefetching, we want to overlap the next copy-in with the
29
+ current all-gather. We do so using a separate copy-in stream. However, since
30
+ we have the all-gather input as a view into the output, we must make sure to
31
+ copy into different memory from the current all-gather's output. Thus, we keep
32
+ a reference to the current all-gather's output and have the next FSDP parameter
33
+ group free it after its copy-in. Finally, we have the last FSDP state flush the
34
+ reference to avoid holding onto memory after forward.
35
+ """
36
+
37
+
38
+ class FSDPCommContext:
39
+ """This has the communication state shared across FSDP states/parameter groups."""
40
+
41
+ def init(self):
42
+ # Setting the all-gather/reduce-scatter streams to be higher priority
43
+ # can help avoid some issues where their copies in/out are delayed and
44
+ # block computation
45
+ high_priority = -1
46
+ # All-gather state and copy-in stream allow overlapping the next
47
+ # copy-in with the current all-gather in forward; copy-in overlaps with
48
+ # reduce-scatter in backward without the separate copy-in stream
49
+ self.all_gather_copy_in_stream = torch.cuda.Stream(priority=high_priority)
50
+ self.all_gather_state: Optional[AllGatherState] = None
51
+ # All-gather stream allows overlapping next all-gather with current
52
+ # forward compute
53
+ self.all_gather_stream = torch.cuda.Stream(priority=high_priority)
54
+ # Reduce-scatter stream gives separate execution "thread" for post-
55
+ # backward logic like pre/post-gradient division and reduce-scatter
56
+ self.reduce_scatter_stream = torch.cuda.Stream(priority=high_priority)
57
+ # Post-forward order for explicit backward prefetching
58
+ self.post_forward_order: List[FSDPParamGroup] = [] # will cause ref cycles
59
+
60
+ def get_all_gather_streams(
61
+ self, training_state: TrainingState
62
+ ) -> Tuple[torch.cuda.Stream, torch.cuda.Stream]:
63
+ if training_state in (TrainingState.FORWARD, TrainingState.PRE_BACKWARD):
64
+ # Use separate streams for implicit prefetching
65
+ return self.all_gather_copy_in_stream, self.all_gather_stream
66
+ current_stream = torch.cuda.current_stream()
67
+ return current_stream, current_stream
68
+
69
+
70
+ # See [Note: Overlapping all-gather copy-in and all-gather]
71
+ class AllGatherState(NamedTuple):
72
+ all_gather_result: AllGatherResult
73
+ event: torch.cuda.Event # all-gather copy-out
74
+
75
+
76
+ class FSDPParamGroup:
77
+ """This class represents a parameter group to communicate together."""
78
+
79
+ _orig_dtype: torch.dtype
80
+ _reduce_dtype: Optional[torch.dtype]
81
+
82
+ def __init__(
83
+ self,
84
+ params: List[nn.Parameter],
85
+ module: nn.Module,
86
+ mesh_info: FSDPMeshInfo,
87
+ post_forward_mesh_info: Optional[FSDPMeshInfo],
88
+ device: torch.device,
89
+ mp_policy: MixedPrecisionPolicy,
90
+ ):
91
+ self.module = module # permit ref cycle because 1:1 lifetime
92
+ param_module_infos = _get_param_module_infos(params, module)
93
+ self.fsdp_params = [
94
+ FSDPParam(
95
+ param, module_info, mesh_info, post_forward_mesh_info, device, mp_policy
96
+ )
97
+ for param, module_info in zip(params, param_module_infos)
98
+ ]
99
+ self.mesh_info = mesh_info
100
+ self.post_forward_mesh_info = post_forward_mesh_info
101
+ self.device = device
102
+ self.mp_policy = mp_policy
103
+ self._training_state = TrainingState.IDLE
104
+ # Group's sharded state always matches its parameters' sharded states
105
+ self._sharded_state = ShardedState.SHARDED
106
+ self._module_fqn: Optional[str] = None # prefixed from root module
107
+
108
+ # - Hook state
109
+ self._module_to_pre_save_state_dict_hook_handle: _ModuleToHandleDict = {}
110
+ self._module_to_pre_load_state_dict_hook_handle: _ModuleToHandleDict = {}
111
+
112
+ # - Communication and communication/computation overlap
113
+ self.comm_ctx = FSDPCommContext()
114
+ # Group's indices in the shared post-forward order
115
+ self._post_forward_indices: List[int] = []
116
+ # Used to avoid mistargeted backward prefetches when the module is used
117
+ # in forward but not in backward: for each forward, we record a tuple
118
+ # of the output's grad fns and later query the autograd engine whether
119
+ # any grad fn will execute in the current backward to know to prefetch.
120
+ self.all_forward_output_grad_fns: Set[Tuple[Node, ...]] = set()
121
+ # Whether to reduce-scatter or all-reduce gradients, respectively
122
+ # (can be set to false to save communication during gradient
123
+ # accumulation); all-reducing without reduce-scatter is disallowed
124
+ self.reduce_scatter_grads: bool = True
125
+ self.all_reduce_grads: bool = True
126
+
127
+ # - CUDA events for stream synchronization
128
+ # Holds the all-gather output buffer, sync objects, and metadata
129
+ self._all_gather_result: Optional[AllGatherResult] = None
130
+ # Holds the reduce-scatter view-out CUDA event that marks the end of
131
+ # the group's post-backward (e.g. reduce-scatter and div), which should
132
+ # be waited on at the end of backward
133
+ self._reduce_scatter_view_out_event: Optional[torch.cuda.Event] = None
134
+ # Holds the reshard-after-forward CUDA event when resharding to a
135
+ # different world size, which should be waited on in the next unshard
136
+ self._reshard_after_forward_event: Optional[torch.cuda.Event] = None
137
+
138
+ # Initialization #
139
+ def _init_mp_dtypes(self) -> None:
140
+ for fsdp_param in self.fsdp_params:
141
+ fsdp_param.init_dtype_attrs(self.mp_policy)
142
+ orig_dtypes = {fsdp_param.orig_dtype for fsdp_param in self.fsdp_params}
143
+ if len(orig_dtypes) != 1:
144
+ # This can be relaxed if we copy-out for the reduce-scatter
145
+ raise AssertionError(
146
+ f"FSDP expects uniform original parameter dtype but got {orig_dtypes}"
147
+ )
148
+ self._orig_dtype = next(iter(orig_dtypes))
149
+ reduce_dtypes = {fsdp_param.reduce_dtype for fsdp_param in self.fsdp_params}
150
+ if len(reduce_dtypes) != 1:
151
+ # This can be relaxed if we issue one reduce-scatter per reduce
152
+ # dtype (but we would need a way for users to specify multiple
153
+ # reduce dtypes)
154
+ raise AssertionError(
155
+ f"FSDP expects uniform reduce dtype but got {reduce_dtypes}"
156
+ )
157
+ self._reduce_dtype = next(iter(reduce_dtypes))
158
+
159
+ def _init_grad_divide_factors(self):
160
+ data_parallel_world_size = 1
161
+ data_parallel_world_size *= self.mesh_info.shard_mesh_size
162
+ if isinstance(self.mesh_info, HSDPMeshInfo):
163
+ data_parallel_world_size *= self.mesh_info.replicate_mesh_size
164
+ if self._reduce_dtype == torch.float32:
165
+ # Use NCCL's AVG op to divide after reduction since it is more
166
+ # performant and fp32 has sufficient precision
167
+ self._grad_divide_factors: Optional[Tuple[float, float]] = None
168
+ return
169
+ # For N data parallel workers, each worker computes g_i, and they
170
+ # collectively reduce (g_1 + ... + g_N) / N. To avoid overflow and
171
+ # underflow, we divide by ~sqrt(N) before and after the reduction.
172
+ factor: int = 1
173
+ while (
174
+ data_parallel_world_size % factor == 0
175
+ and data_parallel_world_size / factor > factor
176
+ ):
177
+ factor *= 2
178
+ factor = float(factor)
179
+ self._grad_divide_factors = (factor, data_parallel_world_size / factor)
180
+
181
+ def lazy_init(self):
182
+ param_names_on_meta = [
183
+ fsdp_param._param_fqn
184
+ for fsdp_param in self.fsdp_params
185
+ if fsdp_param.sharded_param.device.type == "meta"
186
+ ]
187
+ if param_names_on_meta:
188
+ raise RuntimeError(
189
+ "FSDP parameters should be materialized from meta device before training, "
190
+ f"but the following were still on meta device: {param_names_on_meta}\n"
191
+ "For example, call module.to_empty(device) to materialize to device and "
192
+ "call module.reset_parameters() on each module to initialize values."
193
+ )
194
+ # Initialize mixed precision attributes lazily in case the user changes
195
+ # the parameter dtypes after construction time but before forward
196
+ self._init_mp_dtypes()
197
+ self._init_grad_divide_factors()
198
+ self._register_state_dict_hooks()
199
+
200
+ # Runtime #
201
+ def unshard(self, async_op: bool = False):
202
+ if self._all_gather_result is not None: # already called, pending wait
203
+ return
204
+ if self.is_unsharded:
205
+ return # no-op
206
+ if self._reshard_after_forward_event is not None:
207
+ # Resharded parameter data is allocated in the default stream and
208
+ # used in the all-gather streams
209
+ self._wait_all_gather_streams_on_event(self._reshard_after_forward_event)
210
+ self._reshard_after_forward_event = None
211
+ self._all_gather_result = foreach_all_gather(
212
+ self.fsdp_params,
213
+ self._all_gather_process_group,
214
+ async_op,
215
+ *self.comm_ctx.get_all_gather_streams(self._training_state),
216
+ self.device,
217
+ )
218
+
219
+ def wait_for_unshard(self):
220
+ """
221
+ 1. In forward with implict prefetching, to overlap the current copy-out
222
+ with the next all-gather, we save a reference to the current all-gather
223
+ result to free after the next copy-out.
224
+ 2. Otherwise (explicit prefetching or in backward), we free the
225
+ all-gather result immediately after the current copy-out since we can
226
+ already overlap the current copy-out with the previous reduce-scatter.
227
+ """
228
+ if not self._all_gather_result:
229
+ return # no preceding unshard
230
+ if self._training_state == TrainingState.FORWARD: # implicit prefetch
231
+ if prev_all_gather_state := self.comm_ctx.all_gather_state:
232
+ self._wait_all_gather_streams_on_event(prev_all_gather_state.event)
233
+ self.comm_ctx.all_gather_state = None # free the all-gather result
234
+ foreach_all_gather_copy_out(
235
+ self._all_gather_result, self.fsdp_params, self._all_gather_process_group
236
+ )
237
+ for fsdp_param in self.fsdp_params:
238
+ fsdp_param.init_unsharded_param() # no-op after 1st call
239
+ self._to_unsharded()
240
+ all_gather_copy_out_event = torch.cuda.Event()
241
+ all_gather_copy_out_event.record()
242
+ if self._training_state == TrainingState.FORWARD:
243
+ self.comm_ctx.all_gather_state = AllGatherState(
244
+ self._all_gather_result, all_gather_copy_out_event
245
+ )
246
+ else:
247
+ self._wait_all_gather_streams_on_event(all_gather_copy_out_event)
248
+ self._all_gather_result = None # free unless saved in `all_gather_state`
249
+
250
+ def _wait_all_gather_streams_on_event(self, event: torch.cuda.Event):
251
+ self.comm_ctx.all_gather_copy_in_stream.wait_event(event)
252
+ self.comm_ctx.all_gather_stream.wait_event(event)
253
+
254
+ def reshard(self):
255
+ if self._training_state == TrainingState.FORWARD:
256
+ if not self._reshard_after_forward:
257
+ return
258
+ if self._use_post_forward_mesh:
259
+ self._to_sharded_post_forward()
260
+ self._reshard_after_forward_event = torch.cuda.Event()
261
+ self._reshard_after_forward_event.record()
262
+ return
263
+ self._to_sharded()
264
+
265
+ def pre_forward(
266
+ self, module: nn.Module, args: Tuple[Any, ...], kwargs: Dict[str, Any]
267
+ ) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
268
+ with torch.profiler.record_function("FSDP::pre_forward"):
269
+ self._training_state = TrainingState.FORWARD
270
+ self.unshard()
271
+ self.wait_for_unshard()
272
+ args, kwargs = self._register_post_backward_hook(args, kwargs)
273
+ return args, kwargs
274
+
275
+ def post_forward(self, module: nn.Module, input: Any, output: Any):
276
+ with torch.profiler.record_function("FSDP::post_forward"):
277
+ self.reshard()
278
+ self._record_post_forward()
279
+ self._training_state = TrainingState.IDLE
280
+ return output
281
+
282
+ def _record_post_forward(self) -> None:
283
+ # Since a group has one pre-backward unshard for each forward call
284
+ # before the backward, we record each usage (with multiplicity)
285
+ post_forward_index = len(self.comm_ctx.post_forward_order)
286
+ self.comm_ctx.post_forward_order.append(self)
287
+ self._post_forward_indices.append(post_forward_index)
288
+
289
+ def pre_backward(self, forward_grad_fns: Tuple[Any, ...], *unused: Any):
290
+ with torch.profiler.record_function("FSDP::pre_backward"):
291
+ self._training_state = TrainingState.PRE_BACKWARD
292
+ self.unshard() # no-op if prefetched
293
+ self.wait_for_unshard()
294
+ # Can be already removed if running multiple `backward`s
295
+ self.all_forward_output_grad_fns.discard(forward_grad_fns)
296
+ self._prefetch_unshard()
297
+
298
+ def post_backward(self, *unused: Any):
299
+ self._training_state = TrainingState.POST_BACKWARD
300
+ with torch.profiler.record_function("FSDP::post_backward_reshard"):
301
+ if not self.reduce_scatter_grads:
302
+ self.reshard()
303
+ return
304
+ # Save the autograd-computed gradients before resharding to only
305
+ # access the unsharded parameters when their data is present
306
+ fsdp_params_with_grad: List[FSDPParam] = []
307
+ unsharded_grads: List[torch.Tensor] = []
308
+ for fsdp_param in self.fsdp_params:
309
+ if fsdp_param.unsharded_param.grad is not None:
310
+ fsdp_params_with_grad.append(fsdp_param)
311
+ unsharded_grads.append(fsdp_param.unsharded_grad_data)
312
+ fsdp_param.unsharded_param.grad = None
313
+ self.reshard()
314
+ if len(fsdp_params_with_grad) == 0:
315
+ return
316
+ with torch.profiler.record_function("FSDP::post_backward_reduce"):
317
+ self._reduce_scatter_view_out_event = foreach_reduce_scatter(
318
+ fsdp_params_with_grad,
319
+ unsharded_grads,
320
+ self._reduce_scatter_process_group,
321
+ self.comm_ctx.reduce_scatter_stream,
322
+ self._orig_dtype,
323
+ self._reduce_dtype,
324
+ self.device,
325
+ self._grad_divide_factors,
326
+ )
327
+
328
+ def finalize_backward(self):
329
+ if self._reduce_scatter_view_out_event is not None:
330
+ torch.cuda.current_stream().wait_event(self._reduce_scatter_view_out_event)
331
+ self._reduce_scatter_view_out_event = None
332
+ self._training_state = TrainingState.IDLE
333
+ self._post_forward_indices.clear()
334
+ self.all_forward_output_grad_fns.clear()
335
+
336
+ def _prefetch_unshard(self):
337
+ if self._training_state == TrainingState.PRE_BACKWARD:
338
+ if not self._post_forward_indices:
339
+ # Can be cleared if running multiple `backward`s
340
+ return
341
+ curr_index = self._post_forward_indices.pop()
342
+ if (target_index := curr_index - 1) < 0:
343
+ return
344
+ target_fsdp_param_group = self.comm_ctx.post_forward_order[target_index]
345
+ if any(
346
+ torch._C._will_engine_execute_node(grad_fn) # type: ignore[attr-defined]
347
+ for grad_fns in target_fsdp_param_group.all_forward_output_grad_fns
348
+ for grad_fn in grad_fns
349
+ ):
350
+ with torch.profiler.record_function(
351
+ "FSDP::backward_prefetch"
352
+ ), target_fsdp_param_group.use_training_state(
353
+ TrainingState.PRE_BACKWARD
354
+ ):
355
+ target_fsdp_param_group.unshard()
356
+
357
+ # Utilities #
358
+ def _to_sharded(self):
359
+ if not self.is_sharded:
360
+ for fsdp_param in self.fsdp_params:
361
+ fsdp_param.to_sharded()
362
+ self._sharded_state = ShardedState.SHARDED
363
+
364
+ def _to_sharded_post_forward(self):
365
+ if not self.is_sharded_post_forward:
366
+ for fsdp_param in self.fsdp_params:
367
+ fsdp_param.to_sharded_post_forward()
368
+ self._sharded_state = ShardedState.SHARDED_POST_FORWARD
369
+
370
+ def _to_unsharded(self):
371
+ if not self.is_unsharded:
372
+ for fsdp_param in self.fsdp_params:
373
+ fsdp_param.to_unsharded()
374
+ self._sharded_state = ShardedState.UNSHARDED
375
+
376
+ @property
377
+ def is_sharded(self) -> bool:
378
+ return self._sharded_state == ShardedState.SHARDED
379
+
380
+ @property
381
+ def is_sharded_post_forward(self) -> bool:
382
+ return self._sharded_state == ShardedState.SHARDED_POST_FORWARD
383
+
384
+ @property
385
+ def is_unsharded(self) -> bool:
386
+ return self._sharded_state == ShardedState.UNSHARDED
387
+
388
+ @contextlib.contextmanager
389
+ def use_training_state(self, training_state: TrainingState):
390
+ old_training_state = self._training_state
391
+ self._training_state = training_state
392
+ try:
393
+ yield
394
+ finally:
395
+ self._training_state = old_training_state
396
+
397
+ # Hook Registration #
398
+ def _register_post_backward_hook(
399
+ self, args: Tuple[Any, ...], kwargs: Dict[str, Any]
400
+ ) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
401
+ if not torch.is_grad_enabled():
402
+ return args, kwargs
403
+ args_list, args_spec = tree_flatten(args)
404
+ kwargs_list, kwargs_spec = tree_flatten(kwargs)
405
+ args_kwargs_list = list(args_list) + list(kwargs_list)
406
+ inp_tensor_indices: List[int] = []
407
+ inp_tensors: List[torch.Tensor] = []
408
+ for i, obj in enumerate(args_kwargs_list):
409
+ if torch.is_tensor(obj) and obj.requires_grad:
410
+ inp_tensor_indices.append(i)
411
+ inp_tensors.append(obj)
412
+ if len(inp_tensors) == 0:
413
+ return args, kwargs # no tensors that require gradients
414
+ inp_tensors = RegisterPostBackwardFunction.apply(self, *inp_tensors)
415
+ for inp_tensor_idx, inp_tensor in zip(inp_tensor_indices, inp_tensors):
416
+ args_kwargs_list[inp_tensor_idx] = inp_tensor
417
+ args_list = args_kwargs_list[: len(args_list)]
418
+ kwargs_list = args_kwargs_list[len(args_list) :]
419
+ args = tree_unflatten(args_list, args_spec)
420
+ kwargs = tree_unflatten(kwargs_list, kwargs_spec)
421
+ return args, kwargs
422
+
423
+ def _register_state_dict_hooks(self) -> None:
424
+ assert len(self._module_to_pre_save_state_dict_hook_handle) == 0
425
+ assert len(self._module_to_pre_load_state_dict_hook_handle) == 0
426
+ modules_with_fsdp_params: Set[nn.Module] = {
427
+ fsdp_param._module_info.module for fsdp_param in self.fsdp_params
428
+ }
429
+
430
+ def to_sharded_hook(*args: Any, **kwargs: Any) -> None:
431
+ self._to_sharded()
432
+
433
+ for module in modules_with_fsdp_params:
434
+ self._module_to_pre_save_state_dict_hook_handle[
435
+ module
436
+ ] = module.register_state_dict_pre_hook(to_sharded_hook)
437
+ self._module_to_pre_load_state_dict_hook_handle[
438
+ module
439
+ ] = module._register_load_state_dict_pre_hook(to_sharded_hook)
440
+
441
+ # Properties #
442
+ @property
443
+ def _reshard_after_forward(self) -> bool:
444
+ return self.post_forward_mesh_info is not None
445
+
446
+ @property
447
+ def _use_post_forward_mesh(self) -> bool:
448
+ return (
449
+ self._reshard_after_forward
450
+ and self.mesh_info != self.post_forward_mesh_info
451
+ )
452
+
453
+ @property
454
+ def _all_gather_process_group(self) -> dist.ProcessGroup:
455
+ mesh_info = (
456
+ cast(FSDPMeshInfo, self.post_forward_mesh_info)
457
+ if self.is_sharded_post_forward
458
+ else self.mesh_info
459
+ )
460
+ assert isinstance(mesh_info, FSDPMeshInfo)
461
+ return mesh_info.shard_process_group
462
+
463
+ @property
464
+ def _reduce_scatter_process_group(self) -> dist.ProcessGroup:
465
+ mesh_info = self.mesh_info
466
+ assert isinstance(mesh_info, FSDPMeshInfo)
467
+ return mesh_info.shard_process_group
468
+
469
+
470
+ def _get_param_module_infos(
471
+ params: List[nn.Parameter], module: nn.Module
472
+ ) -> List[ParamModuleInfo]:
473
+ """
474
+ Shared parameter: lin1.weight = lin2.weight
475
+ Shared module: mlp.lin1 = mlp.lin2
476
+ We do not remove duplicates when traversing both modules and parameters to
477
+ find shared modules' parameters and shared parameters within a module.
478
+ """
479
+ params_set = set(params)
480
+ param_to_module_info: Dict[nn.Parameter, ParamModuleInfo] = {}
481
+ for _, submodule in module.named_modules(remove_duplicate=False):
482
+ for param_name, param in _named_parameters_with_duplicates(
483
+ submodule, recurse=False
484
+ ):
485
+ if param in params_set:
486
+ if param not in param_to_module_info:
487
+ param_to_module_info[param] = ParamModuleInfo(submodule, param_name)
488
+ else:
489
+ param_to_module_info[param].shared_modules.append(submodule)
490
+ param_to_module_info[param].shared_param_names.append(param_name)
491
+ if len(param_to_module_info) != len(params):
492
+ raise AssertionError(f"Some parameters are not in the module tree of {module}")
493
+ return [param_to_module_info[param] for param in params]
494
+
495
+
496
+ class RegisterPostBackwardFunction(torch.autograd.Function):
497
+ @staticmethod
498
+ def forward(ctx, param_group: FSDPParamGroup, *inputs: torch.Tensor):
499
+ # All tensors in `inputs` should require gradient
500
+ ctx.param_group = param_group
501
+ return inputs
502
+
503
+ @staticmethod
504
+ def backward(ctx, *grads: torch.Tensor):
505
+ ctx.param_group.post_backward()
506
+ return (None,) + grads
shared/package-files/01/01fc50fc2e0170a1bcabdc1ea72825cc879bcc3fe93e91913d1e1da2f97a251e/blob ADDED
@@ -0,0 +1,491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pathlib
3
+ import random
4
+ import tempfile
5
+
6
+ import pytest
7
+
8
+ import networkx as nx
9
+ from networkx.utils.decorators import (
10
+ argmap,
11
+ not_implemented_for,
12
+ np_random_state,
13
+ open_file,
14
+ py_random_state,
15
+ )
16
+ from networkx.utils.misc import PythonRandomInterface
17
+
18
+
19
+ def test_not_implemented_decorator():
20
+ @not_implemented_for("directed")
21
+ def test_d(G):
22
+ pass
23
+
24
+ test_d(nx.Graph())
25
+ with pytest.raises(nx.NetworkXNotImplemented):
26
+ test_d(nx.DiGraph())
27
+
28
+ @not_implemented_for("undirected")
29
+ def test_u(G):
30
+ pass
31
+
32
+ test_u(nx.DiGraph())
33
+ with pytest.raises(nx.NetworkXNotImplemented):
34
+ test_u(nx.Graph())
35
+
36
+ @not_implemented_for("multigraph")
37
+ def test_m(G):
38
+ pass
39
+
40
+ test_m(nx.Graph())
41
+ with pytest.raises(nx.NetworkXNotImplemented):
42
+ test_m(nx.MultiGraph())
43
+
44
+ @not_implemented_for("graph")
45
+ def test_g(G):
46
+ pass
47
+
48
+ test_g(nx.MultiGraph())
49
+ with pytest.raises(nx.NetworkXNotImplemented):
50
+ test_g(nx.Graph())
51
+
52
+ # not MultiDiGraph (multiple arguments => AND)
53
+ @not_implemented_for("directed", "multigraph")
54
+ def test_not_md(G):
55
+ pass
56
+
57
+ test_not_md(nx.Graph())
58
+ test_not_md(nx.DiGraph())
59
+ test_not_md(nx.MultiGraph())
60
+ with pytest.raises(nx.NetworkXNotImplemented):
61
+ test_not_md(nx.MultiDiGraph())
62
+
63
+ # Graph only (multiple decorators => OR)
64
+ @not_implemented_for("directed")
65
+ @not_implemented_for("multigraph")
66
+ def test_graph_only(G):
67
+ pass
68
+
69
+ test_graph_only(nx.Graph())
70
+ with pytest.raises(nx.NetworkXNotImplemented):
71
+ test_graph_only(nx.DiGraph())
72
+ with pytest.raises(nx.NetworkXNotImplemented):
73
+ test_graph_only(nx.MultiGraph())
74
+ with pytest.raises(nx.NetworkXNotImplemented):
75
+ test_graph_only(nx.MultiDiGraph())
76
+
77
+ with pytest.raises(ValueError):
78
+ not_implemented_for("directed", "undirected")
79
+
80
+ with pytest.raises(ValueError):
81
+ not_implemented_for("multigraph", "graph")
82
+
83
+
84
+ def test_not_implemented_decorator_key():
85
+ with pytest.raises(KeyError):
86
+
87
+ @not_implemented_for("foo")
88
+ def test1(G):
89
+ pass
90
+
91
+ test1(nx.Graph())
92
+
93
+
94
+ def test_not_implemented_decorator_raise():
95
+ with pytest.raises(nx.NetworkXNotImplemented):
96
+
97
+ @not_implemented_for("graph")
98
+ def test1(G):
99
+ pass
100
+
101
+ test1(nx.Graph())
102
+
103
+
104
+ class TestOpenFileDecorator:
105
+ def setup_method(self):
106
+ self.text = ["Blah... ", "BLAH ", "BLAH!!!!"]
107
+ self.fobj = tempfile.NamedTemporaryFile("wb+", delete=False)
108
+ self.name = self.fobj.name
109
+
110
+ def teardown_method(self):
111
+ self.fobj.close()
112
+ os.unlink(self.name)
113
+
114
+ def write(self, path):
115
+ for text in self.text:
116
+ path.write(text.encode("ascii"))
117
+
118
+ @open_file(1, "r")
119
+ def read(self, path):
120
+ return path.readlines()[0]
121
+
122
+ @staticmethod
123
+ @open_file(0, "wb")
124
+ def writer_arg0(path):
125
+ path.write(b"demo")
126
+
127
+ @open_file(1, "wb+")
128
+ def writer_arg1(self, path):
129
+ self.write(path)
130
+
131
+ @open_file(2, "wb")
132
+ def writer_arg2default(self, x, path=None):
133
+ if path is None:
134
+ with tempfile.NamedTemporaryFile("wb+") as fh:
135
+ self.write(fh)
136
+ else:
137
+ self.write(path)
138
+
139
+ @open_file(4, "wb")
140
+ def writer_arg4default(self, x, y, other="hello", path=None, **kwargs):
141
+ if path is None:
142
+ with tempfile.NamedTemporaryFile("wb+") as fh:
143
+ self.write(fh)
144
+ else:
145
+ self.write(path)
146
+
147
+ @open_file("path", "wb")
148
+ def writer_kwarg(self, **kwargs):
149
+ path = kwargs.get("path", None)
150
+ if path is None:
151
+ with tempfile.NamedTemporaryFile("wb+") as fh:
152
+ self.write(fh)
153
+ else:
154
+ self.write(path)
155
+
156
+ def test_writer_arg0_str(self):
157
+ self.writer_arg0(self.name)
158
+
159
+ def test_writer_arg0_fobj(self):
160
+ self.writer_arg0(self.fobj)
161
+
162
+ def test_writer_arg0_pathlib(self):
163
+ self.writer_arg0(pathlib.Path(self.name))
164
+
165
+ def test_writer_arg1_str(self):
166
+ self.writer_arg1(self.name)
167
+ assert self.read(self.name) == "".join(self.text)
168
+
169
+ def test_writer_arg1_fobj(self):
170
+ self.writer_arg1(self.fobj)
171
+ assert not self.fobj.closed
172
+ self.fobj.close()
173
+ assert self.read(self.name) == "".join(self.text)
174
+
175
+ def test_writer_arg2default_str(self):
176
+ self.writer_arg2default(0, path=None)
177
+ self.writer_arg2default(0, path=self.name)
178
+ assert self.read(self.name) == "".join(self.text)
179
+
180
+ def test_writer_arg2default_fobj(self):
181
+ self.writer_arg2default(0, path=self.fobj)
182
+ assert not self.fobj.closed
183
+ self.fobj.close()
184
+ assert self.read(self.name) == "".join(self.text)
185
+
186
+ def test_writer_arg2default_fobj_path_none(self):
187
+ self.writer_arg2default(0, path=None)
188
+
189
+ def test_writer_arg4default_fobj(self):
190
+ self.writer_arg4default(0, 1, dog="dog", other="other")
191
+ self.writer_arg4default(0, 1, dog="dog", other="other", path=self.name)
192
+ assert self.read(self.name) == "".join(self.text)
193
+
194
+ def test_writer_kwarg_str(self):
195
+ self.writer_kwarg(path=self.name)
196
+ assert self.read(self.name) == "".join(self.text)
197
+
198
+ def test_writer_kwarg_fobj(self):
199
+ self.writer_kwarg(path=self.fobj)
200
+ self.fobj.close()
201
+ assert self.read(self.name) == "".join(self.text)
202
+
203
+ def test_writer_kwarg_path_none(self):
204
+ self.writer_kwarg(path=None)
205
+
206
+
207
+ class TestRandomState:
208
+ @classmethod
209
+ def setup_class(cls):
210
+ global np
211
+ np = pytest.importorskip("numpy")
212
+
213
+ @np_random_state(1)
214
+ def instantiate_np_random_state(self, random_state):
215
+ assert isinstance(random_state, np.random.RandomState)
216
+ return random_state.random_sample()
217
+
218
+ @py_random_state(1)
219
+ def instantiate_py_random_state(self, random_state):
220
+ assert isinstance(random_state, (random.Random, PythonRandomInterface))
221
+ return random_state.random()
222
+
223
+ def test_random_state_None(self):
224
+ np.random.seed(42)
225
+ rv = np.random.random_sample()
226
+ np.random.seed(42)
227
+ assert rv == self.instantiate_np_random_state(None)
228
+
229
+ random.seed(42)
230
+ rv = random.random()
231
+ random.seed(42)
232
+ assert rv == self.instantiate_py_random_state(None)
233
+
234
+ def test_random_state_np_random(self):
235
+ np.random.seed(42)
236
+ rv = np.random.random_sample()
237
+ np.random.seed(42)
238
+ assert rv == self.instantiate_np_random_state(np.random)
239
+ np.random.seed(42)
240
+ assert rv == self.instantiate_py_random_state(np.random)
241
+
242
+ def test_random_state_int(self):
243
+ np.random.seed(42)
244
+ np_rv = np.random.random_sample()
245
+ random.seed(42)
246
+ py_rv = random.random()
247
+
248
+ np.random.seed(42)
249
+ seed = 1
250
+ rval = self.instantiate_np_random_state(seed)
251
+ rval_expected = np.random.RandomState(seed).rand()
252
+ assert rval, rval_expected
253
+ # test that global seed wasn't changed in function
254
+ assert np_rv == np.random.random_sample()
255
+
256
+ random.seed(42)
257
+ rval = self.instantiate_py_random_state(seed)
258
+ rval_expected = random.Random(seed).random()
259
+ assert rval, rval_expected
260
+ # test that global seed wasn't changed in function
261
+ assert py_rv == random.random()
262
+
263
+ def test_random_state_np_random_RandomState(self):
264
+ np.random.seed(42)
265
+ np_rv = np.random.random_sample()
266
+
267
+ np.random.seed(42)
268
+ seed = 1
269
+ rng = np.random.RandomState(seed)
270
+ rval = self.instantiate_np_random_state(seed)
271
+ rval_expected = np.random.RandomState(seed).rand()
272
+ assert rval, rval_expected
273
+
274
+ rval = self.instantiate_py_random_state(seed)
275
+ rval_expected = np.random.RandomState(seed).rand()
276
+ assert rval, rval_expected
277
+ # test that global seed wasn't changed in function
278
+ assert np_rv == np.random.random_sample()
279
+
280
+ def test_random_state_py_random(self):
281
+ seed = 1
282
+ rng = random.Random(seed)
283
+ rv = self.instantiate_py_random_state(rng)
284
+ assert rv, random.Random(seed).random()
285
+
286
+ pytest.raises(ValueError, self.instantiate_np_random_state, rng)
287
+
288
+
289
+ def test_random_state_string_arg_index():
290
+ with pytest.raises(nx.NetworkXError):
291
+
292
+ @np_random_state("a")
293
+ def make_random_state(rs):
294
+ pass
295
+
296
+ rstate = make_random_state(1)
297
+
298
+
299
+ def test_py_random_state_string_arg_index():
300
+ with pytest.raises(nx.NetworkXError):
301
+
302
+ @py_random_state("a")
303
+ def make_random_state(rs):
304
+ pass
305
+
306
+ rstate = make_random_state(1)
307
+
308
+
309
+ def test_random_state_invalid_arg_index():
310
+ with pytest.raises(nx.NetworkXError):
311
+
312
+ @np_random_state(2)
313
+ def make_random_state(rs):
314
+ pass
315
+
316
+ rstate = make_random_state(1)
317
+
318
+
319
+ def test_py_random_state_invalid_arg_index():
320
+ with pytest.raises(nx.NetworkXError):
321
+
322
+ @py_random_state(2)
323
+ def make_random_state(rs):
324
+ pass
325
+
326
+ rstate = make_random_state(1)
327
+
328
+
329
+ class TestArgmap:
330
+ class ArgmapError(RuntimeError):
331
+ pass
332
+
333
+ def test_trivial_function(self):
334
+ def do_not_call(x):
335
+ raise ArgmapError("do not call this function")
336
+
337
+ @argmap(do_not_call)
338
+ def trivial_argmap():
339
+ return 1
340
+
341
+ assert trivial_argmap() == 1
342
+
343
+ def test_trivial_iterator(self):
344
+ def do_not_call(x):
345
+ raise ArgmapError("do not call this function")
346
+
347
+ @argmap(do_not_call)
348
+ def trivial_argmap():
349
+ yield from (1, 2, 3)
350
+
351
+ assert tuple(trivial_argmap()) == (1, 2, 3)
352
+
353
+ def test_contextmanager(self):
354
+ container = []
355
+
356
+ def contextmanager(x):
357
+ nonlocal container
358
+ return x, lambda: container.append(x)
359
+
360
+ @argmap(contextmanager, 0, 1, 2, try_finally=True)
361
+ def foo(x, y, z):
362
+ return x, y, z
363
+
364
+ x, y, z = foo("a", "b", "c")
365
+
366
+ # context exits are called in reverse
367
+ assert container == ["c", "b", "a"]
368
+
369
+ def test_tryfinally_generator(self):
370
+ container = []
371
+
372
+ def singleton(x):
373
+ return (x,)
374
+
375
+ with pytest.raises(nx.NetworkXError):
376
+
377
+ @argmap(singleton, 0, 1, 2, try_finally=True)
378
+ def foo(x, y, z):
379
+ yield from (x, y, z)
380
+
381
+ @argmap(singleton, 0, 1, 2)
382
+ def foo(x, y, z):
383
+ return x + y + z
384
+
385
+ q = foo("a", "b", "c")
386
+
387
+ assert q == ("a", "b", "c")
388
+
389
+ def test_actual_vararg(self):
390
+ @argmap(lambda x: -x, 4)
391
+ def foo(x, y, *args):
392
+ return (x, y) + tuple(args)
393
+
394
+ assert foo(1, 2, 3, 4, 5, 6) == (1, 2, 3, 4, -5, 6)
395
+
396
+ def test_signature_destroying_intermediate_decorator(self):
397
+ def add_one_to_first_bad_decorator(f):
398
+ """Bad because it doesn't wrap the f signature (clobbers it)"""
399
+
400
+ def decorated(a, *args, **kwargs):
401
+ return f(a + 1, *args, **kwargs)
402
+
403
+ return decorated
404
+
405
+ add_two_to_second = argmap(lambda b: b + 2, 1)
406
+
407
+ @add_two_to_second
408
+ @add_one_to_first_bad_decorator
409
+ def add_one_and_two(a, b):
410
+ return a, b
411
+
412
+ assert add_one_and_two(5, 5) == (6, 7)
413
+
414
+ def test_actual_kwarg(self):
415
+ @argmap(lambda x: -x, "arg")
416
+ def foo(*, arg):
417
+ return arg
418
+
419
+ assert foo(arg=3) == -3
420
+
421
+ def test_nested_tuple(self):
422
+ def xform(x, y):
423
+ u, v = y
424
+ return x + u + v, (x + u, x + v)
425
+
426
+ # we're testing args and kwargs here, too
427
+ @argmap(xform, (0, ("t", 2)))
428
+ def foo(a, *args, **kwargs):
429
+ return a, args, kwargs
430
+
431
+ a, args, kwargs = foo(1, 2, 3, t=4)
432
+
433
+ assert a == 1 + 4 + 3
434
+ assert args == (2, 1 + 3)
435
+ assert kwargs == {"t": 1 + 4}
436
+
437
+ def test_flatten(self):
438
+ assert tuple(argmap._flatten([[[[[], []], [], []], [], [], []]], set())) == ()
439
+
440
+ rlist = ["a", ["b", "c"], [["d"], "e"], "f"]
441
+ assert "".join(argmap._flatten(rlist, set())) == "abcdef"
442
+
443
+ def test_indent(self):
444
+ code = "\n".join(
445
+ argmap._indent(
446
+ *[
447
+ "try:",
448
+ "try:",
449
+ "pass#",
450
+ "finally:",
451
+ "pass#",
452
+ "#",
453
+ "finally:",
454
+ "pass#",
455
+ ]
456
+ )
457
+ )
458
+ assert (
459
+ code
460
+ == """try:
461
+ try:
462
+ pass#
463
+ finally:
464
+ pass#
465
+ #
466
+ finally:
467
+ pass#"""
468
+ )
469
+
470
+ def test_immediate_raise(self):
471
+ @not_implemented_for("directed")
472
+ def yield_nodes(G):
473
+ yield from G
474
+
475
+ G = nx.Graph([(1, 2)])
476
+ D = nx.DiGraph()
477
+
478
+ # test first call (argmap is compiled and executed)
479
+ with pytest.raises(nx.NetworkXNotImplemented):
480
+ node_iter = yield_nodes(D)
481
+
482
+ # test second call (argmap is only executed)
483
+ with pytest.raises(nx.NetworkXNotImplemented):
484
+ node_iter = yield_nodes(D)
485
+
486
+ # ensure that generators still make generators
487
+ node_iter = yield_nodes(G)
488
+ next(node_iter)
489
+ next(node_iter)
490
+ with pytest.raises(StopIteration):
491
+ next(node_iter)
shared/package-files/01/01fd8c8411cabda54d218e5b1517d899c375bb3b789f060570f81876cc62b4dd/blob ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ conv2 = np.array([
4
+ 118.75, 155.5, 197.75, 238.75, 239.5, 228, 303, 629, 789, 599.75,
5
+ 499.25, 527.25, 477.75, 260.5, 180.75, 296.75, 263.5, 155.75, 108.5,
6
+ 199.5, 379.75, 109.5, 74.25, 56.75, -95, -93, -29, 90.5, 302, 56.5,
7
+ 126.75, np.nan])
8
+
9
+ conv1 = np.array([
10
+ np.nan, 118.75, 155.5, 197.75, 238.75, 239.5, 228, 303, 629, 789,
11
+ 599.75, 499.25, 527.25, 477.75, 260.5, 180.75, 296.75, 263.5, 155.75,
12
+ 108.5, 199.5, 379.75, 109.5, 74.25, 56.75, -95, -93, -29, 90.5, 302,
13
+ 56.5, 126.75])
14
+
15
+ recurse = np.array([
16
+ -50, 137.5, 239.625, 428.09375, 627.9765625, 815.005859375,
17
+ 993.248535156, 1277.68786621, 1935.57803345, 2580.10549164,
18
+ 2948.97362709, 3345.75659323, 3786.56085169, 4133.35978708,
19
+ 4241.66005323, 4390.58498669, 4690.35375333, 4854.41156167,
20
+ 4941.39710958, 5021.6507226, 5233.58731935, 5609.60317016,
21
+ 5518.59920746, 5639.35019814, 5652.16245047, 5507.95938738,
22
+ 5467.01015315, 5464.24746171, 5589.93813457, 5919.51546636,
23
+ 5792.12113341, 6007.96971665])
24
+
25
+ recurse_init = np.array([
26
+ 87.5, 278.125, 379.46875, 568.1328125, 767.966796875,
27
+ 955.008300781, 1133.2479248, 1417.6880188, 2075.5779953,
28
+ 2720.10550117, 3088.97362471, 3485.75659382, 3926.56085154,
29
+ 4273.35978711, 4381.66005322, 4530.58498669, 4830.35375333,
30
+ 4994.41156167, 5081.39710958, 5161.6507226, 5373.58731935,
31
+ 5749.60317016, 5658.59920746, 5779.35019814, 5792.16245047,
32
+ 5647.95938738, 5607.01015315, 5604.24746171, 5729.93813457,
33
+ 6059.51546636, 5932.12113341, 6147.96971665])
34
+
35
+ conv2_na = np.array([
36
+ 118.75, 155.5, 197.75, 238.75, 239.5, 228, 303, 629,
37
+ np.nan, np.nan, 499.25, 527.25, 477.75, 260.5, 180.75,
38
+ 296.75, 263.5, 155.75, 108.5, 199.5, 379.75, 109.5, 74.25,
39
+ 56.75, -95, -93, -29, 90.5, 302, 56.5, 126.75, np.nan])
40
+
41
+ conv1_na = np.array([
42
+ np.nan, 118.75, 155.5, 197.75, 238.75, 239.5, 228, 303, 629,
43
+ np.nan, np.nan, 499.25, 527.25, 477.75, 260.5, 180.75, 296.75,
44
+ 263.5, 155.75, 108.5, 199.5, 379.75, 109.5, 74.25, 56.75,
45
+ -95, -93, -29, 90.5, 302, 56.5, 126.75])
46
+
47
+ recurse_na = np.array([
48
+ -50, 137.5, 239.625, 428.09375, 627.9765625, 815.005859375,
49
+ 993.248535156, 1277.68786621, 1935.57803345, np.nan, np.nan,
50
+ np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
51
+ np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
52
+ np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])
53
+
54
+ recurse_init_na = np.array([
55
+ 87.5, 278.125, 379.46875, 568.1328125, 767.966796875,
56
+ 955.008300781, 1133.2479248, 1417.6880188, 2075.5779953,
57
+ np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
58
+ np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
59
+ np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
60
+ np.nan, np.nan])
61
+
62
+ conv2_odd = np.array([
63
+ np.nan, np.nan, 366.95, 412.75, 419.05, 501.15, 850.85,
64
+ 1138.65, 1109, 1053.15, 1043.2, 946.35, 687.55, 523.5,
65
+ 544.65, 485.25, 371.3, 297.2, 344.9, 517.85, 319.55, 260.3,
66
+ 191.15, -11.35, -95.45, -72.15, 40.25, 299.85, 173.95,
67
+ 247.5, np.nan, np.nan])
68
+
69
+ conv1_odd = np.array([
70
+ np.nan, np.nan, np.nan, np.nan, 366.95, 412.75, 419.05, 501.15,
71
+ 850.85, 1138.65, 1109, 1053.15, 1043.2, 946.35, 687.55, 523.5,
72
+ 544.65, 485.25, 371.3, 297.2, 344.9, 517.85, 319.55, 260.3,
73
+ 191.15, -11.35, -95.45, -72.15, 40.25, 299.85, 173.95, 247.5])
74
+
75
+ recurse_odd = np.array([
76
+ 191.5, 462.125, 668.84375, 1044.1453125, 1556.46835938,
77
+ 2238.65205078, 3175.44806152, 4572.56601685, 6833.45236176,
78
+ 9776.38394429, 13509.7387615, 18791.5897613, 26145.4239591,
79
+ 36153.4065035, 49699.8299323, 68480.4947171, 94501.551723,
80
+ 130110.583827, 179061.168784, 246469.715955, 339396.406323,
81
+ 467401.785292, 643016.749056, 885080.436404, 1218108.49028,
82
+ 1676305.60832, 2307074.11064, 3175195.69641, 4370080.25182,
83
+ 6014713.24095, 8277634.14851, 11392536.8578])
shared/package-files/01/01fdabaa17050a45975f62886e1522651c38eda28e0731ea559a1293abed319c/blob ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Results for proportion tests
3
+
4
+ Created on Fri Mar 01 14:48:59 2013
5
+
6
+ Author: Josef Perktold
7
+ """
8
+
9
+ import collections
10
+
11
+ import numpy as np
12
+
13
+ from statsmodels.tools.testing import Holder
14
+
15
+ # numbers from R package `pwr` pwr.chisq.test
16
+ res_binom = collections.defaultdict(Holder)
17
+ res_binom_methods = ["agresti-coull", "asymptotic", "bayes", "cloglog",
18
+ "exact", "logit", "probit", "profile", "lrt", "prop.test",
19
+ "wilson"]
20
+
21
+
22
+ # > bci = binom.confint(x = c(18), n = 20, tol = 1e-8)
23
+ # > mkarray2(bci$lower, "res_binom[(18, 20)].ci_low")
24
+ res_binom[(18, 20)].ci_low = np.array([
25
+ 0.6867561125596077, 0.768521618913513, 0.716146742695748,
26
+ 0.656030707261567, 0.6830172859809176, 0.676197991611287,
27
+ 0.7027685414174645, 0.722052946372325, 0.7220576251734515,
28
+ 0.668722403162941, 0.6989663547715128
29
+ ])
30
+ # > mkarray2(bci$upper, "res_binom[(18, 20)].ci_upp")
31
+ res_binom[(18, 20)].ci_upp = np.array([
32
+ 0.984343760998137, 1.031478381086487, 0.97862751197755,
33
+ 0.974010174395775, 0.9876514728297052, 0.974866415649319,
34
+ 0.978858461808406, 0.982318186566456, 0.982639913376776,
35
+ 0.982487361226571, 0.972133518786232
36
+ ])
37
+ # >
38
+ # > bci = binom.confint(x = c(4), n = 20, tol = 1e-8)
39
+ # > mkarray2(bci$lower, "res_binom[(4, 20)].ci_low")
40
+ res_binom[(4, 20)].ci_low = np.array([
41
+ 0.0749115102767071, 0.0246954918846837, 0.07152005247873425,
42
+ 0.0623757232566298, 0.05733399705003284, 0.0771334546771001,
43
+ 0.0710801045992076, 0.0668624655835687, 0.0668375191189685,
44
+ 0.0661062308910436, 0.0806576625797981
45
+ ])
46
+ # > mkarray2(bci$upper, "res_binom[(4, 20)].ci_upp")
47
+ res_binom[(4, 20)].ci_upp = np.array([
48
+ 0.4217635845549845, 0.3753045081153163, 0.4082257625169254,
49
+ 0.393143902056907, 0.436614002996668, 0.427846901518118,
50
+ 0.4147088121599544, 0.405367872119342, 0.405364309586823,
51
+ 0.442686245059445, 0.4160174322518935
52
+ ])
53
+ # >
54
+ # > bci = binom.confint(x = c(4), n = 200, tol = 1e-8)
55
+ # > mkarray2(bci$lower, "res_binom[(4, 200)].ci_low")
56
+ res_binom[(4, 200)].ci_low = np.array([
57
+ 0.005991954548218395, 0.000597346459104517, 0.00678759879519299,
58
+ 0.006650668467968445, 0.005475565879556443, 0.00752663882411158,
59
+ 0.00705442514086136, 0.00625387073493174, 0.00625223049303646,
60
+ 0.00642601313670221, 0.00780442641634947
61
+ ])
62
+ # > mkarray2(bci$upper, "res_binom[(4, 200)].ci_upp")
63
+ res_binom[(4, 200)].ci_upp = np.array([
64
+ 0.0520995587739575, 0.0394026535408955, 0.0468465669668423,
65
+ 0.04722535678688564, 0.05041360908989634, 0.05206026227201098,
66
+ 0.04916362085874019, 0.04585048214247203, 0.0458490848884339,
67
+ 0.0537574613520185, 0.05028708690582643
68
+ ])
69
+ # > bci = binom.confint(x = c(190), n = 200, tol = 1e-8)
70
+ # Warning message:
71
+ # In binom.bayes(x, n, conf.level = conf.level, ...) :
72
+ # 1 confidence interval failed to converge (marked by '*').
73
+ # Try changing 'tol' to a different value.
74
+ # JP: I replace 0.02094150654714356 by np.nan in Bayes
75
+ # > mkarray2(bci$lower, "res_binom[(190, 200)].ci_low")
76
+ res_binom[(190, 200)].ci_low = np.array([
77
+ 0.909307307911624, 0.919794926420966, np.nan,
78
+ 0.909066091776046, 0.9099724622986486, 0.9095820742314172,
79
+ 0.9118101288857796, 0.913954651984184, 0.913956305842353,
80
+ 0.9073089225133698, 0.910421851861224
81
+ ])
82
+ # > mkarray2(bci$upper, "res_binom[(190, 200)].ci_upp")
83
+ res_binom[(190, 200)].ci_upp = np.array([
84
+ 0.973731898348837, 0.980205073579034, 1, 0.972780587302479,
85
+ 0.975765834527891, 0.9728891271086528, 0.973671370402242,
86
+ 0.974623779100809, 0.974626983311416, 0.974392083257476,
87
+ 0.972617354399236
88
+ ])
89
+
90
+ # > bci = binom.confint(x = c(1), n = 30, tol = 1e-8)
91
+ res_binom[(1, 30)].ci_low = np.array([
92
+ -8.305484e-03, -3.090070e-02, 6.903016e-05, 2.494567e-03,
93
+ 8.435709e-04, 4.675346e-03, 3.475014e-03, 3.012987e-03,
94
+ 1.932430e-03, 1.742467e-03, 5.908590e-03])
95
+
96
+ res_binom[(1, 30)].ci_upp = np.array([
97
+ 0.18091798, 0.09756737, 0.12314380, 0.14513807,
98
+ 0.17216946, 0.20200244, 0.16637241, 0.13868254,
99
+ 0.13868375, 0.19053022, 0.16670391])
100
+
101
+ # > bci = binom.confint(x = c(29), n = 30, tol = 1e-8)
102
+ res_binom[(29, 30)].ci_low = np.array([
103
+ 0.8190820, 0.9024326, 0.8768562, 0.7860836,
104
+ 0.8278305, 0.7979976, 0.8336276, 0.8613175,
105
+ 0.8613162, 0.8094698, 0.8332961])
106
+ res_binom[(29, 30)].ci_upp = np.array([
107
+ 1.0083055, 1.0309007, 0.9999310, 0.9952363,
108
+ 0.9991564, 0.9953247, 0.9965250, 0.9969870,
109
+ 0.9980676, 0.9982575, 0.9940914])
110
+
111
+ # > bci = binom.confint(x = c(0), n = 30, tol = 1e-8)
112
+ # Note: this ci_low clips one negative value to 0
113
+ res_binom[(0, 30)].ci_low = np.zeros(11)
114
+ res_binom[(0, 30)].ci_upp = np.array([
115
+ 0.13471170, 0.00000000, 0.06151672, 0.11570331,
116
+ 0.11570331, 0.11570331, 0.11570331, 0.10402893,
117
+ 0.06201781, 0.14132048, 0.11351339])
118
+
119
+ # > bci = binom.confint(x = c(30), n = 30, tol = 1e-8)
120
+ res_binom[(30, 30)].ci_low = np.array([
121
+ 0.8652883, 1.0000000, 0.9384833, 0.8842967,
122
+ 0.8842967, 0.8842967, 0.8842967, 0.8959711,
123
+ 0.9379822, 0.8586795, 0.8864866])
124
+ # Note: this ci_upp clips one value > 1
125
+ res_binom[(30, 30)].ci_upp = np.ones(11)
shared/package-files/01/01ff193dff9cea1784e8d9a785c2d9473a7362d76d8565495256412afafcc095/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01ff193dff9cea1784e8d9a785c2d9473a7362d76d8565495256412afafcc095
3
+ size 7432112
shared/package-files/02/02015ddd124031a908e80c420f37ceac68125fb51e023c6f3c7b374739369ece/blob 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/blob ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/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/blob 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/blob ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace 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/blob 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/blob 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/blob 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/blob 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/blob 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/blob ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace 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/blob 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/blob ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,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/blob ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & 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/blob 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/blob 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/blob 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/blob ADDED
Binary file (1.45 kB). View file
 
shared/package-files/02/02244e7d6c5346b313ef92d9b2b04c25322cde4cbd9f5c779d49d7ccaa5920b3/blob 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/blob 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/blob 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/blob 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/blob 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/blob 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/blob 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/blob 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/blob 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/blob 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/blob 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/blob ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor fft_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/blob ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace 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/blob ADDED
@@ -0,0 +1 @@
 
 
1
+ {"dir_info": {}, "url": "file:///croot/pytz_1695131579487/work"}
shared/package-files/02/023e5dc747d51d3fc1ecdaa58958424c0f690bf440912ad93eba18eff584d1fd/blob 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/blob 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/0244e03291702df45024dcb5cacbc4f3d4cb30d72dfa7fd371c4ac61c42b4fbf/blob ADDED
Binary file (45.2 kB). View file
 
shared/package-files/02/024944e5509d3fea002765b01b71a37e24e992ca1652e9ea40d0f121a2d8fdc3/EXPERIMENTS.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Experiments
2
+
3
+ All models initialize from random weights. Train labels are used for fitting; validation labels only for selection and error analysis. No test data or pretrained assets are available. Hardware: one H100 80 GB, 22 CPU allocation. Primary reported metrics are validation retrieval rates, not estimates of the external reference's test improvement.
4
+
5
+ ## E000 — starter plumbing smoke
6
+ - Hypothesis: the supplied train/publish/relocate/replay path works.
7
+ - Seed 0; one epoch; deterministic 4,096 train / 512 validation-loss rows.
8
+ - Retrieval: deterministic 128-spectrum sample, seed 0; query JSONL SHA256 `9fe86c73720456e94f6e454516b3f1768e289413f89b185df2dff3fa8f23f75a`.
9
+ - Checkpoint SHA256 `e1a27fbe5db99c9868650e830c65dc53ce420a4ab1362d7a166d833e5ae0c8f4`.
10
+ - Compute: training 10.358 s (one H100 allocated), relocated inference 18.373 s; no scientific benchmark claim from this subset.
11
+ - Metrics: `{"hit_rate_at_1": 0.0, "hit_rate_at_20": 0.0546875, "hit_rate_at_5": 0.015625, "mces_at_1": 30.61328125}`. All 128 rankings valid.
12
+ - Deliberately truncated ranking correctly invalidated with `ranking is not an exact candidate permutation`.
13
+ - Initial timing invocation failed because /usr/bin/time is unavailable; replaced with Python monotonic timing. Initial MCES invocation failed in GLACIER Python; evaluation uses the supplied system Python with myopic_mces. Neither failure changed fitting or inference.
14
+ - Selection: validation cosine loss for commissioning only.
15
+
16
+ ## E001 — all-condition inverse spectrum encoder
17
+ - Hypothesis: explicit fragment and neutral-loss bins retain more discriminating spectrum information than DeepSets mean pooling and provide a useful all-condition fallback.
18
+ - Changed factor: residual binned-spectrum architecture; 0.1 Da bins through 1500 Da, up to 128 peaks; Morgan4096 radius 2; cosine plus weighted BCE loss. Metadata uses precursor, adduct, instrument and observed/missing energy, never true formula.
19
+ - Seed 1; complete 194,119 training spectra; 50 epochs scheduled; one H100; AdamW, batch 512, width 1024, three residual blocks.
20
+ - Selection: full 19,429-query validation retrieval Hit@1 each epoch. Query JSONL SHA256 `7e6f5034f6196d3f18afe31ec8cfc24305b12d09b6cd04293da061cd3f7746e6`.
21
+ - No validation parameters fitted; candidate fingerprints are derived only from supplied structures.
22
+ - Completed 50 epochs in 160.517 s on one H100; max allocated GPU memory 5.631 GB. Selected epoch 2; Hit@1 0.09511555, Hit@5 0.21622317, Hit@20 0.39348397. Independent full replay: Hit@1 0.09393175, Hit@5 0.21606876, Hit@20 0.39389572; 19,429 complete rankings in 49.663 s. MCES running.
23
+ - Checkpoint SHA256 `bce84afa449b4952efaddd558af4c5439e8170976cbe56143a57abf98540f608`. Negative result: continued fitting overfit; final epoch Hit@1 0.08749807. Keep epoch 2. The initially logged retrieval used input-order tie resolution; replay uses candidate-ID ties. All 23 top-one discrepancies were identical-fingerprint ties. Validation cache now uses candidate-ID ties too; repeated evaluation exactly matches replay. No fitting or checkpoint change. Replay 95% molecule bootstrap interval: [0.08021314, 0.10881266], 3,185 molecule groups, 2,000 resamples. Paired smoke subset gain versus E000: +0.0703125; same 117 molecule groups.
24
+ - Packaging adapter initially imported the starter predict module because of sys.path precedence; fixed before any live publication. A premature replay invocation failed while the candidate package was not yet built; the complete replay subsequently passed.
25
+
26
+
27
+
28
+ ## E002 — clean synthetic augmentation
29
+ - Hypothesis: 435,076 synthetic molecular structures increase chemical coverage and reduce the severe train/validation generalization gap in E001.
30
+ - Changed factor: add only the supplied 2,333,485 sanitized ICEBERG simulations. Same formula-free input features; synthetic precursor masses derived from train-only simulation formula metadata. No simulated validation structures or pretrained assets.
31
+ - Seed 1; same architecture/loss as E001, random initialization; 40 epochs × 1,200 steps, batch 512, 25% experimental train / 75% clean synthetic sampling. Eight null/empty simulation spectra are excluded from fitting, leaving 2,333,477 usable rows. Initial preparation stopped on an empty payload; resumed from 1,283,584 complete rows, finished remaining rows in 44.062 s. Failed log and prior source retained. Full-validation selection uses fixed candidate-ID ties. Completed 40 epochs in 292.360 s on the one H100; max allocated CUDA memory 12.316 GB. Selected epoch 40, checkpoint SHA256 `bc0f0251108bb6c602c0ea44de892719c6b0d29c69ef26854911726c57c0faf2`. Independent replay: all 19,429 rankings valid in 86.279 s; Hit@1 0.2329507437, Hit@5 0.3749034948, Hit@20 0.5380101910. Replay exactly matches selection. Same full-validation query hash as E001. Paired molecule-bootstrap improvement over E001 +0.13901899 (95% CI [0.12379366,0.15556200], 3,185 molecule groups, 2,000 resamples). MCES running.
32
+ - Error analysis: H+ Hit@1 0.2745712 versus Na+ 0.1038632; missing energy 0.1650095; released GLACIER conditions 0.3017259 versus remaining conditions 0.1638989. Missing-condition and sodium transfer remain weak.
33
+
34
+
35
+ ## E003 — GLACIER all-condition training (preparing)
36
+ - Hypothesis: the native forward model can learn spectra outside the published condition domain using explicit missing-energy and unknown-instrument embeddings already present in native code.
37
+ - Changed factor: broaden fragment-supervised fitting to all conditions. Preserve existing prepared targets, derive additional MAGMa targets only from corresponding training/validation structures and spectra. Engine reuse per SMILES reduces preparation time without using information across folds. Native architecture kept intact.
38
+ - The first 100-molecule/209-spectrum preparation smoke revealed missing sibling fragments when compared against native preparation. Invalidated those 209 derived rows, added native sibling expansion, and verified all 10 selected cases exactly (root canonical SMILES, raw target spectrum, fragment-mask set). Full preparation now running on 17,050 additional molecular groups / 104,473 spectra, retaining supplied targets unchanged.
39
+
40
+ ## E004 — fine-mass peak transformer
41
+ - Hypothesis: shared peak attention and fine mass-defect features reduce the information loss of 0.1 Da bins and improve unseen-structure retrieval.
42
+ - Changed factor: spectrum architecture/representation; same seed 1, same train+clean-synthetic mixture and loss as E002. Four transformer layers, width 384, 64 strongest peaks, 0.1 Da learned embeddings plus exact-mass sine/cosine features, precursor/condition token. 12,836,736 parameters.
43
+ - Full train fold, 40 epochs × 1,200 steps, batch 512; 25% experimental/75% synthetic. Exact original source/config/logs in E004. Retrieval uses the same full validation query set and candidate-ID ties. Completed in 1120.843 s on the sole H100, maximum allocated CUDA memory10.957 GB. Selected epoch37, checkpoint SHA256 `1d1d4418b4e305306996953e54426a15cd35f0b767c989840c91ec0880818193`; ordinary-cosine validation Hit@1 .30207421895, Hit@5 .47269545525, Hit@20 .63482423182. Final epoch40 was lower (.29996397138), so retained epoch37. Independent replay will use the stronger E008 ranking of these same trained weights.
44
+
45
+ ## Evaluation engineering notes
46
+ - E001 full MCES initially spent 671.031 s in a serial-result pool and was restarted to add an exact identical-graph shortcut and a persistent completed-pair cache. Official MCES threshold=15, stronger bound and CBC solver options are unchanged. The zero shortcut only recognizes the same atom/bond graph (stereochemistry is ignored by the supplied MCES graph definition).
47
+ - Cached MCES jobs were restarted once more after changing SQLite transactions to commit each completed pair, avoiding write locks across long solves. Diagnostic compute is CPU-only; full secondary metrics remain pending until every pair completes.
48
+
49
+ ## E005 — sodium mass-coordinate normalization (prepared)
50
+ - Hypothesis: shifting Na+ fragment and precursor masses by -21.981944235 Da to proton-equivalent coordinates shares fragmentation features with the much larger H+ training population. Neutral losses and the observed adduct indicator remain unchanged.
51
+ - Changed factor: mass-coordinate preprocessing only, compared with E002. Planned same random seed 1, MLP architecture, training mixture, loss, epochs and steps. All training structures remain in the train/clean-synthetic folds. Preparation took 14.136 s; corrected synthetic fractional-precursor feature to preserve original H+ rows exactly. No synthetic positive peak falls below the normalization shift. Candidate IDs never affect the learned score.
52
+ - Training is now running with the planned fixed settings. Separately checked 40 train and40 validation records: normalized preprocessing exactly matches runtime features.
53
+
54
+ Further engineering: E002 passed new-input contract probes including arbitrary IDs, unseen structures, singleton pools, out-of-window peaks, missing/novel instrument labels, and candidate-order invariance. E003 preparation resumed with ten CPU workers after 787.907 s; committed targets retained. Batch-32/accumulation-1 native training will scale MAGMa schedule intervals from 2500 to625 microbatches to preserve the original schedule per observed spectrum; optimizer warmup remains2000 steps.
55
+
56
+ ## E006 — fixed fingerprint score comparison
57
+ - Hypothesis: common Morgan bits dominate ordinary cosine; weighting by their training-fold information content improves discrimination without retraining the spectrum encoder.
58
+ - Changed factor: fixed ranking function only, using the completed E002 checkpoint. Compared eight prespecified rules: cosine, soft Tanimoto, BCE likelihood, size-normalized BCE, cosine with sqrt-IDF, cosine with IDF, square-root-size-normalized dot, and mean dot. No validation fitting; IDF uses only 25,046 experimental train SMILES fingerprints.
59
+ - Selected IDF-weighted cosine: Hit@1 0.2459725153, Hit@5 0.3981162180, Hit@20 0.5622008338 on the same full validation query hash. Paired molecule-bootstrap gain over E002 +0.01302177 (95% CI [0.00855167,0.01742674], 3,185 groups). Eight-rule comparison took 8.841 s on the sole H100, overlapping E004 training briefly.
60
+ - Negative comparisons: BCE Hit@1 0.20433373; normalized BCE 0.22358330; mean dot 0.20505430. Tanimoto 0.23310515; sqrt-IDF cosine 0.24226671; dot/sqrt(size) equals cosine ranking 0.23295074. All results/source retained. Derived checkpoint SHA256 `c20a89ff4ee9c6ec69b593b48971e15a233c8f0382ad5d828700568b550583c7`; full independent replay passed all 19,429 queries in 115.219 s and exactly matched all three hit rates. MCES pending.
61
+
62
+ ## E007 — training-only hard-negative contrastive fine-tuning (prepared)
63
+ - Hypothesis: fingerprint regression ignores which similar-mass candidates must be separated; listwise training against training-only molecular negatives improves retrieval.
64
+ - Changed factor: add multi-positive near-mass InfoNCE to the fingerprint loss, initialized from the task-trained E004 checkpoint after its run completes. No external initialization assets.
65
+ - Negative pools derive solely from 25,046 experimental train and 435,076 sanitized synthetic molecular structures. Neutral masses use their training formula metadata. A ±0.01 Da neighborhood is widened to at least 32 molecules; identical fingerprint negatives are treated as positives to avoid contradictory supervision. Pool preparation 14.511 s.
66
+ - Planned fixed settings: 32 negatives, temperature 0.05, contrastive loss weight0.2, learning rate1e-4,20epochs×1200steps; same experimental/synthetic mixture. Validation only selects checkpoints; no validation candidate is used as a training negative. Training pending.
67
+
68
+ ## E008 — transformer with training-IDF fingerprint ranking
69
+ - Hypothesis/change: apply the fixed training-IDF weighting from E006 to E004 outputs. Network parameters are unchanged; weights derive only from train fingerprints. Same eight predefined fixed rules evaluated in4.108 s; full comparison retained.
70
+ - Selected weighted-cosine validation Hit@1 .31988264965, Hit@5 .49997426527, Hit@20 .67131607391. Source checkpoint E004 epoch37; derived checkpoint SHA256 `c611ede98e88041dafc82cfb71182dcb34f4ac4d93e91603557d0438e859036d`. Full replay passed all19,429 queries in98.440s and exactly matched all hit rates. Paired gain over E006 +.07391013,95% molecule-CI[.05529783,.09264636]. Proton Hit@1 .3674789, sodium .1722609; released GLACIER domain .4087734, remaining conditions .2306343. MCES pending. Exact selected fitting source, configuration, metrics and logs are copied into E008/research lineage; no external pretrained assets.
71
+
72
+ ## E009 — ten-peak transformer (planned from training-source analysis)
73
+ - Hypothesis: retaining many diffuse simulated peaks creates a source mismatch and distracts the encoder; limit both experimental and simulated inputs to the ten strongest peaks.
74
+ - Training-only analysis: deterministic seed1 samples of100,000 spectra per source show top10 retains89.963% of experimental raw intensity versus40.715% of synthetic intensity; mean retained peak counts33.50 versus58.35 (cap128). The ten-peak setting also matches the supplied MIST reproduction recipe.
75
+ - Changed factor versus E004: maximum peak tokens64→10, with the same width384/depth4, seed1, loss, mixture, steps, epochs and cosine checkpoint selection. Check fixed IDF ranking afterward using the already established scoring family. Training pending native smoke and single-GPU availability.
shared/package-files/02/024983a51d08171a34adeb7dd6d44f614aab8107d0dfaee8913b7611ed959bad/blob 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/blob ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & 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/blob 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/blob 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/blob 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/025abe9933a2b39873cf2aaa1790ce80eb9811aaa71086f504d32963a330ba53/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:025abe9933a2b39873cf2aaa1790ce80eb9811aaa71086f504d32963a330ba53
3
+ size 5759081
shared/package-files/02/025b702d601b96948b6bedb82af36ec58c4cd88795979a7677e928cc0f5027ed/blob 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/blob ADDED
Binary file (446 Bytes). View file