Sumitwarrior7 commited on
Commit
be42116
·
verified ·
1 Parent(s): a083046

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .venv/lib/python3.10/site-packages/aiofile/__init__.py +29 -0
  2. .venv/lib/python3.10/site-packages/aiofile/aio.py +329 -0
  3. .venv/lib/python3.10/site-packages/aiofile/py.typed +1 -0
  4. .venv/lib/python3.10/site-packages/aiofile/utils.py +362 -0
  5. .venv/lib/python3.10/site-packages/aiofile/version.py +13 -0
  6. .venv/lib/python3.10/site-packages/functorch/__init__.py +39 -0
  7. .venv/lib/python3.10/site-packages/functorch/_src/__init__.py +0 -0
  8. .venv/lib/python3.10/site-packages/functorch/_src/aot_autograd/__init__.py +8 -0
  9. .venv/lib/python3.10/site-packages/functorch/_src/eager_transforms/__init__.py +7 -0
  10. .venv/lib/python3.10/site-packages/functorch/_src/make_functional/__init__.py +4 -0
  11. .venv/lib/python3.10/site-packages/functorch/_src/vmap/__init__.py +16 -0
  12. .venv/lib/python3.10/site-packages/functorch/compile/__init__.py +30 -0
  13. .venv/lib/python3.10/site-packages/functorch/dim/__init__.py +1603 -0
  14. .venv/lib/python3.10/site-packages/functorch/dim/_dim_entry.py +130 -0
  15. .venv/lib/python3.10/site-packages/functorch/dim/_enable_all_layers.py +143 -0
  16. .venv/lib/python3.10/site-packages/functorch/dim/_getsetitem.py +564 -0
  17. .venv/lib/python3.10/site-packages/functorch/dim/_order.py +215 -0
  18. .venv/lib/python3.10/site-packages/functorch/dim/_py_inst_decoder.py +67 -0
  19. .venv/lib/python3.10/site-packages/functorch/dim/_tensor_info.py +69 -0
  20. .venv/lib/python3.10/site-packages/functorch/dim/_wrap.py +269 -0
  21. .venv/lib/python3.10/site-packages/functorch/dim/magic_trace.py +48 -0
  22. .venv/lib/python3.10/site-packages/functorch/dim/op_properties.py +312 -0
  23. .venv/lib/python3.10/site-packages/functorch/dim/wrap_type.py +71 -0
  24. .venv/lib/python3.10/site-packages/functorch/einops/__init__.py +4 -0
  25. .venv/lib/python3.10/site-packages/functorch/einops/_parsing.py +308 -0
  26. .venv/lib/python3.10/site-packages/functorch/einops/rearrange.py +210 -0
  27. .venv/lib/python3.10/site-packages/functorch/experimental/__init__.py +5 -0
  28. .venv/lib/python3.10/site-packages/functorch/experimental/control_flow.py +6 -0
  29. .venv/lib/python3.10/site-packages/functorch/experimental/ops.py +1 -0
  30. .venv/lib/python3.10/site-packages/h11/__pycache__/_events.cpython-310.pyc +0 -0
  31. .venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/INSTALLER +1 -0
  32. .venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/METADATA +93 -0
  33. .venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/RECORD +63 -0
  34. .venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/REQUESTED +0 -0
  35. .venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/WHEEL +5 -0
  36. .venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/licenses/LICENSE +28 -0
  37. .venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/top_level.txt +1 -0
  38. .venv/lib/python3.10/site-packages/sympy/__init__.py +545 -0
  39. .venv/lib/python3.10/site-packages/sympy/abc.py +111 -0
  40. .venv/lib/python3.10/site-packages/sympy/assumptions/__init__.py +18 -0
  41. .venv/lib/python3.10/site-packages/sympy/assumptions/ask.py +651 -0
  42. .venv/lib/python3.10/site-packages/sympy/assumptions/ask_generated.py +352 -0
  43. .venv/lib/python3.10/site-packages/sympy/assumptions/assume.py +485 -0
  44. .venv/lib/python3.10/site-packages/sympy/assumptions/cnf.py +445 -0
  45. .venv/lib/python3.10/site-packages/sympy/assumptions/facts.py +270 -0
  46. .venv/lib/python3.10/site-packages/sympy/assumptions/handlers/__init__.py +13 -0
  47. .venv/lib/python3.10/site-packages/sympy/assumptions/handlers/calculus.py +273 -0
  48. .venv/lib/python3.10/site-packages/sympy/assumptions/handlers/common.py +164 -0
  49. .venv/lib/python3.10/site-packages/sympy/assumptions/handlers/matrices.py +716 -0
  50. .venv/lib/python3.10/site-packages/sympy/assumptions/handlers/ntheory.py +279 -0
.venv/lib/python3.10/site-packages/aiofile/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .aio import AIOFile
2
+ from .utils import (
3
+ BinaryFileWrapper, FileIOWrapperBase, LineReader, Reader, TextFileWrapper,
4
+ Writer, async_open,
5
+ )
6
+ from .version import (
7
+ __author__, __version__, author_info, package_info, package_license,
8
+ project_home, team_email, version_info,
9
+ )
10
+
11
+
12
+ __all__ = (
13
+ "AIOFile",
14
+ "BinaryFileWrapper",
15
+ "FileIOWrapperBase",
16
+ "LineReader",
17
+ "Reader",
18
+ "TextFileWrapper",
19
+ "Writer",
20
+ "__author__",
21
+ "__version__",
22
+ "async_open",
23
+ "author_info",
24
+ "package_info",
25
+ "package_license",
26
+ "project_home",
27
+ "team_email",
28
+ "version_info",
29
+ )
.venv/lib/python3.10/site-packages/aiofile/aio.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import os
3
+ from collections import namedtuple
4
+ from concurrent.futures import Executor
5
+ from functools import partial
6
+ from os import strerror
7
+ from pathlib import Path
8
+ from typing import (
9
+ Any, Awaitable, BinaryIO, Callable, Dict, Generator, Optional, TextIO,
10
+ TypeVar, Union,
11
+ )
12
+ from weakref import finalize
13
+
14
+ import caio
15
+ from caio.asyncio_base import AsyncioContextBase
16
+
17
+
18
+ _T = TypeVar("_T")
19
+
20
+ AIO_FILE_NOT_OPENED = -1
21
+ AIO_FILE_CLOSED = -2
22
+
23
+ FileIOType = Union[TextIO, BinaryIO]
24
+
25
+ FileMode = namedtuple(
26
+ "FileMode", (
27
+ "readable",
28
+ "writable",
29
+ "plus",
30
+ "appending",
31
+ "created",
32
+ "flags",
33
+ "binary",
34
+ ),
35
+ )
36
+
37
+
38
+ def parse_mode(mode: str) -> FileMode: # noqa: C901
39
+ """ Rewritten from `cpython fileno`_
40
+
41
+ .. _cpython fileio: https://bit.ly/2JY2cnp
42
+ """
43
+
44
+ flags = os.O_RDONLY
45
+
46
+ rwa = False
47
+ writable = False
48
+ readable = False
49
+ plus = False
50
+ appending = False
51
+ created = False
52
+ binary = False
53
+
54
+ for m in mode:
55
+ if m == "x":
56
+ rwa = True
57
+ created = True
58
+ writable = True
59
+ flags |= os.O_EXCL | os.O_CREAT
60
+
61
+ if m == "r":
62
+ if rwa:
63
+ raise Exception("Bad mode")
64
+
65
+ rwa = True
66
+ readable = True
67
+
68
+ if m == "w":
69
+ if rwa:
70
+ raise Exception("Bad mode")
71
+
72
+ rwa = True
73
+ writable = True
74
+
75
+ flags |= os.O_CREAT | os.O_TRUNC
76
+
77
+ if m == "a":
78
+ if rwa:
79
+ raise Exception("Bad mode")
80
+ rwa = True
81
+ writable = True
82
+ appending = True
83
+ flags |= os.O_CREAT | os.O_APPEND
84
+
85
+ if m == "+":
86
+ if plus:
87
+ raise Exception("Bad mode")
88
+ readable = True
89
+ writable = True
90
+ plus = True
91
+
92
+ if m == "b":
93
+ binary = True
94
+ if hasattr(os, "O_BINARY"):
95
+ flags |= os.O_BINARY
96
+
97
+ if readable and writable:
98
+ flags |= os.O_RDWR
99
+
100
+ elif readable:
101
+ flags |= os.O_RDONLY
102
+ else:
103
+ flags |= os.O_WRONLY
104
+
105
+ return FileMode(
106
+ readable=readable,
107
+ writable=writable,
108
+ plus=plus,
109
+ appending=appending,
110
+ created=created,
111
+ flags=flags,
112
+ binary=binary,
113
+ )
114
+
115
+
116
+ class AIOFile:
117
+ _file_obj: Optional[FileIOType]
118
+ _file_obj_owner: bool
119
+ _encoding: str
120
+ _executor: Optional[Executor]
121
+ mode: FileMode
122
+ __open_result: "Optional[asyncio.Future[FileIOType]]"
123
+
124
+ def __init__(
125
+ self, filename: Union[str, Path],
126
+ mode: str = "r", encoding: str = "utf-8",
127
+ context: Optional[AsyncioContextBase] = None,
128
+ executor: Optional[Executor] = None,
129
+ ):
130
+ self.__context = context or get_default_context()
131
+ self.__open_result = None
132
+
133
+ self._fname = str(filename)
134
+ self._open_mode = mode
135
+
136
+ self.mode = parse_mode(mode)
137
+
138
+ self._file_obj = None
139
+ self._file_obj_owner = True
140
+ self._encoding = encoding
141
+ self._executor = executor
142
+
143
+ @classmethod
144
+ def from_fp(cls, fp: FileIOType, **kwargs: Any) -> "AIOFile":
145
+ afp = cls(fp.name, fp.mode, **kwargs)
146
+ afp._file_obj = fp
147
+ afp._open_mode = fp.mode
148
+ afp._file_obj_owner = False
149
+ return afp
150
+
151
+ def _run_in_thread(
152
+ self, func: "Callable[..., _T]", *args: Any, **kwargs: Any,
153
+ ) -> "asyncio.Future[_T]":
154
+ return self.__context.loop.run_in_executor(
155
+ self._executor, partial(func, *args, **kwargs),
156
+ )
157
+
158
+ @property
159
+ def name(self) -> str:
160
+ return self._fname
161
+
162
+ @property
163
+ def loop(self) -> asyncio.AbstractEventLoop:
164
+ return self.__context.loop
165
+
166
+ @property
167
+ def encoding(self) -> str:
168
+ return self._encoding
169
+
170
+ async def open(self) -> Optional[int]:
171
+ if self._file_obj is not None:
172
+ if self._file_obj.closed:
173
+ raise asyncio.InvalidStateError("AIOFile closed")
174
+ return None
175
+
176
+ if self.__open_result is None:
177
+ self.__open_result = self._run_in_thread(
178
+ open,
179
+ self._fname,
180
+ self._open_mode,
181
+ )
182
+ self._file_obj = await self.__open_result
183
+ self.__open_result = None
184
+ return self._file_obj.fileno()
185
+
186
+ await self.__open_result
187
+ return None
188
+
189
+ def __repr__(self) -> str:
190
+ return "<AIOFile: %r>" % self._fname
191
+
192
+ async def close(self) -> None:
193
+ if self._file_obj is None or not self._file_obj_owner:
194
+ return
195
+
196
+ if self.mode.writable:
197
+ await self.fdsync()
198
+
199
+ await self._run_in_thread(self._file_obj.close)
200
+
201
+ def fileno(self) -> int:
202
+ if self._file_obj is None:
203
+ raise asyncio.InvalidStateError("AIOFile closed")
204
+ return self._file_obj.fileno()
205
+
206
+ def __await__(self) -> Generator[None, Any, "AIOFile"]:
207
+ yield from self.open().__await__()
208
+ return self
209
+
210
+ async def __aenter__(self) -> "AIOFile":
211
+ await self.open()
212
+ return self
213
+
214
+ def __aexit__(self, *args: Any) -> Awaitable[Any]:
215
+ return asyncio.get_event_loop().create_task(self.close())
216
+
217
+ async def read(self, size: int = -1, offset: int = 0) -> Union[bytes, str]:
218
+ data = await self.read_bytes(size, offset)
219
+ return data if self.mode.binary else self.decode_bytes(data)
220
+
221
+ async def read_bytes(self, size: int = -1, offset: int = 0) -> bytes:
222
+ if size < -1:
223
+ raise ValueError("Unsupported value %d for size" % size)
224
+
225
+ if size == -1:
226
+ size = (
227
+ await self._run_in_thread(
228
+ os.stat,
229
+ self.fileno(),
230
+ )
231
+ ).st_size
232
+
233
+ return await self.__context.read(size, self.fileno(), offset)
234
+
235
+ async def write(self, data: Union[str, bytes], offset: int = 0) -> int:
236
+ if self.mode.binary:
237
+ if not isinstance(data, bytes):
238
+ raise ValueError("Data must be bytes in binary mode")
239
+ bytes_data = data
240
+ else:
241
+ if not isinstance(data, str):
242
+ raise ValueError("Data must be str in text mode")
243
+ bytes_data = self.encode_bytes(data)
244
+
245
+ return await self.write_bytes(bytes_data, offset)
246
+
247
+ def encode_bytes(self, data: str) -> bytes:
248
+ return data.encode(self._encoding)
249
+
250
+ def decode_bytes(self, data: bytes) -> str:
251
+ return data.decode(self._encoding)
252
+
253
+ async def write_bytes(self, data: bytes, offset: int = 0) -> int:
254
+ data_size = len(data)
255
+ if data_size == 0:
256
+ return 0
257
+
258
+ # data can be written partially, see write(2)
259
+ # (https://www.man7.org/linux/man-pages/man2/write.2.html)
260
+ # for example, it can happen when a disk quota or a resource limit
261
+ # is exceeded (in that case subsequent call will return a
262
+ # corresponding error) or write has been interrupted by
263
+ # an incoming signal
264
+
265
+ # behaviour here in regard to continue trying to write remaining data
266
+ # corresponds to the behaviour of io.BufferedIOBase
267
+ # (https://docs.python.org/3/library/io.html#io.BufferedIOBase.write)
268
+ # which used by object returned open() with `buffering` argument >= 1
269
+ # (effectively the default)
270
+
271
+ written = 0
272
+ while written < data_size:
273
+ res = await self.__context.write(
274
+ data[written:], self.fileno(), offset + written,
275
+ )
276
+ if res == 0:
277
+ raise RuntimeError(
278
+ "Write operation returned 0", self, offset, written,
279
+ )
280
+ elif res < 0:
281
+ # fix for linux_aio implementation bug in caio<=0.6.1
282
+ # (https://github.com/mosquito/caio/pull/7)
283
+ # and safeguard against future similar issues
284
+ errno = -res
285
+ raise OSError(errno, strerror(errno), self._fname)
286
+
287
+ written += res
288
+
289
+ return written
290
+
291
+ async def fsync(self) -> None:
292
+ return await self.__context.fsync(self.fileno())
293
+
294
+ async def fdsync(self) -> None:
295
+ return await self.__context.fdsync(self.fileno())
296
+
297
+ def truncate(self, length: int = 0) -> Awaitable[None]:
298
+ return self._run_in_thread(
299
+ os.ftruncate, self.fileno(), length,
300
+ )
301
+
302
+
303
+ ContextStoreType = Dict[asyncio.AbstractEventLoop, caio.AsyncioContext]
304
+ DEFAULT_CONTEXT_STORE: ContextStoreType = {}
305
+
306
+
307
+ def create_context(
308
+ max_requests: int = caio.AsyncioContext.MAX_REQUESTS_DEFAULT,
309
+ ) -> caio.AsyncioContext:
310
+ loop = asyncio.get_event_loop()
311
+ context = caio.AsyncioContext(max_requests, loop=loop)
312
+
313
+ def finalizer() -> None:
314
+ context.close()
315
+ DEFAULT_CONTEXT_STORE.pop(context, None)
316
+
317
+ finalize(loop, finalizer)
318
+ DEFAULT_CONTEXT_STORE[loop] = context
319
+ return context
320
+
321
+
322
+ def get_default_context() -> caio.AsyncioContext:
323
+ loop = asyncio.get_event_loop()
324
+ context = DEFAULT_CONTEXT_STORE.get(loop)
325
+
326
+ if context is not None:
327
+ return context
328
+
329
+ return create_context()
.venv/lib/python3.10/site-packages/aiofile/py.typed ADDED
@@ -0,0 +1 @@
 
 
1
+
.venv/lib/python3.10/site-packages/aiofile/utils.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import collections.abc
3
+ import io
4
+ import os
5
+ from abc import ABC, abstractmethod
6
+ from pathlib import Path
7
+ from types import MappingProxyType
8
+ from typing import Any, Generator, Tuple, Union
9
+
10
+ from .aio import AIOFile, FileIOType
11
+
12
+
13
+ ENCODING_MAP = MappingProxyType({
14
+ "utf-8": 4,
15
+ "utf-16": 8,
16
+ "UTF-8": 4,
17
+ "UTF-16": 8,
18
+ })
19
+
20
+
21
+ async def unicode_reader(
22
+ afp: AIOFile, chunk_size: int, offset: int, encoding: str = "utf-8",
23
+ ) -> Tuple[int, str]:
24
+
25
+ if chunk_size < 0:
26
+ chunk_bytes = await afp.read_bytes(-1, offset)
27
+ return len(chunk_bytes), chunk_bytes.decode(encoding=encoding)
28
+
29
+ last_error = None
30
+ for retry in range(ENCODING_MAP.get(encoding, 4)):
31
+ chunk_bytes = await afp.read_bytes(chunk_size + retry, offset)
32
+ try:
33
+ chunk = chunk_bytes.decode(encoding=encoding)
34
+ break
35
+ except UnicodeDecodeError as e:
36
+ last_error = e
37
+ else:
38
+ raise last_error # type: ignore
39
+
40
+ chunk_size = len(chunk_bytes)
41
+
42
+ return chunk_size, chunk
43
+
44
+
45
+ class Reader(collections.abc.AsyncIterable):
46
+ __slots__ = "_chunk_size", "__offset", "file", "__lock", "encoding"
47
+
48
+ CHUNK_SIZE = 32 * 1024
49
+
50
+ def __init__(
51
+ self, aio_file: AIOFile, offset: int = 0,
52
+ chunk_size: int = CHUNK_SIZE,
53
+ ):
54
+
55
+ self.__lock = asyncio.Lock()
56
+ self.__offset = int(offset)
57
+
58
+ self._chunk_size = int(chunk_size)
59
+ self.file = aio_file
60
+ self.encoding = self.file.encoding
61
+
62
+ async def read_chunk(self) -> Union[str, bytes]:
63
+ async with self.__lock:
64
+ if self.file.mode.binary:
65
+ chunk = await self.file.read_bytes(
66
+ self._chunk_size, self.__offset,
67
+ ) # type: Union[str, bytes]
68
+ chunk_size = len(chunk)
69
+ else:
70
+ chunk_size, chunk = await unicode_reader(
71
+ self.file, self._chunk_size, self.__offset,
72
+ encoding=self.encoding,
73
+ )
74
+ self.__offset += chunk_size
75
+ return chunk
76
+
77
+ async def __anext__(self) -> Union[str, bytes]:
78
+ chunk = await self.read_chunk()
79
+
80
+ if not chunk:
81
+ raise StopAsyncIteration(chunk)
82
+
83
+ return chunk
84
+
85
+ def __aiter__(self) -> "Reader":
86
+ return self
87
+
88
+
89
+ class Writer:
90
+ __slots__ = "__chunk_size", "__offset", "__aio_file", "__lock"
91
+
92
+ def __init__(self, aio_file: AIOFile, offset: int = 0):
93
+ self.__offset = int(offset)
94
+ self.__aio_file = aio_file
95
+ self.__lock = asyncio.Lock()
96
+
97
+ async def __call__(self, data: Union[str, bytes]) -> None:
98
+ async with self.__lock:
99
+ if isinstance(data, str):
100
+ data = self.__aio_file.encode_bytes(data)
101
+
102
+ await self.__aio_file.write_bytes(data, self.__offset)
103
+ self.__offset += len(data)
104
+
105
+
106
+ class LineReader(collections.abc.AsyncIterable):
107
+ CHUNK_SIZE = 4192
108
+
109
+ def __init__(
110
+ self, aio_file: AIOFile, offset: int = 0,
111
+ chunk_size: int = CHUNK_SIZE, line_sep: str = "\n",
112
+ ):
113
+ self.__reader = Reader(aio_file, chunk_size=chunk_size, offset=offset)
114
+
115
+ self._buffer = (
116
+ io.BytesIO() if aio_file.mode.binary else io.StringIO()
117
+ ) # type: Any
118
+
119
+ self.linesep = (
120
+ aio_file.encode_bytes(line_sep)
121
+ if aio_file.mode.binary
122
+ else line_sep
123
+ )
124
+
125
+ async def readline(self) -> Union[str, bytes]:
126
+ while True:
127
+ line = self._buffer.readline()
128
+ if line and line.endswith(self.linesep):
129
+ return line
130
+
131
+ buffer_remainder = line + self._buffer.read()
132
+ self._buffer.truncate(0)
133
+ self._buffer.seek(0)
134
+
135
+ # No line in buffer, read more data
136
+ chunk = await self.__reader.read_chunk()
137
+ if not chunk:
138
+ # No more data to read, return any remaining content in the buffer
139
+ return buffer_remainder
140
+ # We have more data to read, write it to the buffer and handle it in the next iteration
141
+ self._buffer.write(buffer_remainder)
142
+ self._buffer.write(chunk)
143
+ self._buffer.seek(0)
144
+
145
+ async def __anext__(self) -> Union[bytes, str]:
146
+ line = await self.readline()
147
+
148
+ if not line:
149
+ # We are finished, close the buffer and raise StopAsyncIteration
150
+ self._buffer.close()
151
+ raise StopAsyncIteration(line)
152
+
153
+ return line
154
+
155
+ def __aiter__(self) -> "LineReader":
156
+ return self
157
+
158
+
159
+ class FileIOWrapperBase(ABC):
160
+ _READLINE_CHUNK_SIZE = 4192
161
+
162
+ def __init__(self, afp: AIOFile, *, offset: int = 0):
163
+ self._offset = offset
164
+ self._lock = asyncio.Lock()
165
+ self.file = afp
166
+
167
+ if self.file.mode.appending:
168
+ try:
169
+ self._offset = os.stat(afp.name).st_size
170
+ except FileNotFoundError:
171
+ self._offset = 0
172
+
173
+ @abstractmethod
174
+ async def read(self, length: int = -1) -> Any:
175
+ raise NotImplementedError
176
+
177
+ @abstractmethod
178
+ async def write(self, data: Any) -> int:
179
+ raise NotImplementedError
180
+
181
+ @abstractmethod
182
+ async def readline(
183
+ self, size: int = -1, newline: Any = ...,
184
+ ) -> Union[str, bytes]:
185
+ raise NotImplementedError
186
+
187
+ def seek(self, offset: int) -> None:
188
+ self._offset = offset
189
+
190
+ def tell(self) -> int:
191
+ return self._offset
192
+
193
+ async def flush(self, sync_metadata: bool = False) -> None:
194
+ if sync_metadata:
195
+ await self.file.fsync()
196
+ else:
197
+ await self.file.fdsync()
198
+
199
+ async def close(self) -> None:
200
+ await self.file.close()
201
+
202
+ def __await__(self) -> Generator[None, None, "FileIOWrapperBase"]:
203
+ yield from self.file.__await__()
204
+ return self
205
+
206
+ async def __aenter__(self) -> "FileIOWrapperBase":
207
+ await self.file.open()
208
+ return self
209
+
210
+ async def __aexit__(self, *_: Any) -> None:
211
+ await self.close()
212
+
213
+ def __aiter__(self) -> LineReader:
214
+ return LineReader(self.file)
215
+
216
+ def iter_chunked(self, chunk_size: int = Reader.CHUNK_SIZE) -> Reader:
217
+ return Reader(self.file, chunk_size=chunk_size, offset=self._offset)
218
+
219
+
220
+ class BinaryFileWrapper(FileIOWrapperBase):
221
+ def __init__(self, afp: AIOFile):
222
+ if not afp.mode.binary:
223
+ raise ValueError("Expected file in binary mode")
224
+ super().__init__(afp)
225
+
226
+ async def __read(self, length: int) -> bytes:
227
+ data = await self.file.read_bytes(length, self._offset)
228
+ self._offset += len(data)
229
+ return data
230
+
231
+ async def read(self, length: int = -1) -> bytes:
232
+ async with self._lock:
233
+ return await self.__read(length)
234
+
235
+ async def write(self, data: bytes) -> int:
236
+ async with self._lock:
237
+ operation = self.file.write_bytes(data, self._offset)
238
+ self._offset += len(data)
239
+ await operation
240
+ return len(data)
241
+
242
+ async def readline(self, size: int = -1, newline: bytes = b"\n") -> bytes:
243
+ async with self._lock:
244
+ offset = self._offset
245
+ with io.BytesIO() as fp:
246
+ while True:
247
+ chunk = await self.__read(self._READLINE_CHUNK_SIZE)
248
+
249
+ if chunk:
250
+ if newline not in chunk:
251
+ fp.write(chunk)
252
+ continue
253
+
254
+ fp.write(chunk)
255
+
256
+ if 0 < size <= fp.tell():
257
+ fp.seek(size)
258
+ fp.truncate(size)
259
+ return fp.getvalue()
260
+
261
+ fp.seek(0)
262
+ line = fp.readline()
263
+ self._offset = offset + fp.tell()
264
+ return line
265
+
266
+
267
+ class TextFileWrapper(FileIOWrapperBase):
268
+ def __init__(self, afp: AIOFile):
269
+ if afp.mode.binary:
270
+ raise ValueError("Expected file in text mode")
271
+ super().__init__(afp)
272
+ self.encoding = self.file.encoding
273
+
274
+ async def __read(self, length: int) -> str:
275
+ chunk_size = 0
276
+ offset = self._offset
277
+ chunk = ""
278
+ while length < 0 or length > len(chunk):
279
+ part_offset, part = await unicode_reader(
280
+ self.file, length, offset, self.encoding,
281
+ )
282
+
283
+ if not part:
284
+ break
285
+
286
+ chunk += part
287
+ offset += part_offset
288
+
289
+ if chunk_size > length > 0:
290
+ chunk = chunk[:length]
291
+ offset = length
292
+
293
+ self._offset = offset
294
+ return chunk
295
+
296
+ async def read(self, length: int = -1) -> str:
297
+ async with self._lock:
298
+ return await self.__read(length)
299
+
300
+ async def write(self, data: str) -> int:
301
+ async with self._lock:
302
+ data_bytes = data.encode(self.encoding)
303
+ operation = self.file.write_bytes(data_bytes, self._offset)
304
+ self._offset += len(data_bytes)
305
+
306
+ await operation
307
+ return len(data_bytes)
308
+
309
+ async def readline(self, size: int = -1, newline: str = "\n") -> str:
310
+ async with self._lock:
311
+ offset = self._offset
312
+ with io.StringIO() as fp:
313
+ while True:
314
+ chunk = await self.__read(self._READLINE_CHUNK_SIZE)
315
+
316
+ if chunk:
317
+ if newline not in chunk:
318
+ fp.write(chunk)
319
+ continue
320
+
321
+ fp.write(chunk)
322
+
323
+ if 0 < size <= fp.tell():
324
+ fp.seek(size)
325
+ fp.truncate(size)
326
+ return fp.getvalue()
327
+
328
+ fp.seek(0)
329
+ line = fp.readline()
330
+ self._offset = offset + len(
331
+ line.encode(encoding=self.encoding),
332
+ )
333
+ return line
334
+
335
+
336
+ def async_open(
337
+ file_specifier: Union[str, Path, FileIOType],
338
+ mode: str = "r", *args: Any, **kwargs: Any,
339
+ ) -> Union[BinaryFileWrapper, TextFileWrapper]:
340
+ if isinstance(file_specifier, (str, Path)):
341
+ afp = AIOFile(str(file_specifier), mode, *args, **kwargs)
342
+ else:
343
+ if args:
344
+ raise ValueError("Arguments denied when IO[Any] opening.")
345
+ afp = AIOFile.from_fp(file_specifier, **kwargs)
346
+
347
+ if not afp.mode.binary:
348
+ return TextFileWrapper(afp)
349
+
350
+ return BinaryFileWrapper(afp)
351
+
352
+
353
+ __all__ = (
354
+ "BinaryFileWrapper",
355
+ "FileIOWrapperBase",
356
+ "LineReader",
357
+ "Reader",
358
+ "TextFileWrapper",
359
+ "Writer",
360
+ "async_open",
361
+ "unicode_reader",
362
+ )
.venv/lib/python3.10/site-packages/aiofile/version.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.metadata
2
+
3
+
4
+ package_metadata = importlib.metadata.metadata("aiofile")
5
+
6
+ __author__ = package_metadata["Author"]
7
+ __version__ = package_metadata["Version"]
8
+ author_info = [(package_metadata["Author"], package_metadata["Author-email"])]
9
+ package_info = package_metadata["Summary"]
10
+ package_license = package_metadata["License"]
11
+ project_home = package_metadata["Home-page"]
12
+ team_email = package_metadata["Author-email"]
13
+ version_info = tuple(map(int, __version__.split(".")))
.venv/lib/python3.10/site-packages/functorch/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ import torch
7
+ from torch._functorch.deprecated import (
8
+ combine_state_for_ensemble,
9
+ functionalize,
10
+ grad,
11
+ grad_and_value,
12
+ hessian,
13
+ jacfwd,
14
+ jacrev,
15
+ jvp,
16
+ make_functional,
17
+ make_functional_with_buffers,
18
+ vjp,
19
+ vmap,
20
+ )
21
+
22
+ # utilities. Maybe these should go in their own namespace in the future?
23
+ from torch._functorch.make_functional import (
24
+ FunctionalModule,
25
+ FunctionalModuleWithBuffers,
26
+ )
27
+
28
+ # Was never documented
29
+ from torch._functorch.python_key import make_fx
30
+
31
+
32
+ # Top-level APIs. Please think carefully before adding something to the
33
+ # top-level namespace:
34
+ # - private helper functions should go into torch._functorch
35
+ # - very experimental things should go into functorch.experimental
36
+ # - compilation related things should go into functorch.compile
37
+
38
+
39
+ __version__ = torch.__version__
.venv/lib/python3.10/site-packages/functorch/_src/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/functorch/_src/aot_autograd/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # This file has moved to under torch/_functorch. It is not public API.
2
+ # If you are not a PyTorch developer and you are relying on the following
3
+ # imports, please file an issue.
4
+ from torch._functorch.aot_autograd import (
5
+ aot_autograd_decompositions,
6
+ KNOWN_TYPES,
7
+ PytreeThunk,
8
+ )
.venv/lib/python3.10/site-packages/functorch/_src/eager_transforms/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # This file has moved to under torch/_functorch. It is not public API.
2
+ # If you are not a PyTorch developer and you are relying on the following
3
+ # imports, please file an issue.
4
+ from torch._functorch.eager_transforms import (
5
+ _assert_wrapped_functional,
6
+ _unwrap_functional_tensor,
7
+ )
.venv/lib/python3.10/site-packages/functorch/_src/make_functional/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # This file has moved to under torch/_functorch. It is not public API.
2
+ # If you are not a PyTorch developer and you are relying on the following
3
+ # imports, please file an issue.
4
+ from torch._functorch.make_functional import _swap_state
.venv/lib/python3.10/site-packages/functorch/_src/vmap/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file has moved to under torch/_functorch. It is not public API.
2
+ # If you are not a PyTorch developer and you are relying on the following
3
+ # imports, please file an issue.
4
+ from torch._functorch.vmap import (
5
+ _add_batch_dim,
6
+ _broadcast_to_and_flatten,
7
+ _create_batched_inputs,
8
+ _get_name,
9
+ _process_batched_inputs,
10
+ _remove_batch_dim,
11
+ _unwrap_batched,
12
+ _validate_and_get_batch_size,
13
+ Tensor,
14
+ tree_flatten,
15
+ tree_unflatten,
16
+ )
.venv/lib/python3.10/site-packages/functorch/compile/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch._functorch import config
2
+ from torch._functorch.aot_autograd import (
3
+ aot_function,
4
+ aot_module,
5
+ aot_module_simplified,
6
+ compiled_function,
7
+ compiled_module,
8
+ get_aot_compilation_context,
9
+ get_aot_graph_name,
10
+ get_graph_being_compiled,
11
+ make_boxed_compiler,
12
+ make_boxed_func,
13
+ )
14
+ from torch._functorch.compilers import (
15
+ debug_compile,
16
+ default_decompositions,
17
+ draw_graph_compile,
18
+ memory_efficient_fusion,
19
+ nnc_jit,
20
+ nop,
21
+ print_compile,
22
+ ts_compile,
23
+ )
24
+ from torch._functorch.fx_minifier import minifier
25
+ from torch._functorch.partitioners import (
26
+ default_partition,
27
+ draw_graph,
28
+ min_cut_rematerialization_partition,
29
+ )
30
+ from torch._functorch.python_key import pythonkey_decompose
.venv/lib/python3.10/site-packages/functorch/dim/__init__.py ADDED
@@ -0,0 +1,1603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import dis
4
+ import inspect
5
+ import sys
6
+ from typing import Any, Optional, TYPE_CHECKING, Union
7
+
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Callable, Sequence
11
+
12
+ import torch
13
+ from torch.utils._pytree import tree_flatten, tree_map, tree_unflatten
14
+
15
+ from ._dim_entry import _match_levels, DimEntry, ndim_of_levels
16
+ from ._enable_all_layers import EnableAllLayers
17
+ from ._py_inst_decoder import _PyInstDecoder
18
+ from ._tensor_info import TensorInfo
19
+
20
+
21
+ POINTWISE_OPTIMIZE = True
22
+ DOT_OPTIMIZED = True
23
+
24
+ # Global dimension level counter
25
+ _n_dims_created = 0
26
+
27
+
28
+ def _relevant_op(opcode: Optional[str]) -> bool:
29
+ """Check if opcode is relevant for variable assignment."""
30
+ return bool(opcode and opcode.startswith("STORE_"))
31
+
32
+
33
+ def handle_from_tensor(tensor: torch.Tensor) -> torch.Tensor:
34
+ """Handle tensor conversion for torch function integration."""
35
+ return tensor
36
+
37
+
38
+ def _create_dim(name: str, size: Optional[int] = None) -> Dim:
39
+ """Create a new Dim object."""
40
+ return Dim(name, size if size is not None else -1)
41
+
42
+
43
+ def dims(
44
+ n: Optional[int] = None, sizes: Optional[list[Optional[int]]] = None
45
+ ) -> Union[Dim, tuple[Dim, ...]]:
46
+ """
47
+ Create and return one or more Dim objects.
48
+
49
+ Uses bytecode inspection to determine variable names when possible.
50
+
51
+ Args:
52
+ n (int, optional): The number of dimensions to create. Can be omitted if sizes is specified.
53
+ sizes (List[Optional[int]], optional): A list the same size as the number of dimensions to be
54
+ created, specifying each dimensions size, or None to leave the size unset.
55
+
56
+ Returns:
57
+ Union[Dim, Tuple[Dim, ...]]: Single Dim if n=1, tuple of Dims otherwise.
58
+
59
+ Examples:
60
+ >>> batch, channel, width, height = dims(4)
61
+ >>> batch, channel, width, height = dims(sizes=[None, 3, 224, 224])
62
+ >>> single_dim = dims(1)
63
+ """
64
+ specified_ndims = -1
65
+ found_ndims = 0
66
+
67
+ # Parse arguments
68
+ if sizes is not None:
69
+ specified_ndims = len(sizes)
70
+ if n is not None:
71
+ specified_ndims = n
72
+
73
+ # Use bytecode inspection
74
+ frame = inspect.currentframe()
75
+ if frame is None:
76
+ raise RuntimeError("Unable to get current frame")
77
+ frame = frame.f_back
78
+ try:
79
+ if frame is None:
80
+ raise RuntimeError("Unable to get caller frame")
81
+ code = frame.f_code
82
+ lasti = frame.f_lasti
83
+
84
+ decoder = _PyInstDecoder(code, lasti)
85
+
86
+ if sys.version_info >= (3, 11):
87
+ if decoder.opcode() == "PRECALL":
88
+ decoder.next()
89
+
90
+ # Move to next instruction after the call
91
+ decoder.next()
92
+
93
+ # Determine number of dimensions from bytecode
94
+ if _relevant_op(decoder.opcode()):
95
+ found_ndims = 1
96
+ elif decoder.opcode() == "UNPACK_SEQUENCE":
97
+ found_ndims = decoder.oparg()
98
+ decoder.next() # Move past UNPACK_SEQUENCE
99
+
100
+ if specified_ndims == -1:
101
+ if found_ndims == 0:
102
+ raise SyntaxError(
103
+ "dims() must be assigned to a sequence of variable names or have argument n specified"
104
+ )
105
+ specified_ndims = found_ndims
106
+
107
+ if found_ndims != specified_ndims:
108
+ found_ndims = 0
109
+
110
+ def genobject(i: int) -> Dim:
111
+ nonlocal found_ndims
112
+ name = None
113
+ if i < found_ndims:
114
+ name = decoder.name()
115
+
116
+ if not name:
117
+ name = f"d{i}"
118
+ found_ndims = 0
119
+ else:
120
+ decoder.next() # Move to next STORE instruction
121
+
122
+ size = sizes[i] if sizes is not None else None
123
+ return _create_dim(name, size)
124
+
125
+ # Validate sizes parameter
126
+ if sizes is not None and len(sizes) != specified_ndims:
127
+ raise ValueError(f"expected {specified_ndims} sizes but found {len(sizes)}")
128
+
129
+ if specified_ndims == 1:
130
+ return genobject(0)
131
+
132
+ result = []
133
+ for i in range(specified_ndims):
134
+ result.append(genobject(i))
135
+
136
+ return tuple(result)
137
+
138
+ finally:
139
+ del frame
140
+
141
+
142
+ class DimList:
143
+ """
144
+ A list of first-class dimensions that can be bound to tensor dimensions.
145
+
146
+ A DimList can be in one of two states:
147
+ 1. Unbound: Created with just a name, no specific dimensions yet
148
+ 2. Bound: Either created with specific dimensions/sizes, or bound later via bind() or bind_len()
149
+ """
150
+
151
+ _name: Optional[str]
152
+ _dims: list[Dim]
153
+ _bound: bool
154
+
155
+ def __init__(
156
+ self,
157
+ len_or_dims: Optional[Union[int, Sequence]] = None,
158
+ name: Optional[str] = None,
159
+ ):
160
+ """
161
+ Initialize a new DimList object.
162
+
163
+ Args:
164
+ len_or_dims: Optional length (int) or sequence of dimensions/sizes
165
+ name: Optional name for the dimension list
166
+ """
167
+ # Initialize attributes
168
+ self._name = name
169
+ self._dims: list = []
170
+ self._bound = False
171
+
172
+ if isinstance(len_or_dims, int):
173
+ self.bind_len(len_or_dims)
174
+ elif len_or_dims is not None:
175
+ dims = []
176
+ for i, item in enumerate(len_or_dims):
177
+ if isinstance(item, int):
178
+ dim_name = f"{self._name}{i}" if self._name else f"dim{i}"
179
+ dims.append(Dim(dim_name, item))
180
+ else:
181
+ dims.append(Dim(item))
182
+ self._set_dims(dims)
183
+
184
+ def _set_dims(self, dims: list) -> None:
185
+ """Set the dimensions and mark as bound."""
186
+ self._bound = True
187
+ self._dims = dims
188
+
189
+ def bind_len(self, size: int) -> None:
190
+ """
191
+ Bind this DimList to a specific length.
192
+
193
+ Args:
194
+ size: Number of dimensions to bind to
195
+
196
+ Raises:
197
+ DimensionBindError: If already bound to a different size
198
+ """
199
+ if self._bound:
200
+ if len(self._dims) != size:
201
+ raise DimensionBindError(
202
+ f"Dimlist has size {len(self._dims)} but it is being bound to size {size}"
203
+ )
204
+ else:
205
+ self._bound = True
206
+ self._dims = []
207
+ for i in range(size):
208
+ dim_name = f"{self._name}{i}" if self._name else f"dim{i}"
209
+ self._dims.append(Dim(dim_name))
210
+
211
+ def bind(self, sizes: Sequence[int]) -> None:
212
+ """
213
+ Bind this DimList to specific sizes.
214
+
215
+ Args:
216
+ sizes: Sequence of sizes for each dimension
217
+
218
+ Raises:
219
+ ValueError: If sizes is not a sequence
220
+ """
221
+ if not hasattr(sizes, "__len__") or not hasattr(sizes, "__getitem__"):
222
+ raise ValueError("expected a sequence")
223
+
224
+ size = len(sizes)
225
+ self.bind_len(size)
226
+
227
+ for i, dim_size in enumerate(sizes):
228
+ self._dims[i].size = int(dim_size)
229
+
230
+ def _size(self) -> int:
231
+ if not self._bound:
232
+ raise DimensionBindError("DimList not bound")
233
+ return len(self._dims)
234
+
235
+ def size(self) -> int:
236
+ """Return the size (number of dimensions) of this DimList."""
237
+ return self._size()
238
+
239
+ def _set_bound(self, b: bool) -> None:
240
+ """Set the bound status (for internal use)."""
241
+ self._bound = b
242
+
243
+ @property
244
+ def is_bound(self) -> bool:
245
+ """Property to check if DimList is bound."""
246
+ return self._bound
247
+
248
+ def __len__(self) -> int:
249
+ """Return the length of the DimList."""
250
+ return self.size()
251
+
252
+ def __getitem__(self, key: Union[int, slice]) -> Union[Dim, tuple[Dim, ...]]:
253
+ if not self._bound:
254
+ raise DimensionBindError("DimList not bound")
255
+
256
+ if isinstance(key, int):
257
+ if key < 0 or key >= len(self._dims):
258
+ raise IndexError("index out of bounds")
259
+ return self._dims[key]
260
+ elif isinstance(key, slice):
261
+ start, stop, step = key.indices(len(self._dims))
262
+ result = []
263
+ for i in range(start, stop, step):
264
+ result.append(self._dims[i])
265
+ return tuple(result)
266
+ else:
267
+ raise ValueError("expected an int or a slice")
268
+
269
+ def __repr__(self) -> str:
270
+ """Return string representation of the DimList."""
271
+ if self._bound:
272
+ # Show as tuple representation
273
+ return f"({', '.join(repr(dim) for dim in self._dims)})"
274
+ elif self._name is not None:
275
+ # Show as *name for unbound with name
276
+ return f"*{self._name}"
277
+ else:
278
+ # Show as <unbound_dimlist> for unbound without name
279
+ return "<unbound_dimlist>"
280
+
281
+ def __str__(self) -> str:
282
+ """Return string representation of the DimList."""
283
+ return self.__repr__()
284
+
285
+ @classmethod
286
+ def __torch_function__(
287
+ cls,
288
+ func: Callable,
289
+ types: tuple,
290
+ args: tuple = (),
291
+ kwargs: Optional[dict] = None,
292
+ ) -> Any:
293
+ return _Tensor.__torch_function__(func, types, args, kwargs)
294
+
295
+
296
+ def _create_dimlist(
297
+ name: str, size: Optional[Union[int, list[Optional[int]]]] = None
298
+ ) -> DimList:
299
+ """Create a DimList object with the given name and optional size."""
300
+ dimlist = DimList(name=name)
301
+ if size is not None:
302
+ if isinstance(size, int):
303
+ dimlist.bind_len(size)
304
+ else:
305
+ # size is a list of optional ints
306
+ dimlist.bind_len(len(size))
307
+ for i, s in enumerate(size):
308
+ if s is not None:
309
+ dimlist._dims[i].size = s
310
+ return dimlist
311
+
312
+
313
+ def dimlists(
314
+ n: Optional[int] = None, sizes: Optional[list[Optional[int]]] = None
315
+ ) -> Union[DimList, tuple[DimList, ...]]:
316
+ """
317
+ Create and return one or more DimList objects.
318
+
319
+ Similar to dims() but creates DimList objects instead.
320
+ """
321
+ specified_ndims = -1
322
+ found_ndims = 0
323
+
324
+ # Parse arguments
325
+ if sizes is not None:
326
+ specified_ndims = len(sizes)
327
+ if n is not None:
328
+ specified_ndims = n
329
+
330
+ frame = inspect.currentframe()
331
+ if frame is None:
332
+ raise RuntimeError("Unable to get current frame")
333
+ frame = frame.f_back
334
+ try:
335
+ if frame is None:
336
+ raise RuntimeError("Unable to get caller frame")
337
+ code = frame.f_code
338
+ lasti = frame.f_lasti
339
+
340
+ decoder = _PyInstDecoder(code, lasti)
341
+
342
+ if sys.version_info >= (3, 11):
343
+ if decoder.opcode() == "PRECALL":
344
+ decoder.next()
345
+
346
+ # Move to next instruction after the call
347
+ decoder.next()
348
+
349
+ # Determine number of dimensions from bytecode
350
+ if _relevant_op(decoder.opcode()):
351
+ found_ndims = 1
352
+ elif decoder.opcode() == "UNPACK_SEQUENCE":
353
+ found_ndims = decoder.oparg()
354
+ decoder.next() # Move past UNPACK_SEQUENCE
355
+
356
+ if specified_ndims == -1:
357
+ if found_ndims == 0:
358
+ raise SyntaxError(
359
+ "dimlists() must be assigned to a sequence of variable names or have argument n specified"
360
+ )
361
+ specified_ndims = found_ndims
362
+
363
+ if found_ndims != specified_ndims:
364
+ found_ndims = 0
365
+
366
+ # Generator function for dimlist names
367
+ def genobject(i: int) -> str:
368
+ nonlocal found_ndims
369
+ name = None
370
+ if i < found_ndims:
371
+ name = decoder.name()
372
+
373
+ if not name:
374
+ name = f"d{i}"
375
+ found_ndims = 0
376
+ else:
377
+ decoder.next() # Move to next STORE instruction
378
+
379
+ return name
380
+
381
+ # Validate sizes
382
+ if sizes is not None and len(sizes) != specified_ndims:
383
+ raise ValueError(f"expected {specified_ndims} sizes but found {len(sizes)}")
384
+
385
+ # Create dimlists
386
+ if specified_ndims == 1:
387
+ name = genobject(0)
388
+ return _create_dimlist(name, sizes[0] if sizes is not None else None)
389
+
390
+ result = []
391
+ for i in range(specified_ndims):
392
+ name = genobject(i)
393
+ size = sizes[i] if sizes is not None else None
394
+ result.append(_create_dimlist(name, size))
395
+
396
+ return tuple(result)
397
+
398
+ finally:
399
+ del frame
400
+
401
+
402
+ class DimensionMismatchError(Exception):
403
+ pass
404
+
405
+
406
+ class DimensionBindError(Exception):
407
+ pass
408
+
409
+
410
+ from . import op_properties
411
+
412
+
413
+ def _safe_print(*args: Any, **kwargs: Any) -> None:
414
+ """Safe print that avoids recursive torch function dispatches."""
415
+ import sys
416
+
417
+ # Convert any torch objects to basic representations
418
+ safe_args = []
419
+ for arg in args:
420
+ if hasattr(arg, "__class__") and "torch" in str(type(arg)):
421
+ safe_args.append(f"<{type(arg).__name__}>")
422
+ else:
423
+ safe_args.append(str(arg))
424
+
425
+ print(*safe_args, **kwargs, file=sys.stderr)
426
+
427
+
428
+ class _Tensor:
429
+ def _get_levels(self) -> list[Any]:
430
+ raise NotImplementedError("_get_levels must be implemented by subclass")
431
+
432
+ def _get_tensor(self) -> Optional[torch.Tensor]:
433
+ raise NotImplementedError("_get_tensor must be implemented by subclass")
434
+
435
+ @property
436
+ def ndim(self) -> int:
437
+ raise NotImplementedError("ndim must be implemented by subclass")
438
+
439
+ @property
440
+ def dims(self) -> tuple[Any, ...]:
441
+ return tuple(l.dim() for l in self._get_levels() if not l.is_positional())
442
+
443
+ def dim(self) -> int:
444
+ return self.ndim
445
+
446
+ @classmethod
447
+ def __torch_function__(
448
+ cls,
449
+ func: Callable,
450
+ types: tuple,
451
+ args: tuple = (),
452
+ kwargs: Optional[dict] = None,
453
+ ) -> Any:
454
+ if kwargs is None:
455
+ kwargs = {}
456
+
457
+ if DOT_OPTIMIZED and func is torch.Tensor.__mul__:
458
+ # Check conditions: 2 args, both are tensor-like, both 0-dimensional
459
+ if (
460
+ len(args) == 2
461
+ and not kwargs
462
+ and isinstance(args[0], (_Tensor, torch.Tensor))
463
+ and isinstance(args[1], (_Tensor, torch.Tensor))
464
+ ):
465
+ # Get tensor info for both operands
466
+ lhs_info = TensorInfo.create(
467
+ args[0], ensure_batched=False, ensure_present=False
468
+ )
469
+ rhs_info = TensorInfo.create(
470
+ args[1], ensure_batched=False, ensure_present=False
471
+ )
472
+
473
+ if (
474
+ lhs_info
475
+ and rhs_info
476
+ and lhs_info.tensor is not None
477
+ and rhs_info.tensor is not None
478
+ and lhs_info.tensor.dim() == 0
479
+ and rhs_info.tensor.dim() == 0
480
+ ):
481
+ if (
482
+ lhs_info.tensor.is_floating_point()
483
+ and rhs_info.tensor.is_floating_point()
484
+ ):
485
+ # Collect all unique levels and has_device
486
+ has_device = lhs_info.has_device or rhs_info.has_device
487
+ levels = []
488
+
489
+ for level in lhs_info.levels:
490
+ if level not in levels:
491
+ levels.append(level)
492
+ for level in rhs_info.levels:
493
+ if level not in levels:
494
+ levels.append(level)
495
+
496
+ # Debug print
497
+ # print(f"DEBUG: Creating delayed mul, levels: {levels}, has_device: {has_device}")
498
+
499
+ # Create delayed tensor
500
+ return Tensor.create_delayed(func, args, levels, has_device)
501
+
502
+ if func is torch.Tensor.__getitem__:
503
+ from functorch.dim._getsetitem import getitem
504
+
505
+ return getitem(cls, func, types, args, kwargs)
506
+
507
+ if func is torch.Tensor.__setitem__:
508
+ from functorch.dim._getsetitem import setitem
509
+
510
+ # args should be (tensor, index, value)
511
+ if len(args) == 3:
512
+ setitem(args[0], args[1], args[2])
513
+ return None
514
+ else:
515
+ raise ValueError(f"Expected 3 args for __setitem__, got {len(args)}")
516
+
517
+ # Fast-path for len; mostly to avoid infinite loop in TestMinFunctorchOnly.test_softmax_split
518
+ if func is torch.Tensor.__len__:
519
+ return args[0].size(0)
520
+
521
+ # Special handling for torch.softmax - use the pre-wrapped version
522
+ if func is torch.softmax:
523
+ return softmax(*args, **kwargs)
524
+
525
+ # Special handling for torch.stack - use the custom stack function
526
+ if func is torch.stack:
527
+ return stack(*args, **kwargs)
528
+
529
+ if (
530
+ func is torch.Tensor.split
531
+ or func is torch._VF.split # type: ignore[attr-defined]
532
+ or func is torch._VF.split_with_sizes # type: ignore[attr-defined]
533
+ or func is torch.split
534
+ ):
535
+ return split(*args, **kwargs)
536
+
537
+ return _Tensor._torch_function_fallback(func, types, args, kwargs)
538
+
539
+ @staticmethod
540
+ def _torch_function_fallback(
541
+ func: Callable, types: tuple, args: tuple, kwargs: dict
542
+ ) -> Any:
543
+ """Fallback torch function implementation for non-special-cased functions."""
544
+ is_pointwise = POINTWISE_OPTIMIZE and func in op_properties.pointwise
545
+ # TODO: optimize pytree here
546
+ flat_args, spec = tree_flatten((args, kwargs))
547
+ device_holding_tensor = None
548
+
549
+ infos: list[TensorInfo] = []
550
+ result_levels: list[DimEntry] = []
551
+
552
+ for f in flat_args:
553
+ info = TensorInfo.create(f, not is_pointwise, False)
554
+ infos.append(info)
555
+ if info:
556
+ if not (is_pointwise or info.batchedtensor is not None):
557
+ raise AssertionError(
558
+ "Expected pointwise or batchedtensor to be set"
559
+ )
560
+ if device_holding_tensor is None and info.has_device:
561
+ device_holding_tensor = info.tensor
562
+ # Collect all unique levels
563
+ for level in info.levels:
564
+ if not isinstance(level, DimEntry):
565
+ raise AssertionError(f"Expected DimEntry, got {type(level)}")
566
+ if level not in result_levels:
567
+ result_levels.append(level)
568
+
569
+ if is_pointwise:
570
+ # Pointwise operation: match all tensors to common levels
571
+ for i, info in enumerate(infos):
572
+ if info and info.tensor is not None:
573
+ tensor = info.tensor
574
+ if device_holding_tensor is not None and not info.has_device:
575
+ tensor = tensor.to(device_holding_tensor.device)
576
+ ml = _match_levels(tensor, info.levels, result_levels)
577
+ flat_args[i] = handle_from_tensor(ml)
578
+
579
+ unflat_args, unflat_kwargs = tree_unflatten(flat_args, spec)
580
+ result = func(*unflat_args, **unflat_kwargs)
581
+
582
+ # Wrap tensor results
583
+ def wrap_tensor(obj: Any) -> Any:
584
+ if isinstance(obj, torch.Tensor):
585
+ return Tensor.from_positional(
586
+ obj, result_levels, device_holding_tensor is not None
587
+ )
588
+ return obj
589
+
590
+ # Small fastpath
591
+ if isinstance(result, torch.Tensor):
592
+ return wrap_tensor(result)
593
+ else:
594
+ return tree_map(wrap_tensor, result)
595
+
596
+ # Non-pointwise operation: use functorch vmap layers
597
+ with EnableAllLayers(result_levels) as guard:
598
+ # Update arguments with batched tensors
599
+ for i, info in enumerate(infos):
600
+ if info and info.batchedtensor is not None:
601
+ batched = info.batchedtensor
602
+ if device_holding_tensor is not None and not info.has_device:
603
+ batched = batched.to(device_holding_tensor.device)
604
+ guard.inplace_update_layers(batched, info.levels)
605
+ flat_args[i] = handle_from_tensor(batched)
606
+
607
+ unflat_args, unflat_kwargs = tree_unflatten(flat_args, spec)
608
+ result = func(*unflat_args, **unflat_kwargs)
609
+
610
+ # Unwrap results from functorch layers
611
+ def unwrap_tensor(obj: Any) -> Any:
612
+ if isinstance(obj, torch.Tensor):
613
+ return guard.from_batched(obj, device_holding_tensor is not None)
614
+ return obj
615
+
616
+ if isinstance(result, torch.Tensor):
617
+ return unwrap_tensor(result)
618
+ else:
619
+ return tree_map(unwrap_tensor, result)
620
+
621
+ def __setitem__(self, index: Any, value: Any) -> None:
622
+ """Set values in tensor using first-class dimensions."""
623
+ from functorch.dim._getsetitem import setitem
624
+
625
+ return setitem(self, index, value)
626
+
627
+ # expand and index are OK to be methods because they don't have torch.*
628
+ # versions, but if they did they need the stack/cat treatment
629
+
630
+ def expand(self, *args: Dim) -> _Tensor:
631
+ """
632
+ Expand tensor by adding new dimensions or expanding existing dimensions.
633
+
634
+ If all arguments are Dim objects, adds new named dimensions.
635
+ Otherwise, falls back to regular tensor expansion behavior.
636
+
637
+ Args:
638
+ args: Either Dim objects for new dimensions or sizes for regular expansion
639
+
640
+ Returns:
641
+ New tensor with expanded dimensions
642
+
643
+ Example:
644
+ >>> i, j = dims()
645
+ >>> t = torch.randn(3, 4)
646
+ >>> expanded = t[i].expand(j, k) # Add j, k dimensions
647
+ >>> expanded2 = t[i].expand(2, 4) # Regular expand with sizes
648
+ """
649
+ info = TensorInfo.create(self, ensure_batched=False, ensure_present=False)
650
+
651
+ for arg in args:
652
+ if not isinstance(arg, Dim):
653
+ # Not all args are Dims, fallback to regular expand
654
+ if isinstance(self, torch.Tensor) and not isinstance(self, _Tensor):
655
+ return torch.Tensor.expand(self, *args)
656
+ else:
657
+ return self.__torch_function__(
658
+ torch.Tensor.expand, (type(self),), (self,) + args
659
+ )
660
+
661
+ # All args are Dim objects - proceed with first-class dimension expansion
662
+ if not info:
663
+ # No tensor info available, fallback
664
+ return self.__torch_function__(
665
+ torch.Tensor.expand, (type(self),), (self,) + args
666
+ )
667
+
668
+ # First-class dimension expansion - all args are Dim objects
669
+ data = info.tensor
670
+ if data is None:
671
+ # No tensor data available, fallback
672
+ return self.__torch_function__(
673
+ torch.Tensor.expand, (type(self),), (self,) + args
674
+ )
675
+
676
+ levels = info.levels
677
+
678
+ new_levels: list[DimEntry] = []
679
+ new_sizes = []
680
+ new_strides = []
681
+
682
+ for d in args:
683
+ # Check if dimension already exists in current levels or new_levels
684
+ for level in levels:
685
+ if not level.is_positional() and level.dim() is d:
686
+ raise DimensionBindError(
687
+ f"expanding dimension {d} already exists in tensor with dims"
688
+ )
689
+ for new_level in new_levels:
690
+ if not new_level.is_positional() and new_level.dim() is d:
691
+ raise DimensionBindError(
692
+ f"expanding dimension {d} already exists in tensor with dims"
693
+ )
694
+
695
+ new_levels.append(DimEntry(d))
696
+ new_sizes.append(d.size)
697
+ new_strides.append(0)
698
+
699
+ # Add existing levels
700
+ new_levels.extend(levels)
701
+
702
+ # Add existing sizes and strides
703
+ orig_sizes = list(data.size())
704
+ orig_strides = list(data.stride())
705
+ new_sizes.extend(orig_sizes)
706
+ new_strides.extend(orig_strides)
707
+
708
+ # Create expanded tensor using as_strided
709
+ expanded_data = data.as_strided(new_sizes, new_strides, data.storage_offset())
710
+
711
+ # Return new tensor with expanded dimensions
712
+ result = Tensor.from_positional(expanded_data, new_levels, info.has_device)
713
+ return result # type: ignore[return-value] # Tensor and torch.Tensor are interchangeable
714
+
715
+ def index(
716
+ self,
717
+ dims: Union[int, Dim, tuple[Union[int, Dim], ...], list[Union[int, Dim]]],
718
+ indices: Union[
719
+ int,
720
+ slice,
721
+ torch.Tensor,
722
+ tuple[Union[int, slice, torch.Tensor], ...],
723
+ list[Union[int, slice, torch.Tensor]],
724
+ ],
725
+ ) -> _Tensor:
726
+ """
727
+ Index tensor using first-class dimensions.
728
+ """
729
+ from ._dim_entry import _match_levels
730
+ from ._getsetitem import getsetitem_flat, invoke_getitem
731
+ from ._wrap import _wrap_dim
732
+
733
+ # Helper to check if obj is a dimpack (tuple/list) and extract items
734
+ def maybe_dimpack(obj: Any, check_first: bool = False) -> tuple[Any, bool]:
735
+ if isinstance(obj, (tuple, list)):
736
+ return list(obj), True
737
+ return None, False
738
+
739
+ def parse_dim_entry(s: Any) -> Any:
740
+ d = _wrap_dim(s, self.ndim, False)
741
+ if d.is_none():
742
+ raise TypeError(f"expected a dimension specifyer but found {repr(s)}")
743
+ return d
744
+
745
+ # Helper for dimension not present errors
746
+ def dim_not_present(d: Any) -> None:
747
+ if d.is_positional():
748
+ raise TypeError(
749
+ f"dimension {d.position() + self.ndim} not in tensor of {self.ndim} dimensions"
750
+ )
751
+ else:
752
+ raise TypeError(f"dimension {repr(d.dim())} not in tensor")
753
+
754
+ dims_list: list[Union[int, Dim]] = []
755
+ indices_list: list[Union[int, slice, torch.Tensor]] = []
756
+
757
+ lhs_list = isinstance(dims, (tuple, list))
758
+ rhs_list = isinstance(indices, (tuple, list))
759
+
760
+ if lhs_list and rhs_list:
761
+ # Type narrowing: we know dims and indices are sequences here
762
+ dims_seq = dims # type: ignore[assignment]
763
+ indices_seq = indices # type: ignore[assignment]
764
+ if len(dims_seq) != len(indices_seq): # type: ignore[arg-type]
765
+ raise TypeError(
766
+ f"dims ({len(dims_seq)}) and indices ({len(indices_seq)}) must have the same length" # type: ignore[arg-type]
767
+ )
768
+ dims_list.extend(dims_seq) # type: ignore[arg-type]
769
+ indices_list.extend(indices_seq) # type: ignore[arg-type]
770
+ else:
771
+ dims_list.append(dims) # type: ignore[arg-type]
772
+ indices_list.append(indices) # type: ignore[arg-type]
773
+
774
+ # Create tensor info
775
+ self_info = TensorInfo.create(self, False, False)
776
+
777
+ new_levels: list[Any] = []
778
+ to_flatten: list[Any] = []
779
+ dims_list_flat = []
780
+
781
+ # Process each dim specification
782
+ for i in range(len(dims_list)):
783
+ m, is_dimpack = maybe_dimpack(dims_list[i], check_first=False)
784
+ if is_dimpack:
785
+ if len(m) == 0:
786
+ dims_list_flat.append(DimEntry()) # Empty dimpack
787
+ continue
788
+
789
+ first = parse_dim_entry(m[0])
790
+ dims_list_flat.append(first)
791
+
792
+ if len(m) == 1:
793
+ continue
794
+
795
+ # Multi-element dimpack requires flattening
796
+ if len(to_flatten) == 0:
797
+ new_levels.extend(self_info.levels)
798
+
799
+ rest = []
800
+ for j in range(1, len(m)):
801
+ d = parse_dim_entry(m[j])
802
+ removed = False
803
+ for k in range(len(new_levels)):
804
+ if new_levels[k] == d:
805
+ new_levels.pop(k)
806
+ removed = True
807
+ break
808
+ if not removed:
809
+ dim_not_present(d)
810
+ rest.append(d)
811
+
812
+ # Find first in new_levels
813
+ first_idx = None
814
+ for k in range(len(new_levels)):
815
+ if new_levels[k] == first:
816
+ first_idx = k
817
+ break
818
+ if first_idx is None:
819
+ dim_not_present(first)
820
+ continue # Skip this iteration if dimension not found
821
+
822
+ for j, r in enumerate(rest):
823
+ new_levels.insert(first_idx + 1 + j, r)
824
+ to_flatten.extend(rest)
825
+ else:
826
+ dims_list_flat.append(parse_dim_entry(dims_list[i]))
827
+
828
+ # Handle dimension flattening if needed
829
+ if len(to_flatten) > 0:
830
+ if self_info.tensor is None:
831
+ raise AssertionError(
832
+ "Cannot perform dimension flattening on None tensor"
833
+ )
834
+ rearranged = _match_levels(self_info.tensor, self_info.levels, new_levels)
835
+ sizes = rearranged.size()
836
+ new_sizes: list[Any] = []
837
+ reshape_levels = []
838
+
839
+ for i in range(len(new_levels)):
840
+ if new_levels[i] in to_flatten:
841
+ if len(new_sizes) == 0:
842
+ new_sizes.append(sizes[i])
843
+ else:
844
+ new_sizes[-1] *= sizes[i]
845
+ else:
846
+ new_sizes.append(sizes[i])
847
+ reshape_levels.append(new_levels[i])
848
+
849
+ self_info.tensor = rearranged.reshape(new_sizes)
850
+ self_info.levels = reshape_levels
851
+
852
+ # Check for dimpacks in indices
853
+ has_dimpacks = False
854
+ for idx in indices_list:
855
+ if isinstance(idx, (tuple, list)):
856
+ has_dimpacks = True
857
+ break
858
+
859
+ # Call getsetitem_flat with correct parameters
860
+ info = getsetitem_flat(
861
+ self_info,
862
+ [], # empty input_list
863
+ dims_list_flat, # keys
864
+ indices_list, # values
865
+ has_dimpacks,
866
+ )
867
+
868
+ return invoke_getitem(info)
869
+
870
+ def __repr__(self) -> str:
871
+ tensor, levels, ndim = self._get_tensor(), self._get_levels(), self.ndim
872
+ dims_repr = []
873
+ for l in levels:
874
+ if hasattr(l, "is_positional") and l.is_positional():
875
+ # Convert negative positional to positive: -1 -> ndim-1, -2 -> ndim-2, etc.
876
+ dims_repr.append(l.position() + ndim)
877
+ elif hasattr(l, "dim"):
878
+ dims_repr.append(l.dim())
879
+ elif hasattr(l, "data"):
880
+ dims_repr.append(l.data)
881
+ else:
882
+ dims_repr.append(l)
883
+ return f"{tensor}\nwith dims={tuple(dims_repr)} sizes={tuple(tensor.size())}" # type: ignore[union-attr]
884
+
885
+
886
+ TensorLike = (_Tensor, torch.Tensor)
887
+
888
+
889
+ class Dim(_Tensor):
890
+ _level: int
891
+ _name: str
892
+ _size: int
893
+ _range: Optional[torch.Tensor]
894
+ _batchtensor: Optional[torch.Tensor]
895
+
896
+ def __init__(self, name: str, s: int = -1) -> None:
897
+ global _n_dims_created
898
+ self._name = name
899
+ self._size = s
900
+ self._level = _n_dims_created
901
+ _n_dims_created += 1
902
+ self._range = None
903
+ self._batchtensor = None
904
+
905
+ @property
906
+ def ndim(self) -> int:
907
+ return 1
908
+
909
+ @classmethod
910
+ def check_exact(cls, obj: Any) -> bool:
911
+ return type(obj) is cls
912
+
913
+ @property
914
+ def size(self) -> int:
915
+ if self._size == -1:
916
+ raise ValueError(f"dimension {self._name} is unbound")
917
+ return self._size
918
+
919
+ @size.setter
920
+ def size(self, v: int) -> None:
921
+ if self._size == -1:
922
+ self._size = v
923
+ elif self._size != v:
924
+ raise DimensionBindError(
925
+ f"Dim '{repr(self)}' previously bound to a dimension of size {self._size} "
926
+ f"cannot bind to a dimension of size {v}"
927
+ )
928
+
929
+ @property
930
+ def is_bound(self) -> bool:
931
+ """Return True if this dimension is bound to a size."""
932
+ return self._size != -1
933
+
934
+ def _get_range(self) -> torch.Tensor:
935
+ """
936
+ Get a tensor representing the range [0, size) for this dimension.
937
+
938
+ Returns:
939
+ A 1D tensor with values [0, 1, 2, ..., size-1]
940
+ """
941
+ if self._range is None:
942
+ self._range = torch.arange(self.size)
943
+ return self._range
944
+
945
+ def _get_batchtensor(self) -> torch.Tensor:
946
+ """
947
+ Get a batched tensor representation of this dimension.
948
+
949
+ Returns:
950
+ A batched tensor created from the range tensor
951
+ """
952
+ if self._batchtensor is None:
953
+ self._batchtensor = torch._C._functorch._add_batch_dim(
954
+ self._get_range(), 0, self._level
955
+ )
956
+ return self._batchtensor
957
+
958
+ def __repr__(self) -> str:
959
+ """String representation of a Dim object."""
960
+ return self._name
961
+
962
+ # note that Dim comes before tensor because we want the Dim API for things like size to take precedence.
963
+ # Tensor defines format, but we want to print Dims with special formatting
964
+ __format__ = object.__format__
965
+
966
+
967
+ # Somewhat confusingly, an FCD tensor is also called Tensor. This confusion
968
+ # is somewhat intentional, as FCD tensors are intended to be substitutable
969
+ # with regular Tensor (just with some positional dims hidden).
970
+ class Tensor(_Tensor):
971
+ _tensor: Optional[torch.Tensor]
972
+ _batchtensor: Optional[torch.Tensor]
973
+ _levels: list[DimEntry]
974
+ _has_device: bool
975
+ _delayed: Optional[Callable[[], torch.Tensor]]
976
+ _delayed_orig: Optional[Callable]
977
+ _delayed_args: Optional[tuple]
978
+
979
+ @property
980
+ def ndim(self) -> int:
981
+ return sum(1 if l.is_positional() else 0 for l in self._levels)
982
+
983
+ @classmethod
984
+ def check_exact(cls, other: Any) -> bool:
985
+ return type(other) is cls
986
+
987
+ @classmethod
988
+ def from_positional(
989
+ cls, tensor: torch.Tensor, levels: list[DimEntry], has_device: bool
990
+ ) -> Union[_Tensor, torch.Tensor]:
991
+ """
992
+ Create a functorch Tensor from a regular PyTorch tensor with specified dimension levels.
993
+
994
+ This is the primary way to create Tensor objects with first-class dimensions.
995
+
996
+ Args:
997
+ tensor: The underlying PyTorch tensor
998
+ levels: List of DimEntry objects specifying the dimension structure
999
+ has_device: Whether the tensor is on a device (not CPU)
1000
+
1001
+ Returns:
1002
+ A new Tensor instance with the specified dimensions, or a regular torch.Tensor
1003
+ if there are no named dimensions
1004
+ """
1005
+ seen_dims = 0
1006
+ last = 0
1007
+
1008
+ for l in levels:
1009
+ if l.is_positional():
1010
+ # Validate consecutive positional dimensions
1011
+ if not (last == 0 or last + 1 == l.position()):
1012
+ raise AssertionError(
1013
+ f"Positional dimensions must be consecutive, got {last} then {l.position()}"
1014
+ )
1015
+ last = l.position()
1016
+ else:
1017
+ # This is a named dimension
1018
+ seen_dims += 1
1019
+
1020
+ # Validate final positional dimension
1021
+ if not (last == 0 or last == -1):
1022
+ raise AssertionError(
1023
+ f"Final positional dimension must be 0 or -1, got {last}"
1024
+ )
1025
+
1026
+ if not seen_dims:
1027
+ return tensor
1028
+
1029
+ # Create Tensor object with proper level management
1030
+ result = cls()
1031
+ result._tensor = tensor
1032
+ result._levels = levels
1033
+ result._has_device = has_device
1034
+ result._batchtensor = None # Will be created lazily if needed
1035
+ result._delayed = None
1036
+ result._delayed_orig = None
1037
+ result._delayed_args = None
1038
+
1039
+ # Validate tensor dimensionality matches levels
1040
+ if tensor.dim() != len(levels):
1041
+ raise AssertionError(
1042
+ f"Tensor has {tensor.dim()} dimensions but {len(levels)} levels provided"
1043
+ )
1044
+
1045
+ return result
1046
+
1047
+ @classmethod
1048
+ def create_delayed(
1049
+ cls, orig: Callable, args: tuple, levels: list[DimEntry], has_device: bool
1050
+ ) -> _Tensor:
1051
+ """
1052
+ Create a delayed tensor that defers the operation until later.
1053
+ """
1054
+ result = cls()
1055
+ result._tensor = None # Will be computed when needed
1056
+ result._levels = levels
1057
+ result._has_device = has_device
1058
+ result._batchtensor = None
1059
+ result._delayed_orig = orig
1060
+ result._delayed_args = args
1061
+
1062
+ # Create delayed evaluation function that unwraps Tensor objects
1063
+ def evaluate_delayed() -> torch.Tensor:
1064
+ unwrapped_args = []
1065
+ for arg in args:
1066
+ if hasattr(arg, "_get_tensor"):
1067
+ unwrapped_args.append(arg._get_tensor())
1068
+ else:
1069
+ unwrapped_args.append(arg)
1070
+ return orig(*unwrapped_args)
1071
+
1072
+ result._delayed = evaluate_delayed
1073
+
1074
+ return result
1075
+
1076
+ def _get_tensor(self) -> Optional[torch.Tensor]:
1077
+ """Get the underlying tensor, handling delayed operations if needed."""
1078
+ if (
1079
+ hasattr(self, "_delayed")
1080
+ and self._delayed is not None
1081
+ and self._tensor is None
1082
+ ):
1083
+ # Execute the delayed operation
1084
+ self._tensor = self._delayed()
1085
+ # Clear delayed operation to avoid re-execution
1086
+ self._delayed = None
1087
+ self._delayed_orig = None
1088
+ self._delayed_args = None
1089
+ return self._tensor
1090
+
1091
+ def _get_levels(self) -> list[Any]:
1092
+ """Get the dimension levels."""
1093
+ return self._levels
1094
+
1095
+ def _get_has_device(self) -> bool:
1096
+ """Get whether this tensor has device information."""
1097
+ return self._has_device
1098
+
1099
+ def _get_batchtensor(self) -> Optional[torch.Tensor]:
1100
+ """Get the batched tensor representation, creating it lazily if needed."""
1101
+ if self._batchtensor is None:
1102
+ self._batchtensor = self._add_batch_dims(
1103
+ self._get_tensor(), self._get_levels()
1104
+ )
1105
+ return self._batchtensor
1106
+
1107
+ def _add_batch_dims(
1108
+ self, t: Optional[torch.Tensor], levels_: list[Any]
1109
+ ) -> Optional[torch.Tensor]:
1110
+ levels = list(levels_)
1111
+
1112
+ while True:
1113
+ min_real_index = -1
1114
+ min_index = -1
1115
+ min_value = float("inf") # INT_MAX equivalent
1116
+ i = 0
1117
+ r = 0
1118
+
1119
+ for r, l in enumerate(levels):
1120
+ if not l.is_none():
1121
+ if not l.is_positional() and l.dim()._level < min_value:
1122
+ min_value = l.dim()._level
1123
+ min_index = i
1124
+ min_real_index = r
1125
+ i += 1
1126
+
1127
+ if min_index == -1:
1128
+ return t
1129
+
1130
+ if t is None:
1131
+ raise AssertionError("Expected t to be non-None")
1132
+ t = torch._C._functorch._add_batch_dim(t, min_index, int(min_value))
1133
+
1134
+ levels[min_real_index] = DimEntry()
1135
+ return None
1136
+
1137
+ def order(self, *dims: Any) -> _Tensor:
1138
+ """Reorder the dimensions of this tensor."""
1139
+ from ._order import order
1140
+
1141
+ result = order(self, *dims)
1142
+ return result # type: ignore[return-value] # Tensor and torch.Tensor are interchangeable
1143
+
1144
+
1145
+ def stack(tensors: Any, new_dim: Any, dim: int = 0) -> _Tensor:
1146
+ """
1147
+ Stack tensors along a new dimension.
1148
+
1149
+ Args:
1150
+ tensors: Sequence of tensors to stack
1151
+ new_dim: The new Dim to create for stacking
1152
+ dim: The dimension position to insert the new dimension (default: 0)
1153
+
1154
+ Returns:
1155
+ Stacked tensor with the new dimension
1156
+ """
1157
+ if not tensors:
1158
+ raise ValueError("stack expects a non-empty sequence of tensors")
1159
+
1160
+ # Check if new_dim is a Dim object
1161
+ if not isinstance(new_dim, Dim):
1162
+ # Fall back to regular torch.stack
1163
+ result = torch.stack(tensors, dim=dim)
1164
+ return result # type: ignore[return-value]
1165
+
1166
+ # Collect all result_levels from input tensors
1167
+ result_levels = []
1168
+ infos = []
1169
+
1170
+ for t in tensors:
1171
+ info = TensorInfo.create(t, ensure_batched=False, ensure_present=False)
1172
+ infos.append(info)
1173
+ for level in info.levels:
1174
+ if level not in result_levels:
1175
+ result_levels.append(level)
1176
+
1177
+ # Set the new_dim size to match number of tensors
1178
+ new_dim.size = len(tensors)
1179
+
1180
+ # Match all tensors to the common level structure using _match_levels
1181
+ inputs = []
1182
+ for info in infos:
1183
+ if info.tensor is None:
1184
+ raise AssertionError("Cannot stack tensors with None tensor data")
1185
+ matched_tensor = _match_levels(info.tensor, info.levels, result_levels)
1186
+ inputs.append(matched_tensor)
1187
+
1188
+ # Calculate ndim and resolve the dim parameter
1189
+ ndim = ndim_of_levels(result_levels)
1190
+ rawdim = 0
1191
+ if dim is not None and not (isinstance(dim, int) and dim == 0):
1192
+ from ._wrap import _wrap_dim
1193
+
1194
+ d = _wrap_dim(dim, ndim, False)
1195
+ try:
1196
+ idx = result_levels.index(d)
1197
+ except ValueError:
1198
+ raise TypeError(f"Dimension {dim} does not exist in inputs") from None
1199
+ rawdim = idx
1200
+
1201
+ # Stack tensors at the resolved dimension
1202
+ result = torch.stack(inputs, rawdim)
1203
+
1204
+ # Insert new dimension entry at the correct position
1205
+ result_levels.insert(rawdim, DimEntry(new_dim))
1206
+
1207
+ # Return as a first-class tensor
1208
+ tensor_result = Tensor.from_positional(
1209
+ result, result_levels, infos[0].has_device if infos else True
1210
+ )
1211
+ return tensor_result # type: ignore[return-value]
1212
+
1213
+
1214
+ def split(tensor: Any, split_size_or_sections: Any, dim: Any = None) -> tuple:
1215
+ """
1216
+ Split tensor along a dimension.
1217
+
1218
+ Can handle both regular integer sizes and Dim objects for split sizes.
1219
+ When Dim objects are used, they get bound to the resulting tensor dimensions.
1220
+ """
1221
+ from ._wrap import _wrap_dim
1222
+
1223
+ # Check if dim is a Dim object
1224
+ dim_is_object = isinstance(dim, Dim)
1225
+
1226
+ # Parse split_size_or_sections
1227
+ if isinstance(split_size_or_sections, int):
1228
+ # Single integer - use regular split
1229
+ if dim_is_object:
1230
+ raise TypeError(
1231
+ "when dim is specified as a Dim object, split sizes must also be dimensions."
1232
+ )
1233
+ return _Tensor._torch_function_fallback(
1234
+ torch.Tensor.split,
1235
+ (type(tensor),),
1236
+ (tensor, split_size_or_sections),
1237
+ {"dim": dim},
1238
+ )
1239
+
1240
+ # Check if it's a sequence
1241
+ sizes = []
1242
+ all_dims = True
1243
+ all_ints = True
1244
+
1245
+ for item in split_size_or_sections:
1246
+ sizes.append(item)
1247
+ if isinstance(item, Dim):
1248
+ all_ints = False
1249
+ else:
1250
+ all_dims = False
1251
+
1252
+ if all_ints:
1253
+ # All integers - use regular split
1254
+ if dim_is_object:
1255
+ raise TypeError(
1256
+ "when dim is specified as a Dim object, split sizes must also be dimensions."
1257
+ )
1258
+ return _Tensor._torch_function_fallback(
1259
+ torch.Tensor.split,
1260
+ (type(tensor),),
1261
+ (tensor, split_size_or_sections),
1262
+ {"dim": dim},
1263
+ )
1264
+
1265
+ if not all_dims:
1266
+ raise TypeError("split list must be ints or dims but got a mix")
1267
+
1268
+ # All are Dim objects - handle first-class dimension split
1269
+ self_info = TensorInfo.create(tensor, ensure_batched=False, ensure_present=False)
1270
+ ndim = self_info.ndim()
1271
+
1272
+ if not dim_is_object and ndim == 0:
1273
+ raise TypeError("split expects at least a 1-dimension tensor")
1274
+
1275
+ # Wrap the dimension
1276
+ dim_l = _wrap_dim(dim, ndim, False) if dim is not None else DimEntry(-ndim)
1277
+
1278
+ # Find the index of the dimension in levels
1279
+ idx = None
1280
+ for i, level in enumerate(self_info.levels):
1281
+ if level == dim_l:
1282
+ idx = i
1283
+ break
1284
+
1285
+ if idx is None:
1286
+ if dim is None:
1287
+ dim = 0
1288
+ raise TypeError(f"tensor does not contain dimension {dim}")
1289
+
1290
+ # Calculate split indices
1291
+ indices = []
1292
+ total_size = 0
1293
+ unbound = []
1294
+
1295
+ for i, size_dim in enumerate(sizes):
1296
+ if size_dim.is_bound:
1297
+ indices.append(size_dim.size)
1298
+ total_size += indices[-1]
1299
+ else:
1300
+ indices.append(0)
1301
+ unbound.append(i)
1302
+
1303
+ if self_info.tensor is None:
1304
+ raise AssertionError("Cannot get tensor size on None tensor")
1305
+ tensor_size = self_info.tensor.size(idx)
1306
+
1307
+ # Handle unbound dimensions
1308
+ if unbound:
1309
+ if total_size > tensor_size:
1310
+ raise TypeError(
1311
+ f"sizes of target dimensions add up to more ({total_size}) than source dim ({tensor_size})"
1312
+ )
1313
+ remaining_size = tensor_size - total_size
1314
+ chunk_size = (remaining_size + len(unbound) - 1) // len(unbound)
1315
+ for u in unbound:
1316
+ sz = min(chunk_size, remaining_size)
1317
+ sizes[u].size = sz
1318
+ indices[u] = sz
1319
+ remaining_size -= sz
1320
+ elif tensor_size != total_size:
1321
+ raise TypeError(
1322
+ f"sum of sizes of target dimensions ({total_size}) do not match the source dim ({tensor_size})"
1323
+ )
1324
+
1325
+ # Perform the split
1326
+ result_tensors = self_info.tensor.split_with_sizes(indices, idx)
1327
+
1328
+ # Create result with new levels
1329
+ result = []
1330
+ new_levels = list(self_info.levels)
1331
+
1332
+ for i, (result_tensor, size_dim) in enumerate(zip(result_tensors, sizes)):
1333
+ new_levels[idx] = DimEntry(size_dim)
1334
+ result.append(
1335
+ Tensor.from_positional(
1336
+ result_tensor, list(new_levels), self_info.has_device
1337
+ )
1338
+ )
1339
+
1340
+ return tuple(result)
1341
+
1342
+
1343
+ def cat(tensors: Any, dim: Any, new_dim: Any) -> _Tensor:
1344
+ n = dims(1) # Get single Dim instead of tuple
1345
+ return stack(tensors, n, dim).index([n, dim], new_dim) # type: ignore[list-item]
1346
+
1347
+
1348
+ class DotPart:
1349
+ """
1350
+ Helper class for organizing dimensions in dot products.
1351
+ """
1352
+
1353
+ def __init__(self) -> None:
1354
+ self.dims: list[DimEntry] = []
1355
+ self.total_size = 1
1356
+
1357
+ def append(self, dim_entry: Any) -> None:
1358
+ """Add a dimension entry to this part."""
1359
+ self.dims.append(dim_entry)
1360
+ if not dim_entry.is_positional():
1361
+ self.total_size *= dim_entry.dim().size
1362
+
1363
+
1364
+ def dot_prepare(parts: list[DotPart], tensor_info: TensorInfo) -> torch.Tensor:
1365
+ """
1366
+ Prepare tensor for dot product by matching levels and reshaping.
1367
+ """
1368
+ new_levels = []
1369
+ needs_reshape = False
1370
+
1371
+ for part in parts:
1372
+ if len(part.dims) != 1:
1373
+ needs_reshape = True
1374
+ new_levels.extend(part.dims)
1375
+
1376
+ if tensor_info.tensor is None:
1377
+ raise RuntimeError("Cannot perform dot product on None tensor")
1378
+ result = _match_levels(tensor_info.tensor, tensor_info.levels, new_levels)
1379
+
1380
+ if not needs_reshape:
1381
+ return result
1382
+
1383
+ # Reshape for matrix operations
1384
+ view = [part.total_size for part in parts]
1385
+ return result.reshape(view)
1386
+
1387
+
1388
+ def dot_finish(parts: list[DotPart], result_tensor: torch.Tensor) -> Tensor:
1389
+ """
1390
+ Finish dot product by reshaping result and creating Tensor.
1391
+ """
1392
+ result_levels = []
1393
+ needs_reshape = False
1394
+
1395
+ for part in parts:
1396
+ if len(part.dims) != 1:
1397
+ needs_reshape = True
1398
+ result_levels.extend(part.dims)
1399
+
1400
+ if needs_reshape:
1401
+ new_size = []
1402
+ for level in result_levels:
1403
+ new_size.append(level.dim().size)
1404
+ result_tensor = result_tensor.reshape(new_size)
1405
+
1406
+ tensor_result = Tensor.from_positional(result_tensor, result_levels, True)
1407
+ return tensor_result # type: ignore[return-value]
1408
+
1409
+
1410
+ def dot(lhs: Any, rhs: Any, sum_dims: Any) -> Union[_Tensor, torch.Tensor]:
1411
+ """
1412
+ Perform dot product between two tensors along specified dimensions.
1413
+
1414
+ Args:
1415
+ lhs: Left-hand side tensor
1416
+ rhs: Right-hand side tensor
1417
+ sum_dims: Dimensions to sum over (contract)
1418
+
1419
+ Returns:
1420
+ Result of dot product
1421
+ """
1422
+ # Get tensor info
1423
+ lhs_info = TensorInfo.create(lhs, ensure_batched=False, ensure_present=False)
1424
+ rhs_info = TensorInfo.create(rhs, ensure_batched=False, ensure_present=False)
1425
+
1426
+ if not (lhs_info and rhs_info):
1427
+ # Fall back to regular operations
1428
+ return torch.matmul(lhs, rhs)
1429
+
1430
+ if lhs_info.tensor is None or rhs_info.tensor is None:
1431
+ raise AssertionError("Cannot perform dot product on None tensors")
1432
+
1433
+ lhs_strides = lhs_info.tensor.stride()
1434
+ rhs_strides = rhs_info.tensor.stride()
1435
+
1436
+ # Create dot parts for different dimension categories
1437
+ lro_dims = DotPart() # Left-right-output (batch dims)
1438
+ lo_dims = DotPart() # Left-output only
1439
+ ro_dims = DotPart() # Right-output only
1440
+ lr_dims = DotPart() # Left-right (contracted dims)
1441
+
1442
+ def insert_dim(d: Any, lhs_idx: Any, rhs_idx: Any) -> None:
1443
+ """Insert dimension into appropriate part based on stride pattern."""
1444
+ reduced = d in sum_dims
1445
+ lhs_stride = lhs_strides[lhs_idx] if lhs_idx is not None else 0
1446
+ rhs_stride = rhs_strides[rhs_idx] if rhs_idx is not None else 0
1447
+
1448
+ if reduced:
1449
+ lr_dims.append(d)
1450
+ else:
1451
+ if (lhs_stride == 0) == (rhs_stride == 0):
1452
+ lro_dims.append(d) # Both have or both lack this dim
1453
+ elif lhs_stride != 0:
1454
+ lo_dims.append(d) # Only lhs has this dim
1455
+ else:
1456
+ ro_dims.append(d) # Only rhs has this dim
1457
+
1458
+ # Track which rhs dimensions we've seen
1459
+ rhs_seen = [False] * len(rhs_info.levels)
1460
+
1461
+ # Process lhs dimensions
1462
+ for i, lhs_level in enumerate(lhs_info.levels):
1463
+ rhs_idx = None
1464
+ for j, rhs_level in enumerate(rhs_info.levels):
1465
+ if lhs_level == rhs_level:
1466
+ rhs_idx = j
1467
+ rhs_seen[j] = True
1468
+ break
1469
+
1470
+ insert_dim(lhs_level, i, rhs_idx)
1471
+
1472
+ # Process remaining rhs dimensions
1473
+ for i, rhs_level in enumerate(rhs_info.levels):
1474
+ if not rhs_seen[i]:
1475
+ insert_dim(rhs_level, None, i)
1476
+
1477
+ # Validate sum dimensions exist
1478
+ if len(lr_dims.dims) != len(sum_dims):
1479
+ for d in sum_dims:
1480
+ if d not in lhs_info.levels and d not in rhs_info.levels:
1481
+ raise ValueError(f"summing over non-existent dimension {d}")
1482
+
1483
+ # Prepare tensors and perform matrix multiplication
1484
+ if len(lro_dims.dims) != 0:
1485
+ # Batched matrix multiply
1486
+ lhs_tensor = dot_prepare([lro_dims, lo_dims, lr_dims], lhs_info)
1487
+ rhs_tensor = dot_prepare([lro_dims, lr_dims, ro_dims], rhs_info)
1488
+ result = torch.bmm(lhs_tensor, rhs_tensor)
1489
+ return dot_finish([lro_dims, lo_dims, ro_dims], result)
1490
+ else:
1491
+ # Regular matrix multiply
1492
+ lhs_tensor = dot_prepare([lo_dims, lr_dims], lhs_info)
1493
+ rhs_tensor = dot_prepare([lr_dims, ro_dims], rhs_info)
1494
+ result = torch.mm(lhs_tensor, rhs_tensor)
1495
+ return dot_finish([lo_dims, ro_dims], result)
1496
+
1497
+
1498
+ from functorch.dim._wrap import _wrap
1499
+ from functorch.dim.wrap_type import wrap_type
1500
+
1501
+
1502
+ wrap_type(_Tensor, torch.Tensor, _Tensor.__torch_function__)
1503
+ del _Tensor.ndim
1504
+
1505
+
1506
+ def index(self: Any, positions: Any, dims: Any) -> _Tensor:
1507
+ """
1508
+ Index a regular tensor by binding specified positions to dims.
1509
+
1510
+ This converts a regular tensor to a first-class tensor by binding
1511
+ the specified positional dimensions to Dim objects.
1512
+
1513
+ Args:
1514
+ positions: Tuple of dimension positions to bind
1515
+ dims: Dim objects or tuple of Dim objects to bind to
1516
+
1517
+ Returns:
1518
+ First-class tensor with specified dimensions bound
1519
+ """
1520
+ # If this is already a first-class tensor (_Tensor), call its index method directly
1521
+ if isinstance(self, _Tensor):
1522
+ return _Tensor.index(self, positions, dims)
1523
+
1524
+ # Convert regular tensor to first-class tensor
1525
+ info = TensorInfo.create(self, ensure_batched=False, ensure_present=False)
1526
+
1527
+ # Create the first-class tensor
1528
+ if info.tensor is None:
1529
+ raise AssertionError("Cannot index None tensor")
1530
+ result = Tensor.from_positional(info.tensor, info.levels, info.has_device)
1531
+
1532
+ # Now call the index method on the first-class tensor
1533
+ # Cast result to _Tensor for the method call
1534
+ return _Tensor.index(result, positions, dims) # type: ignore[arg-type]
1535
+
1536
+
1537
+ def _def(name: str, *args: Any, **kwargs: Any) -> None:
1538
+ orig = getattr(torch.Tensor, name)
1539
+ setattr(_Tensor, name, _wrap(orig, *args, **kwargs))
1540
+
1541
+
1542
+ _def("mean")
1543
+ _def("sum")
1544
+ _def("all")
1545
+ _def("amax")
1546
+ _def("amin")
1547
+ _def("aminmax")
1548
+ _def("any")
1549
+ _def("count_nonzero")
1550
+ _def("logsumexp")
1551
+ _def("nanmean")
1552
+ _def("nansum")
1553
+ _def("prod")
1554
+ _def("std", keepdim_offset=2)
1555
+ _def("var", keepdim_offset=2)
1556
+ _def("max", single_dim=True)
1557
+ _def("min", single_dim=True)
1558
+ _def("argmax", single_dim=True)
1559
+ _def("argmin", single_dim=True)
1560
+ _def("kthvalue", single_dim=True)
1561
+ _def("median", single_dim=True)
1562
+ _def("nanmedian", single_dim=True)
1563
+ _def("mode", single_dim=True)
1564
+ _def("sort", reduce=False)
1565
+ _def("argsort", reduce=False)
1566
+ _def("unbind", single_dim=True)
1567
+ _def("chunk", dim_offset=1, reduce=False)
1568
+ _def("cummax", single_dim=True, reduce=False)
1569
+ _def("cummin", single_dim=True, reduce=False)
1570
+ _def("cumprod", single_dim=True, reduce=False)
1571
+ _def("cumprod_", single_dim=True, reduce=False)
1572
+ _def("cumsum", single_dim=True, reduce=False)
1573
+ _def("cumsum_", single_dim=True, reduce=False)
1574
+ _def("logcumsumexp", single_dim=True, reduce=False)
1575
+ _def("renorm", dim_offset=1, single_dim=True, reduce=False)
1576
+ _def("softmax", single_dim=True, reduce=False)
1577
+ softmax = _wrap(torch.nn.functional.softmax, single_dim=True, reduce=False)
1578
+
1579
+ # stuff to handle in the future, because they require special
1580
+ # binding logic for dims
1581
+ # cross
1582
+ # diag_embed
1583
+ # diagonal
1584
+ # diagonal_scatter
1585
+ # diff
1586
+ # nanquantile
1587
+ # quantile
1588
+ # roll
1589
+ # rot90
1590
+ # topk (new dimes on output)
1591
+ # should these all be subsumed by inplace indexing?
1592
+ # index_add_
1593
+ # index_add
1594
+ # index_copy
1595
+ # index_copy_
1596
+ # index_fill
1597
+ # index_fill_
1598
+ # index_select
1599
+ # scatter
1600
+ # scatter_
1601
+ # scatter_add
1602
+ # scatter_add_
1603
+ # scatter_reduce
.venv/lib/python3.10/site-packages/functorch/dim/_dim_entry.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Union
4
+
5
+
6
+ if TYPE_CHECKING:
7
+ from collections.abc import Sequence
8
+
9
+ from . import Dim
10
+
11
+ import torch # noqa: TC002
12
+
13
+
14
+ # NB: The old code represented dimension was from as negative number, so we
15
+ # follow this convention even though it shouldn't be necessary now
16
+ class DimEntry:
17
+ # The dimension this is from the rhs, or a FCD
18
+ data: Union[Dim, int]
19
+
20
+ def __init__(self, data: Union[Dim, int, None] = None) -> None:
21
+ from . import Dim
22
+
23
+ if type(data) is int:
24
+ if data >= 0:
25
+ raise AssertionError(f"Expected negative int, got {data}")
26
+ elif data is None:
27
+ data = 0
28
+ else:
29
+ if not isinstance(data, Dim):
30
+ raise AssertionError(f"Expected Dim, got {type(data)}")
31
+ self.data = data
32
+
33
+ def __eq__(self, other: object) -> bool:
34
+ if not isinstance(other, DimEntry):
35
+ return False
36
+ # Use 'is' for Dim objects to avoid triggering __torch_function__
37
+ # Use '==' only for positional (int) comparisons
38
+ if self.is_positional() and other.is_positional():
39
+ # Both are positional (ints)
40
+ return self.data == other.data
41
+ elif not self.is_positional() and not other.is_positional():
42
+ # Both are Dim objects - use 'is' to avoid __eq__
43
+ return self.data is other.data
44
+ else:
45
+ # One is positional, one is Dim - they can't be equal
46
+ return False
47
+
48
+ def is_positional(self) -> bool:
49
+ return type(self.data) is int and self.data < 0
50
+
51
+ def is_none(self) -> bool:
52
+ # Use isinstance to check for Dim objects, avoid triggering __torch_function__
53
+ from . import Dim
54
+
55
+ if isinstance(self.data, Dim):
56
+ # This is a Dim object, it can't be "none" (which is represented by 0)
57
+ return False
58
+ else:
59
+ # This is an int or other type
60
+ return self.data == 0
61
+
62
+ def position(self) -> int:
63
+ if not isinstance(self.data, int):
64
+ raise AssertionError(f"Expected int, got {type(self.data)}")
65
+ return self.data
66
+
67
+ def dim(self) -> Dim:
68
+ if isinstance(self.data, int):
69
+ raise AssertionError("Expected Dim, got int")
70
+ return self.data
71
+
72
+ def __repr__(self) -> str:
73
+ return repr(self.data)
74
+
75
+
76
+ def ndim_of_levels(levels: Sequence[DimEntry]) -> int:
77
+ r = 0
78
+ for l in levels:
79
+ if l.is_positional():
80
+ r += 1
81
+ return r
82
+
83
+
84
+ def _match_levels(
85
+ tensor: torch.Tensor,
86
+ from_levels: list[DimEntry],
87
+ to_levels: list[DimEntry],
88
+ drop_levels: bool = False,
89
+ ) -> torch.Tensor:
90
+ """
91
+ Reshape a tensor to match target levels using as_strided.
92
+
93
+ Args:
94
+ tensor: Input tensor to reshape
95
+ from_levels: Current levels of the tensor
96
+ to_levels: Target levels to match
97
+ drop_levels: If True, missing dimensions are assumed to have stride 0
98
+
99
+ Returns:
100
+ Reshaped tensor
101
+ """
102
+ if from_levels == to_levels:
103
+ return tensor
104
+
105
+ sizes = tensor.size()
106
+ strides = tensor.stride()
107
+
108
+ if not drop_levels:
109
+ if len(from_levels) > len(to_levels):
110
+ raise AssertionError("Cannot expand dimensions without drop_levels")
111
+
112
+ new_sizes = []
113
+ new_strides = []
114
+
115
+ for level in to_levels:
116
+ # Find index of this level in from_levels
117
+ try:
118
+ idx = from_levels.index(level)
119
+ except ValueError:
120
+ # Level not found in from_levels
121
+ if level.is_positional():
122
+ new_sizes.append(1)
123
+ else:
124
+ new_sizes.append(level.dim().size)
125
+ new_strides.append(0)
126
+ else:
127
+ new_sizes.append(sizes[idx])
128
+ new_strides.append(strides[idx])
129
+
130
+ return tensor.as_strided(new_sizes, new_strides, tensor.storage_offset())
.venv/lib/python3.10/site-packages/functorch/dim/_enable_all_layers.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, TYPE_CHECKING
4
+
5
+ import torch
6
+
7
+ from ._dim_entry import DimEntry
8
+
9
+
10
+ if TYPE_CHECKING:
11
+ from . import Dim, Tensor
12
+
13
+
14
+ class EnableAllLayers:
15
+ """
16
+ RAII-style context manager for enabling functorch vmap layers.
17
+ It manages the creation and cleanup of functorch dynamic layers.
18
+
19
+ This is probably one of the more algorithmically important parts of first
20
+ class dims. Intuitively, FCD can be thought of as another way of using
21
+ vmap, where you don't actually have to vmap at the top level, instead the
22
+ vmaps are implicitly determined by inspecting the bound dimensions on the
23
+ FCD tensors involved in a compute (this is similar to our concept of
24
+ non-lexical modes that we spent a long time talking about years ago). But
25
+ under the hood you still need to actually enable the vmap mode. So once
26
+ FCD has determined all of the dims we are batching over, it needs to
27
+ enable all those layers so functorch can actually apply the batching
28
+ rules. Therefore enable all layers!
29
+ """
30
+
31
+ levels_start: int
32
+ levels_to_dim: list[Dim]
33
+
34
+ def __init__(self, levels: list[DimEntry]):
35
+ """
36
+ Initialize and push dynamic layers for all first-class dimensions.
37
+
38
+ Args:
39
+ levels: List of dimension entries to create layers for
40
+ """
41
+
42
+ from . import Dim
43
+
44
+ self.levels_start = 0
45
+ self.levels_to_dim = []
46
+
47
+ for l in levels:
48
+ if not l.is_positional():
49
+ d = l.dim()
50
+ if not isinstance(d, Dim):
51
+ raise AssertionError(f"Expected Dim, got {type(d)}")
52
+ self.levels_to_dim.append(d)
53
+
54
+ # Sort by level for stable ordering
55
+ self.levels_to_dim.sort(key=lambda d: d._level)
56
+
57
+ def __enter__(self) -> EnableAllLayers: # noqa: PYI034
58
+ # Create functorch dynamic layers
59
+ for i, dim in enumerate(self.levels_to_dim):
60
+ batch_size = dim.size
61
+ level = torch._C._functorch._vmap_increment_nesting(batch_size, "different")
62
+ if i == 0:
63
+ self.levels_start = level
64
+ return self
65
+
66
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
67
+ """Clean up dynamic layers in reverse order."""
68
+ to_remove = self.levels_start + len(self.levels_to_dim) - 1
69
+ for i in range(len(self.levels_to_dim)):
70
+ popped = torch._C._functorch._vmap_decrement_nesting()
71
+ if popped != to_remove - i:
72
+ raise AssertionError(f"Expected layer {to_remove - i}, got {popped}")
73
+
74
+ def from_batched(self, batchedtensor: torch.Tensor, has_device: bool) -> Tensor:
75
+ """
76
+ Create a Tensor from a batched tensor by unwrapping functorch layers.
77
+
78
+ Args:
79
+ batchedtensor: Batched tensor from functorch operation
80
+ has_device: Whether tensor has device info
81
+
82
+ Returns:
83
+ Tensor with appropriate levels
84
+ """
85
+ # Create positional levels for base dimensions
86
+ levels: list[DimEntry] = []
87
+ for i in range(-batchedtensor.dim(), 0):
88
+ levels.append(DimEntry(i))
89
+
90
+ tensor = batchedtensor
91
+
92
+ while torch._C._functorch.is_batchedtensor(tensor):
93
+ level = torch._C._functorch.maybe_get_level(tensor)
94
+ if level is None:
95
+ raise AssertionError("Expected level to be non-None")
96
+ if not (
97
+ level >= self.levels_start
98
+ and level < self.levels_start + len(self.levels_to_dim)
99
+ ):
100
+ raise AssertionError(f"Level {level} out of range")
101
+ dim = DimEntry(self.levels_to_dim[level - self.levels_start])
102
+ bdim = torch._C._functorch.maybe_get_bdim(tensor)
103
+ if bdim is None:
104
+ raise AssertionError("Expected bdim to be non-None")
105
+ levels.insert(bdim, dim)
106
+ tensor = torch._C._functorch.get_unwrapped(tensor)
107
+
108
+ from . import Tensor
109
+
110
+ result = Tensor()
111
+ result._tensor = tensor
112
+ result._batchtensor = batchedtensor
113
+ result._has_device = has_device
114
+ result._levels = levels
115
+ return result
116
+
117
+ def inplace_update_layers(
118
+ self, batchtensor: torch.Tensor, levels: list[DimEntry]
119
+ ) -> None:
120
+ """
121
+ Update the levels of a batched tensor in place.
122
+
123
+ This requires the _maybe_unsafe_set_level binding that we'll add to functorch.
124
+
125
+ Args:
126
+ batchtensor: Batched tensor to update
127
+ levels: New levels to set
128
+ """
129
+ # Check if tensor is batched
130
+ if not torch._C._functorch.is_batchedtensor(batchtensor):
131
+ return
132
+
133
+ impl = batchtensor
134
+
135
+ for i in reversed(range(len(self.levels_to_dim))):
136
+ if impl is None:
137
+ break
138
+
139
+ if any(l == DimEntry(self.levels_to_dim[i]) for l in levels):
140
+ # This is very interesting! The level on batch tensor is
141
+ # meaningless! We set it RIGHT before we go into vmap
142
+ torch._C._functorch._maybe_unsafe_set_level(impl, self.levels_start + i)
143
+ impl = torch._C._functorch.get_unwrapped(impl)
.venv/lib/python3.10/site-packages/functorch/dim/_getsetitem.py ADDED
@@ -0,0 +1,564 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any, Optional, TYPE_CHECKING, Union
5
+
6
+ import torch
7
+
8
+ from ._dim_entry import _match_levels, DimEntry
9
+ from ._tensor_info import TensorInfo
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ from . import Dim
14
+
15
+
16
+ def _safe_index(lst: list, item: Any) -> Optional[int]:
17
+ """
18
+ Helper function to find index of item in list.
19
+
20
+ For DimEntry objects, uses __eq__ comparison which properly handles
21
+ both positional and Dim entries.
22
+
23
+ Returns the index if found, None if not found.
24
+ """
25
+ for i, list_item in enumerate(lst):
26
+ # Use == for DimEntry objects as they have proper __eq__ implementation
27
+ if isinstance(item, DimEntry) and isinstance(list_item, DimEntry):
28
+ if list_item == item:
29
+ return i
30
+ elif list_item is item:
31
+ return i
32
+ return None
33
+
34
+
35
+ @dataclass
36
+ class IndexingInfo:
37
+ can_call_original: bool = False
38
+ advanced_indexing: bool = False
39
+ self_tensor: Optional[torch.Tensor] = None
40
+ flat_inputs: list[Any] = field(default_factory=list)
41
+ result_levels: list[DimEntry] = field(default_factory=list)
42
+ has_device: bool = False
43
+
44
+
45
+ def has_dims(obj: Any) -> bool:
46
+ """
47
+ Check if an object has first-class dimensions.
48
+
49
+ This function checks if the object is either a Dim or a functorch Tensor
50
+ that has first-class dimensions, using the proper check_exact methods.
51
+ """
52
+ from . import Dim, Tensor
53
+
54
+ return Dim.check_exact(obj) or Tensor.check_exact(obj)
55
+
56
+
57
+ def _bind_dims_to_size(sz: int, sd: int, dims: list, nsz: list, nsd: list) -> None:
58
+ """
59
+ Bind dimensions to size and calculate proper strides for dim packs.
60
+ """
61
+ from . import DimensionBindError
62
+
63
+ rhs_prod = 1
64
+ for i, dim in enumerate(dims):
65
+ if not dim.is_bound:
66
+ # Check for multiple unbound dimensions
67
+ for j in range(i + 1, len(dims)):
68
+ if not dims[j].is_bound:
69
+ raise DimensionBindError(
70
+ f"cannot infer the sizes of two dimensions at once {dim!r} and {dims[j]!r}"
71
+ )
72
+ rhs_prod *= dims[j].size
73
+
74
+ # Calculate the size for this unbound dimension
75
+ if sz % rhs_prod != 0:
76
+ tup = tuple(dim.size if dim.is_bound else "?" for dim in dims)
77
+ raise DimensionBindError(
78
+ f"inferred dimension does not evenly fit into larger dimension: {sz} vs {tup}"
79
+ )
80
+
81
+ inferred_size = sz // rhs_prod
82
+ dim.size = inferred_size
83
+ rhs_prod = sz
84
+ break
85
+ else:
86
+ rhs_prod *= dim.size
87
+
88
+ # Final validation that dimensions match
89
+ if rhs_prod != sz:
90
+ tup = tuple(dims)
91
+ raise DimensionBindError(
92
+ f"Dimension sizes to do not match ({sz} != {rhs_prod}) when matching dimension pack {tup}"
93
+ )
94
+
95
+ # Calculate new sizes and strides for each dimension in the pack
96
+ # First calculate all strides by iterating in reverse
97
+ new_strides = [0] * len(dims)
98
+ current_stride = sd
99
+ for i in reversed(range(len(dims))):
100
+ new_strides[i] = current_stride
101
+ current_stride *= dims[i].size
102
+
103
+ # Then append sizes and strides in forward order
104
+ for i in range(len(dims)):
105
+ nsz.append(dims[i].size)
106
+ nsd.append(new_strides[i])
107
+
108
+
109
+ def slice_to_tuple(flat_inputs: list) -> tuple:
110
+ return tuple(flat_inputs)
111
+
112
+
113
+ def extractIndices(index: Any, indices: list) -> bool:
114
+ if isinstance(index, tuple): # mpy::tuple_view::check
115
+ indices.extend(index)
116
+ return True
117
+ elif isinstance(index, torch.Tensor): # THPVariable_Check
118
+ indices.append(index)
119
+ return False
120
+ elif not hasattr(index, "__iter__") or isinstance(
121
+ index, (str, bytes)
122
+ ): # !mpy::is_sequence
123
+ indices.append(index)
124
+ return False
125
+
126
+ # Handle sequence case (list)
127
+ if isinstance(index, list):
128
+ if len(index) >= 32:
129
+ indices.extend(index)
130
+ return True
131
+
132
+ # Check each item in the sequence
133
+ for item in index:
134
+ if (
135
+ isinstance(item, (torch.Tensor, slice))
136
+ or hasattr(item, "__iter__")
137
+ or item is ...
138
+ or item is None
139
+ or has_dims(item)
140
+ ):
141
+ indices.extend(index)
142
+ return True
143
+
144
+ # If we got here, treat as single index
145
+ indices.append(index)
146
+ return False
147
+
148
+ # Default case
149
+ indices.append(index)
150
+ return False
151
+
152
+
153
+ def getitem(cls: Any, func: Any, types: Any, args: Any, kwargs: Any) -> Any:
154
+ self = args[0]
155
+ index = args[1]
156
+
157
+ iinfo = getsetitem(self, index, has_dims(self))
158
+ if iinfo.can_call_original:
159
+ # Call original tensor __getitem__ directly, bypassing __torch_function__
160
+ return torch.Tensor.__getitem__(self, index)
161
+
162
+ return invoke_getitem(iinfo)
163
+
164
+
165
+ def setitem(self: Any, index: Any, rhs: Any) -> None:
166
+ """Set values in tensor using first-class dimensions."""
167
+ from . import DimensionBindError, TensorInfo
168
+
169
+ iinfo = getsetitem(self, index, has_dims(self) or has_dims(rhs))
170
+
171
+ if iinfo.can_call_original:
172
+ # Call original tensor __setitem__ directly, bypassing __torch_function__
173
+ torch._C.TensorBase.__setitem__(self, index, rhs)
174
+ return
175
+
176
+ # Handle RHS tensor with dimensions
177
+ rhs_info = TensorInfo.create(rhs, False, False)
178
+
179
+ if rhs_info:
180
+ # Check that rhs dimensions are compatible with result dimensions
181
+ for l in rhs_info.levels:
182
+ if not l.is_positional():
183
+ # Find this dimension in result levels
184
+ found = False
185
+ for result_level in iinfo.result_levels:
186
+ if (
187
+ not result_level.is_positional()
188
+ and result_level.dim() is l.dim()
189
+ ):
190
+ found = True
191
+ break
192
+
193
+ if not found:
194
+ # Create tuple representation of result levels for error message
195
+ result_dims: list[Union[int, Dim]] = []
196
+ for rl in iinfo.result_levels:
197
+ if rl.is_positional():
198
+ result_dims.append(rl.position())
199
+ else:
200
+ result_dims.append(rl.dim())
201
+
202
+ raise DimensionBindError(
203
+ f"rhs of setitem contains dimension {l.dim()!r} which is not in the dimension on the left "
204
+ f"({tuple(result_dims)!r})"
205
+ )
206
+
207
+ # Match RHS tensor to result levels
208
+ if rhs_info.tensor is None:
209
+ raise AssertionError("Cannot match levels on None tensor")
210
+ matched_rhs = _match_levels(
211
+ rhs_info.tensor, rhs_info.levels, iinfo.result_levels
212
+ )
213
+ else:
214
+ matched_rhs = rhs
215
+
216
+ # For advanced indexing with dimensions, we need special handling
217
+ if iinfo.advanced_indexing:
218
+ # Use advanced indexing - the flat_inputs already contain matched tensors
219
+ tup = slice_to_tuple(iinfo.flat_inputs)
220
+ if iinfo.self_tensor is None:
221
+ raise RuntimeError("Cannot setitem on None tensor")
222
+ torch._C.TensorBase.__setitem__(iinfo.self_tensor, tup, matched_rhs)
223
+ else:
224
+ # Simple copy operation
225
+ if iinfo.self_tensor is None:
226
+ raise RuntimeError("Cannot copy to None tensor")
227
+ iinfo.self_tensor.copy_(matched_rhs)
228
+
229
+
230
+ def invoke_getitem(iinfo: IndexingInfo) -> Any:
231
+ if iinfo.advanced_indexing:
232
+ self_tensor = iinfo.self_tensor
233
+ tup = slice_to_tuple(iinfo.flat_inputs)
234
+ if self_tensor is None:
235
+ raise RuntimeError("Cannot getitem on None tensor")
236
+ rtensor = self_tensor[tup]
237
+ else:
238
+ rtensor = iinfo.self_tensor # type: ignore[assignment]
239
+ if rtensor is None:
240
+ raise RuntimeError("Cannot getitem on None tensor")
241
+ # rtensor is now guaranteed to be not None
242
+
243
+ # Create a Tensor with the proper dimensions using the class method
244
+ from . import Tensor
245
+
246
+ return Tensor.from_positional(rtensor, iinfo.result_levels, iinfo.has_device)
247
+
248
+
249
+ def getsetitem(self: Any, index: Any, tensors_have_dims: bool) -> IndexingInfo:
250
+ from . import DimList # Import DimList for type checking
251
+
252
+ can_call_original_getitem = not tensors_have_dims
253
+
254
+ input_list = []
255
+ if has_dims(index):
256
+ input_list.append(index)
257
+ else:
258
+ is_sequence = extractIndices(index, input_list)
259
+ # nothing about first class dims here, fallback to getitem
260
+ if can_call_original_getitem and not is_sequence:
261
+ return IndexingInfo(can_call_original=True)
262
+
263
+ # Calculate how many dimensions have been indexed in order to compute the
264
+ # size of ... or expand a potentially unbound dimension list.
265
+ dims_indexed = 0
266
+ expanding_object = -1
267
+ unbound_dim_list = None
268
+ dimlists = [] # Track DimList positions for later processing
269
+
270
+ def check_expanding(i: int) -> None:
271
+ nonlocal expanding_object
272
+ if expanding_object != -1:
273
+ from . import DimensionBindError
274
+
275
+ raise DimensionBindError(
276
+ f"at most one ... or unbound dimension list can exist in indexing list but found 2 at offsets "
277
+ f"{expanding_object} and {i}"
278
+ )
279
+ expanding_object = i
280
+
281
+ def is_dimpack(s: Any) -> bool:
282
+ from . import Dim
283
+
284
+ return (
285
+ isinstance(s, (tuple, list))
286
+ and len(s) > 0
287
+ and all(Dim.check_exact(item) for item in s)
288
+ )
289
+
290
+ has_dimpacks_or_none = False
291
+ for i, s in enumerate(input_list):
292
+ if has_dims(s):
293
+ can_call_original_getitem = False
294
+ dims_indexed += 1
295
+ elif s is ...:
296
+ check_expanding(i)
297
+ elif isinstance(s, DimList):
298
+ can_call_original_getitem = False
299
+ if not s.is_bound:
300
+ check_expanding(i)
301
+ unbound_dim_list = s
302
+ else:
303
+ dims_indexed += len(s._dims)
304
+ dimlists.append(i)
305
+ elif s is None:
306
+ has_dimpacks_or_none = True
307
+ elif is_dimpack(s):
308
+ can_call_original_getitem = False
309
+ has_dimpacks_or_none = True
310
+ dims_indexed += 1
311
+ else:
312
+ dims_indexed += 1
313
+
314
+ # Early return if we can use original getitem
315
+ if can_call_original_getitem:
316
+ return IndexingInfo(can_call_original=True)
317
+
318
+ self_info = TensorInfo.create(self, False, True)
319
+ total_dims = len(self_info.levels) # Total dimensions (positional + named)
320
+ if dims_indexed > total_dims:
321
+ raise ValueError(
322
+ f"at least {dims_indexed} indices were supplied but the tensor only has {total_dims} dimensions"
323
+ )
324
+
325
+ # Expand any unbound dimension list, or expand ... into individual : slices.
326
+ expanding_dims = total_dims - dims_indexed
327
+ if expanding_object != -1:
328
+ if unbound_dim_list is not None:
329
+ # Bind unbound dimension list to the expanding dimensions
330
+ unbound_dim_list.bind_len(expanding_dims)
331
+ else:
332
+ # Expand ... into slice(None) objects
333
+ no_slices = [slice(None)] * expanding_dims
334
+ input_list = (
335
+ input_list[:expanding_object]
336
+ + no_slices
337
+ + input_list[expanding_object + 1 :]
338
+ )
339
+
340
+ # Flatten out any dimensions stored in dimlist elements directly into the inputs
341
+ # Process in reverse order to maintain indices
342
+ for i in range(len(dimlists) - 1, -1, -1):
343
+ idx = dimlists[i]
344
+
345
+ # We added more elements to input because of ...
346
+ # so we need to also adjust the index to get back to where the
347
+ # dimlist existed
348
+ if (
349
+ unbound_dim_list is None
350
+ and expanding_object != -1
351
+ and idx > expanding_object
352
+ ):
353
+ idx += expanding_dims
354
+
355
+ dl = input_list[idx]
356
+
357
+ # PRIVATE here naughty
358
+ input_list = input_list[:idx] + dl._dims + input_list[idx + 1 :]
359
+
360
+ return getsetitem_flat(self_info, input_list, [], [], has_dimpacks_or_none)
361
+
362
+
363
+ def getsetitem_flat(
364
+ self_info: TensorInfo,
365
+ input_list: list,
366
+ keys: list[DimEntry],
367
+ values: list,
368
+ has_dimpacks_or_none: bool,
369
+ ) -> IndexingInfo:
370
+ from . import Dim
371
+
372
+ # Track dimension usage
373
+ seen_dims: list[Any] = []
374
+ seen_dims_nuses: list[int] = []
375
+
376
+ def add_dim(dim: Any) -> None:
377
+ # Use safe indexing to avoid triggering __torch_function__ on Dim objects
378
+ idx = _safe_index(seen_dims, dim)
379
+ if idx is not None:
380
+ seen_dims_nuses[idx] += 1
381
+ else:
382
+ seen_dims.append(dim)
383
+ seen_dims_nuses.append(1)
384
+
385
+ flat_inputs = []
386
+ tensor_inputs: list[Any] = []
387
+ device_holding_tensor = None
388
+
389
+ def append_flat_handle(handle: Any) -> None:
390
+ flat_inputs.append(handle)
391
+ tensor_inputs.append(None)
392
+
393
+ def append_tensor_input(ti: TensorInfo) -> None:
394
+ flat_inputs.append(None)
395
+ tensor_inputs.append(ti)
396
+ nonlocal device_holding_tensor
397
+ if ti.has_device and device_holding_tensor is None:
398
+ device_holding_tensor = ti.tensor
399
+
400
+ nsz = []
401
+ nsd = []
402
+ if self_info.tensor is None:
403
+ raise RuntimeError("Cannot get size/stride on None tensor")
404
+ sz = self_info.tensor.size()
405
+ sd = self_info.tensor.stride()
406
+
407
+ def append_size(i: int) -> None:
408
+ if has_dimpacks_or_none:
409
+ nsz.append(sz[i])
410
+ nsd.append(sd[i])
411
+
412
+ input_it = input_list[:]
413
+
414
+ def parse_nones() -> None:
415
+ nonlocal input_it
416
+ while input_it and input_it[0] is None:
417
+ append_flat_handle(slice(None))
418
+ nsz.append(1)
419
+ nsd.append(0)
420
+ input_it = input_it[1:]
421
+
422
+ def append_item(i: int, arg: Any) -> None:
423
+ if Dim.check_exact(arg):
424
+ d = arg
425
+ if d._size == -1:
426
+ d.size = sz[i]
427
+ add_dim(d)
428
+ append_size(i)
429
+ append_flat_handle(arg)
430
+ return
431
+
432
+ info = TensorInfo.create(arg, False, False)
433
+ if info:
434
+ append_size(i)
435
+ append_tensor_input(info)
436
+ for level in info.levels:
437
+ if not level.is_positional():
438
+ add_dim(level.dim())
439
+ return
440
+
441
+ if has_dimpacks_or_none:
442
+ if isinstance(arg, (tuple, list)) and all(Dim.check_exact(d) for d in arg):
443
+ # dim pack
444
+ dim_pack = list(arg)
445
+ for d in dim_pack:
446
+ add_dim(d)
447
+ append_flat_handle(d)
448
+ _bind_dims_to_size(sz[i], sd[i], dim_pack, nsz, nsd)
449
+ return
450
+
451
+ append_size(i)
452
+ append_flat_handle(arg)
453
+
454
+ # Match indexing expressions with tensor dimensions
455
+ for i, level in enumerate(self_info.levels):
456
+ # Use safe indexing to avoid triggering __torch_function__ on DimEntry comparisons
457
+ idx = _safe_index(keys, level)
458
+ if idx is not None:
459
+ append_item(i, values[idx])
460
+ else:
461
+ if level.is_positional():
462
+ parse_nones()
463
+ if not input_it:
464
+ append_flat_handle(slice(None))
465
+ append_size(i)
466
+ else:
467
+ arg = input_it[0]
468
+ input_it = input_it[1:]
469
+ append_item(i, arg)
470
+ else:
471
+ add_dim(level.dim())
472
+ append_flat_handle(level.dim())
473
+ append_size(i)
474
+
475
+ parse_nones()
476
+
477
+ # Restride tensor if needed
478
+ if has_dimpacks_or_none and nsz:
479
+ if self_info.tensor is None:
480
+ raise RuntimeError("Cannot restride None tensor")
481
+ self_tensor = self_info.tensor.as_strided(
482
+ nsz, nsd, self_info.tensor.storage_offset()
483
+ )
484
+ else:
485
+ self_tensor = self_info.tensor
486
+
487
+ # Determine result shape and indexing requirements
488
+ result_levels: list[Any] = []
489
+ index_levels = []
490
+ tensor_insert_point = -1
491
+ requires_getindex = False
492
+
493
+ def mark_tensor_index() -> None:
494
+ nonlocal tensor_insert_point
495
+ if tensor_insert_point == -1:
496
+ tensor_insert_point = len(result_levels)
497
+ elif tensor_insert_point != len(result_levels):
498
+ tensor_insert_point = 0
499
+
500
+ for i, inp in enumerate(flat_inputs):
501
+ if tensor_inputs[i] is not None:
502
+ requires_getindex = True
503
+ mark_tensor_index()
504
+ for level in tensor_inputs[i].levels:
505
+ if level not in index_levels:
506
+ index_levels.append(level)
507
+ elif Dim.check_exact(inp):
508
+ d = inp
509
+ # Use safe indexing to avoid triggering __torch_function__
510
+ dim_idx = _safe_index(seen_dims, d)
511
+ if dim_idx is None:
512
+ raise AssertionError(f"Dim {d} not found in seen_dims")
513
+ if seen_dims_nuses[dim_idx] == 1:
514
+ flat_inputs[i] = slice(None)
515
+ result_levels.append(DimEntry(d))
516
+ else:
517
+ requires_getindex = True
518
+ flat_inputs[i] = None
519
+ tensor_inputs[i] = TensorInfo(
520
+ d._get_range(), [DimEntry(d)], False, None
521
+ )
522
+ if DimEntry(d) not in index_levels:
523
+ index_levels.append(DimEntry(d))
524
+ mark_tensor_index()
525
+ else:
526
+ if inp != slice(None):
527
+ requires_getindex = True
528
+ if not isinstance(inp, int):
529
+ result_levels.append(DimEntry(-1))
530
+
531
+ # Insert indexing dimensions at first tensor use point
532
+ if tensor_insert_point != -1:
533
+ for level in reversed(index_levels):
534
+ result_levels.insert(tensor_insert_point, level)
535
+
536
+ # Match tensors to indexing shape
537
+ if requires_getindex:
538
+ for i in range(len(flat_inputs)):
539
+ if tensor_inputs[i] is not None:
540
+ t = tensor_inputs[i].tensor
541
+ if t is None:
542
+ raise AssertionError("TensorInfo should have valid tensor data")
543
+ if (
544
+ not tensor_inputs[i].has_device
545
+ and device_holding_tensor is not None
546
+ ):
547
+ t = t.to(device_holding_tensor.device)
548
+ flat_inputs[i] = _match_levels(t, tensor_inputs[i].levels, index_levels)
549
+
550
+ # Number positional dimensions correctly
551
+ seen_positionals = 0
552
+ for i in reversed(range(len(result_levels))):
553
+ if result_levels[i].is_positional():
554
+ seen_positionals += 1
555
+ result_levels[i] = DimEntry(-seen_positionals)
556
+
557
+ return IndexingInfo(
558
+ can_call_original=False,
559
+ advanced_indexing=requires_getindex,
560
+ self_tensor=self_tensor,
561
+ flat_inputs=flat_inputs,
562
+ result_levels=result_levels,
563
+ has_device=self_info.has_device,
564
+ )
.venv/lib/python3.10/site-packages/functorch/dim/_order.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, TYPE_CHECKING, Union
4
+
5
+
6
+ if TYPE_CHECKING:
7
+ from collections.abc import Sequence
8
+
9
+ import torch # noqa: TC002
10
+
11
+ from ._dim_entry import _match_levels, DimEntry, ndim_of_levels
12
+
13
+
14
+ def _wrap_dim(arg: Any, orig_ndim: int, allow_none: bool = True) -> DimEntry:
15
+ """
16
+ Convert various dimension representations to DimEntry.
17
+
18
+ Args:
19
+ arg: The argument to convert (Dim, int, or other)
20
+ orig_ndim: Original number of dimensions
21
+ allow_none: Whether to allow None values
22
+
23
+ Returns:
24
+ DimEntry representation of the dimension
25
+ """
26
+ from . import Dim
27
+
28
+ if arg is None and allow_none:
29
+ return DimEntry() # None entry
30
+ elif isinstance(arg, Dim):
31
+ return DimEntry(arg)
32
+ elif isinstance(arg, int):
33
+ if arg < 0:
34
+ pos = arg
35
+ else:
36
+ pos = arg - orig_ndim
37
+ return DimEntry(pos)
38
+ else:
39
+ return DimEntry()
40
+
41
+
42
+ def order(
43
+ tensor_or_dim: Union[torch.Tensor, Any], *dims: Union[Any, Sequence[Any]]
44
+ ) -> torch.Tensor:
45
+ """
46
+ Reorder the dimensions of a tensor or create a tensor from a dimension.
47
+
48
+ It allows reordering tensor dimensions using first-class dimensions and
49
+ positional indices.
50
+
51
+ Args:
52
+ tensor_or_dim: Input tensor with first-class dimensions, or a Dim object
53
+ *dims: Dimensions or sequences of dimensions specifying the new order
54
+
55
+ Returns:
56
+ Tensor with reordered dimensions
57
+
58
+ Examples:
59
+ >>> import torch
60
+ >>> from functorch.dim import dims
61
+ >>> batch, channel, height, width = dims(4)
62
+ >>> x = torch.randn(2, 3, 4, 5)[batch, channel, height, width]
63
+ >>> # Reorder to [height, width, batch, channel]
64
+ >>> y = order(x, height, width, batch, channel)
65
+ """
66
+ from . import Dim, DimList, Tensor
67
+
68
+ # Handle first argument - tensor or dimension
69
+ if isinstance(tensor_or_dim, Tensor):
70
+ # First-class tensor
71
+ orig_levels = tensor_or_dim._levels[:]
72
+ data = tensor_or_dim._tensor
73
+ has_device = tensor_or_dim._has_device
74
+ elif isinstance(tensor_or_dim, Dim):
75
+ # Single dimension - create range tensor
76
+ orig_levels = [DimEntry(tensor_or_dim)]
77
+ data = tensor_or_dim._get_range()
78
+ has_device = False
79
+ else:
80
+ raise ValueError("First argument must be a Tensor or Dim object")
81
+
82
+ flat_positional_dims = []
83
+ to_flatten = [] # List of (start_index, length) pairs for flattening
84
+ levels = orig_levels[:]
85
+
86
+ orig_ndim = ndim_of_levels(levels)
87
+
88
+ def append_dim(d: DimEntry) -> None:
89
+ """Add a dimension to the reordering, removing it from available levels."""
90
+ try:
91
+ idx = levels.index(d)
92
+ except ValueError:
93
+ idx = None
94
+ if idx is None:
95
+ if d.is_positional():
96
+ raise ValueError(
97
+ f"tensor has {orig_ndim} positional dimensions, but {d.position() + orig_ndim} specified, "
98
+ f"or it was specified twice"
99
+ )
100
+ else:
101
+ raise ValueError(
102
+ f"tensor does not contain dim {d.dim()} or it was specified twice"
103
+ )
104
+
105
+ levels[idx] = DimEntry()
106
+ flat_positional_dims.append(d)
107
+
108
+ n_new_positional = 0
109
+
110
+ # Process each dimension argument
111
+ for arg in dims:
112
+ entry = _wrap_dim(arg, orig_ndim, False)
113
+ if not entry.is_none():
114
+ append_dim(entry)
115
+ n_new_positional += 1
116
+ elif isinstance(arg, DimList):
117
+ # Handle DimList
118
+ for dim in arg._dims:
119
+ append_dim(DimEntry(dim))
120
+ n_new_positional += 1
121
+ else:
122
+ # Handle sequences of dimensions for flattening
123
+ n_new_positional += 1
124
+ if not hasattr(arg, "__iter__"):
125
+ raise ValueError("expected a Dim, List[Dim], or Sequence[Dim]")
126
+
127
+ # Convert to list to get length
128
+ seq = list(arg)
129
+ to_flatten.append((len(flat_positional_dims), len(seq)))
130
+
131
+ for item in seq:
132
+ entry = _wrap_dim(item, orig_ndim, False)
133
+ if entry.is_none():
134
+ raise ValueError("expected a Dim or int")
135
+ append_dim(entry)
136
+
137
+ # Build new level ordering
138
+ insert_point = -1
139
+ new_levels: list[DimEntry] = []
140
+
141
+ # Add remaining (non-reordered) levels, finding insertion point for new dimensions
142
+ for level in levels:
143
+ if level.is_none():
144
+ continue
145
+ if level.is_positional():
146
+ if insert_point == -1:
147
+ insert_point = len(new_levels)
148
+ new_levels.extend(flat_positional_dims)
149
+ new_levels.append(level)
150
+
151
+ # If no positional dimensions found, append new dims at the end
152
+ if insert_point == -1:
153
+ insert_point = len(new_levels)
154
+ new_levels.extend(flat_positional_dims)
155
+
156
+ # Match tensor to new level structure
157
+ if data is None:
158
+ raise AssertionError("Cannot reorder None tensor")
159
+ ndata = _match_levels(data, orig_levels, new_levels)
160
+
161
+ # Handle dimension flattening if requested
162
+ if to_flatten:
163
+ # Now build the reshape target
164
+ view_shape = []
165
+ sizes = ndata.size()
166
+
167
+ # Add dimensions before the reordered ones
168
+ for i in range(insert_point):
169
+ view_shape.append(sizes[i])
170
+
171
+ # Process flattening groups
172
+ i = 0
173
+ for start_idx, length in to_flatten:
174
+ # Add individual dims before this flattening group
175
+ while i < start_idx:
176
+ view_shape.append(sizes[insert_point + i])
177
+ i += 1
178
+
179
+ # Flatten the group
180
+ new_size = 1
181
+ for j in range(length):
182
+ new_size *= sizes[insert_point + i + j]
183
+ view_shape.append(new_size)
184
+ i += length
185
+
186
+ # Add remaining individual dims
187
+ while i < len(flat_positional_dims):
188
+ view_shape.append(sizes[insert_point + i])
189
+ i += 1
190
+
191
+ # Add dimensions after the reordered ones
192
+ for i in range(insert_point + len(flat_positional_dims), len(levels)):
193
+ view_shape.append(sizes[i])
194
+
195
+ # Update levels by removing flattened dimensions
196
+ n_to_remove = len(flat_positional_dims) - n_new_positional
197
+ if n_to_remove > 0:
198
+ # Remove flattened levels
199
+ new_levels = (
200
+ new_levels[:insert_point] + new_levels[insert_point + n_to_remove :]
201
+ )
202
+
203
+ ndata = ndata.reshape(view_shape)
204
+
205
+ # Renumber positional dimensions (negative indexing from the right)
206
+ seen = 0
207
+ for i in range(len(new_levels) - 1, -1, -1):
208
+ if new_levels[i].is_positional() or (
209
+ i >= insert_point and i < insert_point + n_new_positional
210
+ ):
211
+ seen -= 1
212
+ new_levels[i] = DimEntry(seen)
213
+
214
+ result = Tensor.from_positional(ndata, new_levels, has_device)
215
+ return result # type: ignore[return-value]
.venv/lib/python3.10/site-packages/functorch/dim/_py_inst_decoder.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dis
2
+ from typing import Any, Optional
3
+
4
+
5
+ class _PyInstDecoder:
6
+ """
7
+ Decodes Python bytecode instructions to extract variable names
8
+ """
9
+
10
+ def __init__(self, code_object: Any, lasti: int) -> None:
11
+ self.code_object = code_object
12
+ self.instructions = list(dis.get_instructions(code_object))
13
+ self.offset = self._find_instruction_index(lasti)
14
+
15
+ def _find_instruction_index(self, lasti: int) -> int:
16
+ """Find instruction index corresponding to lasti (byte offset)."""
17
+ # Find the instruction at or before lasti
18
+ # This should find the CALL instruction, not the next one
19
+ best_idx = 0
20
+ for i, instr in enumerate(self.instructions):
21
+ if instr.offset <= lasti:
22
+ best_idx = i
23
+ else:
24
+ break
25
+ return best_idx
26
+
27
+ def next(self) -> None:
28
+ """Advance to the next instruction."""
29
+ self.offset += 1
30
+
31
+ def opcode(self) -> Optional[str]:
32
+ """Get the opcode name of the current instruction."""
33
+ if self.offset < len(self.instructions):
34
+ return self.instructions[self.offset].opname
35
+ return None
36
+
37
+ def oparg(self) -> int:
38
+ """Get the argument of the current instruction."""
39
+ if self.offset < len(self.instructions):
40
+ return self.instructions[self.offset].arg or 0
41
+ return 0
42
+
43
+ def name(self) -> Optional[str]:
44
+ """
45
+ Extract variable name from current instruction.
46
+ """
47
+ opname = self.opcode()
48
+ if not opname:
49
+ return None
50
+
51
+ names = None
52
+ if opname in ("STORE_NAME", "STORE_GLOBAL"):
53
+ names = self.code_object.co_names
54
+ elif opname == "STORE_FAST":
55
+ names = self.code_object.co_varnames
56
+ elif opname == "STORE_DEREF":
57
+ names = self.code_object.co_cellvars
58
+ if not names:
59
+ names = self.code_object.co_freevars
60
+ else:
61
+ return None
62
+
63
+ arg = self.oparg()
64
+ if names and 0 <= arg < len(names):
65
+ return names[arg]
66
+
67
+ return None
.venv/lib/python3.10/site-packages/functorch/dim/_tensor_info.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Optional, TYPE_CHECKING
5
+
6
+ import torch
7
+
8
+
9
+ if TYPE_CHECKING:
10
+ from ._dim_entry import DimEntry
11
+
12
+
13
+ @dataclass
14
+ class TensorInfo:
15
+ tensor: Optional[torch.Tensor]
16
+ levels: list[DimEntry]
17
+ has_device: bool
18
+ batchedtensor: Optional[torch.Tensor]
19
+
20
+ def __post_init__(self) -> None:
21
+ from ._dim_entry import DimEntry
22
+
23
+ if not all(isinstance(l, DimEntry) for l in self.levels):
24
+ raise AssertionError("All levels must be DimEntry instances")
25
+
26
+ def ndim(self) -> int:
27
+ from ._dim_entry import ndim_of_levels
28
+
29
+ return ndim_of_levels(self.levels)
30
+
31
+ def __bool__(self) -> bool:
32
+ return self.tensor is not None
33
+
34
+ @staticmethod
35
+ def create(
36
+ h: Any, ensure_batched: bool = True, ensure_present: bool = True
37
+ ) -> TensorInfo:
38
+ from . import Dim, DimEntry, Tensor
39
+
40
+ if Tensor.check_exact(h):
41
+ # functorch Tensor with first-class dimensions
42
+ return TensorInfo(
43
+ h._get_tensor(),
44
+ h._get_levels(),
45
+ h._get_has_device(),
46
+ h._get_batchtensor() if ensure_batched else None,
47
+ )
48
+ elif Dim.check_exact(h):
49
+ # For Dim objects, only get range/batchtensor if needed and dimension is bound
50
+ tensor = h._get_range() if h.is_bound else None
51
+ batchtensor = (
52
+ h._get_batchtensor() if ensure_batched and h.is_bound else None
53
+ )
54
+ return TensorInfo(
55
+ tensor,
56
+ [DimEntry(h)],
57
+ False,
58
+ batchtensor,
59
+ )
60
+ elif isinstance(h, torch.Tensor):
61
+ # Plain torch tensor - create positional levels
62
+ levels = []
63
+ for i in range(-h.dim(), 0):
64
+ levels.append(DimEntry(i))
65
+ return TensorInfo(h, levels, True, h)
66
+ else:
67
+ if ensure_present:
68
+ raise ValueError("expected a tensor object")
69
+ return TensorInfo(None, [], False, None)
.venv/lib/python3.10/site-packages/functorch/dim/_wrap.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Python implementation of function wrapping functionality for functorch.dim.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import functools
8
+ from typing import Any, Optional, TYPE_CHECKING
9
+
10
+ import torch
11
+ from torch.utils._pytree import tree_map
12
+
13
+ from ._dim_entry import DimEntry
14
+ from ._enable_all_layers import EnableAllLayers
15
+ from ._tensor_info import TensorInfo
16
+
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Callable
20
+
21
+
22
+ def handle_from_tensor(tensor: torch.Tensor) -> torch.Tensor:
23
+ """Handle tensor conversion for torch function integration."""
24
+ return tensor
25
+
26
+
27
+ class WrappedOperator:
28
+ """
29
+ This class wraps PyTorch operations to support first-class dimensions.
30
+ """
31
+
32
+ def __init__(
33
+ self, orig: Callable, wrapper_implementation: Callable, dim_name: str = "dim"
34
+ ):
35
+ self.orig = orig
36
+ self.wrapper_implementation = wrapper_implementation
37
+ self.name = getattr(orig, "__name__", "")
38
+ self.doc = getattr(orig, "__doc__", None)
39
+ self.dim_name = dim_name
40
+
41
+ self.is_pointwise = False
42
+ self.dim_offset = 0
43
+ self.keepdim_offset = 1
44
+ self.single_dim = False
45
+ self.reduce = True
46
+
47
+ # Update docstring if we have a dim_name
48
+ if self.doc and self.dim_name:
49
+ self.doc = f"{self.doc}\nArgument '{self.dim_name}' can be either an integer or a torchdim.Dim object.\n"
50
+
51
+ def function(self) -> Callable:
52
+ """Create a wrapped function that calls our wrapper implementation."""
53
+
54
+ def wrapped_func(*args: Any, **kwargs: Any) -> Any:
55
+ return self.wrapper_implementation(self, *args, **kwargs)
56
+
57
+ # Copy metadata using functools.update_wrapper for just __name__ and __doc__
58
+ functools.update_wrapper(
59
+ wrapped_func, self.orig, assigned=("__name__",), updated=()
60
+ )
61
+ wrapped_func.__doc__ = self.doc
62
+
63
+ return wrapped_func
64
+
65
+
66
+ def _wrap_dim(dim: Any, ndim: int, keepdim: bool = False) -> DimEntry:
67
+ """Convert single dimension specification to DimEntry object."""
68
+ from . import Dim
69
+
70
+ if isinstance(dim, Dim):
71
+ if keepdim:
72
+ raise ValueError("cannot preserve first-class dimensions with keepdim=True")
73
+ return DimEntry(dim)
74
+ elif isinstance(dim, int):
75
+ i = dim
76
+ while i >= 0:
77
+ i -= ndim
78
+ return DimEntry(i)
79
+ else:
80
+ return DimEntry()
81
+
82
+
83
+ def _wrap_dims(dim: Any, ndim: int, keepdim: bool = False) -> list[DimEntry]:
84
+ """Convert dimension specification to list of DimEntry objects."""
85
+ de = _wrap_dim(dim, ndim, keepdim)
86
+ result = []
87
+ if not de.is_none():
88
+ result.append(de)
89
+ else:
90
+ for d in dim:
91
+ result.append(_wrap_dim(d, ndim, keepdim))
92
+ return result
93
+
94
+
95
+ def patched_dim_method(wrapper: WrappedOperator, *args: Any, **kwargs: Any) -> Any:
96
+ """
97
+ This is the core method that handles dimension-aware operations.
98
+ """
99
+ if not args:
100
+ raise ValueError("Expected at least one argument (self)")
101
+
102
+ # Get dimension argument
103
+ dim_arg = kwargs.get(wrapper.dim_name)
104
+ if dim_arg is None and wrapper.dim_offset < len(args):
105
+ # Try to get dim from positional args (accounting for self at index 0)
106
+ dim_idx = wrapper.dim_offset + 1
107
+ if dim_idx < len(args):
108
+ dim_arg = args[dim_idx]
109
+
110
+ # If no dimension argument provided, fall back to standard functorch handling
111
+ if dim_arg is None:
112
+ info = TensorInfo.create(args[0], ensure_batched=True, ensure_present=False)
113
+ if not info:
114
+ return wrapper.orig(*args, **kwargs)
115
+
116
+ with EnableAllLayers(info.levels) as guard:
117
+ if info.batchedtensor is None:
118
+ raise AssertionError("Expected batchedtensor to be non-None")
119
+ guard.inplace_update_layers(info.batchedtensor, info.levels)
120
+ new_args = list(args)
121
+ new_args[0] = handle_from_tensor(info.batchedtensor)
122
+ result = wrapper.orig(*new_args, **kwargs)
123
+ return guard.from_batched(result, info.has_device)
124
+
125
+ # Handle dimension-aware operation
126
+ info = TensorInfo.create(args[0])
127
+ if not info:
128
+ return wrapper.orig(*args, **kwargs)
129
+
130
+ # Check for keepdim parameter
131
+ keepdim = False
132
+ if wrapper.reduce:
133
+ keepdim_arg = kwargs.get("keepdim")
134
+ if keepdim_arg is None and wrapper.keepdim_offset < len(args):
135
+ keepdim_idx = wrapper.keepdim_offset + 1
136
+ if keepdim_idx < len(args):
137
+ keepdim_arg = args[keepdim_idx]
138
+ if keepdim_arg is not None:
139
+ keepdim = bool(keepdim_arg)
140
+
141
+ # Wrap dimensions
142
+ ndim = info.ndim()
143
+ dims = _wrap_dims(dim_arg, ndim, keepdim)
144
+
145
+ # Convert dimensions to indices and validate
146
+ dim_indices: list[int] = []
147
+ seen = [False] * len(info.levels)
148
+
149
+ for d in dims:
150
+ midx = None
151
+ for i, level in enumerate(info.levels):
152
+ if level == d:
153
+ midx = i
154
+ break
155
+
156
+ if midx is None:
157
+ # Try to match by position/name more flexibly
158
+ for i, level in enumerate(info.levels):
159
+ if hasattr(level, "matches") and level.matches(d):
160
+ midx = i
161
+ break
162
+
163
+ if midx is None:
164
+ level_strs = [str(level) for level in info.levels]
165
+ raise ValueError(
166
+ f"Tensor with dimensions {level_strs} does not contain {d}"
167
+ )
168
+
169
+ seen[midx] = True
170
+ dim_indices.append(midx)
171
+
172
+ # Determine new levels after reduction
173
+ new_levels = []
174
+ if wrapper.reduce and not keepdim:
175
+ for i, level in enumerate(info.levels):
176
+ if not seen[i]:
177
+ new_levels.append(level)
178
+ else:
179
+ new_levels = info.levels[:]
180
+
181
+ # Create dimension indices for the original function
182
+ if len(dim_indices) == 1:
183
+ py_indices: Any = dim_indices[0]
184
+ else:
185
+ py_indices = tuple(dim_indices)
186
+
187
+ # Update arguments
188
+ new_args = list(args)
189
+ new_kwargs = kwargs.copy()
190
+ if info.tensor is None:
191
+ raise AssertionError("Expected tensor to be non-None")
192
+ new_args[0] = handle_from_tensor(info.tensor)
193
+
194
+ # Update dimension argument
195
+ if wrapper.dim_name in new_kwargs:
196
+ new_kwargs[wrapper.dim_name] = py_indices
197
+ else:
198
+ dim_idx = wrapper.dim_offset + 1
199
+ if dim_idx < len(new_args):
200
+ new_args = list(new_args)
201
+ new_args[dim_idx] = py_indices
202
+
203
+ # Call original function
204
+ result = wrapper.orig(*new_args, **new_kwargs)
205
+
206
+ # Wrap results
207
+ def wrap_result(obj: Any) -> Any:
208
+ if isinstance(obj, torch.Tensor):
209
+ from . import Tensor
210
+
211
+ return Tensor.from_positional(obj, new_levels, info.has_device)
212
+ return obj
213
+
214
+ return tree_map(wrap_result, result)
215
+
216
+
217
+ def _wrap(
218
+ orig: Callable,
219
+ dim_offset: Optional[int] = None,
220
+ keepdim_offset: Optional[int] = None,
221
+ dim_name: Optional[str] = None,
222
+ single_dim: Optional[bool] = None,
223
+ reduce: Optional[bool] = None,
224
+ ) -> Callable:
225
+ """
226
+ Wrap a PyTorch function to support first-class dimensions.
227
+
228
+ Args:
229
+ orig: Original function to wrap
230
+ dim_offset: Offset for dimension argument (default: 0)
231
+ keepdim_offset: Offset for keepdim argument (default: 1)
232
+ dim_name: Name of dimension parameter (default: "dim")
233
+ single_dim: Whether function takes single dimension (default: False)
234
+ reduce: Whether function reduces dimensions (default: True)
235
+ """
236
+ dim_name = dim_name or "dim"
237
+
238
+ wrapper = WrappedOperator(orig, patched_dim_method, dim_name)
239
+
240
+ if dim_offset is not None:
241
+ wrapper.dim_offset = dim_offset
242
+ if keepdim_offset is not None:
243
+ wrapper.keepdim_offset = keepdim_offset
244
+ if single_dim is not None:
245
+ wrapper.single_dim = single_dim
246
+ if reduce is not None:
247
+ wrapper.reduce = reduce
248
+
249
+ return wrapper.function()
250
+
251
+
252
+ def call_torch_function(
253
+ wrapper: WrappedOperator,
254
+ func: Callable,
255
+ types: tuple,
256
+ args: tuple = (),
257
+ kwargs: Optional[dict] = None,
258
+ ) -> Any:
259
+ """
260
+ Handle __torch_function__ calls for wrapped operators.
261
+ """
262
+ if kwargs is None:
263
+ kwargs = {}
264
+
265
+ # Import here to avoid circular imports
266
+ from . import _Tensor
267
+
268
+ # Use the torch function mechanism from _Tensor
269
+ return _Tensor.__torch_function__(func, types, args, kwargs)
.venv/lib/python3.10/site-packages/functorch/dim/magic_trace.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ import os
7
+ import signal
8
+ import subprocess
9
+ from collections.abc import Generator
10
+ from contextlib import contextmanager
11
+
12
+
13
+ @contextmanager
14
+ def magic_trace(
15
+ output: str = "trace.fxt", magic_trace_cache: str = "/tmp/magic-trace"
16
+ ) -> Generator[None, None, None]:
17
+ pid = os.getpid()
18
+ if not os.path.exists(magic_trace_cache):
19
+ print(f"Downloading magic_trace to: {magic_trace_cache}")
20
+ subprocess.run(
21
+ [
22
+ "wget",
23
+ "-O",
24
+ magic_trace_cache,
25
+ "-q",
26
+ "https://github.com/janestreet/magic-trace/releases/download/v1.0.2/magic-trace",
27
+ ]
28
+ )
29
+ subprocess.run(["chmod", "+x", magic_trace_cache])
30
+ args = [magic_trace_cache, "attach", "-pid", str(pid), "-o", output]
31
+ p = subprocess.Popen(args, stderr=subprocess.PIPE, encoding="utf-8")
32
+ if p.stderr is None:
33
+ raise AssertionError("Expected stderr to be non-None")
34
+ while True:
35
+ x = p.stderr.readline()
36
+ print(x)
37
+ if "Attached" in x:
38
+ break
39
+ try:
40
+ yield
41
+ finally:
42
+ p.send_signal(signal.SIGINT)
43
+ r = p.wait()
44
+ if p.stderr is not None:
45
+ print(p.stderr.read())
46
+ p.stderr.close()
47
+ if r != 0:
48
+ raise ValueError(f"magic_trace exited abnormally: {r}")
.venv/lib/python3.10/site-packages/functorch/dim/op_properties.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ import torch
7
+
8
+
9
+ # pointwise operators can go through a faster pathway
10
+
11
+ tensor_magic_methods = ["add", ""]
12
+ pointwise_magic_methods_with_reverse = (
13
+ "add",
14
+ "sub",
15
+ "mul",
16
+ "floordiv",
17
+ "div",
18
+ "truediv",
19
+ "mod",
20
+ "pow",
21
+ "lshift",
22
+ "rshift",
23
+ "and",
24
+ "or",
25
+ "xor",
26
+ )
27
+ pointwise_magic_methods = (
28
+ *(x for m in pointwise_magic_methods_with_reverse for x in (m, "r" + m)),
29
+ "eq",
30
+ "gt",
31
+ "le",
32
+ "lt",
33
+ "ge",
34
+ "gt",
35
+ "ne",
36
+ "neg",
37
+ "pos",
38
+ "abs",
39
+ "invert",
40
+ "iadd",
41
+ "isub",
42
+ "imul",
43
+ "ifloordiv",
44
+ "idiv",
45
+ "itruediv",
46
+ "imod",
47
+ "ipow",
48
+ "ilshift",
49
+ "irshift",
50
+ "iand",
51
+ "ior",
52
+ "ixor",
53
+ "int",
54
+ "long",
55
+ "float",
56
+ "complex",
57
+ )
58
+
59
+ pointwise_methods = (*(f"__{m}__" for m in pointwise_magic_methods),)
60
+
61
+ pointwise = (
62
+ *(getattr(torch.Tensor, m) for m in pointwise_methods),
63
+ torch.nn.functional.dropout,
64
+ torch.where,
65
+ torch.Tensor.abs,
66
+ torch.abs,
67
+ torch.Tensor.acos,
68
+ torch.acos,
69
+ torch.Tensor.acosh,
70
+ torch.acosh,
71
+ torch.Tensor.add,
72
+ torch.add,
73
+ torch.Tensor.addcdiv,
74
+ torch.addcdiv,
75
+ torch.Tensor.addcmul,
76
+ torch.addcmul,
77
+ torch.Tensor.addr,
78
+ torch.addr,
79
+ torch.Tensor.angle,
80
+ torch.angle,
81
+ torch.Tensor.asin,
82
+ torch.asin,
83
+ torch.Tensor.asinh,
84
+ torch.asinh,
85
+ torch.Tensor.atan,
86
+ torch.atan,
87
+ torch.Tensor.atan2,
88
+ torch.atan2,
89
+ torch.Tensor.atanh,
90
+ torch.atanh,
91
+ torch.Tensor.bitwise_and,
92
+ torch.bitwise_and,
93
+ torch.Tensor.bitwise_left_shift,
94
+ torch.bitwise_left_shift,
95
+ torch.Tensor.bitwise_not,
96
+ torch.bitwise_not,
97
+ torch.Tensor.bitwise_or,
98
+ torch.bitwise_or,
99
+ torch.Tensor.bitwise_right_shift,
100
+ torch.bitwise_right_shift,
101
+ torch.Tensor.bitwise_xor,
102
+ torch.bitwise_xor,
103
+ torch.Tensor.ceil,
104
+ torch.ceil,
105
+ torch.celu,
106
+ torch.nn.functional.celu,
107
+ torch.Tensor.clamp,
108
+ torch.clamp,
109
+ torch.Tensor.clamp_max,
110
+ torch.clamp_max,
111
+ torch.Tensor.clamp_min,
112
+ torch.clamp_min,
113
+ torch.Tensor.copysign,
114
+ torch.copysign,
115
+ torch.Tensor.cos,
116
+ torch.cos,
117
+ torch.Tensor.cosh,
118
+ torch.cosh,
119
+ torch.Tensor.deg2rad,
120
+ torch.deg2rad,
121
+ torch.Tensor.digamma,
122
+ torch.digamma,
123
+ torch.Tensor.div,
124
+ torch.div,
125
+ torch.dropout,
126
+ torch.nn.functional.dropout,
127
+ torch.nn.functional.elu,
128
+ torch.Tensor.eq,
129
+ torch.eq,
130
+ torch.Tensor.erf,
131
+ torch.erf,
132
+ torch.Tensor.erfc,
133
+ torch.erfc,
134
+ torch.Tensor.erfinv,
135
+ torch.erfinv,
136
+ torch.Tensor.exp,
137
+ torch.exp,
138
+ torch.Tensor.exp2,
139
+ torch.exp2,
140
+ torch.Tensor.expm1,
141
+ torch.expm1,
142
+ torch.feature_dropout,
143
+ torch.Tensor.float_power,
144
+ torch.float_power,
145
+ torch.Tensor.floor,
146
+ torch.floor,
147
+ torch.Tensor.floor_divide,
148
+ torch.floor_divide,
149
+ torch.Tensor.fmod,
150
+ torch.fmod,
151
+ torch.Tensor.frac,
152
+ torch.frac,
153
+ torch.Tensor.frexp,
154
+ torch.frexp,
155
+ torch.Tensor.gcd,
156
+ torch.gcd,
157
+ torch.Tensor.ge,
158
+ torch.ge,
159
+ torch.nn.functional.gelu,
160
+ torch.nn.functional.glu,
161
+ torch.Tensor.gt,
162
+ torch.gt,
163
+ torch.Tensor.hardshrink,
164
+ torch.hardshrink,
165
+ torch.nn.functional.hardshrink,
166
+ torch.nn.functional.hardsigmoid,
167
+ torch.nn.functional.hardswish,
168
+ torch.nn.functional.hardtanh,
169
+ torch.Tensor.heaviside,
170
+ torch.heaviside,
171
+ torch.Tensor.hypot,
172
+ torch.hypot,
173
+ torch.Tensor.i0,
174
+ torch.i0,
175
+ torch.Tensor.igamma,
176
+ torch.igamma,
177
+ torch.Tensor.igammac,
178
+ torch.igammac,
179
+ torch.Tensor.isclose,
180
+ torch.isclose,
181
+ torch.Tensor.isfinite,
182
+ torch.isfinite,
183
+ torch.Tensor.isinf,
184
+ torch.isinf,
185
+ torch.Tensor.isnan,
186
+ torch.isnan,
187
+ torch.Tensor.isneginf,
188
+ torch.isneginf,
189
+ torch.Tensor.isposinf,
190
+ torch.isposinf,
191
+ torch.Tensor.isreal,
192
+ torch.isreal,
193
+ torch.Tensor.kron,
194
+ torch.kron,
195
+ torch.Tensor.lcm,
196
+ torch.lcm,
197
+ torch.Tensor.ldexp,
198
+ torch.ldexp,
199
+ torch.Tensor.le,
200
+ torch.le,
201
+ torch.nn.functional.leaky_relu,
202
+ torch.Tensor.lerp,
203
+ torch.lerp,
204
+ torch.Tensor.lgamma,
205
+ torch.lgamma,
206
+ torch.Tensor.log,
207
+ torch.log,
208
+ torch.Tensor.log10,
209
+ torch.log10,
210
+ torch.Tensor.log1p,
211
+ torch.log1p,
212
+ torch.Tensor.log2,
213
+ torch.log2,
214
+ torch.nn.functional.logsigmoid,
215
+ torch.Tensor.logical_and,
216
+ torch.logical_and,
217
+ torch.Tensor.logical_not,
218
+ torch.logical_not,
219
+ torch.Tensor.logical_or,
220
+ torch.logical_or,
221
+ torch.Tensor.logical_xor,
222
+ torch.logical_xor,
223
+ torch.Tensor.logit,
224
+ torch.logit,
225
+ torch.Tensor.lt,
226
+ torch.lt,
227
+ torch.Tensor.maximum,
228
+ torch.maximum,
229
+ torch.Tensor.minimum,
230
+ torch.minimum,
231
+ torch.nn.functional.mish,
232
+ torch.Tensor.mvlgamma,
233
+ torch.mvlgamma,
234
+ torch.Tensor.nan_to_num,
235
+ torch.nan_to_num,
236
+ torch.Tensor.ne,
237
+ torch.ne,
238
+ torch.Tensor.neg,
239
+ torch.neg,
240
+ torch.Tensor.nextafter,
241
+ torch.nextafter,
242
+ torch.Tensor.outer,
243
+ torch.outer,
244
+ torch.polar,
245
+ torch.Tensor.polygamma,
246
+ torch.polygamma,
247
+ torch.Tensor.positive,
248
+ torch.positive,
249
+ torch.Tensor.pow,
250
+ torch.pow,
251
+ torch.Tensor.prelu,
252
+ torch.prelu,
253
+ torch.nn.functional.prelu,
254
+ torch.Tensor.rad2deg,
255
+ torch.rad2deg,
256
+ torch.Tensor.reciprocal,
257
+ torch.reciprocal,
258
+ torch.Tensor.relu,
259
+ torch.relu,
260
+ torch.nn.functional.relu,
261
+ torch.nn.functional.relu6,
262
+ torch.Tensor.remainder,
263
+ torch.remainder,
264
+ torch.Tensor.round,
265
+ torch.round,
266
+ torch.rrelu,
267
+ torch.nn.functional.rrelu,
268
+ torch.Tensor.rsqrt,
269
+ torch.rsqrt,
270
+ torch.rsub,
271
+ torch.selu,
272
+ torch.nn.functional.selu,
273
+ torch.Tensor.sgn,
274
+ torch.sgn,
275
+ torch.Tensor.sigmoid,
276
+ torch.sigmoid,
277
+ torch.nn.functional.sigmoid,
278
+ torch.Tensor.sign,
279
+ torch.sign,
280
+ torch.Tensor.signbit,
281
+ torch.signbit,
282
+ torch.nn.functional.silu,
283
+ torch.Tensor.sin,
284
+ torch.sin,
285
+ torch.Tensor.sinc,
286
+ torch.sinc,
287
+ torch.Tensor.sinh,
288
+ torch.sinh,
289
+ torch.nn.functional.softplus,
290
+ torch.nn.functional.softshrink,
291
+ torch.Tensor.sqrt,
292
+ torch.sqrt,
293
+ torch.Tensor.square,
294
+ torch.square,
295
+ torch.Tensor.sub,
296
+ torch.sub,
297
+ torch.Tensor.tan,
298
+ torch.tan,
299
+ torch.Tensor.tanh,
300
+ torch.tanh,
301
+ torch.nn.functional.tanh,
302
+ torch.threshold,
303
+ torch.nn.functional.threshold,
304
+ torch.trapz,
305
+ torch.Tensor.true_divide,
306
+ torch.true_divide,
307
+ torch.Tensor.trunc,
308
+ torch.trunc,
309
+ torch.Tensor.xlogy,
310
+ torch.xlogy,
311
+ torch.rand_like,
312
+ )
.venv/lib/python3.10/site-packages/functorch/dim/wrap_type.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import functools
8
+ from collections.abc import Callable
9
+ from types import (
10
+ BuiltinMethodType,
11
+ FunctionType,
12
+ GetSetDescriptorType,
13
+ MethodDescriptorType,
14
+ WrapperDescriptorType,
15
+ )
16
+ from typing import Any
17
+
18
+
19
+ FUNC_TYPES = (
20
+ FunctionType,
21
+ MethodDescriptorType,
22
+ BuiltinMethodType,
23
+ WrapperDescriptorType,
24
+ )
25
+ PROPERTY_TYPES = (GetSetDescriptorType, property)
26
+
27
+
28
+ def _py_wrap_method(orig: Callable, __torch_function__: Callable) -> Callable:
29
+ def impl(*args: Any, **kwargs: Any) -> Any:
30
+ return __torch_function__(orig, None, args, kwargs)
31
+
32
+ # Copy metadata using functools.update_wrapper for just __name__ and __doc__
33
+ functools.update_wrapper(impl, orig, assigned=("__name__", "__doc__"), updated=())
34
+
35
+ return impl
36
+
37
+
38
+ def wrap_type(to_patch: Any, pattern: type, __torch_function__: Callable) -> None:
39
+ wrap_method = _py_wrap_method
40
+
41
+ all: dict[str, Any] = {}
42
+ for t in reversed(pattern.mro()[:-1]): # skip object
43
+ all.update(t.__dict__)
44
+
45
+ def wrap_attr(orig: Any) -> property:
46
+ return property(wrap_method(orig.__get__, __torch_function__))
47
+
48
+ for name, obj in all.items():
49
+ if name in (
50
+ "__dict__",
51
+ "__new__",
52
+ "__init__",
53
+ "__repr__",
54
+ "__weakref__",
55
+ "__doc__",
56
+ "__module__",
57
+ "__dir__",
58
+ ):
59
+ continue
60
+
61
+ # skip things that have been overloaded
62
+ # things that come from object like `__eq__` still need to be patched, however.
63
+ if hasattr(to_patch, name) and getattr(to_patch, name) is not getattr(
64
+ object, name, None
65
+ ):
66
+ continue
67
+
68
+ if isinstance(obj, FUNC_TYPES):
69
+ setattr(to_patch, name, wrap_method(obj, __torch_function__))
70
+ elif isinstance(obj, PROPERTY_TYPES):
71
+ setattr(to_patch, name, wrap_attr(obj))
.venv/lib/python3.10/site-packages/functorch/einops/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .rearrange import rearrange
2
+
3
+
4
+ __all__ = ["rearrange"]
.venv/lib/python3.10/site-packages/functorch/einops/_parsing.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adapted from https://github.com/arogozhnikov/einops/blob/36c7bb16e57d6e57f8f3050f9e07abdf3f00469f/einops/parsing.py.
2
+
3
+ MIT License
4
+
5
+ Copyright (c) 2018 Alex Rogozhnikov
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import keyword
29
+ import warnings
30
+ from typing import Optional, TYPE_CHECKING, Union
31
+
32
+
33
+ if TYPE_CHECKING:
34
+ from collections.abc import Collection, Mapping
35
+
36
+
37
+ _ellipsis: str = "\u2026" # NB, this is a single unicode symbol. String is used as it is not a list, but can be iterated
38
+
39
+
40
+ class AnonymousAxis:
41
+ """Used by `ParsedExpression` to represent an axis with a size (> 1), but no associated identifier.
42
+
43
+ Note: Different instances of this class are not equal to each other, even if they have the same value.
44
+ """
45
+
46
+ def __init__(self, value: str) -> None:
47
+ self.value = int(value)
48
+ if self.value < 1:
49
+ raise ValueError(
50
+ f"Anonymous axis should have positive length, not {self.value}"
51
+ )
52
+
53
+ def __repr__(self) -> str:
54
+ return f"{self.value}-axis"
55
+
56
+
57
+ class ParsedExpression:
58
+ """Structure containing information about one side of an `einops`-style pattern (e.g. 'b c (h w)')."""
59
+
60
+ def __init__(
61
+ self,
62
+ expression: str,
63
+ *,
64
+ allow_underscore: bool = False,
65
+ allow_duplicates: bool = False,
66
+ ) -> None:
67
+ """Parse the expression and store relevant metadata.
68
+
69
+ Args:
70
+ expression (str): the `einops`-pattern to parse
71
+ allow_underscore (bool): whether to allow axis identifier names to begin with an underscore
72
+ allow_duplicates (bool): whether to allow an identifier to appear more than once in the expression
73
+ """
74
+ self.has_ellipsis: bool = False
75
+ self.has_ellipsis_parenthesized: Optional[bool] = None
76
+ self.identifiers: set[Union[str, AnonymousAxis]] = set()
77
+ # that's axes like 2, 3, 4 or 5. Axes with size 1 are exceptional and replaced with empty composition
78
+ self.has_non_unitary_anonymous_axes: bool = False
79
+ # composition keeps structure of composite axes, see how different corner cases are handled in tests
80
+ self.composition: list[Union[list[Union[str, AnonymousAxis]], str]] = []
81
+ if "." in expression:
82
+ if "..." not in expression:
83
+ raise ValueError(
84
+ "Expression may contain dots only inside ellipsis (...)"
85
+ )
86
+ if str.count(expression, "...") != 1 or str.count(expression, ".") != 3:
87
+ raise ValueError(
88
+ "Expression may contain dots only inside ellipsis (...); only one ellipsis for tensor "
89
+ )
90
+ expression = expression.replace("...", _ellipsis)
91
+ self.has_ellipsis = True
92
+
93
+ bracket_group: Optional[list[Union[str, AnonymousAxis]]] = None
94
+
95
+ def add_axis_name(x: str) -> None:
96
+ if x in self.identifiers:
97
+ if not (allow_underscore and x == "_") and not allow_duplicates:
98
+ raise ValueError(
99
+ f"Indexing expression contains duplicate dimension '{x}'"
100
+ )
101
+ if x == _ellipsis:
102
+ self.identifiers.add(_ellipsis)
103
+ if bracket_group is None:
104
+ self.composition.append(_ellipsis)
105
+ self.has_ellipsis_parenthesized = False
106
+ else:
107
+ bracket_group.append(_ellipsis)
108
+ self.has_ellipsis_parenthesized = True
109
+ else:
110
+ is_number = str.isdecimal(x)
111
+ if is_number and int(x) == 1:
112
+ # handling the case of anonymous axis of length 1
113
+ if bracket_group is None:
114
+ self.composition.append([])
115
+ else:
116
+ pass # no need to think about 1s inside parenthesis
117
+ return
118
+ is_axis_name, reason = self.check_axis_name_return_reason(
119
+ x, allow_underscore=allow_underscore
120
+ )
121
+ if not (is_number or is_axis_name):
122
+ raise ValueError(f"Invalid axis identifier: {x}\n{reason}")
123
+ axis_name: Union[str, AnonymousAxis] = (
124
+ AnonymousAxis(x) if is_number else x
125
+ )
126
+ self.identifiers.add(axis_name)
127
+ if is_number:
128
+ self.has_non_unitary_anonymous_axes = True
129
+ if bracket_group is None:
130
+ self.composition.append([axis_name])
131
+ else:
132
+ bracket_group.append(axis_name)
133
+
134
+ current_identifier = None
135
+ for char in expression:
136
+ if char in "() ":
137
+ if current_identifier is not None:
138
+ add_axis_name(current_identifier)
139
+ current_identifier = None
140
+ if char == "(":
141
+ if bracket_group is not None:
142
+ raise ValueError(
143
+ "Axis composition is one-level (brackets inside brackets not allowed)"
144
+ )
145
+ bracket_group = []
146
+ elif char == ")":
147
+ if bracket_group is None:
148
+ raise ValueError("Brackets are not balanced")
149
+ self.composition.append(bracket_group)
150
+ bracket_group = None
151
+ elif str.isalnum(char) or char in ["_", _ellipsis]:
152
+ if current_identifier is None:
153
+ current_identifier = char
154
+ else:
155
+ current_identifier += char
156
+ else:
157
+ raise ValueError(f"Unknown character '{char}'")
158
+
159
+ if bracket_group is not None:
160
+ raise ValueError(f"Imbalanced parentheses in expression: '{expression}'")
161
+ if current_identifier is not None:
162
+ add_axis_name(current_identifier)
163
+
164
+ @staticmethod
165
+ def check_axis_name_return_reason(
166
+ name: str, allow_underscore: bool = False
167
+ ) -> tuple[bool, str]:
168
+ """Check if the given axis name is valid, and a message explaining why if not.
169
+
170
+ Valid axes names are python identifiers except keywords, and should not start or end with an underscore.
171
+
172
+ Args:
173
+ name (str): the axis name to check
174
+ allow_underscore (bool): whether axis names are allowed to start with an underscore
175
+
176
+ Returns:
177
+ tuple[bool, str]: whether the axis name is valid, a message explaining why if not
178
+ """
179
+ if not str.isidentifier(name):
180
+ return False, "not a valid python identifier"
181
+ elif name[0] == "_" or name[-1] == "_":
182
+ if name == "_" and allow_underscore:
183
+ return True, ""
184
+ return False, "axis name should should not start or end with underscore"
185
+ else:
186
+ if keyword.iskeyword(name):
187
+ warnings.warn(
188
+ f"It is discouraged to use axes names that are keywords: {name}",
189
+ RuntimeWarning,
190
+ )
191
+ if name == "axis":
192
+ warnings.warn(
193
+ "It is discouraged to use 'axis' as an axis name and will raise an error in future",
194
+ FutureWarning,
195
+ )
196
+ return True, ""
197
+
198
+ @staticmethod
199
+ def check_axis_name(name: str) -> bool:
200
+ """Check if the name is a valid axis name.
201
+
202
+ Args:
203
+ name (str): the axis name to check
204
+
205
+ Returns:
206
+ bool: whether the axis name is valid
207
+ """
208
+ is_valid, _ = ParsedExpression.check_axis_name_return_reason(name)
209
+ return is_valid
210
+
211
+
212
+ def parse_pattern(
213
+ pattern: str, axes_lengths: Mapping[str, int]
214
+ ) -> tuple[ParsedExpression, ParsedExpression]:
215
+ """Parse an `einops`-style pattern into a left-hand side and right-hand side `ParsedExpression` object.
216
+
217
+ Args:
218
+ pattern (str): the `einops`-style rearrangement pattern
219
+ axes_lengths (Mapping[str, int]): any additional length specifications for dimensions
220
+
221
+ Returns:
222
+ tuple[ParsedExpression, ParsedExpression]: a tuple containing the left-hand side and right-hand side expressions
223
+ """
224
+ # adapted from einops.einops._prepare_transformation_recipe
225
+ # https://github.com/arogozhnikov/einops/blob/230ac1526c1f42c9e1f7373912c7f8047496df11/einops/einops.py
226
+ try:
227
+ left_str, right_str = pattern.split("->")
228
+ except ValueError:
229
+ raise ValueError("Pattern must contain a single '->' separator") from None
230
+
231
+ if _ellipsis in axes_lengths:
232
+ raise ValueError(f"'{_ellipsis}' is not an allowed axis identifier")
233
+
234
+ left = ParsedExpression(left_str)
235
+ right = ParsedExpression(right_str)
236
+
237
+ if not left.has_ellipsis and right.has_ellipsis:
238
+ raise ValueError(
239
+ f"Ellipsis found in right side, but not left side of a pattern {pattern}"
240
+ )
241
+ if left.has_ellipsis and left.has_ellipsis_parenthesized:
242
+ raise ValueError(
243
+ f"Ellipsis is parenthesis in the left side is not allowed: {pattern}"
244
+ )
245
+
246
+ return left, right
247
+
248
+
249
+ def validate_rearrange_expressions(
250
+ left: ParsedExpression, right: ParsedExpression, axes_lengths: Mapping[str, int]
251
+ ) -> None:
252
+ """Perform expression validations that are specific to the `rearrange` operation.
253
+
254
+ Args:
255
+ left (ParsedExpression): left-hand side expression
256
+ right (ParsedExpression): right-hand side expression
257
+ axes_lengths (Mapping[str, int]): any additional length specifications for dimensions
258
+ """
259
+ for length in axes_lengths.values():
260
+ if (length_type := type(length)) is not int:
261
+ raise TypeError(
262
+ f"rearrange axis lengths must be integers, got: {length_type}"
263
+ )
264
+
265
+ if left.has_non_unitary_anonymous_axes or right.has_non_unitary_anonymous_axes:
266
+ raise ValueError("rearrange only supports unnamed axes of size 1")
267
+
268
+ difference = set.symmetric_difference(left.identifiers, right.identifiers)
269
+ if len(difference) > 0:
270
+ raise ValueError(
271
+ f"Identifiers only on one side of rearrange expression (should be on both): {difference}"
272
+ )
273
+
274
+ unmatched_axes = axes_lengths.keys() - left.identifiers
275
+ if len(unmatched_axes) > 0:
276
+ raise ValueError(
277
+ f"Identifiers not found in rearrange expression: {unmatched_axes}"
278
+ )
279
+
280
+
281
+ def comma_separate(collection: Collection[Union[str, Collection[str]]]) -> str:
282
+ """Convert a collection of strings representing first class dims into a comma-separated string.
283
+
284
+ Args:
285
+ collection (Collection[Union[str, Collection[str]]]): the collection of strings to convert
286
+
287
+ Returns:
288
+ str: the comma-separated string
289
+
290
+ Examples:
291
+ >>> comma_separate(("d0",))
292
+ 'd0'
293
+
294
+ >>> comma_separate(("d0", "d1", "d2", "d3"))
295
+ 'd0, d1, d2, d3'
296
+
297
+ >>> comma_separate([("d1", "d4")])
298
+ '(d1, d4)'
299
+
300
+ >>> comma_separate([("d0",), (), ("d1",), ("d2",), ("d3", "d4")])
301
+ '(d0,), (), (d1,), (d2,), (d3, d4)'
302
+ """
303
+ return ", ".join(
304
+ item
305
+ if isinstance(item, str)
306
+ else f"({comma_separate(item)}{',' if len(item) == 1 else ''})"
307
+ for item in collection
308
+ )
.venv/lib/python3.10/site-packages/functorch/einops/rearrange.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ from typing import TYPE_CHECKING, Union
5
+
6
+ import torch
7
+ from functorch.dim import dims # noqa: F401
8
+
9
+ from ._parsing import (
10
+ _ellipsis,
11
+ AnonymousAxis,
12
+ comma_separate,
13
+ parse_pattern,
14
+ validate_rearrange_expressions,
15
+ )
16
+
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Callable, Sequence
20
+
21
+ __all__ = ["rearrange"]
22
+
23
+
24
+ @functools.lru_cache(256)
25
+ def _create_rearrange_callable(
26
+ tensor_ndim: int, pattern: str, **axes_lengths: int
27
+ ) -> Callable[[torch.Tensor], torch.Tensor]:
28
+ r"""Translate an `einops`-style pattern into a callable that performs the rearrange using first-class dimensions.
29
+
30
+ Since the an equivalent result is computed for tensors with the same number of dimensions, with the same pattern and
31
+ specified axes lengths, this function can be memoized.
32
+
33
+ Args:
34
+ tensor_ndim (int): the number of dimensions in the tensor to rearrange
35
+ pattern (str): the `einops`-style rearrangement pattern
36
+ axes_lengths (int): any additional length specifications for dimensions
37
+
38
+ Returns:
39
+ Callable[[torch.Tensor], torch.Tensor]: a callable that performs the rearrangement
40
+ """
41
+ left, right = parse_pattern(pattern, axes_lengths)
42
+ validate_rearrange_expressions(left, right, axes_lengths)
43
+
44
+ n_anon_dims = sum(not dim for dim in left.composition)
45
+ if left.has_ellipsis:
46
+ n_ellipsis_dims = tensor_ndim - (len(left.composition) - 1)
47
+ n_named_dims = len(left.identifiers) - 1
48
+
49
+ if (pattern_ndim := n_anon_dims + n_named_dims) > tensor_ndim:
50
+ raise ValueError(
51
+ f"Number of dimensions in pattern ({pattern_ndim}) must be less than or equal to the number of "
52
+ f"dimensions in the tensor ({tensor_ndim})"
53
+ )
54
+ else:
55
+ n_ellipsis_dims = 0
56
+ n_named_dims = len(left.identifiers)
57
+
58
+ if (pattern_ndim := len(left.composition)) != tensor_ndim:
59
+ raise ValueError(
60
+ f"Number of dimensions in pattern ({pattern_ndim}) must be equal to the number of dimensions in "
61
+ f"the tensor ({tensor_ndim})"
62
+ )
63
+ n_dims = n_named_dims + n_ellipsis_dims + n_anon_dims
64
+
65
+ if n_dims == 0:
66
+ # an identity rearrangement on a 0-dimension tensor
67
+ return lambda tensor: tensor
68
+
69
+ first_class_dims: tuple[str, ...] = tuple(f"d{i}" for i in range(n_dims))
70
+ identifier_dim_map: dict[Union[str, AnonymousAxis], tuple[str, ...]] = {}
71
+ anon_axes: list[AnonymousAxis] = []
72
+
73
+ # map the left-hand side identifiers to strings representing first class dims
74
+ dims_i = 0
75
+ for dimension in left.composition:
76
+ if isinstance(dimension, list):
77
+ for identifier in dimension:
78
+ # non-unitary anon axes are not allowed in rearrange & unitary anon axes are represented as empty lists
79
+ if not isinstance(identifier, str):
80
+ raise AssertionError(f"Expected str, got {type(identifier)}")
81
+ identifier_dim_map[identifier] = (first_class_dims[dims_i],)
82
+ dims_i += 1
83
+ if not dimension:
84
+ # unitary anonymous axis
85
+ anon_axis = AnonymousAxis("1")
86
+ identifier_dim_map[anon_axis] = (first_class_dims[dims_i],)
87
+ anon_axes.append(anon_axis)
88
+ dimension.append(anon_axis)
89
+ dims_i += 1
90
+ elif dimension == _ellipsis:
91
+ identifier = _ellipsis
92
+ identifier_dim_map[identifier] = tuple(
93
+ first_class_dims[dims_i + j] for j in range(n_ellipsis_dims)
94
+ )
95
+ dims_i += n_ellipsis_dims
96
+ else:
97
+ raise ValueError(f"Unexpected dimension: {dimension}")
98
+
99
+ def composition_to_dims(
100
+ composition: Sequence[Union[list[Union[str, AnonymousAxis]], str]],
101
+ ) -> list[Union[str, tuple[str, ...]]]:
102
+ """Convert a `ParsedExpression.composition` into a `Tensor.__getitem__` index of strings representing first
103
+ class dims."""
104
+ dim_composition: list[Union[str, tuple[str, ...]]] = []
105
+ for dimension in composition:
106
+ if isinstance(dimension, list):
107
+ dim_composition.append(
108
+ tuple(
109
+ dim
110
+ for identifier in dimension
111
+ for dim in identifier_dim_map[identifier]
112
+ )
113
+ )
114
+ elif dimension == _ellipsis:
115
+ dim_composition.extend(identifier_dim_map[_ellipsis])
116
+ else:
117
+ raise ValueError(f"Unexpected dimension: {dimension}")
118
+ return dim_composition
119
+
120
+ left_dims = composition_to_dims(left.composition)
121
+ right_dims = composition_to_dims(right.composition)
122
+ anon_dims = tuple(identifier_dim_map[axis][0] for axis in anon_axes)
123
+ specified_lengths = tuple(
124
+ (identifier_dim_map[axis][0], length) for axis, length in axes_lengths.items()
125
+ )
126
+
127
+ custom_rearrange_callable_name = "do_rearrange"
128
+ custom_rearrange_callable_code = (
129
+ (
130
+ f"def {custom_rearrange_callable_name}(tensor):\n"
131
+ f" {comma_separate(first_class_dims)} = dims({n_dims})\n"
132
+ )
133
+ + (
134
+ "".join(
135
+ f" {dim}.size = {length}\n" for (dim, length) in specified_lengths
136
+ )
137
+ if specified_lengths
138
+ else ""
139
+ )
140
+ + f" tensor = tensor[{comma_separate(left_dims)}].order({comma_separate(right_dims)})\n"
141
+ + (
142
+ f" return tensor.sum({comma_separate([anon_dims])}, keepdim=False)\n"
143
+ if anon_dims
144
+ else " return tensor\n"
145
+ )
146
+ )
147
+
148
+ exec(custom_rearrange_callable_code)
149
+ return locals()[custom_rearrange_callable_name]
150
+
151
+
152
+ def rearrange(
153
+ tensor: Union[torch.Tensor, list[torch.Tensor], tuple[torch.Tensor, ...]],
154
+ pattern: str,
155
+ **axes_lengths: int,
156
+ ) -> torch.Tensor:
157
+ r"""A native implementation of `einops.rearrange`, a reader-friendly smart element reordering for multidimensional
158
+ tensors. This operation includes functionality of transpose (axes permutation), reshape (view), squeeze, unsqueeze,
159
+ stack, concatenate and other operations.
160
+
161
+ See: https://einops.rocks/api/rearrange/
162
+
163
+ Args:
164
+ tensor (Tensor or sequence of Tensor): the tensor(s) to rearrange
165
+ pattern (str): the rearrangement pattern
166
+ axes_lengths (int): any additional length specifications for dimensions
167
+
168
+ Returns:
169
+ Tensor: the rearranged tensor
170
+
171
+ Examples:
172
+ >>> # suppose we have a set of 32 images in "h w c" format (height-width-channel)
173
+ >>> images = torch.randn((32, 30, 40, 3))
174
+
175
+ >>> # stack along first (batch) axis, output is a single array
176
+ >>> rearrange(images, "b h w c -> b h w c").shape
177
+ torch.Size([32, 30, 40, 3])
178
+
179
+ >>> # concatenate images along height (vertical axis), 960 = 32 * 30
180
+ >>> rearrange(images, "b h w c -> (b h) w c").shape
181
+ torch.Size([960, 40, 3])
182
+
183
+ >>> # concatenated images along horizontal axis, 1280 = 32 * 40
184
+ >>> rearrange(images, "b h w c -> h (b w) c").shape
185
+ torch.Size([30, 1280, 3])
186
+
187
+ >>> # reordered axes to "b c h w" format for deep learning
188
+ >>> rearrange(images, "b h w c -> b c h w").shape
189
+ torch.Size([32, 3, 30, 40])
190
+
191
+ >>> # flattened each image into a vector, 3600 = 30 * 40 * 3
192
+ >>> rearrange(images, "b h w c -> b (c h w)").shape
193
+ torch.Size([32, 3600])
194
+
195
+ >>> # split each image into 4 smaller (top-left, top-right, bottom-left, bottom-right), 128 = 32 * 2 * 2
196
+ >>> rearrange(images, "b (h1 h) (w1 w) c -> (b h1 w1) h w c", h1=2, w1=2).shape
197
+ torch.Size([128, 15, 20, 3])
198
+
199
+ >>> # space-to-depth operation
200
+ >>> rearrange(images, "b (h h1) (w w1) c -> b h w (c h1 w1)", h1=2, w1=2).shape
201
+ torch.Size([32, 15, 20, 12])
202
+ """
203
+ if not isinstance(tensor, torch.Tensor):
204
+ tensor = torch.stack(tensor)
205
+
206
+ rearrange_callable = _create_rearrange_callable(
207
+ tensor.ndim, pattern, **axes_lengths
208
+ )
209
+
210
+ return rearrange_callable(tensor)
.venv/lib/python3.10/site-packages/functorch/experimental/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # PyTorch forward-mode is not mature yet
2
+ from torch._functorch.apis import chunk_vmap
3
+ from torch._functorch.batch_norm_replacement import replace_all_batch_norm_modules_
4
+ from torch._functorch.eager_transforms import hessian, jacfwd, jvp
5
+ from torch.func import functionalize
.venv/lib/python3.10/site-packages/functorch/experimental/control_flow.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from torch import cond # noqa: F401
2
+ from torch._higher_order_ops.map import ( # noqa: F401
3
+ _stack_pytree,
4
+ _unstack_pytree,
5
+ map,
6
+ )
.venv/lib/python3.10/site-packages/functorch/experimental/ops.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from torch._ops import HigherOrderOperator # noqa: F401
.venv/lib/python3.10/site-packages/h11/__pycache__/_events.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
.venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
.venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/METADATA ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: joserfc
3
+ Version: 1.6.4
4
+ Summary: The ultimate Python library for JOSE RFCs, including JWS, JWE, JWK, JWA, JWT
5
+ Author-email: Hsiaoming Yang <me@lepture.com>
6
+ License: BSD-3-Clause
7
+ Project-URL: Documentation, https://jose.authlib.org/
8
+ Project-URL: Source, https://github.com/authlib/joserfc
9
+ Project-URL: Funding, https://github.com/sponsors/authlib
10
+ Project-URL: Blog, https://blog.authlib.org/
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Environment :: Console
13
+ Classifier: Environment :: Web Environment
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: BSD License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Programming Language :: Python :: Implementation :: CPython
26
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
27
+ Classifier: Topic :: Security
28
+ Classifier: Topic :: Security :: Cryptography
29
+ Requires-Python: >=3.9
30
+ Description-Content-Type: text/x-rst
31
+ License-File: LICENSE
32
+ Requires-Dist: cryptography>=45.0.1
33
+ Provides-Extra: drafts
34
+ Requires-Dist: pycryptodome; extra == "drafts"
35
+ Dynamic: license-file
36
+
37
+ JOSE RFC
38
+ ========
39
+
40
+ ``joserfc`` is a Python library that provides a comprehensive implementation of several
41
+ essential JSON Object Signing and Encryption (JOSE) standards.
42
+
43
+ This package contains implementation of:
44
+
45
+ - RFC7515: JSON Web Signature
46
+ - RFC7516: JSON Web Encryption
47
+ - RFC7517: JSON Web Key
48
+ - RFC7518: JSON Web Algorithms
49
+ - RFC7519: JSON Web Token
50
+ - RFC7520: Examples of Protecting Content Using JSON Object Signing and Encryption
51
+ - RFC7638: JSON Web Key (JWK) Thumbprint
52
+ - RFC7797: JSON Web Signature (JWS) Unencoded Payload Option
53
+ - RFC8037: OKP Key and EdDSA algorithm
54
+ - RFC8812: ES256K algorithm
55
+ - RFC9278: JWK Thumbprint URI
56
+ - RFC9864: ``Ed25519`` and ``Ed448`` algorithms
57
+
58
+ And draft RFCs implementation of:
59
+
60
+ - draft-ietf-jose-deprecate-none-rsa15-02
61
+ - draft-amringer-jose-chacha-02
62
+ - draft-madden-jose-ecdh-1pu-04
63
+
64
+ Usage
65
+ -----
66
+
67
+ A quick and simple JWT encoding and decoding would look something like this:
68
+
69
+ .. code-block:: python
70
+
71
+ >>> from joserfc import jwt, jwk
72
+ >>> key = jwk.import_key("your-secret-key", "oct")
73
+ >>> encoded_jwt = jwt.encode({"alg": "HS256"}, {"k": "value"}, key)
74
+ >>> encoded_jwt
75
+ 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJrIjoidmFsdWUifQ._M8ViO_GK6TnZ9G9eqdlS7IpNWzhoGwaYYDQ3hEwwmA'
76
+ >>> token = jwt.decode(encoded_jwt, key)
77
+ >>> token.header
78
+ {'alg': 'HS256', 'typ': 'JWT'}
79
+ >>> token.claims
80
+ {'key': 'value'}
81
+ >>> claims_requests = jwt.JWTClaimsRegistry()
82
+ >>> claims_requests.validate(token.claims)
83
+
84
+ Useful Links
85
+ ------------
86
+
87
+ 1. GitHub: https://github.com/authlib/joserfc
88
+ 2. Docs: https://jose.authlib.org/en/
89
+
90
+ License
91
+ -------
92
+
93
+ Licensed under BSD. Please see LICENSE for licensing details.
.venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/RECORD ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ joserfc-1.6.4.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
2
+ joserfc-1.6.4.dist-info/METADATA,sha256=fKwfDn_Z0a_IT6f65WNfGad1kJXks7IFOP-VHfX0Nkc,3183
3
+ joserfc-1.6.4.dist-info/RECORD,,
4
+ joserfc-1.6.4.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ joserfc-1.6.4.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
6
+ joserfc-1.6.4.dist-info/licenses/LICENSE,sha256=Ge4fr8yexCF_wyuKZR2CBTjHic9AQctORrSxdqXyqcg,1501
7
+ joserfc-1.6.4.dist-info/top_level.txt,sha256=pTU_ZAJ43AZ3qX9VkHIM98oVG_D37z15bc056667DTM,8
8
+ joserfc/__init__.py,sha256=IQmsBfdBbCP6JSrqTgpmJx9DFxXjxnE6dyh3g_xTW_M,144
9
+ joserfc/_keys.py,sha256=vdkSd4dmnjEoyD0Tx08GjL1gWZzjWanJ7OzP_qAfKFU,6652
10
+ joserfc/_rfc7515/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ joserfc/_rfc7515/compact.py,sha256=-9zbe_mE56T_Qg3ItX4AgGw4Il4E44b1pW9i4SgP0i8,1538
12
+ joserfc/_rfc7515/json.py,sha256=-dvNcN0XCMW1EMQ6Z8uojFtyk1yiSCd9xZNsujY5f5w,5210
13
+ joserfc/_rfc7515/model.py,sha256=bY3mN7RyooJJcKNYTIgBEwWagxeyCpN7L3_uB3u5GQQ,4262
14
+ joserfc/_rfc7515/registry.py,sha256=_XCwH6oRM-OooMRT4gV14jyeSNWZFAl6NuJo2RA1w1E,6260
15
+ joserfc/_rfc7515/types.py,sha256=fomvh-Xkhu5bR3g5ATamK-gisJjsBtC6GNhw7T8DnvU,754
16
+ joserfc/_rfc7516/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
+ joserfc/_rfc7516/compact.py,sha256=4uhq1brqDi8pymRKuYRPS8C7Vx2Tqd6TuoKnBdsSpgw,2263
18
+ joserfc/_rfc7516/json.py,sha256=esSIKYro2AxNfg-iYJPAISw5K2kkJ_I5t-HV9hPt1VE,4911
19
+ joserfc/_rfc7516/message.py,sha256=7_y-MyAL-jRED6nNnECbiVjSMLTokC3uAWhV_VUaQS0,10203
20
+ joserfc/_rfc7516/models.py,sha256=TMjTz907O0mC4lVO1jmi5eAGcG8nKKG8MgqYRuNRaC8,10902
21
+ joserfc/_rfc7516/registry.py,sha256=AhjHyWrzrDKTUt5zLNJwyJzRq2Ew0eEVHiVNwhahoVs,6220
22
+ joserfc/_rfc7516/types.py,sha256=2OxhzfWN3a82nqvvcdOe9-rUBCQc5bAHBTf4xGu16a4,666
23
+ joserfc/_rfc7517/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ joserfc/_rfc7517/models.py,sha256=yFMwC55bE8pQLxNp7BNQ_qEsuV0Fqu6Tb2za5A2lD78,12239
25
+ joserfc/_rfc7517/pem.py,sha256=8TovnKLBqca-4vHcE70Ax5uY8o2stYMyD32AR9NGan4,4792
26
+ joserfc/_rfc7517/types.py,sha256=W_w52zZnCLeSpeci4FfpDkK7bHm-PZbNa5_RwQkBGVo,504
27
+ joserfc/_rfc7518/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
28
+ joserfc/_rfc7518/derive_key.py,sha256=LTYUCzEEdhE6b8k4vUou7sE728eFXvHUSlolBo--qsE,1436
29
+ joserfc/_rfc7518/ec_key.py,sha256=EbnFHumUpLQadt-QOK5zWiJEgqhhtcSfW91dLMhyXnU,9184
30
+ joserfc/_rfc7518/jwe_algs.py,sha256=xtraQpqqAhiFyVEaGbaEISFCP_zvxqo7nkcXwj1owAs,13073
31
+ joserfc/_rfc7518/jwe_encs.py,sha256=tvxsYKrnkxBHAcKZP3_J7XQfiorWcOl8GnluFnCGalU,4143
32
+ joserfc/_rfc7518/jwe_zips.py,sha256=7xrI4V_qKemPlkrpE4lWL_A2I_4aoXQiTvCvbIBQ1oE,1083
33
+ joserfc/_rfc7518/jws_algs.py,sha256=W3D_iK7DxGVgAZi_a8aVK7pTvp69A-fZRl7RrXDGJro,6653
34
+ joserfc/_rfc7518/oct_key.py,sha256=2_mcAuEFarcj6PUUmRuWuzR415NUDybN-90LFPm8u3Y,2973
35
+ joserfc/_rfc7518/rsa_key.py,sha256=fcHCw2AYC6X2KI4WulkTcRYpwMiSC7Y5y1mB95hNXKg,6980
36
+ joserfc/_rfc7518/util.py,sha256=tEcrRgjf1F6eVBqSZBFOA1iR58dfpBWDpXInCXeevwQ,298
37
+ joserfc/_rfc7519/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
38
+ joserfc/_rfc7519/claims.py,sha256=3y4K2gfgUCsywEiRhmNLSnpgfu6e_ieTiFum-7io5og,6491
39
+ joserfc/_rfc7519/security.py,sha256=2fSuKBIPAfZ5ugB-iX0GFxYZtC_oMGvZaY1BAx5LXhM,1270
40
+ joserfc/_rfc7638/__init__.py,sha256=7MKaB3rx62T_UdR8rnsfQdhr3opIqWW0AYbfAIye_9o,938
41
+ joserfc/_rfc7797/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
42
+ joserfc/_rfc7797/compact.py,sha256=Y6tr-2aAoW8ZPQ46wmZeiLGbPO6MrOoWjif7nj8JOeU,2854
43
+ joserfc/_rfc7797/json.py,sha256=aCM7uy0smoMcdVObZj5GkRPZZFswJ2kk_mYO6pEL954,1872
44
+ joserfc/_rfc7797/util.py,sha256=otwMWZk640xD2XTXZfJOb7J53GjVLE0oTRyU_Uleu3I,428
45
+ joserfc/_rfc8037/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
46
+ joserfc/_rfc8037/jws_eddsa.py,sha256=GCQFjhS3cH8o3ooZboLpewHT8dCA34Rz4cnyQLnH1Hc,1350
47
+ joserfc/_rfc8037/okp_key.py,sha256=W6P1WNrv9tcMiERffsLhXj4067WepoQ7GexmL4OGtRk,11436
48
+ joserfc/_rfc8812/__init__.py,sha256=5w3IpVAqUiXa74guNrRK4knyHAA95sRkdDridESvf8c,389
49
+ joserfc/_rfc9278/__init__.py,sha256=pK3qp2WL1nWwB9jwWq-64iROCHWjL1TeRjYFqE_9f5E,974
50
+ joserfc/_rfc9864/__init__.py,sha256=ixUdjXB5vFaMypU1SHvDFlUGkgA8I5aFgUsLZ5ibbfE,120
51
+ joserfc/_rfc9864/jws_eddsa.py,sha256=jw0iIcaYP82_TbZVNsHP-BU70qbPgkS3U2vuB233qb8,1451
52
+ joserfc/drafts/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
53
+ joserfc/drafts/jwe_chacha20.py,sha256=agENvT8XSlbZ9N8grF2u4YOxCeuIOocHXKjSX-kEW5w,1475
54
+ joserfc/drafts/jwe_ecdh_1pu.py,sha256=HiSZ9a49apKZYI980wcDkBE866TaQM5x3_oX_1Xn4og,5084
55
+ joserfc/errors.py,sha256=f9BgE8cYOP8xvOasp5y-kHx5vBVeOD_NAU-3w3K33Ps,6051
56
+ joserfc/jwa.py,sha256=h-BAKxRzf4enessvwcepDa9xxGXqEG6TCsIpxLUi8VY,2287
57
+ joserfc/jwe.py,sha256=2OLsbJrIsbmdVsQ6Fsbym7xI7etPvUqJ-jrTBHBlYfo,9960
58
+ joserfc/jwk.py,sha256=VI-_C3daJtthraOP6fueUsxirdFjCDh-VW03PGT_wwA,6470
59
+ joserfc/jws.py,sha256=4u8V9zwa4yurCDz8mwL7LIL-z5QFJLuUJ3MWSoJkjQo,10878
60
+ joserfc/jwt.py,sha256=4g-5SOh-e9Z6byXAuSqI8BA94KDD_QxVHvaz9Yb_e9E,4060
61
+ joserfc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
62
+ joserfc/registry.py,sha256=KO8KgexGeaqnOk2ZfJAF-G5T7CkosN4Q3OrEMy7VqcQ,7541
63
+ joserfc/util.py,sha256=fg0mtv0RQLbRiDWt-8Rc_bw8Qg592-TCkXuMYNr4fsg,1907
.venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/REQUESTED ADDED
File without changes
.venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
.venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2023, Hsiaoming Yang
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
.venv/lib/python3.10/site-packages/joserfc-1.6.4.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ joserfc
.venv/lib/python3.10/site-packages/sympy/__init__.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SymPy is a Python library for symbolic mathematics. It aims to become a
3
+ full-featured computer algebra system (CAS) while keeping the code as simple
4
+ as possible in order to be comprehensible and easily extensible. SymPy is
5
+ written entirely in Python. It depends on mpmath, and other external libraries
6
+ may be optionally for things like plotting support.
7
+
8
+ See the webpage for more information and documentation:
9
+
10
+ https://sympy.org
11
+
12
+ """
13
+
14
+
15
+ # Keep this in sync with setup.py/pyproject.toml
16
+ import sys
17
+ if sys.version_info < (3, 9):
18
+ raise ImportError("Python version 3.9 or above is required for SymPy.")
19
+ del sys
20
+
21
+
22
+ try:
23
+ import mpmath
24
+ except ImportError:
25
+ raise ImportError("SymPy now depends on mpmath as an external library. "
26
+ "See https://docs.sympy.org/latest/install.html#mpmath for more information.")
27
+
28
+ del mpmath
29
+
30
+ from sympy.release import __version__
31
+ from sympy.core.cache import lazy_function
32
+
33
+ if 'dev' in __version__:
34
+ def enable_warnings():
35
+ import warnings
36
+ warnings.filterwarnings('default', '.*', DeprecationWarning, module='sympy.*')
37
+ del warnings
38
+ enable_warnings()
39
+ del enable_warnings
40
+
41
+
42
+ def __sympy_debug():
43
+ # helper function so we don't import os globally
44
+ import os
45
+ debug_str = os.getenv('SYMPY_DEBUG', 'False')
46
+ if debug_str in ('True', 'False'):
47
+ return eval(debug_str)
48
+ else:
49
+ raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" %
50
+ debug_str)
51
+ # Fails py2 test if using type hinting
52
+ SYMPY_DEBUG = __sympy_debug() # type: bool
53
+
54
+
55
+ from .core import (sympify, SympifyError, cacheit, Basic, Atom,
56
+ preorder_traversal, S, Expr, AtomicExpr, UnevaluatedExpr, Symbol,
57
+ Wild, Dummy, symbols, var, Number, Float, Rational, Integer,
58
+ NumberSymbol, RealNumber, igcd, ilcm, seterr, E, I, nan, oo, pi, zoo,
59
+ AlgebraicNumber, comp, mod_inverse, Pow, integer_nthroot, integer_log,
60
+ trailing, Mul, prod, Add, Mod, Rel, Eq, Ne, Lt, Le, Gt, Ge, Equality,
61
+ GreaterThan, LessThan, Unequality, StrictGreaterThan, StrictLessThan,
62
+ vectorize, Lambda, WildFunction, Derivative, diff, FunctionClass,
63
+ Function, Subs, expand, PoleError, count_ops, expand_mul, expand_log,
64
+ expand_func, expand_trig, expand_complex, expand_multinomial, nfloat,
65
+ expand_power_base, expand_power_exp, arity, PrecisionExhausted, N,
66
+ evalf, Tuple, Dict, gcd_terms, factor_terms, factor_nc, evaluate,
67
+ Catalan, EulerGamma, GoldenRatio, TribonacciConstant, bottom_up, use,
68
+ postorder_traversal, default_sort_key, ordered, num_digits)
69
+
70
+ from .logic import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor,
71
+ Implies, Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map,
72
+ true, false, satisfiable)
73
+
74
+ from .assumptions import (AppliedPredicate, Predicate, AssumptionsContext,
75
+ assuming, Q, ask, register_handler, remove_handler, refine)
76
+
77
+ from .polys import (Poly, PurePoly, poly_from_expr, parallel_poly_from_expr,
78
+ degree, total_degree, degree_list, LC, LM, LT, pdiv, prem, pquo,
79
+ pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert,
80
+ subresultants, resultant, discriminant, cofactors, gcd_list, gcd,
81
+ lcm_list, lcm, terms_gcd, trunc, monic, content, primitive, compose,
82
+ decompose, sturm, gff_list, gff, sqf_norm, sqf_part, sqf_list, sqf,
83
+ factor_list, factor, intervals, refine_root, count_roots, all_roots,
84
+ real_roots, nroots, ground_roots, nth_power_roots_poly, cancel,
85
+ reduced, groebner, is_zero_dimensional, GroebnerBasis, poly,
86
+ symmetrize, horner, interpolate, rational_interpolate, viete, together,
87
+ BasePolynomialError, ExactQuotientFailed, PolynomialDivisionFailed,
88
+ OperationNotSupported, HeuristicGCDFailed, HomomorphismFailed,
89
+ IsomorphismFailed, ExtraneousFactors, EvaluationFailed,
90
+ RefinementFailed, CoercionFailed, NotInvertible, NotReversible,
91
+ NotAlgebraic, DomainError, PolynomialError, UnificationFailed,
92
+ GeneratorsError, GeneratorsNeeded, ComputationFailed,
93
+ UnivariatePolynomialError, MultivariatePolynomialError,
94
+ PolificationFailed, OptionError, FlagError, minpoly,
95
+ minimal_polynomial, primitive_element, field_isomorphism,
96
+ to_number_field, isolate, round_two, prime_decomp, prime_valuation,
97
+ galois_group, itermonomials, Monomial, lex, grlex,
98
+ grevlex, ilex, igrlex, igrevlex, CRootOf, rootof, RootOf,
99
+ ComplexRootOf, RootSum, roots, Domain, FiniteField, IntegerRing,
100
+ RationalField, RealField, ComplexField, PythonFiniteField,
101
+ GMPYFiniteField, PythonIntegerRing, GMPYIntegerRing, PythonRational,
102
+ GMPYRationalField, AlgebraicField, PolynomialRing, FractionField,
103
+ ExpressionDomain, FF_python, FF_gmpy, ZZ_python, ZZ_gmpy, QQ_python,
104
+ QQ_gmpy, GF, FF, ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX, EXRAW,
105
+ construct_domain, swinnerton_dyer_poly, cyclotomic_poly,
106
+ symmetric_poly, random_poly, interpolating_poly, jacobi_poly,
107
+ chebyshevt_poly, chebyshevu_poly, hermite_poly, hermite_prob_poly,
108
+ legendre_poly, laguerre_poly, apart, apart_list, assemble_partfrac_list,
109
+ Options, ring, xring, vring, sring, field, xfield, vfield, sfield)
110
+
111
+ from .series import (Order, O, limit, Limit, gruntz, series, approximants,
112
+ residue, EmptySequence, SeqPer, SeqFormula, sequence, SeqAdd, SeqMul,
113
+ fourier_series, fps, difference_delta, limit_seq)
114
+
115
+ from .functions import (factorial, factorial2, rf, ff, binomial,
116
+ RisingFactorial, FallingFactorial, subfactorial, carmichael,
117
+ fibonacci, lucas, motzkin, tribonacci, harmonic, bernoulli, bell, euler,
118
+ catalan, genocchi, andre, partition, divisor_sigma, legendre_symbol,
119
+ jacobi_symbol, kronecker_symbol, mobius, primenu, primeomega,
120
+ totient, reduced_totient, primepi, sqrt, root, Min, Max, Id,
121
+ real_root, Rem, cbrt, re, im, sign, Abs, conjugate, arg, polar_lift,
122
+ periodic_argument, unbranched_argument, principal_branch, transpose,
123
+ adjoint, polarify, unpolarify, sin, cos, tan, sec, csc, cot, sinc,
124
+ asin, acos, atan, asec, acsc, acot, atan2, exp_polar, exp, ln, log,
125
+ LambertW, sinh, cosh, tanh, coth, sech, csch, asinh, acosh, atanh,
126
+ acoth, asech, acsch, floor, ceiling, frac, Piecewise, piecewise_fold,
127
+ piecewise_exclusive, erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv,
128
+ Ei, expint, E1, li, Li, Si, Ci, Shi, Chi, fresnels, fresnelc, gamma,
129
+ lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma,
130
+ multigamma, dirichlet_eta, zeta, lerchphi, polylog, stieltjes, Eijk,
131
+ LeviCivita, KroneckerDelta, SingularityFunction, DiracDelta, Heaviside,
132
+ bspline_basis, bspline_basis_set, interpolating_spline, besselj,
133
+ bessely, besseli, besselk, hankel1, hankel2, jn, yn, jn_zeros, hn1,
134
+ hn2, airyai, airybi, airyaiprime, airybiprime, marcumq, hyper,
135
+ meijerg, appellf1, legendre, assoc_legendre, hermite, hermite_prob,
136
+ chebyshevt, chebyshevu, chebyshevu_root, chebyshevt_root, laguerre,
137
+ assoc_laguerre, gegenbauer, jacobi, jacobi_normalized, Ynm, Ynm_c,
138
+ Znm, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, beta, mathieus,
139
+ mathieuc, mathieusprime, mathieucprime, riemann_xi, betainc, betainc_regularized)
140
+
141
+ from .ntheory import (nextprime, prevprime, prime, primerange,
142
+ randprime, Sieve, sieve, primorial, cycle_length, composite,
143
+ compositepi, isprime, divisors, proper_divisors, factorint,
144
+ multiplicity, perfect_power, factor_cache, pollard_pm1, pollard_rho, primefactors,
145
+ divisor_count, proper_divisor_count,
146
+ factorrat,
147
+ mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant,
148
+ is_deficient, is_amicable, is_carmichael, abundance, npartitions, is_primitive_root,
149
+ is_quad_residue, n_order, sqrt_mod,
150
+ quadratic_residues, primitive_root, nthroot_mod, is_nthpow_residue,
151
+ sqrt_mod_iter, discrete_log, quadratic_congruence,
152
+ binomial_coefficients, binomial_coefficients_list,
153
+ multinomial_coefficients, continued_fraction_periodic,
154
+ continued_fraction_iterator, continued_fraction_reduce,
155
+ continued_fraction_convergents, continued_fraction, egyptian_fraction)
156
+
157
+ from .concrete import product, Product, summation, Sum
158
+
159
+ from .discrete import (fft, ifft, ntt, intt, fwht, ifwht, mobius_transform,
160
+ inverse_mobius_transform, convolution, covering_product,
161
+ intersecting_product)
162
+
163
+ from .simplify import (simplify, hypersimp, hypersimilar, logcombine,
164
+ separatevars, posify, besselsimp, kroneckersimp, signsimp,
165
+ nsimplify, FU, fu, sqrtdenest, cse, epath, EPath, hyperexpand,
166
+ collect, rcollect, radsimp, collect_const, fraction, numer, denom,
167
+ trigsimp, exptrigsimp, powsimp, powdenest, combsimp, gammasimp,
168
+ ratsimp, ratsimpmodprime)
169
+
170
+ from .sets import (Set, Interval, Union, EmptySet, FiniteSet, ProductSet,
171
+ Intersection, DisjointUnion, imageset, Complement, SymmetricDifference, ImageSet,
172
+ Range, ComplexRegion, Complexes, Reals, Contains, ConditionSet, Ordinal,
173
+ OmegaPower, ord0, PowerSet, Naturals, Naturals0, UniversalSet,
174
+ Integers, Rationals)
175
+
176
+ from .solvers import (solve, solve_linear_system, solve_linear_system_LU,
177
+ solve_undetermined_coeffs, nsolve, solve_linear, checksol, det_quick,
178
+ inv_quick, check_assumptions, failing_assumptions, diophantine,
179
+ rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper, checkodesol,
180
+ classify_ode, dsolve, homogeneous_order, solve_poly_system, factor_system,
181
+ solve_triangulated, pde_separate, pde_separate_add, pde_separate_mul,
182
+ pdsolve, classify_pde, checkpdesol, ode_order, reduce_inequalities,
183
+ reduce_abs_inequality, reduce_abs_inequalities, solve_poly_inequality,
184
+ solve_rational_inequalities, solve_univariate_inequality, decompogen,
185
+ solveset, linsolve, linear_eq_to_matrix, nonlinsolve, substitution)
186
+
187
+ from .matrices import (ShapeError, NonSquareMatrixError, GramSchmidt,
188
+ casoratian, diag, eye, hessian, jordan_cell, list2numpy, matrix2numpy,
189
+ matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2,
190
+ rot_axis3, symarray, wronskian, zeros, MutableDenseMatrix,
191
+ DeferredVector, MatrixBase, Matrix, MutableMatrix,
192
+ MutableSparseMatrix, banded, ImmutableDenseMatrix,
193
+ ImmutableSparseMatrix, ImmutableMatrix, SparseMatrix, MatrixSlice,
194
+ BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity, Inverse,
195
+ MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace, Transpose,
196
+ ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols,
197
+ Adjoint, hadamard_product, HadamardProduct, HadamardPower,
198
+ Determinant, det, diagonalize_vector, DiagMatrix, DiagonalMatrix,
199
+ DiagonalOf, trace, DotProduct, kronecker_product, KroneckerProduct,
200
+ PermutationMatrix, MatrixPermute, Permanent, per, rot_ccw_axis1,
201
+ rot_ccw_axis2, rot_ccw_axis3, rot_givens)
202
+
203
+ from .geometry import (Point, Point2D, Point3D, Line, Ray, Segment, Line2D,
204
+ Segment2D, Ray2D, Line3D, Segment3D, Ray3D, Plane, Ellipse, Circle,
205
+ Polygon, RegularPolygon, Triangle, rad, deg, are_similar, centroid,
206
+ convex_hull, idiff, intersection, closest_points, farthest_points,
207
+ GeometryError, Curve, Parabola)
208
+
209
+ from .utilities import (flatten, group, take, subsets, variations,
210
+ numbered_symbols, cartes, capture, dict_merge, prefixes, postfixes,
211
+ sift, topological_sort, unflatten, has_dups, has_variety, reshape,
212
+ rotations, filldedent, lambdify,
213
+ threaded, xthreaded, public, memoize_property, timed)
214
+
215
+ from .integrals import (integrate, Integral, line_integrate, mellin_transform,
216
+ inverse_mellin_transform, MellinTransform, InverseMellinTransform,
217
+ laplace_transform, laplace_correspondence, laplace_initial_conds,
218
+ inverse_laplace_transform, LaplaceTransform,
219
+ InverseLaplaceTransform, fourier_transform, inverse_fourier_transform,
220
+ FourierTransform, InverseFourierTransform, sine_transform,
221
+ inverse_sine_transform, SineTransform, InverseSineTransform,
222
+ cosine_transform, inverse_cosine_transform, CosineTransform,
223
+ InverseCosineTransform, hankel_transform, inverse_hankel_transform,
224
+ HankelTransform, InverseHankelTransform, singularityintegrate)
225
+
226
+ from .tensor import (IndexedBase, Idx, Indexed, get_contraction_structure,
227
+ get_indices, shape, MutableDenseNDimArray, ImmutableDenseNDimArray,
228
+ MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray,
229
+ tensorproduct, tensorcontraction, tensordiagonal, derive_by_array,
230
+ permutedims, Array, DenseNDimArray, SparseNDimArray)
231
+
232
+ from .parsing import parse_expr
233
+
234
+ from .calculus import (euler_equations, singularities, is_increasing,
235
+ is_strictly_increasing, is_decreasing, is_strictly_decreasing,
236
+ is_monotonic, finite_diff_weights, apply_finite_diff,
237
+ differentiate_finite, periodicity, not_empty_in, AccumBounds,
238
+ is_convex, stationary_points, minimum, maximum)
239
+
240
+ from .algebras import Quaternion
241
+
242
+ from .printing import (pager_print, pretty, pretty_print, pprint,
243
+ pprint_use_unicode, pprint_try_use_unicode, latex, print_latex,
244
+ multiline_latex, mathml, print_mathml, python, print_python, pycode,
245
+ ccode, print_ccode, smtlib_code, glsl_code, print_glsl, cxxcode, fcode,
246
+ print_fcode, rcode, print_rcode, jscode, print_jscode, julia_code,
247
+ mathematica_code, octave_code, rust_code, print_gtk, preview, srepr,
248
+ print_tree, StrPrinter, sstr, sstrrepr, TableForm, dotprint,
249
+ maple_code, print_maple_code)
250
+
251
+ test = lazy_function('sympy.testing.runtests_pytest', 'test')
252
+ doctest = lazy_function('sympy.testing.runtests', 'doctest')
253
+
254
+ # This module causes conflicts with other modules:
255
+ # from .stats import *
256
+ # Adds about .04-.05 seconds of import time
257
+ # from combinatorics import *
258
+ # This module is slow to import:
259
+ #from physics import units
260
+ from .plotting import plot, textplot, plot_backends, plot_implicit, plot_parametric
261
+ from .interactive import init_session, init_printing, interactive_traversal
262
+
263
+ evalf._create_evalf_table()
264
+
265
+ __all__ = [
266
+ '__version__',
267
+
268
+ # sympy.core
269
+ 'sympify', 'SympifyError', 'cacheit', 'Basic', 'Atom',
270
+ 'preorder_traversal', 'S', 'Expr', 'AtomicExpr', 'UnevaluatedExpr',
271
+ 'Symbol', 'Wild', 'Dummy', 'symbols', 'var', 'Number', 'Float',
272
+ 'Rational', 'Integer', 'NumberSymbol', 'RealNumber', 'igcd', 'ilcm',
273
+ 'seterr', 'E', 'I', 'nan', 'oo', 'pi', 'zoo', 'AlgebraicNumber', 'comp',
274
+ 'mod_inverse', 'Pow', 'integer_nthroot', 'integer_log', 'trailing', 'Mul', 'prod',
275
+ 'Add', 'Mod', 'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge', 'Equality',
276
+ 'GreaterThan', 'LessThan', 'Unequality', 'StrictGreaterThan',
277
+ 'StrictLessThan', 'vectorize', 'Lambda', 'WildFunction', 'Derivative',
278
+ 'diff', 'FunctionClass', 'Function', 'Subs', 'expand', 'PoleError',
279
+ 'count_ops', 'expand_mul', 'expand_log', 'expand_func', 'expand_trig',
280
+ 'expand_complex', 'expand_multinomial', 'nfloat', 'expand_power_base',
281
+ 'expand_power_exp', 'arity', 'PrecisionExhausted', 'N', 'evalf', 'Tuple',
282
+ 'Dict', 'gcd_terms', 'factor_terms', 'factor_nc', 'evaluate', 'Catalan',
283
+ 'EulerGamma', 'GoldenRatio', 'TribonacciConstant', 'bottom_up', 'use',
284
+ 'postorder_traversal', 'default_sort_key', 'ordered', 'num_digits',
285
+
286
+ # sympy.logic
287
+ 'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor',
288
+ 'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic',
289
+ 'bool_map', 'true', 'false', 'satisfiable',
290
+
291
+ # sympy.assumptions
292
+ 'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming', 'Q',
293
+ 'ask', 'register_handler', 'remove_handler', 'refine',
294
+
295
+ # sympy.polys
296
+ 'Poly', 'PurePoly', 'poly_from_expr', 'parallel_poly_from_expr', 'degree',
297
+ 'total_degree', 'degree_list', 'LC', 'LM', 'LT', 'pdiv', 'prem', 'pquo',
298
+ 'pexquo', 'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex', 'invert',
299
+ 'subresultants', 'resultant', 'discriminant', 'cofactors', 'gcd_list',
300
+ 'gcd', 'lcm_list', 'lcm', 'terms_gcd', 'trunc', 'monic', 'content',
301
+ 'primitive', 'compose', 'decompose', 'sturm', 'gff_list', 'gff',
302
+ 'sqf_norm', 'sqf_part', 'sqf_list', 'sqf', 'factor_list', 'factor',
303
+ 'intervals', 'refine_root', 'count_roots', 'all_roots', 'real_roots',
304
+ 'nroots', 'ground_roots', 'nth_power_roots_poly', 'cancel', 'reduced',
305
+ 'groebner', 'is_zero_dimensional', 'GroebnerBasis', 'poly', 'symmetrize',
306
+ 'horner', 'interpolate', 'rational_interpolate', 'viete', 'together',
307
+ 'BasePolynomialError', 'ExactQuotientFailed', 'PolynomialDivisionFailed',
308
+ 'OperationNotSupported', 'HeuristicGCDFailed', 'HomomorphismFailed',
309
+ 'IsomorphismFailed', 'ExtraneousFactors', 'EvaluationFailed',
310
+ 'RefinementFailed', 'CoercionFailed', 'NotInvertible', 'NotReversible',
311
+ 'NotAlgebraic', 'DomainError', 'PolynomialError', 'UnificationFailed',
312
+ 'GeneratorsError', 'GeneratorsNeeded', 'ComputationFailed',
313
+ 'UnivariatePolynomialError', 'MultivariatePolynomialError',
314
+ 'PolificationFailed', 'OptionError', 'FlagError', 'minpoly',
315
+ 'minimal_polynomial', 'primitive_element', 'field_isomorphism',
316
+ 'to_number_field', 'isolate', 'round_two', 'prime_decomp',
317
+ 'prime_valuation', 'galois_group', 'itermonomials', 'Monomial', 'lex', 'grlex',
318
+ 'grevlex', 'ilex', 'igrlex', 'igrevlex', 'CRootOf', 'rootof', 'RootOf',
319
+ 'ComplexRootOf', 'RootSum', 'roots', 'Domain', 'FiniteField',
320
+ 'IntegerRing', 'RationalField', 'RealField', 'ComplexField',
321
+ 'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing',
322
+ 'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField',
323
+ 'AlgebraicField', 'PolynomialRing', 'FractionField', 'ExpressionDomain',
324
+ 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy',
325
+ 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'EXRAW',
326
+ 'construct_domain', 'swinnerton_dyer_poly', 'cyclotomic_poly',
327
+ 'symmetric_poly', 'random_poly', 'interpolating_poly', 'jacobi_poly',
328
+ 'chebyshevt_poly', 'chebyshevu_poly', 'hermite_poly', 'hermite_prob_poly',
329
+ 'legendre_poly', 'laguerre_poly', 'apart', 'apart_list', 'assemble_partfrac_list',
330
+ 'Options', 'ring', 'xring', 'vring', 'sring', 'field', 'xfield', 'vfield',
331
+ 'sfield',
332
+
333
+ # sympy.series
334
+ 'Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants',
335
+ 'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence', 'SeqAdd',
336
+ 'SeqMul', 'fourier_series', 'fps', 'difference_delta', 'limit_seq',
337
+
338
+ # sympy.functions
339
+ 'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial',
340
+ 'FallingFactorial', 'subfactorial', 'carmichael', 'fibonacci', 'lucas',
341
+ 'motzkin', 'tribonacci', 'harmonic', 'bernoulli', 'bell', 'euler', 'catalan',
342
+ 'genocchi', 'andre', 'partition', 'divisor_sigma', 'legendre_symbol', 'jacobi_symbol',
343
+ 'kronecker_symbol', 'mobius', 'primenu', 'primeomega', 'totient', 'primepi',
344
+ 'reduced_totient', 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root',
345
+ 'Rem', 'cbrt', 're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift',
346
+ 'periodic_argument', 'unbranched_argument', 'principal_branch',
347
+ 'transpose', 'adjoint', 'polarify', 'unpolarify', 'sin', 'cos', 'tan',
348
+ 'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan', 'asec', 'acsc',
349
+ 'acot', 'atan2', 'exp_polar', 'exp', 'ln', 'log', 'LambertW', 'sinh',
350
+ 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh',
351
+ 'acoth', 'asech', 'acsch', 'floor', 'ceiling', 'frac', 'Piecewise',
352
+ 'piecewise_fold', 'piecewise_exclusive', 'erf', 'erfc', 'erfi', 'erf2',
353
+ 'erfinv', 'erfcinv', 'erf2inv', 'Ei', 'expint', 'E1', 'li', 'Li', 'Si',
354
+ 'Ci', 'Shi', 'Chi', 'fresnels', 'fresnelc', 'gamma', 'lowergamma',
355
+ 'uppergamma', 'polygamma', 'loggamma', 'digamma', 'trigamma', 'multigamma',
356
+ 'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'Eijk', 'LeviCivita',
357
+ 'KroneckerDelta', 'SingularityFunction', 'DiracDelta', 'Heaviside',
358
+ 'bspline_basis', 'bspline_basis_set', 'interpolating_spline', 'besselj',
359
+ 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn', 'yn',
360
+ 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime',
361
+ 'airybiprime', 'marcumq', 'hyper', 'meijerg', 'appellf1', 'legendre',
362
+ 'assoc_legendre', 'hermite', 'hermite_prob', 'chebyshevt', 'chebyshevu',
363
+ 'chebyshevu_root', 'chebyshevt_root', 'laguerre', 'assoc_laguerre',
364
+ 'gegenbauer', 'jacobi', 'jacobi_normalized', 'Ynm', 'Ynm_c', 'Znm',
365
+ 'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi', 'beta',
366
+ 'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime', 'riemann_xi','betainc',
367
+ 'betainc_regularized',
368
+
369
+ # sympy.ntheory
370
+ 'nextprime', 'prevprime', 'prime', 'primerange', 'randprime',
371
+ 'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi',
372
+ 'isprime', 'divisors', 'proper_divisors', 'factorint', 'multiplicity',
373
+ 'perfect_power', 'pollard_pm1', 'factor_cache', 'pollard_rho', 'primefactors',
374
+ 'divisor_count', 'proper_divisor_count',
375
+ 'factorrat',
376
+ 'mersenne_prime_exponent', 'is_perfect', 'is_mersenne_prime',
377
+ 'is_abundant', 'is_deficient', 'is_amicable', 'is_carmichael', 'abundance',
378
+ 'npartitions',
379
+ 'is_primitive_root', 'is_quad_residue',
380
+ 'n_order', 'sqrt_mod', 'quadratic_residues',
381
+ 'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter',
382
+ 'discrete_log', 'quadratic_congruence', 'binomial_coefficients',
383
+ 'binomial_coefficients_list', 'multinomial_coefficients',
384
+ 'continued_fraction_periodic', 'continued_fraction_iterator',
385
+ 'continued_fraction_reduce', 'continued_fraction_convergents',
386
+ 'continued_fraction', 'egyptian_fraction',
387
+
388
+ # sympy.concrete
389
+ 'product', 'Product', 'summation', 'Sum',
390
+
391
+ # sympy.discrete
392
+ 'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform',
393
+ 'inverse_mobius_transform', 'convolution', 'covering_product',
394
+ 'intersecting_product',
395
+
396
+ # sympy.simplify
397
+ 'simplify', 'hypersimp', 'hypersimilar', 'logcombine', 'separatevars',
398
+ 'posify', 'besselsimp', 'kroneckersimp', 'signsimp',
399
+ 'nsimplify', 'FU', 'fu', 'sqrtdenest', 'cse', 'epath', 'EPath',
400
+ 'hyperexpand', 'collect', 'rcollect', 'radsimp', 'collect_const',
401
+ 'fraction', 'numer', 'denom', 'trigsimp', 'exptrigsimp', 'powsimp',
402
+ 'powdenest', 'combsimp', 'gammasimp', 'ratsimp', 'ratsimpmodprime',
403
+
404
+ # sympy.sets
405
+ 'Set', 'Interval', 'Union', 'EmptySet', 'FiniteSet', 'ProductSet',
406
+ 'Intersection', 'imageset', 'DisjointUnion', 'Complement', 'SymmetricDifference',
407
+ 'ImageSet', 'Range', 'ComplexRegion', 'Reals', 'Contains', 'ConditionSet',
408
+ 'Ordinal', 'OmegaPower', 'ord0', 'PowerSet', 'Naturals',
409
+ 'Naturals0', 'UniversalSet', 'Integers', 'Rationals', 'Complexes',
410
+
411
+ # sympy.solvers
412
+ 'solve', 'solve_linear_system', 'solve_linear_system_LU',
413
+ 'solve_undetermined_coeffs', 'nsolve', 'solve_linear', 'checksol',
414
+ 'det_quick', 'inv_quick', 'check_assumptions', 'failing_assumptions',
415
+ 'diophantine', 'rsolve', 'rsolve_poly', 'rsolve_ratio', 'rsolve_hyper',
416
+ 'checkodesol', 'classify_ode', 'dsolve', 'homogeneous_order',
417
+ 'solve_poly_system', 'factor_system', 'solve_triangulated', 'pde_separate',
418
+ 'pde_separate_add', 'pde_separate_mul', 'pdsolve', 'classify_pde',
419
+ 'checkpdesol', 'ode_order', 'reduce_inequalities',
420
+ 'reduce_abs_inequality', 'reduce_abs_inequalities',
421
+ 'solve_poly_inequality', 'solve_rational_inequalities',
422
+ 'solve_univariate_inequality', 'decompogen', 'solveset', 'linsolve',
423
+ 'linear_eq_to_matrix', 'nonlinsolve', 'substitution',
424
+
425
+ # sympy.matrices
426
+ 'ShapeError', 'NonSquareMatrixError', 'GramSchmidt', 'casoratian', 'diag',
427
+ 'eye', 'hessian', 'jordan_cell', 'list2numpy', 'matrix2numpy',
428
+ 'matrix_multiply_elementwise', 'ones', 'randMatrix', 'rot_axis1',
429
+ 'rot_axis2', 'rot_axis3', 'symarray', 'wronskian', 'zeros',
430
+ 'MutableDenseMatrix', 'DeferredVector', 'MatrixBase', 'Matrix',
431
+ 'MutableMatrix', 'MutableSparseMatrix', 'banded', 'ImmutableDenseMatrix',
432
+ 'ImmutableSparseMatrix', 'ImmutableMatrix', 'SparseMatrix', 'MatrixSlice',
433
+ 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix', 'Identity', 'Inverse',
434
+ 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr', 'MatrixSymbol', 'Trace',
435
+ 'Transpose', 'ZeroMatrix', 'OneMatrix', 'blockcut', 'block_collapse',
436
+ 'matrix_symbols', 'Adjoint', 'hadamard_product', 'HadamardProduct',
437
+ 'HadamardPower', 'Determinant', 'det', 'diagonalize_vector', 'DiagMatrix',
438
+ 'DiagonalMatrix', 'DiagonalOf', 'trace', 'DotProduct',
439
+ 'kronecker_product', 'KroneckerProduct', 'PermutationMatrix',
440
+ 'MatrixPermute', 'Permanent', 'per', 'rot_ccw_axis1', 'rot_ccw_axis2',
441
+ 'rot_ccw_axis3', 'rot_givens',
442
+
443
+ # sympy.geometry
444
+ 'Point', 'Point2D', 'Point3D', 'Line', 'Ray', 'Segment', 'Line2D',
445
+ 'Segment2D', 'Ray2D', 'Line3D', 'Segment3D', 'Ray3D', 'Plane', 'Ellipse',
446
+ 'Circle', 'Polygon', 'RegularPolygon', 'Triangle', 'rad', 'deg',
447
+ 'are_similar', 'centroid', 'convex_hull', 'idiff', 'intersection',
448
+ 'closest_points', 'farthest_points', 'GeometryError', 'Curve', 'Parabola',
449
+
450
+ # sympy.utilities
451
+ 'flatten', 'group', 'take', 'subsets', 'variations', 'numbered_symbols',
452
+ 'cartes', 'capture', 'dict_merge', 'prefixes', 'postfixes', 'sift',
453
+ 'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape',
454
+ 'rotations', 'filldedent', 'lambdify', 'threaded', 'xthreaded',
455
+ 'public', 'memoize_property', 'timed',
456
+
457
+ # sympy.integrals
458
+ 'integrate', 'Integral', 'line_integrate', 'mellin_transform',
459
+ 'inverse_mellin_transform', 'MellinTransform', 'InverseMellinTransform',
460
+ 'laplace_transform', 'inverse_laplace_transform', 'LaplaceTransform',
461
+ 'laplace_correspondence', 'laplace_initial_conds',
462
+ 'InverseLaplaceTransform', 'fourier_transform',
463
+ 'inverse_fourier_transform', 'FourierTransform',
464
+ 'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform',
465
+ 'SineTransform', 'InverseSineTransform', 'cosine_transform',
466
+ 'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform',
467
+ 'hankel_transform', 'inverse_hankel_transform', 'HankelTransform',
468
+ 'InverseHankelTransform', 'singularityintegrate',
469
+
470
+ # sympy.tensor
471
+ 'IndexedBase', 'Idx', 'Indexed', 'get_contraction_structure',
472
+ 'get_indices', 'shape', 'MutableDenseNDimArray', 'ImmutableDenseNDimArray',
473
+ 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray',
474
+ 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array',
475
+ 'permutedims', 'Array', 'DenseNDimArray', 'SparseNDimArray',
476
+
477
+ # sympy.parsing
478
+ 'parse_expr',
479
+
480
+ # sympy.calculus
481
+ 'euler_equations', 'singularities', 'is_increasing',
482
+ 'is_strictly_increasing', 'is_decreasing', 'is_strictly_decreasing',
483
+ 'is_monotonic', 'finite_diff_weights', 'apply_finite_diff',
484
+ 'differentiate_finite', 'periodicity', 'not_empty_in',
485
+ 'AccumBounds', 'is_convex', 'stationary_points', 'minimum', 'maximum',
486
+
487
+ # sympy.algebras
488
+ 'Quaternion',
489
+
490
+ # sympy.printing
491
+ 'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode',
492
+ 'pprint_try_use_unicode', 'latex', 'print_latex', 'multiline_latex',
493
+ 'mathml', 'print_mathml', 'python', 'print_python', 'pycode', 'ccode',
494
+ 'print_ccode', 'smtlib_code', 'glsl_code', 'print_glsl', 'cxxcode', 'fcode',
495
+ 'print_fcode', 'rcode', 'print_rcode', 'jscode', 'print_jscode',
496
+ 'julia_code', 'mathematica_code', 'octave_code', 'rust_code', 'print_gtk',
497
+ 'preview', 'srepr', 'print_tree', 'StrPrinter', 'sstr', 'sstrrepr',
498
+ 'TableForm', 'dotprint', 'maple_code', 'print_maple_code',
499
+
500
+ # sympy.plotting
501
+ 'plot', 'textplot', 'plot_backends', 'plot_implicit', 'plot_parametric',
502
+
503
+ # sympy.interactive
504
+ 'init_session', 'init_printing', 'interactive_traversal',
505
+
506
+ # sympy.testing
507
+ 'test', 'doctest',
508
+ ]
509
+
510
+
511
+ #===========================================================================#
512
+ # #
513
+ # XXX: The names below were importable before SymPy 1.6 using #
514
+ # #
515
+ # from sympy import * #
516
+ # #
517
+ # This happened implicitly because there was no __all__ defined in this #
518
+ # __init__.py file. Not every package is imported. The list matches what #
519
+ # would have been imported before. It is possible that these packages will #
520
+ # not be imported by a star-import from sympy in future. #
521
+ # #
522
+ #===========================================================================#
523
+
524
+
525
+ __all__.extend((
526
+ 'algebras',
527
+ 'assumptions',
528
+ 'calculus',
529
+ 'concrete',
530
+ 'discrete',
531
+ 'external',
532
+ 'functions',
533
+ 'geometry',
534
+ 'interactive',
535
+ 'multipledispatch',
536
+ 'ntheory',
537
+ 'parsing',
538
+ 'plotting',
539
+ 'polys',
540
+ 'printing',
541
+ 'release',
542
+ 'strategies',
543
+ 'tensor',
544
+ 'utilities',
545
+ ))
.venv/lib/python3.10/site-packages/sympy/abc.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module exports all latin and greek letters as Symbols, so you can
3
+ conveniently do
4
+
5
+ >>> from sympy.abc import x, y
6
+
7
+ instead of the slightly more clunky-looking
8
+
9
+ >>> from sympy import symbols
10
+ >>> x, y = symbols('x y')
11
+
12
+ Caveats
13
+ =======
14
+
15
+ 1. As of the time of writing this, the names ``O``, ``S``, ``I``, ``N``,
16
+ ``E``, and ``Q`` are colliding with names defined in SymPy. If you import them
17
+ from both ``sympy.abc`` and ``sympy``, the second import will "win".
18
+ This is an issue only for * imports, which should only be used for short-lived
19
+ code such as interactive sessions and throwaway scripts that do not survive
20
+ until the next SymPy upgrade, where ``sympy`` may contain a different set of
21
+ names.
22
+
23
+ 2. This module does not define symbol names on demand, i.e.
24
+ ``from sympy.abc import foo`` will be reported as an error because
25
+ ``sympy.abc`` does not contain the name ``foo``. To get a symbol named ``foo``,
26
+ you still need to use ``Symbol('foo')`` or ``symbols('foo')``.
27
+ You can freely mix usage of ``sympy.abc`` and ``Symbol``/``symbols``, though
28
+ sticking with one and only one way to get the symbols does tend to make the code
29
+ more readable.
30
+
31
+ The module also defines some special names to help detect which names clash
32
+ with the default SymPy namespace.
33
+
34
+ ``_clash1`` defines all the single letter variables that clash with
35
+ SymPy objects; ``_clash2`` defines the multi-letter clashing symbols;
36
+ and ``_clash`` is the union of both. These can be passed for ``locals``
37
+ during sympification if one desires Symbols rather than the non-Symbol
38
+ objects for those names.
39
+
40
+ Examples
41
+ ========
42
+
43
+ >>> from sympy import S
44
+ >>> from sympy.abc import _clash1, _clash2, _clash
45
+ >>> S("Q & C", locals=_clash1)
46
+ C & Q
47
+ >>> S('pi(x)', locals=_clash2)
48
+ pi(x)
49
+ >>> S('pi(C, Q)', locals=_clash)
50
+ pi(C, Q)
51
+
52
+ """
53
+ from __future__ import annotations
54
+ from typing import Any
55
+
56
+ import string
57
+
58
+ from .core import Symbol, symbols
59
+ from .core.alphabets import greeks
60
+ from sympy.parsing.sympy_parser import null
61
+
62
+ ##### Symbol definitions #####
63
+
64
+ # Implementation note: The easiest way to avoid typos in the symbols()
65
+ # parameter is to copy it from the left-hand side of the assignment.
66
+
67
+ a, b, c, d, e, f, g, h, i, j = symbols('a, b, c, d, e, f, g, h, i, j')
68
+ k, l, m, n, o, p, q, r, s, t = symbols('k, l, m, n, o, p, q, r, s, t')
69
+ u, v, w, x, y, z = symbols('u, v, w, x, y, z')
70
+
71
+ A, B, C, D, E, F, G, H, I, J = symbols('A, B, C, D, E, F, G, H, I, J')
72
+ K, L, M, N, O, P, Q, R, S, T = symbols('K, L, M, N, O, P, Q, R, S, T')
73
+ U, V, W, X, Y, Z = symbols('U, V, W, X, Y, Z')
74
+
75
+ alpha, beta, gamma, delta = symbols('alpha, beta, gamma, delta')
76
+ epsilon, zeta, eta, theta = symbols('epsilon, zeta, eta, theta')
77
+ iota, kappa, lamda, mu = symbols('iota, kappa, lamda, mu')
78
+ nu, xi, omicron, pi = symbols('nu, xi, omicron, pi')
79
+ rho, sigma, tau, upsilon = symbols('rho, sigma, tau, upsilon')
80
+ phi, chi, psi, omega = symbols('phi, chi, psi, omega')
81
+
82
+
83
+ ##### Clashing-symbols diagnostics #####
84
+
85
+ # We want to know which names in SymPy collide with those in here.
86
+ # This is mostly for diagnosing SymPy's namespace during SymPy development.
87
+
88
+ _latin = list(string.ascii_letters)
89
+ # QOSINE should not be imported as they clash; gamma, pi and zeta clash, too
90
+ _greek = list(greeks) # make a copy, so we can mutate it
91
+ # Note: We import lamda since lambda is a reserved keyword in Python
92
+ _greek.remove("lambda")
93
+ _greek.append("lamda")
94
+
95
+ ns: dict[str, Any] = {}
96
+ exec('from sympy import *', ns)
97
+ _clash1: dict[str, Any] = {}
98
+ _clash2: dict[str, Any] = {}
99
+ while ns:
100
+ _k, _ = ns.popitem()
101
+ if _k in _greek:
102
+ _clash2[_k] = null
103
+ _greek.remove(_k)
104
+ elif _k in _latin:
105
+ _clash1[_k] = null
106
+ _latin.remove(_k)
107
+ _clash = {}
108
+ _clash.update(_clash1)
109
+ _clash.update(_clash2)
110
+
111
+ del _latin, _greek, Symbol, _k, null
.venv/lib/python3.10/site-packages/sympy/assumptions/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A module to implement logical predicates and assumption system.
3
+ """
4
+
5
+ from .assume import (
6
+ AppliedPredicate, Predicate, AssumptionsContext, assuming,
7
+ global_assumptions
8
+ )
9
+ from .ask import Q, ask, register_handler, remove_handler
10
+ from .refine import refine
11
+ from .relation import BinaryRelation, AppliedBinaryRelation
12
+
13
+ __all__ = [
14
+ 'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming',
15
+ 'global_assumptions', 'Q', 'ask', 'register_handler', 'remove_handler',
16
+ 'refine',
17
+ 'BinaryRelation', 'AppliedBinaryRelation'
18
+ ]
.venv/lib/python3.10/site-packages/sympy/assumptions/ask.py ADDED
@@ -0,0 +1,651 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module for querying SymPy objects about assumptions."""
2
+
3
+ from sympy.assumptions.assume import (global_assumptions, Predicate,
4
+ AppliedPredicate)
5
+ from sympy.assumptions.cnf import CNF, EncodedCNF, Literal
6
+ from sympy.core import sympify
7
+ from sympy.core.kind import BooleanKind
8
+ from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le
9
+ from sympy.logic.inference import satisfiable
10
+ from sympy.utilities.decorator import memoize_property
11
+ from sympy.utilities.exceptions import (sympy_deprecation_warning,
12
+ SymPyDeprecationWarning,
13
+ ignore_warnings)
14
+
15
+
16
+ # Memoization is necessary for the properties of AssumptionKeys to
17
+ # ensure that only one object of Predicate objects are created.
18
+ # This is because assumption handlers are registered on those objects.
19
+
20
+
21
+ class AssumptionKeys:
22
+ """
23
+ This class contains all the supported keys by ``ask``.
24
+ It should be accessed via the instance ``sympy.Q``.
25
+
26
+ """
27
+
28
+ # DO NOT add methods or properties other than predicate keys.
29
+ # SAT solver checks the properties of Q and use them to compute the
30
+ # fact system. Non-predicate attributes will break this.
31
+
32
+ @memoize_property
33
+ def hermitian(self):
34
+ from .handlers.sets import HermitianPredicate
35
+ return HermitianPredicate()
36
+
37
+ @memoize_property
38
+ def antihermitian(self):
39
+ from .handlers.sets import AntihermitianPredicate
40
+ return AntihermitianPredicate()
41
+
42
+ @memoize_property
43
+ def real(self):
44
+ from .handlers.sets import RealPredicate
45
+ return RealPredicate()
46
+
47
+ @memoize_property
48
+ def extended_real(self):
49
+ from .handlers.sets import ExtendedRealPredicate
50
+ return ExtendedRealPredicate()
51
+
52
+ @memoize_property
53
+ def imaginary(self):
54
+ from .handlers.sets import ImaginaryPredicate
55
+ return ImaginaryPredicate()
56
+
57
+ @memoize_property
58
+ def complex(self):
59
+ from .handlers.sets import ComplexPredicate
60
+ return ComplexPredicate()
61
+
62
+ @memoize_property
63
+ def algebraic(self):
64
+ from .handlers.sets import AlgebraicPredicate
65
+ return AlgebraicPredicate()
66
+
67
+ @memoize_property
68
+ def transcendental(self):
69
+ from .predicates.sets import TranscendentalPredicate
70
+ return TranscendentalPredicate()
71
+
72
+ @memoize_property
73
+ def integer(self):
74
+ from .handlers.sets import IntegerPredicate
75
+ return IntegerPredicate()
76
+
77
+ @memoize_property
78
+ def noninteger(self):
79
+ from .predicates.sets import NonIntegerPredicate
80
+ return NonIntegerPredicate()
81
+
82
+ @memoize_property
83
+ def rational(self):
84
+ from .handlers.sets import RationalPredicate
85
+ return RationalPredicate()
86
+
87
+ @memoize_property
88
+ def irrational(self):
89
+ from .handlers.sets import IrrationalPredicate
90
+ return IrrationalPredicate()
91
+
92
+ @memoize_property
93
+ def finite(self):
94
+ from .handlers.calculus import FinitePredicate
95
+ return FinitePredicate()
96
+
97
+ @memoize_property
98
+ def infinite(self):
99
+ from .handlers.calculus import InfinitePredicate
100
+ return InfinitePredicate()
101
+
102
+ @memoize_property
103
+ def positive_infinite(self):
104
+ from .handlers.calculus import PositiveInfinitePredicate
105
+ return PositiveInfinitePredicate()
106
+
107
+ @memoize_property
108
+ def negative_infinite(self):
109
+ from .handlers.calculus import NegativeInfinitePredicate
110
+ return NegativeInfinitePredicate()
111
+
112
+ @memoize_property
113
+ def positive(self):
114
+ from .handlers.order import PositivePredicate
115
+ return PositivePredicate()
116
+
117
+ @memoize_property
118
+ def negative(self):
119
+ from .handlers.order import NegativePredicate
120
+ return NegativePredicate()
121
+
122
+ @memoize_property
123
+ def zero(self):
124
+ from .handlers.order import ZeroPredicate
125
+ return ZeroPredicate()
126
+
127
+ @memoize_property
128
+ def extended_positive(self):
129
+ from .handlers.order import ExtendedPositivePredicate
130
+ return ExtendedPositivePredicate()
131
+
132
+ @memoize_property
133
+ def extended_negative(self):
134
+ from .handlers.order import ExtendedNegativePredicate
135
+ return ExtendedNegativePredicate()
136
+
137
+ @memoize_property
138
+ def nonzero(self):
139
+ from .handlers.order import NonZeroPredicate
140
+ return NonZeroPredicate()
141
+
142
+ @memoize_property
143
+ def nonpositive(self):
144
+ from .handlers.order import NonPositivePredicate
145
+ return NonPositivePredicate()
146
+
147
+ @memoize_property
148
+ def nonnegative(self):
149
+ from .handlers.order import NonNegativePredicate
150
+ return NonNegativePredicate()
151
+
152
+ @memoize_property
153
+ def extended_nonzero(self):
154
+ from .handlers.order import ExtendedNonZeroPredicate
155
+ return ExtendedNonZeroPredicate()
156
+
157
+ @memoize_property
158
+ def extended_nonpositive(self):
159
+ from .handlers.order import ExtendedNonPositivePredicate
160
+ return ExtendedNonPositivePredicate()
161
+
162
+ @memoize_property
163
+ def extended_nonnegative(self):
164
+ from .handlers.order import ExtendedNonNegativePredicate
165
+ return ExtendedNonNegativePredicate()
166
+
167
+ @memoize_property
168
+ def even(self):
169
+ from .handlers.ntheory import EvenPredicate
170
+ return EvenPredicate()
171
+
172
+ @memoize_property
173
+ def odd(self):
174
+ from .handlers.ntheory import OddPredicate
175
+ return OddPredicate()
176
+
177
+ @memoize_property
178
+ def prime(self):
179
+ from .handlers.ntheory import PrimePredicate
180
+ return PrimePredicate()
181
+
182
+ @memoize_property
183
+ def composite(self):
184
+ from .handlers.ntheory import CompositePredicate
185
+ return CompositePredicate()
186
+
187
+ @memoize_property
188
+ def commutative(self):
189
+ from .handlers.common import CommutativePredicate
190
+ return CommutativePredicate()
191
+
192
+ @memoize_property
193
+ def is_true(self):
194
+ from .handlers.common import IsTruePredicate
195
+ return IsTruePredicate()
196
+
197
+ @memoize_property
198
+ def symmetric(self):
199
+ from .handlers.matrices import SymmetricPredicate
200
+ return SymmetricPredicate()
201
+
202
+ @memoize_property
203
+ def invertible(self):
204
+ from .handlers.matrices import InvertiblePredicate
205
+ return InvertiblePredicate()
206
+
207
+ @memoize_property
208
+ def orthogonal(self):
209
+ from .handlers.matrices import OrthogonalPredicate
210
+ return OrthogonalPredicate()
211
+
212
+ @memoize_property
213
+ def unitary(self):
214
+ from .handlers.matrices import UnitaryPredicate
215
+ return UnitaryPredicate()
216
+
217
+ @memoize_property
218
+ def positive_definite(self):
219
+ from .handlers.matrices import PositiveDefinitePredicate
220
+ return PositiveDefinitePredicate()
221
+
222
+ @memoize_property
223
+ def upper_triangular(self):
224
+ from .handlers.matrices import UpperTriangularPredicate
225
+ return UpperTriangularPredicate()
226
+
227
+ @memoize_property
228
+ def lower_triangular(self):
229
+ from .handlers.matrices import LowerTriangularPredicate
230
+ return LowerTriangularPredicate()
231
+
232
+ @memoize_property
233
+ def diagonal(self):
234
+ from .handlers.matrices import DiagonalPredicate
235
+ return DiagonalPredicate()
236
+
237
+ @memoize_property
238
+ def fullrank(self):
239
+ from .handlers.matrices import FullRankPredicate
240
+ return FullRankPredicate()
241
+
242
+ @memoize_property
243
+ def square(self):
244
+ from .handlers.matrices import SquarePredicate
245
+ return SquarePredicate()
246
+
247
+ @memoize_property
248
+ def integer_elements(self):
249
+ from .handlers.matrices import IntegerElementsPredicate
250
+ return IntegerElementsPredicate()
251
+
252
+ @memoize_property
253
+ def real_elements(self):
254
+ from .handlers.matrices import RealElementsPredicate
255
+ return RealElementsPredicate()
256
+
257
+ @memoize_property
258
+ def complex_elements(self):
259
+ from .handlers.matrices import ComplexElementsPredicate
260
+ return ComplexElementsPredicate()
261
+
262
+ @memoize_property
263
+ def singular(self):
264
+ from .predicates.matrices import SingularPredicate
265
+ return SingularPredicate()
266
+
267
+ @memoize_property
268
+ def normal(self):
269
+ from .predicates.matrices import NormalPredicate
270
+ return NormalPredicate()
271
+
272
+ @memoize_property
273
+ def triangular(self):
274
+ from .predicates.matrices import TriangularPredicate
275
+ return TriangularPredicate()
276
+
277
+ @memoize_property
278
+ def unit_triangular(self):
279
+ from .predicates.matrices import UnitTriangularPredicate
280
+ return UnitTriangularPredicate()
281
+
282
+ @memoize_property
283
+ def eq(self):
284
+ from .relation.equality import EqualityPredicate
285
+ return EqualityPredicate()
286
+
287
+ @memoize_property
288
+ def ne(self):
289
+ from .relation.equality import UnequalityPredicate
290
+ return UnequalityPredicate()
291
+
292
+ @memoize_property
293
+ def gt(self):
294
+ from .relation.equality import StrictGreaterThanPredicate
295
+ return StrictGreaterThanPredicate()
296
+
297
+ @memoize_property
298
+ def ge(self):
299
+ from .relation.equality import GreaterThanPredicate
300
+ return GreaterThanPredicate()
301
+
302
+ @memoize_property
303
+ def lt(self):
304
+ from .relation.equality import StrictLessThanPredicate
305
+ return StrictLessThanPredicate()
306
+
307
+ @memoize_property
308
+ def le(self):
309
+ from .relation.equality import LessThanPredicate
310
+ return LessThanPredicate()
311
+
312
+
313
+ Q = AssumptionKeys()
314
+
315
+ def _extract_all_facts(assump, exprs):
316
+ """
317
+ Extract all relevant assumptions from *assump* with respect to given *exprs*.
318
+
319
+ Parameters
320
+ ==========
321
+
322
+ assump : sympy.assumptions.cnf.CNF
323
+
324
+ exprs : tuple of expressions
325
+
326
+ Returns
327
+ =======
328
+
329
+ sympy.assumptions.cnf.CNF
330
+
331
+ Examples
332
+ ========
333
+
334
+ >>> from sympy import Q
335
+ >>> from sympy.assumptions.cnf import CNF
336
+ >>> from sympy.assumptions.ask import _extract_all_facts
337
+ >>> from sympy.abc import x, y
338
+ >>> assump = CNF.from_prop(Q.positive(x) & Q.integer(y))
339
+ >>> exprs = (x,)
340
+ >>> cnf = _extract_all_facts(assump, exprs)
341
+ >>> cnf.clauses
342
+ {frozenset({Literal(Q.positive, False)})}
343
+
344
+ """
345
+ facts = set()
346
+
347
+ for clause in assump.clauses:
348
+ args = []
349
+ for literal in clause:
350
+ if isinstance(literal.lit, AppliedPredicate) and len(literal.lit.arguments) == 1:
351
+ if literal.lit.arg in exprs:
352
+ # Add literal if it has matching in it
353
+ args.append(Literal(literal.lit.function, literal.is_Not))
354
+ else:
355
+ # If any of the literals doesn't have matching expr don't add the whole clause.
356
+ break
357
+ else:
358
+ # If any of the literals aren't unary predicate don't add the whole clause.
359
+ break
360
+
361
+ else:
362
+ if args:
363
+ facts.add(frozenset(args))
364
+ return CNF(facts)
365
+
366
+
367
+ def ask(proposition, assumptions=True, context=global_assumptions):
368
+ """
369
+ Function to evaluate the proposition with assumptions.
370
+
371
+ Explanation
372
+ ===========
373
+
374
+ This function evaluates the proposition to ``True`` or ``False`` if
375
+ the truth value can be determined. If not, it returns ``None``.
376
+
377
+ It should be discerned from :func:`~.refine` which, when applied to a
378
+ proposition, simplifies the argument to symbolic ``Boolean`` instead of
379
+ Python built-in ``True``, ``False`` or ``None``.
380
+
381
+ **Syntax**
382
+
383
+ * ask(proposition)
384
+ Evaluate the *proposition* in global assumption context.
385
+
386
+ * ask(proposition, assumptions)
387
+ Evaluate the *proposition* with respect to *assumptions* in
388
+ global assumption context.
389
+
390
+ Parameters
391
+ ==========
392
+
393
+ proposition : Boolean
394
+ Proposition which will be evaluated to boolean value. If this is
395
+ not ``AppliedPredicate``, it will be wrapped by ``Q.is_true``.
396
+
397
+ assumptions : Boolean, optional
398
+ Local assumptions to evaluate the *proposition*.
399
+
400
+ context : AssumptionsContext, optional
401
+ Default assumptions to evaluate the *proposition*. By default,
402
+ this is ``sympy.assumptions.global_assumptions`` variable.
403
+
404
+ Returns
405
+ =======
406
+
407
+ ``True``, ``False``, or ``None``
408
+
409
+ Raises
410
+ ======
411
+
412
+ TypeError : *proposition* or *assumptions* is not valid logical expression.
413
+
414
+ ValueError : assumptions are inconsistent.
415
+
416
+ Examples
417
+ ========
418
+
419
+ >>> from sympy import ask, Q, pi
420
+ >>> from sympy.abc import x, y
421
+ >>> ask(Q.rational(pi))
422
+ False
423
+ >>> ask(Q.even(x*y), Q.even(x) & Q.integer(y))
424
+ True
425
+ >>> ask(Q.prime(4*x), Q.integer(x))
426
+ False
427
+
428
+ If the truth value cannot be determined, ``None`` will be returned.
429
+
430
+ >>> print(ask(Q.odd(3*x))) # cannot determine unless we know x
431
+ None
432
+
433
+ ``ValueError`` is raised if assumptions are inconsistent.
434
+
435
+ >>> ask(Q.integer(x), Q.even(x) & Q.odd(x))
436
+ Traceback (most recent call last):
437
+ ...
438
+ ValueError: inconsistent assumptions Q.even(x) & Q.odd(x)
439
+
440
+ Notes
441
+ =====
442
+
443
+ Relations in assumptions are not implemented (yet), so the following
444
+ will not give a meaningful result.
445
+
446
+ >>> ask(Q.positive(x), x > 0)
447
+
448
+ It is however a work in progress.
449
+
450
+ See Also
451
+ ========
452
+
453
+ sympy.assumptions.refine.refine : Simplification using assumptions.
454
+ Proposition is not reduced to ``None`` if the truth value cannot
455
+ be determined.
456
+ """
457
+ from sympy.assumptions.satask import satask
458
+ from sympy.assumptions.lra_satask import lra_satask
459
+ from sympy.logic.algorithms.lra_theory import UnhandledInput
460
+
461
+ proposition = sympify(proposition)
462
+ assumptions = sympify(assumptions)
463
+
464
+ if isinstance(proposition, Predicate) or proposition.kind is not BooleanKind:
465
+ raise TypeError("proposition must be a valid logical expression")
466
+
467
+ if isinstance(assumptions, Predicate) or assumptions.kind is not BooleanKind:
468
+ raise TypeError("assumptions must be a valid logical expression")
469
+
470
+ binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le}
471
+ if isinstance(proposition, AppliedPredicate):
472
+ key, args = proposition.function, proposition.arguments
473
+ elif proposition.func in binrelpreds:
474
+ key, args = binrelpreds[type(proposition)], proposition.args
475
+ else:
476
+ key, args = Q.is_true, (proposition,)
477
+
478
+ # convert local and global assumptions to CNF
479
+ assump_cnf = CNF.from_prop(assumptions)
480
+ assump_cnf.extend(context)
481
+
482
+ # extract the relevant facts from assumptions with respect to args
483
+ local_facts = _extract_all_facts(assump_cnf, args)
484
+
485
+ # convert default facts and assumed facts to encoded CNF
486
+ known_facts_cnf = get_all_known_facts()
487
+ enc_cnf = EncodedCNF()
488
+ enc_cnf.from_cnf(CNF(known_facts_cnf))
489
+ enc_cnf.add_from_cnf(local_facts)
490
+
491
+ # check the satisfiability of given assumptions
492
+ if local_facts.clauses and satisfiable(enc_cnf) is False:
493
+ raise ValueError("inconsistent assumptions %s" % assumptions)
494
+
495
+ # quick computation for single fact
496
+ res = _ask_single_fact(key, local_facts)
497
+ if res is not None:
498
+ return res
499
+
500
+ # direct resolution method, no logic
501
+ res = key(*args)._eval_ask(assumptions)
502
+ if res is not None:
503
+ return bool(res)
504
+
505
+ # using satask (still costly)
506
+ res = satask(proposition, assumptions=assumptions, context=context)
507
+ if res is not None:
508
+ return res
509
+
510
+ try:
511
+ res = lra_satask(proposition, assumptions=assumptions, context=context)
512
+ except UnhandledInput:
513
+ return None
514
+
515
+ return res
516
+
517
+
518
+ def _ask_single_fact(key, local_facts):
519
+ """
520
+ Compute the truth value of single predicate using assumptions.
521
+
522
+ Parameters
523
+ ==========
524
+
525
+ key : sympy.assumptions.assume.Predicate
526
+ Proposition predicate.
527
+
528
+ local_facts : sympy.assumptions.cnf.CNF
529
+ Local assumption in CNF form.
530
+
531
+ Returns
532
+ =======
533
+
534
+ ``True``, ``False`` or ``None``
535
+
536
+ Examples
537
+ ========
538
+
539
+ >>> from sympy import Q
540
+ >>> from sympy.assumptions.cnf import CNF
541
+ >>> from sympy.assumptions.ask import _ask_single_fact
542
+
543
+ If prerequisite of proposition is rejected by the assumption,
544
+ return ``False``.
545
+
546
+ >>> key, assump = Q.zero, ~Q.zero
547
+ >>> local_facts = CNF.from_prop(assump)
548
+ >>> _ask_single_fact(key, local_facts)
549
+ False
550
+ >>> key, assump = Q.zero, ~Q.even
551
+ >>> local_facts = CNF.from_prop(assump)
552
+ >>> _ask_single_fact(key, local_facts)
553
+ False
554
+
555
+ If assumption implies the proposition, return ``True``.
556
+
557
+ >>> key, assump = Q.even, Q.zero
558
+ >>> local_facts = CNF.from_prop(assump)
559
+ >>> _ask_single_fact(key, local_facts)
560
+ True
561
+
562
+ If proposition rejects the assumption, return ``False``.
563
+
564
+ >>> key, assump = Q.even, Q.odd
565
+ >>> local_facts = CNF.from_prop(assump)
566
+ >>> _ask_single_fact(key, local_facts)
567
+ False
568
+ """
569
+ if local_facts.clauses:
570
+
571
+ known_facts_dict = get_known_facts_dict()
572
+
573
+ if len(local_facts.clauses) == 1:
574
+ cl, = local_facts.clauses
575
+ if len(cl) == 1:
576
+ f, = cl
577
+ prop_facts = known_facts_dict.get(key, None)
578
+ prop_req = prop_facts[0] if prop_facts is not None else set()
579
+ if f.is_Not and f.arg in prop_req:
580
+ # the prerequisite of proposition is rejected
581
+ return False
582
+
583
+ for clause in local_facts.clauses:
584
+ if len(clause) == 1:
585
+ f, = clause
586
+ prop_facts = known_facts_dict.get(f.arg, None) if not f.is_Not else None
587
+ if prop_facts is None:
588
+ continue
589
+
590
+ prop_req, prop_rej = prop_facts
591
+ if key in prop_req:
592
+ # assumption implies the proposition
593
+ return True
594
+ elif key in prop_rej:
595
+ # proposition rejects the assumption
596
+ return False
597
+
598
+ return None
599
+
600
+
601
+ def register_handler(key, handler):
602
+ """
603
+ Register a handler in the ask system. key must be a string and handler a
604
+ class inheriting from AskHandler.
605
+
606
+ .. deprecated:: 1.8.
607
+ Use multipledispatch handler instead. See :obj:`~.Predicate`.
608
+
609
+ """
610
+ sympy_deprecation_warning(
611
+ """
612
+ The AskHandler system is deprecated. The register_handler() function
613
+ should be replaced with the multipledispatch handler of Predicate.
614
+ """,
615
+ deprecated_since_version="1.8",
616
+ active_deprecations_target='deprecated-askhandler',
617
+ )
618
+ if isinstance(key, Predicate):
619
+ key = key.name.name
620
+ Qkey = getattr(Q, key, None)
621
+ if Qkey is not None:
622
+ Qkey.add_handler(handler)
623
+ else:
624
+ setattr(Q, key, Predicate(key, handlers=[handler]))
625
+
626
+
627
+ def remove_handler(key, handler):
628
+ """
629
+ Removes a handler from the ask system.
630
+
631
+ .. deprecated:: 1.8.
632
+ Use multipledispatch handler instead. See :obj:`~.Predicate`.
633
+
634
+ """
635
+ sympy_deprecation_warning(
636
+ """
637
+ The AskHandler system is deprecated. The remove_handler() function
638
+ should be replaced with the multipledispatch handler of Predicate.
639
+ """,
640
+ deprecated_since_version="1.8",
641
+ active_deprecations_target='deprecated-askhandler',
642
+ )
643
+ if isinstance(key, Predicate):
644
+ key = key.name.name
645
+ # Don't show the same warning again recursively
646
+ with ignore_warnings(SymPyDeprecationWarning):
647
+ getattr(Q, key).remove_handler(handler)
648
+
649
+
650
+ from sympy.assumptions.ask_generated import (get_all_known_facts,
651
+ get_known_facts_dict)
.venv/lib/python3.10/site-packages/sympy/assumptions/ask_generated.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Do NOT manually edit this file.
3
+ Instead, run ./bin/ask_update.py.
4
+ """
5
+
6
+ from sympy.assumptions.ask import Q
7
+ from sympy.assumptions.cnf import Literal
8
+ from sympy.core.cache import cacheit
9
+
10
+ @cacheit
11
+ def get_all_known_facts():
12
+ """
13
+ Known facts between unary predicates as CNF clauses.
14
+ """
15
+ return {
16
+ frozenset((Literal(Q.algebraic, False), Literal(Q.imaginary, True), Literal(Q.transcendental, False))),
17
+ frozenset((Literal(Q.algebraic, False), Literal(Q.negative, True), Literal(Q.transcendental, False))),
18
+ frozenset((Literal(Q.algebraic, False), Literal(Q.positive, True), Literal(Q.transcendental, False))),
19
+ frozenset((Literal(Q.algebraic, False), Literal(Q.rational, True))),
20
+ frozenset((Literal(Q.algebraic, False), Literal(Q.transcendental, False), Literal(Q.zero, True))),
21
+ frozenset((Literal(Q.algebraic, True), Literal(Q.finite, False))),
22
+ frozenset((Literal(Q.algebraic, True), Literal(Q.transcendental, True))),
23
+ frozenset((Literal(Q.antihermitian, False), Literal(Q.hermitian, False), Literal(Q.zero, True))),
24
+ frozenset((Literal(Q.antihermitian, False), Literal(Q.imaginary, True))),
25
+ frozenset((Literal(Q.commutative, False), Literal(Q.finite, True))),
26
+ frozenset((Literal(Q.commutative, False), Literal(Q.infinite, True))),
27
+ frozenset((Literal(Q.complex_elements, False), Literal(Q.real_elements, True))),
28
+ frozenset((Literal(Q.composite, False), Literal(Q.even, True), Literal(Q.positive, True), Literal(Q.prime, False))),
29
+ frozenset((Literal(Q.composite, True), Literal(Q.even, False), Literal(Q.odd, False))),
30
+ frozenset((Literal(Q.composite, True), Literal(Q.positive, False))),
31
+ frozenset((Literal(Q.composite, True), Literal(Q.prime, True))),
32
+ frozenset((Literal(Q.diagonal, False), Literal(Q.lower_triangular, True), Literal(Q.upper_triangular, True))),
33
+ frozenset((Literal(Q.diagonal, True), Literal(Q.lower_triangular, False))),
34
+ frozenset((Literal(Q.diagonal, True), Literal(Q.normal, False))),
35
+ frozenset((Literal(Q.diagonal, True), Literal(Q.symmetric, False))),
36
+ frozenset((Literal(Q.diagonal, True), Literal(Q.upper_triangular, False))),
37
+ frozenset((Literal(Q.even, False), Literal(Q.odd, False), Literal(Q.prime, True))),
38
+ frozenset((Literal(Q.even, False), Literal(Q.zero, True))),
39
+ frozenset((Literal(Q.even, True), Literal(Q.odd, True))),
40
+ frozenset((Literal(Q.even, True), Literal(Q.rational, False))),
41
+ frozenset((Literal(Q.finite, False), Literal(Q.transcendental, True))),
42
+ frozenset((Literal(Q.finite, True), Literal(Q.infinite, True))),
43
+ frozenset((Literal(Q.fullrank, False), Literal(Q.invertible, True))),
44
+ frozenset((Literal(Q.fullrank, True), Literal(Q.invertible, False), Literal(Q.square, True))),
45
+ frozenset((Literal(Q.hermitian, False), Literal(Q.negative, True))),
46
+ frozenset((Literal(Q.hermitian, False), Literal(Q.positive, True))),
47
+ frozenset((Literal(Q.hermitian, False), Literal(Q.zero, True))),
48
+ frozenset((Literal(Q.imaginary, True), Literal(Q.negative, True))),
49
+ frozenset((Literal(Q.imaginary, True), Literal(Q.positive, True))),
50
+ frozenset((Literal(Q.imaginary, True), Literal(Q.zero, True))),
51
+ frozenset((Literal(Q.infinite, False), Literal(Q.negative_infinite, True))),
52
+ frozenset((Literal(Q.infinite, False), Literal(Q.positive_infinite, True))),
53
+ frozenset((Literal(Q.integer_elements, True), Literal(Q.real_elements, False))),
54
+ frozenset((Literal(Q.invertible, False), Literal(Q.positive_definite, True))),
55
+ frozenset((Literal(Q.invertible, False), Literal(Q.singular, False))),
56
+ frozenset((Literal(Q.invertible, False), Literal(Q.unitary, True))),
57
+ frozenset((Literal(Q.invertible, True), Literal(Q.singular, True))),
58
+ frozenset((Literal(Q.invertible, True), Literal(Q.square, False))),
59
+ frozenset((Literal(Q.irrational, False), Literal(Q.negative, True), Literal(Q.rational, False))),
60
+ frozenset((Literal(Q.irrational, False), Literal(Q.positive, True), Literal(Q.rational, False))),
61
+ frozenset((Literal(Q.irrational, False), Literal(Q.rational, False), Literal(Q.zero, True))),
62
+ frozenset((Literal(Q.irrational, True), Literal(Q.negative, False), Literal(Q.positive, False), Literal(Q.zero, False))),
63
+ frozenset((Literal(Q.irrational, True), Literal(Q.rational, True))),
64
+ frozenset((Literal(Q.lower_triangular, False), Literal(Q.triangular, True), Literal(Q.upper_triangular, False))),
65
+ frozenset((Literal(Q.lower_triangular, True), Literal(Q.triangular, False))),
66
+ frozenset((Literal(Q.negative, False), Literal(Q.positive, False), Literal(Q.rational, True), Literal(Q.zero, False))),
67
+ frozenset((Literal(Q.negative, True), Literal(Q.negative_infinite, True))),
68
+ frozenset((Literal(Q.negative, True), Literal(Q.positive, True))),
69
+ frozenset((Literal(Q.negative, True), Literal(Q.positive_infinite, True))),
70
+ frozenset((Literal(Q.negative, True), Literal(Q.zero, True))),
71
+ frozenset((Literal(Q.negative_infinite, True), Literal(Q.positive, True))),
72
+ frozenset((Literal(Q.negative_infinite, True), Literal(Q.positive_infinite, True))),
73
+ frozenset((Literal(Q.negative_infinite, True), Literal(Q.zero, True))),
74
+ frozenset((Literal(Q.normal, False), Literal(Q.unitary, True))),
75
+ frozenset((Literal(Q.normal, True), Literal(Q.square, False))),
76
+ frozenset((Literal(Q.odd, True), Literal(Q.rational, False))),
77
+ frozenset((Literal(Q.orthogonal, False), Literal(Q.real_elements, True), Literal(Q.unitary, True))),
78
+ frozenset((Literal(Q.orthogonal, True), Literal(Q.positive_definite, False))),
79
+ frozenset((Literal(Q.orthogonal, True), Literal(Q.unitary, False))),
80
+ frozenset((Literal(Q.positive, False), Literal(Q.prime, True))),
81
+ frozenset((Literal(Q.positive, True), Literal(Q.positive_infinite, True))),
82
+ frozenset((Literal(Q.positive, True), Literal(Q.zero, True))),
83
+ frozenset((Literal(Q.positive_infinite, True), Literal(Q.zero, True))),
84
+ frozenset((Literal(Q.square, False), Literal(Q.symmetric, True))),
85
+ frozenset((Literal(Q.triangular, False), Literal(Q.unit_triangular, True))),
86
+ frozenset((Literal(Q.triangular, False), Literal(Q.upper_triangular, True)))
87
+ }
88
+
89
+ @cacheit
90
+ def get_all_known_matrix_facts():
91
+ """
92
+ Known facts between unary predicates for matrices as CNF clauses.
93
+ """
94
+ return {
95
+ frozenset((Literal(Q.complex_elements, False), Literal(Q.real_elements, True))),
96
+ frozenset((Literal(Q.diagonal, False), Literal(Q.lower_triangular, True), Literal(Q.upper_triangular, True))),
97
+ frozenset((Literal(Q.diagonal, True), Literal(Q.lower_triangular, False))),
98
+ frozenset((Literal(Q.diagonal, True), Literal(Q.normal, False))),
99
+ frozenset((Literal(Q.diagonal, True), Literal(Q.symmetric, False))),
100
+ frozenset((Literal(Q.diagonal, True), Literal(Q.upper_triangular, False))),
101
+ frozenset((Literal(Q.fullrank, False), Literal(Q.invertible, True))),
102
+ frozenset((Literal(Q.fullrank, True), Literal(Q.invertible, False), Literal(Q.square, True))),
103
+ frozenset((Literal(Q.integer_elements, True), Literal(Q.real_elements, False))),
104
+ frozenset((Literal(Q.invertible, False), Literal(Q.positive_definite, True))),
105
+ frozenset((Literal(Q.invertible, False), Literal(Q.singular, False))),
106
+ frozenset((Literal(Q.invertible, False), Literal(Q.unitary, True))),
107
+ frozenset((Literal(Q.invertible, True), Literal(Q.singular, True))),
108
+ frozenset((Literal(Q.invertible, True), Literal(Q.square, False))),
109
+ frozenset((Literal(Q.lower_triangular, False), Literal(Q.triangular, True), Literal(Q.upper_triangular, False))),
110
+ frozenset((Literal(Q.lower_triangular, True), Literal(Q.triangular, False))),
111
+ frozenset((Literal(Q.normal, False), Literal(Q.unitary, True))),
112
+ frozenset((Literal(Q.normal, True), Literal(Q.square, False))),
113
+ frozenset((Literal(Q.orthogonal, False), Literal(Q.real_elements, True), Literal(Q.unitary, True))),
114
+ frozenset((Literal(Q.orthogonal, True), Literal(Q.positive_definite, False))),
115
+ frozenset((Literal(Q.orthogonal, True), Literal(Q.unitary, False))),
116
+ frozenset((Literal(Q.square, False), Literal(Q.symmetric, True))),
117
+ frozenset((Literal(Q.triangular, False), Literal(Q.unit_triangular, True))),
118
+ frozenset((Literal(Q.triangular, False), Literal(Q.upper_triangular, True)))
119
+ }
120
+
121
+ @cacheit
122
+ def get_all_known_number_facts():
123
+ """
124
+ Known facts between unary predicates for numbers as CNF clauses.
125
+ """
126
+ return {
127
+ frozenset((Literal(Q.algebraic, False), Literal(Q.imaginary, True), Literal(Q.transcendental, False))),
128
+ frozenset((Literal(Q.algebraic, False), Literal(Q.negative, True), Literal(Q.transcendental, False))),
129
+ frozenset((Literal(Q.algebraic, False), Literal(Q.positive, True), Literal(Q.transcendental, False))),
130
+ frozenset((Literal(Q.algebraic, False), Literal(Q.rational, True))),
131
+ frozenset((Literal(Q.algebraic, False), Literal(Q.transcendental, False), Literal(Q.zero, True))),
132
+ frozenset((Literal(Q.algebraic, True), Literal(Q.finite, False))),
133
+ frozenset((Literal(Q.algebraic, True), Literal(Q.transcendental, True))),
134
+ frozenset((Literal(Q.antihermitian, False), Literal(Q.hermitian, False), Literal(Q.zero, True))),
135
+ frozenset((Literal(Q.antihermitian, False), Literal(Q.imaginary, True))),
136
+ frozenset((Literal(Q.commutative, False), Literal(Q.finite, True))),
137
+ frozenset((Literal(Q.commutative, False), Literal(Q.infinite, True))),
138
+ frozenset((Literal(Q.composite, False), Literal(Q.even, True), Literal(Q.positive, True), Literal(Q.prime, False))),
139
+ frozenset((Literal(Q.composite, True), Literal(Q.even, False), Literal(Q.odd, False))),
140
+ frozenset((Literal(Q.composite, True), Literal(Q.positive, False))),
141
+ frozenset((Literal(Q.composite, True), Literal(Q.prime, True))),
142
+ frozenset((Literal(Q.even, False), Literal(Q.odd, False), Literal(Q.prime, True))),
143
+ frozenset((Literal(Q.even, False), Literal(Q.zero, True))),
144
+ frozenset((Literal(Q.even, True), Literal(Q.odd, True))),
145
+ frozenset((Literal(Q.even, True), Literal(Q.rational, False))),
146
+ frozenset((Literal(Q.finite, False), Literal(Q.transcendental, True))),
147
+ frozenset((Literal(Q.finite, True), Literal(Q.infinite, True))),
148
+ frozenset((Literal(Q.hermitian, False), Literal(Q.negative, True))),
149
+ frozenset((Literal(Q.hermitian, False), Literal(Q.positive, True))),
150
+ frozenset((Literal(Q.hermitian, False), Literal(Q.zero, True))),
151
+ frozenset((Literal(Q.imaginary, True), Literal(Q.negative, True))),
152
+ frozenset((Literal(Q.imaginary, True), Literal(Q.positive, True))),
153
+ frozenset((Literal(Q.imaginary, True), Literal(Q.zero, True))),
154
+ frozenset((Literal(Q.infinite, False), Literal(Q.negative_infinite, True))),
155
+ frozenset((Literal(Q.infinite, False), Literal(Q.positive_infinite, True))),
156
+ frozenset((Literal(Q.irrational, False), Literal(Q.negative, True), Literal(Q.rational, False))),
157
+ frozenset((Literal(Q.irrational, False), Literal(Q.positive, True), Literal(Q.rational, False))),
158
+ frozenset((Literal(Q.irrational, False), Literal(Q.rational, False), Literal(Q.zero, True))),
159
+ frozenset((Literal(Q.irrational, True), Literal(Q.negative, False), Literal(Q.positive, False), Literal(Q.zero, False))),
160
+ frozenset((Literal(Q.irrational, True), Literal(Q.rational, True))),
161
+ frozenset((Literal(Q.negative, False), Literal(Q.positive, False), Literal(Q.rational, True), Literal(Q.zero, False))),
162
+ frozenset((Literal(Q.negative, True), Literal(Q.negative_infinite, True))),
163
+ frozenset((Literal(Q.negative, True), Literal(Q.positive, True))),
164
+ frozenset((Literal(Q.negative, True), Literal(Q.positive_infinite, True))),
165
+ frozenset((Literal(Q.negative, True), Literal(Q.zero, True))),
166
+ frozenset((Literal(Q.negative_infinite, True), Literal(Q.positive, True))),
167
+ frozenset((Literal(Q.negative_infinite, True), Literal(Q.positive_infinite, True))),
168
+ frozenset((Literal(Q.negative_infinite, True), Literal(Q.zero, True))),
169
+ frozenset((Literal(Q.odd, True), Literal(Q.rational, False))),
170
+ frozenset((Literal(Q.positive, False), Literal(Q.prime, True))),
171
+ frozenset((Literal(Q.positive, True), Literal(Q.positive_infinite, True))),
172
+ frozenset((Literal(Q.positive, True), Literal(Q.zero, True))),
173
+ frozenset((Literal(Q.positive_infinite, True), Literal(Q.zero, True)))
174
+ }
175
+
176
+ @cacheit
177
+ def get_known_facts_dict():
178
+ """
179
+ Logical relations between unary predicates as dictionary.
180
+
181
+ Each key is a predicate, and item is two groups of predicates.
182
+ First group contains the predicates which are implied by the key, and
183
+ second group contains the predicates which are rejected by the key.
184
+
185
+ """
186
+ return {
187
+ Q.algebraic: (set([Q.algebraic, Q.commutative, Q.complex, Q.finite]),
188
+ set([Q.infinite, Q.negative_infinite, Q.positive_infinite,
189
+ Q.transcendental])),
190
+ Q.antihermitian: (set([Q.antihermitian]), set([])),
191
+ Q.commutative: (set([Q.commutative]), set([])),
192
+ Q.complex: (set([Q.commutative, Q.complex, Q.finite]),
193
+ set([Q.infinite, Q.negative_infinite, Q.positive_infinite])),
194
+ Q.complex_elements: (set([Q.complex_elements]), set([])),
195
+ Q.composite: (set([Q.algebraic, Q.commutative, Q.complex, Q.composite,
196
+ Q.extended_nonnegative, Q.extended_nonzero,
197
+ Q.extended_positive, Q.extended_real, Q.finite, Q.hermitian,
198
+ Q.integer, Q.nonnegative, Q.nonzero, Q.positive, Q.rational,
199
+ Q.real]), set([Q.extended_negative, Q.extended_nonpositive,
200
+ Q.imaginary, Q.infinite, Q.irrational, Q.negative,
201
+ Q.negative_infinite, Q.nonpositive, Q.positive_infinite,
202
+ Q.prime, Q.transcendental, Q.zero])),
203
+ Q.diagonal: (set([Q.diagonal, Q.lower_triangular, Q.normal, Q.square,
204
+ Q.symmetric, Q.triangular, Q.upper_triangular]), set([])),
205
+ Q.even: (set([Q.algebraic, Q.commutative, Q.complex, Q.even,
206
+ Q.extended_real, Q.finite, Q.hermitian, Q.integer, Q.rational,
207
+ Q.real]), set([Q.imaginary, Q.infinite, Q.irrational,
208
+ Q.negative_infinite, Q.odd, Q.positive_infinite,
209
+ Q.transcendental])),
210
+ Q.extended_negative: (set([Q.commutative, Q.extended_negative,
211
+ Q.extended_nonpositive, Q.extended_nonzero, Q.extended_real]),
212
+ set([Q.composite, Q.extended_nonnegative, Q.extended_positive,
213
+ Q.imaginary, Q.nonnegative, Q.positive, Q.positive_infinite,
214
+ Q.prime, Q.zero])),
215
+ Q.extended_nonnegative: (set([Q.commutative, Q.extended_nonnegative,
216
+ Q.extended_real]), set([Q.extended_negative, Q.imaginary,
217
+ Q.negative, Q.negative_infinite])),
218
+ Q.extended_nonpositive: (set([Q.commutative, Q.extended_nonpositive,
219
+ Q.extended_real]), set([Q.composite, Q.extended_positive,
220
+ Q.imaginary, Q.positive, Q.positive_infinite, Q.prime])),
221
+ Q.extended_nonzero: (set([Q.commutative, Q.extended_nonzero,
222
+ Q.extended_real]), set([Q.imaginary, Q.zero])),
223
+ Q.extended_positive: (set([Q.commutative, Q.extended_nonnegative,
224
+ Q.extended_nonzero, Q.extended_positive, Q.extended_real]),
225
+ set([Q.extended_negative, Q.extended_nonpositive, Q.imaginary,
226
+ Q.negative, Q.negative_infinite, Q.nonpositive, Q.zero])),
227
+ Q.extended_real: (set([Q.commutative, Q.extended_real]),
228
+ set([Q.imaginary])),
229
+ Q.finite: (set([Q.commutative, Q.finite]), set([Q.infinite,
230
+ Q.negative_infinite, Q.positive_infinite])),
231
+ Q.fullrank: (set([Q.fullrank]), set([])),
232
+ Q.hermitian: (set([Q.hermitian]), set([])),
233
+ Q.imaginary: (set([Q.antihermitian, Q.commutative, Q.complex,
234
+ Q.finite, Q.imaginary]), set([Q.composite, Q.even,
235
+ Q.extended_negative, Q.extended_nonnegative,
236
+ Q.extended_nonpositive, Q.extended_nonzero,
237
+ Q.extended_positive, Q.extended_real, Q.infinite, Q.integer,
238
+ Q.irrational, Q.negative, Q.negative_infinite, Q.nonnegative,
239
+ Q.nonpositive, Q.nonzero, Q.odd, Q.positive,
240
+ Q.positive_infinite, Q.prime, Q.rational, Q.real, Q.zero])),
241
+ Q.infinite: (set([Q.commutative, Q.infinite]), set([Q.algebraic,
242
+ Q.complex, Q.composite, Q.even, Q.finite, Q.imaginary,
243
+ Q.integer, Q.irrational, Q.negative, Q.nonnegative,
244
+ Q.nonpositive, Q.nonzero, Q.odd, Q.positive, Q.prime,
245
+ Q.rational, Q.real, Q.transcendental, Q.zero])),
246
+ Q.integer: (set([Q.algebraic, Q.commutative, Q.complex,
247
+ Q.extended_real, Q.finite, Q.hermitian, Q.integer, Q.rational,
248
+ Q.real]), set([Q.imaginary, Q.infinite, Q.irrational,
249
+ Q.negative_infinite, Q.positive_infinite, Q.transcendental])),
250
+ Q.integer_elements: (set([Q.complex_elements, Q.integer_elements,
251
+ Q.real_elements]), set([])),
252
+ Q.invertible: (set([Q.fullrank, Q.invertible, Q.square]),
253
+ set([Q.singular])),
254
+ Q.irrational: (set([Q.commutative, Q.complex, Q.extended_nonzero,
255
+ Q.extended_real, Q.finite, Q.hermitian, Q.irrational,
256
+ Q.nonzero, Q.real]), set([Q.composite, Q.even, Q.imaginary,
257
+ Q.infinite, Q.integer, Q.negative_infinite, Q.odd,
258
+ Q.positive_infinite, Q.prime, Q.rational, Q.zero])),
259
+ Q.is_true: (set([Q.is_true]), set([])),
260
+ Q.lower_triangular: (set([Q.lower_triangular, Q.triangular]), set([])),
261
+ Q.negative: (set([Q.commutative, Q.complex, Q.extended_negative,
262
+ Q.extended_nonpositive, Q.extended_nonzero, Q.extended_real,
263
+ Q.finite, Q.hermitian, Q.negative, Q.nonpositive, Q.nonzero,
264
+ Q.real]), set([Q.composite, Q.extended_nonnegative,
265
+ Q.extended_positive, Q.imaginary, Q.infinite,
266
+ Q.negative_infinite, Q.nonnegative, Q.positive,
267
+ Q.positive_infinite, Q.prime, Q.zero])),
268
+ Q.negative_infinite: (set([Q.commutative, Q.extended_negative,
269
+ Q.extended_nonpositive, Q.extended_nonzero, Q.extended_real,
270
+ Q.infinite, Q.negative_infinite]), set([Q.algebraic,
271
+ Q.complex, Q.composite, Q.even, Q.extended_nonnegative,
272
+ Q.extended_positive, Q.finite, Q.imaginary, Q.integer,
273
+ Q.irrational, Q.negative, Q.nonnegative, Q.nonpositive,
274
+ Q.nonzero, Q.odd, Q.positive, Q.positive_infinite, Q.prime,
275
+ Q.rational, Q.real, Q.transcendental, Q.zero])),
276
+ Q.noninteger: (set([Q.noninteger]), set([])),
277
+ Q.nonnegative: (set([Q.commutative, Q.complex, Q.extended_nonnegative,
278
+ Q.extended_real, Q.finite, Q.hermitian, Q.nonnegative,
279
+ Q.real]), set([Q.extended_negative, Q.imaginary, Q.infinite,
280
+ Q.negative, Q.negative_infinite, Q.positive_infinite])),
281
+ Q.nonpositive: (set([Q.commutative, Q.complex, Q.extended_nonpositive,
282
+ Q.extended_real, Q.finite, Q.hermitian, Q.nonpositive,
283
+ Q.real]), set([Q.composite, Q.extended_positive, Q.imaginary,
284
+ Q.infinite, Q.negative_infinite, Q.positive,
285
+ Q.positive_infinite, Q.prime])),
286
+ Q.nonzero: (set([Q.commutative, Q.complex, Q.extended_nonzero,
287
+ Q.extended_real, Q.finite, Q.hermitian, Q.nonzero, Q.real]),
288
+ set([Q.imaginary, Q.infinite, Q.negative_infinite,
289
+ Q.positive_infinite, Q.zero])),
290
+ Q.normal: (set([Q.normal, Q.square]), set([])),
291
+ Q.odd: (set([Q.algebraic, Q.commutative, Q.complex,
292
+ Q.extended_nonzero, Q.extended_real, Q.finite, Q.hermitian,
293
+ Q.integer, Q.nonzero, Q.odd, Q.rational, Q.real]),
294
+ set([Q.even, Q.imaginary, Q.infinite, Q.irrational,
295
+ Q.negative_infinite, Q.positive_infinite, Q.transcendental,
296
+ Q.zero])),
297
+ Q.orthogonal: (set([Q.fullrank, Q.invertible, Q.normal, Q.orthogonal,
298
+ Q.positive_definite, Q.square, Q.unitary]), set([Q.singular])),
299
+ Q.positive: (set([Q.commutative, Q.complex, Q.extended_nonnegative,
300
+ Q.extended_nonzero, Q.extended_positive, Q.extended_real,
301
+ Q.finite, Q.hermitian, Q.nonnegative, Q.nonzero, Q.positive,
302
+ Q.real]), set([Q.extended_negative, Q.extended_nonpositive,
303
+ Q.imaginary, Q.infinite, Q.negative, Q.negative_infinite,
304
+ Q.nonpositive, Q.positive_infinite, Q.zero])),
305
+ Q.positive_definite: (set([Q.fullrank, Q.invertible,
306
+ Q.positive_definite, Q.square]), set([Q.singular])),
307
+ Q.positive_infinite: (set([Q.commutative, Q.extended_nonnegative,
308
+ Q.extended_nonzero, Q.extended_positive, Q.extended_real,
309
+ Q.infinite, Q.positive_infinite]), set([Q.algebraic,
310
+ Q.complex, Q.composite, Q.even, Q.extended_negative,
311
+ Q.extended_nonpositive, Q.finite, Q.imaginary, Q.integer,
312
+ Q.irrational, Q.negative, Q.negative_infinite, Q.nonnegative,
313
+ Q.nonpositive, Q.nonzero, Q.odd, Q.positive, Q.prime,
314
+ Q.rational, Q.real, Q.transcendental, Q.zero])),
315
+ Q.prime: (set([Q.algebraic, Q.commutative, Q.complex,
316
+ Q.extended_nonnegative, Q.extended_nonzero,
317
+ Q.extended_positive, Q.extended_real, Q.finite, Q.hermitian,
318
+ Q.integer, Q.nonnegative, Q.nonzero, Q.positive, Q.prime,
319
+ Q.rational, Q.real]), set([Q.composite, Q.extended_negative,
320
+ Q.extended_nonpositive, Q.imaginary, Q.infinite, Q.irrational,
321
+ Q.negative, Q.negative_infinite, Q.nonpositive,
322
+ Q.positive_infinite, Q.transcendental, Q.zero])),
323
+ Q.rational: (set([Q.algebraic, Q.commutative, Q.complex,
324
+ Q.extended_real, Q.finite, Q.hermitian, Q.rational, Q.real]),
325
+ set([Q.imaginary, Q.infinite, Q.irrational,
326
+ Q.negative_infinite, Q.positive_infinite, Q.transcendental])),
327
+ Q.real: (set([Q.commutative, Q.complex, Q.extended_real, Q.finite,
328
+ Q.hermitian, Q.real]), set([Q.imaginary, Q.infinite,
329
+ Q.negative_infinite, Q.positive_infinite])),
330
+ Q.real_elements: (set([Q.complex_elements, Q.real_elements]), set([])),
331
+ Q.singular: (set([Q.singular]), set([Q.invertible, Q.orthogonal,
332
+ Q.positive_definite, Q.unitary])),
333
+ Q.square: (set([Q.square]), set([])),
334
+ Q.symmetric: (set([Q.square, Q.symmetric]), set([])),
335
+ Q.transcendental: (set([Q.commutative, Q.complex, Q.finite,
336
+ Q.transcendental]), set([Q.algebraic, Q.composite, Q.even,
337
+ Q.infinite, Q.integer, Q.negative_infinite, Q.odd,
338
+ Q.positive_infinite, Q.prime, Q.rational, Q.zero])),
339
+ Q.triangular: (set([Q.triangular]), set([])),
340
+ Q.unit_triangular: (set([Q.triangular, Q.unit_triangular]), set([])),
341
+ Q.unitary: (set([Q.fullrank, Q.invertible, Q.normal, Q.square,
342
+ Q.unitary]), set([Q.singular])),
343
+ Q.upper_triangular: (set([Q.triangular, Q.upper_triangular]), set([])),
344
+ Q.zero: (set([Q.algebraic, Q.commutative, Q.complex, Q.even,
345
+ Q.extended_nonnegative, Q.extended_nonpositive,
346
+ Q.extended_real, Q.finite, Q.hermitian, Q.integer,
347
+ Q.nonnegative, Q.nonpositive, Q.rational, Q.real, Q.zero]),
348
+ set([Q.composite, Q.extended_negative, Q.extended_nonzero,
349
+ Q.extended_positive, Q.imaginary, Q.infinite, Q.irrational,
350
+ Q.negative, Q.negative_infinite, Q.nonzero, Q.odd, Q.positive,
351
+ Q.positive_infinite, Q.prime, Q.transcendental])),
352
+ }
.venv/lib/python3.10/site-packages/sympy/assumptions/assume.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module which implements predicates and assumption context."""
2
+
3
+ from contextlib import contextmanager
4
+ import inspect
5
+ from sympy.core.symbol import Str
6
+ from sympy.core.sympify import _sympify
7
+ from sympy.logic.boolalg import Boolean, false, true
8
+ from sympy.multipledispatch.dispatcher import Dispatcher, str_signature
9
+ from sympy.utilities.exceptions import sympy_deprecation_warning
10
+ from sympy.utilities.iterables import is_sequence
11
+ from sympy.utilities.source import get_class
12
+
13
+
14
+ class AssumptionsContext(set):
15
+ """
16
+ Set containing default assumptions which are applied to the ``ask()``
17
+ function.
18
+
19
+ Explanation
20
+ ===========
21
+
22
+ This is used to represent global assumptions, but you can also use this
23
+ class to create your own local assumptions contexts. It is basically a thin
24
+ wrapper to Python's set, so see its documentation for advanced usage.
25
+
26
+ Examples
27
+ ========
28
+
29
+ The default assumption context is ``global_assumptions``, which is initially empty:
30
+
31
+ >>> from sympy import ask, Q
32
+ >>> from sympy.assumptions import global_assumptions
33
+ >>> global_assumptions
34
+ AssumptionsContext()
35
+
36
+ You can add default assumptions:
37
+
38
+ >>> from sympy.abc import x
39
+ >>> global_assumptions.add(Q.real(x))
40
+ >>> global_assumptions
41
+ AssumptionsContext({Q.real(x)})
42
+ >>> ask(Q.real(x))
43
+ True
44
+
45
+ And remove them:
46
+
47
+ >>> global_assumptions.remove(Q.real(x))
48
+ >>> print(ask(Q.real(x)))
49
+ None
50
+
51
+ The ``clear()`` method removes every assumption:
52
+
53
+ >>> global_assumptions.add(Q.positive(x))
54
+ >>> global_assumptions
55
+ AssumptionsContext({Q.positive(x)})
56
+ >>> global_assumptions.clear()
57
+ >>> global_assumptions
58
+ AssumptionsContext()
59
+
60
+ See Also
61
+ ========
62
+
63
+ assuming
64
+
65
+ """
66
+
67
+ def add(self, *assumptions):
68
+ """Add assumptions."""
69
+ for a in assumptions:
70
+ super().add(a)
71
+
72
+ def _sympystr(self, printer):
73
+ if not self:
74
+ return "%s()" % self.__class__.__name__
75
+ return "{}({})".format(self.__class__.__name__, printer._print_set(self))
76
+
77
+ global_assumptions = AssumptionsContext()
78
+
79
+
80
+ class AppliedPredicate(Boolean):
81
+ """
82
+ The class of expressions resulting from applying ``Predicate`` to
83
+ the arguments. ``AppliedPredicate`` merely wraps its argument and
84
+ remain unevaluated. To evaluate it, use the ``ask()`` function.
85
+
86
+ Examples
87
+ ========
88
+
89
+ >>> from sympy import Q, ask
90
+ >>> Q.integer(1)
91
+ Q.integer(1)
92
+
93
+ The ``function`` attribute returns the predicate, and the ``arguments``
94
+ attribute returns the tuple of arguments.
95
+
96
+ >>> type(Q.integer(1))
97
+ <class 'sympy.assumptions.assume.AppliedPredicate'>
98
+ >>> Q.integer(1).function
99
+ Q.integer
100
+ >>> Q.integer(1).arguments
101
+ (1,)
102
+
103
+ Applied predicates can be evaluated to a boolean value with ``ask``:
104
+
105
+ >>> ask(Q.integer(1))
106
+ True
107
+
108
+ """
109
+ __slots__ = ()
110
+
111
+ def __new__(cls, predicate, *args):
112
+ if not isinstance(predicate, Predicate):
113
+ raise TypeError("%s is not a Predicate." % predicate)
114
+ args = map(_sympify, args)
115
+ return super().__new__(cls, predicate, *args)
116
+
117
+ @property
118
+ def arg(self):
119
+ """
120
+ Return the expression used by this assumption.
121
+
122
+ Examples
123
+ ========
124
+
125
+ >>> from sympy import Q, Symbol
126
+ >>> x = Symbol('x')
127
+ >>> a = Q.integer(x + 1)
128
+ >>> a.arg
129
+ x + 1
130
+
131
+ """
132
+ # Will be deprecated
133
+ args = self._args
134
+ if len(args) == 2:
135
+ # backwards compatibility
136
+ return args[1]
137
+ raise TypeError("'arg' property is allowed only for unary predicates.")
138
+
139
+ @property
140
+ def function(self):
141
+ """
142
+ Return the predicate.
143
+ """
144
+ # Will be changed to self.args[0] after args overriding is removed
145
+ return self._args[0]
146
+
147
+ @property
148
+ def arguments(self):
149
+ """
150
+ Return the arguments which are applied to the predicate.
151
+ """
152
+ # Will be changed to self.args[1:] after args overriding is removed
153
+ return self._args[1:]
154
+
155
+ def _eval_ask(self, assumptions):
156
+ return self.function.eval(self.arguments, assumptions)
157
+
158
+ @property
159
+ def binary_symbols(self):
160
+ from .ask import Q
161
+ if self.function == Q.is_true:
162
+ i = self.arguments[0]
163
+ if i.is_Boolean or i.is_Symbol:
164
+ return i.binary_symbols
165
+ if self.function in (Q.eq, Q.ne):
166
+ if true in self.arguments or false in self.arguments:
167
+ if self.arguments[0].is_Symbol:
168
+ return {self.arguments[0]}
169
+ elif self.arguments[1].is_Symbol:
170
+ return {self.arguments[1]}
171
+ return set()
172
+
173
+
174
+ class PredicateMeta(type):
175
+ def __new__(cls, clsname, bases, dct):
176
+ # If handler is not defined, assign empty dispatcher.
177
+ if "handler" not in dct:
178
+ name = f"Ask{clsname.capitalize()}Handler"
179
+ handler = Dispatcher(name, doc="Handler for key %s" % name)
180
+ dct["handler"] = handler
181
+
182
+ dct["_orig_doc"] = dct.get("__doc__", "")
183
+
184
+ return super().__new__(cls, clsname, bases, dct)
185
+
186
+ @property
187
+ def __doc__(cls):
188
+ handler = cls.handler
189
+ doc = cls._orig_doc
190
+ if cls is not Predicate and handler is not None:
191
+ doc += "Handler\n"
192
+ doc += " =======\n\n"
193
+
194
+ # Append the handler's doc without breaking sphinx documentation.
195
+ docs = [" Multiply dispatched method: %s" % handler.name]
196
+ if handler.doc:
197
+ for line in handler.doc.splitlines():
198
+ if not line:
199
+ continue
200
+ docs.append(" %s" % line)
201
+ other = []
202
+ for sig in handler.ordering[::-1]:
203
+ func = handler.funcs[sig]
204
+ if func.__doc__:
205
+ s = ' Inputs: <%s>' % str_signature(sig)
206
+ lines = []
207
+ for line in func.__doc__.splitlines():
208
+ lines.append(" %s" % line)
209
+ s += "\n".join(lines)
210
+ docs.append(s)
211
+ else:
212
+ other.append(str_signature(sig))
213
+ if other:
214
+ othersig = " Other signatures:"
215
+ for line in other:
216
+ othersig += "\n * %s" % line
217
+ docs.append(othersig)
218
+
219
+ doc += '\n\n'.join(docs)
220
+
221
+ return doc
222
+
223
+
224
+ class Predicate(Boolean, metaclass=PredicateMeta):
225
+ """
226
+ Base class for mathematical predicates. It also serves as a
227
+ constructor for undefined predicate objects.
228
+
229
+ Explanation
230
+ ===========
231
+
232
+ Predicate is a function that returns a boolean value [1].
233
+
234
+ Predicate function is object, and it is instance of predicate class.
235
+ When a predicate is applied to arguments, ``AppliedPredicate``
236
+ instance is returned. This merely wraps the argument and remain
237
+ unevaluated. To obtain the truth value of applied predicate, use the
238
+ function ``ask``.
239
+
240
+ Evaluation of predicate is done by multiple dispatching. You can
241
+ register new handler to the predicate to support new types.
242
+
243
+ Every predicate in SymPy can be accessed via the property of ``Q``.
244
+ For example, ``Q.even`` returns the predicate which checks if the
245
+ argument is even number.
246
+
247
+ To define a predicate which can be evaluated, you must subclass this
248
+ class, make an instance of it, and register it to ``Q``. After then,
249
+ dispatch the handler by argument types.
250
+
251
+ If you directly construct predicate using this class, you will get
252
+ ``UndefinedPredicate`` which cannot be dispatched. This is useful
253
+ when you are building boolean expressions which do not need to be
254
+ evaluated.
255
+
256
+ Examples
257
+ ========
258
+
259
+ Applying and evaluating to boolean value:
260
+
261
+ >>> from sympy import Q, ask
262
+ >>> ask(Q.prime(7))
263
+ True
264
+
265
+ You can define a new predicate by subclassing and dispatching. Here,
266
+ we define a predicate for sexy primes [2] as an example.
267
+
268
+ >>> from sympy import Predicate, Integer
269
+ >>> class SexyPrimePredicate(Predicate):
270
+ ... name = "sexyprime"
271
+ >>> Q.sexyprime = SexyPrimePredicate()
272
+ >>> @Q.sexyprime.register(Integer, Integer)
273
+ ... def _(int1, int2, assumptions):
274
+ ... args = sorted([int1, int2])
275
+ ... if not all(ask(Q.prime(a), assumptions) for a in args):
276
+ ... return False
277
+ ... return args[1] - args[0] == 6
278
+ >>> ask(Q.sexyprime(5, 11))
279
+ True
280
+
281
+ Direct constructing returns ``UndefinedPredicate``, which can be
282
+ applied but cannot be dispatched.
283
+
284
+ >>> from sympy import Predicate, Integer
285
+ >>> Q.P = Predicate("P")
286
+ >>> type(Q.P)
287
+ <class 'sympy.assumptions.assume.UndefinedPredicate'>
288
+ >>> Q.P(1)
289
+ Q.P(1)
290
+ >>> Q.P.register(Integer)(lambda expr, assump: True)
291
+ Traceback (most recent call last):
292
+ ...
293
+ TypeError: <class 'sympy.assumptions.assume.UndefinedPredicate'> cannot be dispatched.
294
+
295
+ References
296
+ ==========
297
+
298
+ .. [1] https://en.wikipedia.org/wiki/Predicate_%28mathematical_logic%29
299
+ .. [2] https://en.wikipedia.org/wiki/Sexy_prime
300
+
301
+ """
302
+
303
+ is_Atom = True
304
+
305
+ def __new__(cls, *args, **kwargs):
306
+ if cls is Predicate:
307
+ return UndefinedPredicate(*args, **kwargs)
308
+ obj = super().__new__(cls, *args)
309
+ return obj
310
+
311
+ @property
312
+ def name(self):
313
+ # May be overridden
314
+ return type(self).__name__
315
+
316
+ @classmethod
317
+ def register(cls, *types, **kwargs):
318
+ """
319
+ Register the signature to the handler.
320
+ """
321
+ if cls.handler is None:
322
+ raise TypeError("%s cannot be dispatched." % type(cls))
323
+ return cls.handler.register(*types, **kwargs)
324
+
325
+ @classmethod
326
+ def register_many(cls, *types, **kwargs):
327
+ """
328
+ Register multiple signatures to same handler.
329
+ """
330
+ def _(func):
331
+ for t in types:
332
+ if not is_sequence(t):
333
+ t = (t,) # for convenience, allow passing `type` to mean `(type,)`
334
+ cls.register(*t, **kwargs)(func)
335
+ return _
336
+
337
+ def __call__(self, *args):
338
+ return AppliedPredicate(self, *args)
339
+
340
+ def eval(self, args, assumptions=True):
341
+ """
342
+ Evaluate ``self(*args)`` under the given assumptions.
343
+
344
+ This uses only direct resolution methods, not logical inference.
345
+ """
346
+ result = None
347
+ try:
348
+ result = self.handler(*args, assumptions=assumptions)
349
+ except NotImplementedError:
350
+ pass
351
+ return result
352
+
353
+ def _eval_refine(self, assumptions):
354
+ # When Predicate is no longer Boolean, delete this method
355
+ return self
356
+
357
+
358
+ class UndefinedPredicate(Predicate):
359
+ """
360
+ Predicate without handler.
361
+
362
+ Explanation
363
+ ===========
364
+
365
+ This predicate is generated by using ``Predicate`` directly for
366
+ construction. It does not have a handler, and evaluating this with
367
+ arguments is done by SAT solver.
368
+
369
+ Examples
370
+ ========
371
+
372
+ >>> from sympy import Predicate, Q
373
+ >>> Q.P = Predicate('P')
374
+ >>> Q.P.func
375
+ <class 'sympy.assumptions.assume.UndefinedPredicate'>
376
+ >>> Q.P.name
377
+ Str('P')
378
+
379
+ """
380
+
381
+ handler = None
382
+
383
+ def __new__(cls, name, handlers=None):
384
+ # "handlers" parameter supports old design
385
+ if not isinstance(name, Str):
386
+ name = Str(name)
387
+ obj = super(Boolean, cls).__new__(cls, name)
388
+ obj.handlers = handlers or []
389
+ return obj
390
+
391
+ @property
392
+ def name(self):
393
+ return self.args[0]
394
+
395
+ def _hashable_content(self):
396
+ return (self.name,)
397
+
398
+ def __getnewargs__(self):
399
+ return (self.name,)
400
+
401
+ def __call__(self, expr):
402
+ return AppliedPredicate(self, expr)
403
+
404
+ def add_handler(self, handler):
405
+ sympy_deprecation_warning(
406
+ """
407
+ The AskHandler system is deprecated. Predicate.add_handler()
408
+ should be replaced with the multipledispatch handler of Predicate.
409
+ """,
410
+ deprecated_since_version="1.8",
411
+ active_deprecations_target='deprecated-askhandler',
412
+ )
413
+ self.handlers.append(handler)
414
+
415
+ def remove_handler(self, handler):
416
+ sympy_deprecation_warning(
417
+ """
418
+ The AskHandler system is deprecated. Predicate.remove_handler()
419
+ should be replaced with the multipledispatch handler of Predicate.
420
+ """,
421
+ deprecated_since_version="1.8",
422
+ active_deprecations_target='deprecated-askhandler',
423
+ )
424
+ self.handlers.remove(handler)
425
+
426
+ def eval(self, args, assumptions=True):
427
+ # Support for deprecated design
428
+ # When old design is removed, this will always return None
429
+ sympy_deprecation_warning(
430
+ """
431
+ The AskHandler system is deprecated. Evaluating UndefinedPredicate
432
+ objects should be replaced with the multipledispatch handler of
433
+ Predicate.
434
+ """,
435
+ deprecated_since_version="1.8",
436
+ active_deprecations_target='deprecated-askhandler',
437
+ stacklevel=5,
438
+ )
439
+ expr, = args
440
+ res, _res = None, None
441
+ mro = inspect.getmro(type(expr))
442
+ for handler in self.handlers:
443
+ cls = get_class(handler)
444
+ for subclass in mro:
445
+ eval_ = getattr(cls, subclass.__name__, None)
446
+ if eval_ is None:
447
+ continue
448
+ res = eval_(expr, assumptions)
449
+ # Do not stop if value returned is None
450
+ # Try to check for higher classes
451
+ if res is None:
452
+ continue
453
+ if _res is None:
454
+ _res = res
455
+ else:
456
+ # only check consistency if both resolutors have concluded
457
+ if _res != res:
458
+ raise ValueError('incompatible resolutors')
459
+ break
460
+ return res
461
+
462
+
463
+ @contextmanager
464
+ def assuming(*assumptions):
465
+ """
466
+ Context manager for assumptions.
467
+
468
+ Examples
469
+ ========
470
+
471
+ >>> from sympy import assuming, Q, ask
472
+ >>> from sympy.abc import x, y
473
+ >>> print(ask(Q.integer(x + y)))
474
+ None
475
+ >>> with assuming(Q.integer(x), Q.integer(y)):
476
+ ... print(ask(Q.integer(x + y)))
477
+ True
478
+ """
479
+ old_global_assumptions = global_assumptions.copy()
480
+ global_assumptions.update(assumptions)
481
+ try:
482
+ yield
483
+ finally:
484
+ global_assumptions.clear()
485
+ global_assumptions.update(old_global_assumptions)
.venv/lib/python3.10/site-packages/sympy/assumptions/cnf.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The classes used here are for the internal use of assumptions system
3
+ only and should not be used anywhere else as these do not possess the
4
+ signatures common to SymPy objects. For general use of logic constructs
5
+ please refer to sympy.logic classes And, Or, Not, etc.
6
+ """
7
+ from itertools import combinations, product, zip_longest
8
+ from sympy.assumptions.assume import AppliedPredicate, Predicate
9
+ from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le
10
+ from sympy.core.singleton import S
11
+ from sympy.logic.boolalg import Or, And, Not, Xnor
12
+ from sympy.logic.boolalg import (Equivalent, ITE, Implies, Nand, Nor, Xor)
13
+
14
+
15
+ class Literal:
16
+ """
17
+ The smallest element of a CNF object.
18
+
19
+ Parameters
20
+ ==========
21
+
22
+ lit : Boolean expression
23
+
24
+ is_Not : bool
25
+
26
+ Examples
27
+ ========
28
+
29
+ >>> from sympy import Q
30
+ >>> from sympy.assumptions.cnf import Literal
31
+ >>> from sympy.abc import x
32
+ >>> Literal(Q.even(x))
33
+ Literal(Q.even(x), False)
34
+ >>> Literal(~Q.even(x))
35
+ Literal(Q.even(x), True)
36
+ """
37
+
38
+ def __new__(cls, lit, is_Not=False):
39
+ if isinstance(lit, Not):
40
+ lit = lit.args[0]
41
+ is_Not = True
42
+ elif isinstance(lit, (AND, OR, Literal)):
43
+ return ~lit if is_Not else lit
44
+ obj = super().__new__(cls)
45
+ obj.lit = lit
46
+ obj.is_Not = is_Not
47
+ return obj
48
+
49
+ @property
50
+ def arg(self):
51
+ return self.lit
52
+
53
+ def rcall(self, expr):
54
+ if callable(self.lit):
55
+ lit = self.lit(expr)
56
+ else:
57
+ lit = self.lit.apply(expr)
58
+ return type(self)(lit, self.is_Not)
59
+
60
+ def __invert__(self):
61
+ is_Not = not self.is_Not
62
+ return Literal(self.lit, is_Not)
63
+
64
+ def __str__(self):
65
+ return '{}({}, {})'.format(type(self).__name__, self.lit, self.is_Not)
66
+
67
+ __repr__ = __str__
68
+
69
+ def __eq__(self, other):
70
+ return self.arg == other.arg and self.is_Not == other.is_Not
71
+
72
+ def __hash__(self):
73
+ h = hash((type(self).__name__, self.arg, self.is_Not))
74
+ return h
75
+
76
+
77
+ class OR:
78
+ """
79
+ A low-level implementation for Or
80
+ """
81
+ def __init__(self, *args):
82
+ self._args = args
83
+
84
+ @property
85
+ def args(self):
86
+ return sorted(self._args, key=str)
87
+
88
+ def rcall(self, expr):
89
+ return type(self)(*[arg.rcall(expr)
90
+ for arg in self._args
91
+ ])
92
+
93
+ def __invert__(self):
94
+ return AND(*[~arg for arg in self._args])
95
+
96
+ def __hash__(self):
97
+ return hash((type(self).__name__,) + tuple(self.args))
98
+
99
+ def __eq__(self, other):
100
+ return self.args == other.args
101
+
102
+ def __str__(self):
103
+ s = '(' + ' | '.join([str(arg) for arg in self.args]) + ')'
104
+ return s
105
+
106
+ __repr__ = __str__
107
+
108
+
109
+ class AND:
110
+ """
111
+ A low-level implementation for And
112
+ """
113
+ def __init__(self, *args):
114
+ self._args = args
115
+
116
+ def __invert__(self):
117
+ return OR(*[~arg for arg in self._args])
118
+
119
+ @property
120
+ def args(self):
121
+ return sorted(self._args, key=str)
122
+
123
+ def rcall(self, expr):
124
+ return type(self)(*[arg.rcall(expr)
125
+ for arg in self._args
126
+ ])
127
+
128
+ def __hash__(self):
129
+ return hash((type(self).__name__,) + tuple(self.args))
130
+
131
+ def __eq__(self, other):
132
+ return self.args == other.args
133
+
134
+ def __str__(self):
135
+ s = '('+' & '.join([str(arg) for arg in self.args])+')'
136
+ return s
137
+
138
+ __repr__ = __str__
139
+
140
+
141
+ def to_NNF(expr, composite_map=None):
142
+ """
143
+ Generates the Negation Normal Form of any boolean expression in terms
144
+ of AND, OR, and Literal objects.
145
+
146
+ Examples
147
+ ========
148
+
149
+ >>> from sympy import Q, Eq
150
+ >>> from sympy.assumptions.cnf import to_NNF
151
+ >>> from sympy.abc import x, y
152
+ >>> expr = Q.even(x) & ~Q.positive(x)
153
+ >>> to_NNF(expr)
154
+ (Literal(Q.even(x), False) & Literal(Q.positive(x), True))
155
+
156
+ Supported boolean objects are converted to corresponding predicates.
157
+
158
+ >>> to_NNF(Eq(x, y))
159
+ Literal(Q.eq(x, y), False)
160
+
161
+ If ``composite_map`` argument is given, ``to_NNF`` decomposes the
162
+ specified predicate into a combination of primitive predicates.
163
+
164
+ >>> cmap = {Q.nonpositive: Q.negative | Q.zero}
165
+ >>> to_NNF(Q.nonpositive, cmap)
166
+ (Literal(Q.negative, False) | Literal(Q.zero, False))
167
+ >>> to_NNF(Q.nonpositive(x), cmap)
168
+ (Literal(Q.negative(x), False) | Literal(Q.zero(x), False))
169
+ """
170
+ from sympy.assumptions.ask import Q
171
+
172
+ if composite_map is None:
173
+ composite_map = {}
174
+
175
+
176
+ binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le}
177
+ if type(expr) in binrelpreds:
178
+ pred = binrelpreds[type(expr)]
179
+ expr = pred(*expr.args)
180
+
181
+ if isinstance(expr, Not):
182
+ arg = expr.args[0]
183
+ tmp = to_NNF(arg, composite_map) # Strategy: negate the NNF of expr
184
+ return ~tmp
185
+
186
+ if isinstance(expr, Or):
187
+ return OR(*[to_NNF(x, composite_map) for x in Or.make_args(expr)])
188
+
189
+ if isinstance(expr, And):
190
+ return AND(*[to_NNF(x, composite_map) for x in And.make_args(expr)])
191
+
192
+ if isinstance(expr, Nand):
193
+ tmp = AND(*[to_NNF(x, composite_map) for x in expr.args])
194
+ return ~tmp
195
+
196
+ if isinstance(expr, Nor):
197
+ tmp = OR(*[to_NNF(x, composite_map) for x in expr.args])
198
+ return ~tmp
199
+
200
+ if isinstance(expr, Xor):
201
+ cnfs = []
202
+ for i in range(0, len(expr.args) + 1, 2):
203
+ for neg in combinations(expr.args, i):
204
+ clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map)
205
+ for s in expr.args]
206
+ cnfs.append(OR(*clause))
207
+ return AND(*cnfs)
208
+
209
+ if isinstance(expr, Xnor):
210
+ cnfs = []
211
+ for i in range(0, len(expr.args) + 1, 2):
212
+ for neg in combinations(expr.args, i):
213
+ clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map)
214
+ for s in expr.args]
215
+ cnfs.append(OR(*clause))
216
+ return ~AND(*cnfs)
217
+
218
+ if isinstance(expr, Implies):
219
+ L, R = to_NNF(expr.args[0], composite_map), to_NNF(expr.args[1], composite_map)
220
+ return OR(~L, R)
221
+
222
+ if isinstance(expr, Equivalent):
223
+ cnfs = []
224
+ for a, b in zip_longest(expr.args, expr.args[1:], fillvalue=expr.args[0]):
225
+ a = to_NNF(a, composite_map)
226
+ b = to_NNF(b, composite_map)
227
+ cnfs.append(OR(~a, b))
228
+ return AND(*cnfs)
229
+
230
+ if isinstance(expr, ITE):
231
+ L = to_NNF(expr.args[0], composite_map)
232
+ M = to_NNF(expr.args[1], composite_map)
233
+ R = to_NNF(expr.args[2], composite_map)
234
+ return AND(OR(~L, M), OR(L, R))
235
+
236
+ if isinstance(expr, AppliedPredicate):
237
+ pred, args = expr.function, expr.arguments
238
+ newpred = composite_map.get(pred, None)
239
+ if newpred is not None:
240
+ return to_NNF(newpred.rcall(*args), composite_map)
241
+
242
+ if isinstance(expr, Predicate):
243
+ newpred = composite_map.get(expr, None)
244
+ if newpred is not None:
245
+ return to_NNF(newpred, composite_map)
246
+
247
+ return Literal(expr)
248
+
249
+
250
+ def distribute_AND_over_OR(expr):
251
+ """
252
+ Distributes AND over OR in the NNF expression.
253
+ Returns the result( Conjunctive Normal Form of expression)
254
+ as a CNF object.
255
+ """
256
+ if not isinstance(expr, (AND, OR)):
257
+ tmp = set()
258
+ tmp.add(frozenset((expr,)))
259
+ return CNF(tmp)
260
+
261
+ if isinstance(expr, OR):
262
+ return CNF.all_or(*[distribute_AND_over_OR(arg)
263
+ for arg in expr._args])
264
+
265
+ if isinstance(expr, AND):
266
+ return CNF.all_and(*[distribute_AND_over_OR(arg)
267
+ for arg in expr._args])
268
+
269
+
270
+ class CNF:
271
+ """
272
+ Class to represent CNF of a Boolean expression.
273
+ Consists of set of clauses, which themselves are stored as
274
+ frozenset of Literal objects.
275
+
276
+ Examples
277
+ ========
278
+
279
+ >>> from sympy import Q
280
+ >>> from sympy.assumptions.cnf import CNF
281
+ >>> from sympy.abc import x
282
+ >>> cnf = CNF.from_prop(Q.real(x) & ~Q.zero(x))
283
+ >>> cnf.clauses
284
+ {frozenset({Literal(Q.zero(x), True)}),
285
+ frozenset({Literal(Q.negative(x), False),
286
+ Literal(Q.positive(x), False), Literal(Q.zero(x), False)})}
287
+ """
288
+ def __init__(self, clauses=None):
289
+ if not clauses:
290
+ clauses = set()
291
+ self.clauses = clauses
292
+
293
+ def add(self, prop):
294
+ clauses = CNF.to_CNF(prop).clauses
295
+ self.add_clauses(clauses)
296
+
297
+ def __str__(self):
298
+ s = ' & '.join(
299
+ ['(' + ' | '.join([str(lit) for lit in clause]) +')'
300
+ for clause in self.clauses]
301
+ )
302
+ return s
303
+
304
+ def extend(self, props):
305
+ for p in props:
306
+ self.add(p)
307
+ return self
308
+
309
+ def copy(self):
310
+ return CNF(set(self.clauses))
311
+
312
+ def add_clauses(self, clauses):
313
+ self.clauses |= clauses
314
+
315
+ @classmethod
316
+ def from_prop(cls, prop):
317
+ res = cls()
318
+ res.add(prop)
319
+ return res
320
+
321
+ def __iand__(self, other):
322
+ self.add_clauses(other.clauses)
323
+ return self
324
+
325
+ def all_predicates(self):
326
+ predicates = set()
327
+ for c in self.clauses:
328
+ predicates |= {arg.lit for arg in c}
329
+ return predicates
330
+
331
+ def _or(self, cnf):
332
+ clauses = set()
333
+ for a, b in product(self.clauses, cnf.clauses):
334
+ tmp = set(a)
335
+ tmp.update(b)
336
+ clauses.add(frozenset(tmp))
337
+ return CNF(clauses)
338
+
339
+ def _and(self, cnf):
340
+ clauses = self.clauses.union(cnf.clauses)
341
+ return CNF(clauses)
342
+
343
+ def _not(self):
344
+ clss = list(self.clauses)
345
+ ll = {frozenset((~x,)) for x in clss[-1]}
346
+ ll = CNF(ll)
347
+
348
+ for rest in clss[:-1]:
349
+ p = {frozenset((~x,)) for x in rest}
350
+ ll = ll._or(CNF(p))
351
+ return ll
352
+
353
+ def rcall(self, expr):
354
+ clause_list = []
355
+ for clause in self.clauses:
356
+ lits = [arg.rcall(expr) for arg in clause]
357
+ clause_list.append(OR(*lits))
358
+ expr = AND(*clause_list)
359
+ return distribute_AND_over_OR(expr)
360
+
361
+ @classmethod
362
+ def all_or(cls, *cnfs):
363
+ b = cnfs[0].copy()
364
+ for rest in cnfs[1:]:
365
+ b = b._or(rest)
366
+ return b
367
+
368
+ @classmethod
369
+ def all_and(cls, *cnfs):
370
+ b = cnfs[0].copy()
371
+ for rest in cnfs[1:]:
372
+ b = b._and(rest)
373
+ return b
374
+
375
+ @classmethod
376
+ def to_CNF(cls, expr):
377
+ from sympy.assumptions.facts import get_composite_predicates
378
+ expr = to_NNF(expr, get_composite_predicates())
379
+ expr = distribute_AND_over_OR(expr)
380
+ return expr
381
+
382
+ @classmethod
383
+ def CNF_to_cnf(cls, cnf):
384
+ """
385
+ Converts CNF object to SymPy's boolean expression
386
+ retaining the form of expression.
387
+ """
388
+ def remove_literal(arg):
389
+ return Not(arg.lit) if arg.is_Not else arg.lit
390
+
391
+ return And(*(Or(*(remove_literal(arg) for arg in clause)) for clause in cnf.clauses))
392
+
393
+
394
+ class EncodedCNF:
395
+ """
396
+ Class for encoding the CNF expression.
397
+ """
398
+ def __init__(self, data=None, encoding=None):
399
+ if not data and not encoding:
400
+ data = []
401
+ encoding = {}
402
+ self.data = data
403
+ self.encoding = encoding
404
+ self._symbols = list(encoding.keys())
405
+
406
+ def from_cnf(self, cnf):
407
+ self._symbols = list(cnf.all_predicates())
408
+ n = len(self._symbols)
409
+ self.encoding = dict(zip(self._symbols, range(1, n + 1)))
410
+ self.data = [self.encode(clause) for clause in cnf.clauses]
411
+
412
+ @property
413
+ def symbols(self):
414
+ return self._symbols
415
+
416
+ @property
417
+ def variables(self):
418
+ return range(1, len(self._symbols) + 1)
419
+
420
+ def copy(self):
421
+ new_data = [set(clause) for clause in self.data]
422
+ return EncodedCNF(new_data, dict(self.encoding))
423
+
424
+ def add_prop(self, prop):
425
+ cnf = CNF.from_prop(prop)
426
+ self.add_from_cnf(cnf)
427
+
428
+ def add_from_cnf(self, cnf):
429
+ clauses = [self.encode(clause) for clause in cnf.clauses]
430
+ self.data += clauses
431
+
432
+ def encode_arg(self, arg):
433
+ literal = arg.lit
434
+ value = self.encoding.get(literal, None)
435
+ if value is None:
436
+ n = len(self._symbols)
437
+ self._symbols.append(literal)
438
+ value = self.encoding[literal] = n + 1
439
+ if arg.is_Not:
440
+ return -value
441
+ else:
442
+ return value
443
+
444
+ def encode(self, clause):
445
+ return {self.encode_arg(arg) if not arg.lit == S.false else 0 for arg in clause}
.venv/lib/python3.10/site-packages/sympy/assumptions/facts.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Known facts in assumptions module.
3
+
4
+ This module defines the facts between unary predicates in ``get_known_facts()``,
5
+ and supports functions to generate the contents in
6
+ ``sympy.assumptions.ask_generated`` file.
7
+ """
8
+
9
+ from sympy.assumptions.ask import Q
10
+ from sympy.assumptions.assume import AppliedPredicate
11
+ from sympy.core.cache import cacheit
12
+ from sympy.core.symbol import Symbol
13
+ from sympy.logic.boolalg import (to_cnf, And, Not, Implies, Equivalent,
14
+ Exclusive,)
15
+ from sympy.logic.inference import satisfiable
16
+
17
+
18
+ @cacheit
19
+ def get_composite_predicates():
20
+ # To reduce the complexity of sat solver, these predicates are
21
+ # transformed into the combination of primitive predicates.
22
+ return {
23
+ Q.real : Q.negative | Q.zero | Q.positive,
24
+ Q.integer : Q.even | Q.odd,
25
+ Q.nonpositive : Q.negative | Q.zero,
26
+ Q.nonzero : Q.negative | Q.positive,
27
+ Q.nonnegative : Q.zero | Q.positive,
28
+ Q.extended_real : Q.negative_infinite | Q.negative | Q.zero | Q.positive | Q.positive_infinite,
29
+ Q.extended_positive: Q.positive | Q.positive_infinite,
30
+ Q.extended_negative: Q.negative | Q.negative_infinite,
31
+ Q.extended_nonzero: Q.negative_infinite | Q.negative | Q.positive | Q.positive_infinite,
32
+ Q.extended_nonpositive: Q.negative_infinite | Q.negative | Q.zero,
33
+ Q.extended_nonnegative: Q.zero | Q.positive | Q.positive_infinite,
34
+ Q.complex : Q.algebraic | Q.transcendental
35
+ }
36
+
37
+
38
+ @cacheit
39
+ def get_known_facts(x=None):
40
+ """
41
+ Facts between unary predicates.
42
+
43
+ Parameters
44
+ ==========
45
+
46
+ x : Symbol, optional
47
+ Placeholder symbol for unary facts. Default is ``Symbol('x')``.
48
+
49
+ Returns
50
+ =======
51
+
52
+ fact : Known facts in conjugated normal form.
53
+
54
+ """
55
+ if x is None:
56
+ x = Symbol('x')
57
+
58
+ fact = And(
59
+ get_number_facts(x),
60
+ get_matrix_facts(x)
61
+ )
62
+ return fact
63
+
64
+
65
+ @cacheit
66
+ def get_number_facts(x = None):
67
+ """
68
+ Facts between unary number predicates.
69
+
70
+ Parameters
71
+ ==========
72
+
73
+ x : Symbol, optional
74
+ Placeholder symbol for unary facts. Default is ``Symbol('x')``.
75
+
76
+ Returns
77
+ =======
78
+
79
+ fact : Known facts in conjugated normal form.
80
+
81
+ """
82
+ if x is None:
83
+ x = Symbol('x')
84
+
85
+ fact = And(
86
+ # primitive predicates for extended real exclude each other.
87
+ Exclusive(Q.negative_infinite(x), Q.negative(x), Q.zero(x),
88
+ Q.positive(x), Q.positive_infinite(x)),
89
+
90
+ # build complex plane
91
+ Exclusive(Q.real(x), Q.imaginary(x)),
92
+ Implies(Q.real(x) | Q.imaginary(x), Q.complex(x)),
93
+
94
+ # other subsets of complex
95
+ Exclusive(Q.transcendental(x), Q.algebraic(x)),
96
+ Equivalent(Q.real(x), Q.rational(x) | Q.irrational(x)),
97
+ Exclusive(Q.irrational(x), Q.rational(x)),
98
+ Implies(Q.rational(x), Q.algebraic(x)),
99
+
100
+ # integers
101
+ Exclusive(Q.even(x), Q.odd(x)),
102
+ Implies(Q.integer(x), Q.rational(x)),
103
+ Implies(Q.zero(x), Q.even(x)),
104
+ Exclusive(Q.composite(x), Q.prime(x)),
105
+ Implies(Q.composite(x) | Q.prime(x), Q.integer(x) & Q.positive(x)),
106
+ Implies(Q.even(x) & Q.positive(x) & ~Q.prime(x), Q.composite(x)),
107
+
108
+ # hermitian and antihermitian
109
+ Implies(Q.real(x), Q.hermitian(x)),
110
+ Implies(Q.imaginary(x), Q.antihermitian(x)),
111
+ Implies(Q.zero(x), Q.hermitian(x) | Q.antihermitian(x)),
112
+
113
+ # define finity and infinity, and build extended real line
114
+ Exclusive(Q.infinite(x), Q.finite(x)),
115
+ Implies(Q.complex(x), Q.finite(x)),
116
+ Implies(Q.negative_infinite(x) | Q.positive_infinite(x), Q.infinite(x)),
117
+
118
+ # commutativity
119
+ Implies(Q.finite(x) | Q.infinite(x), Q.commutative(x)),
120
+ )
121
+ return fact
122
+
123
+
124
+ @cacheit
125
+ def get_matrix_facts(x = None):
126
+ """
127
+ Facts between unary matrix predicates.
128
+
129
+ Parameters
130
+ ==========
131
+
132
+ x : Symbol, optional
133
+ Placeholder symbol for unary facts. Default is ``Symbol('x')``.
134
+
135
+ Returns
136
+ =======
137
+
138
+ fact : Known facts in conjugated normal form.
139
+
140
+ """
141
+ if x is None:
142
+ x = Symbol('x')
143
+
144
+ fact = And(
145
+ # matrices
146
+ Implies(Q.orthogonal(x), Q.positive_definite(x)),
147
+ Implies(Q.orthogonal(x), Q.unitary(x)),
148
+ Implies(Q.unitary(x) & Q.real_elements(x), Q.orthogonal(x)),
149
+ Implies(Q.unitary(x), Q.normal(x)),
150
+ Implies(Q.unitary(x), Q.invertible(x)),
151
+ Implies(Q.normal(x), Q.square(x)),
152
+ Implies(Q.diagonal(x), Q.normal(x)),
153
+ Implies(Q.positive_definite(x), Q.invertible(x)),
154
+ Implies(Q.diagonal(x), Q.upper_triangular(x)),
155
+ Implies(Q.diagonal(x), Q.lower_triangular(x)),
156
+ Implies(Q.lower_triangular(x), Q.triangular(x)),
157
+ Implies(Q.upper_triangular(x), Q.triangular(x)),
158
+ Implies(Q.triangular(x), Q.upper_triangular(x) | Q.lower_triangular(x)),
159
+ Implies(Q.upper_triangular(x) & Q.lower_triangular(x), Q.diagonal(x)),
160
+ Implies(Q.diagonal(x), Q.symmetric(x)),
161
+ Implies(Q.unit_triangular(x), Q.triangular(x)),
162
+ Implies(Q.invertible(x), Q.fullrank(x)),
163
+ Implies(Q.invertible(x), Q.square(x)),
164
+ Implies(Q.symmetric(x), Q.square(x)),
165
+ Implies(Q.fullrank(x) & Q.square(x), Q.invertible(x)),
166
+ Equivalent(Q.invertible(x), ~Q.singular(x)),
167
+ Implies(Q.integer_elements(x), Q.real_elements(x)),
168
+ Implies(Q.real_elements(x), Q.complex_elements(x)),
169
+ )
170
+ return fact
171
+
172
+
173
+
174
+ def generate_known_facts_dict(keys, fact):
175
+ """
176
+ Computes and returns a dictionary which contains the relations between
177
+ unary predicates.
178
+
179
+ Each key is a predicate, and item is two groups of predicates.
180
+ First group contains the predicates which are implied by the key, and
181
+ second group contains the predicates which are rejected by the key.
182
+
183
+ All predicates in *keys* and *fact* must be unary and have same placeholder
184
+ symbol.
185
+
186
+ Parameters
187
+ ==========
188
+
189
+ keys : list of AppliedPredicate instances.
190
+
191
+ fact : Fact between predicates in conjugated normal form.
192
+
193
+ Examples
194
+ ========
195
+
196
+ >>> from sympy import Q, And, Implies
197
+ >>> from sympy.assumptions.facts import generate_known_facts_dict
198
+ >>> from sympy.abc import x
199
+ >>> keys = [Q.even(x), Q.odd(x), Q.zero(x)]
200
+ >>> fact = And(Implies(Q.even(x), ~Q.odd(x)),
201
+ ... Implies(Q.zero(x), Q.even(x)))
202
+ >>> generate_known_facts_dict(keys, fact)
203
+ {Q.even: ({Q.even}, {Q.odd}),
204
+ Q.odd: ({Q.odd}, {Q.even, Q.zero}),
205
+ Q.zero: ({Q.even, Q.zero}, {Q.odd})}
206
+ """
207
+ fact_cnf = to_cnf(fact)
208
+ mapping = single_fact_lookup(keys, fact_cnf)
209
+
210
+ ret = {}
211
+ for key, value in mapping.items():
212
+ implied = set()
213
+ rejected = set()
214
+ for expr in value:
215
+ if isinstance(expr, AppliedPredicate):
216
+ implied.add(expr.function)
217
+ elif isinstance(expr, Not):
218
+ pred = expr.args[0]
219
+ rejected.add(pred.function)
220
+ ret[key.function] = (implied, rejected)
221
+ return ret
222
+
223
+
224
+ @cacheit
225
+ def get_known_facts_keys():
226
+ """
227
+ Return every unary predicates registered to ``Q``.
228
+
229
+ This function is used to generate the keys for
230
+ ``generate_known_facts_dict``.
231
+
232
+ """
233
+ # exclude polyadic predicates
234
+ exclude = {Q.eq, Q.ne, Q.gt, Q.lt, Q.ge, Q.le}
235
+
236
+ result = []
237
+ for attr in Q.__class__.__dict__:
238
+ if attr.startswith('__'):
239
+ continue
240
+ pred = getattr(Q, attr)
241
+ if pred in exclude:
242
+ continue
243
+ result.append(pred)
244
+ return result
245
+
246
+
247
+ def single_fact_lookup(known_facts_keys, known_facts_cnf):
248
+ # Return the dictionary for quick lookup of single fact
249
+ mapping = {}
250
+ for key in known_facts_keys:
251
+ mapping[key] = {key}
252
+ for other_key in known_facts_keys:
253
+ if other_key != key:
254
+ if ask_full_inference(other_key, key, known_facts_cnf):
255
+ mapping[key].add(other_key)
256
+ if ask_full_inference(~other_key, key, known_facts_cnf):
257
+ mapping[key].add(~other_key)
258
+ return mapping
259
+
260
+
261
+ def ask_full_inference(proposition, assumptions, known_facts_cnf):
262
+ """
263
+ Method for inferring properties about objects.
264
+
265
+ """
266
+ if not satisfiable(And(known_facts_cnf, assumptions, proposition)):
267
+ return False
268
+ if not satisfiable(And(known_facts_cnf, assumptions, Not(proposition))):
269
+ return True
270
+ return None
.venv/lib/python3.10/site-packages/sympy/assumptions/handlers/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Multipledispatch handlers for ``Predicate`` are implemented here.
3
+ Handlers in this module are not directly imported to other modules in
4
+ order to avoid circular import problem.
5
+ """
6
+
7
+ from .common import (AskHandler, CommonHandler,
8
+ test_closed_group)
9
+
10
+ __all__ = [
11
+ 'AskHandler', 'CommonHandler',
12
+ 'test_closed_group'
13
+ ]
.venv/lib/python3.10/site-packages/sympy/assumptions/handlers/calculus.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module contains query handlers responsible for calculus queries:
3
+ infinitesimal, finite, etc.
4
+ """
5
+
6
+ from sympy.assumptions import Q, ask
7
+ from sympy.core import Expr, Add, Mul, Pow, Symbol
8
+ from sympy.core.numbers import (NegativeInfinity, GoldenRatio,
9
+ Infinity, Exp1, ComplexInfinity, ImaginaryUnit, NaN, Number, Pi, E,
10
+ TribonacciConstant)
11
+ from sympy.functions import cos, exp, log, sign, sin
12
+ from sympy.logic.boolalg import conjuncts
13
+
14
+ from ..predicates.calculus import (FinitePredicate, InfinitePredicate,
15
+ PositiveInfinitePredicate, NegativeInfinitePredicate)
16
+
17
+
18
+ # FinitePredicate
19
+
20
+
21
+ @FinitePredicate.register(Symbol)
22
+ def _(expr, assumptions):
23
+ """
24
+ Handles Symbol.
25
+ """
26
+ if expr.is_finite is not None:
27
+ return expr.is_finite
28
+ if Q.finite(expr) in conjuncts(assumptions):
29
+ return True
30
+ return None
31
+
32
+ @FinitePredicate.register(Add)
33
+ def _(expr, assumptions):
34
+ """
35
+ Return True if expr is bounded, False if not and None if unknown.
36
+
37
+ Truth Table:
38
+
39
+ +-------+-----+-----------+-----------+
40
+ | | | | |
41
+ | | B | U | ? |
42
+ | | | | |
43
+ +-------+-----+---+---+---+---+---+---+
44
+ | | | | | | | | |
45
+ | | |'+'|'-'|'x'|'+'|'-'|'x'|
46
+ | | | | | | | | |
47
+ +-------+-----+---+---+---+---+---+---+
48
+ | | | | |
49
+ | B | B | U | ? |
50
+ | | | | |
51
+ +---+---+-----+---+---+---+---+---+---+
52
+ | | | | | | | | | |
53
+ | |'+'| | U | ? | ? | U | ? | ? |
54
+ | | | | | | | | | |
55
+ | +---+-----+---+---+---+---+---+---+
56
+ | | | | | | | | | |
57
+ | U |'-'| | ? | U | ? | ? | U | ? |
58
+ | | | | | | | | | |
59
+ | +---+-----+---+---+---+---+---+---+
60
+ | | | | | |
61
+ | |'x'| | ? | ? |
62
+ | | | | | |
63
+ +---+---+-----+---+---+---+---+---+---+
64
+ | | | | |
65
+ | ? | | | ? |
66
+ | | | | |
67
+ +-------+-----+-----------+---+---+---+
68
+
69
+ * 'B' = Bounded
70
+
71
+ * 'U' = Unbounded
72
+
73
+ * '?' = unknown boundedness
74
+
75
+ * '+' = positive sign
76
+
77
+ * '-' = negative sign
78
+
79
+ * 'x' = sign unknown
80
+
81
+ * All Bounded -> True
82
+
83
+ * 1 Unbounded and the rest Bounded -> False
84
+
85
+ * >1 Unbounded, all with same known sign -> False
86
+
87
+ * Any Unknown and unknown sign -> None
88
+
89
+ * Else -> None
90
+
91
+ When the signs are not the same you can have an undefined
92
+ result as in oo - oo, hence 'bounded' is also undefined.
93
+ """
94
+ sign = -1 # sign of unknown or infinite
95
+ result = True
96
+ for arg in expr.args:
97
+ _bounded = ask(Q.finite(arg), assumptions)
98
+ if _bounded:
99
+ continue
100
+ s = ask(Q.extended_positive(arg), assumptions)
101
+ # if there has been more than one sign or if the sign of this arg
102
+ # is None and Bounded is None or there was already
103
+ # an unknown sign, return None
104
+ if sign != -1 and s != sign or \
105
+ s is None and None in (_bounded, sign):
106
+ return None
107
+ else:
108
+ sign = s
109
+ # once False, do not change
110
+ if result is not False:
111
+ result = _bounded
112
+ return result
113
+
114
+ @FinitePredicate.register(Mul)
115
+ def _(expr, assumptions):
116
+ """
117
+ Return True if expr is bounded, False if not and None if unknown.
118
+
119
+ Truth Table:
120
+
121
+ +---+---+---+--------+
122
+ | | | | |
123
+ | | B | U | ? |
124
+ | | | | |
125
+ +---+---+---+---+----+
126
+ | | | | | |
127
+ | | | | s | /s |
128
+ | | | | | |
129
+ +---+---+---+---+----+
130
+ | | | | |
131
+ | B | B | U | ? |
132
+ | | | | |
133
+ +---+---+---+---+----+
134
+ | | | | | |
135
+ | U | | U | U | ? |
136
+ | | | | | |
137
+ +---+---+---+---+----+
138
+ | | | | |
139
+ | ? | | | ? |
140
+ | | | | |
141
+ +---+---+---+---+----+
142
+
143
+ * B = Bounded
144
+
145
+ * U = Unbounded
146
+
147
+ * ? = unknown boundedness
148
+
149
+ * s = signed (hence nonzero)
150
+
151
+ * /s = not signed
152
+ """
153
+ result = True
154
+ possible_zero = False
155
+ for arg in expr.args:
156
+ _bounded = ask(Q.finite(arg), assumptions)
157
+ if _bounded:
158
+ if ask(Q.zero(arg), assumptions) is not False:
159
+ if result is False:
160
+ return None
161
+ possible_zero = True
162
+ elif _bounded is None:
163
+ if result is None:
164
+ return None
165
+ if ask(Q.extended_nonzero(arg), assumptions) is None:
166
+ return None
167
+ if result is not False:
168
+ result = None
169
+ else:
170
+ if possible_zero:
171
+ return None
172
+ result = False
173
+ return result
174
+
175
+ @FinitePredicate.register(Pow)
176
+ def _(expr, assumptions):
177
+ """
178
+ * Unbounded ** NonZero -> Unbounded
179
+
180
+ * Bounded ** Bounded -> Bounded
181
+
182
+ * Abs()<=1 ** Positive -> Bounded
183
+
184
+ * Abs()>=1 ** Negative -> Bounded
185
+
186
+ * Otherwise unknown
187
+ """
188
+ if expr.base == E:
189
+ return ask(Q.finite(expr.exp), assumptions)
190
+
191
+ base_bounded = ask(Q.finite(expr.base), assumptions)
192
+ exp_bounded = ask(Q.finite(expr.exp), assumptions)
193
+ if base_bounded is None and exp_bounded is None: # Common Case
194
+ return None
195
+ if base_bounded is False and ask(Q.extended_nonzero(expr.exp), assumptions):
196
+ return False
197
+ if base_bounded and exp_bounded:
198
+ is_base_zero = ask(Q.zero(expr.base),assumptions)
199
+ is_exp_negative = ask(Q.negative(expr.exp),assumptions)
200
+ if is_base_zero is True and is_exp_negative is True:
201
+ return False
202
+ if is_base_zero is not False and is_exp_negative is not False:
203
+ return None
204
+ return True
205
+ if (abs(expr.base) <= 1) == True and ask(Q.extended_positive(expr.exp), assumptions):
206
+ return True
207
+ if (abs(expr.base) >= 1) == True and ask(Q.extended_negative(expr.exp), assumptions):
208
+ return True
209
+ if (abs(expr.base) >= 1) == True and exp_bounded is False:
210
+ return False
211
+ return None
212
+
213
+ @FinitePredicate.register(exp)
214
+ def _(expr, assumptions):
215
+ return ask(Q.finite(expr.exp), assumptions)
216
+
217
+ @FinitePredicate.register(log)
218
+ def _(expr, assumptions):
219
+ # After complex -> finite fact is registered to new assumption system,
220
+ # querying Q.infinite may be removed.
221
+ if ask(Q.infinite(expr.args[0]), assumptions):
222
+ return False
223
+ return ask(~Q.zero(expr.args[0]), assumptions)
224
+
225
+ @FinitePredicate.register_many(cos, sin, Number, Pi, Exp1, GoldenRatio,
226
+ TribonacciConstant, ImaginaryUnit, sign)
227
+ def _(expr, assumptions):
228
+ return True
229
+
230
+ @FinitePredicate.register_many(ComplexInfinity, Infinity, NegativeInfinity)
231
+ def _(expr, assumptions):
232
+ return False
233
+
234
+ @FinitePredicate.register(NaN)
235
+ def _(expr, assumptions):
236
+ return None
237
+
238
+
239
+ # InfinitePredicate
240
+
241
+
242
+ @InfinitePredicate.register(Expr)
243
+ def _(expr, assumptions):
244
+ is_finite = Q.finite(expr)._eval_ask(assumptions)
245
+ if is_finite is None:
246
+ return None
247
+ return not is_finite
248
+
249
+
250
+ # PositiveInfinitePredicate
251
+
252
+
253
+ @PositiveInfinitePredicate.register(Infinity)
254
+ def _(expr, assumptions):
255
+ return True
256
+
257
+
258
+ @PositiveInfinitePredicate.register_many(NegativeInfinity, ComplexInfinity)
259
+ def _(expr, assumptions):
260
+ return False
261
+
262
+
263
+ # NegativeInfinitePredicate
264
+
265
+
266
+ @NegativeInfinitePredicate.register(NegativeInfinity)
267
+ def _(expr, assumptions):
268
+ return True
269
+
270
+
271
+ @NegativeInfinitePredicate.register_many(Infinity, ComplexInfinity)
272
+ def _(expr, assumptions):
273
+ return False
.venv/lib/python3.10/site-packages/sympy/assumptions/handlers/common.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module defines base class for handlers and some core handlers:
3
+ ``Q.commutative`` and ``Q.is_true``.
4
+ """
5
+
6
+ from sympy.assumptions import Q, ask, AppliedPredicate
7
+ from sympy.core import Basic, Symbol
8
+ from sympy.core.logic import _fuzzy_group, fuzzy_and, fuzzy_or
9
+ from sympy.core.numbers import NaN, Number
10
+ from sympy.logic.boolalg import (And, BooleanTrue, BooleanFalse, conjuncts,
11
+ Equivalent, Implies, Not, Or)
12
+ from sympy.utilities.exceptions import sympy_deprecation_warning
13
+
14
+ from ..predicates.common import CommutativePredicate, IsTruePredicate
15
+
16
+
17
+ class AskHandler:
18
+ """Base class that all Ask Handlers must inherit."""
19
+ def __new__(cls, *args, **kwargs):
20
+ sympy_deprecation_warning(
21
+ """
22
+ The AskHandler system is deprecated. The AskHandler class should
23
+ be replaced with the multipledispatch handler of Predicate
24
+ """,
25
+ deprecated_since_version="1.8",
26
+ active_deprecations_target='deprecated-askhandler',
27
+ )
28
+ return super().__new__(cls, *args, **kwargs)
29
+
30
+
31
+ class CommonHandler(AskHandler):
32
+ # Deprecated
33
+ """Defines some useful methods common to most Handlers. """
34
+
35
+ @staticmethod
36
+ def AlwaysTrue(expr, assumptions):
37
+ return True
38
+
39
+ @staticmethod
40
+ def AlwaysFalse(expr, assumptions):
41
+ return False
42
+
43
+ @staticmethod
44
+ def AlwaysNone(expr, assumptions):
45
+ return None
46
+
47
+ NaN = AlwaysFalse
48
+
49
+
50
+ # CommutativePredicate
51
+
52
+ @CommutativePredicate.register(Symbol)
53
+ def _(expr, assumptions):
54
+ """Objects are expected to be commutative unless otherwise stated"""
55
+ assumps = conjuncts(assumptions)
56
+ if expr.is_commutative is not None:
57
+ return expr.is_commutative and not ~Q.commutative(expr) in assumps
58
+ if Q.commutative(expr) in assumps:
59
+ return True
60
+ elif ~Q.commutative(expr) in assumps:
61
+ return False
62
+ return True
63
+
64
+ @CommutativePredicate.register(Basic)
65
+ def _(expr, assumptions):
66
+ for arg in expr.args:
67
+ if not ask(Q.commutative(arg), assumptions):
68
+ return False
69
+ return True
70
+
71
+ @CommutativePredicate.register(Number)
72
+ def _(expr, assumptions):
73
+ return True
74
+
75
+ @CommutativePredicate.register(NaN)
76
+ def _(expr, assumptions):
77
+ return True
78
+
79
+
80
+ # IsTruePredicate
81
+
82
+ @IsTruePredicate.register(bool)
83
+ def _(expr, assumptions):
84
+ return expr
85
+
86
+ @IsTruePredicate.register(BooleanTrue)
87
+ def _(expr, assumptions):
88
+ return True
89
+
90
+ @IsTruePredicate.register(BooleanFalse)
91
+ def _(expr, assumptions):
92
+ return False
93
+
94
+ @IsTruePredicate.register(AppliedPredicate)
95
+ def _(expr, assumptions):
96
+ return ask(expr, assumptions)
97
+
98
+ @IsTruePredicate.register(Not)
99
+ def _(expr, assumptions):
100
+ arg = expr.args[0]
101
+ if arg.is_Symbol:
102
+ # symbol used as abstract boolean object
103
+ return None
104
+ value = ask(arg, assumptions=assumptions)
105
+ if value in (True, False):
106
+ return not value
107
+ else:
108
+ return None
109
+
110
+ @IsTruePredicate.register(Or)
111
+ def _(expr, assumptions):
112
+ result = False
113
+ for arg in expr.args:
114
+ p = ask(arg, assumptions=assumptions)
115
+ if p is True:
116
+ return True
117
+ if p is None:
118
+ result = None
119
+ return result
120
+
121
+ @IsTruePredicate.register(And)
122
+ def _(expr, assumptions):
123
+ result = True
124
+ for arg in expr.args:
125
+ p = ask(arg, assumptions=assumptions)
126
+ if p is False:
127
+ return False
128
+ if p is None:
129
+ result = None
130
+ return result
131
+
132
+ @IsTruePredicate.register(Implies)
133
+ def _(expr, assumptions):
134
+ p, q = expr.args
135
+ return ask(~p | q, assumptions=assumptions)
136
+
137
+ @IsTruePredicate.register(Equivalent)
138
+ def _(expr, assumptions):
139
+ p, q = expr.args
140
+ pt = ask(p, assumptions=assumptions)
141
+ if pt is None:
142
+ return None
143
+ qt = ask(q, assumptions=assumptions)
144
+ if qt is None:
145
+ return None
146
+ return pt == qt
147
+
148
+
149
+ #### Helper methods
150
+ def test_closed_group(expr, assumptions, key):
151
+ """
152
+ Test for membership in a group with respect
153
+ to the current operation.
154
+ """
155
+ return _fuzzy_group(
156
+ (ask(key(a), assumptions) for a in expr.args), quick_exit=True)
157
+
158
+ def ask_all(*queries, assumptions):
159
+ return fuzzy_and(
160
+ (ask(query, assumptions) for query in queries))
161
+
162
+ def ask_any(*queries, assumptions):
163
+ return fuzzy_or(
164
+ (ask(query, assumptions) for query in queries))
.venv/lib/python3.10/site-packages/sympy/assumptions/handlers/matrices.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module contains query handlers responsible for Matrices queries:
3
+ Square, Symmetric, Invertible etc.
4
+ """
5
+
6
+ from sympy.logic.boolalg import conjuncts
7
+ from sympy.assumptions import Q, ask
8
+ from sympy.assumptions.handlers import test_closed_group
9
+ from sympy.matrices import MatrixBase
10
+ from sympy.matrices.expressions import (BlockMatrix, BlockDiagMatrix, Determinant,
11
+ DiagMatrix, DiagonalMatrix, HadamardProduct, Identity, Inverse, MatAdd, MatMul,
12
+ MatPow, MatrixExpr, MatrixSlice, MatrixSymbol, OneMatrix, Trace, Transpose,
13
+ ZeroMatrix)
14
+ from sympy.matrices.expressions.blockmatrix import reblock_2x2
15
+ from sympy.matrices.expressions.factorizations import Factorization
16
+ from sympy.matrices.expressions.fourier import DFT
17
+ from sympy.core.logic import fuzzy_and
18
+ from sympy.utilities.iterables import sift
19
+ from sympy.core import Basic
20
+
21
+ from ..predicates.matrices import (SquarePredicate, SymmetricPredicate,
22
+ InvertiblePredicate, OrthogonalPredicate, UnitaryPredicate,
23
+ FullRankPredicate, PositiveDefinitePredicate, UpperTriangularPredicate,
24
+ LowerTriangularPredicate, DiagonalPredicate, IntegerElementsPredicate,
25
+ RealElementsPredicate, ComplexElementsPredicate)
26
+
27
+
28
+ def _Factorization(predicate, expr, assumptions):
29
+ if predicate in expr.predicates:
30
+ return True
31
+
32
+
33
+ # SquarePredicate
34
+
35
+ @SquarePredicate.register(MatrixExpr)
36
+ def _(expr, assumptions):
37
+ return expr.shape[0] == expr.shape[1]
38
+
39
+
40
+ # SymmetricPredicate
41
+
42
+ @SymmetricPredicate.register(MatMul)
43
+ def _(expr, assumptions):
44
+ factor, mmul = expr.as_coeff_mmul()
45
+ if all(ask(Q.symmetric(arg), assumptions) for arg in mmul.args):
46
+ return True
47
+ # TODO: implement sathandlers system for the matrices.
48
+ # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric).
49
+ if ask(Q.diagonal(expr), assumptions):
50
+ return True
51
+ if len(mmul.args) >= 2 and mmul.args[0] == mmul.args[-1].T:
52
+ if len(mmul.args) == 2:
53
+ return True
54
+ return ask(Q.symmetric(MatMul(*mmul.args[1:-1])), assumptions)
55
+
56
+ @SymmetricPredicate.register(MatPow)
57
+ def _(expr, assumptions):
58
+ # only for integer powers
59
+ base, exp = expr.args
60
+ int_exp = ask(Q.integer(exp), assumptions)
61
+ if not int_exp:
62
+ return None
63
+ non_negative = ask(~Q.negative(exp), assumptions)
64
+ if (non_negative or non_negative == False
65
+ and ask(Q.invertible(base), assumptions)):
66
+ return ask(Q.symmetric(base), assumptions)
67
+ return None
68
+
69
+ @SymmetricPredicate.register(MatAdd)
70
+ def _(expr, assumptions):
71
+ return all(ask(Q.symmetric(arg), assumptions) for arg in expr.args)
72
+
73
+ @SymmetricPredicate.register(MatrixSymbol)
74
+ def _(expr, assumptions):
75
+ if not expr.is_square:
76
+ return False
77
+ # TODO: implement sathandlers system for the matrices.
78
+ # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric).
79
+ if ask(Q.diagonal(expr), assumptions):
80
+ return True
81
+ if Q.symmetric(expr) in conjuncts(assumptions):
82
+ return True
83
+
84
+ @SymmetricPredicate.register_many(OneMatrix, ZeroMatrix)
85
+ def _(expr, assumptions):
86
+ return ask(Q.square(expr), assumptions)
87
+
88
+ @SymmetricPredicate.register_many(Inverse, Transpose)
89
+ def _(expr, assumptions):
90
+ return ask(Q.symmetric(expr.arg), assumptions)
91
+
92
+ @SymmetricPredicate.register(MatrixSlice)
93
+ def _(expr, assumptions):
94
+ # TODO: implement sathandlers system for the matrices.
95
+ # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric).
96
+ if ask(Q.diagonal(expr), assumptions):
97
+ return True
98
+ if not expr.on_diag:
99
+ return None
100
+ else:
101
+ return ask(Q.symmetric(expr.parent), assumptions)
102
+
103
+ @SymmetricPredicate.register(Identity)
104
+ def _(expr, assumptions):
105
+ return True
106
+
107
+
108
+ # InvertiblePredicate
109
+
110
+ @InvertiblePredicate.register(MatMul)
111
+ def _(expr, assumptions):
112
+ factor, mmul = expr.as_coeff_mmul()
113
+ if all(ask(Q.invertible(arg), assumptions) for arg in mmul.args):
114
+ return True
115
+ if any(ask(Q.invertible(arg), assumptions) is False
116
+ for arg in mmul.args):
117
+ return False
118
+
119
+ @InvertiblePredicate.register(MatPow)
120
+ def _(expr, assumptions):
121
+ # only for integer powers
122
+ base, exp = expr.args
123
+ int_exp = ask(Q.integer(exp), assumptions)
124
+ if not int_exp:
125
+ return None
126
+ if exp.is_negative == False:
127
+ return ask(Q.invertible(base), assumptions)
128
+ return None
129
+
130
+ @InvertiblePredicate.register(MatAdd)
131
+ def _(expr, assumptions):
132
+ return None
133
+
134
+ @InvertiblePredicate.register(MatrixSymbol)
135
+ def _(expr, assumptions):
136
+ if not expr.is_square:
137
+ return False
138
+ if Q.invertible(expr) in conjuncts(assumptions):
139
+ return True
140
+
141
+ @InvertiblePredicate.register_many(Identity, Inverse)
142
+ def _(expr, assumptions):
143
+ return True
144
+
145
+ @InvertiblePredicate.register(ZeroMatrix)
146
+ def _(expr, assumptions):
147
+ return False
148
+
149
+ @InvertiblePredicate.register(OneMatrix)
150
+ def _(expr, assumptions):
151
+ return expr.shape[0] == 1 and expr.shape[1] == 1
152
+
153
+ @InvertiblePredicate.register(Transpose)
154
+ def _(expr, assumptions):
155
+ return ask(Q.invertible(expr.arg), assumptions)
156
+
157
+ @InvertiblePredicate.register(MatrixSlice)
158
+ def _(expr, assumptions):
159
+ if not expr.on_diag:
160
+ return None
161
+ else:
162
+ return ask(Q.invertible(expr.parent), assumptions)
163
+
164
+ @InvertiblePredicate.register(MatrixBase)
165
+ def _(expr, assumptions):
166
+ if not expr.is_square:
167
+ return False
168
+ return expr.rank() == expr.rows
169
+
170
+ @InvertiblePredicate.register(MatrixExpr)
171
+ def _(expr, assumptions):
172
+ if not expr.is_square:
173
+ return False
174
+ return None
175
+
176
+ @InvertiblePredicate.register(BlockMatrix)
177
+ def _(expr, assumptions):
178
+ if not expr.is_square:
179
+ return False
180
+ if expr.blockshape == (1, 1):
181
+ return ask(Q.invertible(expr.blocks[0, 0]), assumptions)
182
+ expr = reblock_2x2(expr)
183
+ if expr.blockshape == (2, 2):
184
+ [[A, B], [C, D]] = expr.blocks.tolist()
185
+ if ask(Q.invertible(A), assumptions) == True:
186
+ invertible = ask(Q.invertible(D - C * A.I * B), assumptions)
187
+ if invertible is not None:
188
+ return invertible
189
+ if ask(Q.invertible(B), assumptions) == True:
190
+ invertible = ask(Q.invertible(C - D * B.I * A), assumptions)
191
+ if invertible is not None:
192
+ return invertible
193
+ if ask(Q.invertible(C), assumptions) == True:
194
+ invertible = ask(Q.invertible(B - A * C.I * D), assumptions)
195
+ if invertible is not None:
196
+ return invertible
197
+ if ask(Q.invertible(D), assumptions) == True:
198
+ invertible = ask(Q.invertible(A - B * D.I * C), assumptions)
199
+ if invertible is not None:
200
+ return invertible
201
+ return None
202
+
203
+ @InvertiblePredicate.register(BlockDiagMatrix)
204
+ def _(expr, assumptions):
205
+ if expr.rowblocksizes != expr.colblocksizes:
206
+ return None
207
+ return fuzzy_and([ask(Q.invertible(a), assumptions) for a in expr.diag])
208
+
209
+
210
+ # OrthogonalPredicate
211
+
212
+ @OrthogonalPredicate.register(MatMul)
213
+ def _(expr, assumptions):
214
+ factor, mmul = expr.as_coeff_mmul()
215
+ if (all(ask(Q.orthogonal(arg), assumptions) for arg in mmul.args) and
216
+ factor == 1):
217
+ return True
218
+ if any(ask(Q.invertible(arg), assumptions) is False
219
+ for arg in mmul.args):
220
+ return False
221
+
222
+ @OrthogonalPredicate.register(MatPow)
223
+ def _(expr, assumptions):
224
+ # only for integer powers
225
+ base, exp = expr.args
226
+ int_exp = ask(Q.integer(exp), assumptions)
227
+ if int_exp:
228
+ return ask(Q.orthogonal(base), assumptions)
229
+ return None
230
+
231
+ @OrthogonalPredicate.register(MatAdd)
232
+ def _(expr, assumptions):
233
+ if (len(expr.args) == 1 and
234
+ ask(Q.orthogonal(expr.args[0]), assumptions)):
235
+ return True
236
+
237
+ @OrthogonalPredicate.register(MatrixSymbol)
238
+ def _(expr, assumptions):
239
+ if (not expr.is_square or
240
+ ask(Q.invertible(expr), assumptions) is False):
241
+ return False
242
+ if Q.orthogonal(expr) in conjuncts(assumptions):
243
+ return True
244
+
245
+ @OrthogonalPredicate.register(Identity)
246
+ def _(expr, assumptions):
247
+ return True
248
+
249
+ @OrthogonalPredicate.register(ZeroMatrix)
250
+ def _(expr, assumptions):
251
+ return False
252
+
253
+ @OrthogonalPredicate.register_many(Inverse, Transpose)
254
+ def _(expr, assumptions):
255
+ return ask(Q.orthogonal(expr.arg), assumptions)
256
+
257
+ @OrthogonalPredicate.register(MatrixSlice)
258
+ def _(expr, assumptions):
259
+ if not expr.on_diag:
260
+ return None
261
+ else:
262
+ return ask(Q.orthogonal(expr.parent), assumptions)
263
+
264
+ @OrthogonalPredicate.register(Factorization)
265
+ def _(expr, assumptions):
266
+ return _Factorization(Q.orthogonal, expr, assumptions)
267
+
268
+
269
+ # UnitaryPredicate
270
+
271
+ @UnitaryPredicate.register(MatMul)
272
+ def _(expr, assumptions):
273
+ factor, mmul = expr.as_coeff_mmul()
274
+ if (all(ask(Q.unitary(arg), assumptions) for arg in mmul.args) and
275
+ abs(factor) == 1):
276
+ return True
277
+ if any(ask(Q.invertible(arg), assumptions) is False
278
+ for arg in mmul.args):
279
+ return False
280
+
281
+ @UnitaryPredicate.register(MatPow)
282
+ def _(expr, assumptions):
283
+ # only for integer powers
284
+ base, exp = expr.args
285
+ int_exp = ask(Q.integer(exp), assumptions)
286
+ if int_exp:
287
+ return ask(Q.unitary(base), assumptions)
288
+ return None
289
+
290
+ @UnitaryPredicate.register(MatrixSymbol)
291
+ def _(expr, assumptions):
292
+ if (not expr.is_square or
293
+ ask(Q.invertible(expr), assumptions) is False):
294
+ return False
295
+ if Q.unitary(expr) in conjuncts(assumptions):
296
+ return True
297
+
298
+ @UnitaryPredicate.register_many(Inverse, Transpose)
299
+ def _(expr, assumptions):
300
+ return ask(Q.unitary(expr.arg), assumptions)
301
+
302
+ @UnitaryPredicate.register(MatrixSlice)
303
+ def _(expr, assumptions):
304
+ if not expr.on_diag:
305
+ return None
306
+ else:
307
+ return ask(Q.unitary(expr.parent), assumptions)
308
+
309
+ @UnitaryPredicate.register_many(DFT, Identity)
310
+ def _(expr, assumptions):
311
+ return True
312
+
313
+ @UnitaryPredicate.register(ZeroMatrix)
314
+ def _(expr, assumptions):
315
+ return False
316
+
317
+ @UnitaryPredicate.register(Factorization)
318
+ def _(expr, assumptions):
319
+ return _Factorization(Q.unitary, expr, assumptions)
320
+
321
+
322
+ # FullRankPredicate
323
+
324
+ @FullRankPredicate.register(MatMul)
325
+ def _(expr, assumptions):
326
+ if all(ask(Q.fullrank(arg), assumptions) for arg in expr.args):
327
+ return True
328
+
329
+ @FullRankPredicate.register(MatPow)
330
+ def _(expr, assumptions):
331
+ # only for integer powers
332
+ base, exp = expr.args
333
+ int_exp = ask(Q.integer(exp), assumptions)
334
+ if int_exp and ask(~Q.negative(exp), assumptions):
335
+ return ask(Q.fullrank(base), assumptions)
336
+ return None
337
+
338
+ @FullRankPredicate.register(Identity)
339
+ def _(expr, assumptions):
340
+ return True
341
+
342
+ @FullRankPredicate.register(ZeroMatrix)
343
+ def _(expr, assumptions):
344
+ return False
345
+
346
+ @FullRankPredicate.register(OneMatrix)
347
+ def _(expr, assumptions):
348
+ return expr.shape[0] == 1 and expr.shape[1] == 1
349
+
350
+ @FullRankPredicate.register_many(Inverse, Transpose)
351
+ def _(expr, assumptions):
352
+ return ask(Q.fullrank(expr.arg), assumptions)
353
+
354
+ @FullRankPredicate.register(MatrixSlice)
355
+ def _(expr, assumptions):
356
+ if ask(Q.orthogonal(expr.parent), assumptions):
357
+ return True
358
+
359
+
360
+ # PositiveDefinitePredicate
361
+
362
+ @PositiveDefinitePredicate.register(MatMul)
363
+ def _(expr, assumptions):
364
+ factor, mmul = expr.as_coeff_mmul()
365
+ if (all(ask(Q.positive_definite(arg), assumptions)
366
+ for arg in mmul.args) and factor > 0):
367
+ return True
368
+ if (len(mmul.args) >= 2
369
+ and mmul.args[0] == mmul.args[-1].T
370
+ and ask(Q.fullrank(mmul.args[0]), assumptions)):
371
+ return ask(Q.positive_definite(
372
+ MatMul(*mmul.args[1:-1])), assumptions)
373
+
374
+ @PositiveDefinitePredicate.register(MatPow)
375
+ def _(expr, assumptions):
376
+ # a power of a positive definite matrix is positive definite
377
+ if ask(Q.positive_definite(expr.args[0]), assumptions):
378
+ return True
379
+
380
+ @PositiveDefinitePredicate.register(MatAdd)
381
+ def _(expr, assumptions):
382
+ if all(ask(Q.positive_definite(arg), assumptions)
383
+ for arg in expr.args):
384
+ return True
385
+
386
+ @PositiveDefinitePredicate.register(MatrixSymbol)
387
+ def _(expr, assumptions):
388
+ if not expr.is_square:
389
+ return False
390
+ if Q.positive_definite(expr) in conjuncts(assumptions):
391
+ return True
392
+
393
+ @PositiveDefinitePredicate.register(Identity)
394
+ def _(expr, assumptions):
395
+ return True
396
+
397
+ @PositiveDefinitePredicate.register(ZeroMatrix)
398
+ def _(expr, assumptions):
399
+ return False
400
+
401
+ @PositiveDefinitePredicate.register(OneMatrix)
402
+ def _(expr, assumptions):
403
+ return expr.shape[0] == 1 and expr.shape[1] == 1
404
+
405
+ @PositiveDefinitePredicate.register_many(Inverse, Transpose)
406
+ def _(expr, assumptions):
407
+ return ask(Q.positive_definite(expr.arg), assumptions)
408
+
409
+ @PositiveDefinitePredicate.register(MatrixSlice)
410
+ def _(expr, assumptions):
411
+ if not expr.on_diag:
412
+ return None
413
+ else:
414
+ return ask(Q.positive_definite(expr.parent), assumptions)
415
+
416
+
417
+ # UpperTriangularPredicate
418
+
419
+ @UpperTriangularPredicate.register(MatMul)
420
+ def _(expr, assumptions):
421
+ factor, matrices = expr.as_coeff_matrices()
422
+ if all(ask(Q.upper_triangular(m), assumptions) for m in matrices):
423
+ return True
424
+
425
+ @UpperTriangularPredicate.register(MatAdd)
426
+ def _(expr, assumptions):
427
+ if all(ask(Q.upper_triangular(arg), assumptions) for arg in expr.args):
428
+ return True
429
+
430
+ @UpperTriangularPredicate.register(MatPow)
431
+ def _(expr, assumptions):
432
+ # only for integer powers
433
+ base, exp = expr.args
434
+ int_exp = ask(Q.integer(exp), assumptions)
435
+ if not int_exp:
436
+ return None
437
+ non_negative = ask(~Q.negative(exp), assumptions)
438
+ if (non_negative or non_negative == False
439
+ and ask(Q.invertible(base), assumptions)):
440
+ return ask(Q.upper_triangular(base), assumptions)
441
+ return None
442
+
443
+ @UpperTriangularPredicate.register(MatrixSymbol)
444
+ def _(expr, assumptions):
445
+ if Q.upper_triangular(expr) in conjuncts(assumptions):
446
+ return True
447
+
448
+ @UpperTriangularPredicate.register_many(Identity, ZeroMatrix)
449
+ def _(expr, assumptions):
450
+ return True
451
+
452
+ @UpperTriangularPredicate.register(OneMatrix)
453
+ def _(expr, assumptions):
454
+ return expr.shape[0] == 1 and expr.shape[1] == 1
455
+
456
+ @UpperTriangularPredicate.register(Transpose)
457
+ def _(expr, assumptions):
458
+ return ask(Q.lower_triangular(expr.arg), assumptions)
459
+
460
+ @UpperTriangularPredicate.register(Inverse)
461
+ def _(expr, assumptions):
462
+ return ask(Q.upper_triangular(expr.arg), assumptions)
463
+
464
+ @UpperTriangularPredicate.register(MatrixSlice)
465
+ def _(expr, assumptions):
466
+ if not expr.on_diag:
467
+ return None
468
+ else:
469
+ return ask(Q.upper_triangular(expr.parent), assumptions)
470
+
471
+ @UpperTriangularPredicate.register(Factorization)
472
+ def _(expr, assumptions):
473
+ return _Factorization(Q.upper_triangular, expr, assumptions)
474
+
475
+ # LowerTriangularPredicate
476
+
477
+ @LowerTriangularPredicate.register(MatMul)
478
+ def _(expr, assumptions):
479
+ factor, matrices = expr.as_coeff_matrices()
480
+ if all(ask(Q.lower_triangular(m), assumptions) for m in matrices):
481
+ return True
482
+
483
+ @LowerTriangularPredicate.register(MatAdd)
484
+ def _(expr, assumptions):
485
+ if all(ask(Q.lower_triangular(arg), assumptions) for arg in expr.args):
486
+ return True
487
+
488
+ @LowerTriangularPredicate.register(MatPow)
489
+ def _(expr, assumptions):
490
+ # only for integer powers
491
+ base, exp = expr.args
492
+ int_exp = ask(Q.integer(exp), assumptions)
493
+ if not int_exp:
494
+ return None
495
+ non_negative = ask(~Q.negative(exp), assumptions)
496
+ if (non_negative or non_negative == False
497
+ and ask(Q.invertible(base), assumptions)):
498
+ return ask(Q.lower_triangular(base), assumptions)
499
+ return None
500
+
501
+ @LowerTriangularPredicate.register(MatrixSymbol)
502
+ def _(expr, assumptions):
503
+ if Q.lower_triangular(expr) in conjuncts(assumptions):
504
+ return True
505
+
506
+ @LowerTriangularPredicate.register_many(Identity, ZeroMatrix)
507
+ def _(expr, assumptions):
508
+ return True
509
+
510
+ @LowerTriangularPredicate.register(OneMatrix)
511
+ def _(expr, assumptions):
512
+ return expr.shape[0] == 1 and expr.shape[1] == 1
513
+
514
+ @LowerTriangularPredicate.register(Transpose)
515
+ def _(expr, assumptions):
516
+ return ask(Q.upper_triangular(expr.arg), assumptions)
517
+
518
+ @LowerTriangularPredicate.register(Inverse)
519
+ def _(expr, assumptions):
520
+ return ask(Q.lower_triangular(expr.arg), assumptions)
521
+
522
+ @LowerTriangularPredicate.register(MatrixSlice)
523
+ def _(expr, assumptions):
524
+ if not expr.on_diag:
525
+ return None
526
+ else:
527
+ return ask(Q.lower_triangular(expr.parent), assumptions)
528
+
529
+ @LowerTriangularPredicate.register(Factorization)
530
+ def _(expr, assumptions):
531
+ return _Factorization(Q.lower_triangular, expr, assumptions)
532
+
533
+
534
+ # DiagonalPredicate
535
+
536
+ def _is_empty_or_1x1(expr):
537
+ return expr.shape in ((0, 0), (1, 1))
538
+
539
+ @DiagonalPredicate.register(MatMul)
540
+ def _(expr, assumptions):
541
+ if _is_empty_or_1x1(expr):
542
+ return True
543
+ factor, matrices = expr.as_coeff_matrices()
544
+ if all(ask(Q.diagonal(m), assumptions) for m in matrices):
545
+ return True
546
+
547
+ @DiagonalPredicate.register(MatPow)
548
+ def _(expr, assumptions):
549
+ # only for integer powers
550
+ base, exp = expr.args
551
+ int_exp = ask(Q.integer(exp), assumptions)
552
+ if not int_exp:
553
+ return None
554
+ non_negative = ask(~Q.negative(exp), assumptions)
555
+ if (non_negative or non_negative == False
556
+ and ask(Q.invertible(base), assumptions)):
557
+ return ask(Q.diagonal(base), assumptions)
558
+ return None
559
+
560
+ @DiagonalPredicate.register(MatAdd)
561
+ def _(expr, assumptions):
562
+ if all(ask(Q.diagonal(arg), assumptions) for arg in expr.args):
563
+ return True
564
+
565
+ @DiagonalPredicate.register(MatrixSymbol)
566
+ def _(expr, assumptions):
567
+ if _is_empty_or_1x1(expr):
568
+ return True
569
+ if Q.diagonal(expr) in conjuncts(assumptions):
570
+ return True
571
+
572
+ @DiagonalPredicate.register(OneMatrix)
573
+ def _(expr, assumptions):
574
+ return expr.shape[0] == 1 and expr.shape[1] == 1
575
+
576
+ @DiagonalPredicate.register_many(Inverse, Transpose)
577
+ def _(expr, assumptions):
578
+ return ask(Q.diagonal(expr.arg), assumptions)
579
+
580
+ @DiagonalPredicate.register(MatrixSlice)
581
+ def _(expr, assumptions):
582
+ if _is_empty_or_1x1(expr):
583
+ return True
584
+ if not expr.on_diag:
585
+ return None
586
+ else:
587
+ return ask(Q.diagonal(expr.parent), assumptions)
588
+
589
+ @DiagonalPredicate.register_many(DiagonalMatrix, DiagMatrix, Identity, ZeroMatrix)
590
+ def _(expr, assumptions):
591
+ return True
592
+
593
+ @DiagonalPredicate.register(Factorization)
594
+ def _(expr, assumptions):
595
+ return _Factorization(Q.diagonal, expr, assumptions)
596
+
597
+
598
+ # IntegerElementsPredicate
599
+
600
+ def BM_elements(predicate, expr, assumptions):
601
+ """ Block Matrix elements. """
602
+ return all(ask(predicate(b), assumptions) for b in expr.blocks)
603
+
604
+ def MS_elements(predicate, expr, assumptions):
605
+ """ Matrix Slice elements. """
606
+ return ask(predicate(expr.parent), assumptions)
607
+
608
+ def MatMul_elements(matrix_predicate, scalar_predicate, expr, assumptions):
609
+ d = sift(expr.args, lambda x: isinstance(x, MatrixExpr))
610
+ factors, matrices = d[False], d[True]
611
+ return fuzzy_and([
612
+ test_closed_group(Basic(*factors), assumptions, scalar_predicate),
613
+ test_closed_group(Basic(*matrices), assumptions, matrix_predicate)])
614
+
615
+
616
+ @IntegerElementsPredicate.register_many(Determinant, HadamardProduct, MatAdd,
617
+ Trace, Transpose)
618
+ def _(expr, assumptions):
619
+ return test_closed_group(expr, assumptions, Q.integer_elements)
620
+
621
+ @IntegerElementsPredicate.register(MatPow)
622
+ def _(expr, assumptions):
623
+ # only for integer powers
624
+ base, exp = expr.args
625
+ int_exp = ask(Q.integer(exp), assumptions)
626
+ if not int_exp:
627
+ return None
628
+ if exp.is_negative == False:
629
+ return ask(Q.integer_elements(base), assumptions)
630
+ return None
631
+
632
+ @IntegerElementsPredicate.register_many(Identity, OneMatrix, ZeroMatrix)
633
+ def _(expr, assumptions):
634
+ return True
635
+
636
+ @IntegerElementsPredicate.register(MatMul)
637
+ def _(expr, assumptions):
638
+ return MatMul_elements(Q.integer_elements, Q.integer, expr, assumptions)
639
+
640
+ @IntegerElementsPredicate.register(MatrixSlice)
641
+ def _(expr, assumptions):
642
+ return MS_elements(Q.integer_elements, expr, assumptions)
643
+
644
+ @IntegerElementsPredicate.register(BlockMatrix)
645
+ def _(expr, assumptions):
646
+ return BM_elements(Q.integer_elements, expr, assumptions)
647
+
648
+
649
+ # RealElementsPredicate
650
+
651
+ @RealElementsPredicate.register_many(Determinant, Factorization, HadamardProduct,
652
+ MatAdd, Trace, Transpose)
653
+ def _(expr, assumptions):
654
+ return test_closed_group(expr, assumptions, Q.real_elements)
655
+
656
+ @RealElementsPredicate.register(MatPow)
657
+ def _(expr, assumptions):
658
+ # only for integer powers
659
+ base, exp = expr.args
660
+ int_exp = ask(Q.integer(exp), assumptions)
661
+ if not int_exp:
662
+ return None
663
+ non_negative = ask(~Q.negative(exp), assumptions)
664
+ if (non_negative or non_negative == False
665
+ and ask(Q.invertible(base), assumptions)):
666
+ return ask(Q.real_elements(base), assumptions)
667
+ return None
668
+
669
+ @RealElementsPredicate.register(MatMul)
670
+ def _(expr, assumptions):
671
+ return MatMul_elements(Q.real_elements, Q.real, expr, assumptions)
672
+
673
+ @RealElementsPredicate.register(MatrixSlice)
674
+ def _(expr, assumptions):
675
+ return MS_elements(Q.real_elements, expr, assumptions)
676
+
677
+ @RealElementsPredicate.register(BlockMatrix)
678
+ def _(expr, assumptions):
679
+ return BM_elements(Q.real_elements, expr, assumptions)
680
+
681
+
682
+ # ComplexElementsPredicate
683
+
684
+ @ComplexElementsPredicate.register_many(Determinant, Factorization, HadamardProduct,
685
+ Inverse, MatAdd, Trace, Transpose)
686
+ def _(expr, assumptions):
687
+ return test_closed_group(expr, assumptions, Q.complex_elements)
688
+
689
+ @ComplexElementsPredicate.register(MatPow)
690
+ def _(expr, assumptions):
691
+ # only for integer powers
692
+ base, exp = expr.args
693
+ int_exp = ask(Q.integer(exp), assumptions)
694
+ if not int_exp:
695
+ return None
696
+ non_negative = ask(~Q.negative(exp), assumptions)
697
+ if (non_negative or non_negative == False
698
+ and ask(Q.invertible(base), assumptions)):
699
+ return ask(Q.complex_elements(base), assumptions)
700
+ return None
701
+
702
+ @ComplexElementsPredicate.register(MatMul)
703
+ def _(expr, assumptions):
704
+ return MatMul_elements(Q.complex_elements, Q.complex, expr, assumptions)
705
+
706
+ @ComplexElementsPredicate.register(MatrixSlice)
707
+ def _(expr, assumptions):
708
+ return MS_elements(Q.complex_elements, expr, assumptions)
709
+
710
+ @ComplexElementsPredicate.register(BlockMatrix)
711
+ def _(expr, assumptions):
712
+ return BM_elements(Q.complex_elements, expr, assumptions)
713
+
714
+ @ComplexElementsPredicate.register(DFT)
715
+ def _(expr, assumptions):
716
+ return True
.venv/lib/python3.10/site-packages/sympy/assumptions/handlers/ntheory.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Handlers for keys related to number theory: prime, even, odd, etc.
3
+ """
4
+
5
+ from sympy.assumptions import Q, ask
6
+ from sympy.core import Add, Basic, Expr, Float, Mul, Pow, S
7
+ from sympy.core.numbers import (ImaginaryUnit, Infinity, Integer, NaN,
8
+ NegativeInfinity, NumberSymbol, Rational, int_valued)
9
+ from sympy.functions import Abs, im, re
10
+ from sympy.ntheory import isprime
11
+
12
+ from sympy.multipledispatch import MDNotImplementedError
13
+
14
+ from ..predicates.ntheory import (PrimePredicate, CompositePredicate,
15
+ EvenPredicate, OddPredicate)
16
+
17
+
18
+ # PrimePredicate
19
+
20
+ def _PrimePredicate_number(expr, assumptions):
21
+ # helper method
22
+ exact = not expr.atoms(Float)
23
+ try:
24
+ i = int(expr.round())
25
+ if (expr - i).equals(0) is False:
26
+ raise TypeError
27
+ except TypeError:
28
+ return False
29
+ if exact:
30
+ return isprime(i)
31
+ # when not exact, we won't give a True or False
32
+ # since the number represents an approximate value
33
+
34
+ @PrimePredicate.register(Expr)
35
+ def _(expr, assumptions):
36
+ ret = expr.is_prime
37
+ if ret is None:
38
+ raise MDNotImplementedError
39
+ return ret
40
+
41
+ @PrimePredicate.register(Basic)
42
+ def _(expr, assumptions):
43
+ if expr.is_number:
44
+ return _PrimePredicate_number(expr, assumptions)
45
+
46
+ @PrimePredicate.register(Mul)
47
+ def _(expr, assumptions):
48
+ if expr.is_number:
49
+ return _PrimePredicate_number(expr, assumptions)
50
+ for arg in expr.args:
51
+ if not ask(Q.integer(arg), assumptions):
52
+ return None
53
+ for arg in expr.args:
54
+ if arg.is_number and arg.is_composite:
55
+ return False
56
+
57
+ @PrimePredicate.register(Pow)
58
+ def _(expr, assumptions):
59
+ """
60
+ Integer**Integer -> !Prime
61
+ """
62
+ if expr.is_number:
63
+ return _PrimePredicate_number(expr, assumptions)
64
+ if ask(Q.integer(expr.exp), assumptions) and \
65
+ ask(Q.integer(expr.base), assumptions):
66
+ prime_base = ask(Q.prime(expr.base), assumptions)
67
+ if prime_base is False:
68
+ return False
69
+ is_exp_one = ask(Q.eq(expr.exp, 1), assumptions)
70
+ if is_exp_one is False:
71
+ return False
72
+ if prime_base is True and is_exp_one is True:
73
+ return True
74
+
75
+ @PrimePredicate.register(Integer)
76
+ def _(expr, assumptions):
77
+ return isprime(expr)
78
+
79
+ @PrimePredicate.register_many(Rational, Infinity, NegativeInfinity, ImaginaryUnit)
80
+ def _(expr, assumptions):
81
+ return False
82
+
83
+ @PrimePredicate.register(Float)
84
+ def _(expr, assumptions):
85
+ return _PrimePredicate_number(expr, assumptions)
86
+
87
+ @PrimePredicate.register(NumberSymbol)
88
+ def _(expr, assumptions):
89
+ return _PrimePredicate_number(expr, assumptions)
90
+
91
+ @PrimePredicate.register(NaN)
92
+ def _(expr, assumptions):
93
+ return None
94
+
95
+
96
+ # CompositePredicate
97
+
98
+ @CompositePredicate.register(Expr)
99
+ def _(expr, assumptions):
100
+ ret = expr.is_composite
101
+ if ret is None:
102
+ raise MDNotImplementedError
103
+ return ret
104
+
105
+ @CompositePredicate.register(Basic)
106
+ def _(expr, assumptions):
107
+ _positive = ask(Q.positive(expr), assumptions)
108
+ if _positive:
109
+ _integer = ask(Q.integer(expr), assumptions)
110
+ if _integer:
111
+ _prime = ask(Q.prime(expr), assumptions)
112
+ if _prime is None:
113
+ return
114
+ # Positive integer which is not prime is not
115
+ # necessarily composite
116
+ _is_one = ask(Q.eq(expr, 1), assumptions)
117
+ if _is_one:
118
+ return False
119
+ if _is_one is None:
120
+ return None
121
+ return not _prime
122
+ else:
123
+ return _integer
124
+ else:
125
+ return _positive
126
+
127
+
128
+ # EvenPredicate
129
+
130
+ def _EvenPredicate_number(expr, assumptions):
131
+ # helper method
132
+ if isinstance(expr, (float, Float)):
133
+ if int_valued(expr):
134
+ return None
135
+ return False
136
+ try:
137
+ i = int(expr.round())
138
+ except TypeError:
139
+ return False
140
+ if not (expr - i).equals(0):
141
+ return False
142
+ return i % 2 == 0
143
+
144
+ @EvenPredicate.register(Expr)
145
+ def _(expr, assumptions):
146
+ ret = expr.is_even
147
+ if ret is None:
148
+ raise MDNotImplementedError
149
+ return ret
150
+
151
+ @EvenPredicate.register(Basic)
152
+ def _(expr, assumptions):
153
+ if expr.is_number:
154
+ return _EvenPredicate_number(expr, assumptions)
155
+
156
+ @EvenPredicate.register(Mul)
157
+ def _(expr, assumptions):
158
+ """
159
+ Even * Integer -> Even
160
+ Even * Odd -> Even
161
+ Integer * Odd -> ?
162
+ Odd * Odd -> Odd
163
+ Even * Even -> Even
164
+ Integer * Integer -> Even if Integer + Integer = Odd
165
+ otherwise -> ?
166
+ """
167
+ if expr.is_number:
168
+ return _EvenPredicate_number(expr, assumptions)
169
+ even, odd, irrational, acc = False, 0, False, 1
170
+ for arg in expr.args:
171
+ # check for all integers and at least one even
172
+ if ask(Q.integer(arg), assumptions):
173
+ if ask(Q.even(arg), assumptions):
174
+ even = True
175
+ elif ask(Q.odd(arg), assumptions):
176
+ odd += 1
177
+ elif not even and acc != 1:
178
+ if ask(Q.odd(acc + arg), assumptions):
179
+ even = True
180
+ elif ask(Q.irrational(arg), assumptions):
181
+ # one irrational makes the result False
182
+ # two makes it undefined
183
+ if irrational:
184
+ break
185
+ irrational = True
186
+ else:
187
+ break
188
+ acc = arg
189
+ else:
190
+ if irrational:
191
+ return False
192
+ if even:
193
+ return True
194
+ if odd == len(expr.args):
195
+ return False
196
+
197
+ @EvenPredicate.register(Add)
198
+ def _(expr, assumptions):
199
+ """
200
+ Even + Odd -> Odd
201
+ Even + Even -> Even
202
+ Odd + Odd -> Even
203
+
204
+ """
205
+ if expr.is_number:
206
+ return _EvenPredicate_number(expr, assumptions)
207
+ _result = True
208
+ for arg in expr.args:
209
+ if ask(Q.even(arg), assumptions):
210
+ pass
211
+ elif ask(Q.odd(arg), assumptions):
212
+ _result = not _result
213
+ else:
214
+ break
215
+ else:
216
+ return _result
217
+
218
+ @EvenPredicate.register(Pow)
219
+ def _(expr, assumptions):
220
+ if expr.is_number:
221
+ return _EvenPredicate_number(expr, assumptions)
222
+ if ask(Q.integer(expr.exp), assumptions):
223
+ if ask(Q.positive(expr.exp), assumptions):
224
+ return ask(Q.even(expr.base), assumptions)
225
+ elif ask(~Q.negative(expr.exp) & Q.odd(expr.base), assumptions):
226
+ return False
227
+ elif expr.base is S.NegativeOne:
228
+ return False
229
+
230
+ @EvenPredicate.register(Integer)
231
+ def _(expr, assumptions):
232
+ return not bool(expr.p & 1)
233
+
234
+ @EvenPredicate.register_many(Rational, Infinity, NegativeInfinity, ImaginaryUnit)
235
+ def _(expr, assumptions):
236
+ return False
237
+
238
+ @EvenPredicate.register(NumberSymbol)
239
+ def _(expr, assumptions):
240
+ return _EvenPredicate_number(expr, assumptions)
241
+
242
+ @EvenPredicate.register(Abs)
243
+ def _(expr, assumptions):
244
+ if ask(Q.real(expr.args[0]), assumptions):
245
+ return ask(Q.even(expr.args[0]), assumptions)
246
+
247
+ @EvenPredicate.register(re)
248
+ def _(expr, assumptions):
249
+ if ask(Q.real(expr.args[0]), assumptions):
250
+ return ask(Q.even(expr.args[0]), assumptions)
251
+
252
+ @EvenPredicate.register(im)
253
+ def _(expr, assumptions):
254
+ if ask(Q.real(expr.args[0]), assumptions):
255
+ return True
256
+
257
+ @EvenPredicate.register(NaN)
258
+ def _(expr, assumptions):
259
+ return None
260
+
261
+
262
+ # OddPredicate
263
+
264
+ @OddPredicate.register(Expr)
265
+ def _(expr, assumptions):
266
+ ret = expr.is_odd
267
+ if ret is None:
268
+ raise MDNotImplementedError
269
+ return ret
270
+
271
+ @OddPredicate.register(Basic)
272
+ def _(expr, assumptions):
273
+ _integer = ask(Q.integer(expr), assumptions)
274
+ if _integer:
275
+ _even = ask(Q.even(expr), assumptions)
276
+ if _even is None:
277
+ return None
278
+ return not _even
279
+ return _integer