Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- shared/package-files/12/12014bea1c391f9e1c72ea1fe2d2767a176792d4fbb6b8198e266aa69b07f102/dechunk.py +207 -0
- shared/package-files/12/1203da797f298a07ce6c3db5008808f6babb20390952fe96c140c128073d8e45/native_channel_shuffle_compositeimplicitautograd_dispatch.h +24 -0
- shared/package-files/12/1203e29bc4a31d6b8affe417017d48ff979913ee52229e6e2003d9b195943168/_sparse_semi_structured_linear_cuda_dispatch.h +23 -0
- shared/package-files/12/1205a30dd9e57c244a2729947010ef32f3e7d192cedc6fe69755c9ef0bcc6c22/stats.py +41 -0
- shared/package-files/12/1208156318870b85d5a072e628bee50312f19661ea71f0c86f5679725a8943c5/qconfig_mapping.py +350 -0
- shared/package-files/12/120b4c07575f5c9b170d7f207ec38dae3c8049f7f6b6673d48a839b368b279f2/native_group_norm_backward_cpu_dispatch.h +24 -0
- shared/package-files/12/120c868dc68b10f7e52a10b9e0d1b0641f3d6e945a3b0a9df5ab2b79ea2301d9/test_common_basic.py +983 -0
- shared/package-files/12/120cc3dd23b5921be0ee9643713b2aa08d0515296c6686dbe8569d2db0212797/Storage.h +2 -0
- shared/package-files/12/120dab704ee3adabf7cd4bee4d7b86e255fd3dbc81202bc0d1705615707626e7/linear.py +14 -0
- shared/package-files/12/120dbf1ac136a09aa9787be0f7c6183bab5f1cff16bf432b57b092e79c516aed/exceptions.py +53 -0
- shared/package-files/12/120f31e6a5b25c3ccf7b331a7c5bb4b34ab23c31e3fac3ec1711ad13a876f6aa/_p_r_o_p.py +12 -0
- shared/package-files/12/120f7ab06ff0c361ba92de8de23952c1503e2c4f37e0a646a78f8480369c07d9/tables.pyi +19 -0
- shared/package-files/12/120fd1be639c98578beacd919530fea0ec5e6c67582cdf5564cd60718dd8326b/printimpl.py +86 -0
- shared/package-files/12/12108cb824b3eb4220409f776ffe302720281e953d27eb9d746e1068c4f43eee/__init__.py +15 -0
- shared/package-files/12/121171ff40fdc3ce4308947d172529ac53e2683bc9a6cdf1cbe2a7e30856723b/erlang.py +528 -0
- shared/package-files/12/12129c6cf2f8efbeb9b56022439edcbac68ad9368842a64282d268119b3751dd/Malta +0 -0
- shared/package-files/12/1212c5348edc16cb540d460fecc27848b6d66c823d47257a8ef90490a3855583/new_empty_compositeexplicitautograd_dispatch.h +30 -0
- shared/package-files/12/1213fa6b70466961d59d6cefa0d6575f1c5c2c07004b9d45fb3929c2811b3aa6/special_hermite_polynomial_h_meta.h +27 -0
- shared/package-files/12/12169e2ff3b05160392e08c5841a79c05e4783b6fdccb2d7b8a8e117b0ef67f9/mime340 +0 -0
- shared/package-files/12/12169e2ff3b05160392e08c5841a79c05e4783b6fdccb2d7b8a8e117b0ef67f9/mm340 +0 -0
- shared/package-files/12/12174302c11791cfb7c8e3decc5159468dfb691739ae231785e71a6eaac10a62/XPUHooksInterface.h +80 -0
- shared/package-files/12/1219c1146c749c177e647332e778a1a1e996b9dd319cd618633403aea599ed23/html_parser.pyi +1 -0
- shared/package-files/12/121a104748e3c4fddcb8bd9ba464fb32e6a0520fe25a3667403d12f0c7e3f939/clamp_ops.h +83 -0
- shared/package-files/12/121ba935b94002988b6c2fc848210afe48dc5f9de4e4797550b198c5d3f9d769/nll_loss2d_backward.h +91 -0
- shared/package-files/12/121cc460893e0c122e534b0c83f75abd248bd70fa8dde9e54f54bdbb396365f3/_vbscript_builtins.py +279 -0
- shared/package-files/12/1222f9226aa41859944e38198efd051a91818d3cd65ea4f7c3a782af342d3e6a/test_hessian_update_strategy.py +300 -0
- shared/package-files/12/122306c1ce83ca4f3ce92ffefff2a5dbc253f073f08cf8ea5f9c2881e8d48b6d/sun-s +0 -0
- shared/package-files/12/1224241dcfb4ec6aff3cafc66adeb2b2a3759397a28693173915458c50040143/colorchooser.py +86 -0
- shared/package-files/12/122465451fa4cc994a577357a18b58ac684c4b7959da85b041dabbee1d5c63c1/message_listener.pyi +5 -0
- shared/package-files/12/122c59580e3e66ea388b09c95140f80d5e4ae66930c68f20c774c0b68ed9fd08/dataframe.py +552 -0
- shared/package-files/12/1232056ea45daf664905a2355efa16469b679d6d4b16b961c9dc430ee2108d22/Mawson +0 -0
- shared/package-files/12/123597bfe27c0b92444f802521b25175cb7270befe772259727a168279423dcf/ndarraytypes.h +1945 -0
- shared/package-files/12/123b7a693e43807904553369db80760123d0b01a3dfc9e8a259fbab196f5b2bb/arima112nc_results.py +1099 -0
- shared/package-files/12/123bba51a65adb7e665ac19d1cbe1a30d426b5ca10e4bd6ba9315ed6f67d9c19/colorscan +0 -0
- shared/package-files/12/123bba51a65adb7e665ac19d1cbe1a30d426b5ca10e4bd6ba9315ed6f67d9c19/cs10 +0 -0
- shared/package-files/12/123c85a2812a517d967db5f31660db0e6aded4a0b95ed943c5ab435368e7a25c/dumb +0 -0
- shared/package-files/12/12405d898c1f97129255511cf8ca74764a24a0d96db6526524865072f4e294bc/is_same_size_native.h +22 -0
- shared/package-files/12/124194a8c1f7a8101b2d56d24ae622e1943cf46e315089834f69d301fde79fd1/jscode.py +339 -0
- shared/package-files/12/12436933cae8c1e4096af342313070ce873eefad3d6a1637675ef780d1fdea1e/PersistentSoftmax.cuh +401 -0
- shared/package-files/12/1245cacd62e0fa3a6c57cadea76616e9f0ec083cfe7777d8d6abf541513b308f/scripting.py +1286 -0
- shared/package-files/12/1247c2e7b7565de963817cb9b2276b247246d760f5826414c8f0cad7c5b3953e/example_1.nc +0 -0
- shared/package-files/12/1248eb53b35366b387ebcc8aaf3e82fdec89312152c46802db23104fd66c71e9/mod.mod +0 -0
- shared/package-files/12/124ffb03b72d9bf581fb7d8d78f6ce0db4392c3319040982bc380f29b21439c8/test_na_indexing.py +75 -0
- shared/package-files/12/12516cb0e8fca551b5ebccb2d04f2e8b24d4143588f611ae58893d928887d401/glu_backward_cuda_dispatch.h +25 -0
- shared/package-files/12/1251946f8a7929c3229bf79d1f833024bf225025750acd4b1217ba38ad9eb67c/screen.mlterm-256color +0 -0
- shared/package-files/12/1252cac9d50cc94cf280970abab3a13fbde9a9ddbf9971d100b43a5b208d94d2/_cholesky_solve_helper_native.h +23 -0
- shared/package-files/12/1255040a0eb9c99f58775d55cf34f675cf61539f7c0a0dd0d6a36cb1f0da1e15/_data.py +0 -0
- shared/package-files/12/1255479c1d949f779a4388c9f0a1c7a7e8705df607332a674ad85f44edf73fdd/trf.py +560 -0
- shared/package-files/12/125db28cc971dffbcea2b7457e290284dbffa3ec1eed250b0e5f7a62ae6408aa/complex.h +618 -0
- shared/package-files/12/125e7a772c88cc9932055ff5807f9b197f2217a2739f4121a662442b9ee0bcab/test_hyper.py +387 -0
shared/package-files/12/12014bea1c391f9e1c72ea1fe2d2767a176792d4fbb6b8198e266aa69b07f102/dechunk.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, cast
|
| 4 |
+
|
| 5 |
+
from contourpy._contourpy import FillType, LineType
|
| 6 |
+
from contourpy.array import (
|
| 7 |
+
concat_codes_or_none,
|
| 8 |
+
concat_offsets_or_none,
|
| 9 |
+
concat_points_or_none,
|
| 10 |
+
concat_points_or_none_with_nan,
|
| 11 |
+
)
|
| 12 |
+
from contourpy.enum_util import as_fill_type, as_line_type
|
| 13 |
+
from contourpy.typecheck import check_filled, check_lines
|
| 14 |
+
|
| 15 |
+
if TYPE_CHECKING:
|
| 16 |
+
import contourpy._contourpy as cpy
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def dechunk_filled(filled: cpy.FillReturn, fill_type: FillType | str) -> cpy.FillReturn:
|
| 20 |
+
"""Return the specified filled contours with chunked data moved into the first chunk.
|
| 21 |
+
|
| 22 |
+
Filled contours that are not chunked (``FillType.OuterCode`` and ``FillType.OuterOffset``) and
|
| 23 |
+
those that are but only contain a single chunk are returned unmodified. Individual polygons are
|
| 24 |
+
unchanged, they are not geometrically combined.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
filled (sequence of arrays): Filled contour data, such as returned by
|
| 28 |
+
:meth:`.ContourGenerator.filled`.
|
| 29 |
+
fill_type (FillType or str): Type of :meth:`~.ContourGenerator.filled` as enum or string
|
| 30 |
+
equivalent.
|
| 31 |
+
|
| 32 |
+
Return:
|
| 33 |
+
Filled contours in a single chunk.
|
| 34 |
+
|
| 35 |
+
.. versionadded:: 1.2.0
|
| 36 |
+
"""
|
| 37 |
+
fill_type = as_fill_type(fill_type)
|
| 38 |
+
|
| 39 |
+
if fill_type in (FillType.OuterCode, FillType.OuterOffset):
|
| 40 |
+
# No-op if fill_type is not chunked.
|
| 41 |
+
return filled
|
| 42 |
+
|
| 43 |
+
check_filled(filled, fill_type)
|
| 44 |
+
if len(filled[0]) < 2:
|
| 45 |
+
# No-op if just one chunk.
|
| 46 |
+
return filled
|
| 47 |
+
|
| 48 |
+
if TYPE_CHECKING:
|
| 49 |
+
filled = cast(cpy.FillReturn_Chunk, filled)
|
| 50 |
+
points = concat_points_or_none(filled[0])
|
| 51 |
+
|
| 52 |
+
if fill_type == FillType.ChunkCombinedCode:
|
| 53 |
+
if TYPE_CHECKING:
|
| 54 |
+
filled = cast(cpy.FillReturn_ChunkCombinedCode, filled)
|
| 55 |
+
if points is None:
|
| 56 |
+
ret1: cpy.FillReturn_ChunkCombinedCode = ([None], [None])
|
| 57 |
+
else:
|
| 58 |
+
ret1 = ([points], [concat_codes_or_none(filled[1])])
|
| 59 |
+
return ret1
|
| 60 |
+
elif fill_type == FillType.ChunkCombinedOffset:
|
| 61 |
+
if TYPE_CHECKING:
|
| 62 |
+
filled = cast(cpy.FillReturn_ChunkCombinedOffset, filled)
|
| 63 |
+
if points is None:
|
| 64 |
+
ret2: cpy.FillReturn_ChunkCombinedOffset = ([None], [None])
|
| 65 |
+
else:
|
| 66 |
+
ret2 = ([points], [concat_offsets_or_none(filled[1])])
|
| 67 |
+
return ret2
|
| 68 |
+
elif fill_type == FillType.ChunkCombinedCodeOffset:
|
| 69 |
+
if TYPE_CHECKING:
|
| 70 |
+
filled = cast(cpy.FillReturn_ChunkCombinedCodeOffset, filled)
|
| 71 |
+
if points is None:
|
| 72 |
+
ret3: cpy.FillReturn_ChunkCombinedCodeOffset = ([None], [None], [None])
|
| 73 |
+
else:
|
| 74 |
+
outer_offsets = concat_offsets_or_none(filled[2])
|
| 75 |
+
ret3 = ([points], [concat_codes_or_none(filled[1])], [outer_offsets])
|
| 76 |
+
return ret3
|
| 77 |
+
elif fill_type == FillType.ChunkCombinedOffsetOffset:
|
| 78 |
+
if TYPE_CHECKING:
|
| 79 |
+
filled = cast(cpy.FillReturn_ChunkCombinedOffsetOffset, filled)
|
| 80 |
+
if points is None:
|
| 81 |
+
ret4: cpy.FillReturn_ChunkCombinedOffsetOffset = ([None], [None], [None])
|
| 82 |
+
else:
|
| 83 |
+
outer_offsets = concat_offsets_or_none(filled[2])
|
| 84 |
+
ret4 = ([points], [concat_offsets_or_none(filled[1])], [outer_offsets])
|
| 85 |
+
return ret4
|
| 86 |
+
else:
|
| 87 |
+
raise ValueError(f"Invalid FillType {fill_type}")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def dechunk_lines(lines: cpy.LineReturn, line_type: LineType | str) -> cpy.LineReturn:
|
| 91 |
+
"""Return the specified contour lines with chunked data moved into the first chunk.
|
| 92 |
+
|
| 93 |
+
Contour lines that are not chunked (``LineType.Separate`` and ``LineType.SeparateCode``) and
|
| 94 |
+
those that are but only contain a single chunk are returned unmodified. Individual lines are
|
| 95 |
+
unchanged, they are not geometrically combined.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
lines (sequence of arrays): Contour line data, such as returned by
|
| 99 |
+
:meth:`.ContourGenerator.lines`.
|
| 100 |
+
line_type (LineType or str): Type of :meth:`~.ContourGenerator.lines` as enum or string
|
| 101 |
+
equivalent.
|
| 102 |
+
|
| 103 |
+
Return:
|
| 104 |
+
Contour lines in a single chunk.
|
| 105 |
+
|
| 106 |
+
.. versionadded:: 1.2.0
|
| 107 |
+
"""
|
| 108 |
+
line_type = as_line_type(line_type)
|
| 109 |
+
|
| 110 |
+
if line_type in (LineType.Separate, LineType.SeparateCode):
|
| 111 |
+
# No-op if line_type is not chunked.
|
| 112 |
+
return lines
|
| 113 |
+
|
| 114 |
+
check_lines(lines, line_type)
|
| 115 |
+
if len(lines[0]) < 2:
|
| 116 |
+
# No-op if just one chunk.
|
| 117 |
+
return lines
|
| 118 |
+
|
| 119 |
+
if TYPE_CHECKING:
|
| 120 |
+
lines = cast(cpy.LineReturn_Chunk, lines)
|
| 121 |
+
|
| 122 |
+
if line_type == LineType.ChunkCombinedCode:
|
| 123 |
+
if TYPE_CHECKING:
|
| 124 |
+
lines = cast(cpy.LineReturn_ChunkCombinedCode, lines)
|
| 125 |
+
points = concat_points_or_none(lines[0])
|
| 126 |
+
if points is None:
|
| 127 |
+
ret1: cpy.LineReturn_ChunkCombinedCode = ([None], [None])
|
| 128 |
+
else:
|
| 129 |
+
ret1 = ([points], [concat_codes_or_none(lines[1])])
|
| 130 |
+
return ret1
|
| 131 |
+
elif line_type == LineType.ChunkCombinedOffset:
|
| 132 |
+
if TYPE_CHECKING:
|
| 133 |
+
lines = cast(cpy.LineReturn_ChunkCombinedOffset, lines)
|
| 134 |
+
points = concat_points_or_none(lines[0])
|
| 135 |
+
if points is None:
|
| 136 |
+
ret2: cpy.LineReturn_ChunkCombinedOffset = ([None], [None])
|
| 137 |
+
else:
|
| 138 |
+
ret2 = ([points], [concat_offsets_or_none(lines[1])])
|
| 139 |
+
return ret2
|
| 140 |
+
elif line_type == LineType.ChunkCombinedNan:
|
| 141 |
+
if TYPE_CHECKING:
|
| 142 |
+
lines = cast(cpy.LineReturn_ChunkCombinedNan, lines)
|
| 143 |
+
points = concat_points_or_none_with_nan(lines[0])
|
| 144 |
+
ret3: cpy.LineReturn_ChunkCombinedNan = ([points],)
|
| 145 |
+
return ret3
|
| 146 |
+
else:
|
| 147 |
+
raise ValueError(f"Invalid LineType {line_type}")
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def dechunk_multi_filled(
|
| 151 |
+
multi_filled: list[cpy.FillReturn],
|
| 152 |
+
fill_type: FillType | str,
|
| 153 |
+
) -> list[cpy.FillReturn]:
|
| 154 |
+
"""Return multiple sets of filled contours with chunked data moved into the first chunks.
|
| 155 |
+
|
| 156 |
+
Filled contours that are not chunked (``FillType.OuterCode`` and ``FillType.OuterOffset``) and
|
| 157 |
+
those that are but only contain a single chunk are returned unmodified. Individual polygons are
|
| 158 |
+
unchanged, they are not geometrically combined.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
multi_filled (nested sequence of arrays): Filled contour data, such as returned by
|
| 162 |
+
:meth:`.ContourGenerator.multi_filled`.
|
| 163 |
+
fill_type (FillType or str): Type of :meth:`~.ContourGenerator.filled` as enum or string
|
| 164 |
+
equivalent.
|
| 165 |
+
|
| 166 |
+
Return:
|
| 167 |
+
Multiple sets of filled contours in a single chunk.
|
| 168 |
+
|
| 169 |
+
.. versionadded:: 1.3.0
|
| 170 |
+
"""
|
| 171 |
+
fill_type = as_fill_type(fill_type)
|
| 172 |
+
|
| 173 |
+
if fill_type in (FillType.OuterCode, FillType.OuterOffset):
|
| 174 |
+
# No-op if fill_type is not chunked.
|
| 175 |
+
return multi_filled
|
| 176 |
+
|
| 177 |
+
return [dechunk_filled(filled, fill_type) for filled in multi_filled]
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def dechunk_multi_lines(
|
| 181 |
+
multi_lines: list[cpy.LineReturn],
|
| 182 |
+
line_type: LineType | str,
|
| 183 |
+
) -> list[cpy.LineReturn]:
|
| 184 |
+
"""Return multiple sets of contour lines with all chunked data moved into the first chunks.
|
| 185 |
+
|
| 186 |
+
Contour lines that are not chunked (``LineType.Separate`` and ``LineType.SeparateCode``) and
|
| 187 |
+
those that are but only contain a single chunk are returned unmodified. Individual lines are
|
| 188 |
+
unchanged, they are not geometrically combined.
|
| 189 |
+
|
| 190 |
+
Args:
|
| 191 |
+
multi_lines (nested sequence of arrays): Contour line data, such as returned by
|
| 192 |
+
:meth:`.ContourGenerator.multi_lines`.
|
| 193 |
+
line_type (LineType or str): Type of :meth:`~.ContourGenerator.lines` as enum or string
|
| 194 |
+
equivalent.
|
| 195 |
+
|
| 196 |
+
Return:
|
| 197 |
+
Multiple sets of contour lines in a single chunk.
|
| 198 |
+
|
| 199 |
+
.. versionadded:: 1.3.0
|
| 200 |
+
"""
|
| 201 |
+
line_type = as_line_type(line_type)
|
| 202 |
+
|
| 203 |
+
if line_type in (LineType.Separate, LineType.SeparateCode):
|
| 204 |
+
# No-op if line_type is not chunked.
|
| 205 |
+
return multi_lines
|
| 206 |
+
|
| 207 |
+
return [dechunk_lines(lines, line_type) for lines in multi_lines]
|
shared/package-files/12/1203da797f298a07ce6c3db5008808f6babb20390952fe96c140c128073d8e45/native_channel_shuffle_compositeimplicitautograd_dispatch.h
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace compositeimplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor native_channel_shuffle(const at::Tensor & self, int64_t groups);
|
| 21 |
+
TORCH_API at::Tensor native_channel_shuffle_symint(const at::Tensor & self, c10::SymInt groups);
|
| 22 |
+
|
| 23 |
+
} // namespace compositeimplicitautograd
|
| 24 |
+
} // namespace at
|
shared/package-files/12/1203e29bc4a31d6b8affe417017d48ff979913ee52229e6e2003d9b195943168/_sparse_semi_structured_linear_cuda_dispatch.h
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cuda {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor _sparse_semi_structured_linear(const at::Tensor & input, const at::Tensor & weight, const at::Tensor & meta, const c10::optional<at::Tensor> & bias={}, c10::optional<c10::string_view> activation=c10::nullopt, c10::optional<at::ScalarType> out_dtype=c10::nullopt);
|
| 21 |
+
|
| 22 |
+
} // namespace cuda
|
| 23 |
+
} // namespace at
|
shared/package-files/12/1205a30dd9e57c244a2729947010ef32f3e7d192cedc6fe69755c9ef0bcc6c22/stats.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.stats` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa: F822
|
| 9 |
+
'find_repeats', 'gmean', 'hmean', 'pmean', 'mode', 'tmean', 'tvar',
|
| 10 |
+
'tmin', 'tmax', 'tstd', 'tsem', 'moment',
|
| 11 |
+
'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest',
|
| 12 |
+
'normaltest', 'jarque_bera',
|
| 13 |
+
'scoreatpercentile', 'percentileofscore',
|
| 14 |
+
'cumfreq', 'relfreq', 'obrientransform',
|
| 15 |
+
'sem', 'zmap', 'zscore', 'gzscore', 'iqr', 'gstd',
|
| 16 |
+
'median_abs_deviation',
|
| 17 |
+
'sigmaclip', 'trimboth', 'trim1', 'trim_mean',
|
| 18 |
+
'f_oneway',
|
| 19 |
+
'pearsonr', 'fisher_exact',
|
| 20 |
+
'spearmanr', 'pointbiserialr',
|
| 21 |
+
'kendalltau', 'weightedtau', 'multiscale_graphcorr',
|
| 22 |
+
'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp',
|
| 23 |
+
'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel',
|
| 24 |
+
'kstest', 'ks_1samp', 'ks_2samp',
|
| 25 |
+
'chisquare', 'power_divergence',
|
| 26 |
+
'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare',
|
| 27 |
+
'rankdata',
|
| 28 |
+
'combine_pvalues', 'wasserstein_distance', 'energy_distance',
|
| 29 |
+
'brunnermunzel', 'alexandergovern', 'distributions',
|
| 30 |
+
'mstats_basic',
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def __dir__():
|
| 35 |
+
return __all__
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def __getattr__(name):
|
| 39 |
+
return _sub_module_deprecation(sub_package="stats", module="stats",
|
| 40 |
+
private_modules=["_stats_py", "_mgc"], all=__all__,
|
| 41 |
+
attribute=name)
|
shared/package-files/12/1208156318870b85d5a072e628bee50312f19661ea71f0c86f5679725a8943c5/qconfig_mapping.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
from collections import OrderedDict
|
| 3 |
+
from typing import Any, Callable, Dict, Tuple, Union, List
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from .fake_quantize import (
|
| 8 |
+
default_weight_fake_quant,
|
| 9 |
+
FixedQParamsFakeQuantize,
|
| 10 |
+
)
|
| 11 |
+
from .observer import (
|
| 12 |
+
_PartialWrapper,
|
| 13 |
+
default_fixed_qparams_range_0to1_observer,
|
| 14 |
+
default_fixed_qparams_range_neg1to1_observer,
|
| 15 |
+
default_placeholder_observer,
|
| 16 |
+
default_weight_observer,
|
| 17 |
+
)
|
| 18 |
+
from .qconfig import (
|
| 19 |
+
default_reuse_input_qconfig,
|
| 20 |
+
default_symmetric_qnnpack_qconfig,
|
| 21 |
+
default_symmetric_qnnpack_qat_qconfig,
|
| 22 |
+
get_default_qconfig,
|
| 23 |
+
get_default_qat_qconfig,
|
| 24 |
+
QConfig,
|
| 25 |
+
QConfigAny,
|
| 26 |
+
default_quint8_weight_qconfig
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
__all__ = [
|
| 31 |
+
"get_default_qconfig_mapping",
|
| 32 |
+
"get_default_qat_qconfig_mapping",
|
| 33 |
+
"QConfigMapping",
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# TODO: replace all usages with these constants
|
| 38 |
+
_GLOBAL_DICT_KEY = ""
|
| 39 |
+
_OBJECT_TYPE_DICT_KEY = "object_type"
|
| 40 |
+
_MODULE_NAME_REGEX_DICT_KEY = "module_name_regex"
|
| 41 |
+
_MODULE_NAME_DICT_KEY = "module_name"
|
| 42 |
+
_MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY = "module_name_object_type_order"
|
| 43 |
+
|
| 44 |
+
# TODO: derive this map from the BackendConfig
|
| 45 |
+
_FIXED_QPARAMS_OP_TO_OBSERVER: Dict[Union[Callable, str], _PartialWrapper] = {
|
| 46 |
+
torch.nn.Hardsigmoid: default_fixed_qparams_range_0to1_observer,
|
| 47 |
+
torch.nn.functional.hardsigmoid: default_fixed_qparams_range_0to1_observer,
|
| 48 |
+
"hardsigmoid": default_fixed_qparams_range_0to1_observer,
|
| 49 |
+
"hardsigmoid_": default_fixed_qparams_range_0to1_observer,
|
| 50 |
+
torch.nn.Sigmoid: default_fixed_qparams_range_0to1_observer,
|
| 51 |
+
torch.sigmoid: default_fixed_qparams_range_0to1_observer,
|
| 52 |
+
"sigmoid": default_fixed_qparams_range_0to1_observer,
|
| 53 |
+
"sigmoid_": default_fixed_qparams_range_0to1_observer,
|
| 54 |
+
torch.nn.Softmax: default_fixed_qparams_range_0to1_observer,
|
| 55 |
+
torch.nn.Tanh: default_fixed_qparams_range_neg1to1_observer,
|
| 56 |
+
torch.tanh: default_fixed_qparams_range_neg1to1_observer,
|
| 57 |
+
"tanh": default_fixed_qparams_range_neg1to1_observer,
|
| 58 |
+
"tanh_": default_fixed_qparams_range_neg1to1_observer,
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _get_default_qconfig_mapping(is_qat: bool, backend: str, version: int) -> QConfigMapping:
|
| 63 |
+
"""
|
| 64 |
+
Return the default QConfigMapping for the given quantization type and backend.
|
| 65 |
+
"""
|
| 66 |
+
if is_qat:
|
| 67 |
+
qconfig = get_default_qat_qconfig(backend, version)
|
| 68 |
+
else:
|
| 69 |
+
qconfig = get_default_qconfig(backend, version)
|
| 70 |
+
default_weight = default_weight_fake_quant if is_qat else default_weight_observer
|
| 71 |
+
|
| 72 |
+
# default_per_channel_weight_observer is not currently compatible with fbgemm backend
|
| 73 |
+
# so we have to modify the weight observer to default_weight_observer or another
|
| 74 |
+
# per tensor supported observer.
|
| 75 |
+
# see https://github.com/pytorch/pytorch/issues/47535
|
| 76 |
+
if backend in ("fbgemm", "x86"):
|
| 77 |
+
qconfig_transpose = QConfig(activation=qconfig.activation, weight=default_weight)
|
| 78 |
+
else:
|
| 79 |
+
qconfig_transpose = qconfig
|
| 80 |
+
|
| 81 |
+
# currently layernorm only supports float weights
|
| 82 |
+
# we have to add this because otherwise there will be a extra quantize-dequantize pair
|
| 83 |
+
qconfig_layernorm = QConfig(activation=qconfig.activation, weight=default_placeholder_observer)
|
| 84 |
+
|
| 85 |
+
qconfig_mapping = QConfigMapping() \
|
| 86 |
+
.set_global(qconfig) \
|
| 87 |
+
.set_object_type("reshape", default_reuse_input_qconfig) \
|
| 88 |
+
.set_object_type(torch.nn.ConvTranspose1d, qconfig_transpose) \
|
| 89 |
+
.set_object_type(torch.nn.ConvTranspose2d, qconfig_transpose) \
|
| 90 |
+
.set_object_type(torch.nn.ConvTranspose3d, qconfig_transpose) \
|
| 91 |
+
.set_object_type(torch.nn.functional.conv_transpose1d, qconfig_transpose) \
|
| 92 |
+
.set_object_type(torch.nn.functional.conv_transpose2d, qconfig_transpose) \
|
| 93 |
+
.set_object_type(torch.nn.functional.conv_transpose3d, qconfig_transpose) \
|
| 94 |
+
.set_object_type(torch.nn.functional.layer_norm, qconfig_layernorm) \
|
| 95 |
+
.set_object_type(torch.nn.LayerNorm, qconfig_layernorm) \
|
| 96 |
+
.set_object_type(torch.nn.PReLU, default_quint8_weight_qconfig) \
|
| 97 |
+
|
| 98 |
+
# Use special observers for ops with fixed qparams
|
| 99 |
+
fixed_qparams_observer_to_qconfig: Dict[Any, QConfigAny] = {}
|
| 100 |
+
for fixed_qparams_op, observer in _FIXED_QPARAMS_OP_TO_OBSERVER.items():
|
| 101 |
+
if observer in fixed_qparams_observer_to_qconfig:
|
| 102 |
+
fixed_qparams_qconfig = fixed_qparams_observer_to_qconfig[observer]
|
| 103 |
+
else:
|
| 104 |
+
if is_qat:
|
| 105 |
+
activation = FixedQParamsFakeQuantize.with_args(observer=observer)
|
| 106 |
+
else:
|
| 107 |
+
activation = observer
|
| 108 |
+
fixed_qparams_qconfig = QConfig(activation=activation, weight=default_weight)
|
| 109 |
+
fixed_qparams_observer_to_qconfig[observer] = fixed_qparams_qconfig
|
| 110 |
+
qconfig_mapping.set_object_type(fixed_qparams_op, fixed_qparams_qconfig)
|
| 111 |
+
|
| 112 |
+
# TODO Currently it's required that separate ops in a fused op/module have the same qconfig.
|
| 113 |
+
# Need to be able to support fusion of ops with different qconfigs
|
| 114 |
+
|
| 115 |
+
return qconfig_mapping
|
| 116 |
+
|
| 117 |
+
def get_default_qconfig_mapping(backend="x86", version=0) -> QConfigMapping:
|
| 118 |
+
"""
|
| 119 |
+
Return the default QConfigMapping for post training quantization.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
* ``backend`` (str) : the quantization backend for the default qconfig mapping, should be
|
| 123 |
+
one of ["x86" (default), "fbgemm", "qnnpack", "onednn"]
|
| 124 |
+
* ``version`` (int) : the version for the default qconfig mapping
|
| 125 |
+
"""
|
| 126 |
+
# TODO: add assert for backend choices
|
| 127 |
+
return _get_default_qconfig_mapping(False, backend, version)
|
| 128 |
+
|
| 129 |
+
def get_default_qat_qconfig_mapping(backend="x86", version=1) -> QConfigMapping:
|
| 130 |
+
"""
|
| 131 |
+
Return the default QConfigMapping for quantization aware training.
|
| 132 |
+
|
| 133 |
+
Args:
|
| 134 |
+
* ``backend`` (str) : the quantization backend for the default qconfig mapping, should be
|
| 135 |
+
one of ["x86" (default), "fbgemm", "qnnpack", "onednn"]
|
| 136 |
+
* ``version`` (int) : the version for the default qconfig mapping
|
| 137 |
+
"""
|
| 138 |
+
return _get_default_qconfig_mapping(True, backend, version)
|
| 139 |
+
|
| 140 |
+
def _get_symmetric_qnnpack_qconfig_mapping() -> QConfigMapping:
|
| 141 |
+
"""
|
| 142 |
+
Return a QConfigMapping that uses `torch.ao.quantization.default_symmetric_qnnpack_qconfig`
|
| 143 |
+
as the default QConfig.
|
| 144 |
+
"""
|
| 145 |
+
default_qconfig = default_symmetric_qnnpack_qconfig
|
| 146 |
+
return _get_default_qconfig_mapping_with_default_qconfig(False, "qnnpack", default_qconfig)
|
| 147 |
+
|
| 148 |
+
def _get_symmetric_qnnpack_qat_qconfig_mapping() -> QConfigMapping:
|
| 149 |
+
"""
|
| 150 |
+
Return a QConfigMapping that uses `torch.ao.quantization.default_symmetric_qnnpack_qat_qconfig`
|
| 151 |
+
as the default QConfig.
|
| 152 |
+
"""
|
| 153 |
+
default_qconfig = default_symmetric_qnnpack_qat_qconfig
|
| 154 |
+
return _get_default_qconfig_mapping_with_default_qconfig(True, "qnnpack", default_qconfig)
|
| 155 |
+
|
| 156 |
+
def _get_default_qconfig_mapping_with_default_qconfig(
|
| 157 |
+
is_qat: bool,
|
| 158 |
+
backend: str,
|
| 159 |
+
default_qconfig: QConfig,
|
| 160 |
+
) -> QConfigMapping:
|
| 161 |
+
"""
|
| 162 |
+
Return a QConfigMapping that uses the provided qconfig as the default QConfig.
|
| 163 |
+
"""
|
| 164 |
+
if is_qat:
|
| 165 |
+
qconfig_mapping = get_default_qat_qconfig_mapping(backend)
|
| 166 |
+
else:
|
| 167 |
+
qconfig_mapping = get_default_qconfig_mapping(backend)
|
| 168 |
+
qconfig_mapping.set_global(default_qconfig)
|
| 169 |
+
for pattern in qconfig_mapping.object_type_qconfigs.keys():
|
| 170 |
+
if pattern not in _FIXED_QPARAMS_OP_TO_OBSERVER:
|
| 171 |
+
qconfig_mapping.set_object_type(pattern, default_qconfig)
|
| 172 |
+
return qconfig_mapping
|
| 173 |
+
|
| 174 |
+
_QCONFIG_STYLE_ORDER: List[str] = [
|
| 175 |
+
"global_qconfig",
|
| 176 |
+
"object_type_qconfigs",
|
| 177 |
+
"module_name_regex_qconfigs",
|
| 178 |
+
"module_name_qconfigs",
|
| 179 |
+
"module_name_object_type_order_qconfigs",
|
| 180 |
+
]
|
| 181 |
+
|
| 182 |
+
class QConfigMapping:
|
| 183 |
+
"""
|
| 184 |
+
Mapping from model ops to :class:`torch.ao.quantization.QConfig` s.
|
| 185 |
+
|
| 186 |
+
The user can specify QConfigs using the following methods (in increasing match priority):
|
| 187 |
+
|
| 188 |
+
``set_global`` : sets the global (default) QConfig
|
| 189 |
+
|
| 190 |
+
``set_object_type`` : sets the QConfig for a given module type, function, or method name
|
| 191 |
+
|
| 192 |
+
``set_module_name_regex`` : sets the QConfig for modules matching the given regex string
|
| 193 |
+
|
| 194 |
+
``set_module_name`` : sets the QConfig for modules matching the given module name
|
| 195 |
+
|
| 196 |
+
``set_module_name_object_type_order`` : sets the QConfig for modules matching a combination
|
| 197 |
+
of the given module name, object type, and the index at which the module appears
|
| 198 |
+
|
| 199 |
+
Example usage::
|
| 200 |
+
|
| 201 |
+
qconfig_mapping = QConfigMapping()
|
| 202 |
+
.set_global(global_qconfig)
|
| 203 |
+
.set_object_type(torch.nn.Linear, qconfig1)
|
| 204 |
+
.set_object_type(torch.nn.ReLU, qconfig1)
|
| 205 |
+
.set_module_name_regex("foo.*bar.*conv[0-9]+", qconfig1)
|
| 206 |
+
.set_module_name_regex("foo.*", qconfig2)
|
| 207 |
+
.set_module_name("module1", qconfig1)
|
| 208 |
+
.set_module_name("module2", qconfig2)
|
| 209 |
+
.set_module_name_object_type_order("foo.bar", torch.nn.functional.linear, 0, qconfig3)
|
| 210 |
+
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
def __init__(self):
|
| 214 |
+
# In increasing match priority:
|
| 215 |
+
self.global_qconfig: QConfigAny = None
|
| 216 |
+
self.object_type_qconfigs: OrderedDict[Union[Callable, str], QConfigAny] = OrderedDict()
|
| 217 |
+
self.module_name_regex_qconfigs: OrderedDict[str, QConfigAny] = OrderedDict()
|
| 218 |
+
self.module_name_qconfigs: OrderedDict[str, QConfigAny] = OrderedDict()
|
| 219 |
+
self.module_name_object_type_order_qconfigs: OrderedDict[Tuple[str, Callable, int], QConfigAny] =\
|
| 220 |
+
OrderedDict()
|
| 221 |
+
|
| 222 |
+
def set_global(self, global_qconfig: QConfigAny) -> QConfigMapping:
|
| 223 |
+
"""
|
| 224 |
+
Set the global (default) QConfig.
|
| 225 |
+
"""
|
| 226 |
+
self.global_qconfig = global_qconfig
|
| 227 |
+
return self
|
| 228 |
+
|
| 229 |
+
def set_object_type(self, object_type: Union[Callable, str], qconfig: QConfigAny) -> QConfigMapping:
|
| 230 |
+
"""
|
| 231 |
+
Set the QConfig for a given module type, function, or method name.
|
| 232 |
+
If the QConfig for an existing object type was already set, the new QConfig will override the old one.
|
| 233 |
+
"""
|
| 234 |
+
self.object_type_qconfigs[object_type] = qconfig
|
| 235 |
+
return self
|
| 236 |
+
|
| 237 |
+
def set_module_name_regex(self, module_name_regex: str, qconfig: QConfigAny) -> QConfigMapping:
|
| 238 |
+
"""
|
| 239 |
+
Set the QConfig for modules matching the given regex string.
|
| 240 |
+
|
| 241 |
+
Regexes will be matched in the order in which they are registered through this method.
|
| 242 |
+
Thus, the caller should register more specific patterns first, e.g.::
|
| 243 |
+
|
| 244 |
+
qconfig_mapping = QConfigMapping()
|
| 245 |
+
.set_module_name_regex("foo.*bar.*conv[0-9]+", qconfig1)
|
| 246 |
+
.set_module_name_regex("foo.*bar.*", qconfig2)
|
| 247 |
+
.set_module_name_regex("foo.*", qconfig3)
|
| 248 |
+
|
| 249 |
+
In this example, "foo.bar.conv0" would match qconfig1, "foo.bar.linear" would match qconfig2,
|
| 250 |
+
and "foo.baz.relu" would match qconfig3.
|
| 251 |
+
|
| 252 |
+
If the QConfig for an existing module name regex was already set, the new QConfig will override the
|
| 253 |
+
old one while preserving the order in which the regexes were originally registered.
|
| 254 |
+
"""
|
| 255 |
+
self.module_name_regex_qconfigs[module_name_regex] = qconfig
|
| 256 |
+
return self
|
| 257 |
+
|
| 258 |
+
def set_module_name(self, module_name: str, qconfig: QConfigAny) -> QConfigMapping:
|
| 259 |
+
"""
|
| 260 |
+
Set the QConfig for modules matching the given module name.
|
| 261 |
+
If the QConfig for an existing module name was already set, the new QConfig will override the old one.
|
| 262 |
+
"""
|
| 263 |
+
self.module_name_qconfigs[module_name] = qconfig
|
| 264 |
+
return self
|
| 265 |
+
|
| 266 |
+
def set_module_name_object_type_order(
|
| 267 |
+
self,
|
| 268 |
+
module_name: str,
|
| 269 |
+
object_type: Callable,
|
| 270 |
+
index: int,
|
| 271 |
+
qconfig: QConfigAny) -> QConfigMapping:
|
| 272 |
+
"""
|
| 273 |
+
Set the QConfig for modules matching a combination of the given module name, object type,
|
| 274 |
+
and the index at which the module appears.
|
| 275 |
+
|
| 276 |
+
If the QConfig for an existing (module name, object type, index) was already set, the new QConfig
|
| 277 |
+
will override the old one.
|
| 278 |
+
"""
|
| 279 |
+
self.module_name_object_type_order_qconfigs[(module_name, object_type, index)] = qconfig
|
| 280 |
+
return self
|
| 281 |
+
|
| 282 |
+
def __repr__(self) -> str:
|
| 283 |
+
output = self.__class__.__name__ + " ("
|
| 284 |
+
for style_name in _QCONFIG_STYLE_ORDER:
|
| 285 |
+
output += f"\n {style_name}"
|
| 286 |
+
qconfigs = getattr(self, style_name)
|
| 287 |
+
if isinstance(qconfigs, OrderedDict) and len(qconfigs) > 0:
|
| 288 |
+
for key, qconfig in qconfigs.items():
|
| 289 |
+
output += f"\n {key}: {qconfig}"
|
| 290 |
+
else:
|
| 291 |
+
output += f"\n {qconfigs}"
|
| 292 |
+
return output + "\n)"
|
| 293 |
+
|
| 294 |
+
# TODO: remove this
|
| 295 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 296 |
+
"""
|
| 297 |
+
Convert this ``QConfigMapping`` to a dictionary with the following keys:
|
| 298 |
+
|
| 299 |
+
"" (for global QConfig)
|
| 300 |
+
|
| 301 |
+
"object_type"
|
| 302 |
+
|
| 303 |
+
"module_name_regex"
|
| 304 |
+
|
| 305 |
+
"module_name"
|
| 306 |
+
|
| 307 |
+
"module_name_object_type_order"
|
| 308 |
+
|
| 309 |
+
The values of this dictionary are lists of tuples.
|
| 310 |
+
"""
|
| 311 |
+
return {
|
| 312 |
+
_GLOBAL_DICT_KEY: self.global_qconfig,
|
| 313 |
+
_OBJECT_TYPE_DICT_KEY: list(self.object_type_qconfigs.items()),
|
| 314 |
+
_MODULE_NAME_REGEX_DICT_KEY: list(self.module_name_regex_qconfigs.items()),
|
| 315 |
+
_MODULE_NAME_DICT_KEY: list(self.module_name_qconfigs.items()),
|
| 316 |
+
_MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY: [
|
| 317 |
+
(*k, v) for k, v in self.module_name_object_type_order_qconfigs.items()
|
| 318 |
+
],
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
# TODO: remove this
|
| 322 |
+
@classmethod
|
| 323 |
+
def from_dict(cls, qconfig_dict: Dict[str, Any]) -> QConfigMapping:
|
| 324 |
+
"""
|
| 325 |
+
Create a ``QConfigMapping`` from a dictionary with the following keys (all optional):
|
| 326 |
+
|
| 327 |
+
"" (for global QConfig)
|
| 328 |
+
|
| 329 |
+
"object_type"
|
| 330 |
+
|
| 331 |
+
"module_name_regex"
|
| 332 |
+
|
| 333 |
+
"module_name"
|
| 334 |
+
|
| 335 |
+
"module_name_object_type_order"
|
| 336 |
+
|
| 337 |
+
The values of this dictionary are expected to be lists of tuples.
|
| 338 |
+
"""
|
| 339 |
+
conf = cls()
|
| 340 |
+
if _GLOBAL_DICT_KEY in qconfig_dict:
|
| 341 |
+
conf.set_global(qconfig_dict[_GLOBAL_DICT_KEY])
|
| 342 |
+
for object_type, qconfig in qconfig_dict.get(_OBJECT_TYPE_DICT_KEY, []):
|
| 343 |
+
conf.set_object_type(object_type, qconfig)
|
| 344 |
+
for module_name_regex, qconfig in qconfig_dict.get(_MODULE_NAME_REGEX_DICT_KEY, []):
|
| 345 |
+
conf.set_module_name_regex(module_name_regex, qconfig)
|
| 346 |
+
for module_name, qconfig in qconfig_dict.get(_MODULE_NAME_DICT_KEY, []):
|
| 347 |
+
conf.set_module_name(module_name, qconfig)
|
| 348 |
+
for module_name, object_type, index, qconfig in qconfig_dict.get(_MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY, []):
|
| 349 |
+
conf.set_module_name_object_type_order(module_name, object_type, index, qconfig)
|
| 350 |
+
return conf
|
shared/package-files/12/120b4c07575f5c9b170d7f207ec38dae3c8049f7f6b6673d48a839b368b279f2/native_group_norm_backward_cpu_dispatch.h
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cpu {
|
| 19 |
+
|
| 20 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> native_group_norm_backward(const at::Tensor & grad_out, const at::Tensor & input, const at::Tensor & mean, const at::Tensor & rstd, const c10::optional<at::Tensor> & weight, int64_t N, int64_t C, int64_t HxW, int64_t group, ::std::array<bool,3> output_mask);
|
| 21 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> native_group_norm_backward_symint(const at::Tensor & grad_out, const at::Tensor & input, const at::Tensor & mean, const at::Tensor & rstd, const c10::optional<at::Tensor> & weight, c10::SymInt N, c10::SymInt C, c10::SymInt HxW, int64_t group, ::std::array<bool,3> output_mask);
|
| 22 |
+
|
| 23 |
+
} // namespace cpu
|
| 24 |
+
} // namespace at
|
shared/package-files/12/120c868dc68b10f7e52a10b9e0d1b0641f3d6e945a3b0a9df5ab2b79ea2301d9/test_common_basic.py
ADDED
|
@@ -0,0 +1,983 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that work on both the Python and C engines but do not have a
|
| 3 |
+
specific classification into the other test modules.
|
| 4 |
+
"""
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from inspect import signature
|
| 7 |
+
from io import StringIO
|
| 8 |
+
import os
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import sys
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import pytest
|
| 14 |
+
|
| 15 |
+
from pandas._config import using_string_dtype
|
| 16 |
+
|
| 17 |
+
from pandas.compat import HAS_PYARROW
|
| 18 |
+
from pandas.errors import (
|
| 19 |
+
EmptyDataError,
|
| 20 |
+
ParserError,
|
| 21 |
+
ParserWarning,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
from pandas import (
|
| 25 |
+
DataFrame,
|
| 26 |
+
Index,
|
| 27 |
+
Timestamp,
|
| 28 |
+
compat,
|
| 29 |
+
)
|
| 30 |
+
import pandas._testing as tm
|
| 31 |
+
|
| 32 |
+
from pandas.io.parsers import TextFileReader
|
| 33 |
+
from pandas.io.parsers.c_parser_wrapper import CParserWrapper
|
| 34 |
+
|
| 35 |
+
pytestmark = pytest.mark.filterwarnings(
|
| 36 |
+
"ignore:Passing a BlockManager to DataFrame:DeprecationWarning"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
|
| 40 |
+
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_override_set_noconvert_columns():
|
| 44 |
+
# see gh-17351
|
| 45 |
+
#
|
| 46 |
+
# Usecols needs to be sorted in _set_noconvert_columns based
|
| 47 |
+
# on the test_usecols_with_parse_dates test from test_usecols.py
|
| 48 |
+
class MyTextFileReader(TextFileReader):
|
| 49 |
+
def __init__(self) -> None:
|
| 50 |
+
self._currow = 0
|
| 51 |
+
self.squeeze = False
|
| 52 |
+
|
| 53 |
+
class MyCParserWrapper(CParserWrapper):
|
| 54 |
+
def _set_noconvert_columns(self):
|
| 55 |
+
if self.usecols_dtype == "integer":
|
| 56 |
+
# self.usecols is a set, which is documented as unordered
|
| 57 |
+
# but in practice, a CPython set of integers is sorted.
|
| 58 |
+
# In other implementations this assumption does not hold.
|
| 59 |
+
# The following code simulates a different order, which
|
| 60 |
+
# before GH 17351 would cause the wrong columns to be
|
| 61 |
+
# converted via the parse_dates parameter
|
| 62 |
+
self.usecols = list(self.usecols)
|
| 63 |
+
self.usecols.reverse()
|
| 64 |
+
return CParserWrapper._set_noconvert_columns(self)
|
| 65 |
+
|
| 66 |
+
data = """a,b,c,d,e
|
| 67 |
+
0,1,2014-01-01,09:00,4
|
| 68 |
+
0,1,2014-01-02,10:00,4"""
|
| 69 |
+
|
| 70 |
+
parse_dates = [[1, 2]]
|
| 71 |
+
cols = {
|
| 72 |
+
"a": [0, 0],
|
| 73 |
+
"c_d": [Timestamp("2014-01-01 09:00:00"), Timestamp("2014-01-02 10:00:00")],
|
| 74 |
+
}
|
| 75 |
+
expected = DataFrame(cols, columns=["c_d", "a"])
|
| 76 |
+
|
| 77 |
+
parser = MyTextFileReader()
|
| 78 |
+
parser.options = {
|
| 79 |
+
"usecols": [0, 2, 3],
|
| 80 |
+
"parse_dates": parse_dates,
|
| 81 |
+
"delimiter": ",",
|
| 82 |
+
}
|
| 83 |
+
parser.engine = "c"
|
| 84 |
+
parser._engine = MyCParserWrapper(StringIO(data), **parser.options)
|
| 85 |
+
|
| 86 |
+
result = parser.read()
|
| 87 |
+
tm.assert_frame_equal(result, expected)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def test_read_csv_local(all_parsers, csv1):
|
| 91 |
+
prefix = "file:///" if compat.is_platform_windows() else "file://"
|
| 92 |
+
parser = all_parsers
|
| 93 |
+
|
| 94 |
+
fname = prefix + str(os.path.abspath(csv1))
|
| 95 |
+
result = parser.read_csv(fname, index_col=0, parse_dates=True)
|
| 96 |
+
# TODO: make unit check more specific
|
| 97 |
+
if parser.engine == "pyarrow":
|
| 98 |
+
result.index = result.index.as_unit("ns")
|
| 99 |
+
expected = DataFrame(
|
| 100 |
+
[
|
| 101 |
+
[0.980269, 3.685731, -0.364216805298, -1.159738],
|
| 102 |
+
[1.047916, -0.041232, -0.16181208307, 0.212549],
|
| 103 |
+
[0.498581, 0.731168, -0.537677223318, 1.346270],
|
| 104 |
+
[1.120202, 1.567621, 0.00364077397681, 0.675253],
|
| 105 |
+
[-0.487094, 0.571455, -1.6116394093, 0.103469],
|
| 106 |
+
[0.836649, 0.246462, 0.588542635376, 1.062782],
|
| 107 |
+
[-0.157161, 1.340307, 1.1957779562, -1.097007],
|
| 108 |
+
],
|
| 109 |
+
columns=["A", "B", "C", "D"],
|
| 110 |
+
index=Index(
|
| 111 |
+
[
|
| 112 |
+
datetime(2000, 1, 3),
|
| 113 |
+
datetime(2000, 1, 4),
|
| 114 |
+
datetime(2000, 1, 5),
|
| 115 |
+
datetime(2000, 1, 6),
|
| 116 |
+
datetime(2000, 1, 7),
|
| 117 |
+
datetime(2000, 1, 10),
|
| 118 |
+
datetime(2000, 1, 11),
|
| 119 |
+
],
|
| 120 |
+
name="index",
|
| 121 |
+
),
|
| 122 |
+
)
|
| 123 |
+
tm.assert_frame_equal(result, expected)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def test_1000_sep(all_parsers):
|
| 127 |
+
parser = all_parsers
|
| 128 |
+
data = """A|B|C
|
| 129 |
+
1|2,334|5
|
| 130 |
+
10|13|10.
|
| 131 |
+
"""
|
| 132 |
+
expected = DataFrame({"A": [1, 10], "B": [2334, 13], "C": [5, 10.0]})
|
| 133 |
+
|
| 134 |
+
if parser.engine == "pyarrow":
|
| 135 |
+
msg = "The 'thousands' option is not supported with the 'pyarrow' engine"
|
| 136 |
+
with pytest.raises(ValueError, match=msg):
|
| 137 |
+
parser.read_csv(StringIO(data), sep="|", thousands=",")
|
| 138 |
+
return
|
| 139 |
+
|
| 140 |
+
result = parser.read_csv(StringIO(data), sep="|", thousands=",")
|
| 141 |
+
tm.assert_frame_equal(result, expected)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@xfail_pyarrow # ValueError: Found non-unique column index
|
| 145 |
+
def test_unnamed_columns(all_parsers):
|
| 146 |
+
data = """A,B,C,,
|
| 147 |
+
1,2,3,4,5
|
| 148 |
+
6,7,8,9,10
|
| 149 |
+
11,12,13,14,15
|
| 150 |
+
"""
|
| 151 |
+
parser = all_parsers
|
| 152 |
+
expected = DataFrame(
|
| 153 |
+
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]],
|
| 154 |
+
dtype=np.int64,
|
| 155 |
+
columns=["A", "B", "C", "Unnamed: 3", "Unnamed: 4"],
|
| 156 |
+
)
|
| 157 |
+
result = parser.read_csv(StringIO(data))
|
| 158 |
+
tm.assert_frame_equal(result, expected)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def test_csv_mixed_type(all_parsers):
|
| 162 |
+
data = """A,B,C
|
| 163 |
+
a,1,2
|
| 164 |
+
b,3,4
|
| 165 |
+
c,4,5
|
| 166 |
+
"""
|
| 167 |
+
parser = all_parsers
|
| 168 |
+
expected = DataFrame({"A": ["a", "b", "c"], "B": [1, 3, 4], "C": [2, 4, 5]})
|
| 169 |
+
result = parser.read_csv(StringIO(data))
|
| 170 |
+
tm.assert_frame_equal(result, expected)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def test_read_csv_low_memory_no_rows_with_index(all_parsers):
|
| 174 |
+
# see gh-21141
|
| 175 |
+
parser = all_parsers
|
| 176 |
+
|
| 177 |
+
if not parser.low_memory:
|
| 178 |
+
pytest.skip("This is a low-memory specific test")
|
| 179 |
+
|
| 180 |
+
data = """A,B,C
|
| 181 |
+
1,1,1,2
|
| 182 |
+
2,2,3,4
|
| 183 |
+
3,3,4,5
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
if parser.engine == "pyarrow":
|
| 187 |
+
msg = "The 'nrows' option is not supported with the 'pyarrow' engine"
|
| 188 |
+
with pytest.raises(ValueError, match=msg):
|
| 189 |
+
parser.read_csv(StringIO(data), low_memory=True, index_col=0, nrows=0)
|
| 190 |
+
return
|
| 191 |
+
|
| 192 |
+
result = parser.read_csv(StringIO(data), low_memory=True, index_col=0, nrows=0)
|
| 193 |
+
expected = DataFrame(columns=["A", "B", "C"])
|
| 194 |
+
tm.assert_frame_equal(result, expected)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def test_read_csv_dataframe(all_parsers, csv1):
|
| 198 |
+
parser = all_parsers
|
| 199 |
+
result = parser.read_csv(csv1, index_col=0, parse_dates=True)
|
| 200 |
+
# TODO: make unit check more specific
|
| 201 |
+
if parser.engine == "pyarrow":
|
| 202 |
+
result.index = result.index.as_unit("ns")
|
| 203 |
+
expected = DataFrame(
|
| 204 |
+
[
|
| 205 |
+
[0.980269, 3.685731, -0.364216805298, -1.159738],
|
| 206 |
+
[1.047916, -0.041232, -0.16181208307, 0.212549],
|
| 207 |
+
[0.498581, 0.731168, -0.537677223318, 1.346270],
|
| 208 |
+
[1.120202, 1.567621, 0.00364077397681, 0.675253],
|
| 209 |
+
[-0.487094, 0.571455, -1.6116394093, 0.103469],
|
| 210 |
+
[0.836649, 0.246462, 0.588542635376, 1.062782],
|
| 211 |
+
[-0.157161, 1.340307, 1.1957779562, -1.097007],
|
| 212 |
+
],
|
| 213 |
+
columns=["A", "B", "C", "D"],
|
| 214 |
+
index=Index(
|
| 215 |
+
[
|
| 216 |
+
datetime(2000, 1, 3),
|
| 217 |
+
datetime(2000, 1, 4),
|
| 218 |
+
datetime(2000, 1, 5),
|
| 219 |
+
datetime(2000, 1, 6),
|
| 220 |
+
datetime(2000, 1, 7),
|
| 221 |
+
datetime(2000, 1, 10),
|
| 222 |
+
datetime(2000, 1, 11),
|
| 223 |
+
],
|
| 224 |
+
name="index",
|
| 225 |
+
),
|
| 226 |
+
)
|
| 227 |
+
tm.assert_frame_equal(result, expected)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
@pytest.mark.parametrize("nrows", [3, 3.0])
|
| 231 |
+
def test_read_nrows(all_parsers, nrows):
|
| 232 |
+
# see gh-10476
|
| 233 |
+
data = """index,A,B,C,D
|
| 234 |
+
foo,2,3,4,5
|
| 235 |
+
bar,7,8,9,10
|
| 236 |
+
baz,12,13,14,15
|
| 237 |
+
qux,12,13,14,15
|
| 238 |
+
foo2,12,13,14,15
|
| 239 |
+
bar2,12,13,14,15
|
| 240 |
+
"""
|
| 241 |
+
expected = DataFrame(
|
| 242 |
+
[["foo", 2, 3, 4, 5], ["bar", 7, 8, 9, 10], ["baz", 12, 13, 14, 15]],
|
| 243 |
+
columns=["index", "A", "B", "C", "D"],
|
| 244 |
+
)
|
| 245 |
+
parser = all_parsers
|
| 246 |
+
|
| 247 |
+
if parser.engine == "pyarrow":
|
| 248 |
+
msg = "The 'nrows' option is not supported with the 'pyarrow' engine"
|
| 249 |
+
with pytest.raises(ValueError, match=msg):
|
| 250 |
+
parser.read_csv(StringIO(data), nrows=nrows)
|
| 251 |
+
return
|
| 252 |
+
|
| 253 |
+
result = parser.read_csv(StringIO(data), nrows=nrows)
|
| 254 |
+
tm.assert_frame_equal(result, expected)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
@pytest.mark.parametrize("nrows", [1.2, "foo", -1])
|
| 258 |
+
def test_read_nrows_bad(all_parsers, nrows):
|
| 259 |
+
data = """index,A,B,C,D
|
| 260 |
+
foo,2,3,4,5
|
| 261 |
+
bar,7,8,9,10
|
| 262 |
+
baz,12,13,14,15
|
| 263 |
+
qux,12,13,14,15
|
| 264 |
+
foo2,12,13,14,15
|
| 265 |
+
bar2,12,13,14,15
|
| 266 |
+
"""
|
| 267 |
+
msg = r"'nrows' must be an integer >=0"
|
| 268 |
+
parser = all_parsers
|
| 269 |
+
if parser.engine == "pyarrow":
|
| 270 |
+
msg = "The 'nrows' option is not supported with the 'pyarrow' engine"
|
| 271 |
+
|
| 272 |
+
with pytest.raises(ValueError, match=msg):
|
| 273 |
+
parser.read_csv(StringIO(data), nrows=nrows)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def test_nrows_skipfooter_errors(all_parsers):
|
| 277 |
+
msg = "'skipfooter' not supported with 'nrows'"
|
| 278 |
+
data = "a\n1\n2\n3\n4\n5\n6"
|
| 279 |
+
parser = all_parsers
|
| 280 |
+
|
| 281 |
+
with pytest.raises(ValueError, match=msg):
|
| 282 |
+
parser.read_csv(StringIO(data), skipfooter=1, nrows=5)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
@skip_pyarrow
|
| 286 |
+
def test_missing_trailing_delimiters(all_parsers):
|
| 287 |
+
parser = all_parsers
|
| 288 |
+
data = """A,B,C,D
|
| 289 |
+
1,2,3,4
|
| 290 |
+
1,3,3,
|
| 291 |
+
1,4,5"""
|
| 292 |
+
|
| 293 |
+
result = parser.read_csv(StringIO(data))
|
| 294 |
+
expected = DataFrame(
|
| 295 |
+
[[1, 2, 3, 4], [1, 3, 3, np.nan], [1, 4, 5, np.nan]],
|
| 296 |
+
columns=["A", "B", "C", "D"],
|
| 297 |
+
)
|
| 298 |
+
tm.assert_frame_equal(result, expected)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def test_skip_initial_space(all_parsers):
|
| 302 |
+
data = (
|
| 303 |
+
'"09-Apr-2012", "01:10:18.300", 2456026.548822908, 12849, '
|
| 304 |
+
"1.00361, 1.12551, 330.65659, 0355626618.16711, 73.48821, "
|
| 305 |
+
"314.11625, 1917.09447, 179.71425, 80.000, 240.000, -350, "
|
| 306 |
+
"70.06056, 344.98370, 1, 1, -0.689265, -0.692787, "
|
| 307 |
+
"0.212036, 14.7674, 41.605, -9999.0, -9999.0, "
|
| 308 |
+
"-9999.0, -9999.0, -9999.0, -9999.0, 000, 012, 128"
|
| 309 |
+
)
|
| 310 |
+
parser = all_parsers
|
| 311 |
+
|
| 312 |
+
if parser.engine == "pyarrow":
|
| 313 |
+
msg = "The 'skipinitialspace' option is not supported with the 'pyarrow' engine"
|
| 314 |
+
with pytest.raises(ValueError, match=msg):
|
| 315 |
+
parser.read_csv(
|
| 316 |
+
StringIO(data),
|
| 317 |
+
names=list(range(33)),
|
| 318 |
+
header=None,
|
| 319 |
+
na_values=["-9999.0"],
|
| 320 |
+
skipinitialspace=True,
|
| 321 |
+
)
|
| 322 |
+
return
|
| 323 |
+
|
| 324 |
+
result = parser.read_csv(
|
| 325 |
+
StringIO(data),
|
| 326 |
+
names=list(range(33)),
|
| 327 |
+
header=None,
|
| 328 |
+
na_values=["-9999.0"],
|
| 329 |
+
skipinitialspace=True,
|
| 330 |
+
)
|
| 331 |
+
expected = DataFrame(
|
| 332 |
+
[
|
| 333 |
+
[
|
| 334 |
+
"09-Apr-2012",
|
| 335 |
+
"01:10:18.300",
|
| 336 |
+
2456026.548822908,
|
| 337 |
+
12849,
|
| 338 |
+
1.00361,
|
| 339 |
+
1.12551,
|
| 340 |
+
330.65659,
|
| 341 |
+
355626618.16711,
|
| 342 |
+
73.48821,
|
| 343 |
+
314.11625,
|
| 344 |
+
1917.09447,
|
| 345 |
+
179.71425,
|
| 346 |
+
80.0,
|
| 347 |
+
240.0,
|
| 348 |
+
-350,
|
| 349 |
+
70.06056,
|
| 350 |
+
344.9837,
|
| 351 |
+
1,
|
| 352 |
+
1,
|
| 353 |
+
-0.689265,
|
| 354 |
+
-0.692787,
|
| 355 |
+
0.212036,
|
| 356 |
+
14.7674,
|
| 357 |
+
41.605,
|
| 358 |
+
np.nan,
|
| 359 |
+
np.nan,
|
| 360 |
+
np.nan,
|
| 361 |
+
np.nan,
|
| 362 |
+
np.nan,
|
| 363 |
+
np.nan,
|
| 364 |
+
0,
|
| 365 |
+
12,
|
| 366 |
+
128,
|
| 367 |
+
]
|
| 368 |
+
]
|
| 369 |
+
)
|
| 370 |
+
tm.assert_frame_equal(result, expected)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
@skip_pyarrow
|
| 374 |
+
def test_trailing_delimiters(all_parsers):
|
| 375 |
+
# see gh-2442
|
| 376 |
+
data = """A,B,C
|
| 377 |
+
1,2,3,
|
| 378 |
+
4,5,6,
|
| 379 |
+
7,8,9,"""
|
| 380 |
+
parser = all_parsers
|
| 381 |
+
result = parser.read_csv(StringIO(data), index_col=False)
|
| 382 |
+
|
| 383 |
+
expected = DataFrame({"A": [1, 4, 7], "B": [2, 5, 8], "C": [3, 6, 9]})
|
| 384 |
+
tm.assert_frame_equal(result, expected)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def test_escapechar(all_parsers):
|
| 388 |
+
# https://stackoverflow.com/questions/13824840/feature-request-for-
|
| 389 |
+
# pandas-read-csv
|
| 390 |
+
data = '''SEARCH_TERM,ACTUAL_URL
|
| 391 |
+
"bra tv board","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord"
|
| 392 |
+
"tv p\xc3\xa5 hjul","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord"
|
| 393 |
+
"SLAGBORD, \\"Bergslagen\\", IKEA:s 1700-tals series","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord"'''
|
| 394 |
+
|
| 395 |
+
parser = all_parsers
|
| 396 |
+
result = parser.read_csv(
|
| 397 |
+
StringIO(data), escapechar="\\", quotechar='"', encoding="utf-8"
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
assert result["SEARCH_TERM"][2] == 'SLAGBORD, "Bergslagen", IKEA:s 1700-tals series'
|
| 401 |
+
|
| 402 |
+
tm.assert_index_equal(result.columns, Index(["SEARCH_TERM", "ACTUAL_URL"]))
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def test_ignore_leading_whitespace(all_parsers):
|
| 406 |
+
# see gh-3374, gh-6607
|
| 407 |
+
parser = all_parsers
|
| 408 |
+
data = " a b c\n 1 2 3\n 4 5 6\n 7 8 9"
|
| 409 |
+
|
| 410 |
+
if parser.engine == "pyarrow":
|
| 411 |
+
msg = "the 'pyarrow' engine does not support regex separators"
|
| 412 |
+
with pytest.raises(ValueError, match=msg):
|
| 413 |
+
parser.read_csv(StringIO(data), sep=r"\s+")
|
| 414 |
+
return
|
| 415 |
+
result = parser.read_csv(StringIO(data), sep=r"\s+")
|
| 416 |
+
|
| 417 |
+
expected = DataFrame({"a": [1, 4, 7], "b": [2, 5, 8], "c": [3, 6, 9]})
|
| 418 |
+
tm.assert_frame_equal(result, expected)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
@skip_pyarrow
|
| 422 |
+
@pytest.mark.parametrize("usecols", [None, [0, 1], ["a", "b"]])
|
| 423 |
+
def test_uneven_lines_with_usecols(all_parsers, usecols):
|
| 424 |
+
# see gh-12203
|
| 425 |
+
parser = all_parsers
|
| 426 |
+
data = r"""a,b,c
|
| 427 |
+
0,1,2
|
| 428 |
+
3,4,5,6,7
|
| 429 |
+
8,9,10"""
|
| 430 |
+
|
| 431 |
+
if usecols is None:
|
| 432 |
+
# Make sure that an error is still raised
|
| 433 |
+
# when the "usecols" parameter is not provided.
|
| 434 |
+
msg = r"Expected \d+ fields in line \d+, saw \d+"
|
| 435 |
+
with pytest.raises(ParserError, match=msg):
|
| 436 |
+
parser.read_csv(StringIO(data))
|
| 437 |
+
else:
|
| 438 |
+
expected = DataFrame({"a": [0, 3, 8], "b": [1, 4, 9]})
|
| 439 |
+
|
| 440 |
+
result = parser.read_csv(StringIO(data), usecols=usecols)
|
| 441 |
+
tm.assert_frame_equal(result, expected)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
@skip_pyarrow
|
| 445 |
+
@pytest.mark.parametrize(
|
| 446 |
+
"data,kwargs,expected",
|
| 447 |
+
[
|
| 448 |
+
# First, check to see that the response of parser when faced with no
|
| 449 |
+
# provided columns raises the correct error, with or without usecols.
|
| 450 |
+
("", {}, None),
|
| 451 |
+
("", {"usecols": ["X"]}, None),
|
| 452 |
+
(
|
| 453 |
+
",,",
|
| 454 |
+
{"names": ["Dummy", "X", "Dummy_2"], "usecols": ["X"]},
|
| 455 |
+
DataFrame(columns=["X"], index=[0], dtype=np.float64),
|
| 456 |
+
),
|
| 457 |
+
(
|
| 458 |
+
"",
|
| 459 |
+
{"names": ["Dummy", "X", "Dummy_2"], "usecols": ["X"]},
|
| 460 |
+
DataFrame(columns=["X"]),
|
| 461 |
+
),
|
| 462 |
+
],
|
| 463 |
+
)
|
| 464 |
+
def test_read_empty_with_usecols(all_parsers, data, kwargs, expected):
|
| 465 |
+
# see gh-12493
|
| 466 |
+
parser = all_parsers
|
| 467 |
+
|
| 468 |
+
if expected is None:
|
| 469 |
+
msg = "No columns to parse from file"
|
| 470 |
+
with pytest.raises(EmptyDataError, match=msg):
|
| 471 |
+
parser.read_csv(StringIO(data), **kwargs)
|
| 472 |
+
else:
|
| 473 |
+
result = parser.read_csv(StringIO(data), **kwargs)
|
| 474 |
+
tm.assert_frame_equal(result, expected)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
@pytest.mark.parametrize(
|
| 478 |
+
"kwargs,expected",
|
| 479 |
+
[
|
| 480 |
+
# gh-8661, gh-8679: this should ignore six lines, including
|
| 481 |
+
# lines with trailing whitespace and blank lines.
|
| 482 |
+
(
|
| 483 |
+
{
|
| 484 |
+
"header": None,
|
| 485 |
+
"delim_whitespace": True,
|
| 486 |
+
"skiprows": [0, 1, 2, 3, 5, 6],
|
| 487 |
+
"skip_blank_lines": True,
|
| 488 |
+
},
|
| 489 |
+
DataFrame([[1.0, 2.0, 4.0], [5.1, np.nan, 10.0]]),
|
| 490 |
+
),
|
| 491 |
+
# gh-8983: test skipping set of rows after a row with trailing spaces.
|
| 492 |
+
(
|
| 493 |
+
{
|
| 494 |
+
"delim_whitespace": True,
|
| 495 |
+
"skiprows": [1, 2, 3, 5, 6],
|
| 496 |
+
"skip_blank_lines": True,
|
| 497 |
+
},
|
| 498 |
+
DataFrame({"A": [1.0, 5.1], "B": [2.0, np.nan], "C": [4.0, 10]}),
|
| 499 |
+
),
|
| 500 |
+
],
|
| 501 |
+
)
|
| 502 |
+
def test_trailing_spaces(all_parsers, kwargs, expected):
|
| 503 |
+
data = "A B C \nrandom line with trailing spaces \nskip\n1,2,3\n1,2.,4.\nrandom line with trailing tabs\t\t\t\n \n5.1,NaN,10.0\n" # noqa: E501
|
| 504 |
+
parser = all_parsers
|
| 505 |
+
|
| 506 |
+
depr_msg = "The 'delim_whitespace' keyword in pd.read_csv is deprecated"
|
| 507 |
+
|
| 508 |
+
if parser.engine == "pyarrow":
|
| 509 |
+
msg = "The 'delim_whitespace' option is not supported with the 'pyarrow' engine"
|
| 510 |
+
with pytest.raises(ValueError, match=msg):
|
| 511 |
+
with tm.assert_produces_warning(
|
| 512 |
+
FutureWarning, match=depr_msg, check_stacklevel=False
|
| 513 |
+
):
|
| 514 |
+
parser.read_csv(StringIO(data.replace(",", " ")), **kwargs)
|
| 515 |
+
return
|
| 516 |
+
|
| 517 |
+
with tm.assert_produces_warning(
|
| 518 |
+
FutureWarning, match=depr_msg, check_stacklevel=False
|
| 519 |
+
):
|
| 520 |
+
result = parser.read_csv(StringIO(data.replace(",", " ")), **kwargs)
|
| 521 |
+
tm.assert_frame_equal(result, expected)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def test_raise_on_sep_with_delim_whitespace(all_parsers):
|
| 525 |
+
# see gh-6607
|
| 526 |
+
data = "a b c\n1 2 3"
|
| 527 |
+
parser = all_parsers
|
| 528 |
+
|
| 529 |
+
depr_msg = "The 'delim_whitespace' keyword in pd.read_csv is deprecated"
|
| 530 |
+
with pytest.raises(ValueError, match="you can only specify one"):
|
| 531 |
+
with tm.assert_produces_warning(
|
| 532 |
+
FutureWarning, match=depr_msg, check_stacklevel=False
|
| 533 |
+
):
|
| 534 |
+
parser.read_csv(StringIO(data), sep=r"\s", delim_whitespace=True)
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def test_read_filepath_or_buffer(all_parsers):
|
| 538 |
+
# see gh-43366
|
| 539 |
+
parser = all_parsers
|
| 540 |
+
|
| 541 |
+
with pytest.raises(TypeError, match="Expected file path name or file-like"):
|
| 542 |
+
parser.read_csv(filepath_or_buffer=b"input")
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
@pytest.mark.parametrize("delim_whitespace", [True, False])
|
| 546 |
+
def test_single_char_leading_whitespace(all_parsers, delim_whitespace):
|
| 547 |
+
# see gh-9710
|
| 548 |
+
parser = all_parsers
|
| 549 |
+
data = """\
|
| 550 |
+
MyColumn
|
| 551 |
+
a
|
| 552 |
+
b
|
| 553 |
+
a
|
| 554 |
+
b\n"""
|
| 555 |
+
|
| 556 |
+
expected = DataFrame({"MyColumn": list("abab")})
|
| 557 |
+
depr_msg = "The 'delim_whitespace' keyword in pd.read_csv is deprecated"
|
| 558 |
+
|
| 559 |
+
if parser.engine == "pyarrow":
|
| 560 |
+
msg = "The 'skipinitialspace' option is not supported with the 'pyarrow' engine"
|
| 561 |
+
with pytest.raises(ValueError, match=msg):
|
| 562 |
+
with tm.assert_produces_warning(
|
| 563 |
+
FutureWarning, match=depr_msg, check_stacklevel=False
|
| 564 |
+
):
|
| 565 |
+
parser.read_csv(
|
| 566 |
+
StringIO(data),
|
| 567 |
+
skipinitialspace=True,
|
| 568 |
+
delim_whitespace=delim_whitespace,
|
| 569 |
+
)
|
| 570 |
+
return
|
| 571 |
+
|
| 572 |
+
with tm.assert_produces_warning(
|
| 573 |
+
FutureWarning, match=depr_msg, check_stacklevel=False
|
| 574 |
+
):
|
| 575 |
+
result = parser.read_csv(
|
| 576 |
+
StringIO(data), skipinitialspace=True, delim_whitespace=delim_whitespace
|
| 577 |
+
)
|
| 578 |
+
tm.assert_frame_equal(result, expected)
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
@pytest.mark.parametrize(
|
| 582 |
+
"sep,skip_blank_lines,exp_data",
|
| 583 |
+
[
|
| 584 |
+
(",", True, [[1.0, 2.0, 4.0], [5.0, np.nan, 10.0], [-70.0, 0.4, 1.0]]),
|
| 585 |
+
(r"\s+", True, [[1.0, 2.0, 4.0], [5.0, np.nan, 10.0], [-70.0, 0.4, 1.0]]),
|
| 586 |
+
(
|
| 587 |
+
",",
|
| 588 |
+
False,
|
| 589 |
+
[
|
| 590 |
+
[1.0, 2.0, 4.0],
|
| 591 |
+
[np.nan, np.nan, np.nan],
|
| 592 |
+
[np.nan, np.nan, np.nan],
|
| 593 |
+
[5.0, np.nan, 10.0],
|
| 594 |
+
[np.nan, np.nan, np.nan],
|
| 595 |
+
[-70.0, 0.4, 1.0],
|
| 596 |
+
],
|
| 597 |
+
),
|
| 598 |
+
],
|
| 599 |
+
)
|
| 600 |
+
def test_empty_lines(all_parsers, sep, skip_blank_lines, exp_data, request):
|
| 601 |
+
parser = all_parsers
|
| 602 |
+
data = """\
|
| 603 |
+
A,B,C
|
| 604 |
+
1,2.,4.
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
5.,NaN,10.0
|
| 608 |
+
|
| 609 |
+
-70,.4,1
|
| 610 |
+
"""
|
| 611 |
+
|
| 612 |
+
if sep == r"\s+":
|
| 613 |
+
data = data.replace(",", " ")
|
| 614 |
+
|
| 615 |
+
if parser.engine == "pyarrow":
|
| 616 |
+
msg = "the 'pyarrow' engine does not support regex separators"
|
| 617 |
+
with pytest.raises(ValueError, match=msg):
|
| 618 |
+
parser.read_csv(
|
| 619 |
+
StringIO(data), sep=sep, skip_blank_lines=skip_blank_lines
|
| 620 |
+
)
|
| 621 |
+
return
|
| 622 |
+
|
| 623 |
+
result = parser.read_csv(StringIO(data), sep=sep, skip_blank_lines=skip_blank_lines)
|
| 624 |
+
expected = DataFrame(exp_data, columns=["A", "B", "C"])
|
| 625 |
+
tm.assert_frame_equal(result, expected)
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
@skip_pyarrow
|
| 629 |
+
def test_whitespace_lines(all_parsers):
|
| 630 |
+
parser = all_parsers
|
| 631 |
+
data = """
|
| 632 |
+
|
| 633 |
+
\t \t\t
|
| 634 |
+
\t
|
| 635 |
+
A,B,C
|
| 636 |
+
\t 1,2.,4.
|
| 637 |
+
5.,NaN,10.0
|
| 638 |
+
"""
|
| 639 |
+
expected = DataFrame([[1, 2.0, 4.0], [5.0, np.nan, 10.0]], columns=["A", "B", "C"])
|
| 640 |
+
result = parser.read_csv(StringIO(data))
|
| 641 |
+
tm.assert_frame_equal(result, expected)
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
@pytest.mark.parametrize(
|
| 645 |
+
"data,expected",
|
| 646 |
+
[
|
| 647 |
+
(
|
| 648 |
+
""" A B C D
|
| 649 |
+
a 1 2 3 4
|
| 650 |
+
b 1 2 3 4
|
| 651 |
+
c 1 2 3 4
|
| 652 |
+
""",
|
| 653 |
+
DataFrame(
|
| 654 |
+
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]],
|
| 655 |
+
columns=["A", "B", "C", "D"],
|
| 656 |
+
index=["a", "b", "c"],
|
| 657 |
+
),
|
| 658 |
+
),
|
| 659 |
+
(
|
| 660 |
+
" a b c\n1 2 3 \n4 5 6\n 7 8 9",
|
| 661 |
+
DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["a", "b", "c"]),
|
| 662 |
+
),
|
| 663 |
+
],
|
| 664 |
+
)
|
| 665 |
+
def test_whitespace_regex_separator(all_parsers, data, expected):
|
| 666 |
+
# see gh-6607
|
| 667 |
+
parser = all_parsers
|
| 668 |
+
if parser.engine == "pyarrow":
|
| 669 |
+
msg = "the 'pyarrow' engine does not support regex separators"
|
| 670 |
+
with pytest.raises(ValueError, match=msg):
|
| 671 |
+
parser.read_csv(StringIO(data), sep=r"\s+")
|
| 672 |
+
return
|
| 673 |
+
|
| 674 |
+
result = parser.read_csv(StringIO(data), sep=r"\s+")
|
| 675 |
+
tm.assert_frame_equal(result, expected)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def test_sub_character(all_parsers, csv_dir_path):
|
| 679 |
+
# see gh-16893
|
| 680 |
+
filename = os.path.join(csv_dir_path, "sub_char.csv")
|
| 681 |
+
expected = DataFrame([[1, 2, 3]], columns=["a", "\x1ab", "c"])
|
| 682 |
+
|
| 683 |
+
parser = all_parsers
|
| 684 |
+
result = parser.read_csv(filename)
|
| 685 |
+
tm.assert_frame_equal(result, expected)
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
@pytest.mark.parametrize("filename", ["sé-es-vé.csv", "ru-sй.csv", "中文文件名.csv"])
|
| 689 |
+
def test_filename_with_special_chars(all_parsers, filename):
|
| 690 |
+
# see gh-15086.
|
| 691 |
+
parser = all_parsers
|
| 692 |
+
df = DataFrame({"a": [1, 2, 3]})
|
| 693 |
+
|
| 694 |
+
with tm.ensure_clean(filename) as path:
|
| 695 |
+
df.to_csv(path, index=False)
|
| 696 |
+
|
| 697 |
+
result = parser.read_csv(path)
|
| 698 |
+
tm.assert_frame_equal(result, df)
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
def test_read_table_same_signature_as_read_csv(all_parsers):
|
| 702 |
+
# GH-34976
|
| 703 |
+
parser = all_parsers
|
| 704 |
+
|
| 705 |
+
table_sign = signature(parser.read_table)
|
| 706 |
+
csv_sign = signature(parser.read_csv)
|
| 707 |
+
|
| 708 |
+
assert table_sign.parameters.keys() == csv_sign.parameters.keys()
|
| 709 |
+
assert table_sign.return_annotation == csv_sign.return_annotation
|
| 710 |
+
|
| 711 |
+
for key, csv_param in csv_sign.parameters.items():
|
| 712 |
+
table_param = table_sign.parameters[key]
|
| 713 |
+
if key == "sep":
|
| 714 |
+
assert csv_param.default == ","
|
| 715 |
+
assert table_param.default == "\t"
|
| 716 |
+
assert table_param.annotation == csv_param.annotation
|
| 717 |
+
assert table_param.kind == csv_param.kind
|
| 718 |
+
continue
|
| 719 |
+
|
| 720 |
+
assert table_param == csv_param
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def test_read_table_equivalency_to_read_csv(all_parsers):
|
| 724 |
+
# see gh-21948
|
| 725 |
+
# As of 0.25.0, read_table is undeprecated
|
| 726 |
+
parser = all_parsers
|
| 727 |
+
data = "a\tb\n1\t2\n3\t4"
|
| 728 |
+
expected = parser.read_csv(StringIO(data), sep="\t")
|
| 729 |
+
result = parser.read_table(StringIO(data))
|
| 730 |
+
tm.assert_frame_equal(result, expected)
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
@pytest.mark.parametrize("read_func", ["read_csv", "read_table"])
|
| 734 |
+
def test_read_csv_and_table_sys_setprofile(all_parsers, read_func):
|
| 735 |
+
# GH#41069
|
| 736 |
+
parser = all_parsers
|
| 737 |
+
data = "a b\n0 1"
|
| 738 |
+
|
| 739 |
+
sys.setprofile(lambda *a, **k: None)
|
| 740 |
+
result = getattr(parser, read_func)(StringIO(data))
|
| 741 |
+
sys.setprofile(None)
|
| 742 |
+
|
| 743 |
+
expected = DataFrame({"a b": ["0 1"]})
|
| 744 |
+
tm.assert_frame_equal(result, expected)
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
@skip_pyarrow
|
| 748 |
+
def test_first_row_bom(all_parsers):
|
| 749 |
+
# see gh-26545
|
| 750 |
+
parser = all_parsers
|
| 751 |
+
data = '''\ufeff"Head1"\t"Head2"\t"Head3"'''
|
| 752 |
+
|
| 753 |
+
result = parser.read_csv(StringIO(data), delimiter="\t")
|
| 754 |
+
expected = DataFrame(columns=["Head1", "Head2", "Head3"])
|
| 755 |
+
tm.assert_frame_equal(result, expected)
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
@skip_pyarrow
|
| 759 |
+
def test_first_row_bom_unquoted(all_parsers):
|
| 760 |
+
# see gh-36343
|
| 761 |
+
parser = all_parsers
|
| 762 |
+
data = """\ufeffHead1\tHead2\tHead3"""
|
| 763 |
+
|
| 764 |
+
result = parser.read_csv(StringIO(data), delimiter="\t")
|
| 765 |
+
expected = DataFrame(columns=["Head1", "Head2", "Head3"])
|
| 766 |
+
tm.assert_frame_equal(result, expected)
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
@pytest.mark.parametrize("nrows", range(1, 6))
|
| 770 |
+
def test_blank_lines_between_header_and_data_rows(all_parsers, nrows):
|
| 771 |
+
# GH 28071
|
| 772 |
+
ref = DataFrame(
|
| 773 |
+
[[np.nan, np.nan], [np.nan, np.nan], [1, 2], [np.nan, np.nan], [3, 4]],
|
| 774 |
+
columns=list("ab"),
|
| 775 |
+
)
|
| 776 |
+
csv = "\nheader\n\na,b\n\n\n1,2\n\n3,4"
|
| 777 |
+
parser = all_parsers
|
| 778 |
+
|
| 779 |
+
if parser.engine == "pyarrow":
|
| 780 |
+
msg = "The 'nrows' option is not supported with the 'pyarrow' engine"
|
| 781 |
+
with pytest.raises(ValueError, match=msg):
|
| 782 |
+
parser.read_csv(
|
| 783 |
+
StringIO(csv), header=3, nrows=nrows, skip_blank_lines=False
|
| 784 |
+
)
|
| 785 |
+
return
|
| 786 |
+
|
| 787 |
+
df = parser.read_csv(StringIO(csv), header=3, nrows=nrows, skip_blank_lines=False)
|
| 788 |
+
tm.assert_frame_equal(df, ref[:nrows])
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
@skip_pyarrow
|
| 792 |
+
def test_no_header_two_extra_columns(all_parsers):
|
| 793 |
+
# GH 26218
|
| 794 |
+
column_names = ["one", "two", "three"]
|
| 795 |
+
ref = DataFrame([["foo", "bar", "baz"]], columns=column_names)
|
| 796 |
+
stream = StringIO("foo,bar,baz,bam,blah")
|
| 797 |
+
parser = all_parsers
|
| 798 |
+
df = parser.read_csv_check_warnings(
|
| 799 |
+
ParserWarning,
|
| 800 |
+
"Length of header or names does not match length of data. "
|
| 801 |
+
"This leads to a loss of data with index_col=False.",
|
| 802 |
+
stream,
|
| 803 |
+
header=None,
|
| 804 |
+
names=column_names,
|
| 805 |
+
index_col=False,
|
| 806 |
+
)
|
| 807 |
+
tm.assert_frame_equal(df, ref)
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
def test_read_csv_names_not_accepting_sets(all_parsers):
|
| 811 |
+
# GH 34946
|
| 812 |
+
data = """\
|
| 813 |
+
1,2,3
|
| 814 |
+
4,5,6\n"""
|
| 815 |
+
parser = all_parsers
|
| 816 |
+
with pytest.raises(ValueError, match="Names should be an ordered collection."):
|
| 817 |
+
parser.read_csv(StringIO(data), names=set("QAZ"))
|
| 818 |
+
|
| 819 |
+
|
| 820 |
+
def test_read_table_delim_whitespace_default_sep(all_parsers):
|
| 821 |
+
# GH: 35958
|
| 822 |
+
f = StringIO("a b c\n1 -2 -3\n4 5 6")
|
| 823 |
+
parser = all_parsers
|
| 824 |
+
|
| 825 |
+
depr_msg = "The 'delim_whitespace' keyword in pd.read_table is deprecated"
|
| 826 |
+
|
| 827 |
+
if parser.engine == "pyarrow":
|
| 828 |
+
msg = "The 'delim_whitespace' option is not supported with the 'pyarrow' engine"
|
| 829 |
+
with pytest.raises(ValueError, match=msg):
|
| 830 |
+
with tm.assert_produces_warning(
|
| 831 |
+
FutureWarning, match=depr_msg, check_stacklevel=False
|
| 832 |
+
):
|
| 833 |
+
parser.read_table(f, delim_whitespace=True)
|
| 834 |
+
return
|
| 835 |
+
with tm.assert_produces_warning(
|
| 836 |
+
FutureWarning, match=depr_msg, check_stacklevel=False
|
| 837 |
+
):
|
| 838 |
+
result = parser.read_table(f, delim_whitespace=True)
|
| 839 |
+
expected = DataFrame({"a": [1, 4], "b": [-2, 5], "c": [-3, 6]})
|
| 840 |
+
tm.assert_frame_equal(result, expected)
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
@pytest.mark.parametrize("delimiter", [",", "\t"])
|
| 844 |
+
def test_read_csv_delim_whitespace_non_default_sep(all_parsers, delimiter):
|
| 845 |
+
# GH: 35958
|
| 846 |
+
f = StringIO("a b c\n1 -2 -3\n4 5 6")
|
| 847 |
+
parser = all_parsers
|
| 848 |
+
msg = (
|
| 849 |
+
"Specified a delimiter with both sep and "
|
| 850 |
+
"delim_whitespace=True; you can only specify one."
|
| 851 |
+
)
|
| 852 |
+
depr_msg = "The 'delim_whitespace' keyword in pd.read_csv is deprecated"
|
| 853 |
+
with tm.assert_produces_warning(
|
| 854 |
+
FutureWarning, match=depr_msg, check_stacklevel=False
|
| 855 |
+
):
|
| 856 |
+
with pytest.raises(ValueError, match=msg):
|
| 857 |
+
parser.read_csv(f, delim_whitespace=True, sep=delimiter)
|
| 858 |
+
|
| 859 |
+
with pytest.raises(ValueError, match=msg):
|
| 860 |
+
parser.read_csv(f, delim_whitespace=True, delimiter=delimiter)
|
| 861 |
+
|
| 862 |
+
|
| 863 |
+
def test_read_csv_delimiter_and_sep_no_default(all_parsers):
|
| 864 |
+
# GH#39823
|
| 865 |
+
f = StringIO("a,b\n1,2")
|
| 866 |
+
parser = all_parsers
|
| 867 |
+
msg = "Specified a sep and a delimiter; you can only specify one."
|
| 868 |
+
with pytest.raises(ValueError, match=msg):
|
| 869 |
+
parser.read_csv(f, sep=" ", delimiter=".")
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
@pytest.mark.parametrize("kwargs", [{"delimiter": "\n"}, {"sep": "\n"}])
|
| 873 |
+
def test_read_csv_line_break_as_separator(kwargs, all_parsers):
|
| 874 |
+
# GH#43528
|
| 875 |
+
parser = all_parsers
|
| 876 |
+
data = """a,b,c
|
| 877 |
+
1,2,3
|
| 878 |
+
"""
|
| 879 |
+
msg = (
|
| 880 |
+
r"Specified \\n as separator or delimiter. This forces the python engine "
|
| 881 |
+
r"which does not accept a line terminator. Hence it is not allowed to use "
|
| 882 |
+
r"the line terminator as separator."
|
| 883 |
+
)
|
| 884 |
+
with pytest.raises(ValueError, match=msg):
|
| 885 |
+
parser.read_csv(StringIO(data), **kwargs)
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
@pytest.mark.parametrize("delimiter", [",", "\t"])
|
| 889 |
+
def test_read_table_delim_whitespace_non_default_sep(all_parsers, delimiter):
|
| 890 |
+
# GH: 35958
|
| 891 |
+
f = StringIO("a b c\n1 -2 -3\n4 5 6")
|
| 892 |
+
parser = all_parsers
|
| 893 |
+
msg = (
|
| 894 |
+
"Specified a delimiter with both sep and "
|
| 895 |
+
"delim_whitespace=True; you can only specify one."
|
| 896 |
+
)
|
| 897 |
+
depr_msg = "The 'delim_whitespace' keyword in pd.read_table is deprecated"
|
| 898 |
+
with tm.assert_produces_warning(
|
| 899 |
+
FutureWarning, match=depr_msg, check_stacklevel=False
|
| 900 |
+
):
|
| 901 |
+
with pytest.raises(ValueError, match=msg):
|
| 902 |
+
parser.read_table(f, delim_whitespace=True, sep=delimiter)
|
| 903 |
+
|
| 904 |
+
with pytest.raises(ValueError, match=msg):
|
| 905 |
+
parser.read_table(f, delim_whitespace=True, delimiter=delimiter)
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
@skip_pyarrow
|
| 909 |
+
def test_dict_keys_as_names(all_parsers):
|
| 910 |
+
# GH: 36928
|
| 911 |
+
data = "1,2"
|
| 912 |
+
|
| 913 |
+
keys = {"a": int, "b": int}.keys()
|
| 914 |
+
parser = all_parsers
|
| 915 |
+
|
| 916 |
+
result = parser.read_csv(StringIO(data), names=keys)
|
| 917 |
+
expected = DataFrame({"a": [1], "b": [2]})
|
| 918 |
+
tm.assert_frame_equal(result, expected)
|
| 919 |
+
|
| 920 |
+
|
| 921 |
+
@pytest.mark.xfail(using_string_dtype() and HAS_PYARROW, reason="TODO(infer_string)")
|
| 922 |
+
@xfail_pyarrow # UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 0
|
| 923 |
+
def test_encoding_surrogatepass(all_parsers):
|
| 924 |
+
# GH39017
|
| 925 |
+
parser = all_parsers
|
| 926 |
+
content = b"\xed\xbd\xbf"
|
| 927 |
+
decoded = content.decode("utf-8", errors="surrogatepass")
|
| 928 |
+
expected = DataFrame({decoded: [decoded]}, index=[decoded * 2])
|
| 929 |
+
expected.index.name = decoded * 2
|
| 930 |
+
|
| 931 |
+
with tm.ensure_clean() as path:
|
| 932 |
+
Path(path).write_bytes(
|
| 933 |
+
content * 2 + b"," + content + b"\n" + content * 2 + b"," + content
|
| 934 |
+
)
|
| 935 |
+
df = parser.read_csv(path, encoding_errors="surrogatepass", index_col=0)
|
| 936 |
+
tm.assert_frame_equal(df, expected)
|
| 937 |
+
with pytest.raises(UnicodeDecodeError, match="'utf-8' codec can't decode byte"):
|
| 938 |
+
parser.read_csv(path)
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
def test_malformed_second_line(all_parsers):
|
| 942 |
+
# see GH14782
|
| 943 |
+
parser = all_parsers
|
| 944 |
+
data = "\na\nb\n"
|
| 945 |
+
result = parser.read_csv(StringIO(data), skip_blank_lines=False, header=1)
|
| 946 |
+
expected = DataFrame({"a": ["b"]})
|
| 947 |
+
tm.assert_frame_equal(result, expected)
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
@skip_pyarrow
|
| 951 |
+
def test_short_single_line(all_parsers):
|
| 952 |
+
# GH 47566
|
| 953 |
+
parser = all_parsers
|
| 954 |
+
columns = ["a", "b", "c"]
|
| 955 |
+
data = "1,2"
|
| 956 |
+
result = parser.read_csv(StringIO(data), header=None, names=columns)
|
| 957 |
+
expected = DataFrame({"a": [1], "b": [2], "c": [np.nan]})
|
| 958 |
+
tm.assert_frame_equal(result, expected)
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
@xfail_pyarrow # ValueError: Length mismatch: Expected axis has 2 elements
|
| 962 |
+
def test_short_multi_line(all_parsers):
|
| 963 |
+
# GH 47566
|
| 964 |
+
parser = all_parsers
|
| 965 |
+
columns = ["a", "b", "c"]
|
| 966 |
+
data = "1,2\n1,2"
|
| 967 |
+
result = parser.read_csv(StringIO(data), header=None, names=columns)
|
| 968 |
+
expected = DataFrame({"a": [1, 1], "b": [2, 2], "c": [np.nan, np.nan]})
|
| 969 |
+
tm.assert_frame_equal(result, expected)
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
def test_read_seek(all_parsers):
|
| 973 |
+
# GH48646
|
| 974 |
+
parser = all_parsers
|
| 975 |
+
prefix = "### DATA\n"
|
| 976 |
+
content = "nkey,value\ntables,rectangular\n"
|
| 977 |
+
with tm.ensure_clean() as path:
|
| 978 |
+
Path(path).write_text(prefix + content, encoding="utf-8")
|
| 979 |
+
with open(path, encoding="utf-8") as file:
|
| 980 |
+
file.readline()
|
| 981 |
+
actual = parser.read_csv(file)
|
| 982 |
+
expected = parser.read_csv(StringIO(content))
|
| 983 |
+
tm.assert_frame_equal(actual, expected)
|
shared/package-files/12/120cc3dd23b5921be0ee9643713b2aa08d0515296c6686dbe8569d2db0212797/Storage.h
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
#include <c10/core/Storage.h>
|
shared/package-files/12/120dab704ee3adabf7cd4bee4d7b86e255fd3dbc81202bc0d1705615707626e7/linear.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: F401
|
| 2 |
+
r"""Quantized Modules.
|
| 3 |
+
|
| 4 |
+
This file is in the process of migration to `torch/ao/nn/quantized`, and
|
| 5 |
+
is kept here for compatibility while the migration process is ongoing.
|
| 6 |
+
If you are adding a new entry/functionality, please, add it to the
|
| 7 |
+
appropriate file under the `torch/ao/nn/quantized/modules`,
|
| 8 |
+
while adding an import statement here.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
__all__ = ['LinearPackedParams', 'Linear']
|
| 12 |
+
|
| 13 |
+
from torch.ao.nn.quantized.modules.linear import Linear
|
| 14 |
+
from torch.ao.nn.quantized.modules.linear import LinearPackedParams
|
shared/package-files/12/120dbf1ac136a09aa9787be0f7c6183bab5f1cff16bf432b57b092e79c516aed/exceptions.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from errno import ENOENT
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class InvalidArchiveError(Exception):
|
| 5 |
+
"""Raised when libarchive can't open a file"""
|
| 6 |
+
|
| 7 |
+
def __init__(self, fn, msg, *args, **kw):
|
| 8 |
+
msg = (
|
| 9 |
+
"Error with archive %s. You probably need to delete and re-download "
|
| 10 |
+
"or re-create this file. Message was:\n\n%s" % (fn, msg)
|
| 11 |
+
)
|
| 12 |
+
self.errno = ENOENT
|
| 13 |
+
super().__init__(msg)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ArchiveCreationError(Exception):
|
| 17 |
+
"""Raised when an archive fails during creation"""
|
| 18 |
+
|
| 19 |
+
pass
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class CaseInsensitiveFileSystemError(InvalidArchiveError):
|
| 23 |
+
def __init__(self, package_location, extract_location, **kwargs):
|
| 24 |
+
message = """
|
| 25 |
+
Cannot extract package to a case-insensitive file system. Your install
|
| 26 |
+
destination does not differentiate between upper and lowercase
|
| 27 |
+
characters, and this breaks things. Try installing to a location that
|
| 28 |
+
is case-sensitive. Windows drives are usually the culprit here - can
|
| 29 |
+
you install to a native Unix drive, or turn on case sensitivity for
|
| 30 |
+
this (Windows) location?
|
| 31 |
+
|
| 32 |
+
package location: %(package_location)s
|
| 33 |
+
extract location: %(extract_location)s
|
| 34 |
+
"""
|
| 35 |
+
self.package_location = package_location
|
| 36 |
+
self.extract_location = extract_location
|
| 37 |
+
super().__init__(package_location, message, **kwargs)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class ConversionError(Exception):
|
| 41 |
+
def __init__(self, missing_files, mismatching_sizes, *args, **kw):
|
| 42 |
+
self.missing_files = missing_files
|
| 43 |
+
self.mismatching_sizes = mismatching_sizes
|
| 44 |
+
errors = ""
|
| 45 |
+
if self.missing_files:
|
| 46 |
+
errors = "Missing files in converted package: %s\n" % self.missing_files
|
| 47 |
+
errors = (
|
| 48 |
+
errors
|
| 49 |
+
+ "Mismatching sizes (corruption) in converted package: %s" # noqa
|
| 50 |
+
% self.mismatching_sizes
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
super().__init__(errors, *args, **kw)
|
shared/package-files/12/120f31e6a5b25c3ccf7b331a7c5bb4b34ab23c31e3fac3ec1711ad13a876f6aa/_p_r_o_p.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .otBase import BaseTTXConverter
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6prop.html
|
| 5 |
+
class table__p_r_o_p(BaseTTXConverter):
|
| 6 |
+
"""The AAT ``prop`` table can store a variety of per-glyph properties, such as
|
| 7 |
+
Unicode directionality or whether glyphs are non-spacing marks.
|
| 8 |
+
|
| 9 |
+
See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6prop.html
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
pass
|
shared/package-files/12/120f7ab06ff0c361ba92de8de23952c1503e2c4f37e0a646a78f8480369c07d9/tables.pyi
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
from markdown.blockprocessors import BlockProcessor
|
| 4 |
+
from markdown.extensions import Extension
|
| 5 |
+
|
| 6 |
+
PIPE_NONE: int
|
| 7 |
+
PIPE_LEFT: int
|
| 8 |
+
PIPE_RIGHT: int
|
| 9 |
+
|
| 10 |
+
class TableProcessor(BlockProcessor):
|
| 11 |
+
RE_CODE_PIPES: Any
|
| 12 |
+
RE_END_BORDER: Any
|
| 13 |
+
border: bool = ...
|
| 14 |
+
separator: str = ...
|
| 15 |
+
def __init__(self, parser) -> None: ...
|
| 16 |
+
|
| 17 |
+
class TableExtension(Extension): ...
|
| 18 |
+
|
| 19 |
+
def makeExtension(**kwargs): ...
|
shared/package-files/12/120fd1be639c98578beacd919530fea0ec5e6c67582cdf5564cd60718dd8326b/printimpl.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import singledispatch
|
| 2 |
+
from llvmlite import ir
|
| 3 |
+
from numba.core import types, cgutils
|
| 4 |
+
from numba.core.errors import NumbaWarning
|
| 5 |
+
from numba.core.imputils import Registry
|
| 6 |
+
from numba.cuda import nvvmutils
|
| 7 |
+
from warnings import warn
|
| 8 |
+
|
| 9 |
+
registry = Registry()
|
| 10 |
+
lower = registry.lower
|
| 11 |
+
|
| 12 |
+
voidptr = ir.PointerType(ir.IntType(8))
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# NOTE: we don't use @lower here since print_item() doesn't return a LLVM value
|
| 16 |
+
|
| 17 |
+
@singledispatch
|
| 18 |
+
def print_item(ty, context, builder, val):
|
| 19 |
+
"""
|
| 20 |
+
Handle printing of a single value of the given Numba type.
|
| 21 |
+
A (format string, [list of arguments]) is returned that will allow
|
| 22 |
+
forming the final printf()-like call.
|
| 23 |
+
"""
|
| 24 |
+
raise NotImplementedError("printing unimplemented for values of type %s"
|
| 25 |
+
% (ty,))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@print_item.register(types.Integer)
|
| 29 |
+
@print_item.register(types.IntegerLiteral)
|
| 30 |
+
def int_print_impl(ty, context, builder, val):
|
| 31 |
+
if ty in types.unsigned_domain:
|
| 32 |
+
rawfmt = "%llu"
|
| 33 |
+
dsttype = types.uint64
|
| 34 |
+
else:
|
| 35 |
+
rawfmt = "%lld"
|
| 36 |
+
dsttype = types.int64
|
| 37 |
+
lld = context.cast(builder, val, ty, dsttype)
|
| 38 |
+
return rawfmt, [lld]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@print_item.register(types.Float)
|
| 42 |
+
def real_print_impl(ty, context, builder, val):
|
| 43 |
+
lld = context.cast(builder, val, ty, types.float64)
|
| 44 |
+
return "%f", [lld]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@print_item.register(types.StringLiteral)
|
| 48 |
+
def const_print_impl(ty, context, builder, sigval):
|
| 49 |
+
pyval = ty.literal_value
|
| 50 |
+
assert isinstance(pyval, str) # Ensured by lowering
|
| 51 |
+
rawfmt = "%s"
|
| 52 |
+
val = context.insert_string_const_addrspace(builder, pyval)
|
| 53 |
+
return rawfmt, [val]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@lower(print, types.VarArg(types.Any))
|
| 57 |
+
def print_varargs(context, builder, sig, args):
|
| 58 |
+
"""This function is a generic 'print' wrapper for arbitrary types.
|
| 59 |
+
It dispatches to the appropriate 'print' implementations above
|
| 60 |
+
depending on the detected real types in the signature."""
|
| 61 |
+
|
| 62 |
+
vprint = nvvmutils.declare_vprint(builder.module)
|
| 63 |
+
|
| 64 |
+
formats = []
|
| 65 |
+
values = []
|
| 66 |
+
|
| 67 |
+
for i, (argtype, argval) in enumerate(zip(sig.args, args)):
|
| 68 |
+
argfmt, argvals = print_item(argtype, context, builder, argval)
|
| 69 |
+
formats.append(argfmt)
|
| 70 |
+
values.extend(argvals)
|
| 71 |
+
|
| 72 |
+
rawfmt = " ".join(formats) + "\n"
|
| 73 |
+
if len(args) > 32:
|
| 74 |
+
msg = ('CUDA print() cannot print more than 32 items. '
|
| 75 |
+
'The raw format string will be emitted by the kernel instead.')
|
| 76 |
+
warn(msg, NumbaWarning)
|
| 77 |
+
|
| 78 |
+
rawfmt = rawfmt.replace('%', '%%')
|
| 79 |
+
fmt = context.insert_string_const_addrspace(builder, rawfmt)
|
| 80 |
+
array = cgutils.make_anonymous_struct(builder, values)
|
| 81 |
+
arrayptr = cgutils.alloca_once_value(builder, array)
|
| 82 |
+
|
| 83 |
+
vprint = nvvmutils.declare_vprint(builder.module)
|
| 84 |
+
builder.call(vprint, (fmt, builder.bitcast(arrayptr, voidptr)))
|
| 85 |
+
|
| 86 |
+
return context.get_dummy_value()
|
shared/package-files/12/12108cb824b3eb4220409f776ffe302720281e953d27eb9d746e1068c4f43eee/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
| 2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
| 3 |
+
# for complete details.
|
| 4 |
+
|
| 5 |
+
__title__ = "packaging"
|
| 6 |
+
__summary__ = "Core utilities for Python packages"
|
| 7 |
+
__uri__ = "https://github.com/pypa/packaging"
|
| 8 |
+
|
| 9 |
+
__version__ = "23.2"
|
| 10 |
+
|
| 11 |
+
__author__ = "Donald Stufft and individual contributors"
|
| 12 |
+
__email__ = "donald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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.lexers.erlang
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
Lexers for Erlang.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import re
|
| 12 |
+
|
| 13 |
+
from pygments.lexer import Lexer, RegexLexer, bygroups, words, do_insertions, \
|
| 14 |
+
include, default, line_re
|
| 15 |
+
from pygments.token import Comment, Operator, Keyword, Name, String, \
|
| 16 |
+
Number, Punctuation, Generic, Whitespace
|
| 17 |
+
|
| 18 |
+
__all__ = ['ErlangLexer', 'ErlangShellLexer', 'ElixirConsoleLexer',
|
| 19 |
+
'ElixirLexer']
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ErlangLexer(RegexLexer):
|
| 23 |
+
"""
|
| 24 |
+
For the Erlang functional programming language.
|
| 25 |
+
|
| 26 |
+
.. versionadded:: 0.9
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
name = 'Erlang'
|
| 30 |
+
url = 'https://www.erlang.org/'
|
| 31 |
+
aliases = ['erlang']
|
| 32 |
+
filenames = ['*.erl', '*.hrl', '*.es', '*.escript']
|
| 33 |
+
mimetypes = ['text/x-erlang']
|
| 34 |
+
|
| 35 |
+
keywords = (
|
| 36 |
+
'after', 'begin', 'case', 'catch', 'cond', 'end', 'fun', 'if',
|
| 37 |
+
'let', 'of', 'query', 'receive', 'try', 'when',
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
builtins = ( # See erlang(3) man page
|
| 41 |
+
'abs', 'append_element', 'apply', 'atom_to_list', 'binary_to_list',
|
| 42 |
+
'bitstring_to_list', 'binary_to_term', 'bit_size', 'bump_reductions',
|
| 43 |
+
'byte_size', 'cancel_timer', 'check_process_code', 'delete_module',
|
| 44 |
+
'demonitor', 'disconnect_node', 'display', 'element', 'erase', 'exit',
|
| 45 |
+
'float', 'float_to_list', 'fun_info', 'fun_to_list',
|
| 46 |
+
'function_exported', 'garbage_collect', 'get', 'get_keys',
|
| 47 |
+
'group_leader', 'hash', 'hd', 'integer_to_list', 'iolist_to_binary',
|
| 48 |
+
'iolist_size', 'is_atom', 'is_binary', 'is_bitstring', 'is_boolean',
|
| 49 |
+
'is_builtin', 'is_float', 'is_function', 'is_integer', 'is_list',
|
| 50 |
+
'is_number', 'is_pid', 'is_port', 'is_process_alive', 'is_record',
|
| 51 |
+
'is_reference', 'is_tuple', 'length', 'link', 'list_to_atom',
|
| 52 |
+
'list_to_binary', 'list_to_bitstring', 'list_to_existing_atom',
|
| 53 |
+
'list_to_float', 'list_to_integer', 'list_to_pid', 'list_to_tuple',
|
| 54 |
+
'load_module', 'localtime_to_universaltime', 'make_tuple', 'md5',
|
| 55 |
+
'md5_final', 'md5_update', 'memory', 'module_loaded', 'monitor',
|
| 56 |
+
'monitor_node', 'node', 'nodes', 'open_port', 'phash', 'phash2',
|
| 57 |
+
'pid_to_list', 'port_close', 'port_command', 'port_connect',
|
| 58 |
+
'port_control', 'port_call', 'port_info', 'port_to_list',
|
| 59 |
+
'process_display', 'process_flag', 'process_info', 'purge_module',
|
| 60 |
+
'put', 'read_timer', 'ref_to_list', 'register', 'resume_process',
|
| 61 |
+
'round', 'send', 'send_after', 'send_nosuspend', 'set_cookie',
|
| 62 |
+
'setelement', 'size', 'spawn', 'spawn_link', 'spawn_monitor',
|
| 63 |
+
'spawn_opt', 'split_binary', 'start_timer', 'statistics',
|
| 64 |
+
'suspend_process', 'system_flag', 'system_info', 'system_monitor',
|
| 65 |
+
'system_profile', 'term_to_binary', 'tl', 'trace', 'trace_delivered',
|
| 66 |
+
'trace_info', 'trace_pattern', 'trunc', 'tuple_size', 'tuple_to_list',
|
| 67 |
+
'universaltime_to_localtime', 'unlink', 'unregister', 'whereis'
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
operators = r'(\+\+?|--?|\*|/|<|>|/=|=:=|=/=|=<|>=|==?|<-|!|\?)'
|
| 71 |
+
word_operators = (
|
| 72 |
+
'and', 'andalso', 'band', 'bnot', 'bor', 'bsl', 'bsr', 'bxor',
|
| 73 |
+
'div', 'not', 'or', 'orelse', 'rem', 'xor'
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
atom_re = r"(?:[a-z]\w*|'[^\n']*[^\\]')"
|
| 77 |
+
|
| 78 |
+
variable_re = r'(?:[A-Z_]\w*)'
|
| 79 |
+
|
| 80 |
+
esc_char_re = r'[bdefnrstv\'"\\]'
|
| 81 |
+
esc_octal_re = r'[0-7][0-7]?[0-7]?'
|
| 82 |
+
esc_hex_re = r'(?:x[0-9a-fA-F]{2}|x\{[0-9a-fA-F]+\})'
|
| 83 |
+
esc_ctrl_re = r'\^[a-zA-Z]'
|
| 84 |
+
escape_re = r'(?:\\(?:'+esc_char_re+r'|'+esc_octal_re+r'|'+esc_hex_re+r'|'+esc_ctrl_re+r'))'
|
| 85 |
+
|
| 86 |
+
macro_re = r'(?:'+variable_re+r'|'+atom_re+r')'
|
| 87 |
+
|
| 88 |
+
base_re = r'(?:[2-9]|[12][0-9]|3[0-6])'
|
| 89 |
+
|
| 90 |
+
tokens = {
|
| 91 |
+
'root': [
|
| 92 |
+
(r'\s+', Whitespace),
|
| 93 |
+
(r'(%.*)(\n)', bygroups(Comment, Whitespace)),
|
| 94 |
+
(words(keywords, suffix=r'\b'), Keyword),
|
| 95 |
+
(words(builtins, suffix=r'\b'), Name.Builtin),
|
| 96 |
+
(words(word_operators, suffix=r'\b'), Operator.Word),
|
| 97 |
+
(r'^-', Punctuation, 'directive'),
|
| 98 |
+
(operators, Operator),
|
| 99 |
+
(r'"', String, 'string'),
|
| 100 |
+
(r'<<', Name.Label),
|
| 101 |
+
(r'>>', Name.Label),
|
| 102 |
+
('(' + atom_re + ')(:)', bygroups(Name.Namespace, Punctuation)),
|
| 103 |
+
('(?:^|(?<=:))(' + atom_re + r')(\s*)(\()',
|
| 104 |
+
bygroups(Name.Function, Whitespace, Punctuation)),
|
| 105 |
+
(r'[+-]?' + base_re + r'#[0-9a-zA-Z]+', Number.Integer),
|
| 106 |
+
(r'[+-]?\d+', Number.Integer),
|
| 107 |
+
(r'[+-]?\d+.\d+', Number.Float),
|
| 108 |
+
(r'[]\[:_@\".{}()|;,]', Punctuation),
|
| 109 |
+
(variable_re, Name.Variable),
|
| 110 |
+
(atom_re, Name),
|
| 111 |
+
(r'\?'+macro_re, Name.Constant),
|
| 112 |
+
(r'\$(?:'+escape_re+r'|\\[ %]|[^\\])', String.Char),
|
| 113 |
+
(r'#'+atom_re+r'(:?\.'+atom_re+r')?', Name.Label),
|
| 114 |
+
|
| 115 |
+
# Erlang script shebang
|
| 116 |
+
(r'\A#!.+\n', Comment.Hashbang),
|
| 117 |
+
|
| 118 |
+
# EEP 43: Maps
|
| 119 |
+
# http://www.erlang.org/eeps/eep-0043.html
|
| 120 |
+
(r'#\{', Punctuation, 'map_key'),
|
| 121 |
+
],
|
| 122 |
+
'string': [
|
| 123 |
+
(escape_re, String.Escape),
|
| 124 |
+
(r'"', String, '#pop'),
|
| 125 |
+
(r'~[0-9.*]*[~#+BPWXb-ginpswx]', String.Interpol),
|
| 126 |
+
(r'[^"\\~]+', String),
|
| 127 |
+
(r'~', String),
|
| 128 |
+
],
|
| 129 |
+
'directive': [
|
| 130 |
+
(r'(define)(\s*)(\()('+macro_re+r')',
|
| 131 |
+
bygroups(Name.Entity, Whitespace, Punctuation, Name.Constant), '#pop'),
|
| 132 |
+
(r'(record)(\s*)(\()('+macro_re+r')',
|
| 133 |
+
bygroups(Name.Entity, Whitespace, Punctuation, Name.Label), '#pop'),
|
| 134 |
+
(atom_re, Name.Entity, '#pop'),
|
| 135 |
+
],
|
| 136 |
+
'map_key': [
|
| 137 |
+
include('root'),
|
| 138 |
+
(r'=>', Punctuation, 'map_val'),
|
| 139 |
+
(r':=', Punctuation, 'map_val'),
|
| 140 |
+
(r'\}', Punctuation, '#pop'),
|
| 141 |
+
],
|
| 142 |
+
'map_val': [
|
| 143 |
+
include('root'),
|
| 144 |
+
(r',', Punctuation, '#pop'),
|
| 145 |
+
(r'(?=\})', Punctuation, '#pop'),
|
| 146 |
+
],
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class ErlangShellLexer(Lexer):
|
| 151 |
+
"""
|
| 152 |
+
Shell sessions in erl (for Erlang code).
|
| 153 |
+
|
| 154 |
+
.. versionadded:: 1.1
|
| 155 |
+
"""
|
| 156 |
+
name = 'Erlang erl session'
|
| 157 |
+
aliases = ['erl']
|
| 158 |
+
filenames = ['*.erl-sh']
|
| 159 |
+
mimetypes = ['text/x-erl-shellsession']
|
| 160 |
+
|
| 161 |
+
_prompt_re = re.compile(r'(?:\([\w@_.]+\))?\d+>(?=\s|\Z)')
|
| 162 |
+
|
| 163 |
+
def get_tokens_unprocessed(self, text):
|
| 164 |
+
erlexer = ErlangLexer(**self.options)
|
| 165 |
+
|
| 166 |
+
curcode = ''
|
| 167 |
+
insertions = []
|
| 168 |
+
for match in line_re.finditer(text):
|
| 169 |
+
line = match.group()
|
| 170 |
+
m = self._prompt_re.match(line)
|
| 171 |
+
if m is not None:
|
| 172 |
+
end = m.end()
|
| 173 |
+
insertions.append((len(curcode),
|
| 174 |
+
[(0, Generic.Prompt, line[:end])]))
|
| 175 |
+
curcode += line[end:]
|
| 176 |
+
else:
|
| 177 |
+
if curcode:
|
| 178 |
+
yield from do_insertions(insertions,
|
| 179 |
+
erlexer.get_tokens_unprocessed(curcode))
|
| 180 |
+
curcode = ''
|
| 181 |
+
insertions = []
|
| 182 |
+
if line.startswith('*'):
|
| 183 |
+
yield match.start(), Generic.Traceback, line
|
| 184 |
+
else:
|
| 185 |
+
yield match.start(), Generic.Output, line
|
| 186 |
+
if curcode:
|
| 187 |
+
yield from do_insertions(insertions,
|
| 188 |
+
erlexer.get_tokens_unprocessed(curcode))
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def gen_elixir_string_rules(name, symbol, token):
|
| 192 |
+
states = {}
|
| 193 |
+
states['string_' + name] = [
|
| 194 |
+
(r'[^#%s\\]+' % (symbol,), token),
|
| 195 |
+
include('escapes'),
|
| 196 |
+
(r'\\.', token),
|
| 197 |
+
(r'(%s)' % (symbol,), bygroups(token), "#pop"),
|
| 198 |
+
include('interpol')
|
| 199 |
+
]
|
| 200 |
+
return states
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def gen_elixir_sigstr_rules(term, term_class, token, interpol=True):
|
| 204 |
+
if interpol:
|
| 205 |
+
return [
|
| 206 |
+
(r'[^#%s\\]+' % (term_class,), token),
|
| 207 |
+
include('escapes'),
|
| 208 |
+
(r'\\.', token),
|
| 209 |
+
(r'%s[a-zA-Z]*' % (term,), token, '#pop'),
|
| 210 |
+
include('interpol')
|
| 211 |
+
]
|
| 212 |
+
else:
|
| 213 |
+
return [
|
| 214 |
+
(r'[^%s\\]+' % (term_class,), token),
|
| 215 |
+
(r'\\.', token),
|
| 216 |
+
(r'%s[a-zA-Z]*' % (term,), token, '#pop'),
|
| 217 |
+
]
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class ElixirLexer(RegexLexer):
|
| 221 |
+
"""
|
| 222 |
+
For the Elixir language.
|
| 223 |
+
|
| 224 |
+
.. versionadded:: 1.5
|
| 225 |
+
"""
|
| 226 |
+
|
| 227 |
+
name = 'Elixir'
|
| 228 |
+
url = 'http://elixir-lang.org'
|
| 229 |
+
aliases = ['elixir', 'ex', 'exs']
|
| 230 |
+
filenames = ['*.ex', '*.eex', '*.exs', '*.leex']
|
| 231 |
+
mimetypes = ['text/x-elixir']
|
| 232 |
+
|
| 233 |
+
KEYWORD = ('fn', 'do', 'end', 'after', 'else', 'rescue', 'catch')
|
| 234 |
+
KEYWORD_OPERATOR = ('not', 'and', 'or', 'when', 'in')
|
| 235 |
+
BUILTIN = (
|
| 236 |
+
'case', 'cond', 'for', 'if', 'unless', 'try', 'receive', 'raise',
|
| 237 |
+
'quote', 'unquote', 'unquote_splicing', 'throw', 'super',
|
| 238 |
+
)
|
| 239 |
+
BUILTIN_DECLARATION = (
|
| 240 |
+
'def', 'defp', 'defmodule', 'defprotocol', 'defmacro', 'defmacrop',
|
| 241 |
+
'defdelegate', 'defexception', 'defstruct', 'defimpl', 'defcallback',
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
BUILTIN_NAMESPACE = ('import', 'require', 'use', 'alias')
|
| 245 |
+
CONSTANT = ('nil', 'true', 'false')
|
| 246 |
+
|
| 247 |
+
PSEUDO_VAR = ('_', '__MODULE__', '__DIR__', '__ENV__', '__CALLER__')
|
| 248 |
+
|
| 249 |
+
OPERATORS3 = (
|
| 250 |
+
'<<<', '>>>', '|||', '&&&', '^^^', '~~~', '===', '!==',
|
| 251 |
+
'~>>', '<~>', '|~>', '<|>',
|
| 252 |
+
)
|
| 253 |
+
OPERATORS2 = (
|
| 254 |
+
'==', '!=', '<=', '>=', '&&', '||', '<>', '++', '--', '|>', '=~',
|
| 255 |
+
'->', '<-', '|', '.', '=', '~>', '<~',
|
| 256 |
+
)
|
| 257 |
+
OPERATORS1 = ('<', '>', '+', '-', '*', '/', '!', '^', '&')
|
| 258 |
+
|
| 259 |
+
PUNCTUATION = (
|
| 260 |
+
'\\\\', '<<', '>>', '=>', '(', ')', ':', ';', ',', '[', ']',
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
def get_tokens_unprocessed(self, text):
|
| 264 |
+
for index, token, value in RegexLexer.get_tokens_unprocessed(self, text):
|
| 265 |
+
if token is Name:
|
| 266 |
+
if value in self.KEYWORD:
|
| 267 |
+
yield index, Keyword, value
|
| 268 |
+
elif value in self.KEYWORD_OPERATOR:
|
| 269 |
+
yield index, Operator.Word, value
|
| 270 |
+
elif value in self.BUILTIN:
|
| 271 |
+
yield index, Keyword, value
|
| 272 |
+
elif value in self.BUILTIN_DECLARATION:
|
| 273 |
+
yield index, Keyword.Declaration, value
|
| 274 |
+
elif value in self.BUILTIN_NAMESPACE:
|
| 275 |
+
yield index, Keyword.Namespace, value
|
| 276 |
+
elif value in self.CONSTANT:
|
| 277 |
+
yield index, Name.Constant, value
|
| 278 |
+
elif value in self.PSEUDO_VAR:
|
| 279 |
+
yield index, Name.Builtin.Pseudo, value
|
| 280 |
+
else:
|
| 281 |
+
yield index, token, value
|
| 282 |
+
else:
|
| 283 |
+
yield index, token, value
|
| 284 |
+
|
| 285 |
+
def gen_elixir_sigil_rules():
|
| 286 |
+
# all valid sigil terminators (excluding heredocs)
|
| 287 |
+
terminators = [
|
| 288 |
+
(r'\{', r'\}', '}', 'cb'),
|
| 289 |
+
(r'\[', r'\]', r'\]', 'sb'),
|
| 290 |
+
(r'\(', r'\)', ')', 'pa'),
|
| 291 |
+
('<', '>', '>', 'ab'),
|
| 292 |
+
('/', '/', '/', 'slas'),
|
| 293 |
+
(r'\|', r'\|', '|', 'pipe'),
|
| 294 |
+
('"', '"', '"', 'quot'),
|
| 295 |
+
("'", "'", "'", 'apos'),
|
| 296 |
+
]
|
| 297 |
+
|
| 298 |
+
# heredocs have slightly different rules
|
| 299 |
+
triquotes = [(r'"""', 'triquot'), (r"'''", 'triapos')]
|
| 300 |
+
|
| 301 |
+
token = String.Other
|
| 302 |
+
states = {'sigils': []}
|
| 303 |
+
|
| 304 |
+
for term, name in triquotes:
|
| 305 |
+
states['sigils'] += [
|
| 306 |
+
(r'(~[a-z])(%s)' % (term,), bygroups(token, String.Heredoc),
|
| 307 |
+
(name + '-end', name + '-intp')),
|
| 308 |
+
(r'(~[A-Z])(%s)' % (term,), bygroups(token, String.Heredoc),
|
| 309 |
+
(name + '-end', name + '-no-intp')),
|
| 310 |
+
]
|
| 311 |
+
|
| 312 |
+
states[name + '-end'] = [
|
| 313 |
+
(r'[a-zA-Z]+', token, '#pop'),
|
| 314 |
+
default('#pop'),
|
| 315 |
+
]
|
| 316 |
+
states[name + '-intp'] = [
|
| 317 |
+
(r'^(\s*)(' + term + ')', bygroups(Whitespace, String.Heredoc), '#pop'),
|
| 318 |
+
include('heredoc_interpol'),
|
| 319 |
+
]
|
| 320 |
+
states[name + '-no-intp'] = [
|
| 321 |
+
(r'^(\s*)(' + term +')', bygroups(Whitespace, String.Heredoc), '#pop'),
|
| 322 |
+
include('heredoc_no_interpol'),
|
| 323 |
+
]
|
| 324 |
+
|
| 325 |
+
for lterm, rterm, rterm_class, name in terminators:
|
| 326 |
+
states['sigils'] += [
|
| 327 |
+
(r'~[a-z]' + lterm, token, name + '-intp'),
|
| 328 |
+
(r'~[A-Z]' + lterm, token, name + '-no-intp'),
|
| 329 |
+
]
|
| 330 |
+
states[name + '-intp'] = \
|
| 331 |
+
gen_elixir_sigstr_rules(rterm, rterm_class, token)
|
| 332 |
+
states[name + '-no-intp'] = \
|
| 333 |
+
gen_elixir_sigstr_rules(rterm, rterm_class, token, interpol=False)
|
| 334 |
+
|
| 335 |
+
return states
|
| 336 |
+
|
| 337 |
+
op3_re = "|".join(re.escape(s) for s in OPERATORS3)
|
| 338 |
+
op2_re = "|".join(re.escape(s) for s in OPERATORS2)
|
| 339 |
+
op1_re = "|".join(re.escape(s) for s in OPERATORS1)
|
| 340 |
+
ops_re = r'(?:%s|%s|%s)' % (op3_re, op2_re, op1_re)
|
| 341 |
+
punctuation_re = "|".join(re.escape(s) for s in PUNCTUATION)
|
| 342 |
+
alnum = r'\w'
|
| 343 |
+
name_re = r'(?:\.\.\.|[a-z_]%s*[!?]?)' % alnum
|
| 344 |
+
modname_re = r'[A-Z]%(alnum)s*(?:\.[A-Z]%(alnum)s*)*' % {'alnum': alnum}
|
| 345 |
+
complex_name_re = r'(?:%s|%s|%s)' % (name_re, modname_re, ops_re)
|
| 346 |
+
special_atom_re = r'(?:\.\.\.|<<>>|%\{\}|%|\{\})'
|
| 347 |
+
|
| 348 |
+
long_hex_char_re = r'(\\x\{)([\da-fA-F]+)(\})'
|
| 349 |
+
hex_char_re = r'(\\x[\da-fA-F]{1,2})'
|
| 350 |
+
escape_char_re = r'(\\[abdefnrstv])'
|
| 351 |
+
|
| 352 |
+
tokens = {
|
| 353 |
+
'root': [
|
| 354 |
+
(r'\s+', Whitespace),
|
| 355 |
+
(r'#.*$', Comment.Single),
|
| 356 |
+
|
| 357 |
+
# Various kinds of characters
|
| 358 |
+
(r'(\?)' + long_hex_char_re,
|
| 359 |
+
bygroups(String.Char,
|
| 360 |
+
String.Escape, Number.Hex, String.Escape)),
|
| 361 |
+
(r'(\?)' + hex_char_re,
|
| 362 |
+
bygroups(String.Char, String.Escape)),
|
| 363 |
+
(r'(\?)' + escape_char_re,
|
| 364 |
+
bygroups(String.Char, String.Escape)),
|
| 365 |
+
(r'\?\\?.', String.Char),
|
| 366 |
+
|
| 367 |
+
# '::' has to go before atoms
|
| 368 |
+
(r':::', String.Symbol),
|
| 369 |
+
(r'::', Operator),
|
| 370 |
+
|
| 371 |
+
# atoms
|
| 372 |
+
(r':' + special_atom_re, String.Symbol),
|
| 373 |
+
(r':' + complex_name_re, String.Symbol),
|
| 374 |
+
(r':"', String.Symbol, 'string_double_atom'),
|
| 375 |
+
(r":'", String.Symbol, 'string_single_atom'),
|
| 376 |
+
|
| 377 |
+
# [keywords: ...]
|
| 378 |
+
(r'(%s|%s)(:)(?=\s|\n)' % (special_atom_re, complex_name_re),
|
| 379 |
+
bygroups(String.Symbol, Punctuation)),
|
| 380 |
+
|
| 381 |
+
# @attributes
|
| 382 |
+
(r'@' + name_re, Name.Attribute),
|
| 383 |
+
|
| 384 |
+
# identifiers
|
| 385 |
+
(name_re, Name),
|
| 386 |
+
(r'(%%?)(%s)' % (modname_re,), bygroups(Punctuation, Name.Class)),
|
| 387 |
+
|
| 388 |
+
# operators and punctuation
|
| 389 |
+
(op3_re, Operator),
|
| 390 |
+
(op2_re, Operator),
|
| 391 |
+
(punctuation_re, Punctuation),
|
| 392 |
+
(r'&\d', Name.Entity), # anon func arguments
|
| 393 |
+
(op1_re, Operator),
|
| 394 |
+
|
| 395 |
+
# numbers
|
| 396 |
+
(r'0b[01]+', Number.Bin),
|
| 397 |
+
(r'0o[0-7]+', Number.Oct),
|
| 398 |
+
(r'0x[\da-fA-F]+', Number.Hex),
|
| 399 |
+
(r'\d(_?\d)*\.\d(_?\d)*([eE][-+]?\d(_?\d)*)?', Number.Float),
|
| 400 |
+
(r'\d(_?\d)*', Number.Integer),
|
| 401 |
+
|
| 402 |
+
# strings and heredocs
|
| 403 |
+
(r'(""")(\s*)', bygroups(String.Heredoc, Whitespace),
|
| 404 |
+
'heredoc_double'),
|
| 405 |
+
(r"(''')(\s*)$", bygroups(String.Heredoc, Whitespace),
|
| 406 |
+
'heredoc_single'),
|
| 407 |
+
(r'"', String.Double, 'string_double'),
|
| 408 |
+
(r"'", String.Single, 'string_single'),
|
| 409 |
+
|
| 410 |
+
include('sigils'),
|
| 411 |
+
|
| 412 |
+
(r'%\{', Punctuation, 'map_key'),
|
| 413 |
+
(r'\{', Punctuation, 'tuple'),
|
| 414 |
+
],
|
| 415 |
+
'heredoc_double': [
|
| 416 |
+
(r'^(\s*)(""")', bygroups(Whitespace, String.Heredoc), '#pop'),
|
| 417 |
+
include('heredoc_interpol'),
|
| 418 |
+
],
|
| 419 |
+
'heredoc_single': [
|
| 420 |
+
(r"^\s*'''", String.Heredoc, '#pop'),
|
| 421 |
+
include('heredoc_interpol'),
|
| 422 |
+
],
|
| 423 |
+
'heredoc_interpol': [
|
| 424 |
+
(r'[^#\\\n]+', String.Heredoc),
|
| 425 |
+
include('escapes'),
|
| 426 |
+
(r'\\.', String.Heredoc),
|
| 427 |
+
(r'\n+', String.Heredoc),
|
| 428 |
+
include('interpol'),
|
| 429 |
+
],
|
| 430 |
+
'heredoc_no_interpol': [
|
| 431 |
+
(r'[^\\\n]+', String.Heredoc),
|
| 432 |
+
(r'\\.', String.Heredoc),
|
| 433 |
+
(r'\n+', Whitespace),
|
| 434 |
+
],
|
| 435 |
+
'escapes': [
|
| 436 |
+
(long_hex_char_re,
|
| 437 |
+
bygroups(String.Escape, Number.Hex, String.Escape)),
|
| 438 |
+
(hex_char_re, String.Escape),
|
| 439 |
+
(escape_char_re, String.Escape),
|
| 440 |
+
],
|
| 441 |
+
'interpol': [
|
| 442 |
+
(r'#\{', String.Interpol, 'interpol_string'),
|
| 443 |
+
],
|
| 444 |
+
'interpol_string': [
|
| 445 |
+
(r'\}', String.Interpol, "#pop"),
|
| 446 |
+
include('root')
|
| 447 |
+
],
|
| 448 |
+
'map_key': [
|
| 449 |
+
include('root'),
|
| 450 |
+
(r':', Punctuation, 'map_val'),
|
| 451 |
+
(r'=>', Punctuation, 'map_val'),
|
| 452 |
+
(r'\}', Punctuation, '#pop'),
|
| 453 |
+
],
|
| 454 |
+
'map_val': [
|
| 455 |
+
include('root'),
|
| 456 |
+
(r',', Punctuation, '#pop'),
|
| 457 |
+
(r'(?=\})', Punctuation, '#pop'),
|
| 458 |
+
],
|
| 459 |
+
'tuple': [
|
| 460 |
+
include('root'),
|
| 461 |
+
(r'\}', Punctuation, '#pop'),
|
| 462 |
+
],
|
| 463 |
+
}
|
| 464 |
+
tokens.update(gen_elixir_string_rules('double', '"', String.Double))
|
| 465 |
+
tokens.update(gen_elixir_string_rules('single', "'", String.Single))
|
| 466 |
+
tokens.update(gen_elixir_string_rules('double_atom', '"', String.Symbol))
|
| 467 |
+
tokens.update(gen_elixir_string_rules('single_atom', "'", String.Symbol))
|
| 468 |
+
tokens.update(gen_elixir_sigil_rules())
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
class ElixirConsoleLexer(Lexer):
|
| 472 |
+
"""
|
| 473 |
+
For Elixir interactive console (iex) output like:
|
| 474 |
+
|
| 475 |
+
.. sourcecode:: iex
|
| 476 |
+
|
| 477 |
+
iex> [head | tail] = [1,2,3]
|
| 478 |
+
[1,2,3]
|
| 479 |
+
iex> head
|
| 480 |
+
1
|
| 481 |
+
iex> tail
|
| 482 |
+
[2,3]
|
| 483 |
+
iex> [head | tail]
|
| 484 |
+
[1,2,3]
|
| 485 |
+
iex> length [head | tail]
|
| 486 |
+
3
|
| 487 |
+
|
| 488 |
+
.. versionadded:: 1.5
|
| 489 |
+
"""
|
| 490 |
+
|
| 491 |
+
name = 'Elixir iex session'
|
| 492 |
+
aliases = ['iex']
|
| 493 |
+
mimetypes = ['text/x-elixir-shellsession']
|
| 494 |
+
|
| 495 |
+
_prompt_re = re.compile(r'(iex|\.{3})((?:\([\w@_.]+\))?\d+|\(\d+\))?> ')
|
| 496 |
+
|
| 497 |
+
def get_tokens_unprocessed(self, text):
|
| 498 |
+
exlexer = ElixirLexer(**self.options)
|
| 499 |
+
|
| 500 |
+
curcode = ''
|
| 501 |
+
in_error = False
|
| 502 |
+
insertions = []
|
| 503 |
+
for match in line_re.finditer(text):
|
| 504 |
+
line = match.group()
|
| 505 |
+
if line.startswith('** '):
|
| 506 |
+
in_error = True
|
| 507 |
+
insertions.append((len(curcode),
|
| 508 |
+
[(0, Generic.Error, line[:-1])]))
|
| 509 |
+
curcode += line[-1:]
|
| 510 |
+
else:
|
| 511 |
+
m = self._prompt_re.match(line)
|
| 512 |
+
if m is not None:
|
| 513 |
+
in_error = False
|
| 514 |
+
end = m.end()
|
| 515 |
+
insertions.append((len(curcode),
|
| 516 |
+
[(0, Generic.Prompt, line[:end])]))
|
| 517 |
+
curcode += line[end:]
|
| 518 |
+
else:
|
| 519 |
+
if curcode:
|
| 520 |
+
yield from do_insertions(
|
| 521 |
+
insertions, exlexer.get_tokens_unprocessed(curcode))
|
| 522 |
+
curcode = ''
|
| 523 |
+
insertions = []
|
| 524 |
+
token = Generic.Error if in_error else Generic.Output
|
| 525 |
+
yield match.start(), token, line
|
| 526 |
+
if curcode:
|
| 527 |
+
yield from do_insertions(
|
| 528 |
+
insertions, exlexer.get_tokens_unprocessed(curcode))
|
shared/package-files/12/12129c6cf2f8efbeb9b56022439edcbac68ad9368842a64282d268119b3751dd/Malta
ADDED
|
Binary file (2.62 kB). View file
|
|
|
shared/package-files/12/1212c5348edc16cb540d460fecc27848b6d66c823d47257a8ef90490a3855583/new_empty_compositeexplicitautograd_dispatch.h
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace compositeexplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor new_empty(const at::Tensor & self, at::IntArrayRef size, at::TensorOptions options={});
|
| 21 |
+
TORCH_API at::Tensor new_empty(const at::Tensor & self, at::IntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
|
| 22 |
+
TORCH_API at::Tensor new_empty_symint(const at::Tensor & self, c10::SymIntArrayRef size, at::TensorOptions options={});
|
| 23 |
+
TORCH_API at::Tensor new_empty_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
|
| 24 |
+
TORCH_API at::Tensor & new_empty_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef size);
|
| 25 |
+
TORCH_API at::Tensor & new_empty_outf(const at::Tensor & self, at::IntArrayRef size, at::Tensor & out);
|
| 26 |
+
TORCH_API at::Tensor & new_empty_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef size);
|
| 27 |
+
TORCH_API at::Tensor & new_empty_symint_outf(const at::Tensor & self, c10::SymIntArrayRef size, at::Tensor & out);
|
| 28 |
+
|
| 29 |
+
} // namespace compositeexplicitautograd
|
| 30 |
+
} // namespace at
|
shared/package-files/12/1213fa6b70466961d59d6cefa0d6575f1c5c2c07004b9d45fb3929c2811b3aa6/special_hermite_polynomial_h_meta.h
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeMetaFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/TensorIterator.h>
|
| 13 |
+
#include <ATen/TensorMeta.h>
|
| 14 |
+
#include <tuple>
|
| 15 |
+
#include <vector>
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace meta {
|
| 19 |
+
|
| 20 |
+
struct TORCH_API structured_special_hermite_polynomial_h : public TensorIteratorBase {
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
void meta(const at::Tensor & x, const at::Tensor & n);
|
| 24 |
+
};
|
| 25 |
+
|
| 26 |
+
} // namespace native
|
| 27 |
+
} // namespace at
|
shared/package-files/12/12169e2ff3b05160392e08c5841a79c05e4783b6fdccb2d7b8a8e117b0ef67f9/mime340
ADDED
|
Binary file (422 Bytes). View file
|
|
|
shared/package-files/12/12169e2ff3b05160392e08c5841a79c05e4783b6fdccb2d7b8a8e117b0ef67f9/mm340
ADDED
|
Binary file (422 Bytes). View file
|
|
|
shared/package-files/12/12174302c11791cfb7c8e3decc5159468dfb691739ae231785e71a6eaac10a62/XPUHooksInterface.h
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <c10/core/Device.h>
|
| 4 |
+
#include <c10/util/Exception.h>
|
| 5 |
+
#include <ATen/core/Generator.h>
|
| 6 |
+
#include <c10/util/Registry.h>
|
| 7 |
+
|
| 8 |
+
#include <cstddef>
|
| 9 |
+
#include <functional>
|
| 10 |
+
#include <memory>
|
| 11 |
+
|
| 12 |
+
namespace at {
|
| 13 |
+
|
| 14 |
+
constexpr const char* XPU_HELP =
|
| 15 |
+
"The XPU backend requires Intel Extension for Pytorch;"
|
| 16 |
+
"this error has occurred because you are trying "
|
| 17 |
+
"to use some XPU's functionality, but the Intel Extension for Pytorch has not been "
|
| 18 |
+
"loaded for some reason. The Intel Extension for Pytorch MUST "
|
| 19 |
+
"be loaded, EVEN IF you don't directly use any symbols from that!";
|
| 20 |
+
|
| 21 |
+
struct TORCH_API XPUHooksInterface {
|
| 22 |
+
virtual ~XPUHooksInterface() {}
|
| 23 |
+
|
| 24 |
+
virtual void initXPU() const {
|
| 25 |
+
TORCH_CHECK(
|
| 26 |
+
false,
|
| 27 |
+
"Cannot initialize XPU without Intel Extension for Pytorch.",
|
| 28 |
+
XPU_HELP);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
virtual bool hasXPU() const {
|
| 32 |
+
return false;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
virtual std::string showConfig() const {
|
| 36 |
+
TORCH_CHECK(
|
| 37 |
+
false,
|
| 38 |
+
"Cannot query detailed XPU version without Intel Extension for Pytorch. ",
|
| 39 |
+
XPU_HELP);
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
virtual int32_t getGlobalIdxFromDevice(const Device& device) const {
|
| 43 |
+
TORCH_CHECK(false, "Cannot get XPU global device index without ATen_xpu library.");
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
virtual Generator getXPUGenerator(C10_UNUSED DeviceIndex device_index = -1) const {
|
| 47 |
+
TORCH_CHECK(false, "Cannot get XPU generator without Intel Extension for Pytorch. ", XPU_HELP);
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
virtual const Generator& getDefaultXPUGenerator(C10_UNUSED DeviceIndex device_index = -1) const {
|
| 51 |
+
TORCH_CHECK(false, "Cannot get default XPU generator without Intel Extension for Pytorch. ", XPU_HELP);
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
virtual DeviceIndex getNumGPUs() const {
|
| 55 |
+
return 0;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
virtual DeviceIndex current_device() const {
|
| 59 |
+
TORCH_CHECK(false, "Cannot get current device on XPU without ATen_xpu library.");
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
virtual Device getDeviceFromPtr(void* /*data*/) const {
|
| 63 |
+
TORCH_CHECK(false, "Cannot get device of pointer on XPU without ATen_xpu library.");
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
virtual void deviceSynchronize(DeviceIndex /*device_index*/) const {
|
| 67 |
+
TORCH_CHECK(false, "Cannot synchronize XPU device without ATen_xpu library.");
|
| 68 |
+
}
|
| 69 |
+
};
|
| 70 |
+
|
| 71 |
+
struct TORCH_API XPUHooksArgs {};
|
| 72 |
+
|
| 73 |
+
C10_DECLARE_REGISTRY(XPUHooksRegistry, XPUHooksInterface, XPUHooksArgs);
|
| 74 |
+
#define REGISTER_XPU_HOOKS(clsname) \
|
| 75 |
+
C10_REGISTER_CLASS(XPUHooksRegistry, clsname, clsname)
|
| 76 |
+
|
| 77 |
+
namespace detail {
|
| 78 |
+
TORCH_API const XPUHooksInterface& getXPUHooks();
|
| 79 |
+
} // namespace detail
|
| 80 |
+
} // namespace at
|
shared/package-files/12/1219c1146c749c177e647332e778a1a1e996b9dd319cd618633403aea599ed23/html_parser.pyi
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from html.parser import *
|
shared/package-files/12/121a104748e3c4fddcb8bd9ba464fb32e6a0520fe25a3667403d12f0c7e3f939/clamp_ops.h
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API clamp {
|
| 18 |
+
using schema = at::Tensor (const at::Tensor &, const c10::optional<at::Scalar> &, const c10::optional<at::Scalar> &);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clamp")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clamp(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor")
|
| 24 |
+
static at::Tensor call(const at::Tensor & self, const c10::optional<at::Scalar> & min, const c10::optional<at::Scalar> & max);
|
| 25 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const c10::optional<at::Scalar> & min, const c10::optional<at::Scalar> & max);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API clamp_Tensor {
|
| 29 |
+
using schema = at::Tensor (const at::Tensor &, const c10::optional<at::Tensor> &, const c10::optional<at::Tensor> &);
|
| 30 |
+
using ptr_schema = schema*;
|
| 31 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 32 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clamp")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clamp.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor")
|
| 35 |
+
static at::Tensor call(const at::Tensor & self, const c10::optional<at::Tensor> & min, const c10::optional<at::Tensor> & max);
|
| 36 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const c10::optional<at::Tensor> & min, const c10::optional<at::Tensor> & max);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
struct TORCH_API clamp_ {
|
| 40 |
+
using schema = at::Tensor & (at::Tensor &, const c10::optional<at::Scalar> &, const c10::optional<at::Scalar> &);
|
| 41 |
+
using ptr_schema = schema*;
|
| 42 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 43 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clamp_")
|
| 44 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 45 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clamp_(Tensor(a!) self, Scalar? min=None, Scalar? max=None) -> Tensor(a!)")
|
| 46 |
+
static at::Tensor & call(at::Tensor & self, const c10::optional<at::Scalar> & min, const c10::optional<at::Scalar> & max);
|
| 47 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const c10::optional<at::Scalar> & min, const c10::optional<at::Scalar> & max);
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
struct TORCH_API clamp__Tensor {
|
| 51 |
+
using schema = at::Tensor & (at::Tensor &, const c10::optional<at::Tensor> &, const c10::optional<at::Tensor> &);
|
| 52 |
+
using ptr_schema = schema*;
|
| 53 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 54 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clamp_")
|
| 55 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
|
| 56 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clamp_.Tensor(Tensor(a!) self, Tensor? min=None, Tensor? max=None) -> Tensor(a!)")
|
| 57 |
+
static at::Tensor & call(at::Tensor & self, const c10::optional<at::Tensor> & min, const c10::optional<at::Tensor> & max);
|
| 58 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const c10::optional<at::Tensor> & min, const c10::optional<at::Tensor> & max);
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
struct TORCH_API clamp_out {
|
| 62 |
+
using schema = at::Tensor & (const at::Tensor &, const c10::optional<at::Scalar> &, const c10::optional<at::Scalar> &, at::Tensor &);
|
| 63 |
+
using ptr_schema = schema*;
|
| 64 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 65 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clamp")
|
| 66 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 67 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clamp.out(Tensor self, Scalar? min=None, Scalar? max=None, *, Tensor(a!) out) -> Tensor(a!)")
|
| 68 |
+
static at::Tensor & call(const at::Tensor & self, const c10::optional<at::Scalar> & min, const c10::optional<at::Scalar> & max, at::Tensor & out);
|
| 69 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const c10::optional<at::Scalar> & min, const c10::optional<at::Scalar> & max, at::Tensor & out);
|
| 70 |
+
};
|
| 71 |
+
|
| 72 |
+
struct TORCH_API clamp_Tensor_out {
|
| 73 |
+
using schema = at::Tensor & (const at::Tensor &, const c10::optional<at::Tensor> &, const c10::optional<at::Tensor> &, at::Tensor &);
|
| 74 |
+
using ptr_schema = schema*;
|
| 75 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 76 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::clamp")
|
| 77 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out")
|
| 78 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "clamp.Tensor_out(Tensor self, Tensor? min=None, Tensor? max=None, *, Tensor(a!) out) -> Tensor(a!)")
|
| 79 |
+
static at::Tensor & call(const at::Tensor & self, const c10::optional<at::Tensor> & min, const c10::optional<at::Tensor> & max, at::Tensor & out);
|
| 80 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const c10::optional<at::Tensor> & min, const c10::optional<at::Tensor> & max, at::Tensor & out);
|
| 81 |
+
};
|
| 82 |
+
|
| 83 |
+
}} // namespace at::_ops
|
shared/package-files/12/121ba935b94002988b6c2fc848210afe48dc5f9de4e4797550b198c5d3f9d769/nll_loss2d_backward.h
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <c10/util/Optional.h>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/nll_loss2d_backward_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::nll_loss2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!)
|
| 26 |
+
inline at::Tensor & nll_loss2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight) {
|
| 27 |
+
return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input);
|
| 28 |
+
}
|
| 29 |
+
namespace symint {
|
| 30 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
|
| 31 |
+
at::Tensor & nll_loss2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight) {
|
| 32 |
+
return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input);
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
// aten::nll_loss2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!)
|
| 37 |
+
inline at::Tensor & nll_loss2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input) {
|
| 38 |
+
return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input);
|
| 39 |
+
}
|
| 40 |
+
namespace symint {
|
| 41 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
|
| 42 |
+
at::Tensor & nll_loss2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input) {
|
| 43 |
+
return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input);
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// aten::nll_loss2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!)
|
| 48 |
+
inline at::Tensor & nll_loss2d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight) {
|
| 49 |
+
return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input);
|
| 50 |
+
}
|
| 51 |
+
namespace symint {
|
| 52 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
|
| 53 |
+
at::Tensor & nll_loss2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight) {
|
| 54 |
+
return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input);
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
// aten::nll_loss2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!)
|
| 59 |
+
inline at::Tensor & nll_loss2d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input) {
|
| 60 |
+
return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input);
|
| 61 |
+
}
|
| 62 |
+
namespace symint {
|
| 63 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
|
| 64 |
+
at::Tensor & nll_loss2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input) {
|
| 65 |
+
return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input);
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
// aten::nll_loss2d_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor
|
| 70 |
+
inline at::Tensor nll_loss2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight) {
|
| 71 |
+
return at::_ops::nll_loss2d_backward::call(grad_output, self, target, weight, reduction, ignore_index, total_weight);
|
| 72 |
+
}
|
| 73 |
+
namespace symint {
|
| 74 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
|
| 75 |
+
at::Tensor nll_loss2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight) {
|
| 76 |
+
return at::_ops::nll_loss2d_backward::call(grad_output, self, target, weight, reduction, ignore_index, total_weight);
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
// aten::nll_loss2d_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor
|
| 81 |
+
inline at::Tensor nll_loss2d_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight) {
|
| 82 |
+
return at::_ops::nll_loss2d_backward::call(grad_output, self, target, weight, reduction, ignore_index, total_weight);
|
| 83 |
+
}
|
| 84 |
+
namespace symint {
|
| 85 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
|
| 86 |
+
at::Tensor nll_loss2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight) {
|
| 87 |
+
return at::_ops::nll_loss2d_backward::call(grad_output, self, target, weight, reduction, ignore_index, total_weight);
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
}
|
shared/package-files/12/121cc460893e0c122e534b0c83f75abd248bd70fa8dde9e54f54bdbb396365f3/_vbscript_builtins.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.lexers._vbscript_builtins
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
These are manually translated lists from
|
| 6 |
+
http://www.indusoft.com/pdf/VBScript%20Reference.pdf.
|
| 7 |
+
|
| 8 |
+
:copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
|
| 9 |
+
:license: BSD, see LICENSE for details.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
KEYWORDS = [
|
| 13 |
+
'ByRef',
|
| 14 |
+
'ByVal',
|
| 15 |
+
# dim: special rule
|
| 16 |
+
'call',
|
| 17 |
+
'case',
|
| 18 |
+
'class',
|
| 19 |
+
# const: special rule
|
| 20 |
+
'do',
|
| 21 |
+
'each',
|
| 22 |
+
'else',
|
| 23 |
+
'elseif',
|
| 24 |
+
'end',
|
| 25 |
+
'erase',
|
| 26 |
+
'execute',
|
| 27 |
+
'function',
|
| 28 |
+
'exit',
|
| 29 |
+
'for',
|
| 30 |
+
'function',
|
| 31 |
+
'GetRef',
|
| 32 |
+
'global',
|
| 33 |
+
'if',
|
| 34 |
+
'let',
|
| 35 |
+
'loop',
|
| 36 |
+
'next',
|
| 37 |
+
'new',
|
| 38 |
+
# option: special rule
|
| 39 |
+
'private',
|
| 40 |
+
'public',
|
| 41 |
+
'redim',
|
| 42 |
+
'select',
|
| 43 |
+
'set',
|
| 44 |
+
'sub',
|
| 45 |
+
'then',
|
| 46 |
+
'wend',
|
| 47 |
+
'while',
|
| 48 |
+
'with',
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
BUILTIN_FUNCTIONS = [
|
| 52 |
+
'Abs',
|
| 53 |
+
'Array',
|
| 54 |
+
'Asc',
|
| 55 |
+
'Atn',
|
| 56 |
+
'CBool',
|
| 57 |
+
'CByte',
|
| 58 |
+
'CCur',
|
| 59 |
+
'CDate',
|
| 60 |
+
'CDbl',
|
| 61 |
+
'Chr',
|
| 62 |
+
'CInt',
|
| 63 |
+
'CLng',
|
| 64 |
+
'Cos',
|
| 65 |
+
'CreateObject',
|
| 66 |
+
'CSng',
|
| 67 |
+
'CStr',
|
| 68 |
+
'Date',
|
| 69 |
+
'DateAdd',
|
| 70 |
+
'DateDiff',
|
| 71 |
+
'DatePart',
|
| 72 |
+
'DateSerial',
|
| 73 |
+
'DateValue',
|
| 74 |
+
'Day',
|
| 75 |
+
'Eval',
|
| 76 |
+
'Exp',
|
| 77 |
+
'Filter',
|
| 78 |
+
'Fix',
|
| 79 |
+
'FormatCurrency',
|
| 80 |
+
'FormatDateTime',
|
| 81 |
+
'FormatNumber',
|
| 82 |
+
'FormatPercent',
|
| 83 |
+
'GetObject',
|
| 84 |
+
'GetLocale',
|
| 85 |
+
'Hex',
|
| 86 |
+
'Hour',
|
| 87 |
+
'InStr',
|
| 88 |
+
'inStrRev',
|
| 89 |
+
'Int',
|
| 90 |
+
'IsArray',
|
| 91 |
+
'IsDate',
|
| 92 |
+
'IsEmpty',
|
| 93 |
+
'IsNull',
|
| 94 |
+
'IsNumeric',
|
| 95 |
+
'IsObject',
|
| 96 |
+
'Join',
|
| 97 |
+
'LBound',
|
| 98 |
+
'LCase',
|
| 99 |
+
'Left',
|
| 100 |
+
'Len',
|
| 101 |
+
'LoadPicture',
|
| 102 |
+
'Log',
|
| 103 |
+
'LTrim',
|
| 104 |
+
'Mid',
|
| 105 |
+
'Minute',
|
| 106 |
+
'Month',
|
| 107 |
+
'MonthName',
|
| 108 |
+
'MsgBox',
|
| 109 |
+
'Now',
|
| 110 |
+
'Oct',
|
| 111 |
+
'Randomize',
|
| 112 |
+
'RegExp',
|
| 113 |
+
'Replace',
|
| 114 |
+
'RGB',
|
| 115 |
+
'Right',
|
| 116 |
+
'Rnd',
|
| 117 |
+
'Round',
|
| 118 |
+
'RTrim',
|
| 119 |
+
'ScriptEngine',
|
| 120 |
+
'ScriptEngineBuildVersion',
|
| 121 |
+
'ScriptEngineMajorVersion',
|
| 122 |
+
'ScriptEngineMinorVersion',
|
| 123 |
+
'Second',
|
| 124 |
+
'SetLocale',
|
| 125 |
+
'Sgn',
|
| 126 |
+
'Space',
|
| 127 |
+
'Split',
|
| 128 |
+
'Sqr',
|
| 129 |
+
'StrComp',
|
| 130 |
+
'String',
|
| 131 |
+
'StrReverse',
|
| 132 |
+
'Tan',
|
| 133 |
+
'Time',
|
| 134 |
+
'Timer',
|
| 135 |
+
'TimeSerial',
|
| 136 |
+
'TimeValue',
|
| 137 |
+
'Trim',
|
| 138 |
+
'TypeName',
|
| 139 |
+
'UBound',
|
| 140 |
+
'UCase',
|
| 141 |
+
'VarType',
|
| 142 |
+
'Weekday',
|
| 143 |
+
'WeekdayName',
|
| 144 |
+
'Year',
|
| 145 |
+
]
|
| 146 |
+
|
| 147 |
+
BUILTIN_VARIABLES = [
|
| 148 |
+
'Debug',
|
| 149 |
+
'Dictionary',
|
| 150 |
+
'Drive',
|
| 151 |
+
'Drives',
|
| 152 |
+
'Err',
|
| 153 |
+
'File',
|
| 154 |
+
'Files',
|
| 155 |
+
'FileSystemObject',
|
| 156 |
+
'Folder',
|
| 157 |
+
'Folders',
|
| 158 |
+
'Match',
|
| 159 |
+
'Matches',
|
| 160 |
+
'RegExp',
|
| 161 |
+
'Submatches',
|
| 162 |
+
'TextStream',
|
| 163 |
+
]
|
| 164 |
+
|
| 165 |
+
OPERATORS = [
|
| 166 |
+
'+',
|
| 167 |
+
'-',
|
| 168 |
+
'*',
|
| 169 |
+
'/',
|
| 170 |
+
'\\',
|
| 171 |
+
'^',
|
| 172 |
+
'|',
|
| 173 |
+
'<',
|
| 174 |
+
'<=',
|
| 175 |
+
'>',
|
| 176 |
+
'>=',
|
| 177 |
+
'=',
|
| 178 |
+
'<>',
|
| 179 |
+
'&',
|
| 180 |
+
'$',
|
| 181 |
+
]
|
| 182 |
+
|
| 183 |
+
OPERATOR_WORDS = [
|
| 184 |
+
'mod',
|
| 185 |
+
'and',
|
| 186 |
+
'or',
|
| 187 |
+
'xor',
|
| 188 |
+
'eqv',
|
| 189 |
+
'imp',
|
| 190 |
+
'is',
|
| 191 |
+
'not',
|
| 192 |
+
]
|
| 193 |
+
|
| 194 |
+
BUILTIN_CONSTANTS = [
|
| 195 |
+
'False',
|
| 196 |
+
'True',
|
| 197 |
+
'vbAbort',
|
| 198 |
+
'vbAbortRetryIgnore',
|
| 199 |
+
'vbApplicationModal',
|
| 200 |
+
'vbArray',
|
| 201 |
+
'vbBinaryCompare',
|
| 202 |
+
'vbBlack',
|
| 203 |
+
'vbBlue',
|
| 204 |
+
'vbBoole',
|
| 205 |
+
'vbByte',
|
| 206 |
+
'vbCancel',
|
| 207 |
+
'vbCr',
|
| 208 |
+
'vbCritical',
|
| 209 |
+
'vbCrLf',
|
| 210 |
+
'vbCurrency',
|
| 211 |
+
'vbCyan',
|
| 212 |
+
'vbDataObject',
|
| 213 |
+
'vbDate',
|
| 214 |
+
'vbDefaultButton1',
|
| 215 |
+
'vbDefaultButton2',
|
| 216 |
+
'vbDefaultButton3',
|
| 217 |
+
'vbDefaultButton4',
|
| 218 |
+
'vbDouble',
|
| 219 |
+
'vbEmpty',
|
| 220 |
+
'vbError',
|
| 221 |
+
'vbExclamation',
|
| 222 |
+
'vbFalse',
|
| 223 |
+
'vbFirstFullWeek',
|
| 224 |
+
'vbFirstJan1',
|
| 225 |
+
'vbFormFeed',
|
| 226 |
+
'vbFriday',
|
| 227 |
+
'vbGeneralDate',
|
| 228 |
+
'vbGreen',
|
| 229 |
+
'vbIgnore',
|
| 230 |
+
'vbInformation',
|
| 231 |
+
'vbInteger',
|
| 232 |
+
'vbLf',
|
| 233 |
+
'vbLong',
|
| 234 |
+
'vbLongDate',
|
| 235 |
+
'vbLongTime',
|
| 236 |
+
'vbMagenta',
|
| 237 |
+
'vbMonday',
|
| 238 |
+
'vbMsgBoxHelpButton',
|
| 239 |
+
'vbMsgBoxRight',
|
| 240 |
+
'vbMsgBoxRtlReading',
|
| 241 |
+
'vbMsgBoxSetForeground',
|
| 242 |
+
'vbNewLine',
|
| 243 |
+
'vbNo',
|
| 244 |
+
'vbNull',
|
| 245 |
+
'vbNullChar',
|
| 246 |
+
'vbNullString',
|
| 247 |
+
'vbObject',
|
| 248 |
+
'vbObjectError',
|
| 249 |
+
'vbOK',
|
| 250 |
+
'vbOKCancel',
|
| 251 |
+
'vbOKOnly',
|
| 252 |
+
'vbQuestion',
|
| 253 |
+
'vbRed',
|
| 254 |
+
'vbRetry',
|
| 255 |
+
'vbRetryCancel',
|
| 256 |
+
'vbSaturday',
|
| 257 |
+
'vbShortDate',
|
| 258 |
+
'vbShortTime',
|
| 259 |
+
'vbSingle',
|
| 260 |
+
'vbString',
|
| 261 |
+
'vbSunday',
|
| 262 |
+
'vbSystemModal',
|
| 263 |
+
'vbTab',
|
| 264 |
+
'vbTextCompare',
|
| 265 |
+
'vbThursday',
|
| 266 |
+
'vbTrue',
|
| 267 |
+
'vbTuesday',
|
| 268 |
+
'vbUseDefault',
|
| 269 |
+
'vbUseSystem',
|
| 270 |
+
'vbUseSystem',
|
| 271 |
+
'vbVariant',
|
| 272 |
+
'vbVerticalTab',
|
| 273 |
+
'vbWednes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
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
from numpy.linalg import norm
|
| 7 |
+
from numpy.testing import (TestCase, assert_array_almost_equal,
|
| 8 |
+
assert_array_equal, assert_array_less)
|
| 9 |
+
from scipy.optimize import (BFGS, SR1)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Rosenbrock:
|
| 13 |
+
"""Rosenbrock function.
|
| 14 |
+
|
| 15 |
+
The following optimization problem:
|
| 16 |
+
minimize sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self, n=2, random_state=0):
|
| 20 |
+
rng = np.random.RandomState(random_state)
|
| 21 |
+
self.x0 = rng.uniform(-1, 1, n)
|
| 22 |
+
self.x_opt = np.ones(n)
|
| 23 |
+
|
| 24 |
+
def fun(self, x):
|
| 25 |
+
x = np.asarray(x)
|
| 26 |
+
r = np.sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0,
|
| 27 |
+
axis=0)
|
| 28 |
+
return r
|
| 29 |
+
|
| 30 |
+
def grad(self, x):
|
| 31 |
+
x = np.asarray(x)
|
| 32 |
+
xm = x[1:-1]
|
| 33 |
+
xm_m1 = x[:-2]
|
| 34 |
+
xm_p1 = x[2:]
|
| 35 |
+
der = np.zeros_like(x)
|
| 36 |
+
der[1:-1] = (200 * (xm - xm_m1**2) -
|
| 37 |
+
400 * (xm_p1 - xm**2) * xm - 2 * (1 - xm))
|
| 38 |
+
der[0] = -400 * x[0] * (x[1] - x[0]**2) - 2 * (1 - x[0])
|
| 39 |
+
der[-1] = 200 * (x[-1] - x[-2]**2)
|
| 40 |
+
return der
|
| 41 |
+
|
| 42 |
+
def hess(self, x):
|
| 43 |
+
x = np.atleast_1d(x)
|
| 44 |
+
H = np.diag(-400 * x[:-1], 1) - np.diag(400 * x[:-1], -1)
|
| 45 |
+
diagonal = np.zeros(len(x), dtype=x.dtype)
|
| 46 |
+
diagonal[0] = 1200 * x[0]**2 - 400 * x[1] + 2
|
| 47 |
+
diagonal[-1] = 200
|
| 48 |
+
diagonal[1:-1] = 202 + 1200 * x[1:-1]**2 - 400 * x[2:]
|
| 49 |
+
H = H + np.diag(diagonal)
|
| 50 |
+
return H
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class TestHessianUpdateStrategy(TestCase):
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_hessian_initialization(self):
|
| 57 |
+
|
| 58 |
+
ndims = 5
|
| 59 |
+
symmetric_matrix = np.array([[43, 24, 33, 34, 49],
|
| 60 |
+
[24, 36, 44, 15, 44],
|
| 61 |
+
[33, 44, 37, 1, 30],
|
| 62 |
+
[34, 15, 1, 5, 46],
|
| 63 |
+
[49, 44, 30, 46, 22]])
|
| 64 |
+
init_scales = (
|
| 65 |
+
('auto', np.eye(ndims)),
|
| 66 |
+
(2, np.eye(ndims) * 2),
|
| 67 |
+
(np.arange(1, ndims + 1) * np.eye(ndims),
|
| 68 |
+
np.arange(1, ndims + 1) * np.eye(ndims)),
|
| 69 |
+
(symmetric_matrix, symmetric_matrix),)
|
| 70 |
+
for approx_type in ['hess', 'inv_hess']:
|
| 71 |
+
for init_scale, true_matrix in init_scales:
|
| 72 |
+
# large min_{denominator,curvatur} makes them skip an update,
|
| 73 |
+
# so we can have our initial matrix
|
| 74 |
+
quasi_newton = (BFGS(init_scale=init_scale,
|
| 75 |
+
min_curvature=1e50,
|
| 76 |
+
exception_strategy='skip_update'),
|
| 77 |
+
SR1(init_scale=init_scale,
|
| 78 |
+
min_denominator=1e50))
|
| 79 |
+
|
| 80 |
+
for qn in quasi_newton:
|
| 81 |
+
qn.initialize(ndims, approx_type)
|
| 82 |
+
B = qn.get_matrix()
|
| 83 |
+
|
| 84 |
+
assert_array_equal(B, np.eye(ndims))
|
| 85 |
+
# don't test the auto init scale
|
| 86 |
+
if isinstance(init_scale, str) and init_scale == 'auto':
|
| 87 |
+
continue
|
| 88 |
+
|
| 89 |
+
qn.update(np.ones(ndims) * 1e-5, np.arange(ndims) + 0.2)
|
| 90 |
+
B = qn.get_matrix()
|
| 91 |
+
assert_array_equal(B, true_matrix)
|
| 92 |
+
|
| 93 |
+
# For this list of points, it is known
|
| 94 |
+
# that no exception occur during the
|
| 95 |
+
# Hessian update. Hence no update is
|
| 96 |
+
# skiped or damped.
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_initialize_catch_illegal(self):
|
| 100 |
+
ndims = 3
|
| 101 |
+
# no complex allowed
|
| 102 |
+
inits_msg_errtype = ((complex(3.14),
|
| 103 |
+
r"float\(\) argument must be a string or a "
|
| 104 |
+
r"(real )?number, not 'complex'",
|
| 105 |
+
TypeError),
|
| 106 |
+
|
| 107 |
+
(np.array([3.2, 2.3, 1.2]).astype(np.complex128),
|
| 108 |
+
"init_scale contains complex elements, "
|
| 109 |
+
"must be real.",
|
| 110 |
+
TypeError),
|
| 111 |
+
|
| 112 |
+
(np.array([[43, 24, 33],
|
| 113 |
+
[24, 36, 44, ],
|
| 114 |
+
[33, 44, 37, ]]).astype(np.complex128),
|
| 115 |
+
"init_scale contains complex elements, "
|
| 116 |
+
"must be real.",
|
| 117 |
+
TypeError),
|
| 118 |
+
|
| 119 |
+
# not square
|
| 120 |
+
(np.array([[43, 55, 66]]),
|
| 121 |
+
re.escape(
|
| 122 |
+
"If init_scale is an array, it must have the "
|
| 123 |
+
"dimensions of the hess/inv_hess: (3, 3)."
|
| 124 |
+
" Got (1, 3)."),
|
| 125 |
+
ValueError),
|
| 126 |
+
|
| 127 |
+
# not symmetric
|
| 128 |
+
(np.array([[43, 24, 33],
|
| 129 |
+
[24.1, 36, 44, ],
|
| 130 |
+
[33, 44, 37, ]]),
|
| 131 |
+
re.escape("If init_scale is an array, it must be"
|
| 132 |
+
" symmetric (passing scipy.linalg.issymmetric)"
|
| 133 |
+
" to be an approximation of a hess/inv_hess."),
|
| 134 |
+
ValueError),
|
| 135 |
+
)
|
| 136 |
+
for approx_type in ['hess', 'inv_hess']:
|
| 137 |
+
for init_scale, message, errortype in inits_msg_errtype:
|
| 138 |
+
# large min_{denominator,curvatur} makes it skip an update,
|
| 139 |
+
# so we can retrieve our initial matrix
|
| 140 |
+
quasi_newton = (BFGS(init_scale=init_scale),
|
| 141 |
+
SR1(init_scale=init_scale))
|
| 142 |
+
|
| 143 |
+
for qn in quasi_newton:
|
| 144 |
+
qn.initialize(ndims, approx_type)
|
| 145 |
+
with pytest.raises(errortype, match=message):
|
| 146 |
+
qn.update(np.ones(ndims), np.arange(ndims))
|
| 147 |
+
|
| 148 |
+
def test_rosenbrock_with_no_exception(self):
|
| 149 |
+
# Define auxiliary problem
|
| 150 |
+
prob = Rosenbrock(n=5)
|
| 151 |
+
# Define iteration points
|
| 152 |
+
x_list = [[0.0976270, 0.4303787, 0.2055267, 0.0897663, -0.15269040],
|
| 153 |
+
[0.1847239, 0.0505757, 0.2123832, 0.0255081, 0.00083286],
|
| 154 |
+
[0.2142498, -0.0188480, 0.0503822, 0.0347033, 0.03323606],
|
| 155 |
+
[0.2071680, -0.0185071, 0.0341337, -0.0139298, 0.02881750],
|
| 156 |
+
[0.1533055, -0.0322935, 0.0280418, -0.0083592, 0.01503699],
|
| 157 |
+
[0.1382378, -0.0276671, 0.0266161, -0.0074060, 0.02801610],
|
| 158 |
+
[0.1651957, -0.0049124, 0.0269665, -0.0040025, 0.02138184],
|
| 159 |
+
[0.2354930, 0.0443711, 0.0173959, 0.0041872, 0.00794563],
|
| 160 |
+
[0.4168118, 0.1433867, 0.0111714, 0.0126265, -0.00658537],
|
| 161 |
+
[0.4681972, 0.2153273, 0.0225249, 0.0152704, -0.00463809],
|
| 162 |
+
[0.6023068, 0.3346815, 0.0731108, 0.0186618, -0.00371541],
|
| 163 |
+
[0.6415743, 0.3985468, 0.1324422, 0.0214160, -0.00062401],
|
| 164 |
+
[0.7503690, 0.5447616, 0.2804541, 0.0539851, 0.00242230],
|
| 165 |
+
[0.7452626, 0.5644594, 0.3324679, 0.0865153, 0.00454960],
|
| 166 |
+
[0.8059782, 0.6586838, 0.4229577, 0.1452990, 0.00976702],
|
| 167 |
+
[0.8549542, 0.7226562, 0.4991309, 0.2420093, 0.02772661],
|
| 168 |
+
[0.8571332, 0.7285741, 0.5279076, 0.2824549, 0.06030276],
|
| 169 |
+
[0.8835633, 0.7727077, 0.5957984, 0.3411303, 0.09652185],
|
| 170 |
+
[0.9071558, 0.8299587, 0.6771400, 0.4402896, 0.17469338],
|
| 171 |
+
[0.9190793, 0.8486480, 0.7163332, 0.5083780, 0.26107691],
|
| 172 |
+
[0.9371223, 0.8762177, 0.7653702, 0.5773109, 0.32181041],
|
| 173 |
+
[0.9554613, 0.9119893, 0.8282687, 0.6776178, 0.43162744],
|
| 174 |
+
[0.9545744, 0.9099264, 0.8270244, 0.6822220, 0.45237623],
|
| 175 |
+
[0.9688112, 0.9351710, 0.8730961, 0.7546601, 0.56622448],
|
| 176 |
+
[0.9743227, 0.9491953, 0.9005150, 0.8086497, 0.64505437],
|
| 177 |
+
[0.9807345, 0.9638853, 0.9283012, 0.8631675, 0.73812581],
|
| 178 |
+
[0.9886746, 0.9777760, 0.9558950, 0.9123417, 0.82726553],
|
| 179 |
+
[0.9899096, 0.9803828, 0.9615592, 0.9255600, 0.85822149],
|
| 180 |
+
[0.9969510, 0.9935441, 0.9864657, 0.9726775, 0.94358663],
|
| 181 |
+
[0.9979533, 0.9960274, 0.9921724, 0.9837415, 0.96626288],
|
| 182 |
+
[0.9995981, 0.9989171, 0.9974178, 0.9949954, 0.99023356],
|
| 183 |
+
[1.0002640, 1.0005088, 1.0010594, 1.0021161, 1.00386912],
|
| 184 |
+
[0.9998903, 0.9998459, 0.9997795, 0.9995484, 0.99916305],
|
| 185 |
+
[1.0000008, 0.9999905, 0.9999481, 0.9998903, 0.99978047],
|
| 186 |
+
[1.0000004, 0.9999983, 1.0000001, 1.0000031, 1.00000297],
|
| 187 |
+
[0.9999995, 1.0000003, 1.0000005, 1.0000001, 1.00000032],
|
| 188 |
+
[0.9999999, 0.9999997, 0.9999994, 0.9999989, 0.99999786],
|
| 189 |
+
[0.9999999, 0.9999999, 0.9999999, 0.9999999, 0.99999991]]
|
| 190 |
+
# Get iteration points
|
| 191 |
+
grad_list = [prob.grad(x) for x in x_list]
|
| 192 |
+
delta_x = [np.array(x_list[i+1])-np.array(x_list[i])
|
| 193 |
+
for i in range(len(x_list)-1)]
|
| 194 |
+
delta_grad = [grad_list[i+1]-grad_list[i]
|
| 195 |
+
for i in range(len(grad_list)-1)]
|
| 196 |
+
# Check curvature condition
|
| 197 |
+
for s, y in zip(delta_x, delta_grad):
|
| 198 |
+
if np.dot(s, y) <= 0:
|
| 199 |
+
raise ArithmeticError()
|
| 200 |
+
# Define QuasiNewton update
|
| 201 |
+
for quasi_newton in (BFGS(init_scale=1, min_curvature=1e-4),
|
| 202 |
+
SR1(init_scale=1)):
|
| 203 |
+
hess = deepcopy(quasi_newton)
|
| 204 |
+
inv_hess = deepcopy(quasi_newton)
|
| 205 |
+
hess.initialize(len(x_list[0]), 'hess')
|
| 206 |
+
inv_hess.initialize(len(x_list[0]), 'inv_hess')
|
| 207 |
+
# Compare the hessian and its inverse
|
| 208 |
+
for s, y in zip(delta_x, delta_grad):
|
| 209 |
+
hess.update(s, y)
|
| 210 |
+
inv_hess.update(s, y)
|
| 211 |
+
B = hess.get_matrix()
|
| 212 |
+
H = inv_hess.get_matrix()
|
| 213 |
+
assert_array_almost_equal(np.linalg.inv(B), H, decimal=10)
|
| 214 |
+
B_true = prob.hess(x_list[len(delta_x)])
|
| 215 |
+
assert_array_less(norm(B - B_true)/norm(B_true), 0.1)
|
| 216 |
+
|
| 217 |
+
def test_SR1_skip_update(self):
|
| 218 |
+
# Define auxiliary problem
|
| 219 |
+
prob = Rosenbrock(n=5)
|
| 220 |
+
# Define iteration points
|
| 221 |
+
x_list = [[0.0976270, 0.4303787, 0.2055267, 0.0897663, -0.15269040],
|
| 222 |
+
[0.1847239, 0.0505757, 0.2123832, 0.0255081, 0.00083286],
|
| 223 |
+
[0.2142498, -0.0188480, 0.0503822, 0.0347033, 0.03323606],
|
| 224 |
+
[0.2071680, -0.0185071, 0.0341337, -0.0139298, 0.02881750],
|
| 225 |
+
[0.1533055, -0.0322935, 0.0280418, -0.0083592, 0.01503699],
|
| 226 |
+
[0.1382378, -0.0276671, 0.0266161, -0.0074060, 0.02801610],
|
| 227 |
+
[0.1651957, -0.0049124, 0.0269665, -0.0040025, 0.02138184],
|
| 228 |
+
[0.2354930, 0.0443711, 0.0173959, 0.0041872, 0.00794563],
|
| 229 |
+
[0.4168118, 0.1433867, 0.0111714, 0.0126265, -0.00658537],
|
| 230 |
+
[0.4681972, 0.2153273, 0.0225249, 0.0152704, -0.00463809],
|
| 231 |
+
[0.6023068, 0.3346815, 0.0731108, 0.0186618, -0.00371541],
|
| 232 |
+
[0.6415743, 0.3985468, 0.1324422, 0.0214160, -0.00062401],
|
| 233 |
+
[0.7503690, 0.5447616, 0.2804541, 0.0539851, 0.00242230],
|
| 234 |
+
[0.7452626, 0.5644594, 0.3324679, 0.0865153, 0.00454960],
|
| 235 |
+
[0.8059782, 0.6586838, 0.4229577, 0.1452990, 0.00976702],
|
| 236 |
+
[0.8549542, 0.7226562, 0.4991309, 0.2420093, 0.02772661],
|
| 237 |
+
[0.8571332, 0.7285741, 0.5279076, 0.2824549, 0.06030276],
|
| 238 |
+
[0.8835633, 0.7727077, 0.5957984, 0.3411303, 0.09652185],
|
| 239 |
+
[0.9071558, 0.8299587, 0.6771400, 0.4402896, 0.17469338]]
|
| 240 |
+
# Get iteration points
|
| 241 |
+
grad_list = [prob.grad(x) for x in x_list]
|
| 242 |
+
delta_x = [np.array(x_list[i+1])-np.array(x_list[i])
|
| 243 |
+
for i in range(len(x_list)-1)]
|
| 244 |
+
delta_grad = [grad_list[i+1]-grad_list[i]
|
| 245 |
+
for i in range(len(grad_list)-1)]
|
| 246 |
+
hess = SR1(init_scale=1, min_denominator=1e-2)
|
| 247 |
+
hess.initialize(len(x_list[0]), 'hess')
|
| 248 |
+
# Compare the Hessian and its inverse
|
| 249 |
+
for i in range(len(delta_x)-1):
|
| 250 |
+
s = delta_x[i]
|
| 251 |
+
y = delta_grad[i]
|
| 252 |
+
hess.update(s, y)
|
| 253 |
+
# Test skip update
|
| 254 |
+
B = np.copy(hess.get_matrix())
|
| 255 |
+
s = delta_x[17]
|
| 256 |
+
y = delta_grad[17]
|
| 257 |
+
hess.update(s, y)
|
| 258 |
+
B_updated = np.copy(hess.get_matrix())
|
| 259 |
+
assert_array_equal(B, B_updated)
|
| 260 |
+
|
| 261 |
+
def test_BFGS_skip_update(self):
|
| 262 |
+
# Define auxiliary problem
|
| 263 |
+
prob = Rosenbrock(n=5)
|
| 264 |
+
# Define iteration points
|
| 265 |
+
x_list = [[0.0976270, 0.4303787, 0.2055267, 0.0897663, -0.15269040],
|
| 266 |
+
[0.1847239, 0.0505757, 0.2123832, 0.0255081, 0.00083286],
|
| 267 |
+
[0.2142498, -0.0188480, 0.0503822, 0.0347033, 0.03323606],
|
| 268 |
+
[0.2071680, -0.0185071, 0.0341337, -0.0139298, 0.02881750],
|
| 269 |
+
[0.1533055, -0.0322935, 0.0280418, -0.0083592, 0.01503699],
|
| 270 |
+
[0.1382378, -0.0276671, 0.0266161, -0.0074060, 0.02801610],
|
| 271 |
+
[0.1651957, -0.0049124, 0.0269665, -0.0040025, 0.02138184]]
|
| 272 |
+
# Get iteration points
|
| 273 |
+
grad_list = [prob.grad(x) for x in x_list]
|
| 274 |
+
delta_x = [np.array(x_list[i+1])-np.array(x_list[i])
|
| 275 |
+
for i in range(len(x_list)-1)]
|
| 276 |
+
delta_grad = [grad_list[i+1]-grad_list[i]
|
| 277 |
+
for i in range(len(grad_list)-1)]
|
| 278 |
+
hess = BFGS(init_scale=1, min_curvature=10)
|
| 279 |
+
hess.initialize(len(x_list[0]), 'hess')
|
| 280 |
+
# Compare the Hessian and its inverse
|
| 281 |
+
for i in range(len(delta_x)-1):
|
| 282 |
+
s = delta_x[i]
|
| 283 |
+
y = delta_grad[i]
|
| 284 |
+
hess.update(s, y)
|
| 285 |
+
# Test skip update
|
| 286 |
+
B = np.copy(hess.get_matrix())
|
| 287 |
+
s = delta_x[5]
|
| 288 |
+
y = delta_grad[5]
|
| 289 |
+
hess.update(s, y)
|
| 290 |
+
B_updated = np.copy(hess.get_matrix())
|
| 291 |
+
assert_array_equal(B, B_updated)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
@pytest.mark.parametrize('strategy', [BFGS, SR1])
|
| 295 |
+
@pytest.mark.parametrize('approx_type', ['hess', 'inv_hess'])
|
| 296 |
+
def test_matmul_equals_dot(strategy, approx_type):
|
| 297 |
+
H = strategy(init_scale=1)
|
| 298 |
+
H.initialize(2, approx_type)
|
| 299 |
+
v = np.array([1, 2])
|
| 300 |
+
assert_array_equal(H @ v, H.dot(v))
|
shared/package-files/12/122306c1ce83ca4f3ce92ffefff2a5dbc253f073f08cf8ea5f9c2881e8d48b6d/sun-s
ADDED
|
Binary file (1.02 kB). View file
|
|
|
shared/package-files/12/1224241dcfb4ec6aff3cafc66adeb2b2a3759397a28693173915458c50040143/colorchooser.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# tk common color chooser dialogue
|
| 2 |
+
#
|
| 3 |
+
# this module provides an interface to the native color dialogue
|
| 4 |
+
# available in Tk 4.2 and newer.
|
| 5 |
+
#
|
| 6 |
+
# written by Fredrik Lundh, May 1997
|
| 7 |
+
#
|
| 8 |
+
# fixed initialcolor handling in August 1998
|
| 9 |
+
#
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
from tkinter.commondialog import Dialog
|
| 13 |
+
|
| 14 |
+
__all__ = ["Chooser", "askcolor"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Chooser(Dialog):
|
| 18 |
+
"""Create a dialog for the tk_chooseColor command.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
master: The master widget for this dialog. If not provided,
|
| 22 |
+
defaults to options['parent'] (if defined).
|
| 23 |
+
options: Dictionary of options for the tk_chooseColor call.
|
| 24 |
+
initialcolor: Specifies the selected color when the
|
| 25 |
+
dialog is first displayed. This can be a tk color
|
| 26 |
+
string or a 3-tuple of ints in the range (0, 255)
|
| 27 |
+
for an RGB triplet.
|
| 28 |
+
parent: The parent window of the color dialog. The
|
| 29 |
+
color dialog is displayed on top of this.
|
| 30 |
+
title: A string for the title of the dialog box.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
command = "tk_chooseColor"
|
| 34 |
+
|
| 35 |
+
def _fixoptions(self):
|
| 36 |
+
"""Ensure initialcolor is a tk color string.
|
| 37 |
+
|
| 38 |
+
Convert initialcolor from a RGB triplet to a color string.
|
| 39 |
+
"""
|
| 40 |
+
try:
|
| 41 |
+
color = self.options["initialcolor"]
|
| 42 |
+
if isinstance(color, tuple):
|
| 43 |
+
# Assume an RGB triplet.
|
| 44 |
+
self.options["initialcolor"] = "#%02x%02x%02x" % color
|
| 45 |
+
except KeyError:
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
def _fixresult(self, widget, result):
|
| 49 |
+
"""Adjust result returned from call to tk_chooseColor.
|
| 50 |
+
|
| 51 |
+
Return both an RGB tuple of ints in the range (0, 255) and the
|
| 52 |
+
tk color string in the form #rrggbb.
|
| 53 |
+
"""
|
| 54 |
+
# Result can be many things: an empty tuple, an empty string, or
|
| 55 |
+
# a _tkinter.Tcl_Obj, so this somewhat weird check handles that.
|
| 56 |
+
if not result or not str(result):
|
| 57 |
+
return None, None # canceled
|
| 58 |
+
|
| 59 |
+
# To simplify application code, the color chooser returns
|
| 60 |
+
# an RGB tuple together with the Tk color string.
|
| 61 |
+
r, g, b = widget.winfo_rgb(result)
|
| 62 |
+
return (r//256, g//256, b//256), str(result)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
#
|
| 66 |
+
# convenience stuff
|
| 67 |
+
|
| 68 |
+
def askcolor(color=None, **options):
|
| 69 |
+
"""Display dialog window for selection of a color.
|
| 70 |
+
|
| 71 |
+
Convenience wrapper for the Chooser class. Displays the color
|
| 72 |
+
chooser dialog with color as the initial value.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
if color:
|
| 76 |
+
options = options.copy()
|
| 77 |
+
options["initialcolor"] = color
|
| 78 |
+
|
| 79 |
+
return Chooser(**options).show()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# --------------------------------------------------------------------
|
| 83 |
+
# test stuff
|
| 84 |
+
|
| 85 |
+
if __name__ == "__main__":
|
| 86 |
+
print("color", askcolor())
|
shared/package-files/12/122465451fa4cc994a577357a18b58ac684c4b7959da85b041dabbee1d5c63c1/message_listener.pyi
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class MessageListener(object):
|
| 2 |
+
def Modified(self) -> None: ...
|
| 3 |
+
|
| 4 |
+
class NullMessage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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Any
|
| 4 |
+
|
| 5 |
+
import dask.dataframe as dd
|
| 6 |
+
|
| 7 |
+
from narwhals._dask.utils import add_row_index, evaluate_exprs, narwhals_to_native_dtype
|
| 8 |
+
from narwhals._pandas_like.utils import native_to_narwhals_dtype, select_columns_by_name
|
| 9 |
+
from narwhals._typing_compat import assert_never
|
| 10 |
+
from narwhals._utils import (
|
| 11 |
+
Implementation,
|
| 12 |
+
ValidateBackendVersion,
|
| 13 |
+
_remap_full_join_keys,
|
| 14 |
+
check_column_names_are_unique,
|
| 15 |
+
check_columns_exist,
|
| 16 |
+
generate_temporary_column_name,
|
| 17 |
+
not_implemented,
|
| 18 |
+
parse_columns_to_drop,
|
| 19 |
+
)
|
| 20 |
+
from narwhals.exceptions import MultiOutputExpressionError
|
| 21 |
+
from narwhals.typing import CompliantLazyFrame
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
from collections.abc import Iterable, Iterator, Mapping, Sequence
|
| 25 |
+
from io import BytesIO
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
from types import ModuleType
|
| 28 |
+
from typing import TypeAlias
|
| 29 |
+
|
| 30 |
+
import dask.dataframe.dask_expr as dx
|
| 31 |
+
from typing_extensions import Self, TypeIs
|
| 32 |
+
|
| 33 |
+
from narwhals._compliant.typing import CompliantDataFrameAny
|
| 34 |
+
from narwhals._dask.expr import DaskExpr
|
| 35 |
+
from narwhals._dask.group_by import DaskLazyGroupBy
|
| 36 |
+
from narwhals._dask.namespace import DaskNamespace
|
| 37 |
+
from narwhals._typing import _EagerAllowedImpl
|
| 38 |
+
from narwhals._utils import Version, _LimitedContext
|
| 39 |
+
from narwhals.dataframe import LazyFrame
|
| 40 |
+
from narwhals.dtypes import DType
|
| 41 |
+
from narwhals.exceptions import ColumnNotFoundError
|
| 42 |
+
from narwhals.typing import (
|
| 43 |
+
AsofJoinStrategy,
|
| 44 |
+
IntoDType,
|
| 45 |
+
JoinStrategy,
|
| 46 |
+
UniqueKeepStrategy,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
Incomplete: TypeAlias = "Any"
|
| 50 |
+
"""Using `_pandas_like` utils with `_dask`.
|
| 51 |
+
|
| 52 |
+
Typing this correctly will complicate the `_pandas_like`-side.
|
| 53 |
+
Very low priority until `dask` adds typing.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class DaskLazyFrame(
|
| 58 |
+
CompliantLazyFrame["DaskExpr", "dd.DataFrame", "LazyFrame[dd.DataFrame]"],
|
| 59 |
+
ValidateBackendVersion,
|
| 60 |
+
):
|
| 61 |
+
_implementation = Implementation.DASK
|
| 62 |
+
|
| 63 |
+
def __init__(
|
| 64 |
+
self,
|
| 65 |
+
native_dataframe: dd.DataFrame,
|
| 66 |
+
*,
|
| 67 |
+
version: Version,
|
| 68 |
+
validate_backend_version: bool = False,
|
| 69 |
+
) -> None:
|
| 70 |
+
self._native_frame: dd.DataFrame = native_dataframe
|
| 71 |
+
self._version = version
|
| 72 |
+
self._cached_schema: dict[str, DType] | None = None
|
| 73 |
+
self._cached_columns: list[str] | None = None
|
| 74 |
+
if validate_backend_version:
|
| 75 |
+
self._validate_backend_version()
|
| 76 |
+
|
| 77 |
+
@staticmethod
|
| 78 |
+
def _is_native(obj: dd.DataFrame | Any) -> TypeIs[dd.DataFrame]:
|
| 79 |
+
return isinstance(obj, dd.DataFrame)
|
| 80 |
+
|
| 81 |
+
@classmethod
|
| 82 |
+
def from_native(cls, data: dd.DataFrame, /, *, context: _LimitedContext) -> Self:
|
| 83 |
+
return cls(data, version=context._version)
|
| 84 |
+
|
| 85 |
+
def to_narwhals(self) -> LazyFrame[dd.DataFrame]:
|
| 86 |
+
return self._version.lazyframe(self, level="lazy")
|
| 87 |
+
|
| 88 |
+
def __native_namespace__(self) -> ModuleType:
|
| 89 |
+
if self._implementation is Implementation.DASK:
|
| 90 |
+
return self._implementation.to_native_namespace()
|
| 91 |
+
|
| 92 |
+
msg = f"Expected dask, got: {type(self._implementation)}" # pragma: no cover
|
| 93 |
+
raise AssertionError(msg)
|
| 94 |
+
|
| 95 |
+
def __narwhals_namespace__(self) -> DaskNamespace:
|
| 96 |
+
from narwhals._dask.namespace import DaskNamespace
|
| 97 |
+
|
| 98 |
+
return DaskNamespace(version=self._version)
|
| 99 |
+
|
| 100 |
+
def __narwhals_lazyframe__(self) -> Self:
|
| 101 |
+
return self
|
| 102 |
+
|
| 103 |
+
def _with_version(self, version: Version) -> Self:
|
| 104 |
+
return self.__class__(self.native, version=version)
|
| 105 |
+
|
| 106 |
+
def _with_native(self, df: Any) -> Self:
|
| 107 |
+
return self.__class__(df, version=self._version)
|
| 108 |
+
|
| 109 |
+
def _check_columns_exist(self, subset: Sequence[str]) -> ColumnNotFoundError | None:
|
| 110 |
+
return check_columns_exist(subset, available=self.columns)
|
| 111 |
+
|
| 112 |
+
def _iter_columns(self) -> Iterator[dx.Series]:
|
| 113 |
+
for _col, ser in self.native.items(): # noqa: PERF102
|
| 114 |
+
yield ser
|
| 115 |
+
|
| 116 |
+
def _evaluate_single_output_expr(self, obj: DaskExpr) -> dx.Series:
|
| 117 |
+
results = obj._call(self)
|
| 118 |
+
if len(results) != 1: # pragma: no cover
|
| 119 |
+
msg = "multi-output expressions not allowed in this context"
|
| 120 |
+
raise MultiOutputExpressionError(msg)
|
| 121 |
+
return results[0]
|
| 122 |
+
|
| 123 |
+
def with_columns(self, *exprs: DaskExpr) -> Self:
|
| 124 |
+
new_series = evaluate_exprs(self, *exprs)
|
| 125 |
+
return self._with_native(self.native.assign(**dict(new_series)))
|
| 126 |
+
|
| 127 |
+
def collect(
|
| 128 |
+
self, backend: _EagerAllowedImpl | None, **kwargs: Any
|
| 129 |
+
) -> CompliantDataFrameAny:
|
| 130 |
+
result = self.native.compute(**kwargs)
|
| 131 |
+
|
| 132 |
+
if backend is None or backend is Implementation.PANDAS:
|
| 133 |
+
from narwhals._pandas_like.dataframe import PandasLikeDataFrame
|
| 134 |
+
|
| 135 |
+
return PandasLikeDataFrame(
|
| 136 |
+
result,
|
| 137 |
+
implementation=Implementation.PANDAS,
|
| 138 |
+
validate_backend_version=True,
|
| 139 |
+
version=self._version,
|
| 140 |
+
validate_column_names=True,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
if backend is Implementation.POLARS:
|
| 144 |
+
import polars as pl # ignore-banned-import
|
| 145 |
+
|
| 146 |
+
from narwhals._polars.dataframe import PolarsDataFrame
|
| 147 |
+
|
| 148 |
+
return PolarsDataFrame(
|
| 149 |
+
pl.from_pandas(result),
|
| 150 |
+
validate_backend_version=True,
|
| 151 |
+
version=self._version,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
if backend is Implementation.PYARROW:
|
| 155 |
+
import pyarrow as pa # ignore-banned-import
|
| 156 |
+
|
| 157 |
+
from narwhals._arrow.dataframe import ArrowDataFrame
|
| 158 |
+
|
| 159 |
+
return ArrowDataFrame(
|
| 160 |
+
pa.Table.from_pandas(result),
|
| 161 |
+
validate_backend_version=True,
|
| 162 |
+
version=self._version,
|
| 163 |
+
validate_column_names=True,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
msg = f"Unsupported `backend` value: {backend}" # pragma: no cover
|
| 167 |
+
raise ValueError(msg) # pragma: no cover
|
| 168 |
+
|
| 169 |
+
@property
|
| 170 |
+
def columns(self) -> list[str]:
|
| 171 |
+
if self._cached_columns is None:
|
| 172 |
+
self._cached_columns = (
|
| 173 |
+
list(self.schema)
|
| 174 |
+
if self._cached_schema is not None
|
| 175 |
+
else self.native.columns.tolist()
|
| 176 |
+
)
|
| 177 |
+
return self._cached_columns
|
| 178 |
+
|
| 179 |
+
def filter(self, predicate: DaskExpr) -> Self:
|
| 180 |
+
# `[0]` is safe as the predicate's expression only returns a single column
|
| 181 |
+
mask = predicate(self)[0]
|
| 182 |
+
return self._with_native(self.native.loc[mask])
|
| 183 |
+
|
| 184 |
+
def simple_select(self, *column_names: str) -> Self:
|
| 185 |
+
df: Incomplete = self.native
|
| 186 |
+
native = select_columns_by_name(df, list(column_names), self._implementation)
|
| 187 |
+
return self._with_native(native)
|
| 188 |
+
|
| 189 |
+
def aggregate(self, *exprs: DaskExpr) -> Self:
|
| 190 |
+
new_series = evaluate_exprs(self, *exprs)
|
| 191 |
+
df = dd.concat([val.rename(name) for name, val in new_series], axis=1)
|
| 192 |
+
return self._with_native(df)
|
| 193 |
+
|
| 194 |
+
def select(self, *exprs: DaskExpr) -> Self:
|
| 195 |
+
new_series = evaluate_exprs(self, *exprs)
|
| 196 |
+
df: Incomplete = self.native
|
| 197 |
+
df = select_columns_by_name(
|
| 198 |
+
df.assign(**dict(new_series)),
|
| 199 |
+
[s[0] for s in new_series],
|
| 200 |
+
self._implementation,
|
| 201 |
+
)
|
| 202 |
+
return self._with_native(df)
|
| 203 |
+
|
| 204 |
+
def drop_nulls(self, subset: Sequence[str] | None) -> Self:
|
| 205 |
+
if subset is None:
|
| 206 |
+
return self._with_native(self.native.dropna())
|
| 207 |
+
plx = self.__narwhals_namespace__()
|
| 208 |
+
mask = ~plx.any_horizontal(plx.col(*subset).is_null(), ignore_nulls=True)
|
| 209 |
+
return self.filter(mask)
|
| 210 |
+
|
| 211 |
+
@property
|
| 212 |
+
def schema(self) -> dict[str, DType]:
|
| 213 |
+
if self._cached_schema is None:
|
| 214 |
+
native_dtypes = self.native.dtypes
|
| 215 |
+
self._cached_schema = {
|
| 216 |
+
col: native_to_narwhals_dtype(
|
| 217 |
+
native_dtypes[col], self._version, self._implementation
|
| 218 |
+
)
|
| 219 |
+
for col in self.native.columns
|
| 220 |
+
}
|
| 221 |
+
return self._cached_schema
|
| 222 |
+
|
| 223 |
+
def collect_schema(self) -> dict[str, DType]:
|
| 224 |
+
return self.schema
|
| 225 |
+
|
| 226 |
+
def drop(self, columns: Sequence[str], *, strict: bool) -> Self:
|
| 227 |
+
to_drop = parse_columns_to_drop(self, columns, strict=strict)
|
| 228 |
+
|
| 229 |
+
return self._with_native(self.native.drop(columns=to_drop))
|
| 230 |
+
|
| 231 |
+
def with_row_index(self, name: str, order_by: Sequence[str] | None) -> Self:
|
| 232 |
+
# Implementation is based on the following StackOverflow reply:
|
| 233 |
+
# https://stackoverflow.com/questions/60831518/in-dask-how-does-one-add-a-range-of-integersauto-increment-to-a-new-column/60852409#60852409
|
| 234 |
+
if order_by is None:
|
| 235 |
+
# Keep for backcompat, Narwhals used to allow no `order_by` in Dask.
|
| 236 |
+
return self._with_native(add_row_index(self.native, name))
|
| 237 |
+
plx = self.__narwhals_namespace__()
|
| 238 |
+
columns = self.columns
|
| 239 |
+
const_expr = plx.lit(1, dtype=None).alias(name).broadcast()
|
| 240 |
+
row_index_expr = (
|
| 241 |
+
plx.col(name).cum_sum(reverse=False).over(partition_by=[], order_by=order_by)
|
| 242 |
+
- plx.lit(1, dtype=None).broadcast()
|
| 243 |
+
)
|
| 244 |
+
return self.with_columns(const_expr).select(row_index_expr, plx.col(*columns))
|
| 245 |
+
|
| 246 |
+
def rename(self, mapping: Mapping[str, str]) -> Self:
|
| 247 |
+
return self._with_native(self.native.rename(columns=mapping))
|
| 248 |
+
|
| 249 |
+
def cast(self, dtypes: Mapping[str, IntoDType]) -> Self:
|
| 250 |
+
native_dtypes = {
|
| 251 |
+
name: narwhals_to_native_dtype(dtype, self._version)
|
| 252 |
+
for name, dtype in dtypes.items()
|
| 253 |
+
}
|
| 254 |
+
return self._with_native(self.native.astype(native_dtypes))
|
| 255 |
+
|
| 256 |
+
def head(self, n: int) -> Self:
|
| 257 |
+
return self._with_native(self.native.head(n=n, compute=False, npartitions=-1))
|
| 258 |
+
|
| 259 |
+
def unique(
|
| 260 |
+
self,
|
| 261 |
+
subset: Sequence[str] | None,
|
| 262 |
+
*,
|
| 263 |
+
keep: UniqueKeepStrategy,
|
| 264 |
+
order_by: Sequence[str] | None,
|
| 265 |
+
) -> Self:
|
| 266 |
+
if subset and (error := self._check_columns_exist(subset)):
|
| 267 |
+
raise error
|
| 268 |
+
if keep == "none":
|
| 269 |
+
subset = subset or self.columns
|
| 270 |
+
token = generate_temporary_column_name(
|
| 271 |
+
n_bytes=8, columns=subset, prefix="count_"
|
| 272 |
+
)
|
| 273 |
+
ser = self.native.groupby(subset).size().rename(token)
|
| 274 |
+
ser = ser[ser == 1]
|
| 275 |
+
unique = ser.reset_index().drop(columns=token)
|
| 276 |
+
result = self.native.merge(unique, on=subset, how="inner")
|
| 277 |
+
else:
|
| 278 |
+
mapped_keep = {"any": "first"}.get(keep, keep)
|
| 279 |
+
if order_by:
|
| 280 |
+
native = self.sort(*order_by, descending=False, nulls_last=False).native
|
| 281 |
+
else:
|
| 282 |
+
native = self.native
|
| 283 |
+
result = native.drop_duplicates(subset=subset, keep=mapped_keep)
|
| 284 |
+
return self._with_native(result)
|
| 285 |
+
|
| 286 |
+
def sort(self, *by: str, descending: bool | Sequence[bool], nulls_last: bool) -> Self:
|
| 287 |
+
if isinstance(descending, bool):
|
| 288 |
+
ascending: bool | list[bool] = not descending
|
| 289 |
+
else:
|
| 290 |
+
ascending = [not d for d in descending]
|
| 291 |
+
position = "last" if nulls_last else "first"
|
| 292 |
+
return self._with_native(
|
| 293 |
+
self.native.sort_values(list(by), ascending=ascending, na_position=position)
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
def top_k(self, k: int, *, by: Iterable[str], reverse: bool | Sequence[bool]) -> Self:
|
| 297 |
+
df = self.native
|
| 298 |
+
schema = self.schema
|
| 299 |
+
by = list(by)
|
| 300 |
+
if isinstance(reverse, bool) and all(schema[x].is_numeric() for x in by):
|
| 301 |
+
if reverse:
|
| 302 |
+
return self._with_native(df.nsmallest(k, by))
|
| 303 |
+
return self._with_native(df.nlargest(k, by))
|
| 304 |
+
if isinstance(reverse, bool):
|
| 305 |
+
reverse = [reverse] * len(by)
|
| 306 |
+
return self._with_native(
|
| 307 |
+
df.sort_values(by, ascending=list(reverse)).head(
|
| 308 |
+
n=k, compute=False, npartitions=-1
|
| 309 |
+
)
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
def _join_inner(
|
| 313 |
+
self, other: Self, *, left_on: Sequence[str], right_on: Sequence[str], suffix: str
|
| 314 |
+
) -> dd.DataFrame:
|
| 315 |
+
return self.native.dropna(subset=left_on, how="any").merge(
|
| 316 |
+
other.native,
|
| 317 |
+
left_on=left_on,
|
| 318 |
+
right_on=right_on,
|
| 319 |
+
how="inner",
|
| 320 |
+
suffixes=("", suffix),
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
def _join_left(
|
| 324 |
+
self, other: Self, *, left_on: Sequence[str], right_on: Sequence[str], suffix: str
|
| 325 |
+
) -> dd.DataFrame:
|
| 326 |
+
result_native = self.native.merge(
|
| 327 |
+
other.native.dropna(subset=right_on, how="any"),
|
| 328 |
+
how="left",
|
| 329 |
+
left_on=left_on,
|
| 330 |
+
right_on=right_on,
|
| 331 |
+
suffixes=("", suffix),
|
| 332 |
+
)
|
| 333 |
+
extra = [
|
| 334 |
+
right_key if right_key not in self.columns else f"{right_key}{suffix}"
|
| 335 |
+
for left_key, right_key in zip(left_on, right_on, strict=True)
|
| 336 |
+
if right_key != left_key
|
| 337 |
+
]
|
| 338 |
+
return result_native.drop(columns=extra)
|
| 339 |
+
|
| 340 |
+
def _join_full(
|
| 341 |
+
self, other: Self, *, left_on: Sequence[str], right_on: Sequence[str], suffix: str
|
| 342 |
+
) -> dd.DataFrame:
|
| 343 |
+
# dask does not retain keys post-join
|
| 344 |
+
# we must append the suffix to each key before-hand
|
| 345 |
+
self_native = self.native
|
| 346 |
+
right_on_mapper = _remap_full_join_keys(left_on, right_on, suffix)
|
| 347 |
+
other_native = other.native.rename(columns=right_on_mapper)
|
| 348 |
+
check_column_names_are_unique(other_native.columns)
|
| 349 |
+
right_suffixed = list(right_on_mapper.values())
|
| 350 |
+
|
| 351 |
+
left_null_mask = self_native[list(left_on)].isna().any(axis=1)
|
| 352 |
+
right_null_mask = other_native[right_suffixed].isna().any(axis=1)
|
| 353 |
+
|
| 354 |
+
# We need to add suffix to `other` columns overlapping in `self` if not in keys
|
| 355 |
+
to_rename = set(other.columns).intersection(self.columns).difference(right_on)
|
| 356 |
+
right_null_rows = other_native[right_null_mask].rename(
|
| 357 |
+
columns={col: f"{col}{suffix}" for col in to_rename}
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
join_result = self_native[~left_null_mask].merge(
|
| 361 |
+
other_native[~right_null_mask],
|
| 362 |
+
left_on=left_on,
|
| 363 |
+
right_on=right_suffixed,
|
| 364 |
+
how="outer",
|
| 365 |
+
suffixes=("", suffix),
|
| 366 |
+
)
|
| 367 |
+
return dd.concat(
|
| 368 |
+
[join_result, self_native[left_null_mask], right_null_rows],
|
| 369 |
+
axis=0,
|
| 370 |
+
join="outer",
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
def _join_cross(self, other: Self, *, suffix: str) -> dd.DataFrame:
|
| 374 |
+
key_token = generate_temporary_column_name(
|
| 375 |
+
n_bytes=8, columns=(*self.columns, *other.columns), prefix="cross_join_key_"
|
| 376 |
+
)
|
| 377 |
+
return (
|
| 378 |
+
self.native.assign(**{key_token: 0})
|
| 379 |
+
.merge(
|
| 380 |
+
other.native.assign(**{key_token: 0}),
|
| 381 |
+
how="inner",
|
| 382 |
+
left_on=key_token,
|
| 383 |
+
right_on=key_token,
|
| 384 |
+
suffixes=("", suffix),
|
| 385 |
+
)
|
| 386 |
+
.drop(columns=key_token)
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
def _join_semi(
|
| 390 |
+
self, other: Self, *, left_on: Sequence[str], right_on: Sequence[str]
|
| 391 |
+
) -> dd.DataFrame:
|
| 392 |
+
other_native = self._join_filter_rename(
|
| 393 |
+
other=other,
|
| 394 |
+
columns_to_select=list(right_on),
|
| 395 |
+
columns_mapping=dict(zip(right_on, left_on, strict=False)),
|
| 396 |
+
)
|
| 397 |
+
return self.native.dropna(subset=left_on, how="any").merge(
|
| 398 |
+
other_native, how="inner", left_on=left_on, right_on=left_on
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
def _join_anti(
|
| 402 |
+
self, other: Self, *, left_on: Sequence[str], right_on: Sequence[str]
|
| 403 |
+
) -> dd.DataFrame:
|
| 404 |
+
indicator_token = generate_temporary_column_name(
|
| 405 |
+
n_bytes=8, columns=(*self.columns, *other.columns), prefix="join_indicator_"
|
| 406 |
+
)
|
| 407 |
+
other_native = self._join_filter_rename(
|
| 408 |
+
other=other,
|
| 409 |
+
columns_to_select=list(right_on),
|
| 410 |
+
columns_mapping=dict(zip(right_on, left_on, strict=False)),
|
| 411 |
+
)
|
| 412 |
+
df = self.native.merge(
|
| 413 |
+
other_native.dropna(subset=left_on, how="any"),
|
| 414 |
+
how="left",
|
| 415 |
+
indicator=indicator_token, # pyright: ignore[reportArgumentType]
|
| 416 |
+
left_on=left_on,
|
| 417 |
+
right_on=left_on,
|
| 418 |
+
)
|
| 419 |
+
return df[df[indicator_token] == "left_only"].drop(columns=[indicator_token])
|
| 420 |
+
|
| 421 |
+
def _join_filter_rename(
|
| 422 |
+
self, other: Self, columns_to_select: list[str], columns_mapping: dict[str, str]
|
| 423 |
+
) -> dd.DataFrame:
|
| 424 |
+
"""Helper function to avoid creating extra columns and row duplication.
|
| 425 |
+
|
| 426 |
+
Used in `"anti"` and `"semi`" join's.
|
| 427 |
+
|
| 428 |
+
Notice that a native object is returned.
|
| 429 |
+
"""
|
| 430 |
+
other_native: Incomplete = other.native
|
| 431 |
+
# rename to avoid creating extra columns in join
|
| 432 |
+
return (
|
| 433 |
+
select_columns_by_name(other_native, columns_to_select, self._implementation)
|
| 434 |
+
.rename(columns=columns_mapping)
|
| 435 |
+
.drop_duplicates()
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
def join(
|
| 439 |
+
self,
|
| 440 |
+
other: Self,
|
| 441 |
+
*,
|
| 442 |
+
how: JoinStrategy,
|
| 443 |
+
left_on: Sequence[str] | None,
|
| 444 |
+
right_on: Sequence[str] | None,
|
| 445 |
+
suffix: str,
|
| 446 |
+
) -> Self:
|
| 447 |
+
if how == "cross":
|
| 448 |
+
result = self._join_cross(other=other, suffix=suffix)
|
| 449 |
+
|
| 450 |
+
elif left_on is None or right_on is None: # pragma: no cover
|
| 451 |
+
raise ValueError(left_on, right_on)
|
| 452 |
+
|
| 453 |
+
elif how == "inner":
|
| 454 |
+
result = self._join_inner(
|
| 455 |
+
other=other, left_on=left_on, right_on=right_on, suffix=suffix
|
| 456 |
+
)
|
| 457 |
+
elif how == "anti":
|
| 458 |
+
result = self._join_anti(other=other, left_on=left_on, right_on=right_on)
|
| 459 |
+
elif how == "semi":
|
| 460 |
+
result = self._join_semi(other=other, left_on=left_on, right_on=right_on)
|
| 461 |
+
elif how == "left":
|
| 462 |
+
result = self._join_left(
|
| 463 |
+
other=other, left_on=left_on, right_on=right_on, suffix=suffix
|
| 464 |
+
)
|
| 465 |
+
elif how == "full":
|
| 466 |
+
result = self._join_full(
|
| 467 |
+
other=other, left_on=left_on, right_on=right_on, suffix=suffix
|
| 468 |
+
)
|
| 469 |
+
else:
|
| 470 |
+
assert_never(how)
|
| 471 |
+
return self._with_native(result)
|
| 472 |
+
|
| 473 |
+
def join_asof(
|
| 474 |
+
self,
|
| 475 |
+
other: Self,
|
| 476 |
+
*,
|
| 477 |
+
left_on: str,
|
| 478 |
+
right_on: str,
|
| 479 |
+
by_left: Sequence[str] | None,
|
| 480 |
+
by_right: Sequence[str] | None,
|
| 481 |
+
strategy: AsofJoinStrategy,
|
| 482 |
+
suffix: str,
|
| 483 |
+
) -> Self:
|
| 484 |
+
plx = self.__native_namespace__()
|
| 485 |
+
return self._with_native(
|
| 486 |
+
plx.merge_asof(
|
| 487 |
+
self.native,
|
| 488 |
+
other.native,
|
| 489 |
+
left_on=left_on,
|
| 490 |
+
right_on=right_on,
|
| 491 |
+
left_by=by_left,
|
| 492 |
+
right_by=by_right,
|
| 493 |
+
direction=strategy,
|
| 494 |
+
suffixes=("", suffix),
|
| 495 |
+
)
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
def group_by(
|
| 499 |
+
self, keys: Sequence[str] | Sequence[DaskExpr], *, drop_null_keys: bool
|
| 500 |
+
) -> DaskLazyGroupBy:
|
| 501 |
+
from narwhals._dask.group_by import DaskLazyGroupBy
|
| 502 |
+
|
| 503 |
+
return DaskLazyGroupBy(self, keys, drop_null_keys=drop_null_keys)
|
| 504 |
+
|
| 505 |
+
def tail(self, n: int) -> Self: # pragma: no cover
|
| 506 |
+
native_frame = self.native
|
| 507 |
+
n_partitions = native_frame.npartitions
|
| 508 |
+
|
| 509 |
+
if n_partitions == 1:
|
| 510 |
+
return self._with_native(self.native.tail(n=n, compute=False))
|
| 511 |
+
msg = (
|
| 512 |
+
"`LazyFrame.tail` is not supported for Dask backend with multiple partitions."
|
| 513 |
+
)
|
| 514 |
+
raise NotImplementedError(msg)
|
| 515 |
+
|
| 516 |
+
def gather_every(self, n: int, offset: int) -> Self:
|
| 517 |
+
row_index_token = generate_temporary_column_name(
|
| 518 |
+
n_bytes=8, columns=self.columns, prefix="row_index_"
|
| 519 |
+
)
|
| 520 |
+
plx = self.__narwhals_namespace__()
|
| 521 |
+
offset_expr = plx.lit(offset, dtype=None).broadcast()
|
| 522 |
+
n_expr = plx.lit(n, dtype=None).broadcast()
|
| 523 |
+
zero_expr = plx.lit(0, dtype=None).broadcast()
|
| 524 |
+
return (
|
| 525 |
+
self.with_row_index(row_index_token, order_by=None)
|
| 526 |
+
.filter(
|
| 527 |
+
(plx.col(row_index_token) >= offset_expr)
|
| 528 |
+
& ((plx.col(row_index_token) - offset_expr) % n_expr == zero_expr)
|
| 529 |
+
)
|
| 530 |
+
.drop([row_index_token], strict=False)
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
def unpivot(
|
| 534 |
+
self,
|
| 535 |
+
on: Sequence[str] | None,
|
| 536 |
+
index: Sequence[str] | None,
|
| 537 |
+
variable_name: str,
|
| 538 |
+
value_name: str,
|
| 539 |
+
) -> Self:
|
| 540 |
+
return self._with_native(
|
| 541 |
+
self.native.melt(
|
| 542 |
+
id_vars=index,
|
| 543 |
+
value_vars=on,
|
| 544 |
+
var_name=variable_name,
|
| 545 |
+
value_name=value_name,
|
| 546 |
+
)
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
def sink_parquet(self, file: str | Path | BytesIO) -> None:
|
| 550 |
+
self.native.to_parquet(file)
|
| 551 |
+
|
| 552 |
+
explode = not_implemented()
|
shared/package-files/12/1232056ea45daf664905a2355efa16469b679d6d4b16b961c9dc430ee2108d22/Mawson
ADDED
|
Binary file (185 Bytes). View file
|
|
|
shared/package-files/12/123597bfe27c0b92444f802521b25175cb7270befe772259727a168279423dcf/ndarraytypes.h
ADDED
|
@@ -0,0 +1,1945 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#ifndef NUMPY_CORE_INCLUDE_NUMPY_NDARRAYTYPES_H_
|
| 2 |
+
#define NUMPY_CORE_INCLUDE_NUMPY_NDARRAYTYPES_H_
|
| 3 |
+
|
| 4 |
+
#include "npy_common.h"
|
| 5 |
+
#include "npy_endian.h"
|
| 6 |
+
#include "npy_cpu.h"
|
| 7 |
+
#include "utils.h"
|
| 8 |
+
|
| 9 |
+
#define NPY_NO_EXPORT NPY_VISIBILITY_HIDDEN
|
| 10 |
+
|
| 11 |
+
/* Only use thread if configured in config and python supports it */
|
| 12 |
+
#if defined WITH_THREAD && !NPY_NO_SMP
|
| 13 |
+
#define NPY_ALLOW_THREADS 1
|
| 14 |
+
#else
|
| 15 |
+
#define NPY_ALLOW_THREADS 0
|
| 16 |
+
#endif
|
| 17 |
+
|
| 18 |
+
#ifndef __has_extension
|
| 19 |
+
#define __has_extension(x) 0
|
| 20 |
+
#endif
|
| 21 |
+
|
| 22 |
+
#if !defined(_NPY_NO_DEPRECATIONS) && \
|
| 23 |
+
((defined(__GNUC__)&& __GNUC__ >= 6) || \
|
| 24 |
+
__has_extension(attribute_deprecated_with_message))
|
| 25 |
+
#define NPY_ATTR_DEPRECATE(text) __attribute__ ((deprecated (text)))
|
| 26 |
+
#else
|
| 27 |
+
#define NPY_ATTR_DEPRECATE(text)
|
| 28 |
+
#endif
|
| 29 |
+
|
| 30 |
+
/*
|
| 31 |
+
* There are several places in the code where an array of dimensions
|
| 32 |
+
* is allocated statically. This is the size of that static
|
| 33 |
+
* allocation.
|
| 34 |
+
*
|
| 35 |
+
* The array creation itself could have arbitrary dimensions but all
|
| 36 |
+
* the places where static allocation is used would need to be changed
|
| 37 |
+
* to dynamic (including inside of several structures)
|
| 38 |
+
*/
|
| 39 |
+
|
| 40 |
+
#define NPY_MAXDIMS 32
|
| 41 |
+
#define NPY_MAXARGS 32
|
| 42 |
+
|
| 43 |
+
/* Used for Converter Functions "O&" code in ParseTuple */
|
| 44 |
+
#define NPY_FAIL 0
|
| 45 |
+
#define NPY_SUCCEED 1
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
enum NPY_TYPES { NPY_BOOL=0,
|
| 49 |
+
NPY_BYTE, NPY_UBYTE,
|
| 50 |
+
NPY_SHORT, NPY_USHORT,
|
| 51 |
+
NPY_INT, NPY_UINT,
|
| 52 |
+
NPY_LONG, NPY_ULONG,
|
| 53 |
+
NPY_LONGLONG, NPY_ULONGLONG,
|
| 54 |
+
NPY_FLOAT, NPY_DOUBLE, NPY_LONGDOUBLE,
|
| 55 |
+
NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE,
|
| 56 |
+
NPY_OBJECT=17,
|
| 57 |
+
NPY_STRING, NPY_UNICODE,
|
| 58 |
+
NPY_VOID,
|
| 59 |
+
/*
|
| 60 |
+
* New 1.6 types appended, may be integrated
|
| 61 |
+
* into the above in 2.0.
|
| 62 |
+
*/
|
| 63 |
+
NPY_DATETIME, NPY_TIMEDELTA, NPY_HALF,
|
| 64 |
+
|
| 65 |
+
NPY_NTYPES,
|
| 66 |
+
NPY_NOTYPE,
|
| 67 |
+
NPY_CHAR NPY_ATTR_DEPRECATE("Use NPY_STRING"),
|
| 68 |
+
NPY_USERDEF=256, /* leave room for characters */
|
| 69 |
+
|
| 70 |
+
/* The number of types not including the new 1.6 types */
|
| 71 |
+
NPY_NTYPES_ABI_COMPATIBLE=21
|
| 72 |
+
};
|
| 73 |
+
#if defined(_MSC_VER) && !defined(__clang__)
|
| 74 |
+
#pragma deprecated(NPY_CHAR)
|
| 75 |
+
#endif
|
| 76 |
+
|
| 77 |
+
/* basetype array priority */
|
| 78 |
+
#define NPY_PRIORITY 0.0
|
| 79 |
+
|
| 80 |
+
/* default subtype priority */
|
| 81 |
+
#define NPY_SUBTYPE_PRIORITY 1.0
|
| 82 |
+
|
| 83 |
+
/* default scalar priority */
|
| 84 |
+
#define NPY_SCALAR_PRIORITY -1000000.0
|
| 85 |
+
|
| 86 |
+
/* How many floating point types are there (excluding half) */
|
| 87 |
+
#define NPY_NUM_FLOATTYPE 3
|
| 88 |
+
|
| 89 |
+
/*
|
| 90 |
+
* These characters correspond to the array type and the struct
|
| 91 |
+
* module
|
| 92 |
+
*/
|
| 93 |
+
|
| 94 |
+
enum NPY_TYPECHAR {
|
| 95 |
+
NPY_BOOLLTR = '?',
|
| 96 |
+
NPY_BYTELTR = 'b',
|
| 97 |
+
NPY_UBYTELTR = 'B',
|
| 98 |
+
NPY_SHORTLTR = 'h',
|
| 99 |
+
NPY_USHORTLTR = 'H',
|
| 100 |
+
NPY_INTLTR = 'i',
|
| 101 |
+
NPY_UINTLTR = 'I',
|
| 102 |
+
NPY_LONGLTR = 'l',
|
| 103 |
+
NPY_ULONGLTR = 'L',
|
| 104 |
+
NPY_LONGLONGLTR = 'q',
|
| 105 |
+
NPY_ULONGLONGLTR = 'Q',
|
| 106 |
+
NPY_HALFLTR = 'e',
|
| 107 |
+
NPY_FLOATLTR = 'f',
|
| 108 |
+
NPY_DOUBLELTR = 'd',
|
| 109 |
+
NPY_LONGDOUBLELTR = 'g',
|
| 110 |
+
NPY_CFLOATLTR = 'F',
|
| 111 |
+
NPY_CDOUBLELTR = 'D',
|
| 112 |
+
NPY_CLONGDOUBLELTR = 'G',
|
| 113 |
+
NPY_OBJECTLTR = 'O',
|
| 114 |
+
NPY_STRINGLTR = 'S',
|
| 115 |
+
NPY_STRINGLTR2 = 'a',
|
| 116 |
+
NPY_UNICODELTR = 'U',
|
| 117 |
+
NPY_VOIDLTR = 'V',
|
| 118 |
+
NPY_DATETIMELTR = 'M',
|
| 119 |
+
NPY_TIMEDELTALTR = 'm',
|
| 120 |
+
NPY_CHARLTR = 'c',
|
| 121 |
+
|
| 122 |
+
/*
|
| 123 |
+
* No Descriptor, just a define -- this let's
|
| 124 |
+
* Python users specify an array of integers
|
| 125 |
+
* large enough to hold a pointer on the
|
| 126 |
+
* platform
|
| 127 |
+
*/
|
| 128 |
+
NPY_INTPLTR = 'p',
|
| 129 |
+
NPY_UINTPLTR = 'P',
|
| 130 |
+
|
| 131 |
+
/*
|
| 132 |
+
* These are for dtype 'kinds', not dtype 'typecodes'
|
| 133 |
+
* as the above are for.
|
| 134 |
+
*/
|
| 135 |
+
NPY_GENBOOLLTR ='b',
|
| 136 |
+
NPY_SIGNEDLTR = 'i',
|
| 137 |
+
NPY_UNSIGNEDLTR = 'u',
|
| 138 |
+
NPY_FLOATINGLTR = 'f',
|
| 139 |
+
NPY_COMPLEXLTR = 'c'
|
| 140 |
+
};
|
| 141 |
+
|
| 142 |
+
/*
|
| 143 |
+
* Changing this may break Numpy API compatibility
|
| 144 |
+
* due to changing offsets in PyArray_ArrFuncs, so be
|
| 145 |
+
* careful. Here we have reused the mergesort slot for
|
| 146 |
+
* any kind of stable sort, the actual implementation will
|
| 147 |
+
* depend on the data type.
|
| 148 |
+
*/
|
| 149 |
+
typedef enum {
|
| 150 |
+
NPY_QUICKSORT=0,
|
| 151 |
+
NPY_HEAPSORT=1,
|
| 152 |
+
NPY_MERGESORT=2,
|
| 153 |
+
NPY_STABLESORT=2,
|
| 154 |
+
} NPY_SORTKIND;
|
| 155 |
+
#define NPY_NSORTS (NPY_STABLESORT + 1)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
typedef enum {
|
| 159 |
+
NPY_INTROSELECT=0
|
| 160 |
+
} NPY_SELECTKIND;
|
| 161 |
+
#define NPY_NSELECTS (NPY_INTROSELECT + 1)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
typedef enum {
|
| 165 |
+
NPY_SEARCHLEFT=0,
|
| 166 |
+
NPY_SEARCHRIGHT=1
|
| 167 |
+
} NPY_SEARCHSIDE;
|
| 168 |
+
#define NPY_NSEARCHSIDES (NPY_SEARCHRIGHT + 1)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
typedef enum {
|
| 172 |
+
NPY_NOSCALAR=-1,
|
| 173 |
+
NPY_BOOL_SCALAR,
|
| 174 |
+
NPY_INTPOS_SCALAR,
|
| 175 |
+
NPY_INTNEG_SCALAR,
|
| 176 |
+
NPY_FLOAT_SCALAR,
|
| 177 |
+
NPY_COMPLEX_SCALAR,
|
| 178 |
+
NPY_OBJECT_SCALAR
|
| 179 |
+
} NPY_SCALARKIND;
|
| 180 |
+
#define NPY_NSCALARKINDS (NPY_OBJECT_SCALAR + 1)
|
| 181 |
+
|
| 182 |
+
/* For specifying array memory layout or iteration order */
|
| 183 |
+
typedef enum {
|
| 184 |
+
/* Fortran order if inputs are all Fortran, C otherwise */
|
| 185 |
+
NPY_ANYORDER=-1,
|
| 186 |
+
/* C order */
|
| 187 |
+
NPY_CORDER=0,
|
| 188 |
+
/* Fortran order */
|
| 189 |
+
NPY_FORTRANORDER=1,
|
| 190 |
+
/* An order as close to the inputs as possible */
|
| 191 |
+
NPY_KEEPORDER=2
|
| 192 |
+
} NPY_ORDER;
|
| 193 |
+
|
| 194 |
+
/* For specifying allowed casting in operations which support it */
|
| 195 |
+
typedef enum {
|
| 196 |
+
_NPY_ERROR_OCCURRED_IN_CAST = -1,
|
| 197 |
+
/* Only allow identical types */
|
| 198 |
+
NPY_NO_CASTING=0,
|
| 199 |
+
/* Allow identical and byte swapped types */
|
| 200 |
+
NPY_EQUIV_CASTING=1,
|
| 201 |
+
/* Only allow safe casts */
|
| 202 |
+
NPY_SAFE_CASTING=2,
|
| 203 |
+
/* Allow safe casts or casts within the same kind */
|
| 204 |
+
NPY_SAME_KIND_CASTING=3,
|
| 205 |
+
/* Allow any casts */
|
| 206 |
+
NPY_UNSAFE_CASTING=4,
|
| 207 |
+
} NPY_CASTING;
|
| 208 |
+
|
| 209 |
+
typedef enum {
|
| 210 |
+
NPY_CLIP=0,
|
| 211 |
+
NPY_WRAP=1,
|
| 212 |
+
NPY_RAISE=2
|
| 213 |
+
} NPY_CLIPMODE;
|
| 214 |
+
|
| 215 |
+
typedef enum {
|
| 216 |
+
NPY_VALID=0,
|
| 217 |
+
NPY_SAME=1,
|
| 218 |
+
NPY_FULL=2
|
| 219 |
+
} NPY_CORRELATEMODE;
|
| 220 |
+
|
| 221 |
+
/* The special not-a-time (NaT) value */
|
| 222 |
+
#define NPY_DATETIME_NAT NPY_MIN_INT64
|
| 223 |
+
|
| 224 |
+
/*
|
| 225 |
+
* Upper bound on the length of a DATETIME ISO 8601 string
|
| 226 |
+
* YEAR: 21 (64-bit year)
|
| 227 |
+
* MONTH: 3
|
| 228 |
+
* DAY: 3
|
| 229 |
+
* HOURS: 3
|
| 230 |
+
* MINUTES: 3
|
| 231 |
+
* SECONDS: 3
|
| 232 |
+
* ATTOSECONDS: 1 + 3*6
|
| 233 |
+
* TIMEZONE: 5
|
| 234 |
+
* NULL TERMINATOR: 1
|
| 235 |
+
*/
|
| 236 |
+
#define NPY_DATETIME_MAX_ISO8601_STRLEN (21 + 3*5 + 1 + 3*6 + 6 + 1)
|
| 237 |
+
|
| 238 |
+
/* The FR in the unit names stands for frequency */
|
| 239 |
+
typedef enum {
|
| 240 |
+
/* Force signed enum type, must be -1 for code compatibility */
|
| 241 |
+
NPY_FR_ERROR = -1, /* error or undetermined */
|
| 242 |
+
|
| 243 |
+
/* Start of valid units */
|
| 244 |
+
NPY_FR_Y = 0, /* Years */
|
| 245 |
+
NPY_FR_M = 1, /* Months */
|
| 246 |
+
NPY_FR_W = 2, /* Weeks */
|
| 247 |
+
/* Gap where 1.6 NPY_FR_B (value 3) was */
|
| 248 |
+
NPY_FR_D = 4, /* Days */
|
| 249 |
+
NPY_FR_h = 5, /* hours */
|
| 250 |
+
NPY_FR_m = 6, /* minutes */
|
| 251 |
+
NPY_FR_s = 7, /* seconds */
|
| 252 |
+
NPY_FR_ms = 8, /* milliseconds */
|
| 253 |
+
NPY_FR_us = 9, /* microseconds */
|
| 254 |
+
NPY_FR_ns = 10, /* nanoseconds */
|
| 255 |
+
NPY_FR_ps = 11, /* picoseconds */
|
| 256 |
+
NPY_FR_fs = 12, /* femtoseconds */
|
| 257 |
+
NPY_FR_as = 13, /* attoseconds */
|
| 258 |
+
NPY_FR_GENERIC = 14 /* unbound units, can convert to anything */
|
| 259 |
+
} NPY_DATETIMEUNIT;
|
| 260 |
+
|
| 261 |
+
/*
|
| 262 |
+
* NOTE: With the NPY_FR_B gap for 1.6 ABI compatibility, NPY_DATETIME_NUMUNITS
|
| 263 |
+
* is technically one more than the actual number of units.
|
| 264 |
+
*/
|
| 265 |
+
#define NPY_DATETIME_NUMUNITS (NPY_FR_GENERIC + 1)
|
| 266 |
+
#define NPY_DATETIME_DEFAULTUNIT NPY_FR_GENERIC
|
| 267 |
+
|
| 268 |
+
/*
|
| 269 |
+
* Business day conventions for mapping invalid business
|
| 270 |
+
* days to valid business days.
|
| 271 |
+
*/
|
| 272 |
+
typedef enum {
|
| 273 |
+
/* Go forward in time to the following business day. */
|
| 274 |
+
NPY_BUSDAY_FORWARD,
|
| 275 |
+
NPY_BUSDAY_FOLLOWING = NPY_BUSDAY_FORWARD,
|
| 276 |
+
/* Go backward in time to the preceding business day. */
|
| 277 |
+
NPY_BUSDAY_BACKWARD,
|
| 278 |
+
NPY_BUSDAY_PRECEDING = NPY_BUSDAY_BACKWARD,
|
| 279 |
+
/*
|
| 280 |
+
* Go forward in time to the following business day, unless it
|
| 281 |
+
* crosses a month boundary, in which case go backward
|
| 282 |
+
*/
|
| 283 |
+
NPY_BUSDAY_MODIFIEDFOLLOWING,
|
| 284 |
+
/*
|
| 285 |
+
* Go backward in time to the preceding business day, unless it
|
| 286 |
+
* crosses a month boundary, in which case go forward.
|
| 287 |
+
*/
|
| 288 |
+
NPY_BUSDAY_MODIFIEDPRECEDING,
|
| 289 |
+
/* Produce a NaT for non-business days. */
|
| 290 |
+
NPY_BUSDAY_NAT,
|
| 291 |
+
/* Raise an exception for non-business days. */
|
| 292 |
+
NPY_BUSDAY_RAISE
|
| 293 |
+
} NPY_BUSDAY_ROLL;
|
| 294 |
+
|
| 295 |
+
/************************************************************
|
| 296 |
+
* NumPy Auxiliary Data for inner loops, sort functions, etc.
|
| 297 |
+
************************************************************/
|
| 298 |
+
|
| 299 |
+
/*
|
| 300 |
+
* When creating an auxiliary data struct, this should always appear
|
| 301 |
+
* as the first member, like this:
|
| 302 |
+
*
|
| 303 |
+
* typedef struct {
|
| 304 |
+
* NpyAuxData base;
|
| 305 |
+
* double constant;
|
| 306 |
+
* } constant_multiplier_aux_data;
|
| 307 |
+
*/
|
| 308 |
+
typedef struct NpyAuxData_tag NpyAuxData;
|
| 309 |
+
|
| 310 |
+
/* Function pointers for freeing or cloning auxiliary data */
|
| 311 |
+
typedef void (NpyAuxData_FreeFunc) (NpyAuxData *);
|
| 312 |
+
typedef NpyAuxData *(NpyAuxData_CloneFunc) (NpyAuxData *);
|
| 313 |
+
|
| 314 |
+
struct NpyAuxData_tag {
|
| 315 |
+
NpyAuxData_FreeFunc *free;
|
| 316 |
+
NpyAuxData_CloneFunc *clone;
|
| 317 |
+
/* To allow for a bit of expansion without breaking the ABI */
|
| 318 |
+
void *reserved[2];
|
| 319 |
+
};
|
| 320 |
+
|
| 321 |
+
/* Macros to use for freeing and cloning auxiliary data */
|
| 322 |
+
#define NPY_AUXDATA_FREE(auxdata) \
|
| 323 |
+
do { \
|
| 324 |
+
if ((auxdata) != NULL) { \
|
| 325 |
+
(auxdata)->free(auxdata); \
|
| 326 |
+
} \
|
| 327 |
+
} while(0)
|
| 328 |
+
#define NPY_AUXDATA_CLONE(auxdata) \
|
| 329 |
+
((auxdata)->clone(auxdata))
|
| 330 |
+
|
| 331 |
+
#define NPY_ERR(str) fprintf(stderr, #str); fflush(stderr);
|
| 332 |
+
#define NPY_ERR2(str) fprintf(stderr, str); fflush(stderr);
|
| 333 |
+
|
| 334 |
+
/*
|
| 335 |
+
* Macros to define how array, and dimension/strides data is
|
| 336 |
+
* allocated. These should be made private
|
| 337 |
+
*/
|
| 338 |
+
|
| 339 |
+
#define NPY_USE_PYMEM 1
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
#if NPY_USE_PYMEM == 1
|
| 343 |
+
/* use the Raw versions which are safe to call with the GIL released */
|
| 344 |
+
#define PyArray_malloc PyMem_RawMalloc
|
| 345 |
+
#define PyArray_free PyMem_RawFree
|
| 346 |
+
#define PyArray_realloc PyMem_RawRealloc
|
| 347 |
+
#else
|
| 348 |
+
#define PyArray_malloc malloc
|
| 349 |
+
#define PyArray_free free
|
| 350 |
+
#define PyArray_realloc realloc
|
| 351 |
+
#endif
|
| 352 |
+
|
| 353 |
+
/* Dimensions and strides */
|
| 354 |
+
#define PyDimMem_NEW(size) \
|
| 355 |
+
((npy_intp *)PyArray_malloc(size*sizeof(npy_intp)))
|
| 356 |
+
|
| 357 |
+
#define PyDimMem_FREE(ptr) PyArray_free(ptr)
|
| 358 |
+
|
| 359 |
+
#define PyDimMem_RENEW(ptr,size) \
|
| 360 |
+
((npy_intp *)PyArray_realloc(ptr,size*sizeof(npy_intp)))
|
| 361 |
+
|
| 362 |
+
/* forward declaration */
|
| 363 |
+
struct _PyArray_Descr;
|
| 364 |
+
|
| 365 |
+
/* These must deal with unaligned and swapped data if necessary */
|
| 366 |
+
typedef PyObject * (PyArray_GetItemFunc) (void *, void *);
|
| 367 |
+
typedef int (PyArray_SetItemFunc)(PyObject *, void *, void *);
|
| 368 |
+
|
| 369 |
+
typedef void (PyArray_CopySwapNFunc)(void *, npy_intp, void *, npy_intp,
|
| 370 |
+
npy_intp, int, void *);
|
| 371 |
+
|
| 372 |
+
typedef void (PyArray_CopySwapFunc)(void *, void *, int, void *);
|
| 373 |
+
typedef npy_bool (PyArray_NonzeroFunc)(void *, void *);
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
/*
|
| 377 |
+
* These assume aligned and notswapped data -- a buffer will be used
|
| 378 |
+
* before or contiguous data will be obtained
|
| 379 |
+
*/
|
| 380 |
+
|
| 381 |
+
typedef int (PyArray_CompareFunc)(const void *, const void *, void *);
|
| 382 |
+
typedef int (PyArray_ArgFunc)(void*, npy_intp, npy_intp*, void *);
|
| 383 |
+
|
| 384 |
+
typedef void (PyArray_DotFunc)(void *, npy_intp, void *, npy_intp, void *,
|
| 385 |
+
npy_intp, void *);
|
| 386 |
+
|
| 387 |
+
typedef void (PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *,
|
| 388 |
+
void *);
|
| 389 |
+
|
| 390 |
+
/*
|
| 391 |
+
* XXX the ignore argument should be removed next time the API version
|
| 392 |
+
* is bumped. It used to be the separator.
|
| 393 |
+
*/
|
| 394 |
+
typedef int (PyArray_ScanFunc)(FILE *fp, void *dptr,
|
| 395 |
+
char *ignore, struct _PyArray_Descr *);
|
| 396 |
+
typedef int (PyArray_FromStrFunc)(char *s, void *dptr, char **endptr,
|
| 397 |
+
struct _PyArray_Descr *);
|
| 398 |
+
|
| 399 |
+
typedef int (PyArray_FillFunc)(void *, npy_intp, void *);
|
| 400 |
+
|
| 401 |
+
typedef int (PyArray_SortFunc)(void *, npy_intp, void *);
|
| 402 |
+
typedef int (PyArray_ArgSortFunc)(void *, npy_intp *, npy_intp, void *);
|
| 403 |
+
typedef int (PyArray_PartitionFunc)(void *, npy_intp, npy_intp,
|
| 404 |
+
npy_intp *, npy_intp *,
|
| 405 |
+
void *);
|
| 406 |
+
typedef int (PyArray_ArgPartitionFunc)(void *, npy_intp *, npy_intp, npy_intp,
|
| 407 |
+
npy_intp *, npy_intp *,
|
| 408 |
+
void *);
|
| 409 |
+
|
| 410 |
+
typedef int (PyArray_FillWithScalarFunc)(void *, npy_intp, void *, void *);
|
| 411 |
+
|
| 412 |
+
typedef int (PyArray_ScalarKindFunc)(void *);
|
| 413 |
+
|
| 414 |
+
typedef void (PyArray_FastClipFunc)(void *in, npy_intp n_in, void *min,
|
| 415 |
+
void *max, void *out);
|
| 416 |
+
typedef void (PyArray_FastPutmaskFunc)(void *in, void *mask, npy_intp n_in,
|
| 417 |
+
void *values, npy_intp nv);
|
| 418 |
+
typedef int (PyArray_FastTakeFunc)(void *dest, void *src, npy_intp *indarray,
|
| 419 |
+
npy_intp nindarray, npy_intp n_outer,
|
| 420 |
+
npy_intp m_middle, npy_intp nelem,
|
| 421 |
+
NPY_CLIPMODE clipmode);
|
| 422 |
+
|
| 423 |
+
typedef struct {
|
| 424 |
+
npy_intp *ptr;
|
| 425 |
+
int len;
|
| 426 |
+
} PyArray_Dims;
|
| 427 |
+
|
| 428 |
+
typedef struct {
|
| 429 |
+
/*
|
| 430 |
+
* Functions to cast to most other standard types
|
| 431 |
+
* Can have some NULL entries. The types
|
| 432 |
+
* DATETIME, TIMEDELTA, and HALF go into the castdict
|
| 433 |
+
* even though they are built-in.
|
| 434 |
+
*/
|
| 435 |
+
PyArray_VectorUnaryFunc *cast[NPY_NTYPES_ABI_COMPATIBLE];
|
| 436 |
+
|
| 437 |
+
/* The next four functions *cannot* be NULL */
|
| 438 |
+
|
| 439 |
+
/*
|
| 440 |
+
* Functions to get and set items with standard Python types
|
| 441 |
+
* -- not array scalars
|
| 442 |
+
*/
|
| 443 |
+
PyArray_GetItemFunc *getitem;
|
| 444 |
+
PyArray_SetItemFunc *setitem;
|
| 445 |
+
|
| 446 |
+
/*
|
| 447 |
+
* Copy and/or swap data. Memory areas may not overlap
|
| 448 |
+
* Use memmove first if they might
|
| 449 |
+
*/
|
| 450 |
+
PyArray_CopySwapNFunc *copyswapn;
|
| 451 |
+
PyArray_CopySwapFunc *copyswap;
|
| 452 |
+
|
| 453 |
+
/*
|
| 454 |
+
* Function to compare items
|
| 455 |
+
* Can be NULL
|
| 456 |
+
*/
|
| 457 |
+
PyArray_CompareFunc *compare;
|
| 458 |
+
|
| 459 |
+
/*
|
| 460 |
+
* Function to select largest
|
| 461 |
+
* Can be NULL
|
| 462 |
+
*/
|
| 463 |
+
PyArray_ArgFunc *argmax;
|
| 464 |
+
|
| 465 |
+
/*
|
| 466 |
+
* Function to compute dot product
|
| 467 |
+
* Can be NULL
|
| 468 |
+
*/
|
| 469 |
+
PyArray_DotFunc *dotfunc;
|
| 470 |
+
|
| 471 |
+
/*
|
| 472 |
+
* Function to scan an ASCII file and
|
| 473 |
+
* place a single value plus possible separator
|
| 474 |
+
* Can be NULL
|
| 475 |
+
*/
|
| 476 |
+
PyArray_ScanFunc *scanfunc;
|
| 477 |
+
|
| 478 |
+
/*
|
| 479 |
+
* Function to read a single value from a string
|
| 480 |
+
* and adjust the pointer; Can be NULL
|
| 481 |
+
*/
|
| 482 |
+
PyArray_FromStrFunc *fromstr;
|
| 483 |
+
|
| 484 |
+
/*
|
| 485 |
+
* Function to determine if data is zero or not
|
| 486 |
+
* If NULL a default version is
|
| 487 |
+
* used at Registration time.
|
| 488 |
+
*/
|
| 489 |
+
PyArray_NonzeroFunc *nonzero;
|
| 490 |
+
|
| 491 |
+
/*
|
| 492 |
+
* Used for arange. Should return 0 on success
|
| 493 |
+
* and -1 on failure.
|
| 494 |
+
* Can be NULL.
|
| 495 |
+
*/
|
| 496 |
+
PyArray_FillFunc *fill;
|
| 497 |
+
|
| 498 |
+
/*
|
| 499 |
+
* Function to fill arrays with scalar values
|
| 500 |
+
* Can be NULL
|
| 501 |
+
*/
|
| 502 |
+
PyArray_FillWithScalarFunc *fillwithscalar;
|
| 503 |
+
|
| 504 |
+
/*
|
| 505 |
+
* Sorting functions
|
| 506 |
+
* Can be NULL
|
| 507 |
+
*/
|
| 508 |
+
PyArray_SortFunc *sort[NPY_NSORTS];
|
| 509 |
+
PyArray_ArgSortFunc *argsort[NPY_NSORTS];
|
| 510 |
+
|
| 511 |
+
/*
|
| 512 |
+
* Dictionary of additional casting functions
|
| 513 |
+
* PyArray_VectorUnaryFuncs
|
| 514 |
+
* which can be populated to support casting
|
| 515 |
+
* to other registered types. Can be NULL
|
| 516 |
+
*/
|
| 517 |
+
PyObject *castdict;
|
| 518 |
+
|
| 519 |
+
/*
|
| 520 |
+
* Functions useful for generalizing
|
| 521 |
+
* the casting rules.
|
| 522 |
+
* Can be NULL;
|
| 523 |
+
*/
|
| 524 |
+
PyArray_ScalarKindFunc *scalarkind;
|
| 525 |
+
int **cancastscalarkindto;
|
| 526 |
+
int *cancastto;
|
| 527 |
+
|
| 528 |
+
PyArray_FastClipFunc *fastclip;
|
| 529 |
+
PyArray_FastPutmaskFunc *fastputmask;
|
| 530 |
+
PyArray_FastTakeFunc *fasttake;
|
| 531 |
+
|
| 532 |
+
/*
|
| 533 |
+
* Function to select smallest
|
| 534 |
+
* Can be NULL
|
| 535 |
+
*/
|
| 536 |
+
PyArray_ArgFunc *argmin;
|
| 537 |
+
|
| 538 |
+
} PyArray_ArrFuncs;
|
| 539 |
+
|
| 540 |
+
/* The item must be reference counted when it is inserted or extracted. */
|
| 541 |
+
#define NPY_ITEM_REFCOUNT 0x01
|
| 542 |
+
/* Same as needing REFCOUNT */
|
| 543 |
+
#define NPY_ITEM_HASOBJECT 0x01
|
| 544 |
+
/* Convert to list for pickling */
|
| 545 |
+
#define NPY_LIST_PICKLE 0x02
|
| 546 |
+
/* The item is a POINTER */
|
| 547 |
+
#define NPY_ITEM_IS_POINTER 0x04
|
| 548 |
+
/* memory needs to be initialized for this data-type */
|
| 549 |
+
#define NPY_NEEDS_INIT 0x08
|
| 550 |
+
/* operations need Python C-API so don't give-up thread. */
|
| 551 |
+
#define NPY_NEEDS_PYAPI 0x10
|
| 552 |
+
/* Use f.getitem when extracting elements of this data-type */
|
| 553 |
+
#define NPY_USE_GETITEM 0x20
|
| 554 |
+
/* Use f.setitem when setting creating 0-d array from this data-type.*/
|
| 555 |
+
#define NPY_USE_SETITEM 0x40
|
| 556 |
+
/* A sticky flag specifically for structured arrays */
|
| 557 |
+
#define NPY_ALIGNED_STRUCT 0x80
|
| 558 |
+
|
| 559 |
+
/*
|
| 560 |
+
*These are inherited for global data-type if any data-types in the
|
| 561 |
+
* field have them
|
| 562 |
+
*/
|
| 563 |
+
#define NPY_FROM_FIELDS (NPY_NEEDS_INIT | NPY_LIST_PICKLE | \
|
| 564 |
+
NPY_ITEM_REFCOUNT | NPY_NEEDS_PYAPI)
|
| 565 |
+
|
| 566 |
+
#define NPY_OBJECT_DTYPE_FLAGS (NPY_LIST_PICKLE | NPY_USE_GETITEM | \
|
| 567 |
+
NPY_ITEM_IS_POINTER | NPY_ITEM_REFCOUNT | \
|
| 568 |
+
NPY_NEEDS_INIT | NPY_NEEDS_PYAPI)
|
| 569 |
+
|
| 570 |
+
#define PyDataType_FLAGCHK(dtype, flag) \
|
| 571 |
+
(((dtype)->flags & (flag)) == (flag))
|
| 572 |
+
|
| 573 |
+
#define PyDataType_REFCHK(dtype) \
|
| 574 |
+
PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT)
|
| 575 |
+
|
| 576 |
+
typedef struct _PyArray_Descr {
|
| 577 |
+
PyObject_HEAD
|
| 578 |
+
/*
|
| 579 |
+
* the type object representing an
|
| 580 |
+
* instance of this type -- should not
|
| 581 |
+
* be two type_numbers with the same type
|
| 582 |
+
* object.
|
| 583 |
+
*/
|
| 584 |
+
PyTypeObject *typeobj;
|
| 585 |
+
/* kind for this type */
|
| 586 |
+
char kind;
|
| 587 |
+
/* unique-character representing this type */
|
| 588 |
+
char type;
|
| 589 |
+
/*
|
| 590 |
+
* '>' (big), '<' (little), '|'
|
| 591 |
+
* (not-applicable), or '=' (native).
|
| 592 |
+
*/
|
| 593 |
+
char byteorder;
|
| 594 |
+
/* flags describing data type */
|
| 595 |
+
char flags;
|
| 596 |
+
/* number representing this type */
|
| 597 |
+
int type_num;
|
| 598 |
+
/* element size (itemsize) for this type */
|
| 599 |
+
int elsize;
|
| 600 |
+
/* alignment needed for this type */
|
| 601 |
+
int alignment;
|
| 602 |
+
/*
|
| 603 |
+
* Non-NULL if this type is
|
| 604 |
+
* is an array (C-contiguous)
|
| 605 |
+
* of some other type
|
| 606 |
+
*/
|
| 607 |
+
struct _arr_descr *subarray;
|
| 608 |
+
/*
|
| 609 |
+
* The fields dictionary for this type
|
| 610 |
+
* For statically defined descr this
|
| 611 |
+
* is always Py_None
|
| 612 |
+
*/
|
| 613 |
+
PyObject *fields;
|
| 614 |
+
/*
|
| 615 |
+
* An ordered tuple of field names or NULL
|
| 616 |
+
* if no fields are defined
|
| 617 |
+
*/
|
| 618 |
+
PyObject *names;
|
| 619 |
+
/*
|
| 620 |
+
* a table of functions specific for each
|
| 621 |
+
* basic data descriptor
|
| 622 |
+
*/
|
| 623 |
+
PyArray_ArrFuncs *f;
|
| 624 |
+
/* Metadata about this dtype */
|
| 625 |
+
PyObject *metadata;
|
| 626 |
+
/*
|
| 627 |
+
* Metadata specific to the C implementation
|
| 628 |
+
* of the particular dtype. This was added
|
| 629 |
+
* for NumPy 1.7.0.
|
| 630 |
+
*/
|
| 631 |
+
NpyAuxData *c_metadata;
|
| 632 |
+
/* Cached hash value (-1 if not yet computed).
|
| 633 |
+
* This was added for NumPy 2.0.0.
|
| 634 |
+
*/
|
| 635 |
+
npy_hash_t hash;
|
| 636 |
+
} PyArray_Descr;
|
| 637 |
+
|
| 638 |
+
typedef struct _arr_descr {
|
| 639 |
+
PyArray_Descr *base;
|
| 640 |
+
PyObject *shape; /* a tuple */
|
| 641 |
+
} PyArray_ArrayDescr;
|
| 642 |
+
|
| 643 |
+
/*
|
| 644 |
+
* Memory handler structure for array data.
|
| 645 |
+
*/
|
| 646 |
+
/* The declaration of free differs from PyMemAllocatorEx */
|
| 647 |
+
typedef struct {
|
| 648 |
+
void *ctx;
|
| 649 |
+
void* (*malloc) (void *ctx, size_t size);
|
| 650 |
+
void* (*calloc) (void *ctx, size_t nelem, size_t elsize);
|
| 651 |
+
void* (*realloc) (void *ctx, void *ptr, size_t new_size);
|
| 652 |
+
void (*free) (void *ctx, void *ptr, size_t size);
|
| 653 |
+
/*
|
| 654 |
+
* This is the end of the version=1 struct. Only add new fields after
|
| 655 |
+
* this line
|
| 656 |
+
*/
|
| 657 |
+
} PyDataMemAllocator;
|
| 658 |
+
|
| 659 |
+
typedef struct {
|
| 660 |
+
char name[127]; /* multiple of 64 to keep the struct aligned */
|
| 661 |
+
uint8_t version; /* currently 1 */
|
| 662 |
+
PyDataMemAllocator allocator;
|
| 663 |
+
} PyDataMem_Handler;
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
/*
|
| 667 |
+
* The main array object structure.
|
| 668 |
+
*
|
| 669 |
+
* It has been recommended to use the inline functions defined below
|
| 670 |
+
* (PyArray_DATA and friends) to access fields here for a number of
|
| 671 |
+
* releases. Direct access to the members themselves is deprecated.
|
| 672 |
+
* To ensure that your code does not use deprecated access,
|
| 673 |
+
* #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
|
| 674 |
+
* (or NPY_1_8_API_VERSION or higher as required).
|
| 675 |
+
*/
|
| 676 |
+
/* This struct will be moved to a private header in a future release */
|
| 677 |
+
typedef struct tagPyArrayObject_fields {
|
| 678 |
+
PyObject_HEAD
|
| 679 |
+
/* Pointer to the raw data buffer */
|
| 680 |
+
char *data;
|
| 681 |
+
/* The number of dimensions, also called 'ndim' */
|
| 682 |
+
int nd;
|
| 683 |
+
/* The size in each dimension, also called 'shape' */
|
| 684 |
+
npy_intp *dimensions;
|
| 685 |
+
/*
|
| 686 |
+
* Number of bytes to jump to get to the
|
| 687 |
+
* next element in each dimension
|
| 688 |
+
*/
|
| 689 |
+
npy_intp *strides;
|
| 690 |
+
/*
|
| 691 |
+
* This object is decref'd upon
|
| 692 |
+
* deletion of array. Except in the
|
| 693 |
+
* case of WRITEBACKIFCOPY which has
|
| 694 |
+
* special handling.
|
| 695 |
+
*
|
| 696 |
+
* For views it points to the original
|
| 697 |
+
* array, collapsed so no chains of
|
| 698 |
+
* views occur.
|
| 699 |
+
*
|
| 700 |
+
* For creation from buffer object it
|
| 701 |
+
* points to an object that should be
|
| 702 |
+
* decref'd on deletion
|
| 703 |
+
*
|
| 704 |
+
* For WRITEBACKIFCOPY flag this is an
|
| 705 |
+
* array to-be-updated upon calling
|
| 706 |
+
* PyArray_ResolveWritebackIfCopy
|
| 707 |
+
*/
|
| 708 |
+
PyObject *base;
|
| 709 |
+
/* Pointer to type structure */
|
| 710 |
+
PyArray_Descr *descr;
|
| 711 |
+
/* Flags describing array -- see below */
|
| 712 |
+
int flags;
|
| 713 |
+
/* For weak references */
|
| 714 |
+
PyObject *weakreflist;
|
| 715 |
+
#if NPY_FEATURE_VERSION >= NPY_1_20_API_VERSION
|
| 716 |
+
void *_buffer_info; /* private buffer info, tagged to allow warning */
|
| 717 |
+
#endif
|
| 718 |
+
/*
|
| 719 |
+
* For malloc/calloc/realloc/free per object
|
| 720 |
+
*/
|
| 721 |
+
#if NPY_FEATURE_VERSION >= NPY_1_22_API_VERSION
|
| 722 |
+
PyObject *mem_handler;
|
| 723 |
+
#endif
|
| 724 |
+
} PyArrayObject_fields;
|
| 725 |
+
|
| 726 |
+
/*
|
| 727 |
+
* To hide the implementation details, we only expose
|
| 728 |
+
* the Python struct HEAD.
|
| 729 |
+
*/
|
| 730 |
+
#if !defined(NPY_NO_DEPRECATED_API) || \
|
| 731 |
+
(NPY_NO_DEPRECATED_API < NPY_1_7_API_VERSION)
|
| 732 |
+
/*
|
| 733 |
+
* Can't put this in npy_deprecated_api.h like the others.
|
| 734 |
+
* PyArrayObject field access is deprecated as of NumPy 1.7.
|
| 735 |
+
*/
|
| 736 |
+
typedef PyArrayObject_fields PyArrayObject;
|
| 737 |
+
#else
|
| 738 |
+
typedef struct tagPyArrayObject {
|
| 739 |
+
PyObject_HEAD
|
| 740 |
+
} PyArrayObject;
|
| 741 |
+
#endif
|
| 742 |
+
|
| 743 |
+
/*
|
| 744 |
+
* Removed 2020-Nov-25, NumPy 1.20
|
| 745 |
+
* #define NPY_SIZEOF_PYARRAYOBJECT (sizeof(PyArrayObject_fields))
|
| 746 |
+
*
|
| 747 |
+
* The above macro was removed as it gave a false sense of a stable ABI
|
| 748 |
+
* with respect to the structures size. If you require a runtime constant,
|
| 749 |
+
* you can use `PyArray_Type.tp_basicsize` instead. Otherwise, please
|
| 750 |
+
* see the PyArrayObject documentation or ask the NumPy developers for
|
| 751 |
+
* information on how to correctly replace the macro in a way that is
|
| 752 |
+
* compatible with multiple NumPy versions.
|
| 753 |
+
*/
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
/* Array Flags Object */
|
| 757 |
+
typedef struct PyArrayFlagsObject {
|
| 758 |
+
PyObject_HEAD
|
| 759 |
+
PyObject *arr;
|
| 760 |
+
int flags;
|
| 761 |
+
} PyArrayFlagsObject;
|
| 762 |
+
|
| 763 |
+
/* Mirrors buffer object to ptr */
|
| 764 |
+
|
| 765 |
+
typedef struct {
|
| 766 |
+
PyObject_HEAD
|
| 767 |
+
PyObject *base;
|
| 768 |
+
void *ptr;
|
| 769 |
+
npy_intp len;
|
| 770 |
+
int flags;
|
| 771 |
+
} PyArray_Chunk;
|
| 772 |
+
|
| 773 |
+
typedef struct {
|
| 774 |
+
NPY_DATETIMEUNIT base;
|
| 775 |
+
int num;
|
| 776 |
+
} PyArray_DatetimeMetaData;
|
| 777 |
+
|
| 778 |
+
typedef struct {
|
| 779 |
+
NpyAuxData base;
|
| 780 |
+
PyArray_DatetimeMetaData meta;
|
| 781 |
+
} PyArray_DatetimeDTypeMetaData;
|
| 782 |
+
|
| 783 |
+
/*
|
| 784 |
+
* This structure contains an exploded view of a date-time value.
|
| 785 |
+
* NaT is represented by year == NPY_DATETIME_NAT.
|
| 786 |
+
*/
|
| 787 |
+
typedef struct {
|
| 788 |
+
npy_int64 year;
|
| 789 |
+
npy_int32 month, day, hour, min, sec, us, ps, as;
|
| 790 |
+
} npy_datetimestruct;
|
| 791 |
+
|
| 792 |
+
/* This is not used internally. */
|
| 793 |
+
typedef struct {
|
| 794 |
+
npy_int64 day;
|
| 795 |
+
npy_int32 sec, us, ps, as;
|
| 796 |
+
} npy_timedeltastruct;
|
| 797 |
+
|
| 798 |
+
typedef int (PyArray_FinalizeFunc)(PyArrayObject *, PyObject *);
|
| 799 |
+
|
| 800 |
+
/*
|
| 801 |
+
* Means c-style contiguous (last index varies the fastest). The data
|
| 802 |
+
* elements right after each other.
|
| 803 |
+
*
|
| 804 |
+
* This flag may be requested in constructor functions.
|
| 805 |
+
* This flag may be tested for in PyArray_FLAGS(arr).
|
| 806 |
+
*/
|
| 807 |
+
#define NPY_ARRAY_C_CONTIGUOUS 0x0001
|
| 808 |
+
|
| 809 |
+
/*
|
| 810 |
+
* Set if array is a contiguous Fortran array: the first index varies
|
| 811 |
+
* the fastest in memory (strides array is reverse of C-contiguous
|
| 812 |
+
* array)
|
| 813 |
+
*
|
| 814 |
+
* This flag may be requested in constructor functions.
|
| 815 |
+
* This flag may be tested for in PyArray_FLAGS(arr).
|
| 816 |
+
*/
|
| 817 |
+
#define NPY_ARRAY_F_CONTIGUOUS 0x0002
|
| 818 |
+
|
| 819 |
+
/*
|
| 820 |
+
* Note: all 0-d arrays are C_CONTIGUOUS and F_CONTIGUOUS. If a
|
| 821 |
+
* 1-d array is C_CONTIGUOUS it is also F_CONTIGUOUS. Arrays with
|
| 822 |
+
* more then one dimension can be C_CONTIGUOUS and F_CONTIGUOUS
|
| 823 |
+
* at the same time if they have either zero or one element.
|
| 824 |
+
* A higher dimensional array always has the same contiguity flags as
|
| 825 |
+
* `array.squeeze()`; dimensions with `array.shape[dimension] == 1` are
|
| 826 |
+
* effectively ignored when checking for contiguity.
|
| 827 |
+
*/
|
| 828 |
+
|
| 829 |
+
/*
|
| 830 |
+
* If set, the array owns the data: it will be free'd when the array
|
| 831 |
+
* is deleted.
|
| 832 |
+
*
|
| 833 |
+
* This flag may be tested for in PyArray_FLAGS(arr).
|
| 834 |
+
*/
|
| 835 |
+
#define NPY_ARRAY_OWNDATA 0x0004
|
| 836 |
+
|
| 837 |
+
/*
|
| 838 |
+
* An array never has the next four set; they're only used as parameter
|
| 839 |
+
* flags to the various FromAny functions
|
| 840 |
+
*
|
| 841 |
+
* This flag may be requested in constructor functions.
|
| 842 |
+
*/
|
| 843 |
+
|
| 844 |
+
/* Cause a cast to occur regardless of whether or not it is safe. */
|
| 845 |
+
#define NPY_ARRAY_FORCECAST 0x0010
|
| 846 |
+
|
| 847 |
+
/*
|
| 848 |
+
* Always copy the array. Returned arrays are always CONTIGUOUS,
|
| 849 |
+
* ALIGNED, and WRITEABLE. See also: NPY_ARRAY_ENSURENOCOPY = 0x4000.
|
| 850 |
+
*
|
| 851 |
+
* This flag may be requested in constructor functions.
|
| 852 |
+
*/
|
| 853 |
+
#define NPY_ARRAY_ENSURECOPY 0x0020
|
| 854 |
+
|
| 855 |
+
/*
|
| 856 |
+
* Make sure the returned array is a base-class ndarray
|
| 857 |
+
*
|
| 858 |
+
* This flag may be requested in constructor functions.
|
| 859 |
+
*/
|
| 860 |
+
#define NPY_ARRAY_ENSUREARRAY 0x0040
|
| 861 |
+
|
| 862 |
+
/*
|
| 863 |
+
* Make sure that the strides are in units of the element size Needed
|
| 864 |
+
* for some operations with record-arrays.
|
| 865 |
+
*
|
| 866 |
+
* This flag may be requested in constructor functions.
|
| 867 |
+
*/
|
| 868 |
+
#define NPY_ARRAY_ELEMENTSTRIDES 0x0080
|
| 869 |
+
|
| 870 |
+
/*
|
| 871 |
+
* Array data is aligned on the appropriate memory address for the type
|
| 872 |
+
* stored according to how the compiler would align things (e.g., an
|
| 873 |
+
* array of integers (4 bytes each) starts on a memory address that's
|
| 874 |
+
* a multiple of 4)
|
| 875 |
+
*
|
| 876 |
+
* This flag may be requested in constructor functions.
|
| 877 |
+
* This flag may be tested for in PyArray_FLAGS(arr).
|
| 878 |
+
*/
|
| 879 |
+
#define NPY_ARRAY_ALIGNED 0x0100
|
| 880 |
+
|
| 881 |
+
/*
|
| 882 |
+
* Array data has the native endianness
|
| 883 |
+
*
|
| 884 |
+
* This flag may be requested in constructor functions.
|
| 885 |
+
*/
|
| 886 |
+
#define NPY_ARRAY_NOTSWAPPED 0x0200
|
| 887 |
+
|
| 888 |
+
/*
|
| 889 |
+
* Array data is writeable
|
| 890 |
+
*
|
| 891 |
+
* This flag may be requested in constructor functions.
|
| 892 |
+
* This flag may be tested for in PyArray_FLAGS(arr).
|
| 893 |
+
*/
|
| 894 |
+
#define NPY_ARRAY_WRITEABLE 0x0400
|
| 895 |
+
|
| 896 |
+
/*
|
| 897 |
+
* If this flag is set, then base contains a pointer to an array of
|
| 898 |
+
* the same size that should be updated with the current contents of
|
| 899 |
+
* this array when PyArray_ResolveWritebackIfCopy is called.
|
| 900 |
+
*
|
| 901 |
+
* This flag may be requested in constructor functions.
|
| 902 |
+
* This flag may be tested for in PyArray_FLAGS(arr).
|
| 903 |
+
*/
|
| 904 |
+
#define NPY_ARRAY_WRITEBACKIFCOPY 0x2000
|
| 905 |
+
|
| 906 |
+
/*
|
| 907 |
+
* No copy may be made while converting from an object/array (result is a view)
|
| 908 |
+
*
|
| 909 |
+
* This flag may be requested in constructor functions.
|
| 910 |
+
*/
|
| 911 |
+
#define NPY_ARRAY_ENSURENOCOPY 0x4000
|
| 912 |
+
|
| 913 |
+
/*
|
| 914 |
+
* NOTE: there are also internal flags defined in multiarray/arrayobject.h,
|
| 915 |
+
* which start at bit 31 and work down.
|
| 916 |
+
*/
|
| 917 |
+
|
| 918 |
+
#define NPY_ARRAY_BEHAVED (NPY_ARRAY_ALIGNED | \
|
| 919 |
+
NPY_ARRAY_WRITEABLE)
|
| 920 |
+
#define NPY_ARRAY_BEHAVED_NS (NPY_ARRAY_ALIGNED | \
|
| 921 |
+
NPY_ARRAY_WRITEABLE | \
|
| 922 |
+
NPY_ARRAY_NOTSWAPPED)
|
| 923 |
+
#define NPY_ARRAY_CARRAY (NPY_ARRAY_C_CONTIGUOUS | \
|
| 924 |
+
NPY_ARRAY_BEHAVED)
|
| 925 |
+
#define NPY_ARRAY_CARRAY_RO (NPY_ARRAY_C_CONTIGUOUS | \
|
| 926 |
+
NPY_ARRAY_ALIGNED)
|
| 927 |
+
#define NPY_ARRAY_FARRAY (NPY_ARRAY_F_CONTIGUOUS | \
|
| 928 |
+
NPY_ARRAY_BEHAVED)
|
| 929 |
+
#define NPY_ARRAY_FARRAY_RO (NPY_ARRAY_F_CONTIGUOUS | \
|
| 930 |
+
NPY_ARRAY_ALIGNED)
|
| 931 |
+
#define NPY_ARRAY_DEFAULT (NPY_ARRAY_CARRAY)
|
| 932 |
+
#define NPY_ARRAY_IN_ARRAY (NPY_ARRAY_CARRAY_RO)
|
| 933 |
+
#define NPY_ARRAY_OUT_ARRAY (NPY_ARRAY_CARRAY)
|
| 934 |
+
#define NPY_ARRAY_INOUT_ARRAY (NPY_ARRAY_CARRAY)
|
| 935 |
+
#define NPY_ARRAY_INOUT_ARRAY2 (NPY_ARRAY_CARRAY | \
|
| 936 |
+
NPY_ARRAY_WRITEBACKIFCOPY)
|
| 937 |
+
#define NPY_ARRAY_IN_FARRAY (NPY_ARRAY_FARRAY_RO)
|
| 938 |
+
#define NPY_ARRAY_OUT_FARRAY (NPY_ARRAY_FARRAY)
|
| 939 |
+
#define NPY_ARRAY_INOUT_FARRAY (NPY_ARRAY_FARRAY)
|
| 940 |
+
#define NPY_ARRAY_INOUT_FARRAY2 (NPY_ARRAY_FARRAY | \
|
| 941 |
+
NPY_ARRAY_WRITEBACKIFCOPY)
|
| 942 |
+
|
| 943 |
+
#define NPY_ARRAY_UPDATE_ALL (NPY_ARRAY_C_CONTIGUOUS | \
|
| 944 |
+
NPY_ARRAY_F_CONTIGUOUS | \
|
| 945 |
+
NPY_ARRAY_ALIGNED)
|
| 946 |
+
|
| 947 |
+
/* This flag is for the array interface, not PyArrayObject */
|
| 948 |
+
#define NPY_ARR_HAS_DESCR 0x0800
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
/*
|
| 954 |
+
* Size of internal buffers used for alignment Make BUFSIZE a multiple
|
| 955 |
+
* of sizeof(npy_cdouble) -- usually 16 so that ufunc buffers are aligned
|
| 956 |
+
*/
|
| 957 |
+
#define NPY_MIN_BUFSIZE ((int)sizeof(npy_cdouble))
|
| 958 |
+
#define NPY_MAX_BUFSIZE (((int)sizeof(npy_cdouble))*1000000)
|
| 959 |
+
#define NPY_BUFSIZE 8192
|
| 960 |
+
/* buffer stress test size: */
|
| 961 |
+
/*#define NPY_BUFSIZE 17*/
|
| 962 |
+
|
| 963 |
+
#define PyArray_MAX(a,b) (((a)>(b))?(a):(b))
|
| 964 |
+
#define PyArray_MIN(a,b) (((a)<(b))?(a):(b))
|
| 965 |
+
#define PyArray_CLT(p,q) ((((p).real==(q).real) ? ((p).imag < (q).imag) : \
|
| 966 |
+
((p).real < (q).real)))
|
| 967 |
+
#define PyArray_CGT(p,q) ((((p).real==(q).real) ? ((p).imag > (q).imag) : \
|
| 968 |
+
((p).real > (q).real)))
|
| 969 |
+
#define PyArray_CLE(p,q) ((((p).real==(q).real) ? ((p).imag <= (q).imag) : \
|
| 970 |
+
((p).real <= (q).real)))
|
| 971 |
+
#define PyArray_CGE(p,q) ((((p).real==(q).real) ? ((p).imag >= (q).imag) : \
|
| 972 |
+
((p).real >= (q).real)))
|
| 973 |
+
#define PyArray_CEQ(p,q) (((p).real==(q).real) && ((p).imag == (q).imag))
|
| 974 |
+
#define PyArray_CNE(p,q) (((p).real!=(q).real) || ((p).imag != (q).imag))
|
| 975 |
+
|
| 976 |
+
/*
|
| 977 |
+
* C API: consists of Macros and functions. The MACROS are defined
|
| 978 |
+
* here.
|
| 979 |
+
*/
|
| 980 |
+
|
| 981 |
+
|
| 982 |
+
#define PyArray_ISCONTIGUOUS(m) PyArray_CHKFLAGS((m), NPY_ARRAY_C_CONTIGUOUS)
|
| 983 |
+
#define PyArray_ISWRITEABLE(m) PyArray_CHKFLAGS((m), NPY_ARRAY_WRITEABLE)
|
| 984 |
+
#define PyArray_ISALIGNED(m) PyArray_CHKFLAGS((m), NPY_ARRAY_ALIGNED)
|
| 985 |
+
|
| 986 |
+
#define PyArray_IS_C_CONTIGUOUS(m) PyArray_CHKFLAGS((m), NPY_ARRAY_C_CONTIGUOUS)
|
| 987 |
+
#define PyArray_IS_F_CONTIGUOUS(m) PyArray_CHKFLAGS((m), NPY_ARRAY_F_CONTIGUOUS)
|
| 988 |
+
|
| 989 |
+
/* the variable is used in some places, so always define it */
|
| 990 |
+
#define NPY_BEGIN_THREADS_DEF PyThreadState *_save=NULL;
|
| 991 |
+
#if NPY_ALLOW_THREADS
|
| 992 |
+
#define NPY_BEGIN_ALLOW_THREADS Py_BEGIN_ALLOW_THREADS
|
| 993 |
+
#define NPY_END_ALLOW_THREADS Py_END_ALLOW_THREADS
|
| 994 |
+
#define NPY_BEGIN_THREADS do {_save = PyEval_SaveThread();} while (0);
|
| 995 |
+
#define NPY_END_THREADS do { if (_save) \
|
| 996 |
+
{ PyEval_RestoreThread(_save); _save = NULL;} } while (0);
|
| 997 |
+
#define NPY_BEGIN_THREADS_THRESHOLDED(loop_size) do { if ((loop_size) > 500) \
|
| 998 |
+
{ _save = PyEval_SaveThread();} } while (0);
|
| 999 |
+
|
| 1000 |
+
#define NPY_BEGIN_THREADS_DESCR(dtype) \
|
| 1001 |
+
do {if (!(PyDataType_FLAGCHK((dtype), NPY_NEEDS_PYAPI))) \
|
| 1002 |
+
NPY_BEGIN_THREADS;} while (0);
|
| 1003 |
+
|
| 1004 |
+
#define NPY_END_THREADS_DESCR(dtype) \
|
| 1005 |
+
do {if (!(PyDataType_FLAGCHK((dtype), NPY_NEEDS_PYAPI))) \
|
| 1006 |
+
NPY_END_THREADS; } while (0);
|
| 1007 |
+
|
| 1008 |
+
#define NPY_ALLOW_C_API_DEF PyGILState_STATE __save__;
|
| 1009 |
+
#define NPY_ALLOW_C_API do {__save__ = PyGILState_Ensure();} while (0);
|
| 1010 |
+
#define NPY_DISABLE_C_API do {PyGILState_Release(__save__);} while (0);
|
| 1011 |
+
#else
|
| 1012 |
+
#define NPY_BEGIN_ALLOW_THREADS
|
| 1013 |
+
#define NPY_END_ALLOW_THREADS
|
| 1014 |
+
#define NPY_BEGIN_THREADS
|
| 1015 |
+
#define NPY_END_THREADS
|
| 1016 |
+
#define NPY_BEGIN_THREADS_THRESHOLDED(loop_size)
|
| 1017 |
+
#define NPY_BEGIN_THREADS_DESCR(dtype)
|
| 1018 |
+
#define NPY_END_THREADS_DESCR(dtype)
|
| 1019 |
+
#define NPY_ALLOW_C_API_DEF
|
| 1020 |
+
#define NPY_ALLOW_C_API
|
| 1021 |
+
#define NPY_DISABLE_C_API
|
| 1022 |
+
#endif
|
| 1023 |
+
|
| 1024 |
+
/**********************************
|
| 1025 |
+
* The nditer object, added in 1.6
|
| 1026 |
+
**********************************/
|
| 1027 |
+
|
| 1028 |
+
/* The actual structure of the iterator is an internal detail */
|
| 1029 |
+
typedef struct NpyIter_InternalOnly NpyIter;
|
| 1030 |
+
|
| 1031 |
+
/* Iterator function pointers that may be specialized */
|
| 1032 |
+
typedef int (NpyIter_IterNextFunc)(NpyIter *iter);
|
| 1033 |
+
typedef void (NpyIter_GetMultiIndexFunc)(NpyIter *iter,
|
| 1034 |
+
npy_intp *outcoords);
|
| 1035 |
+
|
| 1036 |
+
/*** Global flags that may be passed to the iterator constructors ***/
|
| 1037 |
+
|
| 1038 |
+
/* Track an index representing C order */
|
| 1039 |
+
#define NPY_ITER_C_INDEX 0x00000001
|
| 1040 |
+
/* Track an index representing Fortran order */
|
| 1041 |
+
#define NPY_ITER_F_INDEX 0x00000002
|
| 1042 |
+
/* Track a multi-index */
|
| 1043 |
+
#define NPY_ITER_MULTI_INDEX 0x00000004
|
| 1044 |
+
/* User code external to the iterator does the 1-dimensional innermost loop */
|
| 1045 |
+
#define NPY_ITER_EXTERNAL_LOOP 0x00000008
|
| 1046 |
+
/* Convert all the operands to a common data type */
|
| 1047 |
+
#define NPY_ITER_COMMON_DTYPE 0x00000010
|
| 1048 |
+
/* Operands may hold references, requiring API access during iteration */
|
| 1049 |
+
#define NPY_ITER_REFS_OK 0x00000020
|
| 1050 |
+
/* Zero-sized operands should be permitted, iteration checks IterSize for 0 */
|
| 1051 |
+
#define NPY_ITER_ZEROSIZE_OK 0x00000040
|
| 1052 |
+
/* Permits reductions (size-0 stride with dimension size > 1) */
|
| 1053 |
+
#define NPY_ITER_REDUCE_OK 0x00000080
|
| 1054 |
+
/* Enables sub-range iteration */
|
| 1055 |
+
#define NPY_ITER_RANGED 0x00000100
|
| 1056 |
+
/* Enables buffering */
|
| 1057 |
+
#define NPY_ITER_BUFFERED 0x00000200
|
| 1058 |
+
/* When buffering is enabled, grows the inner loop if possible */
|
| 1059 |
+
#define NPY_ITER_GROWINNER 0x00000400
|
| 1060 |
+
/* Delay allocation of buffers until first Reset* call */
|
| 1061 |
+
#define NPY_ITER_DELAY_BUFALLOC 0x00000800
|
| 1062 |
+
/* When NPY_KEEPORDER is specified, disable reversing negative-stride axes */
|
| 1063 |
+
#define NPY_ITER_DONT_NEGATE_STRIDES 0x00001000
|
| 1064 |
+
/*
|
| 1065 |
+
* If output operands overlap with other operands (based on heuristics that
|
| 1066 |
+
* has false positives but no false negatives), make temporary copies to
|
| 1067 |
+
* eliminate overlap.
|
| 1068 |
+
*/
|
| 1069 |
+
#define NPY_ITER_COPY_IF_OVERLAP 0x00002000
|
| 1070 |
+
|
| 1071 |
+
/*** Per-operand flags that may be passed to the iterator constructors ***/
|
| 1072 |
+
|
| 1073 |
+
/* The operand will be read from and written to */
|
| 1074 |
+
#define NPY_ITER_READWRITE 0x00010000
|
| 1075 |
+
/* The operand will only be read from */
|
| 1076 |
+
#define NPY_ITER_READONLY 0x00020000
|
| 1077 |
+
/* The operand will only be written to */
|
| 1078 |
+
#define NPY_ITER_WRITEONLY 0x00040000
|
| 1079 |
+
/* The operand's data must be in native byte order */
|
| 1080 |
+
#define NPY_ITER_NBO 0x00080000
|
| 1081 |
+
/* The operand's data must be aligned */
|
| 1082 |
+
#define NPY_ITER_ALIGNED 0x00100000
|
| 1083 |
+
/* The operand's data must be contiguous (within the inner loop) */
|
| 1084 |
+
#define NPY_ITER_CONTIG 0x00200000
|
| 1085 |
+
/* The operand may be copied to satisfy requirements */
|
| 1086 |
+
#define NPY_ITER_COPY 0x00400000
|
| 1087 |
+
/* The operand may be copied with WRITEBACKIFCOPY to satisfy requirements */
|
| 1088 |
+
#define NPY_ITER_UPDATEIFCOPY 0x00800000
|
| 1089 |
+
/* Allocate the operand if it is NULL */
|
| 1090 |
+
#define NPY_ITER_ALLOCATE 0x01000000
|
| 1091 |
+
/* If an operand is allocated, don't use any subtype */
|
| 1092 |
+
#define NPY_ITER_NO_SUBTYPE 0x02000000
|
| 1093 |
+
/* This is a virtual array slot, operand is NULL but temporary data is there */
|
| 1094 |
+
#define NPY_ITER_VIRTUAL 0x04000000
|
| 1095 |
+
/* Require that the dimension match the iterator dimensions exactly */
|
| 1096 |
+
#define NPY_ITER_NO_BROADCAST 0x08000000
|
| 1097 |
+
/* A mask is being used on this array, affects buffer -> array copy */
|
| 1098 |
+
#define NPY_ITER_WRITEMASKED 0x10000000
|
| 1099 |
+
/* This array is the mask for all WRITEMASKED operands */
|
| 1100 |
+
#define NPY_ITER_ARRAYMASK 0x20000000
|
| 1101 |
+
/* Assume iterator order data access for COPY_IF_OVERLAP */
|
| 1102 |
+
#define NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE 0x40000000
|
| 1103 |
+
|
| 1104 |
+
#define NPY_ITER_GLOBAL_FLAGS 0x0000ffff
|
| 1105 |
+
#define NPY_ITER_PER_OP_FLAGS 0xffff0000
|
| 1106 |
+
|
| 1107 |
+
|
| 1108 |
+
/*****************************
|
| 1109 |
+
* Basic iterator object
|
| 1110 |
+
*****************************/
|
| 1111 |
+
|
| 1112 |
+
/* FWD declaration */
|
| 1113 |
+
typedef struct PyArrayIterObject_tag PyArrayIterObject;
|
| 1114 |
+
|
| 1115 |
+
/*
|
| 1116 |
+
* type of the function which translates a set of coordinates to a
|
| 1117 |
+
* pointer to the data
|
| 1118 |
+
*/
|
| 1119 |
+
typedef char* (*npy_iter_get_dataptr_t)(
|
| 1120 |
+
PyArrayIterObject* iter, const npy_intp*);
|
| 1121 |
+
|
| 1122 |
+
struct PyArrayIterObject_tag {
|
| 1123 |
+
PyObject_HEAD
|
| 1124 |
+
int nd_m1; /* number of dimensions - 1 */
|
| 1125 |
+
npy_intp index, size;
|
| 1126 |
+
npy_intp coordinates[NPY_MAXDIMS];/* N-dimensional loop */
|
| 1127 |
+
npy_intp dims_m1[NPY_MAXDIMS]; /* ao->dimensions - 1 */
|
| 1128 |
+
npy_intp strides[NPY_MAXDIMS]; /* ao->strides or fake */
|
| 1129 |
+
npy_intp backstrides[NPY_MAXDIMS];/* how far to jump back */
|
| 1130 |
+
npy_intp factors[NPY_MAXDIMS]; /* shape factors */
|
| 1131 |
+
PyArrayObject *ao;
|
| 1132 |
+
char *dataptr; /* pointer to current item*/
|
| 1133 |
+
npy_bool contiguous;
|
| 1134 |
+
|
| 1135 |
+
npy_intp bounds[NPY_MAXDIMS][2];
|
| 1136 |
+
npy_intp limits[NPY_MAXDIMS][2];
|
| 1137 |
+
npy_intp limits_sizes[NPY_MAXDIMS];
|
| 1138 |
+
npy_iter_get_dataptr_t translate;
|
| 1139 |
+
} ;
|
| 1140 |
+
|
| 1141 |
+
|
| 1142 |
+
/* Iterator API */
|
| 1143 |
+
#define PyArrayIter_Check(op) PyObject_TypeCheck((op), &PyArrayIter_Type)
|
| 1144 |
+
|
| 1145 |
+
#define _PyAIT(it) ((PyArrayIterObject *)(it))
|
| 1146 |
+
#define PyArray_ITER_RESET(it) do { \
|
| 1147 |
+
_PyAIT(it)->index = 0; \
|
| 1148 |
+
_PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao); \
|
| 1149 |
+
memset(_PyAIT(it)->coordinates, 0, \
|
| 1150 |
+
(_PyAIT(it)->nd_m1+1)*sizeof(npy_intp)); \
|
| 1151 |
+
} while (0)
|
| 1152 |
+
|
| 1153 |
+
#define _PyArray_ITER_NEXT1(it) do { \
|
| 1154 |
+
(it)->dataptr += _PyAIT(it)->strides[0]; \
|
| 1155 |
+
(it)->coordinates[0]++; \
|
| 1156 |
+
} while (0)
|
| 1157 |
+
|
| 1158 |
+
#define _PyArray_ITER_NEXT2(it) do { \
|
| 1159 |
+
if ((it)->coordinates[1] < (it)->dims_m1[1]) { \
|
| 1160 |
+
(it)->coordinates[1]++; \
|
| 1161 |
+
(it)->dataptr += (it)->strides[1]; \
|
| 1162 |
+
} \
|
| 1163 |
+
else { \
|
| 1164 |
+
(it)->coordinates[1] = 0; \
|
| 1165 |
+
(it)->coordinates[0]++; \
|
| 1166 |
+
(it)->dataptr += (it)->strides[0] - \
|
| 1167 |
+
(it)->backstrides[1]; \
|
| 1168 |
+
} \
|
| 1169 |
+
} while (0)
|
| 1170 |
+
|
| 1171 |
+
#define PyArray_ITER_NEXT(it) do { \
|
| 1172 |
+
_PyAIT(it)->index++; \
|
| 1173 |
+
if (_PyAIT(it)->nd_m1 == 0) { \
|
| 1174 |
+
_PyArray_ITER_NEXT1(_PyAIT(it)); \
|
| 1175 |
+
} \
|
| 1176 |
+
else if (_PyAIT(it)->contiguous) \
|
| 1177 |
+
_PyAIT(it)->dataptr += PyArray_DESCR(_PyAIT(it)->ao)->elsize; \
|
| 1178 |
+
else if (_PyAIT(it)->nd_m1 == 1) { \
|
| 1179 |
+
_PyArray_ITER_NEXT2(_PyAIT(it)); \
|
| 1180 |
+
} \
|
| 1181 |
+
else { \
|
| 1182 |
+
int __npy_i; \
|
| 1183 |
+
for (__npy_i=_PyAIT(it)->nd_m1; __npy_i >= 0; __npy_i--) { \
|
| 1184 |
+
if (_PyAIT(it)->coordinates[__npy_i] < \
|
| 1185 |
+
_PyAIT(it)->dims_m1[__npy_i]) { \
|
| 1186 |
+
_PyAIT(it)->coordinates[__npy_i]++; \
|
| 1187 |
+
_PyAIT(it)->dataptr += \
|
| 1188 |
+
_PyAIT(it)->strides[__npy_i]; \
|
| 1189 |
+
break; \
|
| 1190 |
+
} \
|
| 1191 |
+
else { \
|
| 1192 |
+
_PyAIT(it)->coordinates[__npy_i] = 0; \
|
| 1193 |
+
_PyAIT(it)->dataptr -= \
|
| 1194 |
+
_PyAIT(it)->backstrides[__npy_i]; \
|
| 1195 |
+
} \
|
| 1196 |
+
} \
|
| 1197 |
+
} \
|
| 1198 |
+
} while (0)
|
| 1199 |
+
|
| 1200 |
+
#define PyArray_ITER_GOTO(it, destination) do { \
|
| 1201 |
+
int __npy_i; \
|
| 1202 |
+
_PyAIT(it)->index = 0; \
|
| 1203 |
+
_PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao); \
|
| 1204 |
+
for (__npy_i = _PyAIT(it)->nd_m1; __npy_i>=0; __npy_i--) { \
|
| 1205 |
+
if (destination[__npy_i] < 0) { \
|
| 1206 |
+
destination[__npy_i] += \
|
| 1207 |
+
_PyAIT(it)->dims_m1[__npy_i]+1; \
|
| 1208 |
+
} \
|
| 1209 |
+
_PyAIT(it)->dataptr += destination[__npy_i] * \
|
| 1210 |
+
_PyAIT(it)->strides[__npy_i]; \
|
| 1211 |
+
_PyAIT(it)->coordinates[__npy_i] = \
|
| 1212 |
+
destination[__npy_i]; \
|
| 1213 |
+
_PyAIT(it)->index += destination[__npy_i] * \
|
| 1214 |
+
( __npy_i==_PyAIT(it)->nd_m1 ? 1 : \
|
| 1215 |
+
_PyAIT(it)->dims_m1[__npy_i+1]+1) ; \
|
| 1216 |
+
} \
|
| 1217 |
+
} while (0)
|
| 1218 |
+
|
| 1219 |
+
#define PyArray_ITER_GOTO1D(it, ind) do { \
|
| 1220 |
+
int __npy_i; \
|
| 1221 |
+
npy_intp __npy_ind = (npy_intp)(ind); \
|
| 1222 |
+
if (__npy_ind < 0) __npy_ind += _PyAIT(it)->size; \
|
| 1223 |
+
_PyAIT(it)->index = __npy_ind; \
|
| 1224 |
+
if (_PyAIT(it)->nd_m1 == 0) { \
|
| 1225 |
+
_PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao) + \
|
| 1226 |
+
__npy_ind * _PyAIT(it)->strides[0]; \
|
| 1227 |
+
} \
|
| 1228 |
+
else if (_PyAIT(it)->contiguous) \
|
| 1229 |
+
_PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao) + \
|
| 1230 |
+
__npy_ind * PyArray_DESCR(_PyAIT(it)->ao)->elsize; \
|
| 1231 |
+
else { \
|
| 1232 |
+
_PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao); \
|
| 1233 |
+
for (__npy_i = 0; __npy_i<=_PyAIT(it)->nd_m1; \
|
| 1234 |
+
__npy_i++) { \
|
| 1235 |
+
_PyAIT(it)->coordinates[__npy_i] = \
|
| 1236 |
+
(__npy_ind / _PyAIT(it)->factors[__npy_i]); \
|
| 1237 |
+
_PyAIT(it)->dataptr += \
|
| 1238 |
+
(__npy_ind / _PyAIT(it)->factors[__npy_i]) \
|
| 1239 |
+
* _PyAIT(it)->strides[__npy_i]; \
|
| 1240 |
+
__npy_ind %= _PyAIT(it)->factors[__npy_i]; \
|
| 1241 |
+
} \
|
| 1242 |
+
} \
|
| 1243 |
+
} while (0)
|
| 1244 |
+
|
| 1245 |
+
#define PyArray_ITER_DATA(it) ((void *)(_PyAIT(it)->dataptr))
|
| 1246 |
+
|
| 1247 |
+
#define PyArray_ITER_NOTDONE(it) (_PyAIT(it)->index < _PyAIT(it)->size)
|
| 1248 |
+
|
| 1249 |
+
|
| 1250 |
+
/*
|
| 1251 |
+
* Any object passed to PyArray_Broadcast must be binary compatible
|
| 1252 |
+
* with this structure.
|
| 1253 |
+
*/
|
| 1254 |
+
|
| 1255 |
+
typedef struct {
|
| 1256 |
+
PyObject_HEAD
|
| 1257 |
+
int numiter; /* number of iters */
|
| 1258 |
+
npy_intp size; /* broadcasted size */
|
| 1259 |
+
npy_intp index; /* current index */
|
| 1260 |
+
int nd; /* number of dims */
|
| 1261 |
+
npy_intp dimensions[NPY_MAXDIMS]; /* dimensions */
|
| 1262 |
+
PyArrayIterObject *iters[NPY_MAXARGS]; /* iterators */
|
| 1263 |
+
} PyArrayMultiIterObject;
|
| 1264 |
+
|
| 1265 |
+
#define _PyMIT(m) ((PyArrayMultiIterObject *)(m))
|
| 1266 |
+
#define PyArray_MultiIter_RESET(multi) do { \
|
| 1267 |
+
int __npy_mi; \
|
| 1268 |
+
_PyMIT(multi)->index = 0; \
|
| 1269 |
+
for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \
|
| 1270 |
+
PyArray_ITER_RESET(_PyMIT(multi)->iters[__npy_mi]); \
|
| 1271 |
+
} \
|
| 1272 |
+
} while (0)
|
| 1273 |
+
|
| 1274 |
+
#define PyArray_MultiIter_NEXT(multi) do { \
|
| 1275 |
+
int __npy_mi; \
|
| 1276 |
+
_PyMIT(multi)->index++; \
|
| 1277 |
+
for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \
|
| 1278 |
+
PyArray_ITER_NEXT(_PyMIT(multi)->iters[__npy_mi]); \
|
| 1279 |
+
} \
|
| 1280 |
+
} while (0)
|
| 1281 |
+
|
| 1282 |
+
#define PyArray_MultiIter_GOTO(multi, dest) do { \
|
| 1283 |
+
int __npy_mi; \
|
| 1284 |
+
for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \
|
| 1285 |
+
PyArray_ITER_GOTO(_PyMIT(multi)->iters[__npy_mi], dest); \
|
| 1286 |
+
} \
|
| 1287 |
+
_PyMIT(multi)->index = _PyMIT(multi)->iters[0]->index; \
|
| 1288 |
+
} while (0)
|
| 1289 |
+
|
| 1290 |
+
#define PyArray_MultiIter_GOTO1D(multi, ind) do { \
|
| 1291 |
+
int __npy_mi; \
|
| 1292 |
+
for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \
|
| 1293 |
+
PyArray_ITER_GOTO1D(_PyMIT(multi)->iters[__npy_mi], ind); \
|
| 1294 |
+
} \
|
| 1295 |
+
_PyMIT(multi)->index = _PyMIT(multi)->iters[0]->index; \
|
| 1296 |
+
} while (0)
|
| 1297 |
+
|
| 1298 |
+
#define PyArray_MultiIter_DATA(multi, i) \
|
| 1299 |
+
((void *)(_PyMIT(multi)->iters[i]->dataptr))
|
| 1300 |
+
|
| 1301 |
+
#define PyArray_MultiIter_NEXTi(multi, i) \
|
| 1302 |
+
PyArray_ITER_NEXT(_PyMIT(multi)->iters[i])
|
| 1303 |
+
|
| 1304 |
+
#define PyArray_MultiIter_NOTDONE(multi) \
|
| 1305 |
+
(_PyMIT(multi)->index < _PyMIT(multi)->size)
|
| 1306 |
+
|
| 1307 |
+
/*
|
| 1308 |
+
* Store the information needed for fancy-indexing over an array. The
|
| 1309 |
+
* fields are slightly unordered to keep consec, dataptr and subspace
|
| 1310 |
+
* where they were originally.
|
| 1311 |
+
*/
|
| 1312 |
+
typedef struct {
|
| 1313 |
+
PyObject_HEAD
|
| 1314 |
+
/*
|
| 1315 |
+
* Multi-iterator portion --- needs to be present in this
|
| 1316 |
+
* order to work with PyArray_Broadcast
|
| 1317 |
+
*/
|
| 1318 |
+
|
| 1319 |
+
int numiter; /* number of index-array
|
| 1320 |
+
iterators */
|
| 1321 |
+
npy_intp size; /* size of broadcasted
|
| 1322 |
+
result */
|
| 1323 |
+
npy_intp index; /* current index */
|
| 1324 |
+
int nd; /* number of dims */
|
| 1325 |
+
npy_intp dimensions[NPY_MAXDIMS]; /* dimensions */
|
| 1326 |
+
NpyIter *outer; /* index objects
|
| 1327 |
+
iterator */
|
| 1328 |
+
void *unused[NPY_MAXDIMS - 2];
|
| 1329 |
+
PyArrayObject *array;
|
| 1330 |
+
/* Flat iterator for the indexed array. For compatibility solely. */
|
| 1331 |
+
PyArrayIterObject *ait;
|
| 1332 |
+
|
| 1333 |
+
/*
|
| 1334 |
+
* Subspace array. For binary compatibility (was an iterator,
|
| 1335 |
+
* but only the check for NULL should be used).
|
| 1336 |
+
*/
|
| 1337 |
+
PyArrayObject *subspace;
|
| 1338 |
+
|
| 1339 |
+
/*
|
| 1340 |
+
* if subspace iteration, then this is the array of axes in
|
| 1341 |
+
* the underlying array represented by the index objects
|
| 1342 |
+
*/
|
| 1343 |
+
int iteraxes[NPY_MAXDIMS];
|
| 1344 |
+
npy_intp fancy_strides[NPY_MAXDIMS];
|
| 1345 |
+
|
| 1346 |
+
/* pointer when all fancy indices are 0 */
|
| 1347 |
+
char *baseoffset;
|
| 1348 |
+
|
| 1349 |
+
/*
|
| 1350 |
+
* after binding consec denotes at which axis the fancy axes
|
| 1351 |
+
* are inserted.
|
| 1352 |
+
*/
|
| 1353 |
+
int consec;
|
| 1354 |
+
char *dataptr;
|
| 1355 |
+
|
| 1356 |
+
int nd_fancy;
|
| 1357 |
+
npy_intp fancy_dims[NPY_MAXDIMS];
|
| 1358 |
+
|
| 1359 |
+
/*
|
| 1360 |
+
* Whether the iterator (any of the iterators) requires API. This is
|
| 1361 |
+
* unused by NumPy itself; ArrayMethod flags are more precise.
|
| 1362 |
+
*/
|
| 1363 |
+
int needs_api;
|
| 1364 |
+
|
| 1365 |
+
/*
|
| 1366 |
+
* Extra op information.
|
| 1367 |
+
*/
|
| 1368 |
+
PyArrayObject *extra_op;
|
| 1369 |
+
PyArray_Descr *extra_op_dtype; /* desired dtype */
|
| 1370 |
+
npy_uint32 *extra_op_flags; /* Iterator flags */
|
| 1371 |
+
|
| 1372 |
+
NpyIter *extra_op_iter;
|
| 1373 |
+
NpyIter_IterNextFunc *extra_op_next;
|
| 1374 |
+
char **extra_op_ptrs;
|
| 1375 |
+
|
| 1376 |
+
/*
|
| 1377 |
+
* Information about the iteration state.
|
| 1378 |
+
*/
|
| 1379 |
+
NpyIter_IterNextFunc *outer_next;
|
| 1380 |
+
char **outer_ptrs;
|
| 1381 |
+
npy_intp *outer_strides;
|
| 1382 |
+
|
| 1383 |
+
/*
|
| 1384 |
+
* Information about the subspace iterator.
|
| 1385 |
+
*/
|
| 1386 |
+
NpyIter *subspace_iter;
|
| 1387 |
+
NpyIter_IterNextFunc *subspace_next;
|
| 1388 |
+
char **subspace_ptrs;
|
| 1389 |
+
npy_intp *subspace_strides;
|
| 1390 |
+
|
| 1391 |
+
/* Count for the external loop (which ever it is) for API iteration */
|
| 1392 |
+
npy_intp iter_count;
|
| 1393 |
+
|
| 1394 |
+
} PyArrayMapIterObject;
|
| 1395 |
+
|
| 1396 |
+
enum {
|
| 1397 |
+
NPY_NEIGHBORHOOD_ITER_ZERO_PADDING,
|
| 1398 |
+
NPY_NEIGHBORHOOD_ITER_ONE_PADDING,
|
| 1399 |
+
NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING,
|
| 1400 |
+
NPY_NEIGHBORHOOD_ITER_CIRCULAR_PADDING,
|
| 1401 |
+
NPY_NEIGHBORHOOD_ITER_MIRROR_PADDING
|
| 1402 |
+
};
|
| 1403 |
+
|
| 1404 |
+
typedef struct {
|
| 1405 |
+
PyObject_HEAD
|
| 1406 |
+
|
| 1407 |
+
/*
|
| 1408 |
+
* PyArrayIterObject part: keep this in this exact order
|
| 1409 |
+
*/
|
| 1410 |
+
int nd_m1; /* number of dimensions - 1 */
|
| 1411 |
+
npy_intp index, size;
|
| 1412 |
+
npy_intp coordinates[NPY_MAXDIMS];/* N-dimensional loop */
|
| 1413 |
+
npy_intp dims_m1[NPY_MAXDIMS]; /* ao->dimensions - 1 */
|
| 1414 |
+
npy_intp strides[NPY_MAXDIMS]; /* ao->strides or fake */
|
| 1415 |
+
npy_intp backstrides[NPY_MAXDIMS];/* how far to jump back */
|
| 1416 |
+
npy_intp factors[NPY_MAXDIMS]; /* shape factors */
|
| 1417 |
+
PyArrayObject *ao;
|
| 1418 |
+
char *dataptr; /* pointer to current item*/
|
| 1419 |
+
npy_bool contiguous;
|
| 1420 |
+
|
| 1421 |
+
npy_intp bounds[NPY_MAXDIMS][2];
|
| 1422 |
+
npy_intp limits[NPY_MAXDIMS][2];
|
| 1423 |
+
npy_intp limits_sizes[NPY_MAXDIMS];
|
| 1424 |
+
npy_iter_get_dataptr_t translate;
|
| 1425 |
+
|
| 1426 |
+
/*
|
| 1427 |
+
* New members
|
| 1428 |
+
*/
|
| 1429 |
+
npy_intp nd;
|
| 1430 |
+
|
| 1431 |
+
/* Dimensions is the dimension of the array */
|
| 1432 |
+
npy_intp dimensions[NPY_MAXDIMS];
|
| 1433 |
+
|
| 1434 |
+
/*
|
| 1435 |
+
* Neighborhood points coordinates are computed relatively to the
|
| 1436 |
+
* point pointed by _internal_iter
|
| 1437 |
+
*/
|
| 1438 |
+
PyArrayIterObject* _internal_iter;
|
| 1439 |
+
/*
|
| 1440 |
+
* To keep a reference to the representation of the constant value
|
| 1441 |
+
* for constant padding
|
| 1442 |
+
*/
|
| 1443 |
+
char* constant;
|
| 1444 |
+
|
| 1445 |
+
int mode;
|
| 1446 |
+
} PyArrayNeighborhoodIterObject;
|
| 1447 |
+
|
| 1448 |
+
/*
|
| 1449 |
+
* Neighborhood iterator API
|
| 1450 |
+
*/
|
| 1451 |
+
|
| 1452 |
+
/* General: those work for any mode */
|
| 1453 |
+
static inline int
|
| 1454 |
+
PyArrayNeighborhoodIter_Reset(PyArrayNeighborhoodIterObject* iter);
|
| 1455 |
+
static inline int
|
| 1456 |
+
PyArrayNeighborhoodIter_Next(PyArrayNeighborhoodIterObject* iter);
|
| 1457 |
+
#if 0
|
| 1458 |
+
static inline int
|
| 1459 |
+
PyArrayNeighborhoodIter_Next2D(PyArrayNeighborhoodIterObject* iter);
|
| 1460 |
+
#endif
|
| 1461 |
+
|
| 1462 |
+
/*
|
| 1463 |
+
* Include inline implementations - functions defined there are not
|
| 1464 |
+
* considered public API
|
| 1465 |
+
*/
|
| 1466 |
+
#define NUMPY_CORE_INCLUDE_NUMPY__NEIGHBORHOOD_IMP_H_
|
| 1467 |
+
#include "_neighborhood_iterator_imp.h"
|
| 1468 |
+
#undef NUMPY_CORE_INCLUDE_NUMPY__NEIGHBORHOOD_IMP_H_
|
| 1469 |
+
|
| 1470 |
+
|
| 1471 |
+
|
| 1472 |
+
/* The default array type */
|
| 1473 |
+
#define NPY_DEFAULT_TYPE NPY_DOUBLE
|
| 1474 |
+
|
| 1475 |
+
/*
|
| 1476 |
+
* All sorts of useful ways to look into a PyArrayObject. It is recommended
|
| 1477 |
+
* to use PyArrayObject * objects instead of always casting from PyObject *,
|
| 1478 |
+
* for improved type checking.
|
| 1479 |
+
*
|
| 1480 |
+
* In many cases here the macro versions of the accessors are deprecated,
|
| 1481 |
+
* but can't be immediately changed to inline functions because the
|
| 1482 |
+
* preexisting macros accept PyObject * and do automatic casts. Inline
|
| 1483 |
+
* functions accepting PyArrayObject * provides for some compile-time
|
| 1484 |
+
* checking of correctness when working with these objects in C.
|
| 1485 |
+
*/
|
| 1486 |
+
|
| 1487 |
+
#define PyArray_ISONESEGMENT(m) (PyArray_CHKFLAGS(m, NPY_ARRAY_C_CONTIGUOUS) || \
|
| 1488 |
+
PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS))
|
| 1489 |
+
|
| 1490 |
+
#define PyArray_ISFORTRAN(m) (PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS) && \
|
| 1491 |
+
(!PyArray_CHKFLAGS(m, NPY_ARRAY_C_CONTIGUOUS)))
|
| 1492 |
+
|
| 1493 |
+
#define PyArray_FORTRAN_IF(m) ((PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS) ? \
|
| 1494 |
+
NPY_ARRAY_F_CONTIGUOUS : 0))
|
| 1495 |
+
|
| 1496 |
+
#if (defined(NPY_NO_DEPRECATED_API) && (NPY_1_7_API_VERSION <= NPY_NO_DEPRECATED_API))
|
| 1497 |
+
/*
|
| 1498 |
+
* Changing access macros into functions, to allow for future hiding
|
| 1499 |
+
* of the internal memory layout. This later hiding will allow the 2.x series
|
| 1500 |
+
* to change the internal representation of arrays without affecting
|
| 1501 |
+
* ABI compatibility.
|
| 1502 |
+
*/
|
| 1503 |
+
|
| 1504 |
+
static inline int
|
| 1505 |
+
PyArray_NDIM(const PyArrayObject *arr)
|
| 1506 |
+
{
|
| 1507 |
+
return ((PyArrayObject_fields *)arr)->nd;
|
| 1508 |
+
}
|
| 1509 |
+
|
| 1510 |
+
static inline void *
|
| 1511 |
+
PyArray_DATA(PyArrayObject *arr)
|
| 1512 |
+
{
|
| 1513 |
+
return ((PyArrayObject_fields *)arr)->data;
|
| 1514 |
+
}
|
| 1515 |
+
|
| 1516 |
+
static inline char *
|
| 1517 |
+
PyArray_BYTES(PyArrayObject *arr)
|
| 1518 |
+
{
|
| 1519 |
+
return ((PyArrayObject_fields *)arr)->data;
|
| 1520 |
+
}
|
| 1521 |
+
|
| 1522 |
+
static inline npy_intp *
|
| 1523 |
+
PyArray_DIMS(PyArrayObject *arr)
|
| 1524 |
+
{
|
| 1525 |
+
return ((PyArrayObject_fields *)arr)->dimensions;
|
| 1526 |
+
}
|
| 1527 |
+
|
| 1528 |
+
static inline npy_intp *
|
| 1529 |
+
PyArray_STRIDES(PyArrayObject *arr)
|
| 1530 |
+
{
|
| 1531 |
+
return ((PyArrayObject_fields *)arr)->strides;
|
| 1532 |
+
}
|
| 1533 |
+
|
| 1534 |
+
static inline npy_intp
|
| 1535 |
+
PyArray_DIM(const PyArrayObject *arr, int idim)
|
| 1536 |
+
{
|
| 1537 |
+
return ((PyArrayObject_fields *)arr)->dimensions[idim];
|
| 1538 |
+
}
|
| 1539 |
+
|
| 1540 |
+
static inline npy_intp
|
| 1541 |
+
PyArray_STRIDE(const PyArrayObject *arr, int istride)
|
| 1542 |
+
{
|
| 1543 |
+
return ((PyArrayObject_fields *)arr)->strides[istride];
|
| 1544 |
+
}
|
| 1545 |
+
|
| 1546 |
+
static inline NPY_RETURNS_BORROWED_REF PyObject *
|
| 1547 |
+
PyArray_BASE(PyArrayObject *arr)
|
| 1548 |
+
{
|
| 1549 |
+
return ((PyArrayObject_fields *)arr)->base;
|
| 1550 |
+
}
|
| 1551 |
+
|
| 1552 |
+
static inline NPY_RETURNS_BORROWED_REF PyArray_Descr *
|
| 1553 |
+
PyArray_DESCR(PyArrayObject *arr)
|
| 1554 |
+
{
|
| 1555 |
+
return ((PyArrayObject_fields *)arr)->descr;
|
| 1556 |
+
}
|
| 1557 |
+
|
| 1558 |
+
static inline int
|
| 1559 |
+
PyArray_FLAGS(const PyArrayObject *arr)
|
| 1560 |
+
{
|
| 1561 |
+
return ((PyArrayObject_fields *)arr)->flags;
|
| 1562 |
+
}
|
| 1563 |
+
|
| 1564 |
+
static inline npy_intp
|
| 1565 |
+
PyArray_ITEMSIZE(const PyArrayObject *arr)
|
| 1566 |
+
{
|
| 1567 |
+
return ((PyArrayObject_fields *)arr)->descr->elsize;
|
| 1568 |
+
}
|
| 1569 |
+
|
| 1570 |
+
static inline int
|
| 1571 |
+
PyArray_TYPE(const PyArrayObject *arr)
|
| 1572 |
+
{
|
| 1573 |
+
return ((PyArrayObject_fields *)arr)->descr->type_num;
|
| 1574 |
+
}
|
| 1575 |
+
|
| 1576 |
+
static inline int
|
| 1577 |
+
PyArray_CHKFLAGS(const PyArrayObject *arr, int flags)
|
| 1578 |
+
{
|
| 1579 |
+
return (PyArray_FLAGS(arr) & flags) == flags;
|
| 1580 |
+
}
|
| 1581 |
+
|
| 1582 |
+
static inline PyObject *
|
| 1583 |
+
PyArray_GETITEM(const PyArrayObject *arr, const char *itemptr)
|
| 1584 |
+
{
|
| 1585 |
+
return ((PyArrayObject_fields *)arr)->descr->f->getitem(
|
| 1586 |
+
(void *)itemptr, (PyArrayObject *)arr);
|
| 1587 |
+
}
|
| 1588 |
+
|
| 1589 |
+
/*
|
| 1590 |
+
* SETITEM should only be used if it is known that the value is a scalar
|
| 1591 |
+
* and of a type understood by the arrays dtype.
|
| 1592 |
+
* Use `PyArray_Pack` if the value may be of a different dtype.
|
| 1593 |
+
*/
|
| 1594 |
+
static inline int
|
| 1595 |
+
PyArray_SETITEM(PyArrayObject *arr, char *itemptr, PyObject *v)
|
| 1596 |
+
{
|
| 1597 |
+
return ((PyArrayObject_fields *)arr)->descr->f->setitem(v, itemptr, arr);
|
| 1598 |
+
}
|
| 1599 |
+
|
| 1600 |
+
#else
|
| 1601 |
+
|
| 1602 |
+
/* These macros are deprecated as of NumPy 1.7. */
|
| 1603 |
+
#define PyArray_NDIM(obj) (((PyArrayObject_fields *)(obj))->nd)
|
| 1604 |
+
#define PyArray_BYTES(obj) (((PyArrayObject_fields *)(obj))->data)
|
| 1605 |
+
#define PyArray_DATA(obj) ((void *)((PyArrayObject_fields *)(obj))->data)
|
| 1606 |
+
#define PyArray_DIMS(obj) (((PyArrayObject_fields *)(obj))->dimensions)
|
| 1607 |
+
#define PyArray_STRIDES(obj) (((PyArrayObject_fields *)(obj))->strides)
|
| 1608 |
+
#define PyArray_DIM(obj,n) (PyArray_DIMS(obj)[n])
|
| 1609 |
+
#define PyArray_STRIDE(obj,n) (PyArray_STRIDES(obj)[n])
|
| 1610 |
+
#define PyArray_BASE(obj) (((PyArrayObject_fields *)(obj))->base)
|
| 1611 |
+
#define PyArray_DESCR(obj) (((PyArrayObject_fields *)(obj))->descr)
|
| 1612 |
+
#define PyArray_FLAGS(obj) (((PyArrayObject_fields *)(obj))->flags)
|
| 1613 |
+
#define PyArray_CHKFLAGS(m, FLAGS) \
|
| 1614 |
+
((((PyArrayObject_fields *)(m))->flags & (FLAGS)) == (FLAGS))
|
| 1615 |
+
#define PyArray_ITEMSIZE(obj) \
|
| 1616 |
+
(((PyArrayObject_fields *)(obj))->descr->elsize)
|
| 1617 |
+
#define PyArray_TYPE(obj) \
|
| 1618 |
+
(((PyArrayObject_fields *)(obj))->descr->type_num)
|
| 1619 |
+
#define PyArray_GETITEM(obj,itemptr) \
|
| 1620 |
+
PyArray_DESCR(obj)->f->getitem((char *)(itemptr), \
|
| 1621 |
+
(PyArrayObject *)(obj))
|
| 1622 |
+
|
| 1623 |
+
#define PyArray_SETITEM(obj,itemptr,v) \
|
| 1624 |
+
PyArray_DESCR(obj)->f->setitem((PyObject *)(v), \
|
| 1625 |
+
(char *)(itemptr), \
|
| 1626 |
+
(PyArrayObject *)(obj))
|
| 1627 |
+
#endif
|
| 1628 |
+
|
| 1629 |
+
static inline PyArray_Descr *
|
| 1630 |
+
PyArray_DTYPE(PyArrayObject *arr)
|
| 1631 |
+
{
|
| 1632 |
+
return ((PyArrayObject_fields *)arr)->descr;
|
| 1633 |
+
}
|
| 1634 |
+
|
| 1635 |
+
static inline npy_intp *
|
| 1636 |
+
PyArray_SHAPE(PyArrayObject *arr)
|
| 1637 |
+
{
|
| 1638 |
+
return ((PyArrayObject_fields *)arr)->dimensions;
|
| 1639 |
+
}
|
| 1640 |
+
|
| 1641 |
+
/*
|
| 1642 |
+
* Enables the specified array flags. Does no checking,
|
| 1643 |
+
* assumes you know what you're doing.
|
| 1644 |
+
*/
|
| 1645 |
+
static inline void
|
| 1646 |
+
PyArray_ENABLEFLAGS(PyArrayObject *arr, int flags)
|
| 1647 |
+
{
|
| 1648 |
+
((PyArrayObject_fields *)arr)->flags |= flags;
|
| 1649 |
+
}
|
| 1650 |
+
|
| 1651 |
+
/*
|
| 1652 |
+
* Clears the specified array flags. Does no checking,
|
| 1653 |
+
* assumes you know what you're doing.
|
| 1654 |
+
*/
|
| 1655 |
+
static inline void
|
| 1656 |
+
PyArray_CLEARFLAGS(PyArrayObject *arr, int flags)
|
| 1657 |
+
{
|
| 1658 |
+
((PyArrayObject_fields *)arr)->flags &= ~flags;
|
| 1659 |
+
}
|
| 1660 |
+
|
| 1661 |
+
#if NPY_FEATURE_VERSION >= NPY_1_22_API_VERSION
|
| 1662 |
+
static inline NPY_RETURNS_BORROWED_REF PyObject *
|
| 1663 |
+
PyArray_HANDLER(PyArrayObject *arr)
|
| 1664 |
+
{
|
| 1665 |
+
return ((PyArrayObject_fields *)arr)->mem_handler;
|
| 1666 |
+
}
|
| 1667 |
+
#endif
|
| 1668 |
+
|
| 1669 |
+
#define PyTypeNum_ISBOOL(type) ((type) == NPY_BOOL)
|
| 1670 |
+
|
| 1671 |
+
#define PyTypeNum_ISUNSIGNED(type) (((type) == NPY_UBYTE) || \
|
| 1672 |
+
((type) == NPY_USHORT) || \
|
| 1673 |
+
((type) == NPY_UINT) || \
|
| 1674 |
+
((type) == NPY_ULONG) || \
|
| 1675 |
+
((type) == NPY_ULONGLONG))
|
| 1676 |
+
|
| 1677 |
+
#define PyTypeNum_ISSIGNED(type) (((type) == NPY_BYTE) || \
|
| 1678 |
+
((type) == NPY_SHORT) || \
|
| 1679 |
+
((type) == NPY_INT) || \
|
| 1680 |
+
((type) == NPY_LONG) || \
|
| 1681 |
+
((type) == NPY_LONGLONG))
|
| 1682 |
+
|
| 1683 |
+
#define PyTypeNum_ISINTEGER(type) (((type) >= NPY_BYTE) && \
|
| 1684 |
+
((type) <= NPY_ULONGLONG))
|
| 1685 |
+
|
| 1686 |
+
#define PyTypeNum_ISFLOAT(type) ((((type) >= NPY_FLOAT) && \
|
| 1687 |
+
((type) <= NPY_LONGDOUBLE)) || \
|
| 1688 |
+
((type) == NPY_HALF))
|
| 1689 |
+
|
| 1690 |
+
#define PyTypeNum_ISNUMBER(type) (((type) <= NPY_CLONGDOUBLE) || \
|
| 1691 |
+
((type) == NPY_HALF))
|
| 1692 |
+
|
| 1693 |
+
#define PyTypeNum_ISSTRING(type) (((type) == NPY_STRING) || \
|
| 1694 |
+
((type) == NPY_UNICODE))
|
| 1695 |
+
|
| 1696 |
+
#define PyTypeNum_ISCOMPLEX(type) (((type) >= NPY_CFLOAT) && \
|
| 1697 |
+
((type) <= NPY_CLONGDOUBLE))
|
| 1698 |
+
|
| 1699 |
+
#define PyTypeNum_ISPYTHON(type) (((type) == NPY_LONG) || \
|
| 1700 |
+
((type) == NPY_DOUBLE) || \
|
| 1701 |
+
((type) == NPY_CDOUBLE) || \
|
| 1702 |
+
((type) == NPY_BOOL) || \
|
| 1703 |
+
((type) == NPY_OBJECT ))
|
| 1704 |
+
|
| 1705 |
+
#define PyTypeNum_ISFLEXIBLE(type) (((type) >=NPY_STRING) && \
|
| 1706 |
+
((type) <=NPY_VOID))
|
| 1707 |
+
|
| 1708 |
+
#define PyTypeNum_ISDATETIME(type) (((type) >=NPY_DATETIME) && \
|
| 1709 |
+
((type) <=NPY_TIMEDELTA))
|
| 1710 |
+
|
| 1711 |
+
#define PyTypeNum_ISUSERDEF(type) (((type) >= NPY_USERDEF) && \
|
| 1712 |
+
((type) < NPY_USERDEF+ \
|
| 1713 |
+
NPY_NUMUSERTYPES))
|
| 1714 |
+
|
| 1715 |
+
#define PyTypeNum_ISEXTENDED(type) (PyTypeNum_ISFLEXIBLE(type) || \
|
| 1716 |
+
PyTypeNum_ISUSERDEF(type))
|
| 1717 |
+
|
| 1718 |
+
#define PyTypeNum_ISOBJECT(type) ((type) == NPY_OBJECT)
|
| 1719 |
+
|
| 1720 |
+
|
| 1721 |
+
#define PyDataType_ISBOOL(obj) PyTypeNum_ISBOOL(((PyArray_Descr*)(obj))->type_num)
|
| 1722 |
+
#define PyDataType_ISUNSIGNED(obj) PyTypeNum_ISUNSIGNED(((PyArray_Descr*)(obj))->type_num)
|
| 1723 |
+
#define PyDataType_ISSIGNED(obj) PyTypeNum_ISSIGNED(((PyArray_Descr*)(obj))->type_num)
|
| 1724 |
+
#define PyDataType_ISINTEGER(obj) PyTypeNum_ISINTEGER(((PyArray_Descr*)(obj))->type_num )
|
| 1725 |
+
#define PyDataType_ISFLOAT(obj) PyTypeNum_ISFLOAT(((PyArray_Descr*)(obj))->type_num)
|
| 1726 |
+
#define PyDataType_ISNUMBER(obj) PyTypeNum_ISNUMBER(((PyArray_Descr*)(obj))->type_num)
|
| 1727 |
+
#define PyDataType_ISSTRING(obj) PyTypeNum_ISSTRING(((PyArray_Descr*)(obj))->type_num)
|
| 1728 |
+
#define PyDataType_ISCOMPLEX(obj) PyTypeNum_ISCOMPLEX(((PyArray_Descr*)(obj))->type_num)
|
| 1729 |
+
#define PyDataType_ISPYTHON(obj) PyTypeNum_ISPYTHON(((PyArray_Descr*)(obj))->type_num)
|
| 1730 |
+
#define PyDataType_ISFLEXIBLE(obj) PyTypeNum_ISFLEXIBLE(((PyArray_Descr*)(obj))->type_num)
|
| 1731 |
+
#define PyDataType_ISDATETIME(obj) PyTypeNum_ISDATETIME(((PyArray_Descr*)(obj))->type_num)
|
| 1732 |
+
#define PyDataType_ISUSERDEF(obj) PyTypeNum_ISUSERDEF(((PyArray_Descr*)(obj))->type_num)
|
| 1733 |
+
#define PyDataType_ISEXTENDED(obj) PyTypeNum_ISEXTENDED(((PyArray_Descr*)(obj))->type_num)
|
| 1734 |
+
#define PyDataType_ISOBJECT(obj) PyTypeNum_ISOBJECT(((PyArray_Descr*)(obj))->type_num)
|
| 1735 |
+
#define PyDataType_HASFIELDS(obj) (((PyArray_Descr *)(obj))->names != NULL)
|
| 1736 |
+
#define PyDataType_HASSUBARRAY(dtype) ((dtype)->subarray != NULL)
|
| 1737 |
+
#define PyDataType_ISUNSIZED(dtype) ((dtype)->elsize == 0 && \
|
| 1738 |
+
!PyDataType_HASFIELDS(dtype))
|
| 1739 |
+
#define PyDataType_MAKEUNSIZED(dtype) ((dtype)->elsize = 0)
|
| 1740 |
+
|
| 1741 |
+
#define PyArray_ISBOOL(obj) PyTypeNum_ISBOOL(PyArray_TYPE(obj))
|
| 1742 |
+
#define PyArray_ISUNSIGNED(obj) PyTypeNum_ISUNSIGNED(PyArray_TYPE(obj))
|
| 1743 |
+
#define PyArray_ISSIGNED(obj) PyTypeNum_ISSIGNED(PyArray_TYPE(obj))
|
| 1744 |
+
#define PyArray_ISINTEGER(obj) PyTypeNum_ISINTEGER(PyArray_TYPE(obj))
|
| 1745 |
+
#define PyArray_ISFLOAT(obj) PyTypeNum_ISFLOAT(PyArray_TYPE(obj))
|
| 1746 |
+
#define PyArray_ISNUMBER(obj) PyTypeNum_ISNUMBER(PyArray_TYPE(obj))
|
| 1747 |
+
#define PyArray_ISSTRING(obj) PyTypeNum_ISSTRING(PyArray_TYPE(obj))
|
| 1748 |
+
#define PyArray_ISCOMPLEX(obj) PyTypeNum_ISCOMPLEX(PyArray_TYPE(obj))
|
| 1749 |
+
#define PyArray_ISPYTHON(obj) PyTypeNum_ISPYTHON(PyArray_TYPE(obj))
|
| 1750 |
+
#define PyArray_ISFLEXIBLE(obj) PyTypeNum_ISFLEXIBLE(PyArray_TYPE(obj))
|
| 1751 |
+
#define PyArray_ISDATETIME(obj) PyTypeNum_ISDATETIME(PyArray_TYPE(obj))
|
| 1752 |
+
#define PyArray_ISUSERDEF(obj) PyTypeNum_ISUSERDEF(PyArray_TYPE(obj))
|
| 1753 |
+
#define PyArray_ISEXTENDED(obj) PyTypeNum_ISEXTENDED(PyArray_TYPE(obj))
|
| 1754 |
+
#define PyArray_ISOBJECT(obj) PyTypeNum_ISOBJECT(PyArray_TYPE(obj))
|
| 1755 |
+
#define PyArray_HASFIELDS(obj) PyDataType_HASFIELDS(PyArray_DESCR(obj))
|
| 1756 |
+
|
| 1757 |
+
/*
|
| 1758 |
+
* FIXME: This should check for a flag on the data-type that
|
| 1759 |
+
* states whether or not it is variable length. Because the
|
| 1760 |
+
* ISFLEXIBLE check is hard-coded to the built-in data-types.
|
| 1761 |
+
*/
|
| 1762 |
+
#define PyArray_ISVARIABLE(obj) PyTypeNum_ISFLEXIBLE(PyArray_TYPE(obj))
|
| 1763 |
+
|
| 1764 |
+
#define PyArray_SAFEALIGNEDCOPY(obj) (PyArray_ISALIGNED(obj) && !PyArray_ISVARIABLE(obj))
|
| 1765 |
+
|
| 1766 |
+
|
| 1767 |
+
#define NPY_LITTLE '<'
|
| 1768 |
+
#define NPY_BIG '>'
|
| 1769 |
+
#define NPY_NATIVE '='
|
| 1770 |
+
#define NPY_SWAP 's'
|
| 1771 |
+
#define NPY_IGNORE '|'
|
| 1772 |
+
|
| 1773 |
+
#if NPY_BYTE_ORDER == NPY_BIG_ENDIAN
|
| 1774 |
+
#define NPY_NATBYTE NPY_BIG
|
| 1775 |
+
#define NPY_OPPBYTE NPY_LITTLE
|
| 1776 |
+
#else
|
| 1777 |
+
#define NPY_NATBYTE NPY_LITTLE
|
| 1778 |
+
#define NPY_OPPBYTE NPY_BIG
|
| 1779 |
+
#endif
|
| 1780 |
+
|
| 1781 |
+
#define PyArray_ISNBO(arg) ((arg) != NPY_OPPBYTE)
|
| 1782 |
+
#define PyArray_IsNativeByteOrder PyArray_ISNBO
|
| 1783 |
+
#define PyArray_ISNOTSWAPPED(m) PyArray_ISNBO(PyArray_DESCR(m)->byteorder)
|
| 1784 |
+
#define PyArray_ISBYTESWAPPED(m) (!PyArray_ISNOTSWAPPED(m))
|
| 1785 |
+
|
| 1786 |
+
#define PyArray_FLAGSWAP(m, flags) (PyArray_CHKFLAGS(m, flags) && \
|
| 1787 |
+
PyArray_ISNOTSWAPPED(m))
|
| 1788 |
+
|
| 1789 |
+
#define PyArray_ISCARRAY(m) PyArray_FLAGSWAP(m, NPY_ARRAY_CARRAY)
|
| 1790 |
+
#define PyArray_ISCARRAY_RO(m) PyArray_FLAGSWAP(m, NPY_ARRAY_CARRAY_RO)
|
| 1791 |
+
#define PyArray_ISFARRAY(m) PyArray_FLAGSWAP(m, NPY_ARRAY_FARRAY)
|
| 1792 |
+
#define PyArray_ISFARRAY_RO(m) PyArray_FLAGSWAP(m, NPY_ARRAY_FARRAY_RO)
|
| 1793 |
+
#define PyArray_ISBEHAVED(m) PyArray_FLAGSWAP(m, NPY_ARRAY_BEHAVED)
|
| 1794 |
+
#define PyArray_ISBEHAVED_RO(m) PyArray_FLAGSWAP(m, NPY_ARRAY_ALIGNED)
|
| 1795 |
+
|
| 1796 |
+
|
| 1797 |
+
#define PyDataType_ISNOTSWAPPED(d) PyArray_ISNBO(((PyArray_Descr *)(d))->byteorder)
|
| 1798 |
+
#define PyDataType_ISBYTESWAPPED(d) (!PyDataType_ISNOTSWAPPED(d))
|
| 1799 |
+
|
| 1800 |
+
/************************************************************
|
| 1801 |
+
* A struct used by PyArray_CreateSortedStridePerm, new in 1.7.
|
| 1802 |
+
************************************************************/
|
| 1803 |
+
|
| 1804 |
+
typedef struct {
|
| 1805 |
+
npy_intp perm, stride;
|
| 1806 |
+
} npy_stride_sort_item;
|
| 1807 |
+
|
| 1808 |
+
/************************************************************
|
| 1809 |
+
* This is the form of the struct that's stored in the
|
| 1810 |
+
* PyCapsule returned by an array's __array_struct__ attribute. See
|
| 1811 |
+
* https://docs.scipy.org/doc/numpy/reference/arrays.interface.html for the full
|
| 1812 |
+
* documentation.
|
| 1813 |
+
************************************************************/
|
| 1814 |
+
typedef struct {
|
| 1815 |
+
int two; /*
|
| 1816 |
+
* contains the integer 2 as a sanity
|
| 1817 |
+
* check
|
| 1818 |
+
*/
|
| 1819 |
+
|
| 1820 |
+
int nd; /* number of dimensions */
|
| 1821 |
+
|
| 1822 |
+
char typekind; /*
|
| 1823 |
+
* kind in array --- character code of
|
| 1824 |
+
* typestr
|
| 1825 |
+
*/
|
| 1826 |
+
|
| 1827 |
+
int itemsize; /* size of each element */
|
| 1828 |
+
|
| 1829 |
+
int flags; /*
|
| 1830 |
+
* how should be data interpreted. Valid
|
| 1831 |
+
* flags are CONTIGUOUS (1), F_CONTIGUOUS (2),
|
| 1832 |
+
* ALIGNED (0x100), NOTSWAPPED (0x200), and
|
| 1833 |
+
* WRITEABLE (0x400). ARR_HAS_DESCR (0x800)
|
| 1834 |
+
* states that arrdescr field is present in
|
| 1835 |
+
* structure
|
| 1836 |
+
*/
|
| 1837 |
+
|
| 1838 |
+
npy_intp *shape; /*
|
| 1839 |
+
* A length-nd array of shape
|
| 1840 |
+
* information
|
| 1841 |
+
*/
|
| 1842 |
+
|
| 1843 |
+
npy_intp *strides; /* A length-nd array of stride information */
|
| 1844 |
+
|
| 1845 |
+
void *data; /* A pointer to the first element of the array */
|
| 1846 |
+
|
| 1847 |
+
PyObject *descr; /*
|
| 1848 |
+
* A list of fields or NULL (ignored if flags
|
| 1849 |
+
* does not have ARR_HAS_DESCR flag set)
|
| 1850 |
+
*/
|
| 1851 |
+
} PyArrayInterface;
|
| 1852 |
+
|
| 1853 |
+
/*
|
| 1854 |
+
* This is a function for hooking into the PyDataMem_NEW/FREE/RENEW functions.
|
| 1855 |
+
* See the documentation for PyDataMem_SetEventHook.
|
| 1856 |
+
*/
|
| 1857 |
+
typedef void (PyDataMem_EventHookFunc)(void *inp, void *outp, size_t size,
|
| 1858 |
+
void *user_data);
|
| 1859 |
+
|
| 1860 |
+
|
| 1861 |
+
/*
|
| 1862 |
+
* PyArray_DTypeMeta related definitions.
|
| 1863 |
+
*
|
| 1864 |
+
* As of now, this API is preliminary and will be extended as necessary.
|
| 1865 |
+
*/
|
| 1866 |
+
#if defined(NPY_INTERNAL_BUILD) && NPY_INTERNAL_BUILD
|
| 1867 |
+
/*
|
| 1868 |
+
* The Structures defined in this block are currently considered
|
| 1869 |
+
* private API and may change without warning!
|
| 1870 |
+
* Part of this (at least the size) is expected to be public API without
|
| 1871 |
+
* further modifications.
|
| 1872 |
+
*/
|
| 1873 |
+
/* TODO: Make this definition public in the API, as soon as its settled */
|
| 1874 |
+
NPY_NO_EXPORT extern PyTypeObject PyArrayDTypeMeta_Type;
|
| 1875 |
+
|
| 1876 |
+
/*
|
| 1877 |
+
* While NumPy DTypes would not need to be heap types the plan is to
|
| 1878 |
+
* make DTypes available in Python at which point they will be heap types.
|
| 1879 |
+
* Since we also wish to add fields to the DType class, this looks like
|
| 1880 |
+
* a typical instance definition, but with PyHeapTypeObject instead of
|
| 1881 |
+
* only the PyObject_HEAD.
|
| 1882 |
+
* This must only be exposed very extremely careful consideration, since
|
| 1883 |
+
* it is a fairly complex construct which may be better to allow
|
| 1884 |
+
* refactoring of.
|
| 1885 |
+
*/
|
| 1886 |
+
typedef struct {
|
| 1887 |
+
PyHeapTypeObject super;
|
| 1888 |
+
|
| 1889 |
+
/*
|
| 1890 |
+
* Most DTypes will have a singleton default instance, for the
|
| 1891 |
+
* parametric legacy DTypes (bytes, string, void, datetime) this
|
| 1892 |
+
* may be a pointer to the *prototype* instance?
|
| 1893 |
+
*/
|
| 1894 |
+
PyArray_Descr *singleton;
|
| 1895 |
+
/* Copy of the legacy DTypes type number, usually invalid. */
|
| 1896 |
+
int type_num;
|
| 1897 |
+
|
| 1898 |
+
/* The type object of the scalar instances (may be NULL?) */
|
| 1899 |
+
PyTypeObject *scalar_type;
|
| 1900 |
+
/*
|
| 1901 |
+
* DType flags to signal legacy, parametric, or
|
| 1902 |
+
* abstract. But plenty of space for additional information/flags.
|
| 1903 |
+
*/
|
| 1904 |
+
npy_uint64 flags;
|
| 1905 |
+
|
| 1906 |
+
/*
|
| 1907 |
+
* Use indirection in order to allow a fixed size for this struct.
|
| 1908 |
+
* A stable ABI size makes creating a static DType less painful
|
| 1909 |
+
* while also ensuring flexibility for all opaque API (with one
|
| 1910 |
+
* indirection due the pointer lookup).
|
| 1911 |
+
*/
|
| 1912 |
+
void *dt_slots;
|
| 1913 |
+
void *reserved[3];
|
| 1914 |
+
} PyArray_DTypeMeta;
|
| 1915 |
+
|
| 1916 |
+
#endif /* NPY_INTERNAL_BUILD */
|
| 1917 |
+
|
| 1918 |
+
|
| 1919 |
+
/*
|
| 1920 |
+
* Use the keyword NPY_DEPRECATED_INCLUDES to ensure that the header files
|
| 1921 |
+
* npy_*_*_deprecated_api.h are only included from here and nowhere else.
|
| 1922 |
+
*/
|
| 1923 |
+
#ifdef NPY_DEPRECATED_INCLUDES
|
| 1924 |
+
#error "Do not use the reserved keyword NPY_DEPRECATED_INCLUDES."
|
| 1925 |
+
#endif
|
| 1926 |
+
#define NPY_DEPRECATED_INCLUDES
|
| 1927 |
+
#if !defined(NPY_NO_DEPRECATED_API) || \
|
| 1928 |
+
(NPY_NO_DEPRECATED_API < NPY_1_7_API_VERSION)
|
| 1929 |
+
#include "npy_1_7_deprecated_api.h"
|
| 1930 |
+
#endif
|
| 1931 |
+
/*
|
| 1932 |
+
* There is no file npy_1_8_deprecated_api.h since there are no additional
|
| 1933 |
+
* deprecated API features in NumPy 1.8.
|
| 1934 |
+
*
|
| 1935 |
+
* Note to maintainers: insert code like the following in future NumPy
|
| 1936 |
+
* versions.
|
| 1937 |
+
*
|
| 1938 |
+
* #if !defined(NPY_NO_DEPRECATED_API) || \
|
| 1939 |
+
* (NPY_NO_DEPRECATED_API < NPY_1_9_API_VERSION)
|
| 1940 |
+
* #include "npy_1_9_deprecated_api.h"
|
| 1941 |
+
* #endif
|
| 1942 |
+
*/
|
| 1943 |
+
#undef NPY_DEPRECATED_INCLUDES
|
| 1944 |
+
|
| 1945 |
+
#endif /* NUMPY_CORE_INCLUDE_NUMPY_NDARRAYTYPES_H_ */
|
shared/package-files/12/123b7a693e43807904553369db80760123d0b01a3dfc9e8a259fbab196f5b2bb/arima112nc_results.py
ADDED
|
@@ -0,0 +1,1099 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from statsmodels.tools.tools import Bunch
|
| 4 |
+
|
| 5 |
+
llf = np.array([-240.79351748413])
|
| 6 |
+
|
| 7 |
+
nobs = np.array([202])
|
| 8 |
+
|
| 9 |
+
k = np.array([4])
|
| 10 |
+
|
| 11 |
+
k_exog = np.array([1])
|
| 12 |
+
|
| 13 |
+
sigma = np.array([.79349479007541])
|
| 14 |
+
|
| 15 |
+
chi2 = np.array([31643.977146904])
|
| 16 |
+
|
| 17 |
+
df_model = np.array([3])
|
| 18 |
+
|
| 19 |
+
k_ar = np.array([1])
|
| 20 |
+
|
| 21 |
+
k_ma = np.array([2])
|
| 22 |
+
|
| 23 |
+
params = np.array([
|
| 24 |
+
.99502750401315,
|
| 25 |
+
-.68630179255403,
|
| 26 |
+
-.19840894739396,
|
| 27 |
+
.79349479007541])
|
| 28 |
+
|
| 29 |
+
cov_params = np.array([
|
| 30 |
+
.00010016992219,
|
| 31 |
+
-.00021444523598,
|
| 32 |
+
-.00023305572854,
|
| 33 |
+
-6.768123591e-06,
|
| 34 |
+
-.00021444523598,
|
| 35 |
+
.00104186449549,
|
| 36 |
+
.00023669747281,
|
| 37 |
+
3.902897504e-06,
|
| 38 |
+
-.00023305572854,
|
| 39 |
+
.00023669747281,
|
| 40 |
+
.0010810935718,
|
| 41 |
+
.00020764808165,
|
| 42 |
+
-6.768123591e-06,
|
| 43 |
+
3.902897504e-06,
|
| 44 |
+
.00020764808165,
|
| 45 |
+
.0002668504612]).reshape(4, 4)
|
| 46 |
+
|
| 47 |
+
xb = np.array([
|
| 48 |
+
0,
|
| 49 |
+
0,
|
| 50 |
+
.11361486464739,
|
| 51 |
+
.14230862259865,
|
| 52 |
+
.07256115227938,
|
| 53 |
+
.13274206221104,
|
| 54 |
+
.06747215241194,
|
| 55 |
+
.13822889328003,
|
| 56 |
+
.09585004299879,
|
| 57 |
+
.06099047139287,
|
| 58 |
+
.10120190680027,
|
| 59 |
+
.07761032879353,
|
| 60 |
+
.07942545413971,
|
| 61 |
+
.11177492141724,
|
| 62 |
+
.06088993698359,
|
| 63 |
+
.11208334565163,
|
| 64 |
+
.0755797252059,
|
| 65 |
+
.07422959059477,
|
| 66 |
+
.12350624799728,
|
| 67 |
+
.07623053342104,
|
| 68 |
+
.12391770631075,
|
| 69 |
+
.06531815230846,
|
| 70 |
+
.08897981792688,
|
| 71 |
+
.09103457629681,
|
| 72 |
+
.10980048775673,
|
| 73 |
+
.09255626052618,
|
| 74 |
+
.12732291221619,
|
| 75 |
+
.08764986693859,
|
| 76 |
+
.14262486994267,
|
| 77 |
+
.19330270588398,
|
| 78 |
+
.13410428166389,
|
| 79 |
+
.2202503234148,
|
| 80 |
+
.1138079687953,
|
| 81 |
+
.17364008724689,
|
| 82 |
+
.19471970200539,
|
| 83 |
+
.20120698213577,
|
| 84 |
+
.24072274565697,
|
| 85 |
+
.21839858591557,
|
| 86 |
+
.29251739382744,
|
| 87 |
+
.26838713884354,
|
| 88 |
+
.28637075424194,
|
| 89 |
+
.3556769490242,
|
| 90 |
+
.33624804019928,
|
| 91 |
+
.35650280117989,
|
| 92 |
+
.3974232673645,
|
| 93 |
+
.40968126058578,
|
| 94 |
+
.36446389555931,
|
| 95 |
+
.40641778707504,
|
| 96 |
+
.40639826655388,
|
| 97 |
+
.32208651304245,
|
| 98 |
+
.41636437177658,
|
| 99 |
+
.34307014942169,
|
| 100 |
+
.3511538207531,
|
| 101 |
+
.34216031432152,
|
| 102 |
+
.33759200572968,
|
| 103 |
+
.36354607343674,
|
| 104 |
+
.39148297905922,
|
| 105 |
+
.55032896995544,
|
| 106 |
+
.4113195836544,
|
| 107 |
+
.7244918346405,
|
| 108 |
+
.67152947187424,
|
| 109 |
+
.76787060499191,
|
| 110 |
+
.77276849746704,
|
| 111 |
+
.96944856643677,
|
| 112 |
+
.88270664215088,
|
| 113 |
+
.7563271522522,
|
| 114 |
+
.86404490470886,
|
| 115 |
+
.82250237464905,
|
| 116 |
+
.83520317077637,
|
| 117 |
+
.65044301748276,
|
| 118 |
+
.83044308423996,
|
| 119 |
+
.79827356338501,
|
| 120 |
+
.78103590011597,
|
| 121 |
+
.93702721595764,
|
| 122 |
+
.78709679841995,
|
| 123 |
+
.81435388326645,
|
| 124 |
+
.89593154191971,
|
| 125 |
+
.92867535352707,
|
| 126 |
+
1.0709822177887,
|
| 127 |
+
1.0957812070847,
|
| 128 |
+
1.0792914628983,
|
| 129 |
+
1.3286831378937,
|
| 130 |
+
1.4503024816513,
|
| 131 |
+
1.4619816541672,
|
| 132 |
+
1.7190475463867,
|
| 133 |
+
1.8096150159836,
|
| 134 |
+
1.5324629545212,
|
| 135 |
+
1.721804857254,
|
| 136 |
+
1.8408879041672,
|
| 137 |
+
1.6955831050873,
|
| 138 |
+
1.8928952217102,
|
| 139 |
+
1.7459137439728,
|
| 140 |
+
1.5055395364761,
|
| 141 |
+
1.3664853572845,
|
| 142 |
+
1.8893030881882,
|
| 143 |
+
1.256967663765,
|
| 144 |
+
1.0567245483398,
|
| 145 |
+
1.2921603918076,
|
| 146 |
+
1.2266329526901,
|
| 147 |
+
1.2085332870483,
|
| 148 |
+
1.275726556778,
|
| 149 |
+
1.2278587818146,
|
| 150 |
+
1.1046848297119,
|
| 151 |
+
1.1517647504807,
|
| 152 |
+
.99646359682083,
|
| 153 |
+
1.194694519043,
|
| 154 |
+
.97580307722092,
|
| 155 |
+
1.0148292779922,
|
| 156 |
+
1.1635760068893,
|
| 157 |
+
.35167038440704,
|
| 158 |
+
.95728904008865,
|
| 159 |
+
.78414303064346,
|
| 160 |
+
.95968008041382,
|
| 161 |
+
.97746151685715,
|
| 162 |
+
.94291216135025,
|
| 163 |
+
.99327826499939,
|
| 164 |
+
.93940645456314,
|
| 165 |
+
1.013852596283,
|
| 166 |
+
1.0454497337341,
|
| 167 |
+
1.0929356813431,
|
| 168 |
+
1.0810794830322,
|
| 169 |
+
1.2874436378479,
|
| 170 |
+
1.1533098220825,
|
| 171 |
+
1.0470397472382,
|
| 172 |
+
1.4171674251556,
|
| 173 |
+
1.1959022283554,
|
| 174 |
+
1.3181202411652,
|
| 175 |
+
1.7197531461716,
|
| 176 |
+
1.2677561044693,
|
| 177 |
+
1.0768386125565,
|
| 178 |
+
1.2508004903793,
|
| 179 |
+
1.1625586748123,
|
| 180 |
+
1.1872273683548,
|
| 181 |
+
1.1668027639389,
|
| 182 |
+
1.1576874256134,
|
| 183 |
+
1.1782459020615,
|
| 184 |
+
1.1398378610611,
|
| 185 |
+
1.1065219640732,
|
| 186 |
+
1.0032601356506,
|
| 187 |
+
1.1087976694107,
|
| 188 |
+
.95788156986237,
|
| 189 |
+
1.0163568258286,
|
| 190 |
+
1.079482793808,
|
| 191 |
+
1.0131409168243,
|
| 192 |
+
1.0506906509399,
|
| 193 |
+
1.1052004098892,
|
| 194 |
+
.95601671934128,
|
| 195 |
+
.99452114105225,
|
| 196 |
+
1.0641269683838,
|
| 197 |
+
1.1217628717422,
|
| 198 |
+
.98107707500458,
|
| 199 |
+
1.0877858400345,
|
| 200 |
+
1.0735836029053,
|
| 201 |
+
.86890149116516,
|
| 202 |
+
.86449563503265,
|
| 203 |
+
1.0060983896255,
|
| 204 |
+
.79812264442444,
|
| 205 |
+
.70991164445877,
|
| 206 |
+
.91461282968521,
|
| 207 |
+
.78625136613846,
|
| 208 |
+
.8291689157486,
|
| 209 |
+
.93680161237717,
|
| 210 |
+
.81633454561234,
|
| 211 |
+
1.0196126699448,
|
| 212 |
+
.95442569255829,
|
| 213 |
+
1.1131925582886,
|
| 214 |
+
1.1916073560715,
|
| 215 |
+
1.05200278759,
|
| 216 |
+
1.2451642751694,
|
| 217 |
+
.97296446561813,
|
| 218 |
+
1.0647999048233,
|
| 219 |
+
.78715896606445,
|
| 220 |
+
.74267995357513,
|
| 221 |
+
1.1400059461594,
|
| 222 |
+
.82839399576187,
|
| 223 |
+
1.0262999534607,
|
| 224 |
+
1.0628409385681,
|
| 225 |
+
.84051495790482,
|
| 226 |
+
.82304340600967,
|
| 227 |
+
1.0028872489929,
|
| 228 |
+
1.0457111597061,
|
| 229 |
+
.97847640514374,
|
| 230 |
+
1.1855980157852,
|
| 231 |
+
1.195351600647,
|
| 232 |
+
1.0270363092422,
|
| 233 |
+
1.3610677719116,
|
| 234 |
+
1.0189098119736,
|
| 235 |
+
2.1800265312195,
|
| 236 |
+
.86722087860107,
|
| 237 |
+
1.3893752098083,
|
| 238 |
+
1.4851142168045,
|
| 239 |
+
.65110164880753,
|
| 240 |
+
1.417050242424,
|
| 241 |
+
1.4938380718231,
|
| 242 |
+
1.2786860466003,
|
| 243 |
+
1.446773648262,
|
| 244 |
+
1.9284181594849,
|
| 245 |
+
1.4071846008301,
|
| 246 |
+
2.4745123386383,
|
| 247 |
+
.53088372945786,
|
| 248 |
+
-.25887301564217,
|
| 249 |
+
1.0166070461273,
|
| 250 |
+
1.1028108596802])
|
| 251 |
+
|
| 252 |
+
y = np.array([
|
| 253 |
+
np.nan,
|
| 254 |
+
28.979999542236,
|
| 255 |
+
29.263614654541,
|
| 256 |
+
29.492309570313,
|
| 257 |
+
29.442562103271,
|
| 258 |
+
29.672742843628,
|
| 259 |
+
29.617471694946,
|
| 260 |
+
29.888229370117,
|
| 261 |
+
29.935850143433,
|
| 262 |
+
29.870990753174,
|
| 263 |
+
30.021202087402,
|
| 264 |
+
30.057609558105,
|
| 265 |
+
30.119426727295,
|
| 266 |
+
30.321773529053,
|
| 267 |
+
30.280889511108,
|
| 268 |
+
30.492082595825,
|
| 269 |
+
30.515581130981,
|
| 270 |
+
30.554229736328,
|
| 271 |
+
30.813507080078,
|
| 272 |
+
30.826231002808,
|
| 273 |
+
31.063919067383,
|
| 274 |
+
31.015319824219,
|
| 275 |
+
31.108980178833,
|
| 276 |
+
31.21103477478,
|
| 277 |
+
31.389801025391,
|
| 278 |
+
31.472555160522,
|
| 279 |
+
31.707323074341,
|
| 280 |
+
31.737649917603,
|
| 281 |
+
32.022624969482,
|
| 282 |
+
32.473300933838,
|
| 283 |
+
32.584106445313,
|
| 284 |
+
33.070247650146,
|
| 285 |
+
33.013809204102,
|
| 286 |
+
33.273639678955,
|
| 287 |
+
33.594722747803,
|
| 288 |
+
33.901206970215,
|
| 289 |
+
34.340721130371,
|
| 290 |
+
34.61840057373,
|
| 291 |
+
35.192520141602,
|
| 292 |
+
35.568386077881,
|
| 293 |
+
35.98637008667,
|
| 294 |
+
36.65567779541,
|
| 295 |
+
37.136245727539,
|
| 296 |
+
37.65650177002,
|
| 297 |
+
38.297424316406,
|
| 298 |
+
38.909679412842,
|
| 299 |
+
39.264465332031,
|
| 300 |
+
39.806419372559,
|
| 301 |
+
40.306400299072,
|
| 302 |
+
40.42208480835,
|
| 303 |
+
41.016361236572,
|
| 304 |
+
41.243072509766,
|
| 305 |
+
41.551155090332,
|
| 306 |
+
41.84215927124,
|
| 307 |
+
42.137592315674,
|
| 308 |
+
42.563545227051,
|
| 309 |
+
43.091484069824,
|
| 310 |
+
44.250328063965,
|
| 311 |
+
44.611320495605,
|
| 312 |
+
46.324489593506,
|
| 313 |
+
47.471527099609,
|
| 314 |
+
48.867870330811,
|
| 315 |
+
50.072769165039,
|
| 316 |
+
51.9694480896,
|
| 317 |
+
53.182704925537,
|
| 318 |
+
53.756328582764,
|
| 319 |
+
54.864044189453,
|
| 320 |
+
55.722503662109,
|
| 321 |
+
56.635204315186,
|
| 322 |
+
56.750442504883,
|
| 323 |
+
57.830444335938,
|
| 324 |
+
58.698276519775,
|
| 325 |
+
59.481037139893,
|
| 326 |
+
60.937026977539,
|
| 327 |
+
61.587097167969,
|
| 328 |
+
62.414352416992,
|
| 329 |
+
63.595932006836,
|
| 330 |
+
64.828674316406,
|
| 331 |
+
66.570983886719,
|
| 332 |
+
68.195777893066,
|
| 333 |
+
69.579292297363,
|
| 334 |
+
71.928680419922,
|
| 335 |
+
74.450302124023,
|
| 336 |
+
76.661979675293,
|
| 337 |
+
79.719047546387,
|
| 338 |
+
82.709617614746,
|
| 339 |
+
84.132461547852,
|
| 340 |
+
86.421798706055,
|
| 341 |
+
89.040885925293,
|
| 342 |
+
90.79557800293,
|
| 343 |
+
93.39289855957,
|
| 344 |
+
95.14591217041,
|
| 345 |
+
95.905540466309,
|
| 346 |
+
96.366485595703,
|
| 347 |
+
99.389305114746,
|
| 348 |
+
99.356964111328,
|
| 349 |
+
98.956726074219,
|
| 350 |
+
100.09216308594,
|
| 351 |
+
101.02663421631,
|
| 352 |
+
102.00853729248,
|
| 353 |
+
103.37572479248,
|
| 354 |
+
104.52786254883,
|
| 355 |
+
105.20468139648,
|
| 356 |
+
106.25176239014,
|
| 357 |
+
106.69645690918,
|
| 358 |
+
108.19469451904,
|
| 359 |
+
108.67579650879,
|
| 360 |
+
109.51483154297,
|
| 361 |
+
111.06357574463,
|
| 362 |
+
109.05166625977,
|
| 363 |
+
110.45729064941,
|
| 364 |
+
110.98413848877,
|
| 365 |
+
112.35968017578,
|
| 366 |
+
113.6774597168,
|
| 367 |
+
114.74291229248,
|
| 368 |
+
115.99327850342,
|
| 369 |
+
116.93940734863,
|
| 370 |
+
118.21385192871,
|
| 371 |
+
119.54544830322,
|
| 372 |
+
120.99293518066,
|
| 373 |
+
122.28107452393,
|
| 374 |
+
124.38744354248,
|
| 375 |
+
125.65331268311,
|
| 376 |
+
126.44704437256,
|
| 377 |
+
128.91716003418,
|
| 378 |
+
130.09590148926,
|
| 379 |
+
131.81811523438,
|
| 380 |
+
135.11975097656,
|
| 381 |
+
135.96775817871,
|
| 382 |
+
136.17684936523,
|
| 383 |
+
137.45079040527,
|
| 384 |
+
138.36254882813,
|
| 385 |
+
139.48722839355,
|
| 386 |
+
140.56680297852,
|
| 387 |
+
141.65768432617,
|
| 388 |
+
142.87825012207,
|
| 389 |
+
143.93983459473,
|
| 390 |
+
144.9065246582,
|
| 391 |
+
145.50326538086,
|
| 392 |
+
146.70880126953,
|
| 393 |
+
147.25788879395,
|
| 394 |
+
148.21635437012,
|
| 395 |
+
149.47947692871,
|
| 396 |
+
150.41313171387,
|
| 397 |
+
151.55068969727,
|
| 398 |
+
152.90519714355,
|
| 399 |
+
153.55603027344,
|
| 400 |
+
154.49452209473,
|
| 401 |
+
155.76412963867,
|
| 402 |
+
157.22177124023,
|
| 403 |
+
157.98107910156,
|
| 404 |
+
159.28778076172,
|
| 405 |
+
160.47357177734,
|
| 406 |
+
160.76889038086,
|
| 407 |
+
161.26449584961,
|
| 408 |
+
162.50610351563,
|
| 409 |
+
162.7981262207,
|
| 410 |
+
162.90991210938,
|
| 411 |
+
164.11460876465,
|
| 412 |
+
164.6862487793,
|
| 413 |
+
165.5291595459,
|
| 414 |
+
166.83679199219,
|
| 415 |
+
167.5163269043,
|
| 416 |
+
169.11961364746,
|
| 417 |
+
170.25442504883,
|
| 418 |
+
172.01318359375,
|
| 419 |
+
173.8916015625,
|
| 420 |
+
174.95199584961,
|
| 421 |
+
176.84516906738,
|
| 422 |
+
177.37295532227,
|
| 423 |
+
178.46479797363,
|
| 424 |
+
178.38716125488,
|
| 425 |
+
178.44267272949,
|
| 426 |
+
180.44000244141,
|
| 427 |
+
180.8283996582,
|
| 428 |
+
182.22630310059,
|
| 429 |
+
183.66284179688,
|
| 430 |
+
184.04051208496,
|
| 431 |
+
184.52304077148,
|
| 432 |
+
185.90287780762,
|
| 433 |
+
187.34571838379,
|
| 434 |
+
188.37846374512,
|
| 435 |
+
190.28559875488,
|
| 436 |
+
191.99536132813,
|
| 437 |
+
192.82704162598,
|
| 438 |
+
195.16107177734,
|
| 439 |
+
195.71890258789,
|
| 440 |
+
201.3800201416,
|
| 441 |
+
200.26721191406,
|
| 442 |
+
202.08937072754,
|
| 443 |
+
204.18510437012,
|
| 444 |
+
202.55110168457,
|
| 445 |
+
204.99105834961,
|
| 446 |
+
207.41383361816,
|
| 447 |
+
208.61668395996,
|
| 448 |
+
210.57977294922,
|
| 449 |
+
214.4234161377,
|
| 450 |
+
215.40417480469,
|
| 451 |
+
221.08451843262,
|
| 452 |
+
217.41989135742,
|
| 453 |
+
211.91511535645,
|
| 454 |
+
213.68760681152,
|
| 455 |
+
215.57180786133])
|
| 456 |
+
|
| 457 |
+
resid = np.array([
|
| 458 |
+
np.nan,
|
| 459 |
+
.17000007629395,
|
| 460 |
+
.08638589829206,
|
| 461 |
+
-.12230817228556,
|
| 462 |
+
.09743892401457,
|
| 463 |
+
-.12274374067783,
|
| 464 |
+
.13252860307693,
|
| 465 |
+
-.04822873324156,
|
| 466 |
+
-.12585072219372,
|
| 467 |
+
.04901013895869,
|
| 468 |
+
-.04120244085789,
|
| 469 |
+
-.01760895550251,
|
| 470 |
+
.0905727148056,
|
| 471 |
+
-.1017746925354,
|
| 472 |
+
.09910991042852,
|
| 473 |
+
-.05208196863532,
|
| 474 |
+
-.03558072075248,
|
| 475 |
+
.13577139377594,
|
| 476 |
+
-.0635067820549,
|
| 477 |
+
.11377000063658,
|
| 478 |
+
-.11391747742891,
|
| 479 |
+
.00468154205009,
|
| 480 |
+
.01102056354284,
|
| 481 |
+
.0689652711153,
|
| 482 |
+
-.00980201456696,
|
| 483 |
+
.10744450241327,
|
| 484 |
+
-.05732321739197,
|
| 485 |
+
.14234967529774,
|
| 486 |
+
.25737473368645,
|
| 487 |
+
-.02330071851611,
|
| 488 |
+
.26589342951775,
|
| 489 |
+
-.17024727165699,
|
| 490 |
+
.08618897944689,
|
| 491 |
+
.12636296451092,
|
| 492 |
+
.10527954250574,
|
| 493 |
+
.19879072904587,
|
| 494 |
+
.05928030610085,
|
| 495 |
+
.28160139918327,
|
| 496 |
+
.10748030990362,
|
| 497 |
+
.13161440193653,
|
| 498 |
+
.31362771987915,
|
| 499 |
+
.14432306587696,
|
| 500 |
+
.16375194489956,
|
| 501 |
+
.24349948763847,
|
| 502 |
+
.20257519185543,
|
| 503 |
+
-.00967973750085,
|
| 504 |
+
.13553610444069,
|
| 505 |
+
.09358221292496,
|
| 506 |
+
-.20640131831169,
|
| 507 |
+
.17791347205639,
|
| 508 |
+
-.11636133491993,
|
| 509 |
+
-.04307091236115,
|
| 510 |
+
-.05115458369255,
|
| 511 |
+
-.04216108098626,
|
| 512 |
+
.06240950897336,
|
| 513 |
+
.13645392656326,
|
| 514 |
+
.60851699113846,
|
| 515 |
+
-.05032894387841,
|
| 516 |
+
.98867815732956,
|
| 517 |
+
.47550892829895,
|
| 518 |
+
.62846976518631,
|
| 519 |
+
.43213015794754,
|
| 520 |
+
.92723226547241,
|
| 521 |
+
.33055067062378,
|
| 522 |
+
-.18270587921143,
|
| 523 |
+
.24367287755013,
|
| 524 |
+
.0359565988183,
|
| 525 |
+
.07749536633492,
|
| 526 |
+
-.53520393371582,
|
| 527 |
+
.24955849349499,
|
| 528 |
+
.0695584192872,
|
| 529 |
+
.00172565307003,
|
| 530 |
+
.51896333694458,
|
| 531 |
+
-.13702796399593,
|
| 532 |
+
.01290242280811,
|
| 533 |
+
.28564843535423,
|
| 534 |
+
.30406919121742,
|
| 535 |
+
.67132312059402,
|
| 536 |
+
.5290162563324,
|
| 537 |
+
.30422034859657,
|
| 538 |
+
1.0207070112228,
|
| 539 |
+
1.0713183879852,
|
| 540 |
+
.74969446659088,
|
| 541 |
+
1.3380213975906,
|
| 542 |
+
1.1809539794922,
|
| 543 |
+
-.10961806029081,
|
| 544 |
+
.56753551959991,
|
| 545 |
+
.77819520235062,
|
| 546 |
+
.05911364778876,
|
| 547 |
+
.70441842079163,
|
| 548 |
+
.0071063125506,
|
| 549 |
+
-.74591380357742,
|
| 550 |
+
-.90554106235504,
|
| 551 |
+
1.1335146427155,
|
| 552 |
+
-1.2893046140671,
|
| 553 |
+
-1.4569646120071,
|
| 554 |
+
-.15672297775745,
|
| 555 |
+
-.29216033220291,
|
| 556 |
+
-.22663290798664,
|
| 557 |
+
.09146212786436,
|
| 558 |
+
-.0757219940424,
|
| 559 |
+
-.42786338925362,
|
| 560 |
+
-.10468477010727,
|
| 561 |
+
-.55176627635956,
|
| 562 |
+
.3035394847393,
|
| 563 |
+
-.49469754099846,
|
| 564 |
+
-.1758000254631,
|
| 565 |
+
.38517218828201,
|
| 566 |
+
-2.3635804653168,
|
| 567 |
+
.44833266735077,
|
| 568 |
+
-.25729209184647,
|
| 569 |
+
.41586154699326,
|
| 570 |
+
.34031534194946,
|
| 571 |
+
.1225445792079,
|
| 572 |
+
.25708478689194,
|
| 573 |
+
.00672172475606,
|
| 574 |
+
.26059049367905,
|
| 575 |
+
.28615045547485,
|
| 576 |
+
.35455179214478,
|
| 577 |
+
.2070597410202,
|
| 578 |
+
.81892204284668,
|
| 579 |
+
.11255792528391,
|
| 580 |
+
-.25330832600594,
|
| 581 |
+
1.0529587268829,
|
| 582 |
+
-.0171735137701,
|
| 583 |
+
.40410390496254,
|
| 584 |
+
1.5818736553192,
|
| 585 |
+
-.41975006461143,
|
| 586 |
+
-.86774694919586,
|
| 587 |
+
.02315225638449,
|
| 588 |
+
-.25080046057701,
|
| 589 |
+
-.06255260109901,
|
| 590 |
+
-.08723650127649,
|
| 591 |
+
-.06679660826921,
|
| 592 |
+
.04230948910117,
|
| 593 |
+
-.07823982834816,
|
| 594 |
+
-.13983787596226,
|
| 595 |
+
-.40652501583099,
|
| 596 |
+
.09674594551325,
|
| 597 |
+
-.40880066156387,
|
| 598 |
+
-.05788768827915,
|
| 599 |
+
.1836401373148,
|
| 600 |
+
-.07948285341263,
|
| 601 |
+
.08686522394419,
|
| 602 |
+
.24931237101555,
|
| 603 |
+
-.30519738793373,
|
| 604 |
+
-.05602284148335,
|
| 605 |
+
.20547580718994,
|
| 606 |
+
.33588215708733,
|
| 607 |
+
-.22176894545555,
|
| 608 |
+
.21891987323761,
|
| 609 |
+
.11221113055944,
|
| 610 |
+
-.57358360290527,
|
| 611 |
+
-.36890152096748,
|
| 612 |
+
.23551045358181,
|
| 613 |
+
-.50609844923019,
|
| 614 |
+
-.59812569618225,
|
| 615 |
+
.29008835554123,
|
| 616 |
+
-.21461589634418,
|
| 617 |
+
.013751687482,
|
| 618 |
+
.37082800269127,
|
| 619 |
+
-.13679853081703,
|
| 620 |
+
.5836746096611,
|
| 621 |
+
.18038421869278,
|
| 622 |
+
.64556515216827,
|
| 623 |
+
.68681055307388,
|
| 624 |
+
.00838960427791,
|
| 625 |
+
.64800941944122,
|
| 626 |
+
-.44517654180527,
|
| 627 |
+
.02703555487096,
|
| 628 |
+
-.8647877573967,
|
| 629 |
+
-.68716812133789,
|
| 630 |
+
.85732614994049,
|
| 631 |
+
-.44000896811485,
|
| 632 |
+
.37160298228264,
|
| 633 |
+
.37370926141739,
|
| 634 |
+
-.46285009384155,
|
| 635 |
+
-.34051498770714,
|
| 636 |
+
.37695357203484,
|
| 637 |
+
.3971218764782,
|
| 638 |
+
.05427964404225,
|
| 639 |
+
.72153580188751,
|
| 640 |
+
.51439893245697,
|
| 641 |
+
-.19535164535046,
|
| 642 |
+
.97296363115311,
|
| 643 |
+
-.46107393503189,
|
| 644 |
+
3.4810900688171,
|
| 645 |
+
-1.9800295829773,
|
| 646 |
+
.43278217315674,
|
| 647 |
+
.61062479019165,
|
| 648 |
+
-2.2851173877716,
|
| 649 |
+
1.0229095220566,
|
| 650 |
+
.92894279956818,
|
| 651 |
+
-.07583882659674,
|
| 652 |
+
.51631212234497,
|
| 653 |
+
1.9152258634567,
|
| 654 |
+
-.42641922831535,
|
| 655 |
+
3.2058219909668,
|
| 656 |
+
-4.1955056190491,
|
| 657 |
+
-5.2458953857422,
|
| 658 |
+
.75588232278824,
|
| 659 |
+
.7813817858696,
|
| 660 |
+
.81318950653076])
|
| 661 |
+
|
| 662 |
+
yr = np.array([
|
| 663 |
+
np.nan,
|
| 664 |
+
.17000007629395,
|
| 665 |
+
.08638589829206,
|
| 666 |
+
-.12230817228556,
|
| 667 |
+
.09743892401457,
|
| 668 |
+
-.12274374067783,
|
| 669 |
+
.13252860307693,
|
| 670 |
+
-.04822873324156,
|
| 671 |
+
-.12585072219372,
|
| 672 |
+
.04901013895869,
|
| 673 |
+
-.04120244085789,
|
| 674 |
+
-.01760895550251,
|
| 675 |
+
.0905727148056,
|
| 676 |
+
-.1017746925354,
|
| 677 |
+
.09910991042852,
|
| 678 |
+
-.05208196863532,
|
| 679 |
+
-.03558072075248,
|
| 680 |
+
.13577139377594,
|
| 681 |
+
-.0635067820549,
|
| 682 |
+
.11377000063658,
|
| 683 |
+
-.11391747742891,
|
| 684 |
+
.00468154205009,
|
| 685 |
+
.01102056354284,
|
| 686 |
+
.0689652711153,
|
| 687 |
+
-.00980201456696,
|
| 688 |
+
.10744450241327,
|
| 689 |
+
-.05732321739197,
|
| 690 |
+
.14234967529774,
|
| 691 |
+
.25737473368645,
|
| 692 |
+
-.02330071851611,
|
| 693 |
+
.26589342951775,
|
| 694 |
+
-.17024727165699,
|
| 695 |
+
.08618897944689,
|
| 696 |
+
.12636296451092,
|
| 697 |
+
.10527954250574,
|
| 698 |
+
.19879072904587,
|
| 699 |
+
.05928030610085,
|
| 700 |
+
.28160139918327,
|
| 701 |
+
.10748030990362,
|
| 702 |
+
.13161440193653,
|
| 703 |
+
.31362771987915,
|
| 704 |
+
.14432306587696,
|
| 705 |
+
.16375194489956,
|
| 706 |
+
.24349948763847,
|
| 707 |
+
.20257519185543,
|
| 708 |
+
-.00967973750085,
|
| 709 |
+
.13553610444069,
|
| 710 |
+
.09358221292496,
|
| 711 |
+
-.20640131831169,
|
| 712 |
+
.17791347205639,
|
| 713 |
+
-.11636133491993,
|
| 714 |
+
-.04307091236115,
|
| 715 |
+
-.05115458369255,
|
| 716 |
+
-.04216108098626,
|
| 717 |
+
.06240950897336,
|
| 718 |
+
.13645392656326,
|
| 719 |
+
.60851699113846,
|
| 720 |
+
-.05032894387841,
|
| 721 |
+
.98867815732956,
|
| 722 |
+
.47550892829895,
|
| 723 |
+
.62846976518631,
|
| 724 |
+
.43213015794754,
|
| 725 |
+
.92723226547241,
|
| 726 |
+
.33055067062378,
|
| 727 |
+
-.18270587921143,
|
| 728 |
+
.24367287755013,
|
| 729 |
+
.0359565988183,
|
| 730 |
+
.07749536633492,
|
| 731 |
+
-.53520393371582,
|
| 732 |
+
.24955849349499,
|
| 733 |
+
.0695584192872,
|
| 734 |
+
.00172565307003,
|
| 735 |
+
.51896333694458,
|
| 736 |
+
-.13702796399593,
|
| 737 |
+
.01290242280811,
|
| 738 |
+
.28564843535423,
|
| 739 |
+
.30406919121742,
|
| 740 |
+
.67132312059402,
|
| 741 |
+
.5290162563324,
|
| 742 |
+
.30422034859657,
|
| 743 |
+
1.0207070112228,
|
| 744 |
+
1.0713183879852,
|
| 745 |
+
.74969446659088,
|
| 746 |
+
1.3380213975906,
|
| 747 |
+
1.1809539794922,
|
| 748 |
+
-.10961806029081,
|
| 749 |
+
.56753551959991,
|
| 750 |
+
.77819520235062,
|
| 751 |
+
.05911364778876,
|
| 752 |
+
.70441842079163,
|
| 753 |
+
.0071063125506,
|
| 754 |
+
-.74591380357742,
|
| 755 |
+
-.90554106235504,
|
| 756 |
+
1.1335146427155,
|
| 757 |
+
-1.2893046140671,
|
| 758 |
+
-1.4569646120071,
|
| 759 |
+
-.15672297775745,
|
| 760 |
+
-.29216033220291,
|
| 761 |
+
-.22663290798664,
|
| 762 |
+
.09146212786436,
|
| 763 |
+
-.0757219940424,
|
| 764 |
+
-.42786338925362,
|
| 765 |
+
-.10468477010727,
|
| 766 |
+
-.55176627635956,
|
| 767 |
+
.3035394847393,
|
| 768 |
+
-.49469754099846,
|
| 769 |
+
-.1758000254631,
|
| 770 |
+
.38517218828201,
|
| 771 |
+
-2.3635804653168,
|
| 772 |
+
.44833266735077,
|
| 773 |
+
-.25729209184647,
|
| 774 |
+
.41586154699326,
|
| 775 |
+
.34031534194946,
|
| 776 |
+
.1225445792079,
|
| 777 |
+
.25708478689194,
|
| 778 |
+
.00672172475606,
|
| 779 |
+
.26059049367905,
|
| 780 |
+
.28615045547485,
|
| 781 |
+
.35455179214478,
|
| 782 |
+
.2070597410202,
|
| 783 |
+
.81892204284668,
|
| 784 |
+
.11255792528391,
|
| 785 |
+
-.25330832600594,
|
| 786 |
+
1.0529587268829,
|
| 787 |
+
-.0171735137701,
|
| 788 |
+
.40410390496254,
|
| 789 |
+
1.5818736553192,
|
| 790 |
+
-.41975006461143,
|
| 791 |
+
-.86774694919586,
|
| 792 |
+
.02315225638449,
|
| 793 |
+
-.25080046057701,
|
| 794 |
+
-.06255260109901,
|
| 795 |
+
-.08723650127649,
|
| 796 |
+
-.06679660826921,
|
| 797 |
+
.04230948910117,
|
| 798 |
+
-.07823982834816,
|
| 799 |
+
-.13983787596226,
|
| 800 |
+
-.40652501583099,
|
| 801 |
+
.09674594551325,
|
| 802 |
+
-.40880066156387,
|
| 803 |
+
-.05788768827915,
|
| 804 |
+
.1836401373148,
|
| 805 |
+
-.07948285341263,
|
| 806 |
+
.08686522394419,
|
| 807 |
+
.24931237101555,
|
| 808 |
+
-.30519738793373,
|
| 809 |
+
-.05602284148335,
|
| 810 |
+
.20547580718994,
|
| 811 |
+
.33588215708733,
|
| 812 |
+
-.22176894545555,
|
| 813 |
+
.21891987323761,
|
| 814 |
+
.11221113055944,
|
| 815 |
+
-.57358360290527,
|
| 816 |
+
-.36890152096748,
|
| 817 |
+
.23551045358181,
|
| 818 |
+
-.50609844923019,
|
| 819 |
+
-.59812569618225,
|
| 820 |
+
.29008835554123,
|
| 821 |
+
-.21461589634418,
|
| 822 |
+
.013751687482,
|
| 823 |
+
.37082800269127,
|
| 824 |
+
-.13679853081703,
|
| 825 |
+
.5836746096611,
|
| 826 |
+
.18038421869278,
|
| 827 |
+
.64556515216827,
|
| 828 |
+
.68681055307388,
|
| 829 |
+
.00838960427791,
|
| 830 |
+
.64800941944122,
|
| 831 |
+
-.44517654180527,
|
| 832 |
+
.02703555487096,
|
| 833 |
+
-.8647877573967,
|
| 834 |
+
-.68716812133789,
|
| 835 |
+
.85732614994049,
|
| 836 |
+
-.44000896811485,
|
| 837 |
+
.37160298228264,
|
| 838 |
+
.37370926141739,
|
| 839 |
+
-.46285009384155,
|
| 840 |
+
-.34051498770714,
|
| 841 |
+
.37695357203484,
|
| 842 |
+
.3971218764782,
|
| 843 |
+
.05427964404225,
|
| 844 |
+
.72153580188751,
|
| 845 |
+
.51439893245697,
|
| 846 |
+
-.19535164535046,
|
| 847 |
+
.97296363115311,
|
| 848 |
+
-.46107393503189,
|
| 849 |
+
3.4810900688171,
|
| 850 |
+
-1.9800295829773,
|
| 851 |
+
.43278217315674,
|
| 852 |
+
.61062479019165,
|
| 853 |
+
-2.2851173877716,
|
| 854 |
+
1.0229095220566,
|
| 855 |
+
.92894279956818,
|
| 856 |
+
-.07583882659674,
|
| 857 |
+
.51631212234497,
|
| 858 |
+
1.9152258634567,
|
| 859 |
+
-.42641922831535,
|
| 860 |
+
3.2058219909668,
|
| 861 |
+
-4.1955056190491,
|
| 862 |
+
-5.2458953857422,
|
| 863 |
+
.75588232278824,
|
| 864 |
+
.7813817858696,
|
| 865 |
+
.81318950653076])
|
| 866 |
+
|
| 867 |
+
mse = np.array([
|
| 868 |
+
1.4407075643539,
|
| 869 |
+
1.4407075643539,
|
| 870 |
+
.79720854759216,
|
| 871 |
+
.75209444761276,
|
| 872 |
+
.71109557151794,
|
| 873 |
+
.68920749425888,
|
| 874 |
+
.67417079210281,
|
| 875 |
+
.66374856233597,
|
| 876 |
+
.65616118907928,
|
| 877 |
+
.65050256252289,
|
| 878 |
+
.64619332551956,
|
| 879 |
+
.64286160469055,
|
| 880 |
+
.64025497436523,
|
| 881 |
+
.63819670677185,
|
| 882 |
+
.63655960559845,
|
| 883 |
+
.6352499127388,
|
| 884 |
+
.63419729471207,
|
| 885 |
+
.63334810733795,
|
| 886 |
+
.63266098499298,
|
| 887 |
+
.63210368156433,
|
| 888 |
+
.63165074586868,
|
| 889 |
+
.63128209114075,
|
| 890 |
+
.63098156452179,
|
| 891 |
+
.63073641061783,
|
| 892 |
+
.63053613901138,
|
| 893 |
+
.63037252426147,
|
| 894 |
+
.6302387714386,
|
| 895 |
+
.63012927770615,
|
| 896 |
+
.63003975152969,
|
| 897 |
+
.62996637821198,
|
| 898 |
+
.62990635633469,
|
| 899 |
+
.62985718250275,
|
| 900 |
+
.62981688976288,
|
| 901 |
+
.62978386878967,
|
| 902 |
+
.62975686788559,
|
| 903 |
+
.62973469495773,
|
| 904 |
+
.62971651554108,
|
| 905 |
+
.62970167398453,
|
| 906 |
+
.62968945503235,
|
| 907 |
+
.62967944145203,
|
| 908 |
+
.62967127561569,
|
| 909 |
+
.62966454029083,
|
| 910 |
+
.62965905666351,
|
| 911 |
+
.62965452671051,
|
| 912 |
+
.62965083122253,
|
| 913 |
+
.62964779138565,
|
| 914 |
+
.62964528799057,
|
| 915 |
+
.62964326143265,
|
| 916 |
+
.62964159250259,
|
| 917 |
+
.62964022159576,
|
| 918 |
+
.62963908910751,
|
| 919 |
+
.62963819503784,
|
| 920 |
+
.62963742017746,
|
| 921 |
+
.62963682413101,
|
| 922 |
+
.62963628768921,
|
| 923 |
+
.6296358704567,
|
| 924 |
+
.62963551282883,
|
| 925 |
+
.62963527441025,
|
| 926 |
+
.62963503599167,
|
| 927 |
+
.62963485717773,
|
| 928 |
+
.6296346783638,
|
| 929 |
+
.62963455915451,
|
| 930 |
+
.62963443994522,
|
| 931 |
+
.62963438034058,
|
| 932 |
+
.62963432073593,
|
| 933 |
+
.62963426113129,
|
| 934 |
+
.62963420152664,
|
| 935 |
+
.629634141922,
|
| 936 |
+
.629634141922,
|
| 937 |
+
.62963408231735,
|
| 938 |
+
.62963408231735,
|
| 939 |
+
.62963408231735,
|
| 940 |
+
.62963402271271,
|
| 941 |
+
.62963402271271,
|
| 942 |
+
.62963402271271,
|
| 943 |
+
.62963402271271,
|
| 944 |
+
.62963402271271,
|
| 945 |
+
.62963402271271,
|
| 946 |
+
.62963402271271,
|
| 947 |
+
.62963402271271,
|
| 948 |
+
.62963402271271,
|
| 949 |
+
.62963396310806,
|
| 950 |
+
.62963396310806,
|
| 951 |
+
.62963396310806,
|
| 952 |
+
.62963396310806,
|
| 953 |
+
.62963396310806,
|
| 954 |
+
.62963396310806,
|
| 955 |
+
.62963396310806,
|
| 956 |
+
.62963396310806,
|
| 957 |
+
.62963396310806,
|
| 958 |
+
.62963396310806,
|
| 959 |
+
.62963396310806,
|
| 960 |
+
.62963396310806,
|
| 961 |
+
.62963396310806,
|
| 962 |
+
.62963396310806,
|
| 963 |
+
.62963396310806,
|
| 964 |
+
.62963396310806,
|
| 965 |
+
.62963396310806,
|
| 966 |
+
.62963396310806,
|
| 967 |
+
.62963396310806,
|
| 968 |
+
.62963396310806,
|
| 969 |
+
.62963396310806,
|
| 970 |
+
.62963396310806,
|
| 971 |
+
.62963396310806,
|
| 972 |
+
.62963396310806,
|
| 973 |
+
.62963396310806,
|
| 974 |
+
.62963396310806,
|
| 975 |
+
.62963396310806,
|
| 976 |
+
.62963396310806,
|
| 977 |
+
.62963396310806,
|
| 978 |
+
.62963396310806,
|
| 979 |
+
.62963396310806,
|
| 980 |
+
.62963396310806,
|
| 981 |
+
.62963396310806,
|
| 982 |
+
.62963396310806,
|
| 983 |
+
.62963396310806,
|
| 984 |
+
.62963396310806,
|
| 985 |
+
.62963396310806,
|
| 986 |
+
.62963396310806,
|
| 987 |
+
.62963396310806,
|
| 988 |
+
.62963396310806,
|
| 989 |
+
.62963396310806,
|
| 990 |
+
.62963396310806,
|
| 991 |
+
.62963396310806,
|
| 992 |
+
.62963396310806,
|
| 993 |
+
.62963396310806,
|
| 994 |
+
.62963396310806,
|
| 995 |
+
.62963396310806,
|
| 996 |
+
.62963396310806,
|
| 997 |
+
.62963396310806,
|
| 998 |
+
.62963396310806,
|
| 999 |
+
.62963396310806,
|
| 1000 |
+
.62963396310806,
|
| 1001 |
+
.62963396310806,
|
| 1002 |
+
.62963396310806,
|
| 1003 |
+
.62963396310806,
|
| 1004 |
+
.62963396310806,
|
| 1005 |
+
.62963396310806,
|
| 1006 |
+
.62963396310806,
|
| 1007 |
+
.62963396310806,
|
| 1008 |
+
.62963396310806,
|
| 1009 |
+
.62963396310806,
|
| 1010 |
+
.62963396310806,
|
| 1011 |
+
.62963396310806,
|
| 1012 |
+
.62963396310806,
|
| 1013 |
+
.62963396310806,
|
| 1014 |
+
.62963396310806,
|
| 1015 |
+
.62963396310806,
|
| 1016 |
+
.62963396310806,
|
| 1017 |
+
.62963396310806,
|
| 1018 |
+
.62963396310806,
|
| 1019 |
+
.62963396310806,
|
| 1020 |
+
.62963396310806,
|
| 1021 |
+
.62963396310806,
|
| 1022 |
+
.62963396310806,
|
| 1023 |
+
.62963396310806,
|
| 1024 |
+
.62963396310806,
|
| 1025 |
+
.62963396310806,
|
| 1026 |
+
.62963396310806,
|
| 1027 |
+
.62963396310806,
|
| 1028 |
+
.62963396310806,
|
| 1029 |
+
.62963396310806,
|
| 1030 |
+
.62963396310806,
|
| 1031 |
+
.62963396310806,
|
| 1032 |
+
.62963396310806,
|
| 1033 |
+
.62963396310806,
|
| 1034 |
+
.62963396310806,
|
| 1035 |
+
.62963396310806,
|
| 1036 |
+
.62963396310806,
|
| 1037 |
+
.62963396310806,
|
| 1038 |
+
.62963396310806,
|
| 1039 |
+
.62963396310806,
|
| 1040 |
+
.62963396310806,
|
| 1041 |
+
.62963396310806,
|
| 1042 |
+
.62963396310806,
|
| 1043 |
+
.62963396310806,
|
| 1044 |
+
.62963396310806,
|
| 1045 |
+
.62963396310806,
|
| 1046 |
+
.62963396310806,
|
| 1047 |
+
.62963396310806,
|
| 1048 |
+
.62963396310806,
|
| 1049 |
+
.62963396310806,
|
| 1050 |
+
.62963396310806,
|
| 1051 |
+
.62963396310806,
|
| 1052 |
+
.62963396310806,
|
| 1053 |
+
.62963396310806,
|
| 1054 |
+
.62963396310806,
|
| 1055 |
+
.62963396310806,
|
| 1056 |
+
.62963396310806,
|
| 1057 |
+
.62963396310806,
|
| 1058 |
+
.62963396310806,
|
| 1059 |
+
.62963396310806,
|
| 1060 |
+
.62963396310806,
|
| 1061 |
+
.62963396310806,
|
| 1062 |
+
.62963396310806,
|
| 1063 |
+
.62963396310806,
|
| 1064 |
+
.62963396310806,
|
| 1065 |
+
.62963396310806,
|
| 1066 |
+
.62963396310806,
|
| 1067 |
+
.62963396310806,
|
| 1068 |
+
.62963396310806,
|
| 1069 |
+
.62963396310806,
|
| 1070 |
+
.62963396310806])
|
| 1071 |
+
|
| 1072 |
+
icstats = np.array([
|
| 1073 |
+
202,
|
| 1074 |
+
np.nan,
|
| 1075 |
+
-240.79351748413,
|
| 1076 |
+
4,
|
| 1077 |
+
489.58703496826,
|
| 1078 |
+
502.82010575786])
|
| 1079 |
+
|
| 1080 |
+
|
| 1081 |
+
results = Bunch(
|
| 1082 |
+
llf=llf,
|
| 1083 |
+
nobs=nobs,
|
| 1084 |
+
k=k,
|
| 1085 |
+
k_exog=k_exog,
|
| 1086 |
+
sigma=sigma,
|
| 1087 |
+
chi2=chi2,
|
| 1088 |
+
df_model=df_model,
|
| 1089 |
+
k_ar=k_ar,
|
| 1090 |
+
k_ma=k_ma,
|
| 1091 |
+
params=params,
|
| 1092 |
+
cov_params=cov_params,
|
| 1093 |
+
xb=xb,
|
| 1094 |
+
y=y,
|
| 1095 |
+
resid=resid,
|
| 1096 |
+
yr=yr,
|
| 1097 |
+
mse=mse,
|
| 1098 |
+
icstats=icstats
|
| 1099 |
+
)
|
shared/package-files/12/123bba51a65adb7e665ac19d1cbe1a30d426b5ca10e4bd6ba9315ed6f67d9c19/colorscan
ADDED
|
Binary file (440 Bytes). View file
|
|
|
shared/package-files/12/123bba51a65adb7e665ac19d1cbe1a30d426b5ca10e4bd6ba9315ed6f67d9c19/cs10
ADDED
|
Binary file (440 Bytes). View file
|
|
|
shared/package-files/12/123c85a2812a517d967db5f31660db0e6aded4a0b95ed943c5ab435368e7a25c/dumb
ADDED
|
Binary file (308 Bytes). View file
|
|
|
shared/package-files/12/12405d898c1f97129255511cf8ca74764a24a0d96db6526524865072f4e294bc/is_same_size_native.h
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API bool is_same_size(const at::Tensor & self, const at::Tensor & other);
|
| 20 |
+
TORCH_API bool nested_is_same_size(const at::Tensor & self, const at::Tensor & other);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
shared/package-files/12/124194a8c1f7a8101b2d56d24ae622e1943cf46e315089834f69d301fde79fd1/jscode.py
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Javascript code printer
|
| 3 |
+
|
| 4 |
+
The JavascriptCodePrinter converts single SymPy expressions into single
|
| 5 |
+
Javascript expressions, using the functions defined in the Javascript
|
| 6 |
+
Math object where possible.
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
from sympy.core import S
|
| 14 |
+
from sympy.core.numbers import equal_valued
|
| 15 |
+
from sympy.printing.codeprinter import CodePrinter
|
| 16 |
+
from sympy.printing.precedence import precedence, PRECEDENCE
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# dictionary mapping SymPy function to (argument_conditions, Javascript_function).
|
| 20 |
+
# Used in JavascriptCodePrinter._print_Function(self)
|
| 21 |
+
known_functions = {
|
| 22 |
+
'Abs': 'Math.abs',
|
| 23 |
+
'acos': 'Math.acos',
|
| 24 |
+
'acosh': 'Math.acosh',
|
| 25 |
+
'asin': 'Math.asin',
|
| 26 |
+
'asinh': 'Math.asinh',
|
| 27 |
+
'atan': 'Math.atan',
|
| 28 |
+
'atan2': 'Math.atan2',
|
| 29 |
+
'atanh': 'Math.atanh',
|
| 30 |
+
'ceiling': 'Math.ceil',
|
| 31 |
+
'cos': 'Math.cos',
|
| 32 |
+
'cosh': 'Math.cosh',
|
| 33 |
+
'exp': 'Math.exp',
|
| 34 |
+
'floor': 'Math.floor',
|
| 35 |
+
'log': 'Math.log',
|
| 36 |
+
'Max': 'Math.max',
|
| 37 |
+
'Min': 'Math.min',
|
| 38 |
+
'sign': 'Math.sign',
|
| 39 |
+
'sin': 'Math.sin',
|
| 40 |
+
'sinh': 'Math.sinh',
|
| 41 |
+
'tan': 'Math.tan',
|
| 42 |
+
'tanh': 'Math.tanh',
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class JavascriptCodePrinter(CodePrinter):
|
| 47 |
+
""""A Printer to convert Python expressions to strings of JavaScript code
|
| 48 |
+
"""
|
| 49 |
+
printmethod = '_javascript'
|
| 50 |
+
language = 'JavaScript'
|
| 51 |
+
|
| 52 |
+
_default_settings: dict[str, Any] = {
|
| 53 |
+
'order': None,
|
| 54 |
+
'full_prec': 'auto',
|
| 55 |
+
'precision': 17,
|
| 56 |
+
'user_functions': {},
|
| 57 |
+
'human': True,
|
| 58 |
+
'allow_unknown_functions': False,
|
| 59 |
+
'contract': True,
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
def __init__(self, settings={}):
|
| 63 |
+
CodePrinter.__init__(self, settings)
|
| 64 |
+
self.known_functions = dict(known_functions)
|
| 65 |
+
userfuncs = settings.get('user_functions', {})
|
| 66 |
+
self.known_functions.update(userfuncs)
|
| 67 |
+
|
| 68 |
+
def _rate_index_position(self, p):
|
| 69 |
+
return p*5
|
| 70 |
+
|
| 71 |
+
def _get_statement(self, codestring):
|
| 72 |
+
return "%s;" % codestring
|
| 73 |
+
|
| 74 |
+
def _get_comment(self, text):
|
| 75 |
+
return "// {}".format(text)
|
| 76 |
+
|
| 77 |
+
def _declare_number_const(self, name, value):
|
| 78 |
+
return "var {} = {};".format(name, value.evalf(self._settings['precision']))
|
| 79 |
+
|
| 80 |
+
def _format_code(self, lines):
|
| 81 |
+
return self.indent_code(lines)
|
| 82 |
+
|
| 83 |
+
def _traverse_matrix_indices(self, mat):
|
| 84 |
+
rows, cols = mat.shape
|
| 85 |
+
return ((i, j) for i in range(rows) for j in range(cols))
|
| 86 |
+
|
| 87 |
+
def _get_loop_opening_ending(self, indices):
|
| 88 |
+
open_lines = []
|
| 89 |
+
close_lines = []
|
| 90 |
+
loopstart = "for (var %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){"
|
| 91 |
+
for i in indices:
|
| 92 |
+
# Javascript arrays start at 0 and end at dimension-1
|
| 93 |
+
open_lines.append(loopstart % {
|
| 94 |
+
'varble': self._print(i.label),
|
| 95 |
+
'start': self._print(i.lower),
|
| 96 |
+
'end': self._print(i.upper + 1)})
|
| 97 |
+
close_lines.append("}")
|
| 98 |
+
return open_lines, close_lines
|
| 99 |
+
|
| 100 |
+
def _print_Pow(self, expr):
|
| 101 |
+
PREC = precedence(expr)
|
| 102 |
+
if equal_valued(expr.exp, -1):
|
| 103 |
+
return '1/%s' % (self.parenthesize(expr.base, PREC))
|
| 104 |
+
elif equal_valued(expr.exp, 0.5):
|
| 105 |
+
return 'Math.sqrt(%s)' % self._print(expr.base)
|
| 106 |
+
elif expr.exp == S.One/3:
|
| 107 |
+
return 'Math.cbrt(%s)' % self._print(expr.base)
|
| 108 |
+
else:
|
| 109 |
+
return 'Math.pow(%s, %s)' % (self._print(expr.base),
|
| 110 |
+
self._print(expr.exp))
|
| 111 |
+
|
| 112 |
+
def _print_Rational(self, expr):
|
| 113 |
+
p, q = int(expr.p), int(expr.q)
|
| 114 |
+
return '%d/%d' % (p, q)
|
| 115 |
+
|
| 116 |
+
def _print_Mod(self, expr):
|
| 117 |
+
num, den = expr.args
|
| 118 |
+
PREC = precedence(expr)
|
| 119 |
+
snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args]
|
| 120 |
+
# % is remainder (same sign as numerator), not modulo (same sign as
|
| 121 |
+
# denominator), in js. Hence, % only works as modulo if both numbers
|
| 122 |
+
# have the same sign
|
| 123 |
+
if (num.is_nonnegative and den.is_nonnegative or
|
| 124 |
+
num.is_nonpositive and den.is_nonpositive):
|
| 125 |
+
return f"{snum} % {sden}"
|
| 126 |
+
return f"(({snum} % {sden}) + {sden}) % {sden}"
|
| 127 |
+
|
| 128 |
+
def _print_Relational(self, expr):
|
| 129 |
+
lhs_code = self._print(expr.lhs)
|
| 130 |
+
rhs_code = self._print(expr.rhs)
|
| 131 |
+
op = expr.rel_op
|
| 132 |
+
return "{} {} {}".format(lhs_code, op, rhs_code)
|
| 133 |
+
|
| 134 |
+
def _print_Indexed(self, expr):
|
| 135 |
+
# calculate index for 1d array
|
| 136 |
+
dims = expr.shape
|
| 137 |
+
elem = S.Zero
|
| 138 |
+
offset = S.One
|
| 139 |
+
for i in reversed(range(expr.rank)):
|
| 140 |
+
elem += expr.indices[i]*offset
|
| 141 |
+
offset *= dims[i]
|
| 142 |
+
return "%s[%s]" % (self._print(expr.base.label), self._print(elem))
|
| 143 |
+
|
| 144 |
+
def _print_Idx(self, expr):
|
| 145 |
+
return self._print(expr.label)
|
| 146 |
+
|
| 147 |
+
def _print_Exp1(self, expr):
|
| 148 |
+
return "Math.E"
|
| 149 |
+
|
| 150 |
+
def _print_Pi(self, expr):
|
| 151 |
+
return 'Math.PI'
|
| 152 |
+
|
| 153 |
+
def _print_Infinity(self, expr):
|
| 154 |
+
return 'Number.POSITIVE_INFINITY'
|
| 155 |
+
|
| 156 |
+
def _print_NegativeInfinity(self, expr):
|
| 157 |
+
return 'Number.NEGATIVE_INFINITY'
|
| 158 |
+
|
| 159 |
+
def _print_Piecewise(self, expr):
|
| 160 |
+
from sympy.codegen.ast import Assignment
|
| 161 |
+
if expr.args[-1].cond != True:
|
| 162 |
+
# We need the last conditional to be a True, otherwise the resulting
|
| 163 |
+
# function may not return a result.
|
| 164 |
+
raise ValueError("All Piecewise expressions must contain an "
|
| 165 |
+
"(expr, True) statement to be used as a default "
|
| 166 |
+
"condition. Without one, the generated "
|
| 167 |
+
"expression may not evaluate to anything under "
|
| 168 |
+
"some condition.")
|
| 169 |
+
lines = []
|
| 170 |
+
if expr.has(Assignment):
|
| 171 |
+
for i, (e, c) in enumerate(expr.args):
|
| 172 |
+
if i == 0:
|
| 173 |
+
lines.append("if (%s) {" % self._print(c))
|
| 174 |
+
elif i == len(expr.args) - 1 and c == True:
|
| 175 |
+
lines.append("else {")
|
| 176 |
+
else:
|
| 177 |
+
lines.append("else if (%s) {" % self._print(c))
|
| 178 |
+
code0 = self._print(e)
|
| 179 |
+
lines.append(code0)
|
| 180 |
+
lines.append("}")
|
| 181 |
+
return "\n".join(lines)
|
| 182 |
+
else:
|
| 183 |
+
# The piecewise was used in an expression, need to do inline
|
| 184 |
+
# operators. This has the downside that inline operators will
|
| 185 |
+
# not work for statements that span multiple lines (Matrix or
|
| 186 |
+
# Indexed expressions).
|
| 187 |
+
ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), self._print(e))
|
| 188 |
+
for e, c in expr.args[:-1]]
|
| 189 |
+
last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
|
| 190 |
+
return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
|
| 191 |
+
|
| 192 |
+
def _print_MatrixElement(self, expr):
|
| 193 |
+
return "{}[{}]".format(self.parenthesize(expr.parent,
|
| 194 |
+
PRECEDENCE["Atom"], strict=True),
|
| 195 |
+
expr.j + expr.i*expr.parent.shape[1])
|
| 196 |
+
|
| 197 |
+
def indent_code(self, code):
|
| 198 |
+
"""Accepts a string of code or a list of code lines"""
|
| 199 |
+
|
| 200 |
+
if isinstance(code, str):
|
| 201 |
+
code_lines = self.indent_code(code.splitlines(True))
|
| 202 |
+
return ''.join(code_lines)
|
| 203 |
+
|
| 204 |
+
tab = " "
|
| 205 |
+
inc_token = ('{', '(', '{\n', '(\n')
|
| 206 |
+
dec_token = ('}', ')')
|
| 207 |
+
|
| 208 |
+
code = [ line.lstrip(' \t') for line in code ]
|
| 209 |
+
|
| 210 |
+
increase = [ int(any(map(line.endswith, inc_token))) for line in code ]
|
| 211 |
+
decrease = [ int(any(map(line.startswith, dec_token)))
|
| 212 |
+
for line in code ]
|
| 213 |
+
|
| 214 |
+
pretty = []
|
| 215 |
+
level = 0
|
| 216 |
+
for n, line in enumerate(code):
|
| 217 |
+
if line in ('', '\n'):
|
| 218 |
+
pretty.append(line)
|
| 219 |
+
continue
|
| 220 |
+
level -= decrease[n]
|
| 221 |
+
pretty.append("%s%s" % (tab*level, line))
|
| 222 |
+
level += increase[n]
|
| 223 |
+
return pretty
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def jscode(expr, assign_to=None, **settings):
|
| 227 |
+
"""Converts an expr to a string of javascript code
|
| 228 |
+
|
| 229 |
+
Parameters
|
| 230 |
+
==========
|
| 231 |
+
|
| 232 |
+
expr : Expr
|
| 233 |
+
A SymPy expression to be converted.
|
| 234 |
+
assign_to : optional
|
| 235 |
+
When given, the argument is used as the name of the variable to which
|
| 236 |
+
the expression is assigned. Can be a string, ``Symbol``,
|
| 237 |
+
``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
|
| 238 |
+
line-wrapping, or for expressions that generate multi-line statements.
|
| 239 |
+
precision : integer, optional
|
| 240 |
+
The precision for numbers such as pi [default=15].
|
| 241 |
+
user_functions : dict, optional
|
| 242 |
+
A dictionary where keys are ``FunctionClass`` instances and values are
|
| 243 |
+
their string representations. Alternatively, the dictionary value can
|
| 244 |
+
be a list of tuples i.e. [(argument_test, js_function_string)]. See
|
| 245 |
+
below for examples.
|
| 246 |
+
human : bool, optional
|
| 247 |
+
If True, the result is a single string that may contain some constant
|
| 248 |
+
declarations for the number symbols. If False, the same information is
|
| 249 |
+
returned in a tuple of (symbols_to_declare, not_supported_functions,
|
| 250 |
+
code_text). [default=True].
|
| 251 |
+
contract: bool, optional
|
| 252 |
+
If True, ``Indexed`` instances are assumed to obey tensor contraction
|
| 253 |
+
rules and the corresponding nested loops over indices are generated.
|
| 254 |
+
Setting contract=False will not generate loops, instead the user is
|
| 255 |
+
responsible to provide values for the indices in the code.
|
| 256 |
+
[default=True].
|
| 257 |
+
|
| 258 |
+
Examples
|
| 259 |
+
========
|
| 260 |
+
|
| 261 |
+
>>> from sympy import jscode, symbols, Rational, sin, ceiling, Abs
|
| 262 |
+
>>> x, tau = symbols("x, tau")
|
| 263 |
+
>>> jscode((2*tau)**Rational(7, 2))
|
| 264 |
+
'8*Math.sqrt(2)*Math.pow(tau, 7/2)'
|
| 265 |
+
>>> jscode(sin(x), assign_to="s")
|
| 266 |
+
's = Math.sin(x);'
|
| 267 |
+
|
| 268 |
+
Custom printing can be defined for certain types by passing a dictionary of
|
| 269 |
+
"type" : "function" to the ``user_functions`` kwarg. Alternatively, the
|
| 270 |
+
dictionary value can be a list of tuples i.e. [(argument_test,
|
| 271 |
+
js_function_string)].
|
| 272 |
+
|
| 273 |
+
>>> custom_functions = {
|
| 274 |
+
... "ceiling": "CEIL",
|
| 275 |
+
... "Abs": [(lambda x: not x.is_integer, "fabs"),
|
| 276 |
+
... (lambda x: x.is_integer, "ABS")]
|
| 277 |
+
... }
|
| 278 |
+
>>> jscode(Abs(x) + ceiling(x), user_functions=custom_functions)
|
| 279 |
+
'fabs(x) + CEIL(x)'
|
| 280 |
+
|
| 281 |
+
``Piecewise`` expressions are converted into conditionals. If an
|
| 282 |
+
``assign_to`` variable is provided an if statement is created, otherwise
|
| 283 |
+
the ternary operator is used. Note that if the ``Piecewise`` lacks a
|
| 284 |
+
default term, represented by ``(expr, True)`` then an error will be thrown.
|
| 285 |
+
This is to prevent generating an expression that may not evaluate to
|
| 286 |
+
anything.
|
| 287 |
+
|
| 288 |
+
>>> from sympy import Piecewise
|
| 289 |
+
>>> expr = Piecewise((x + 1, x > 0), (x, True))
|
| 290 |
+
>>> print(jscode(expr, tau))
|
| 291 |
+
if (x > 0) {
|
| 292 |
+
tau = x + 1;
|
| 293 |
+
}
|
| 294 |
+
else {
|
| 295 |
+
tau = x;
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
Support for loops is provided through ``Indexed`` types. With
|
| 299 |
+
``contract=True`` these expressions will be turned into loops, whereas
|
| 300 |
+
``contract=False`` will just print the assignment expression that should be
|
| 301 |
+
looped over:
|
| 302 |
+
|
| 303 |
+
>>> from sympy import Eq, IndexedBase, Idx
|
| 304 |
+
>>> len_y = 5
|
| 305 |
+
>>> y = IndexedBase('y', shape=(len_y,))
|
| 306 |
+
>>> t = IndexedBase('t', shape=(len_y,))
|
| 307 |
+
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
|
| 308 |
+
>>> i = Idx('i', len_y-1)
|
| 309 |
+
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
|
| 310 |
+
>>> jscode(e.rhs, assign_to=e.lhs, contract=False)
|
| 311 |
+
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
|
| 312 |
+
|
| 313 |
+
Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
|
| 314 |
+
must be provided to ``assign_to``. Note that any expression that can be
|
| 315 |
+
generated normally can also exist inside a Matrix:
|
| 316 |
+
|
| 317 |
+
>>> from sympy import Matrix, MatrixSymbol
|
| 318 |
+
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
|
| 319 |
+
>>> A = MatrixSymbol('A', 3, 1)
|
| 320 |
+
>>> print(jscode(mat, A))
|
| 321 |
+
A[0] = Math.pow(x, 2);
|
| 322 |
+
if (x > 0) {
|
| 323 |
+
A[1] = x + 1;
|
| 324 |
+
}
|
| 325 |
+
else {
|
| 326 |
+
A[1] = x;
|
| 327 |
+
}
|
| 328 |
+
A[2] = Math.sin(x);
|
| 329 |
+
"""
|
| 330 |
+
|
| 331 |
+
return JavascriptCodePrinter(settings).doprint(expr, assign_to)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def print_jscode(expr, **settings):
|
| 335 |
+
"""Prints the Javascript representation of the given expression.
|
| 336 |
+
|
| 337 |
+
See jscode for the meaning of the optional arguments.
|
| 338 |
+
"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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <cfloat>
|
| 4 |
+
#include <limits>
|
| 5 |
+
#include <stdint.h>
|
| 6 |
+
#include <cuda_fp16.h>
|
| 7 |
+
#include <c10/macros/Macros.h>
|
| 8 |
+
|
| 9 |
+
#include <ATen/cuda/DeviceUtils.cuh>
|
| 10 |
+
|
| 11 |
+
namespace {
|
| 12 |
+
|
| 13 |
+
int log2_ceil(int value) {
|
| 14 |
+
int log2_value = 0;
|
| 15 |
+
while ((1 << log2_value) < value) ++log2_value;
|
| 16 |
+
return log2_value;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
template<typename T>
|
| 20 |
+
struct Add {
|
| 21 |
+
__device__ __forceinline__ T operator()(T a, T b) const {
|
| 22 |
+
return a + b;
|
| 23 |
+
}
|
| 24 |
+
};
|
| 25 |
+
|
| 26 |
+
template<typename T>
|
| 27 |
+
struct Max {
|
| 28 |
+
__device__ __forceinline__ T operator()(T a, T b) const {
|
| 29 |
+
return a < b ? b : a;
|
| 30 |
+
}
|
| 31 |
+
};
|
| 32 |
+
|
| 33 |
+
template <typename acc_t, int WARP_BATCH, int WARP_SIZE, template<typename> class ReduceOp>
|
| 34 |
+
__device__ __forceinline__ void warp_reduce(acc_t* sum) {
|
| 35 |
+
ReduceOp<acc_t> r;
|
| 36 |
+
#pragma unroll
|
| 37 |
+
for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) {
|
| 38 |
+
#pragma unroll
|
| 39 |
+
for (int i = 0; i < WARP_BATCH; ++i) {
|
| 40 |
+
acc_t b = WARP_SHFL_XOR(sum[i], offset, WARP_SIZE);
|
| 41 |
+
sum[i] = r(sum[i], b);
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
// The softmax_warp_* methods perform softmax forward and backward propagation on samples spanning the fast dimension.
|
| 47 |
+
// Each sample contains element_count scalar elements. element_count can be any integer value <= 1024.
|
| 48 |
+
// The template arguments have the following meaning:
|
| 49 |
+
// One "WARP" works on one "BATCH". One "BATCH" contains "WARP_BATCH" samples.
|
| 50 |
+
// WARP_BATCH is equal to 1 when element_count is large, and > 1 when element_count is small.
|
| 51 |
+
// A "WARP" contains "C10_WARPS_SIZE" threads, these treads are guaranteed to belong to the same warp.
|
| 52 |
+
// This is important because it means only __shfl_ instructions are required for reductions.
|
| 53 |
+
// Note that this means WARP_SIZE must be a power of two and <= architecture warp size.
|
| 54 |
+
// CUDA warp size is 32 for all existing GPU architectures, but there is no guarantee this will not change for future arch.
|
| 55 |
+
// ROCm warp size is 64 for all currently ROCm-supported GPU architectures, but this may change for future archs.
|
| 56 |
+
// is_log_softmax is a flag indicating whether SoftMax or LogSoftMax should be computed.
|
| 57 |
+
// is_masked is a flag indicating whether SoftMax or MaskedSoftMax should be computed.
|
| 58 |
+
// The template can be instantiated with any floating point type for the type arguments input_t, output_t and acc_t.
|
| 59 |
+
// This allows SoftMax to be fused with a cast immediately following the SoftMax.
|
| 60 |
+
// The mask should have the same shape as input, with a boolean indicate if the value is masked.
|
| 61 |
+
// The head_chunk_size is only used for transformer mask softmax, equals to H * D * D.
|
| 62 |
+
// For instance:
|
| 63 |
+
// input_t=half, acc_t=float, output_t=half => read half tensor, float accumulators, write half tensor.
|
| 64 |
+
// input_t=half, acc_t=float, output_t=float => read half tensor, float accumulators, write float tensor.
|
| 65 |
+
// input_t_float, acc_t=float, output_t=half => read float tensor, float accumulators, write half tensor.
|
| 66 |
+
|
| 67 |
+
template <typename input_t, typename output_t, typename acc_t, int log2_elements, bool is_log_softmax, bool is_masked>
|
| 68 |
+
__global__ void softmax_warp_forward(output_t *dst, const input_t *src, int batch_size, int stride, int element_count, const bool *mask = nullptr, const int head_chunk_size = -1, bool is_transformer_mask = false)
|
| 69 |
+
{
|
| 70 |
+
// WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and warp_size of method warp_softmax_forward_kernel.
|
| 71 |
+
constexpr int next_power_of_two = 1 << log2_elements;
|
| 72 |
+
constexpr int WARP_SIZE = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE;
|
| 73 |
+
constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE;
|
| 74 |
+
constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1;
|
| 75 |
+
|
| 76 |
+
int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH;
|
| 77 |
+
|
| 78 |
+
// batch_size might not be a multiple of WARP_BATCH. Check how
|
| 79 |
+
// many batches have to computed within this WARP.
|
| 80 |
+
int local_batches = batch_size - first_batch;
|
| 81 |
+
if (local_batches > WARP_BATCH)
|
| 82 |
+
local_batches = WARP_BATCH;
|
| 83 |
+
|
| 84 |
+
// there might be multiple batches per warp. compute the index within the batch
|
| 85 |
+
int local_idx = threadIdx.x;
|
| 86 |
+
int idx_offset = first_batch * stride + local_idx;
|
| 87 |
+
|
| 88 |
+
src += idx_offset;
|
| 89 |
+
dst += idx_offset;
|
| 90 |
+
|
| 91 |
+
if (is_transformer_mask) {
|
| 92 |
+
mask += ((first_batch * stride) / head_chunk_size) * stride + local_idx;
|
| 93 |
+
} else {
|
| 94 |
+
mask += idx_offset;
|
| 95 |
+
}
|
| 96 |
+
// The nested loops over WARP_BATCH and then WARP_ITERATIONS can be simplified to one loop,
|
| 97 |
+
// but I think doing so would obfuscate the logic of the algorithm, thus I chose to keep
|
| 98 |
+
// the nested loops.
|
| 99 |
+
// This should have no impact on performance because the loops are unrolled anyway.
|
| 100 |
+
|
| 101 |
+
// load data from global memory
|
| 102 |
+
acc_t elements[WARP_BATCH][WARP_ITERATIONS];
|
| 103 |
+
for (int i = 0; i < WARP_BATCH; ++i) {
|
| 104 |
+
int batch_element_count = (i >= local_batches) ? 0 : element_count;
|
| 105 |
+
for (int it = 0; it < WARP_ITERATIONS; ++it) {
|
| 106 |
+
int element_index = local_idx + it * WARP_SIZE;
|
| 107 |
+
if (element_index < batch_element_count) {
|
| 108 |
+
elements[i][it] = src[i*element_count+it*WARP_SIZE];
|
| 109 |
+
} else {
|
| 110 |
+
elements[i][it] = -std::numeric_limits<acc_t>::infinity();
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
// compute max_value
|
| 116 |
+
acc_t max_value[WARP_BATCH];
|
| 117 |
+
#pragma unroll
|
| 118 |
+
for (int i = 0; i < WARP_BATCH; ++i) {
|
| 119 |
+
int batch_element_count = (i >= local_batches) ? 0 : element_count;
|
| 120 |
+
bool is_meaningful_max = false;
|
| 121 |
+
max_value[i] = elements[i][0];
|
| 122 |
+
#pragma unroll
|
| 123 |
+
for (int it = 0; it < WARP_ITERATIONS; ++it) {
|
| 124 |
+
if (is_masked) {
|
| 125 |
+
int idx = it*WARP_SIZE;
|
| 126 |
+
if ((idx + local_idx) < batch_element_count) {
|
| 127 |
+
if (!is_transformer_mask) {
|
| 128 |
+
idx += i*element_count;
|
| 129 |
+
}
|
| 130 |
+
if (!mask[idx]) {
|
| 131 |
+
max_value[i] = (is_meaningful_max && max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it];
|
| 132 |
+
is_meaningful_max = true;
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
} else {
|
| 136 |
+
max_value[i] = max_value[i] > elements[i][it] ? max_value[i] : elements[i][it];
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
if (is_masked) {
|
| 140 |
+
if (!is_meaningful_max) {
|
| 141 |
+
max_value[i] = -std::numeric_limits<acc_t>::infinity();
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
warp_reduce<acc_t, WARP_BATCH, WARP_SIZE, Max>(max_value);
|
| 146 |
+
|
| 147 |
+
acc_t sum[WARP_BATCH] { 0.0f };
|
| 148 |
+
#pragma unroll
|
| 149 |
+
for (int i = 0; i < WARP_BATCH; ++i) {
|
| 150 |
+
int batch_element_count = (i >= local_batches) ? 0 : element_count;
|
| 151 |
+
#pragma unroll
|
| 152 |
+
for (int it = 0; it < WARP_ITERATIONS; ++it) {
|
| 153 |
+
if (!is_masked) {
|
| 154 |
+
if (is_log_softmax) {
|
| 155 |
+
sum[i] += std::exp(elements[i][it] - max_value[i]);
|
| 156 |
+
} else {
|
| 157 |
+
elements[i][it] = std::exp(elements[i][it] - max_value[i]);
|
| 158 |
+
sum[i] += elements[i][it];
|
| 159 |
+
}
|
| 160 |
+
} else {
|
| 161 |
+
int idx = it*WARP_SIZE;
|
| 162 |
+
bool valid = (idx + local_idx) < batch_element_count;
|
| 163 |
+
if (!is_transformer_mask) {
|
| 164 |
+
idx += i*element_count;
|
| 165 |
+
}
|
| 166 |
+
if (valid) {
|
| 167 |
+
if (!mask[idx]) {
|
| 168 |
+
if (is_log_softmax) {
|
| 169 |
+
sum[i] += std::exp(elements[i][it] - max_value[i]);
|
| 170 |
+
} else {
|
| 171 |
+
elements[i][it] = std::exp(elements[i][it] - max_value[i]);
|
| 172 |
+
sum[i] += elements[i][it];
|
| 173 |
+
}
|
| 174 |
+
} else {
|
| 175 |
+
if (!is_log_softmax) {
|
| 176 |
+
// Masked values are treated as -infinity, and std::exp(-infinity) is 0.
|
| 177 |
+
elements[i][it] = 0;
|
| 178 |
+
}
|
| 179 |
+
}
|
| 180 |
+
} else {
|
| 181 |
+
if (!is_log_softmax) {
|
| 182 |
+
elements[i][it] = 0.;
|
| 183 |
+
}
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
}
|
| 187 |
+
}
|
| 188 |
+
warp_reduce<acc_t, WARP_BATCH, WARP_SIZE, Add>(sum);
|
| 189 |
+
|
| 190 |
+
// store result
|
| 191 |
+
#pragma unroll
|
| 192 |
+
for (int i = 0; i < WARP_BATCH; ++i) {
|
| 193 |
+
if (i >= local_batches)
|
| 194 |
+
break;
|
| 195 |
+
if (is_log_softmax) sum[i] = std::log(sum[i]);
|
| 196 |
+
#pragma unroll
|
| 197 |
+
for (int it = 0; it < WARP_ITERATIONS; ++it) {
|
| 198 |
+
int element_index = local_idx + it * WARP_SIZE;
|
| 199 |
+
if (element_index < element_count) {
|
| 200 |
+
if (is_log_softmax) {
|
| 201 |
+
dst[i*element_count+it*WARP_SIZE] = elements[i][it] - max_value[i] - sum[i];
|
| 202 |
+
} else if (sum[i] == 0) {
|
| 203 |
+
dst[i*element_count+it*WARP_SIZE] = std::numeric_limits<acc_t>::quiet_NaN();
|
| 204 |
+
} else {
|
| 205 |
+
dst[i*element_count+it*WARP_SIZE] = elements[i][it] / sum[i];
|
| 206 |
+
}
|
| 207 |
+
} else {
|
| 208 |
+
break;
|
| 209 |
+
}
|
| 210 |
+
}
|
| 211 |
+
}
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
template <typename input_t, typename output_t, typename acc_t, int log2_elements, bool is_log_softmax, bool is_masked>
|
| 215 |
+
__global__ void softmax_warp_backward(output_t *gradInput, const input_t *grad, const input_t *output, int batch_size, int stride, int element_count, const bool *mask = nullptr)
|
| 216 |
+
{
|
| 217 |
+
// WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and warp_size of method warp_softmax_backward_kernel.
|
| 218 |
+
constexpr int next_power_of_two = 1 << log2_elements;
|
| 219 |
+
constexpr int WARP_SIZE = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE;
|
| 220 |
+
constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE;
|
| 221 |
+
constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1;
|
| 222 |
+
|
| 223 |
+
int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH;
|
| 224 |
+
|
| 225 |
+
// batch_size might not be a multiple of WARP_BATCH. Check how
|
| 226 |
+
// many batches have to computed within this WARP.
|
| 227 |
+
int local_batches = batch_size - first_batch;
|
| 228 |
+
if (local_batches > WARP_BATCH)
|
| 229 |
+
local_batches = WARP_BATCH;
|
| 230 |
+
|
| 231 |
+
// there might be multiple batches per warp. compute the index within the batch
|
| 232 |
+
int local_idx = threadIdx.x % WARP_SIZE;
|
| 233 |
+
|
| 234 |
+
// the first element to process by the current thread
|
| 235 |
+
int thread_offset = first_batch * stride + local_idx;
|
| 236 |
+
grad += thread_offset;
|
| 237 |
+
output += thread_offset;
|
| 238 |
+
gradInput += thread_offset;
|
| 239 |
+
if (is_masked) {
|
| 240 |
+
mask += thread_offset;
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
// The nested loops over WARP_BATCH and then WARP_ITERATIONS can be simplified to one loop,
|
| 244 |
+
// but I think doing so would obfuscate the logic of the algorithm, thus I chose to keep
|
| 245 |
+
// the nested loops.
|
| 246 |
+
// This should have no impact on performance because the loops are unrolled anyway.
|
| 247 |
+
|
| 248 |
+
// load data from global memory
|
| 249 |
+
acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS];
|
| 250 |
+
acc_t output_reg[WARP_BATCH][WARP_ITERATIONS];
|
| 251 |
+
for (int i = 0; i < WARP_BATCH; ++i) {
|
| 252 |
+
int batch_element_count = (i >= local_batches) ? 0 : element_count;
|
| 253 |
+
for (int it = 0; it < WARP_ITERATIONS; ++it) {
|
| 254 |
+
int element_index = local_idx + it * WARP_SIZE;
|
| 255 |
+
if (element_index < batch_element_count) {
|
| 256 |
+
grad_reg[i][it] = grad[i*element_count+it*WARP_SIZE];
|
| 257 |
+
output_reg[i][it] = output[i*element_count+it*WARP_SIZE];
|
| 258 |
+
} else {
|
| 259 |
+
grad_reg[i][it] = acc_t(0);
|
| 260 |
+
output_reg[i][it] = acc_t(0);
|
| 261 |
+
}
|
| 262 |
+
}
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
acc_t sum[WARP_BATCH] { 0.0f };
|
| 266 |
+
#pragma unroll
|
| 267 |
+
for (int i = 0; i < WARP_BATCH; ++i) {
|
| 268 |
+
#pragma unroll
|
| 269 |
+
for (int it = 0; it < WARP_ITERATIONS; ++it) {
|
| 270 |
+
if (!is_masked || !mask[i*element_count+it*WARP_SIZE]) {
|
| 271 |
+
sum[i] += grad_reg[i][it];
|
| 272 |
+
}
|
| 273 |
+
}
|
| 274 |
+
}
|
| 275 |
+
warp_reduce<acc_t, WARP_BATCH, WARP_SIZE, Add>(sum);
|
| 276 |
+
|
| 277 |
+
// store result
|
| 278 |
+
#pragma unroll
|
| 279 |
+
for (int i = 0; i < WARP_BATCH; ++i) {
|
| 280 |
+
if (i >= local_batches)
|
| 281 |
+
break;
|
| 282 |
+
#pragma unroll
|
| 283 |
+
for (int it = 0; it < WARP_ITERATIONS; ++it) {
|
| 284 |
+
int element_index = local_idx + it * WARP_SIZE;
|
| 285 |
+
if (element_index < element_count) {
|
| 286 |
+
if (is_masked && mask[i*element_count+it*WARP_SIZE]) {
|
| 287 |
+
gradInput[i*element_count+it*WARP_SIZE] = 0;
|
| 288 |
+
}
|
| 289 |
+
// compute gradients
|
| 290 |
+
else if (is_log_softmax) {
|
| 291 |
+
gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - std::exp(output_reg[i][it]) * sum[i]);
|
| 292 |
+
} else {
|
| 293 |
+
gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - output_reg[i][it] * sum[i]);
|
| 294 |
+
}
|
| 295 |
+
}
|
| 296 |
+
}
|
| 297 |
+
}
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
} // end of anonymous namespace
|
| 301 |
+
|
| 302 |
+
template<typename input_t, typename output_t, typename acc_t, bool is_log_softmax, bool is_masked>
|
| 303 |
+
void dispatch_softmax_forward(output_t *dst, const input_t *src, int softmax_elements, int softmax_elements_stride, int batch_count, const bool *mask = nullptr, int chunk_size = -1, bool is_transformer_mask = false)
|
| 304 |
+
{
|
| 305 |
+
TORCH_INTERNAL_ASSERT( softmax_elements >= 0 && softmax_elements <= 1024 );
|
| 306 |
+
if (softmax_elements == 0) {
|
| 307 |
+
return;
|
| 308 |
+
} else {
|
| 309 |
+
int log2_elements = log2_ceil(softmax_elements);
|
| 310 |
+
const int next_power_of_two = 1 << log2_elements;
|
| 311 |
+
|
| 312 |
+
// This value must match the WARP_SIZE constexpr value computed inside softmax_warp_forward.
|
| 313 |
+
int warp_size = at::cuda::warp_size();
|
| 314 |
+
warp_size = (next_power_of_two < warp_size) ? next_power_of_two : warp_size;
|
| 315 |
+
|
| 316 |
+
// This value must match the WARP_BATCH constexpr value computed inside softmax_warp_forward.
|
| 317 |
+
int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1;
|
| 318 |
+
|
| 319 |
+
// use 128 threads per block to maximize gpu utilization
|
| 320 |
+
constexpr int threads_per_block = 128;
|
| 321 |
+
|
| 322 |
+
int warps_per_block = (threads_per_block / warp_size);
|
| 323 |
+
int batches_per_block = warps_per_block * batches_per_warp;
|
| 324 |
+
int blocks = (batch_count + batches_per_block - 1) / batches_per_block;
|
| 325 |
+
dim3 threads(warp_size, warps_per_block, 1);
|
| 326 |
+
// Launch code would be more elegant if C++ supported FOR CONSTEXPR
|
| 327 |
+
switch (log2_elements) {
|
| 328 |
+
#define LAUNCH_SOFTMAX_WARP_FORWARD(L2E) case L2E: \
|
| 329 |
+
softmax_warp_forward<input_t, output_t, acc_t, L2E, is_log_softmax, is_masked> \
|
| 330 |
+
<<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, \
|
| 331 |
+
src, batch_count, softmax_elements_stride, softmax_elements, mask, chunk_size, is_transformer_mask); \
|
| 332 |
+
C10_CUDA_KERNEL_LAUNCH_CHECK(); \
|
| 333 |
+
break;
|
| 334 |
+
|
| 335 |
+
LAUNCH_SOFTMAX_WARP_FORWARD(0); // 1
|
| 336 |
+
LAUNCH_SOFTMAX_WARP_FORWARD(1); // 2
|
| 337 |
+
LAUNCH_SOFTMAX_WARP_FORWARD(2); // 4
|
| 338 |
+
LAUNCH_SOFTMAX_WARP_FORWARD(3); // 8
|
| 339 |
+
LAUNCH_SOFTMAX_WARP_FORWARD(4); // 16
|
| 340 |
+
LAUNCH_SOFTMAX_WARP_FORWARD(5); // 32
|
| 341 |
+
LAUNCH_SOFTMAX_WARP_FORWARD(6); // 64
|
| 342 |
+
LAUNCH_SOFTMAX_WARP_FORWARD(7); // 128
|
| 343 |
+
LAUNCH_SOFTMAX_WARP_FORWARD(8); // 256
|
| 344 |
+
LAUNCH_SOFTMAX_WARP_FORWARD(9); // 512
|
| 345 |
+
LAUNCH_SOFTMAX_WARP_FORWARD(10); ; // 1024
|
| 346 |
+
default:
|
| 347 |
+
break;
|
| 348 |
+
}
|
| 349 |
+
}
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
template<typename input_t, typename output_t, typename acc_t, bool is_log_softmax, bool is_masked>
|
| 353 |
+
void dispatch_softmax_backward(output_t *grad_input, const input_t *grad, const input_t *output, int softmax_elements, int softmax_elements_stride, int batch_count, const bool *mask = nullptr)
|
| 354 |
+
{
|
| 355 |
+
TORCH_INTERNAL_ASSERT( softmax_elements >= 0 && softmax_elements <= 1024 );
|
| 356 |
+
if (softmax_elements == 0) {
|
| 357 |
+
return;
|
| 358 |
+
} else {
|
| 359 |
+
int log2_elements = log2_ceil(softmax_elements);
|
| 360 |
+
const int next_power_of_two = 1 << log2_elements;
|
| 361 |
+
|
| 362 |
+
// This value must match the WARP_SIZE constexpr value computed inside softmax_warp_backward.
|
| 363 |
+
int warp_size = at::cuda::warp_size();
|
| 364 |
+
warp_size = (next_power_of_two < warp_size) ? next_power_of_two : warp_size;
|
| 365 |
+
|
| 366 |
+
// This value must match the WARP_BATCH constexpr value computed inside softmax_warp_backward.
|
| 367 |
+
int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1;
|
| 368 |
+
|
| 369 |
+
// use 128 threads per block to maximize gpu utilization
|
| 370 |
+
constexpr int threads_per_block = 128;
|
| 371 |
+
|
| 372 |
+
int warps_per_block = (threads_per_block / warp_size);
|
| 373 |
+
int batches_per_block = warps_per_block * batches_per_warp;
|
| 374 |
+
int blocks = (batch_count + batches_per_block - 1) / batches_per_block;
|
| 375 |
+
dim3 threads(warp_size, warps_per_block, 1);
|
| 376 |
+
// Launch code would be more elegant if C++ supported FOR CONSTEXPR
|
| 377 |
+
switch (log2_elements) {
|
| 378 |
+
#define LAUNCH_SOFTMAX_WARP_BACKWARD(L2E) case L2E: \
|
| 379 |
+
softmax_warp_backward<input_t, output_t, acc_t, L2E, is_log_softmax, is_masked> \
|
| 380 |
+
<<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>> \
|
| 381 |
+
(grad_input, grad, output, batch_count, softmax_elements_stride, \
|
| 382 |
+
softmax_elements, mask); \
|
| 383 |
+
C10_CUDA_KERNEL_LAUNCH_CHECK(); \
|
| 384 |
+
break;
|
| 385 |
+
|
| 386 |
+
LAUNCH_SOFTMAX_WARP_BACKWARD(0); // 1
|
| 387 |
+
LAUNCH_SOFTMAX_WARP_BACKWARD(1); // 2
|
| 388 |
+
LAUNCH_SOFTMAX_WARP_BACKWARD(2); // 4
|
| 389 |
+
LAUNCH_SOFTMAX_WARP_BACKWARD(3); // 8
|
| 390 |
+
LAUNCH_SOFTMAX_WARP_BACKWARD(4); // 16
|
| 391 |
+
LAUNCH_SOFTMAX_WARP_BACKWARD(5); // 32
|
| 392 |
+
LAUNCH_SOFTMAX_WARP_BACKWARD(6); // 64
|
| 393 |
+
LAUNCH_SOFTMAX_WARP_BACKWARD(7); // 128
|
| 394 |
+
LAUNCH_SOFTMAX_WARP_BACKWARD(8); // 256
|
| 395 |
+
LAUNCH_SOFTMAX_WARP_BACKWARD(9); // 512
|
| 396 |
+
LAUNCH_SOFTMAX_WARP_BACKWARD(10); // 1024
|
| 397 |
+
default:
|
| 398 |
+
break;
|
| 399 |
+
}
|
| 400 |
+
}
|
| 401 |
+
}
|
shared/package-files/12/1245cacd62e0fa3a6c57cadea76616e9f0ec083cfe7777d8d6abf541513b308f/scripting.py
ADDED
|
@@ -0,0 +1,1286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
|
| 5 |
+
Lexer for scripting and embedded languages.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import re
|
| 12 |
+
|
| 13 |
+
from pygments.lexer import RegexLexer, include, bygroups, default, combined, \
|
| 14 |
+
words
|
| 15 |
+
from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
|
| 16 |
+
Number, Punctuation, Error, Whitespace, Other
|
| 17 |
+
from pygments.util import get_bool_opt, get_list_opt
|
| 18 |
+
|
| 19 |
+
__all__ = ['LuaLexer', 'MoonScriptLexer', 'ChaiscriptLexer', 'LSLLexer',
|
| 20 |
+
'AppleScriptLexer', 'RexxLexer', 'MOOCodeLexer', 'HybrisLexer',
|
| 21 |
+
'EasytrieveLexer', 'JclLexer', 'MiniScriptLexer']
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class LuaLexer(RegexLexer):
|
| 25 |
+
"""
|
| 26 |
+
For Lua source code.
|
| 27 |
+
|
| 28 |
+
Additional options accepted:
|
| 29 |
+
|
| 30 |
+
`func_name_highlighting`
|
| 31 |
+
If given and ``True``, highlight builtin function names
|
| 32 |
+
(default: ``True``).
|
| 33 |
+
`disabled_modules`
|
| 34 |
+
If given, must be a list of module names whose function names
|
| 35 |
+
should not be highlighted. By default all modules are highlighted.
|
| 36 |
+
|
| 37 |
+
To get a list of allowed modules have a look into the
|
| 38 |
+
`_lua_builtins` module:
|
| 39 |
+
|
| 40 |
+
.. sourcecode:: pycon
|
| 41 |
+
|
| 42 |
+
>>> from pygments.lexers._lua_builtins import MODULES
|
| 43 |
+
>>> MODULES.keys()
|
| 44 |
+
['string', 'coroutine', 'modules', 'io', 'basic', ...]
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
name = 'Lua'
|
| 48 |
+
url = 'https://www.lua.org/'
|
| 49 |
+
aliases = ['lua']
|
| 50 |
+
filenames = ['*.lua', '*.wlua']
|
| 51 |
+
mimetypes = ['text/x-lua', 'application/x-lua']
|
| 52 |
+
|
| 53 |
+
_comment_multiline = r'(?:--\[(?P<level>=*)\[[\w\W]*?\](?P=level)\])'
|
| 54 |
+
_comment_single = r'(?:--.*$)'
|
| 55 |
+
_space = r'(?:\s+)'
|
| 56 |
+
_s = r'(?:%s|%s|%s)' % (_comment_multiline, _comment_single, _space)
|
| 57 |
+
_name = r'(?:[^\W\d]\w*)'
|
| 58 |
+
|
| 59 |
+
tokens = {
|
| 60 |
+
'root': [
|
| 61 |
+
# Lua allows a file to start with a shebang.
|
| 62 |
+
(r'#!.*', Comment.Preproc),
|
| 63 |
+
default('base'),
|
| 64 |
+
],
|
| 65 |
+
'ws': [
|
| 66 |
+
(_comment_multiline, Comment.Multiline),
|
| 67 |
+
(_comment_single, Comment.Single),
|
| 68 |
+
(_space, Text),
|
| 69 |
+
],
|
| 70 |
+
'base': [
|
| 71 |
+
include('ws'),
|
| 72 |
+
|
| 73 |
+
(r'(?i)0x[\da-f]*(\.[\da-f]*)?(p[+-]?\d+)?', Number.Hex),
|
| 74 |
+
(r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float),
|
| 75 |
+
(r'(?i)\d+e[+-]?\d+', Number.Float),
|
| 76 |
+
(r'\d+', Number.Integer),
|
| 77 |
+
|
| 78 |
+
# multiline strings
|
| 79 |
+
(r'(?s)\[(=*)\[.*?\]\1\]', String),
|
| 80 |
+
|
| 81 |
+
(r'::', Punctuation, 'label'),
|
| 82 |
+
(r'\.{3}', Punctuation),
|
| 83 |
+
(r'[=<>|~&+\-*/%#^]+|\.\.', Operator),
|
| 84 |
+
(r'[\[\]{}().,:;]', Punctuation),
|
| 85 |
+
(r'(and|or|not)\b', Operator.Word),
|
| 86 |
+
|
| 87 |
+
('(break|do|else|elseif|end|for|if|in|repeat|return|then|until|'
|
| 88 |
+
r'while)\b', Keyword.Reserved),
|
| 89 |
+
(r'goto\b', Keyword.Reserved, 'goto'),
|
| 90 |
+
(r'(local)\b', Keyword.Declaration),
|
| 91 |
+
(r'(true|false|nil)\b', Keyword.Constant),
|
| 92 |
+
|
| 93 |
+
(r'(function)\b', Keyword.Reserved, 'funcname'),
|
| 94 |
+
|
| 95 |
+
(r'[A-Za-z_]\w*(\.[A-Za-z_]\w*)?', Name),
|
| 96 |
+
|
| 97 |
+
("'", String.Single, combined('stringescape', 'sqs')),
|
| 98 |
+
('"', String.Double, combined('stringescape', 'dqs'))
|
| 99 |
+
],
|
| 100 |
+
|
| 101 |
+
'funcname': [
|
| 102 |
+
include('ws'),
|
| 103 |
+
(r'[.:]', Punctuation),
|
| 104 |
+
(r'%s(?=%s*[.:])' % (_name, _s), Name.Class),
|
| 105 |
+
(_name, Name.Function, '#pop'),
|
| 106 |
+
# inline function
|
| 107 |
+
(r'\(', Punctuation, '#pop'),
|
| 108 |
+
],
|
| 109 |
+
|
| 110 |
+
'goto': [
|
| 111 |
+
include('ws'),
|
| 112 |
+
(_name, Name.Label, '#pop'),
|
| 113 |
+
],
|
| 114 |
+
|
| 115 |
+
'label': [
|
| 116 |
+
include('ws'),
|
| 117 |
+
(r'::', Punctuation, '#pop'),
|
| 118 |
+
(_name, Name.Label),
|
| 119 |
+
],
|
| 120 |
+
|
| 121 |
+
'stringescape': [
|
| 122 |
+
(r'\\([abfnrtv\\"\']|[\r\n]{1,2}|z\s*|x[0-9a-fA-F]{2}|\d{1,3}|'
|
| 123 |
+
r'u\{[0-9a-fA-F]+\})', String.Escape),
|
| 124 |
+
],
|
| 125 |
+
|
| 126 |
+
'sqs': [
|
| 127 |
+
(r"'", String.Single, '#pop'),
|
| 128 |
+
(r"[^\\']+", String.Single),
|
| 129 |
+
],
|
| 130 |
+
|
| 131 |
+
'dqs': [
|
| 132 |
+
(r'"', String.Double, '#pop'),
|
| 133 |
+
(r'[^\\"]+', String.Double),
|
| 134 |
+
]
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
def __init__(self, **options):
|
| 138 |
+
self.func_name_highlighting = get_bool_opt(
|
| 139 |
+
options, 'func_name_highlighting', True)
|
| 140 |
+
self.disabled_modules = get_list_opt(options, 'disabled_modules', [])
|
| 141 |
+
|
| 142 |
+
self._functions = set()
|
| 143 |
+
if self.func_name_highlighting:
|
| 144 |
+
from pygments.lexers._lua_builtins import MODULES
|
| 145 |
+
for mod, func in MODULES.items():
|
| 146 |
+
if mod not in self.disabled_modules:
|
| 147 |
+
self._functions.update(func)
|
| 148 |
+
RegexLexer.__init__(self, **options)
|
| 149 |
+
|
| 150 |
+
def get_tokens_unprocessed(self, text):
|
| 151 |
+
for index, token, value in \
|
| 152 |
+
RegexLexer.get_tokens_unprocessed(self, text):
|
| 153 |
+
if token is Name:
|
| 154 |
+
if value in self._functions:
|
| 155 |
+
yield index, Name.Builtin, value
|
| 156 |
+
continue
|
| 157 |
+
elif '.' in value:
|
| 158 |
+
a, b = value.split('.')
|
| 159 |
+
yield index, Name, a
|
| 160 |
+
yield index + len(a), Punctuation, '.'
|
| 161 |
+
yield index + len(a) + 1, Name, b
|
| 162 |
+
continue
|
| 163 |
+
yield index, token, value
|
| 164 |
+
|
| 165 |
+
class MoonScriptLexer(LuaLexer):
|
| 166 |
+
"""
|
| 167 |
+
For MoonScript source code.
|
| 168 |
+
|
| 169 |
+
.. versionadded:: 1.5
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
+
name = 'MoonScript'
|
| 173 |
+
url = 'http://moonscript.org'
|
| 174 |
+
aliases = ['moonscript', 'moon']
|
| 175 |
+
filenames = ['*.moon']
|
| 176 |
+
mimetypes = ['text/x-moonscript', 'application/x-moonscript']
|
| 177 |
+
|
| 178 |
+
tokens = {
|
| 179 |
+
'root': [
|
| 180 |
+
(r'#!(.*?)$', Comment.Preproc),
|
| 181 |
+
default('base'),
|
| 182 |
+
],
|
| 183 |
+
'base': [
|
| 184 |
+
('--.*$', Comment.Single),
|
| 185 |
+
(r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number.Float),
|
| 186 |
+
(r'(?i)\d+e[+-]?\d+', Number.Float),
|
| 187 |
+
(r'(?i)0x[0-9a-f]*', Number.Hex),
|
| 188 |
+
(r'\d+', Number.Integer),
|
| 189 |
+
(r'\n', Whitespace),
|
| 190 |
+
(r'[^\S\n]+', Text),
|
| 191 |
+
(r'(?s)\[(=*)\[.*?\]\1\]', String),
|
| 192 |
+
(r'(->|=>)', Name.Function),
|
| 193 |
+
(r':[a-zA-Z_]\w*', Name.Variable),
|
| 194 |
+
(r'(==|!=|~=|<=|>=|\.\.\.|\.\.|[=+\-*/%^<>#!.\\:])', Operator),
|
| 195 |
+
(r'[;,]', Punctuation),
|
| 196 |
+
(r'[\[\]{}()]', Keyword.Type),
|
| 197 |
+
(r'[a-zA-Z_]\w*:', Name.Variable),
|
| 198 |
+
(words((
|
| 199 |
+
'class', 'extends', 'if', 'then', 'super', 'do', 'with',
|
| 200 |
+
'import', 'export', 'while', 'elseif', 'return', 'for', 'in',
|
| 201 |
+
'from', 'when', 'using', 'else', 'and', 'or', 'not', 'switch',
|
| 202 |
+
'break'), suffix=r'\b'),
|
| 203 |
+
Keyword),
|
| 204 |
+
(r'(true|false|nil)\b', Keyword.Constant),
|
| 205 |
+
(r'(and|or|not)\b', Operator.Word),
|
| 206 |
+
(r'(self)\b', Name.Builtin.Pseudo),
|
| 207 |
+
(r'@@?([a-zA-Z_]\w*)?', Name.Variable.Class),
|
| 208 |
+
(r'[A-Z]\w*', Name.Class), # proper name
|
| 209 |
+
(r'[A-Za-z_]\w*(\.[A-Za-z_]\w*)?', Name),
|
| 210 |
+
("'", String.Single, combined('stringescape', 'sqs')),
|
| 211 |
+
('"', String.Double, combined('stringescape', 'dqs'))
|
| 212 |
+
],
|
| 213 |
+
'stringescape': [
|
| 214 |
+
(r'''\\([abfnrtv\\"']|\d{1,3})''', String.Escape)
|
| 215 |
+
],
|
| 216 |
+
'sqs': [
|
| 217 |
+
("'", String.Single, '#pop'),
|
| 218 |
+
("[^']+", String)
|
| 219 |
+
],
|
| 220 |
+
'dqs': [
|
| 221 |
+
('"', String.Double, '#pop'),
|
| 222 |
+
('[^"]+', String)
|
| 223 |
+
]
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
def get_tokens_unprocessed(self, text):
|
| 227 |
+
# set . as Operator instead of Punctuation
|
| 228 |
+
for index, token, value in LuaLexer.get_tokens_unprocessed(self, text):
|
| 229 |
+
if token == Punctuation and value == ".":
|
| 230 |
+
token = Operator
|
| 231 |
+
yield index, token, value
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class ChaiscriptLexer(RegexLexer):
|
| 235 |
+
"""
|
| 236 |
+
For ChaiScript source code.
|
| 237 |
+
|
| 238 |
+
.. versionadded:: 2.0
|
| 239 |
+
"""
|
| 240 |
+
|
| 241 |
+
name = 'ChaiScript'
|
| 242 |
+
url = 'http://chaiscript.com/'
|
| 243 |
+
aliases = ['chaiscript', 'chai']
|
| 244 |
+
filenames = ['*.chai']
|
| 245 |
+
mimetypes = ['text/x-chaiscript', 'application/x-chaiscript']
|
| 246 |
+
|
| 247 |
+
flags = re.DOTALL | re.MULTILINE
|
| 248 |
+
|
| 249 |
+
tokens = {
|
| 250 |
+
'commentsandwhitespace': [
|
| 251 |
+
(r'\s+', Text),
|
| 252 |
+
(r'//.*?\n', Comment.Single),
|
| 253 |
+
(r'/\*.*?\*/', Comment.Multiline),
|
| 254 |
+
(r'^\#.*?\n', Comment.Single)
|
| 255 |
+
],
|
| 256 |
+
'slashstartsregex': [
|
| 257 |
+
include('commentsandwhitespace'),
|
| 258 |
+
(r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/'
|
| 259 |
+
r'([gim]+\b|\B)', String.Regex, '#pop'),
|
| 260 |
+
(r'(?=/)', Text, ('#pop', 'badregex')),
|
| 261 |
+
default('#pop')
|
| 262 |
+
],
|
| 263 |
+
'badregex': [
|
| 264 |
+
(r'\n', Text, '#pop')
|
| 265 |
+
],
|
| 266 |
+
'root': [
|
| 267 |
+
include('commentsandwhitespace'),
|
| 268 |
+
(r'\n', Text),
|
| 269 |
+
(r'[^\S\n]+', Text),
|
| 270 |
+
(r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|\.\.'
|
| 271 |
+
r'(<<|>>>?|==?|!=?|[-<>+*%&|^/])=?', Operator, 'slashstartsregex'),
|
| 272 |
+
(r'[{(\[;,]', Punctuation, 'slashstartsregex'),
|
| 273 |
+
(r'[})\].]', Punctuation),
|
| 274 |
+
(r'[=+\-*/]', Operator),
|
| 275 |
+
(r'(for|in|while|do|break|return|continue|if|else|'
|
| 276 |
+
r'throw|try|catch'
|
| 277 |
+
r')\b', Keyword, 'slashstartsregex'),
|
| 278 |
+
(r'(var)\b', Keyword.Declaration, 'slashstartsregex'),
|
| 279 |
+
(r'(attr|def|fun)\b', Keyword.Reserved),
|
| 280 |
+
(r'(true|false)\b', Keyword.Constant),
|
| 281 |
+
(r'(eval|throw)\b', Name.Builtin),
|
| 282 |
+
(r'`\S+`', Name.Builtin),
|
| 283 |
+
(r'[$a-zA-Z_]\w*', Name.Other),
|
| 284 |
+
(r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
|
| 285 |
+
(r'0x[0-9a-fA-F]+', Number.Hex),
|
| 286 |
+
(r'[0-9]+', Number.Integer),
|
| 287 |
+
(r'"', String.Double, 'dqstring'),
|
| 288 |
+
(r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single),
|
| 289 |
+
],
|
| 290 |
+
'dqstring': [
|
| 291 |
+
(r'\$\{[^"}]+?\}', String.Interpol),
|
| 292 |
+
(r'\$', String.Double),
|
| 293 |
+
(r'\\\\', String.Double),
|
| 294 |
+
(r'\\"', String.Double),
|
| 295 |
+
(r'[^\\"$]+', String.Double),
|
| 296 |
+
(r'"', String.Double, '#pop'),
|
| 297 |
+
],
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class LSLLexer(RegexLexer):
|
| 302 |
+
"""
|
| 303 |
+
For Second Life's Linden Scripting Language source code.
|
| 304 |
+
|
| 305 |
+
.. versionadded:: 2.0
|
| 306 |
+
"""
|
| 307 |
+
|
| 308 |
+
name = 'LSL'
|
| 309 |
+
aliases = ['lsl']
|
| 310 |
+
filenames = ['*.lsl']
|
| 311 |
+
mimetypes = ['text/x-lsl']
|
| 312 |
+
|
| 313 |
+
flags = re.MULTILINE
|
| 314 |
+
|
| 315 |
+
lsl_keywords = r'\b(?:do|else|for|if|jump|return|while)\b'
|
| 316 |
+
lsl_types = r'\b(?:float|integer|key|list|quaternion|rotation|string|vector)\b'
|
| 317 |
+
lsl_states = r'\b(?:(?:state)\s+\w+|default)\b'
|
| 318 |
+
lsl_events = r'\b(?:state_(?:entry|exit)|touch(?:_(?:start|end))?|(?:land_)?collision(?:_(?:start|end))?|timer|listen|(?:no_)?sensor|control|(?:not_)?at_(?:rot_)?target|money|email|run_time_permissions|changed|attach|dataserver|moving_(?:start|end)|link_message|(?:on|object)_rez|remote_data|http_re(?:sponse|quest)|path_update|transaction_result)\b'
|
| 319 |
+
lsl_functions_builtin = r'\b(?:ll(?:ReturnObjectsBy(?:ID|Owner)|Json(?:2List|[GS]etValue|ValueType)|Sin|Cos|Tan|Atan2|Sqrt|Pow|Abs|Fabs|Frand|Floor|Ceil|Round|Vec(?:Mag|Norm|Dist)|Rot(?:Between|2(?:Euler|Fwd|Left|Up))|(?:Euler|Axes)2Rot|Whisper|(?:Region|Owner)?Say|Shout|Listen(?:Control|Remove)?|Sensor(?:Repeat|Remove)?|Detected(?:Name|Key|Owner|Type|Pos|Vel|Grab|Rot|Group|LinkNumber)|Die|Ground|Wind|(?:[GS]et)(?:AnimationOverride|MemoryLimit|PrimMediaParams|ParcelMusicURL|Object(?:Desc|Name)|PhysicsMaterial|Status|Scale|Color|Alpha|Texture|Pos|Rot|Force|Torque)|ResetAnimationOverride|(?:Scale|Offset|Rotate)Texture|(?:Rot)?Target(?:Remove)?|(?:Stop)?MoveToTarget|Apply(?:Rotational)?Impulse|Set(?:KeyframedMotion|ContentType|RegionPos|(?:Angular)?Velocity|Buoyancy|HoverHeight|ForceAndTorque|TimerEvent|ScriptState|Damage|TextureAnim|Sound(?:Queueing|Radius)|Vehicle(?:Type|(?:Float|Vector|Rotation)Param)|(?:Touch|Sit)?Text|Camera(?:Eye|At)Offset|PrimitiveParams|ClickAction|Link(?:Alpha|Color|PrimitiveParams(?:Fast)?|Texture(?:Anim)?|Camera|Media)|RemoteScriptAccessPin|PayPrice|LocalRot)|ScaleByFactor|Get(?:(?:Max|Min)ScaleFactor|ClosestNavPoint|StaticPath|SimStats|Env|PrimitiveParams|Link(?:PrimitiveParams|Number(?:OfSides)?|Key|Name|Media)|HTTPHeader|FreeURLs|Object(?:Details|PermMask|PrimCount)|Parcel(?:MaxPrims|Details|Prim(?:Count|Owners))|Attached|(?:SPMax|Free|Used)Memory|Region(?:Name|TimeDilation|FPS|Corner|AgentCount)|Root(?:Position|Rotation)|UnixTime|(?:Parcel|Region)Flags|(?:Wall|GMT)clock|SimulatorHostname|BoundingBox|GeometricCenter|Creator|NumberOf(?:Prims|NotecardLines|Sides)|Animation(?:List)?|(?:Camera|Local)(?:Pos|Rot)|Vel|Accel|Omega|Time(?:stamp|OfDay)|(?:Object|CenterOf)?Mass|MassMKS|Energy|Owner|(?:Owner)?Key|SunDirection|Texture(?:Offset|Scale|Rot)|Inventory(?:Number|Name|Key|Type|Creator|PermMask)|Permissions(?:Key)?|StartParameter|List(?:Length|EntryType)|Date|Agent(?:Size|Info|Language|List)|LandOwnerAt|NotecardLine|Script(?:Name|State))|(?:Get|Reset|GetAndReset)Time|PlaySound(?:Slave)?|LoopSound(?:Master|Slave)?|(?:Trigger|Stop|Preload)Sound|(?:(?:Get|Delete)Sub|Insert)String|To(?:Upper|Lower)|Give(?:InventoryList|Money)|RezObject|(?:Stop)?LookAt|Sleep|CollisionFilter|(?:Take|Release)Controls|DetachFromAvatar|AttachToAvatar(?:Temp)?|InstantMessage|(?:GetNext)?Email|StopHover|MinEventDelay|RotLookAt|String(?:Length|Trim)|(?:Start|Stop)Animation|TargetOmega|RequestPermissions|(?:Create|Break)Link|BreakAllLinks|(?:Give|Remove)Inventory|Water|PassTouches|Request(?:Agent|Inventory)Data|TeleportAgent(?:Home|GlobalCoords)?|ModifyLand|CollisionSound|ResetScript|MessageLinked|PushObject|PassCollisions|AxisAngle2Rot|Rot2(?:Axis|Angle)|A(?:cos|sin)|AngleBetween|AllowInventoryDrop|SubStringIndex|List2(?:CSV|Integer|Json|Float|String|Key|Vector|Rot|List(?:Strided)?)|DeleteSubList|List(?:Statistics|Sort|Randomize|(?:Insert|Find|Replace)List)|EdgeOfWorld|AdjustSoundVolume|Key2Name|TriggerSoundLimited|EjectFromLand|(?:CSV|ParseString)2List|OverMyLand|SameGroup|UnSit|Ground(?:Slope|Normal|Contour)|GroundRepel|(?:Set|Remove)VehicleFlags|(?:AvatarOn)?(?:Link)?SitTarget|Script(?:Danger|Profiler)|Dialog|VolumeDetect|ResetOtherScript|RemoteLoadScriptPin|(?:Open|Close)RemoteDataChannel|SendRemoteData|RemoteDataReply|(?:Integer|String)ToBase64|XorBase64|Log(?:10)?|Base64To(?:String|Integer)|ParseStringKeepNulls|RezAtRoot|RequestSimulatorData|ForceMouselook|(?:Load|Release|(?:E|Une)scape)URL|ParcelMedia(?:CommandList|Query)|ModPow|MapDestination|(?:RemoveFrom|AddTo|Reset)Land(?:Pass|Ban)List|(?:Set|Clear)CameraParams|HTTP(?:Request|Response)|TextBox|DetectedTouch(?:UV|Face|Pos|(?:N|Bin)ormal|ST)|(?:MD5|SHA1|DumpList2)String|Request(?:Secure)?URL|Clear(?:Prim|Link)Media|(?:Link)?ParticleSystem|(?:Get|Request)(?:Username|DisplayName)|RegionSayTo|CastRay|GenerateKey|TransferLindenDollars|ManageEstateAccess|(?:Create|Delete)Character|ExecCharacterCmd|Evade|FleeFrom|NavigateTo|PatrolPoints|Pursue|UpdateCharacter|WanderWithin))\b'
|
| 320 |
+
lsl_constants_float = r'\b(?:DEG_TO_RAD|PI(?:_BY_TWO)?|RAD_TO_DEG|SQRT2|TWO_PI)\b'
|
| 321 |
+
lsl_constants_integer = r'\b(?:JSON_APPEND|STATUS_(?:PHYSICS|ROTATE_[XYZ]|PHANTOM|SANDBOX|BLOCK_GRAB(?:_OBJECT)?|(?:DIE|RETURN)_AT_EDGE|CAST_SHADOWS|OK|MALFORMED_PARAMS|TYPE_MISMATCH|BOUNDS_ERROR|NOT_(?:FOUND|SUPPORTED)|INTERNAL_ERROR|WHITELIST_FAILED)|AGENT(?:_(?:BY_(?:LEGACY_|USER)NAME|FLYING|ATTACHMENTS|SCRIPTED|MOUSELOOK|SITTING|ON_OBJECT|AWAY|WALKING|IN_AIR|TYPING|CROUCHING|BUSY|ALWAYS_RUN|AUTOPILOT|LIST_(?:PARCEL(?:_OWNER)?|REGION)))?|CAMERA_(?:PITCH|DISTANCE|BEHINDNESS_(?:ANGLE|LAG)|(?:FOCUS|POSITION)(?:_(?:THRESHOLD|LOCKED|LAG))?|FOCUS_OFFSET|ACTIVE)|ANIM_ON|LOOP|REVERSE|PING_PONG|SMOOTH|ROTATE|SCALE|ALL_SIDES|LINK_(?:ROOT|SET|ALL_(?:OTHERS|CHILDREN)|THIS)|ACTIVE|PASSIVE|SCRIPTED|CONTROL_(?:FWD|BACK|(?:ROT_)?(?:LEFT|RIGHT)|UP|DOWN|(?:ML_)?LBUTTON)|PERMISSION_(?:RETURN_OBJECTS|DEBIT|OVERRIDE_ANIMATIONS|SILENT_ESTATE_MANAGEMENT|TAKE_CONTROLS|TRIGGER_ANIMATION|ATTACH|CHANGE_LINKS|(?:CONTROL|TRACK)_CAMERA|TELEPORT)|INVENTORY_(?:TEXTURE|SOUND|OBJECT|SCRIPT|LANDMARK|CLOTHING|NOTECARD|BODYPART|ANIMATION|GESTURE|ALL|NONE)|CHANGED_(?:INVENTORY|COLOR|SHAPE|SCALE|TEXTURE|LINK|ALLOWED_DROP|OWNER|REGION(?:_START)?|TELEPORT|MEDIA)|OBJECT_(?:(?:PHYSICS|SERVER|STREAMING)_COST|UNKNOWN_DETAIL|CHARACTER_TIME|PHANTOM|PHYSICS|TEMP_ON_REZ|NAME|DESC|POS|PRIM_EQUIVALENCE|RETURN_(?:PARCEL(?:_OWNER)?|REGION)|ROO?T|VELOCITY|OWNER|GROUP|CREATOR|ATTACHED_POINT|RENDER_WEIGHT|PATHFINDING_TYPE|(?:RUNNING|TOTAL)_SCRIPT_COUNT|SCRIPT_(?:MEMORY|TIME))|TYPE_(?:INTEGER|FLOAT|STRING|KEY|VECTOR|ROTATION|INVALID)|(?:DEBUG|PUBLIC)_CHANNEL|ATTACH_(?:AVATAR_CENTER|CHEST|HEAD|BACK|PELVIS|MOUTH|CHIN|NECK|NOSE|BELLY|[LR](?:SHOULDER|HAND|FOOT|EAR|EYE|[UL](?:ARM|LEG)|HIP)|(?:LEFT|RIGHT)_PEC|HUD_(?:CENTER_[12]|TOP_(?:RIGHT|CENTER|LEFT)|BOTTOM(?:_(?:RIGHT|LEFT))?))|LAND_(?:LEVEL|RAISE|LOWER|SMOOTH|NOISE|REVERT)|DATA_(?:ONLINE|NAME|BORN|SIM_(?:POS|STATUS|RATING)|PAYINFO)|PAYMENT_INFO_(?:ON_FILE|USED)|REMOTE_DATA_(?:CHANNEL|REQUEST|REPLY)|PSYS_(?:PART_(?:BF_(?:ZERO|ONE(?:_MINUS_(?:DEST_COLOR|SOURCE_(ALPHA|COLOR)))?|DEST_COLOR|SOURCE_(ALPHA|COLOR))|BLEND_FUNC_(DEST|SOURCE)|FLAGS|(?:START|END)_(?:COLOR|ALPHA|SCALE|GLOW)|MAX_AGE|(?:RIBBON|WIND|INTERP_(?:COLOR|SCALE)|BOUNCE|FOLLOW_(?:SRC|VELOCITY)|TARGET_(?:POS|LINEAR)|EMISSIVE)_MASK)|SRC_(?:MAX_AGE|PATTERN|ANGLE_(?:BEGIN|END)|BURST_(?:RATE|PART_COUNT|RADIUS|SPEED_(?:MIN|MAX))|ACCEL|TEXTURE|TARGET_KEY|OMEGA|PATTERN_(?:DROP|EXPLODE|ANGLE(?:_CONE(?:_EMPTY)?)?)))|VEHICLE_(?:REFERENCE_FRAME|TYPE_(?:NONE|SLED|CAR|BOAT|AIRPLANE|BALLOON)|(?:LINEAR|ANGULAR)_(?:FRICTION_TIMESCALE|MOTOR_DIRECTION)|LINEAR_MOTOR_OFFSET|HOVER_(?:HEIGHT|EFFICIENCY|TIMESCALE)|BUOYANCY|(?:LINEAR|ANGULAR)_(?:DEFLECTION_(?:EFFICIENCY|TIMESCALE)|MOTOR_(?:DECAY_)?TIMESCALE)|VERTICAL_ATTRACTION_(?:EFFICIENCY|TIMESCALE)|BANKING_(?:EFFICIENCY|MIX|TIMESCALE)|FLAG_(?:NO_DEFLECTION_UP|LIMIT_(?:ROLL_ONLY|MOTOR_UP)|HOVER_(?:(?:WATER|TERRAIN|UP)_ONLY|GLOBAL_HEIGHT)|MOUSELOOK_(?:STEER|BANK)|CAMERA_DECOUPLED))|PRIM_(?:TYPE(?:_(?:BOX|CYLINDER|PRISM|SPHERE|TORUS|TUBE|RING|SCULPT))?|HOLE_(?:DEFAULT|CIRCLE|SQUARE|TRIANGLE)|MATERIAL(?:_(?:STONE|METAL|GLASS|WOOD|FLESH|PLASTIC|RUBBER))?|SHINY_(?:NONE|LOW|MEDIUM|HIGH)|BUMP_(?:NONE|BRIGHT|DARK|WOOD|BARK|BRICKS|CHECKER|CONCRETE|TILE|STONE|DISKS|GRAVEL|BLOBS|SIDING|LARGETILE|STUCCO|SUCTION|WEAVE)|TEXGEN_(?:DEFAULT|PLANAR)|SCULPT_(?:TYPE_(?:SPHERE|TORUS|PLANE|CYLINDER|MASK)|FLAG_(?:MIRROR|INVERT))|PHYSICS(?:_(?:SHAPE_(?:CONVEX|NONE|PRIM|TYPE)))?|(?:POS|ROT)_LOCAL|SLICE|TEXT|FLEXIBLE|POINT_LIGHT|TEMP_ON_REZ|PHANTOM|POSITION|SIZE|ROTATION|TEXTURE|NAME|OMEGA|DESC|LINK_TARGET|COLOR|BUMP_SHINY|FULLBRIGHT|TEXGEN|GLOW|MEDIA_(?:ALT_IMAGE_ENABLE|CONTROLS|(?:CURRENT|HOME)_URL|AUTO_(?:LOOP|PLAY|SCALE|ZOOM)|FIRST_CLICK_INTERACT|(?:WIDTH|HEIGHT)_PIXELS|WHITELIST(?:_ENABLE)?|PERMS_(?:INTERACT|CONTROL)|PARAM_MAX|CONTROLS_(?:STANDARD|MINI)|PERM_(?:NONE|OWNER|GROUP|ANYONE)|MAX_(?:URL_LENGTH|WHITELIST_(?:SIZE|COUNT)|(?:WIDTH|HEIGHT)_PIXELS)))|MASK_(?:BASE|OWNER|GROUP|EVERYONE|NEXT)|PERM_(?:TRANSFER|MODIFY|COPY|MOVE|ALL)|PARCEL_(?:MEDIA_COMMAND_(?:STOP|PAUSE|PLAY|LOOP|TEXTURE|URL|TIME|AGENT|UNLOAD|AUTO_ALIGN|TYPE|SIZE|DESC|LOOP_SET)|FLAG_(?:ALLOW_(?:FLY|(?:GROUP_)?SCRIPTS|LANDMARK|TERRAFORM|DAMAGE|CREATE_(?:GROUP_)?OBJECTS)|USE_(?:ACCESS_(?:GROUP|LIST)|BAN_LIST|LAND_PASS_LIST)|LOCAL_SOUND_ONLY|RESTRICT_PUSHOBJECT|ALLOW_(?:GROUP|ALL)_OBJECT_ENTRY)|COUNT_(?:TOTAL|OWNER|GROUP|OTHER|SELECTED|TEMP)|DETAILS_(?:NAME|DESC|OWNER|GROUP|AREA|ID|SEE_AVATARS))|LIST_STAT_(?:MAX|MIN|MEAN|MEDIAN|STD_DEV|SUM(?:_SQUARES)?|NUM_COUNT|GEOMETRIC_MEAN|RANGE)|PAY_(?:HIDE|DEFAULT)|REGION_FLAG_(?:ALLOW_DAMAGE|FIXED_SUN|BLOCK_TERRAFORM|SANDBOX|DISABLE_(?:COLLISIONS|PHYSICS)|BLOCK_FLY|ALLOW_DIRECT_TELEPORT|RESTRICT_PUSHOBJECT)|HTTP_(?:METHOD|MIMETYPE|BODY_(?:MAXLENGTH|TRUNCATED)|CUSTOM_HEADER|PRAGMA_NO_CACHE|VERBOSE_THROTTLE|VERIFY_CERT)|STRING_(?:TRIM(?:_(?:HEAD|TAIL))?)|CLICK_ACTION_(?:NONE|TOUCH|SIT|BUY|PAY|OPEN(?:_MEDIA)?|PLAY|ZOOM)|TOUCH_INVALID_FACE|PROFILE_(?:NONE|SCRIPT_MEMORY)|RC_(?:DATA_FLAGS|DETECT_PHANTOM|GET_(?:LINK_NUM|NORMAL|ROOT_KEY)|MAX_HITS|REJECT_(?:TYPES|AGENTS|(?:NON)?PHYSICAL|LAND))|RCERR_(?:CAST_TIME_EXCEEDED|SIM_PERF_LOW|UNKNOWN)|ESTATE_ACCESS_(?:ALLOWED_(?:AGENT|GROUP)_(?:ADD|REMOVE)|BANNED_AGENT_(?:ADD|REMOVE))|DENSITY|FRICTION|RESTITUTION|GRAVITY_MULTIPLIER|KFM_(?:COMMAND|CMD_(?:PLAY|STOP|PAUSE|SET_MODE)|MODE|FORWARD|LOOP|PING_PONG|REVERSE|DATA|ROTATION|TRANSLATION)|ERR_(?:GENERIC|PARCEL_PERMISSIONS|MALFORMED_PARAMS|RUNTIME_PERMISSIONS|THROTTLED)|CHARACTER_(?:CMD_(?:(?:SMOOTH_)?STOP|JUMP)|DESIRED_(?:TURN_)?SPEED|RADIUS|STAY_WITHIN_PARCEL|LENGTH|ORIENTATION|ACCOUNT_FOR_SKIPPED_FRAMES|AVOIDANCE_MODE|TYPE(?:_(?:[A-D]|NONE))?|MAX_(?:DECEL|TURN_RADIUS|(?:ACCEL|SPEED)))|PURSUIT_(?:OFFSET|FUZZ_FACTOR|GOAL_TOLERANCE|INTERCEPT)|REQUIRE_LINE_OF_SIGHT|FORCE_DIRECT_PATH|VERTICAL|HORIZONTAL|AVOID_(?:CHARACTERS|DYNAMIC_OBSTACLES|NONE)|PU_(?:EVADE_(?:HIDDEN|SPOTTED)|FAILURE_(?:DYNAMIC_PATHFINDING_DISABLED|INVALID_(?:GOAL|START)|NO_(?:NAVMESH|VALID_DESTINATION)|OTHER|TARGET_GONE|(?:PARCEL_)?UNREACHABLE)|(?:GOAL|SLOWDOWN_DISTANCE)_REACHED)|TRAVERSAL_TYPE(?:_(?:FAST|NONE|SLOW))?|CONTENT_TYPE_(?:ATOM|FORM|HTML|JSON|LLSD|RSS|TEXT|XHTML|XML)|GCNP_(?:RADIUS|STATIC)|(?:PATROL|WANDER)_PAUSE_AT_WAYPOINTS|OPT_(?:AVATAR|CHARACTER|EXCLUSION_VOLUME|LEGACY_LINKSET|MATERIAL_VOLUME|OTHER|STATIC_OBSTACLE|WALKABLE)|SIM_STAT_PCT_CHARS_STEPPED)\b'
|
| 322 |
+
lsl_constants_integer_boolean = r'\b(?:FALSE|TRUE)\b'
|
| 323 |
+
lsl_constants_rotation = r'\b(?:ZERO_ROTATION)\b'
|
| 324 |
+
lsl_constants_string = r'\b(?:EOF|JSON_(?:ARRAY|DELETE|FALSE|INVALID|NULL|NUMBER|OBJECT|STRING|TRUE)|NULL_KEY|TEXTURE_(?:BLANK|DEFAULT|MEDIA|PLYWOOD|TRANSPARENT)|URL_REQUEST_(?:GRANTED|DENIED))\b'
|
| 325 |
+
lsl_constants_vector = r'\b(?:TOUCH_INVALID_(?:TEXCOORD|VECTOR)|ZERO_VECTOR)\b'
|
| 326 |
+
lsl_invalid_broken = r'\b(?:LAND_(?:LARGE|MEDIUM|SMALL)_BRUSH)\b'
|
| 327 |
+
lsl_invalid_deprecated = r'\b(?:ATTACH_[LR]PEC|DATA_RATING|OBJECT_ATTACHMENT_(?:GEOMETRY_BYTES|SURFACE_AREA)|PRIM_(?:CAST_SHADOWS|MATERIAL_LIGHT|TYPE_LEGACY)|PSYS_SRC_(?:INNER|OUTER)ANGLE|VEHICLE_FLAG_NO_FLY_UP|ll(?:Cloud|Make(?:Explosion|Fountain|Smoke|Fire)|RemoteDataSetRegion|Sound(?:Preload)?|XorBase64Strings(?:Correct)?))\b'
|
| 328 |
+
lsl_invalid_illegal = r'\b(?:event)\b'
|
| 329 |
+
lsl_invalid_unimplemented = r'\b(?:CHARACTER_(?:MAX_ANGULAR_(?:ACCEL|SPEED)|TURN_SPEED_MULTIPLIER)|PERMISSION_(?:CHANGE_(?:JOINTS|PERMISSIONS)|RELEASE_OWNERSHIP|REMAP_CONTROLS)|PRIM_PHYSICS_MATERIAL|PSYS_SRC_OBJ_REL_MASK|ll(?:CollisionSprite|(?:Stop)?PointAt|(?:(?:Refresh|Set)Prim)URL|(?:Take|Release)Camera|RemoteLoadScript))\b'
|
| 330 |
+
lsl_reserved_godmode = r'\b(?:ll(?:GodLikeRezObject|Set(?:Inventory|Object)PermMask))\b'
|
| 331 |
+
lsl_reserved_log = r'\b(?:print)\b'
|
| 332 |
+
lsl_operators = r'\+\+|\-\-|<<|>>|&&?|\|\|?|\^|~|[!%<>=*+\-/]=?'
|
| 333 |
+
|
| 334 |
+
tokens = {
|
| 335 |
+
'root':
|
| 336 |
+
[
|
| 337 |
+
(r'//.*?\n', Comment.Single),
|
| 338 |
+
(r'/\*', Comment.Multiline, 'comment'),
|
| 339 |
+
(r'"', String.Double, 'string'),
|
| 340 |
+
(lsl_keywords, Keyword),
|
| 341 |
+
(lsl_types, Keyword.Type),
|
| 342 |
+
(lsl_states, Name.Class),
|
| 343 |
+
(lsl_events, Name.Builtin),
|
| 344 |
+
(lsl_functions_builtin, Name.Function),
|
| 345 |
+
(lsl_constants_float, Keyword.Constant),
|
| 346 |
+
(lsl_constants_integer, Keyword.Constant),
|
| 347 |
+
(lsl_constants_integer_boolean, Keyword.Constant),
|
| 348 |
+
(lsl_constants_rotation, Keyword.Constant),
|
| 349 |
+
(lsl_constants_string, Keyword.Constant),
|
| 350 |
+
(lsl_constants_vector, Keyword.Constant),
|
| 351 |
+
(lsl_invalid_broken, Error),
|
| 352 |
+
(lsl_invalid_deprecated, Error),
|
| 353 |
+
(lsl_invalid_illegal, Error),
|
| 354 |
+
(lsl_invalid_unimplemented, Error),
|
| 355 |
+
(lsl_reserved_godmode, Keyword.Reserved),
|
| 356 |
+
(lsl_reserved_log, Keyword.Reserved),
|
| 357 |
+
(r'\b([a-zA-Z_]\w*)\b', Name.Variable),
|
| 358 |
+
(r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d*', Number.Float),
|
| 359 |
+
(r'(\d+\.\d*|\.\d+)', Number.Float),
|
| 360 |
+
(r'0[xX][0-9a-fA-F]+', Number.Hex),
|
| 361 |
+
(r'\d+', Number.Integer),
|
| 362 |
+
(lsl_operators, Operator),
|
| 363 |
+
(r':=?', Error),
|
| 364 |
+
(r'[,;{}()\[\]]', Punctuation),
|
| 365 |
+
(r'\n+', Whitespace),
|
| 366 |
+
(r'\s+', Whitespace)
|
| 367 |
+
],
|
| 368 |
+
'comment':
|
| 369 |
+
[
|
| 370 |
+
(r'[^*/]+', Comment.Multiline),
|
| 371 |
+
(r'/\*', Comment.Multiline, '#push'),
|
| 372 |
+
(r'\*/', Comment.Multiline, '#pop'),
|
| 373 |
+
(r'[*/]', Comment.Multiline)
|
| 374 |
+
],
|
| 375 |
+
'string':
|
| 376 |
+
[
|
| 377 |
+
(r'\\([nt"\\])', String.Escape),
|
| 378 |
+
(r'"', String.Double, '#pop'),
|
| 379 |
+
(r'\\.', Error),
|
| 380 |
+
(r'[^"\\]+', String.Double),
|
| 381 |
+
]
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
class AppleScriptLexer(RegexLexer):
|
| 386 |
+
"""
|
| 387 |
+
For AppleScript source code,
|
| 388 |
+
including `AppleScript Studio
|
| 389 |
+
<http://developer.apple.com/documentation/AppleScript/
|
| 390 |
+
Reference/StudioReference>`_.
|
| 391 |
+
Contributed by Andreas Amann <aamann@mac.com>.
|
| 392 |
+
|
| 393 |
+
.. versionadded:: 1.0
|
| 394 |
+
"""
|
| 395 |
+
|
| 396 |
+
name = 'AppleScript'
|
| 397 |
+
url = 'https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html'
|
| 398 |
+
aliases = ['applescript']
|
| 399 |
+
filenames = ['*.applescript']
|
| 400 |
+
|
| 401 |
+
flags = re.MULTILINE | re.DOTALL
|
| 402 |
+
|
| 403 |
+
Identifiers = r'[a-zA-Z]\w*'
|
| 404 |
+
|
| 405 |
+
# XXX: use words() for all of these
|
| 406 |
+
Literals = ('AppleScript', 'current application', 'false', 'linefeed',
|
| 407 |
+
'missing value', 'pi', 'quote', 'result', 'return', 'space',
|
| 408 |
+
'tab', 'text item delimiters', 'true', 'version')
|
| 409 |
+
Classes = ('alias ', 'application ', 'boolean ', 'class ', 'constant ',
|
| 410 |
+
'date ', 'file ', 'integer ', 'list ', 'number ', 'POSIX file ',
|
| 411 |
+
'real ', 'record ', 'reference ', 'RGB color ', 'script ',
|
| 412 |
+
'text ', 'unit types', '(?:Unicode )?text', 'string')
|
| 413 |
+
BuiltIn = ('attachment', 'attribute run', 'character', 'day', 'month',
|
| 414 |
+
'paragraph', 'word', 'year')
|
| 415 |
+
HandlerParams = ('about', 'above', 'against', 'apart from', 'around',
|
| 416 |
+
'aside from', 'at', 'below', 'beneath', 'beside',
|
| 417 |
+
'between', 'for', 'given', 'instead of', 'on', 'onto',
|
| 418 |
+
'out of', 'over', 'since')
|
| 419 |
+
Commands = ('ASCII (character|number)', 'activate', 'beep', 'choose URL',
|
| 420 |
+
'choose application', 'choose color', 'choose file( name)?',
|
| 421 |
+
'choose folder', 'choose from list',
|
| 422 |
+
'choose remote application', 'clipboard info',
|
| 423 |
+
'close( access)?', 'copy', 'count', 'current date', 'delay',
|
| 424 |
+
'delete', 'display (alert|dialog)', 'do shell script',
|
| 425 |
+
'duplicate', 'exists', 'get eof', 'get volume settings',
|
| 426 |
+
'info for', 'launch', 'list (disks|folder)', 'load script',
|
| 427 |
+
'log', 'make', 'mount volume', 'new', 'offset',
|
| 428 |
+
'open( (for access|location))?', 'path to', 'print', 'quit',
|
| 429 |
+
'random number', 'read', 'round', 'run( script)?',
|
| 430 |
+
'say', 'scripting components',
|
| 431 |
+
'set (eof|the clipboard to|volume)', 'store script',
|
| 432 |
+
'summarize', 'system attribute', 'system info',
|
| 433 |
+
'the clipboard', 'time to GMT', 'write', 'quoted form')
|
| 434 |
+
References = ('(in )?back of', '(in )?front of', '[0-9]+(st|nd|rd|th)',
|
| 435 |
+
'first', 'second', 'third', 'fourth', 'fifth', 'sixth',
|
| 436 |
+
'seventh', 'eighth', 'ninth', 'tenth', 'after', 'back',
|
| 437 |
+
'before', 'behind', 'every', 'front', 'index', 'last',
|
| 438 |
+
'middle', 'some', 'that', 'through', 'thru', 'where', 'whose')
|
| 439 |
+
Operators = ("and", "or", "is equal", "equals", "(is )?equal to", "is not",
|
| 440 |
+
"isn't", "isn't equal( to)?", "is not equal( to)?",
|
| 441 |
+
"doesn't equal", "does not equal", "(is )?greater than",
|
| 442 |
+
"comes after", "is not less than or equal( to)?",
|
| 443 |
+
"isn't less than or equal( to)?", "(is )?less than",
|
| 444 |
+
"comes before", "is not greater than or equal( to)?",
|
| 445 |
+
"isn't greater than or equal( to)?",
|
| 446 |
+
"(is )?greater than or equal( to)?", "is not less than",
|
| 447 |
+
"isn't less than", "does not come before",
|
| 448 |
+
"doesn't come before", "(is )?less than or equal( to)?",
|
| 449 |
+
"is not greater than", "isn't greater than",
|
| 450 |
+
"does not come after", "doesn't come after", "starts? with",
|
| 451 |
+
"begins? with", "ends? with", "contains?", "does not contain",
|
| 452 |
+
"doesn't contain", "is in", "is contained by", "is not in",
|
| 453 |
+
"is not contained by", "isn't contained by", "div", "mod",
|
| 454 |
+
"not", "(a )?(ref( to)?|reference to)", "is", "does")
|
| 455 |
+
Control = ('considering', 'else', 'error', 'exit', 'from', 'if',
|
| 456 |
+
'ignoring', 'in', 'repeat', 'tell', 'then', 'times', 'to',
|
| 457 |
+
'try', 'until', 'using terms from', 'while', 'whith',
|
| 458 |
+
'with timeout( of)?', 'with transaction', 'by', 'continue',
|
| 459 |
+
'end', 'its?', 'me', 'my', 'return', 'of', 'as')
|
| 460 |
+
Declarations = ('global', 'local', 'prop(erty)?', 'set', 'get')
|
| 461 |
+
Reserved = ('but', 'put', 'returning', 'the')
|
| 462 |
+
StudioClasses = ('action cell', 'alert reply', 'application', 'box',
|
| 463 |
+
'browser( cell)?', 'bundle', 'button( cell)?', 'cell',
|
| 464 |
+
'clip view', 'color well', 'color-panel',
|
| 465 |
+
'combo box( item)?', 'control',
|
| 466 |
+
'data( (cell|column|item|row|source))?', 'default entry',
|
| 467 |
+
'dialog reply', 'document', 'drag info', 'drawer',
|
| 468 |
+
'event', 'font(-panel)?', 'formatter',
|
| 469 |
+
'image( (cell|view))?', 'matrix', 'menu( item)?', 'item',
|
| 470 |
+
'movie( view)?', 'open-panel', 'outline view', 'panel',
|
| 471 |
+
'pasteboard', 'plugin', 'popup button',
|
| 472 |
+
'progress indicator', 'responder', 'save-panel',
|
| 473 |
+
'scroll view', 'secure text field( cell)?', 'slider',
|
| 474 |
+
'sound', 'split view', 'stepper', 'tab view( item)?',
|
| 475 |
+
'table( (column|header cell|header view|view))',
|
| 476 |
+
'text( (field( cell)?|view))?', 'toolbar( item)?',
|
| 477 |
+
'user-defaults', 'view', 'window')
|
| 478 |
+
StudioEvents = ('accept outline drop', 'accept table drop', 'action',
|
| 479 |
+
'activated', 'alert ended', 'awake from nib', 'became key',
|
| 480 |
+
'became main', 'begin editing', 'bounds changed',
|
| 481 |
+
'cell value', 'cell value changed', 'change cell value',
|
| 482 |
+
'change item value', 'changed', 'child of item',
|
| 483 |
+
'choose menu item', 'clicked', 'clicked toolbar item',
|
| 484 |
+
'closed', 'column clicked', 'column moved',
|
| 485 |
+
'column resized', 'conclude drop', 'data representation',
|
| 486 |
+
'deminiaturized', 'dialog ended', 'document nib name',
|
| 487 |
+
'double clicked', 'drag( (entered|exited|updated))?',
|
| 488 |
+
'drop', 'end editing', 'exposed', 'idle', 'item expandable',
|
| 489 |
+
'item value', 'item value changed', 'items changed',
|
| 490 |
+
'keyboard down', 'keyboard up', 'launched',
|
| 491 |
+
'load data representation', 'miniaturized', 'mouse down',
|
| 492 |
+
'mouse dragged', 'mouse entered', 'mouse exited',
|
| 493 |
+
'mouse moved', 'mouse up', 'moved',
|
| 494 |
+
'number of browser rows', 'number of items',
|
| 495 |
+
'number of rows', 'open untitled', 'opened', 'panel ended',
|
| 496 |
+
'parameters updated', 'plugin loaded', 'prepare drop',
|
| 497 |
+
'prepare outline drag', 'prepare outline drop',
|
| 498 |
+
'prepare table drag', 'prepare table drop',
|
| 499 |
+
'read from file', 'resigned active', 'resigned key',
|
| 500 |
+
'resigned main', 'resized( sub views)?',
|
| 501 |
+
'right mouse down', 'right mouse dragged',
|
| 502 |
+
'right mouse up', 'rows changed', 'scroll wheel',
|
| 503 |
+
'selected tab view item', 'selection changed',
|
| 504 |
+
'selection changing', 'should begin editing',
|
| 505 |
+
'should close', 'should collapse item',
|
| 506 |
+
'should end editing', 'should expand item',
|
| 507 |
+
'should open( untitled)?',
|
| 508 |
+
'should quit( after last window closed)?',
|
| 509 |
+
'should select column', 'should select item',
|
| 510 |
+
'should select row', 'should select tab view item',
|
| 511 |
+
'should selection change', 'should zoom', 'shown',
|
| 512 |
+
'update menu item', 'update parameters',
|
| 513 |
+
'update toolbar item', 'was hidden', 'was miniaturized',
|
| 514 |
+
'will become active', 'will close', 'will dismiss',
|
| 515 |
+
'will display browser cell', 'will display cell',
|
| 516 |
+
'will display item cell', 'will display outline cell',
|
| 517 |
+
'will finish launching', 'will hide', 'will miniaturize',
|
| 518 |
+
'will move', 'will open', 'will pop up', 'will quit',
|
| 519 |
+
'will resign active', 'will resize( sub views)?',
|
| 520 |
+
'will select tab view item', 'will show', 'will zoom',
|
| 521 |
+
'write to file', 'zoomed')
|
| 522 |
+
StudioCommands = ('animate', 'append', 'call method', 'center',
|
| 523 |
+
'close drawer', 'close panel', 'display',
|
| 524 |
+
'display alert', 'display dialog', 'display panel', 'go',
|
| 525 |
+
'hide', 'highlight', 'increment', 'item for',
|
| 526 |
+
'load image', 'load movie', 'load nib', 'load panel',
|
| 527 |
+
'load sound', 'localized string', 'lock focus', 'log',
|
| 528 |
+
'open drawer', 'path for', 'pause', 'perform action',
|
| 529 |
+
'play', 'register', 'resume', 'scroll', 'select( all)?',
|
| 530 |
+
'show', 'size to fit', 'start', 'step back',
|
| 531 |
+
'step forward', 'stop', 'synchronize', 'unlock focus',
|
| 532 |
+
'update')
|
| 533 |
+
StudioProperties = ('accepts arrow key', 'action method', 'active',
|
| 534 |
+
'alignment', 'allowed identifiers',
|
| 535 |
+
'allows branch selection', 'allows column reordering',
|
| 536 |
+
'allows column resizing', 'allows column selection',
|
| 537 |
+
'allows customization',
|
| 538 |
+
'allows editing text attributes',
|
| 539 |
+
'allows empty selection', 'allows mixed state',
|
| 540 |
+
'allows multiple selection', 'allows reordering',
|
| 541 |
+
'allows undo', 'alpha( value)?', 'alternate image',
|
| 542 |
+
'alternate increment value', 'alternate title',
|
| 543 |
+
'animation delay', 'associated file name',
|
| 544 |
+
'associated object', 'auto completes', 'auto display',
|
| 545 |
+
'auto enables items', 'auto repeat',
|
| 546 |
+
'auto resizes( outline column)?',
|
| 547 |
+
'auto save expanded items', 'auto save name',
|
| 548 |
+
'auto save table columns', 'auto saves configuration',
|
| 549 |
+
'auto scroll', 'auto sizes all columns to fit',
|
| 550 |
+
'auto sizes cells', 'background color', 'bezel state',
|
| 551 |
+
'bezel style', 'bezeled', 'border rect', 'border type',
|
| 552 |
+
'bordered', 'bounds( rotation)?', 'box type',
|
| 553 |
+
'button returned', 'button type',
|
| 554 |
+
'can choose directories', 'can choose files',
|
| 555 |
+
'can draw', 'can hide',
|
| 556 |
+
'cell( (background color|size|type))?', 'characters',
|
| 557 |
+
'class', 'click count', 'clicked( data)? column',
|
| 558 |
+
'clicked data item', 'clicked( data)? row',
|
| 559 |
+
'closeable', 'collating', 'color( (mode|panel))',
|
| 560 |
+
'command key down', 'configuration',
|
| 561 |
+
'content(s| (size|view( margins)?))?', 'context',
|
| 562 |
+
'continuous', 'control key down', 'control size',
|
| 563 |
+
'control tint', 'control view',
|
| 564 |
+
'controller visible', 'coordinate system',
|
| 565 |
+
'copies( on scroll)?', 'corner view', 'current cell',
|
| 566 |
+
'current column', 'current( field)? editor',
|
| 567 |
+
'current( menu)? item', 'current row',
|
| 568 |
+
'current tab view item', 'data source',
|
| 569 |
+
'default identifiers', 'delta (x|y|z)',
|
| 570 |
+
'destination window', 'directory', 'display mode',
|
| 571 |
+
'displayed cell', 'document( (edited|rect|view))?',
|
| 572 |
+
'double value', 'dragged column', 'dragged distance',
|
| 573 |
+
'dragged items', 'draws( cell)? background',
|
| 574 |
+
'draws grid', 'dynamically scrolls', 'echos bullets',
|
| 575 |
+
'edge', 'editable', 'edited( data)? column',
|
| 576 |
+
'edited data item', 'edited( data)? row', 'enabled',
|
| 577 |
+
'enclosing scroll view', 'ending page',
|
| 578 |
+
'error handling', 'event number', 'event type',
|
| 579 |
+
'excluded from windows menu', 'executable path',
|
| 580 |
+
'expanded', 'fax number', 'field editor', 'file kind',
|
| 581 |
+
'file name', 'file type', 'first responder',
|
| 582 |
+
'first visible column', 'flipped', 'floating',
|
| 583 |
+
'font( panel)?', 'formatter', 'frameworks path',
|
| 584 |
+
'frontmost', 'gave up', 'grid color', 'has data items',
|
| 585 |
+
'has horizontal ruler', 'has horizontal scroller',
|
| 586 |
+
'has parent data item', 'has resize indicator',
|
| 587 |
+
'has shadow', 'has sub menu', 'has vertical ruler',
|
| 588 |
+
'has vertical scroller', 'header cell', 'header view',
|
| 589 |
+
'hidden', 'hides when deactivated', 'highlights by',
|
| 590 |
+
'horizontal line scroll', 'horizontal page scroll',
|
| 591 |
+
'horizontal ruler view', 'horizontally resizable',
|
| 592 |
+
'icon image', 'id', 'identifier',
|
| 593 |
+
'ignores multiple clicks',
|
| 594 |
+
'image( (alignment|dims when disabled|frame style|scaling))?',
|
| 595 |
+
'imports graphics', 'increment value',
|
| 596 |
+
'indentation per level', 'indeterminate', 'index',
|
| 597 |
+
'integer value', 'intercell spacing', 'item height',
|
| 598 |
+
'key( (code|equivalent( modifier)?|window))?',
|
| 599 |
+
'knob thickness', 'label', 'last( visible)? column',
|
| 600 |
+
'leading offset', 'leaf', 'level', 'line scroll',
|
| 601 |
+
'loaded', 'localized sort', 'location', 'loop mode',
|
| 602 |
+
'main( (bunde|menu|window))?', 'marker follows cell',
|
| 603 |
+
'matrix mode', 'maximum( content)? size',
|
| 604 |
+
'maximum visible columns',
|
| 605 |
+
'menu( form representation)?', 'miniaturizable',
|
| 606 |
+
'miniaturized', 'minimized image', 'minimized title',
|
| 607 |
+
'minimum column width', 'minimum( content)? size',
|
| 608 |
+
'modal', 'modified', 'mouse down state',
|
| 609 |
+
'movie( (controller|file|rect))?', 'muted', 'name',
|
| 610 |
+
'needs display', 'next state', 'next text',
|
| 611 |
+
'number of tick marks', 'only tick mark values',
|
| 612 |
+
'opaque', 'open panel', 'option key down',
|
| 613 |
+
'outline table column', 'page scroll', 'pages across',
|
| 614 |
+
'pages down', 'palette label', 'pane splitter',
|
| 615 |
+
'parent data item', 'parent window', 'pasteboard',
|
| 616 |
+
'path( (names|separator))?', 'playing',
|
| 617 |
+
'plays every frame', 'plays selection only', 'position',
|
| 618 |
+
'preferred edge', 'preferred type', 'pressure',
|
| 619 |
+
'previous text', 'prompt', 'properties',
|
| 620 |
+
'prototype cell', 'pulls down', 'rate',
|
| 621 |
+
'released when closed', 'repeated',
|
| 622 |
+
'requested print time', 'required file type',
|
| 623 |
+
'resizable', 'resized column', 'resource path',
|
| 624 |
+
'returns records', 'reuses columns', 'rich text',
|
| 625 |
+
'roll over', 'row height', 'rulers visible',
|
| 626 |
+
'save panel', 'scripts path', 'scrollable',
|
| 627 |
+
'selectable( identifiers)?', 'selected cell',
|
| 628 |
+
'selected( data)? columns?', 'selected data items?',
|
| 629 |
+
'selected( data)? rows?', 'selected item identifier',
|
| 630 |
+
'selection by rect', 'send action on arrow key',
|
| 631 |
+
'sends action when done editing', 'separates columns',
|
| 632 |
+
'separator item', 'sequence number', 'services menu',
|
| 633 |
+
'shared frameworks path', 'shared support path',
|
| 634 |
+
'sheet', 'shift key down', 'shows alpha',
|
| 635 |
+
'shows state by', 'size( mode)?',
|
| 636 |
+
'smart insert delete enabled', 'sort case sensitivity',
|
| 637 |
+
'sort column', 'sort order', 'sort type',
|
| 638 |
+
'sorted( data rows)?', 'sound', 'source( mask)?',
|
| 639 |
+
'spell checking enabled', 'starting page', 'state',
|
| 640 |
+
'string value', 'sub menu', 'super menu', 'super view',
|
| 641 |
+
'tab key traverses cells', 'tab state', 'tab type',
|
| 642 |
+
'tab view', 'table view', 'tag', 'target( printer)?',
|
| 643 |
+
'text color', 'text container insert',
|
| 644 |
+
'text container origin', 'text returned',
|
| 645 |
+
'tick mark position', 'time stamp',
|
| 646 |
+
'title(d| (cell|font|height|position|rect))?',
|
| 647 |
+
'tool tip', 'toolbar', 'trailing offset', 'transparent',
|
| 648 |
+
'treat packages as directories', 'truncated labels',
|
| 649 |
+
'types', 'unmodified characters', 'update views',
|
| 650 |
+
'use sort indicator', 'user defaults',
|
| 651 |
+
'uses data source', 'uses ruler',
|
| 652 |
+
'uses threaded animation',
|
| 653 |
+
'uses title from previous column', 'value wraps',
|
| 654 |
+
'version',
|
| 655 |
+
'vertical( (line scroll|page scroll|ruler view))?',
|
| 656 |
+
'vertically resizable', 'view',
|
| 657 |
+
'visible( document rect)?', 'volume', 'width', 'window',
|
| 658 |
+
'windows menu', 'wraps', 'zoomable', 'zoomed')
|
| 659 |
+
|
| 660 |
+
tokens = {
|
| 661 |
+
'root': [
|
| 662 |
+
(r'\s+', Text),
|
| 663 |
+
(r'¬\n', String.Escape),
|
| 664 |
+
(r"'s\s+", Text), # This is a possessive, consider moving
|
| 665 |
+
(r'(--|#).*?$', Comment),
|
| 666 |
+
(r'\(\*', Comment.Multiline, 'comment'),
|
| 667 |
+
(r'[(){}!,.:]', Punctuation),
|
| 668 |
+
(r'(«)([^»]+)(»)',
|
| 669 |
+
bygroups(Text, Name.Builtin, Text)),
|
| 670 |
+
(r'\b((?:considering|ignoring)\s*)'
|
| 671 |
+
r'(application responses|case|diacriticals|hyphens|'
|
| 672 |
+
r'numeric strings|punctuation|white space)',
|
| 673 |
+
bygroups(Keyword, Name.Builtin)),
|
| 674 |
+
(r'(-|\*|\+|&|≠|>=?|<=?|=|≥|≤|/|÷|\^)', Operator),
|
| 675 |
+
(r"\b(%s)\b" % '|'.join(Operators), Operator.Word),
|
| 676 |
+
(r'^(\s*(?:on|end)\s+)'
|
| 677 |
+
r'(%s)' % '|'.join(StudioEvents[::-1]),
|
| 678 |
+
bygroups(Keyword, Name.Function)),
|
| 679 |
+
(r'^(\s*)(in|on|script|to)(\s+)', bygroups(Text, Keyword, Text)),
|
| 680 |
+
(r'\b(as )(%s)\b' % '|'.join(Classes),
|
| 681 |
+
bygroups(Keyword, Name.Class)),
|
| 682 |
+
(r'\b(%s)\b' % '|'.join(Literals), Name.Constant),
|
| 683 |
+
(r'\b(%s)\b' % '|'.join(Commands), Name.Builtin),
|
| 684 |
+
(r'\b(%s)\b' % '|'.join(Control), Keyword),
|
| 685 |
+
(r'\b(%s)\b' % '|'.join(Declarations), Keyword),
|
| 686 |
+
(r'\b(%s)\b' % '|'.join(Reserved), Name.Builtin),
|
| 687 |
+
(r'\b(%s)s?\b' % '|'.join(BuiltIn), Name.Builtin),
|
| 688 |
+
(r'\b(%s)\b' % '|'.join(HandlerParams), Name.Builtin),
|
| 689 |
+
(r'\b(%s)\b' % '|'.join(StudioProperties), Name.Attribute),
|
| 690 |
+
(r'\b(%s)s?\b' % '|'.join(StudioClasses), Name.Builtin),
|
| 691 |
+
(r'\b(%s)\b' % '|'.join(StudioCommands), Name.Builtin),
|
| 692 |
+
(r'\b(%s)\b' % '|'.join(References), Name.Builtin),
|
| 693 |
+
(r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double),
|
| 694 |
+
(r'\b(%s)\b' % Identifiers, Name.Variable),
|
| 695 |
+
(r'[-+]?(\d+\.\d*|\d*\.\d+)(E[-+][0-9]+)?', Number.Float),
|
| 696 |
+
(r'[-+]?\d+', Number.Integer),
|
| 697 |
+
],
|
| 698 |
+
'comment': [
|
| 699 |
+
(r'\(\*', Comment.Multiline, '#push'),
|
| 700 |
+
(r'\*\)', Comment.Multiline, '#pop'),
|
| 701 |
+
('[^*(]+', Comment.Multiline),
|
| 702 |
+
('[*(]', Comment.Multiline),
|
| 703 |
+
],
|
| 704 |
+
}
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
class RexxLexer(RegexLexer):
|
| 708 |
+
"""
|
| 709 |
+
Rexx is a scripting language available for
|
| 710 |
+
a wide range of different platforms with its roots found on mainframe
|
| 711 |
+
systems. It is popular for I/O- and data based tasks and can act as glue
|
| 712 |
+
language to bind different applications together.
|
| 713 |
+
|
| 714 |
+
.. versionadded:: 2.0
|
| 715 |
+
"""
|
| 716 |
+
name = 'Rexx'
|
| 717 |
+
url = 'http://www.rexxinfo.org/'
|
| 718 |
+
aliases = ['rexx', 'arexx']
|
| 719 |
+
filenames = ['*.rexx', '*.rex', '*.rx', '*.arexx']
|
| 720 |
+
mimetypes = ['text/x-rexx']
|
| 721 |
+
flags = re.IGNORECASE
|
| 722 |
+
|
| 723 |
+
tokens = {
|
| 724 |
+
'root': [
|
| 725 |
+
(r'\s+', Whitespace),
|
| 726 |
+
(r'/\*', Comment.Multiline, 'comment'),
|
| 727 |
+
(r'"', String, 'string_double'),
|
| 728 |
+
(r"'", String, 'string_single'),
|
| 729 |
+
(r'[0-9]+(\.[0-9]+)?(e[+-]?[0-9])?', Number),
|
| 730 |
+
(r'([a-z_]\w*)(\s*)(:)(\s*)(procedure)\b',
|
| 731 |
+
bygroups(Name.Function, Whitespace, Operator, Whitespace,
|
| 732 |
+
Keyword.Declaration)),
|
| 733 |
+
(r'([a-z_]\w*)(\s*)(:)',
|
| 734 |
+
bygroups(Name.Label, Whitespace, Operator)),
|
| 735 |
+
include('function'),
|
| 736 |
+
include('keyword'),
|
| 737 |
+
include('operator'),
|
| 738 |
+
(r'[a-z_]\w*', Text),
|
| 739 |
+
],
|
| 740 |
+
'function': [
|
| 741 |
+
(words((
|
| 742 |
+
'abbrev', 'abs', 'address', 'arg', 'b2x', 'bitand', 'bitor', 'bitxor',
|
| 743 |
+
'c2d', 'c2x', 'center', 'charin', 'charout', 'chars', 'compare',
|
| 744 |
+
'condition', 'copies', 'd2c', 'd2x', 'datatype', 'date', 'delstr',
|
| 745 |
+
'delword', 'digits', 'errortext', 'form', 'format', 'fuzz', 'insert',
|
| 746 |
+
'lastpos', 'left', 'length', 'linein', 'lineout', 'lines', 'max',
|
| 747 |
+
'min', 'overlay', 'pos', 'queued', 'random', 'reverse', 'right', 'sign',
|
| 748 |
+
'sourceline', 'space', 'stream', 'strip', 'substr', 'subword', 'symbol',
|
| 749 |
+
'time', 'trace', 'translate', 'trunc', 'value', 'verify', 'word',
|
| 750 |
+
'wordindex', 'wordlength', 'wordpos', 'words', 'x2b', 'x2c', 'x2d',
|
| 751 |
+
'xrange'), suffix=r'(\s*)(\()'),
|
| 752 |
+
bygroups(Name.Builtin, Whitespace, Operator)),
|
| 753 |
+
],
|
| 754 |
+
'keyword': [
|
| 755 |
+
(r'(address|arg|by|call|do|drop|else|end|exit|for|forever|if|'
|
| 756 |
+
r'interpret|iterate|leave|nop|numeric|off|on|options|parse|'
|
| 757 |
+
r'pull|push|queue|return|say|select|signal|to|then|trace|until|'
|
| 758 |
+
r'while)\b', Keyword.Reserved),
|
| 759 |
+
],
|
| 760 |
+
'operator': [
|
| 761 |
+
(r'(-|//|/|\(|\)|\*\*|\*|\\<<|\\<|\\==|\\=|\\>>|\\>|\\|\|\||\||'
|
| 762 |
+
r'&&|&|%|\+|<<=|<<|<=|<>|<|==|=|><|>=|>>=|>>|>|¬<<|¬<|¬==|¬=|'
|
| 763 |
+
r'¬>>|¬>|¬|\.|,)', Operator),
|
| 764 |
+
],
|
| 765 |
+
'string_double': [
|
| 766 |
+
(r'[^"\n]+', String),
|
| 767 |
+
(r'""', String),
|
| 768 |
+
(r'"', String, '#pop'),
|
| 769 |
+
(r'\n', Text, '#pop'), # Stray linefeed also terminates strings.
|
| 770 |
+
],
|
| 771 |
+
'string_single': [
|
| 772 |
+
(r'[^\'\n]+', String),
|
| 773 |
+
(r'\'\'', String),
|
| 774 |
+
(r'\'', String, '#pop'),
|
| 775 |
+
(r'\n', Text, '#pop'), # Stray linefeed also terminates strings.
|
| 776 |
+
],
|
| 777 |
+
'comment': [
|
| 778 |
+
(r'[^*]+', Comment.Multiline),
|
| 779 |
+
(r'\*/', Comment.Multiline, '#pop'),
|
| 780 |
+
(r'\*', Comment.Multiline),
|
| 781 |
+
]
|
| 782 |
+
}
|
| 783 |
+
|
| 784 |
+
_c = lambda s: re.compile(s, re.MULTILINE)
|
| 785 |
+
_ADDRESS_COMMAND_PATTERN = _c(r'^\s*address\s+command\b')
|
| 786 |
+
_ADDRESS_PATTERN = _c(r'^\s*address\s+')
|
| 787 |
+
_DO_WHILE_PATTERN = _c(r'^\s*do\s+while\b')
|
| 788 |
+
_IF_THEN_DO_PATTERN = _c(r'^\s*if\b.+\bthen\s+do\s*$')
|
| 789 |
+
_PROCEDURE_PATTERN = _c(r'^\s*([a-z_]\w*)(\s*)(:)(\s*)(procedure)\b')
|
| 790 |
+
_ELSE_DO_PATTERN = _c(r'\belse\s+do\s*$')
|
| 791 |
+
_PARSE_ARG_PATTERN = _c(r'^\s*parse\s+(upper\s+)?(arg|value)\b')
|
| 792 |
+
PATTERNS_AND_WEIGHTS = (
|
| 793 |
+
(_ADDRESS_COMMAND_PATTERN, 0.2),
|
| 794 |
+
(_ADDRESS_PATTERN, 0.05),
|
| 795 |
+
(_DO_WHILE_PATTERN, 0.1),
|
| 796 |
+
(_ELSE_DO_PATTERN, 0.1),
|
| 797 |
+
(_IF_THEN_DO_PATTERN, 0.1),
|
| 798 |
+
(_PROCEDURE_PATTERN, 0.5),
|
| 799 |
+
(_PARSE_ARG_PATTERN, 0.2),
|
| 800 |
+
)
|
| 801 |
+
|
| 802 |
+
def analyse_text(text):
|
| 803 |
+
"""
|
| 804 |
+
Check for initial comment and patterns that distinguish Rexx from other
|
| 805 |
+
C-like languages.
|
| 806 |
+
"""
|
| 807 |
+
if re.search(r'/\*\**\s*rexx', text, re.IGNORECASE):
|
| 808 |
+
# Header matches MVS Rexx requirements, this is certainly a Rexx
|
| 809 |
+
# script.
|
| 810 |
+
return 1.0
|
| 811 |
+
elif text.startswith('/*'):
|
| 812 |
+
# Header matches general Rexx requirements; the source code might
|
| 813 |
+
# still be any language using C comments such as C++, C# or Java.
|
| 814 |
+
lowerText = text.lower()
|
| 815 |
+
result = sum(weight
|
| 816 |
+
for (pattern, weight) in RexxLexer.PATTERNS_AND_WEIGHTS
|
| 817 |
+
if pattern.search(lowerText)) + 0.01
|
| 818 |
+
return min(result, 1.0)
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
class MOOCodeLexer(RegexLexer):
|
| 822 |
+
"""
|
| 823 |
+
For MOOCode (the MOO scripting language).
|
| 824 |
+
|
| 825 |
+
.. versionadded:: 0.9
|
| 826 |
+
"""
|
| 827 |
+
name = 'MOOCode'
|
| 828 |
+
url = 'http://www.moo.mud.org/'
|
| 829 |
+
filenames = ['*.moo']
|
| 830 |
+
aliases = ['moocode', 'moo']
|
| 831 |
+
mimetypes = ['text/x-moocode']
|
| 832 |
+
|
| 833 |
+
tokens = {
|
| 834 |
+
'root': [
|
| 835 |
+
# Numbers
|
| 836 |
+
(r'(0|[1-9][0-9_]*)', Number.Integer),
|
| 837 |
+
# Strings
|
| 838 |
+
(r'"(\\\\|\\[^\\]|[^"\\])*"', String),
|
| 839 |
+
# exceptions
|
| 840 |
+
(r'(E_PERM|E_DIV)', Name.Exception),
|
| 841 |
+
# db-refs
|
| 842 |
+
(r'((#[-0-9]+)|(\$\w+))', Name.Entity),
|
| 843 |
+
# Keywords
|
| 844 |
+
(r'\b(if|else|elseif|endif|for|endfor|fork|endfork|while'
|
| 845 |
+
r'|endwhile|break|continue|return|try'
|
| 846 |
+
r'|except|endtry|finally|in)\b', Keyword),
|
| 847 |
+
# builtins
|
| 848 |
+
(r'(random|length)', Name.Builtin),
|
| 849 |
+
# special variables
|
| 850 |
+
(r'(player|caller|this|args)', Name.Variable.Instance),
|
| 851 |
+
# skip whitespace
|
| 852 |
+
(r'\s+', Text),
|
| 853 |
+
(r'\n', Text),
|
| 854 |
+
# other operators
|
| 855 |
+
(r'([!;=,{}&|:.\[\]@()<>?]+)', Operator),
|
| 856 |
+
# function call
|
| 857 |
+
(r'(\w+)(\()', bygroups(Name.Function, Operator)),
|
| 858 |
+
# variables
|
| 859 |
+
(r'(\w+)', Text),
|
| 860 |
+
]
|
| 861 |
+
}
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
class HybrisLexer(RegexLexer):
|
| 865 |
+
"""
|
| 866 |
+
For Hybris source code.
|
| 867 |
+
|
| 868 |
+
.. versionadded:: 1.4
|
| 869 |
+
"""
|
| 870 |
+
|
| 871 |
+
name = 'Hybris'
|
| 872 |
+
aliases = ['hybris', 'hy']
|
| 873 |
+
filenames = ['*.hy', '*.hyb']
|
| 874 |
+
mimetypes = ['text/x-hybris', 'application/x-hybris']
|
| 875 |
+
|
| 876 |
+
flags = re.MULTILINE | re.DOTALL
|
| 877 |
+
|
| 878 |
+
tokens = {
|
| 879 |
+
'root': [
|
| 880 |
+
# method names
|
| 881 |
+
(r'^(\s*(?:function|method|operator\s+)+?)'
|
| 882 |
+
r'([a-zA-Z_]\w*)'
|
| 883 |
+
r'(\s*)(\()', bygroups(Keyword, Name.Function, Text, Operator)),
|
| 884 |
+
(r'[^\S\n]+', Text),
|
| 885 |
+
(r'//.*?\n', Comment.Single),
|
| 886 |
+
(r'/\*.*?\*/', Comment.Multiline),
|
| 887 |
+
(r'@[a-zA-Z_][\w.]*', Name.Decorator),
|
| 888 |
+
(r'(break|case|catch|next|default|do|else|finally|for|foreach|of|'
|
| 889 |
+
r'unless|if|new|return|switch|me|throw|try|while)\b', Keyword),
|
| 890 |
+
(r'(extends|private|protected|public|static|throws|function|method|'
|
| 891 |
+
r'operator)\b', Keyword.Declaration),
|
| 892 |
+
(r'(true|false|null|__FILE__|__LINE__|__VERSION__|__LIB_PATH__|'
|
| 893 |
+
r'__INC_PATH__)\b', Keyword.Constant),
|
| 894 |
+
(r'(class|struct)(\s+)',
|
| 895 |
+
bygroups(Keyword.Declaration, Text), 'class'),
|
| 896 |
+
(r'(import|include)(\s+)',
|
| 897 |
+
bygroups(Keyword.Namespace, Text), 'import'),
|
| 898 |
+
(words((
|
| 899 |
+
'gc_collect', 'gc_mm_items', 'gc_mm_usage', 'gc_collect_threshold',
|
| 900 |
+
'urlencode', 'urldecode', 'base64encode', 'base64decode', 'sha1', 'crc32',
|
| 901 |
+
'sha2', 'md5', 'md5_file', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos',
|
| 902 |
+
'cosh', 'exp', 'fabs', 'floor', 'fmod', 'log', 'log10', 'pow', 'sin',
|
| 903 |
+
'sinh', 'sqrt', 'tan', 'tanh', 'isint', 'isfloat', 'ischar', 'isstring',
|
| 904 |
+
'isarray', 'ismap', 'isalias', 'typeof', 'sizeof', 'toint', 'tostring',
|
| 905 |
+
'fromxml', 'toxml', 'binary', 'pack', 'load', 'eval', 'var_names',
|
| 906 |
+
'var_values', 'user_functions', 'dyn_functions', 'methods', 'call',
|
| 907 |
+
'call_method', 'mknod', 'mkfifo', 'mount', 'umount2', 'umount', 'ticks',
|
| 908 |
+
'usleep', 'sleep', 'time', 'strtime', 'strdate', 'dllopen', 'dlllink',
|
| 909 |
+
'dllcall', 'dllcall_argv', 'dllclose', 'env', 'exec', 'fork', 'getpid',
|
| 910 |
+
'wait', 'popen', 'pclose', 'exit', 'kill', 'pthread_create',
|
| 911 |
+
'pthread_create_argv', 'pthread_exit', 'pthread_join', 'pthread_kill',
|
| 912 |
+
'smtp_send', 'http_get', 'http_post', 'http_download', 'socket', 'bind',
|
| 913 |
+
'listen', 'accept', 'getsockname', 'getpeername', 'settimeout', 'connect',
|
| 914 |
+
'server', 'recv', 'send', 'close', 'print', 'println', 'printf', 'input',
|
| 915 |
+
'readline', 'serial_open', 'serial_fcntl', 'serial_get_attr',
|
| 916 |
+
'serial_get_ispeed', 'serial_get_ospeed', 'serial_set_attr',
|
| 917 |
+
'serial_set_ispeed', 'serial_set_ospeed', 'serial_write', 'serial_read',
|
| 918 |
+
'serial_close', 'xml_load', 'xml_parse', 'fopen', 'fseek', 'ftell',
|
| 919 |
+
'fsize', 'fread', 'fwrite', 'fgets', 'fclose', 'file', 'readdir',
|
| 920 |
+
'pcre_replace', 'size', 'pop', 'unmap', 'has', 'keys', 'values',
|
| 921 |
+
'length', 'find', 'substr', 'replace', 'split', 'trim', 'remove',
|
| 922 |
+
'contains', 'join'), suffix=r'\b'),
|
| 923 |
+
Name.Builtin),
|
| 924 |
+
(words((
|
| 925 |
+
'MethodReference', 'Runner', 'Dll', 'Thread', 'Pipe', 'Process',
|
| 926 |
+
'Runnable', 'CGI', 'ClientSocket', 'Socket', 'ServerSocket',
|
| 927 |
+
'File', 'Console', 'Directory', 'Exception'), suffix=r'\b'),
|
| 928 |
+
Keyword.Type),
|
| 929 |
+
(r'"(\\\\|\\[^\\]|[^"\\])*"', String),
|
| 930 |
+
(r"'\\.'|'[^\\]'|'\\u[0-9a-f]{4}'", String.Char),
|
| 931 |
+
(r'(\.)([a-zA-Z_]\w*)',
|
| 932 |
+
bygroups(Operator, Name.Attribute)),
|
| 933 |
+
(r'[a-zA-Z_]\w*:', Name.Label),
|
| 934 |
+
(r'[a-zA-Z_$]\w*', Name),
|
| 935 |
+
(r'[~^*!%&\[\](){}<>|+=:;,./?\-@]+', Operator),
|
| 936 |
+
(r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
|
| 937 |
+
(r'0x[0-9a-f]+', Number.Hex),
|
| 938 |
+
(r'[0-9]+L?', Number.Integer),
|
| 939 |
+
(r'\n', Text),
|
| 940 |
+
],
|
| 941 |
+
'class': [
|
| 942 |
+
(r'[a-zA-Z_]\w*', Name.Class, '#pop')
|
| 943 |
+
],
|
| 944 |
+
'import': [
|
| 945 |
+
(r'[\w.]+\*?', Name.Namespace, '#pop')
|
| 946 |
+
],
|
| 947 |
+
}
|
| 948 |
+
|
| 949 |
+
def analyse_text(text):
|
| 950 |
+
"""public method and private method don't seem to be quite common
|
| 951 |
+
elsewhere."""
|
| 952 |
+
result = 0
|
| 953 |
+
if re.search(r'\b(?:public|private)\s+method\b', text):
|
| 954 |
+
result += 0.01
|
| 955 |
+
return result
|
| 956 |
+
|
| 957 |
+
|
| 958 |
+
|
| 959 |
+
class EasytrieveLexer(RegexLexer):
|
| 960 |
+
"""
|
| 961 |
+
Easytrieve Plus is a programming language for extracting, filtering and
|
| 962 |
+
converting sequential data. Furthermore it can layout data for reports.
|
| 963 |
+
It is mainly used on mainframe platforms and can access several of the
|
| 964 |
+
mainframe's native file formats. It is somewhat comparable to awk.
|
| 965 |
+
|
| 966 |
+
.. versionadded:: 2.1
|
| 967 |
+
"""
|
| 968 |
+
name = 'Easytrieve'
|
| 969 |
+
aliases = ['easytrieve']
|
| 970 |
+
filenames = ['*.ezt', '*.mac']
|
| 971 |
+
mimetypes = ['text/x-easytrieve']
|
| 972 |
+
flags = 0
|
| 973 |
+
|
| 974 |
+
# Note: We cannot use r'\b' at the start and end of keywords because
|
| 975 |
+
# Easytrieve Plus delimiter characters are:
|
| 976 |
+
#
|
| 977 |
+
# * space ( )
|
| 978 |
+
# * apostrophe (')
|
| 979 |
+
# * period (.)
|
| 980 |
+
# * comma (,)
|
| 981 |
+
# * parenthesis ( and )
|
| 982 |
+
# * colon (:)
|
| 983 |
+
#
|
| 984 |
+
# Additionally words end once a '*' appears, indicatins a comment.
|
| 985 |
+
_DELIMITERS = r' \'.,():\n'
|
| 986 |
+
_DELIMITERS_OR_COMENT = _DELIMITERS + '*'
|
| 987 |
+
_DELIMITER_PATTERN = '[' + _DELIMITERS + ']'
|
| 988 |
+
_DELIMITER_PATTERN_CAPTURE = '(' + _DELIMITER_PATTERN + ')'
|
| 989 |
+
_NON_DELIMITER_OR_COMMENT_PATTERN = '[^' + _DELIMITERS_OR_COMENT + ']'
|
| 990 |
+
_OPERATORS_PATTERN = '[.+\\-/=\\[\\](){}<>;,&%¬]'
|
| 991 |
+
_KEYWORDS = [
|
| 992 |
+
'AFTER-BREAK', 'AFTER-LINE', 'AFTER-SCREEN', 'AIM', 'AND', 'ATTR',
|
| 993 |
+
'BEFORE', 'BEFORE-BREAK', 'BEFORE-LINE', 'BEFORE-SCREEN', 'BUSHU',
|
| 994 |
+
'BY', 'CALL', 'CASE', 'CHECKPOINT', 'CHKP', 'CHKP-STATUS', 'CLEAR',
|
| 995 |
+
'CLOSE', 'COL', 'COLOR', 'COMMIT', 'CONTROL', 'COPY', 'CURSOR', 'D',
|
| 996 |
+
'DECLARE', 'DEFAULT', 'DEFINE', 'DELETE', 'DENWA', 'DISPLAY', 'DLI',
|
| 997 |
+
'DO', 'DUPLICATE', 'E', 'ELSE', 'ELSE-IF', 'END', 'END-CASE',
|
| 998 |
+
'END-DO', 'END-IF', 'END-PROC', 'ENDPAGE', 'ENDTABLE', 'ENTER', 'EOF',
|
| 999 |
+
'EQ', 'ERROR', 'EXIT', 'EXTERNAL', 'EZLIB', 'F1', 'F10', 'F11', 'F12',
|
| 1000 |
+
'F13', 'F14', 'F15', 'F16', 'F17', 'F18', 'F19', 'F2', 'F20', 'F21',
|
| 1001 |
+
'F22', 'F23', 'F24', 'F25', 'F26', 'F27', 'F28', 'F29', 'F3', 'F30',
|
| 1002 |
+
'F31', 'F32', 'F33', 'F34', 'F35', 'F36', 'F4', 'F5', 'F6', 'F7',
|
| 1003 |
+
'F8', 'F9', 'FETCH', 'FILE-STATUS', 'FILL', 'FINAL', 'FIRST',
|
| 1004 |
+
'FIRST-DUP', 'FOR', 'GE', 'GET', 'GO', 'GOTO', 'GQ', 'GR', 'GT',
|
| 1005 |
+
'HEADING', 'HEX', 'HIGH-VALUES', 'IDD', 'IDMS', 'IF', 'IN', 'INSERT',
|
| 1006 |
+
'JUSTIFY', 'KANJI-DATE', 'KANJI-DATE-LONG', 'KANJI-TIME', 'KEY',
|
| 1007 |
+
'KEY-PRESSED', 'KOKUGO', 'KUN', 'LAST-DUP', 'LE', 'LEVEL', 'LIKE',
|
| 1008 |
+
'LINE', 'LINE-COUNT', 'LINE-NUMBER', 'LINK', 'LIST', 'LOW-VALUES',
|
| 1009 |
+
'LQ', 'LS', 'LT', 'MACRO', 'MASK', 'MATCHED', 'MEND', 'MESSAGE',
|
| 1010 |
+
'MOVE', 'MSTART', 'NE', 'NEWPAGE', 'NOMASK', 'NOPRINT', 'NOT',
|
| 1011 |
+
'NOTE', 'NOVERIFY', 'NQ', 'NULL', 'OF', 'OR', 'OTHERWISE', 'PA1',
|
| 1012 |
+
'PA2', 'PA3', 'PAGE-COUNT', 'PAGE-NUMBER', 'PARM-REGISTER',
|
| 1013 |
+
'PATH-ID', 'PATTERN', 'PERFORM', 'POINT', 'POS', 'PRIMARY', 'PRINT',
|
| 1014 |
+
'PROCEDURE', 'PROGRAM', 'PUT', 'READ', 'RECORD', 'RECORD-COUNT',
|
| 1015 |
+
'RECORD-LENGTH', 'REFRESH', 'RELEASE', 'RENUM', 'REPEAT', 'REPORT',
|
| 1016 |
+
'REPORT-INPUT', 'RESHOW', 'RESTART', 'RETRIEVE', 'RETURN-CODE',
|
| 1017 |
+
'ROLLBACK', 'ROW', 'S', 'SCREEN', 'SEARCH', 'SECONDARY', 'SELECT',
|
| 1018 |
+
'SEQUENCE', 'SIZE', 'SKIP', 'SOKAKU', 'SORT', 'SQL', 'STOP', 'SUM',
|
| 1019 |
+
'SYSDATE', 'SYSDATE-LONG', 'SYSIN', 'SYSIPT', 'SYSLST', 'SYSPRINT',
|
| 1020 |
+
'SYSSNAP', 'SYSTIME', 'TALLY', 'TERM-COLUMNS', 'TERM-NAME',
|
| 1021 |
+
'TERM-ROWS', 'TERMINATION', 'TITLE', 'TO', 'TRANSFER', 'TRC',
|
| 1022 |
+
'UNIQUE', 'UNTIL', 'UPDATE', 'UPPERCASE', 'USER', 'USERID', 'VALUE',
|
| 1023 |
+
'VERIFY', 'W', 'WHEN', 'WHILE', 'WORK', 'WRITE', 'X', 'XDM', 'XRST'
|
| 1024 |
+
]
|
| 1025 |
+
|
| 1026 |
+
tokens = {
|
| 1027 |
+
'root': [
|
| 1028 |
+
(r'\*.*\n', Comment.Single),
|
| 1029 |
+
(r'\n+', Whitespace),
|
| 1030 |
+
# Macro argument
|
| 1031 |
+
(r'&' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+\.', Name.Variable,
|
| 1032 |
+
'after_macro_argument'),
|
| 1033 |
+
# Macro call
|
| 1034 |
+
(r'%' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name.Variable),
|
| 1035 |
+
(r'(FILE|MACRO|REPORT)(\s+)',
|
| 1036 |
+
bygroups(Keyword.Declaration, Whitespace), 'after_declaration'),
|
| 1037 |
+
(r'(JOB|PARM)' + r'(' + _DELIMITER_PATTERN + r')',
|
| 1038 |
+
bygroups(Keyword.Declaration, Operator)),
|
| 1039 |
+
(words(_KEYWORDS, suffix=_DELIMITER_PATTERN_CAPTURE),
|
| 1040 |
+
bygroups(Keyword.Reserved, Operator)),
|
| 1041 |
+
(_OPERATORS_PATTERN, Operator),
|
| 1042 |
+
# Procedure declaration
|
| 1043 |
+
(r'(' + _NON_DELIMITER_OR_COMMENT_PATTERN + r'+)(\s*)(\.?)(\s*)(PROC)(\s*\n)',
|
| 1044 |
+
bygroups(Name.Function, Whitespace, Operator, Whitespace,
|
| 1045 |
+
Keyword.Declaration, Whitespace)),
|
| 1046 |
+
(r'[0-9]+\.[0-9]*', Number.Float),
|
| 1047 |
+
(r'[0-9]+', Number.Integer),
|
| 1048 |
+
(r"'(''|[^'])*'", String),
|
| 1049 |
+
(r'\s+', Whitespace),
|
| 1050 |
+
# Everything else just belongs to a name
|
| 1051 |
+
(_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name),
|
| 1052 |
+
],
|
| 1053 |
+
'after_declaration': [
|
| 1054 |
+
(_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name.Function),
|
| 1055 |
+
default('#pop'),
|
| 1056 |
+
],
|
| 1057 |
+
'after_macro_argument': [
|
| 1058 |
+
(r'\*.*\n', Comment.Single, '#pop'),
|
| 1059 |
+
(r'\s+', Whitespace, '#pop'),
|
| 1060 |
+
(_OPERATORS_PATTERN, Operator, '#pop'),
|
| 1061 |
+
(r"'(''|[^'])*'", String, '#pop'),
|
| 1062 |
+
# Everything else just belongs to a name
|
| 1063 |
+
(_NON_DELIMITER_OR_COMMENT_PATTERN + r'+', Name),
|
| 1064 |
+
],
|
| 1065 |
+
}
|
| 1066 |
+
_COMMENT_LINE_REGEX = re.compile(r'^\s*\*')
|
| 1067 |
+
_MACRO_HEADER_REGEX = re.compile(r'^\s*MACRO')
|
| 1068 |
+
|
| 1069 |
+
def analyse_text(text):
|
| 1070 |
+
"""
|
| 1071 |
+
Perform a structural analysis for basic Easytrieve constructs.
|
| 1072 |
+
"""
|
| 1073 |
+
result = 0.0
|
| 1074 |
+
lines = text.split('\n')
|
| 1075 |
+
hasEndProc = False
|
| 1076 |
+
hasHeaderComment = False
|
| 1077 |
+
hasFile = False
|
| 1078 |
+
hasJob = False
|
| 1079 |
+
hasProc = False
|
| 1080 |
+
hasParm = False
|
| 1081 |
+
hasReport = False
|
| 1082 |
+
|
| 1083 |
+
def isCommentLine(line):
|
| 1084 |
+
return EasytrieveLexer._COMMENT_LINE_REGEX.match(lines[0]) is not None
|
| 1085 |
+
|
| 1086 |
+
def isEmptyLine(line):
|
| 1087 |
+
return not bool(line.strip())
|
| 1088 |
+
|
| 1089 |
+
# Remove possible empty lines and header comments.
|
| 1090 |
+
while lines and (isEmptyLine(lines[0]) or isCommentLine(lines[0])):
|
| 1091 |
+
if not isEmptyLine(lines[0]):
|
| 1092 |
+
hasHeaderComment = True
|
| 1093 |
+
del lines[0]
|
| 1094 |
+
|
| 1095 |
+
if EasytrieveLexer._MACRO_HEADER_REGEX.match(lines[0]):
|
| 1096 |
+
# Looks like an Easytrieve macro.
|
| 1097 |
+
result = 0.4
|
| 1098 |
+
if hasHeaderComment:
|
| 1099 |
+
result += 0.4
|
| 1100 |
+
else:
|
| 1101 |
+
# Scan the source for lines starting with indicators.
|
| 1102 |
+
for line in lines:
|
| 1103 |
+
words = line.split()
|
| 1104 |
+
if (len(words) >= 2):
|
| 1105 |
+
firstWord = words[0]
|
| 1106 |
+
if not hasReport:
|
| 1107 |
+
if not hasJob:
|
| 1108 |
+
if not hasFile:
|
| 1109 |
+
if not hasParm:
|
| 1110 |
+
if firstWord == 'PARM':
|
| 1111 |
+
hasParm = True
|
| 1112 |
+
if firstWord == 'FILE':
|
| 1113 |
+
hasFile = True
|
| 1114 |
+
if firstWord == 'JOB':
|
| 1115 |
+
hasJob = True
|
| 1116 |
+
elif firstWord == 'PROC':
|
| 1117 |
+
hasProc = True
|
| 1118 |
+
elif firstWord == 'END-PROC':
|
| 1119 |
+
hasEndProc = True
|
| 1120 |
+
elif firstWord == 'REPORT':
|
| 1121 |
+
hasReport = True
|
| 1122 |
+
|
| 1123 |
+
# Weight the findings.
|
| 1124 |
+
if hasJob and (hasProc == hasEndProc):
|
| 1125 |
+
if hasHeaderComment:
|
| 1126 |
+
result += 0.1
|
| 1127 |
+
if hasParm:
|
| 1128 |
+
if hasProc:
|
| 1129 |
+
# Found PARM, JOB and PROC/END-PROC:
|
| 1130 |
+
# pretty sure this is Easytrieve.
|
| 1131 |
+
result += 0.8
|
| 1132 |
+
else:
|
| 1133 |
+
# Found PARAM and JOB: probably this is Easytrieve
|
| 1134 |
+
result += 0.5
|
| 1135 |
+
else:
|
| 1136 |
+
# Found JOB and possibly other keywords: might be Easytrieve
|
| 1137 |
+
result += 0.11
|
| 1138 |
+
if hasParm:
|
| 1139 |
+
# Note: PARAM is not a proper English word, so this is
|
| 1140 |
+
# regarded a much better indicator for Easytrieve than
|
| 1141 |
+
# the other words.
|
| 1142 |
+
result += 0.2
|
| 1143 |
+
if hasFile:
|
| 1144 |
+
result += 0.01
|
| 1145 |
+
if hasReport:
|
| 1146 |
+
result += 0.01
|
| 1147 |
+
assert 0.0 <= result <= 1.0
|
| 1148 |
+
return result
|
| 1149 |
+
|
| 1150 |
+
|
| 1151 |
+
class JclLexer(RegexLexer):
|
| 1152 |
+
"""
|
| 1153 |
+
Job Control Language (JCL)
|
| 1154 |
+
is a scripting language used on mainframe platforms to instruct the system
|
| 1155 |
+
on how to run a batch job or start a subsystem. It is somewhat
|
| 1156 |
+
comparable to MS DOS batch and Unix shell scripts.
|
| 1157 |
+
|
| 1158 |
+
.. versionadded:: 2.1
|
| 1159 |
+
"""
|
| 1160 |
+
name = 'JCL'
|
| 1161 |
+
aliases = ['jcl']
|
| 1162 |
+
filenames = ['*.jcl']
|
| 1163 |
+
mimetypes = ['text/x-jcl']
|
| 1164 |
+
flags = re.IGNORECASE
|
| 1165 |
+
|
| 1166 |
+
tokens = {
|
| 1167 |
+
'root': [
|
| 1168 |
+
(r'//\*.*\n', Comment.Single),
|
| 1169 |
+
(r'//', Keyword.Pseudo, 'statement'),
|
| 1170 |
+
(r'/\*', Keyword.Pseudo, 'jes2_statement'),
|
| 1171 |
+
# TODO: JES3 statement
|
| 1172 |
+
(r'.*\n', Other) # Input text or inline code in any language.
|
| 1173 |
+
],
|
| 1174 |
+
'statement': [
|
| 1175 |
+
(r'\s*\n', Whitespace, '#pop'),
|
| 1176 |
+
(r'([a-z]\w*)(\s+)(exec|job)(\s*)',
|
| 1177 |
+
bygroups(Name.Label, Whitespace, Keyword.Reserved, Whitespace),
|
| 1178 |
+
'option'),
|
| 1179 |
+
(r'[a-z]\w*', Name.Variable, 'statement_command'),
|
| 1180 |
+
(r'\s+', Whitespace, 'statement_command'),
|
| 1181 |
+
],
|
| 1182 |
+
'statement_command': [
|
| 1183 |
+
(r'\s+(command|cntl|dd|endctl|endif|else|include|jcllib|'
|
| 1184 |
+
r'output|pend|proc|set|then|xmit)\s+', Keyword.Reserved, 'option'),
|
| 1185 |
+
include('option')
|
| 1186 |
+
],
|
| 1187 |
+
'jes2_statement': [
|
| 1188 |
+
(r'\s*\n', Whitespace, '#pop'),
|
| 1189 |
+
(r'\$', Keyword, 'option'),
|
| 1190 |
+
(r'\b(jobparam|message|netacct|notify|output|priority|route|'
|
| 1191 |
+
r'setup|signoff|xeq|xmit)\b', Keyword, 'option'),
|
| 1192 |
+
],
|
| 1193 |
+
'option': [
|
| 1194 |
+
# (r'\n', Text, 'root'),
|
| 1195 |
+
(r'\*', Name.Builtin),
|
| 1196 |
+
(r'[\[\](){}<>;,]', Punctuation),
|
| 1197 |
+
(r'[-+*/=&%]', Operator),
|
| 1198 |
+
(r'[a-z_]\w*', Name),
|
| 1199 |
+
(r'\d+\.\d*', Number.Float),
|
| 1200 |
+
(r'\.\d+', Number.Float),
|
| 1201 |
+
(r'\d+', Number.Integer),
|
| 1202 |
+
(r"'", String, 'option_string'),
|
| 1203 |
+
(r'[ \t]+', Whitespace, 'option_comment'),
|
| 1204 |
+
(r'\.', Punctuation),
|
| 1205 |
+
],
|
| 1206 |
+
'option_string': [
|
| 1207 |
+
(r"(\n)(//)", bygroups(Text, Keyword.Pseudo)),
|
| 1208 |
+
(r"''", String),
|
| 1209 |
+
(r"[^']", String),
|
| 1210 |
+
(r"'", String, '#pop'),
|
| 1211 |
+
],
|
| 1212 |
+
'option_comment': [
|
| 1213 |
+
# (r'\n', Text, 'root'),
|
| 1214 |
+
(r'.+', Comment.Single),
|
| 1215 |
+
]
|
| 1216 |
+
}
|
| 1217 |
+
|
| 1218 |
+
_JOB_HEADER_PATTERN = re.compile(r'^//[a-z#$@][a-z0-9#$@]{0,7}\s+job(\s+.*)?$',
|
| 1219 |
+
re.IGNORECASE)
|
| 1220 |
+
|
| 1221 |
+
def analyse_text(text):
|
| 1222 |
+
"""
|
| 1223 |
+
Recognize JCL job by header.
|
| 1224 |
+
"""
|
| 1225 |
+
result = 0.0
|
| 1226 |
+
lines = text.split('\n')
|
| 1227 |
+
if len(lines) > 0:
|
| 1228 |
+
if JclLexer._JOB_HEADER_PATTERN.match(lines[0]):
|
| 1229 |
+
result = 1.0
|
| 1230 |
+
assert 0.0 <= result <= 1.0
|
| 1231 |
+
return result
|
| 1232 |
+
|
| 1233 |
+
|
| 1234 |
+
class MiniScriptLexer(RegexLexer):
|
| 1235 |
+
"""
|
| 1236 |
+
For MiniScript source code.
|
| 1237 |
+
|
| 1238 |
+
.. versionadded:: 2.6
|
| 1239 |
+
"""
|
| 1240 |
+
|
| 1241 |
+
name = 'MiniScript'
|
| 1242 |
+
url = 'https://miniscript.org'
|
| 1243 |
+
aliases = ['miniscript', 'ms']
|
| 1244 |
+
filenames = ['*.ms']
|
| 1245 |
+
mimetypes = ['text/x-minicript', 'application/x-miniscript']
|
| 1246 |
+
|
| 1247 |
+
tokens = {
|
| 1248 |
+
'root': [
|
| 1249 |
+
(r'#!(.*?)$', Comment.Preproc),
|
| 1250 |
+
default('base'),
|
| 1251 |
+
],
|
| 1252 |
+
'base': [
|
| 1253 |
+
('//.*$', Comment.Single),
|
| 1254 |
+
(r'(?i)(\d*\.\d+|\d+\.\d*)(e[+-]?\d+)?', Number),
|
| 1255 |
+
(r'(?i)\d+e[+-]?\d+', Number),
|
| 1256 |
+
(r'\d+', Number),
|
| 1257 |
+
(r'\n', Text),
|
| 1258 |
+
(r'[^\S\n]+', Text),
|
| 1259 |
+
(r'"', String, 'string_double'),
|
| 1260 |
+
(r'(==|!=|<=|>=|[=+\-*/%^<>.:])', Operator),
|
| 1261 |
+
(r'[;,\[\]{}()]', Punctuation),
|
| 1262 |
+
(words((
|
| 1263 |
+
'break', 'continue', 'else', 'end', 'for', 'function', 'if',
|
| 1264 |
+
'in', 'isa', 'then', 'repeat', 'return', 'while'), suffix=r'\b'),
|
| 1265 |
+
Keyword),
|
| 1266 |
+
(words((
|
| 1267 |
+
'abs', 'acos', 'asin', 'atan', 'ceil', 'char', 'cos', 'floor',
|
| 1268 |
+
'log', 'round', 'rnd', 'pi', 'sign', 'sin', 'sqrt', 'str', 'tan',
|
| 1269 |
+
'hasIndex', 'indexOf', 'len', 'val', 'code', 'remove', 'lower',
|
| 1270 |
+
'upper', 'replace', 'split', 'indexes', 'values', 'join', 'sum',
|
| 1271 |
+
'sort', 'shuffle', 'push', 'pop', 'pull', 'range',
|
| 1272 |
+
'print', 'input', 'time', 'wait', 'locals', 'globals', 'outer',
|
| 1273 |
+
'yield'), suffix=r'\b'),
|
| 1274 |
+
Name.Builtin),
|
| 1275 |
+
(r'(true|false|null)\b', Keyword.Constant),
|
| 1276 |
+
(r'(and|or|not|new)\b', Operator.Word),
|
| 1277 |
+
(r'(self|super|__isa)\b', Name.Builtin.Pseudo),
|
| 1278 |
+
(r'[a-zA-Z_]\w*', Name.Variable)
|
| 1279 |
+
],
|
| 1280 |
+
'string_double': [
|
| 1281 |
+
(r'[^"\n]+', String),
|
| 1282 |
+
(r'""', String),
|
| 1283 |
+
(r'"', String, '#pop'),
|
| 1284 |
+
(r'\n', Text, '#pop'), # Stray linefeed also terminates strings.
|
| 1285 |
+
]
|
| 1286 |
+
}
|
shared/package-files/12/1247c2e7b7565de963817cb9b2276b247246d760f5826414c8f0cad7c5b3953e/example_1.nc
ADDED
|
Binary file (1.74 kB). View file
|
|
|
shared/package-files/12/1248eb53b35366b387ebcc8aaf3e82fdec89312152c46802db23104fd66c71e9/mod.mod
ADDED
|
Binary file (412 Bytes). View file
|
|
|
shared/package-files/12/124ffb03b72d9bf581fb7d8d78f6ce0db4392c3319040982bc380f29b21439c8/test_na_indexing.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import pandas._testing as tm
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@pytest.mark.parametrize(
|
| 8 |
+
"values, dtype",
|
| 9 |
+
[
|
| 10 |
+
([], "object"),
|
| 11 |
+
([1, 2, 3], "int64"),
|
| 12 |
+
([1.0, 2.0, 3.0], "float64"),
|
| 13 |
+
(["a", "b", "c"], "object"),
|
| 14 |
+
(["a", "b", "c"], "string"),
|
| 15 |
+
([1, 2, 3], "datetime64[ns]"),
|
| 16 |
+
([1, 2, 3], "datetime64[ns, CET]"),
|
| 17 |
+
([1, 2, 3], "timedelta64[ns]"),
|
| 18 |
+
(["2000", "2001", "2002"], "Period[D]"),
|
| 19 |
+
([1, 0, 3], "Sparse"),
|
| 20 |
+
([pd.Interval(0, 1), pd.Interval(1, 2), pd.Interval(3, 4)], "interval"),
|
| 21 |
+
],
|
| 22 |
+
)
|
| 23 |
+
@pytest.mark.parametrize(
|
| 24 |
+
"mask", [[True, False, False], [True, True, True], [False, False, False]]
|
| 25 |
+
)
|
| 26 |
+
@pytest.mark.parametrize("indexer_class", [list, pd.array, pd.Index, pd.Series])
|
| 27 |
+
@pytest.mark.parametrize("frame", [True, False])
|
| 28 |
+
def test_series_mask_boolean(values, dtype, mask, indexer_class, frame):
|
| 29 |
+
# In case len(values) < 3
|
| 30 |
+
index = ["a", "b", "c"][: len(values)]
|
| 31 |
+
mask = mask[: len(values)]
|
| 32 |
+
|
| 33 |
+
obj = pd.Series(values, dtype=dtype, index=index)
|
| 34 |
+
if frame:
|
| 35 |
+
if len(values) == 0:
|
| 36 |
+
# Otherwise obj is an empty DataFrame with shape (0, 1)
|
| 37 |
+
obj = pd.DataFrame(dtype=dtype, index=index)
|
| 38 |
+
else:
|
| 39 |
+
obj = obj.to_frame()
|
| 40 |
+
|
| 41 |
+
if indexer_class is pd.array:
|
| 42 |
+
mask = pd.array(mask, dtype="boolean")
|
| 43 |
+
elif indexer_class is pd.Series:
|
| 44 |
+
mask = pd.Series(mask, index=obj.index, dtype="boolean")
|
| 45 |
+
else:
|
| 46 |
+
mask = indexer_class(mask)
|
| 47 |
+
|
| 48 |
+
expected = obj[mask]
|
| 49 |
+
|
| 50 |
+
result = obj[mask]
|
| 51 |
+
tm.assert_equal(result, expected)
|
| 52 |
+
|
| 53 |
+
if indexer_class is pd.Series:
|
| 54 |
+
msg = "iLocation based boolean indexing cannot use an indexable as a mask"
|
| 55 |
+
with pytest.raises(ValueError, match=msg):
|
| 56 |
+
result = obj.iloc[mask]
|
| 57 |
+
tm.assert_equal(result, expected)
|
| 58 |
+
else:
|
| 59 |
+
result = obj.iloc[mask]
|
| 60 |
+
tm.assert_equal(result, expected)
|
| 61 |
+
|
| 62 |
+
result = obj.loc[mask]
|
| 63 |
+
tm.assert_equal(result, expected)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_na_treated_as_false(frame_or_series, indexer_sli):
|
| 67 |
+
# https://github.com/pandas-dev/pandas/issues/31503
|
| 68 |
+
obj = frame_or_series([1, 2, 3])
|
| 69 |
+
|
| 70 |
+
mask = pd.array([True, False, None], dtype="boolean")
|
| 71 |
+
|
| 72 |
+
result = indexer_sli(obj)[mask]
|
| 73 |
+
expected = indexer_sli(obj)[mask.fillna(False)]
|
| 74 |
+
|
| 75 |
+
tm.assert_equal(result, expected)
|
shared/package-files/12/12516cb0e8fca551b5ebccb2d04f2e8b24d4143588f611ae58893d928887d401/glu_backward_cuda_dispatch.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cuda {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor glu_backward(const at::Tensor & grad_output, const at::Tensor & self, int64_t dim);
|
| 21 |
+
TORCH_API at::Tensor & glu_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, int64_t dim);
|
| 22 |
+
TORCH_API at::Tensor & glu_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, int64_t dim, at::Tensor & grad_input);
|
| 23 |
+
|
| 24 |
+
} // namespace cuda
|
| 25 |
+
} // namespace at
|
shared/package-files/12/1251946f8a7929c3229bf79d1f833024bf225025750acd4b1217ba38ad9eb67c/screen.mlterm-256color
ADDED
|
Binary file (3.32 kB). View file
|
|
|
shared/package-files/12/1252cac9d50cc94cf280970abab3a13fbde9a9ddbf9971d100b43a5b208d94d2/_cholesky_solve_helper_native.h
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor & _cholesky_solve_helper_out(const at::Tensor & self, const at::Tensor & A, bool upper, at::Tensor & out);
|
| 20 |
+
TORCH_API at::Tensor _cholesky_solve_helper_cpu(const at::Tensor & self, const at::Tensor & A, bool upper);
|
| 21 |
+
TORCH_API at::Tensor _cholesky_solve_helper_cuda(const at::Tensor & self, const at::Tensor & A, bool upper);
|
| 22 |
+
} // namespace native
|
| 23 |
+
} // namespace at
|
shared/package-files/12/1255040a0eb9c99f58775d55cf34f675cf61539f7c0a0dd0d6a36cb1f0da1e15/_data.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
shared/package-files/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trust Region Reflective algorithm for least-squares optimization.
|
| 2 |
+
|
| 3 |
+
The algorithm is based on ideas from paper [STIR]_. The main idea is to
|
| 4 |
+
account for the presence of the bounds by appropriate scaling of the variables (or,
|
| 5 |
+
equivalently, changing a trust-region shape). Let's introduce a vector v:
|
| 6 |
+
|
| 7 |
+
| ub[i] - x[i], if g[i] < 0 and ub[i] < np.inf
|
| 8 |
+
v[i] = | x[i] - lb[i], if g[i] > 0 and lb[i] > -np.inf
|
| 9 |
+
| 1, otherwise
|
| 10 |
+
|
| 11 |
+
where g is the gradient of a cost function and lb, ub are the bounds. Its
|
| 12 |
+
components are distances to the bounds at which the anti-gradient points (if
|
| 13 |
+
this distance is finite). Define a scaling matrix D = diag(v**0.5).
|
| 14 |
+
First-order optimality conditions can be stated as
|
| 15 |
+
|
| 16 |
+
D^2 g(x) = 0.
|
| 17 |
+
|
| 18 |
+
Meaning that components of the gradient should be zero for strictly interior
|
| 19 |
+
variables, and components must point inside the feasible region for variables
|
| 20 |
+
on the bound.
|
| 21 |
+
|
| 22 |
+
Now consider this system of equations as a new optimization problem. If the
|
| 23 |
+
point x is strictly interior (not on the bound), then the left-hand side is
|
| 24 |
+
differentiable and the Newton step for it satisfies
|
| 25 |
+
|
| 26 |
+
(D^2 H + diag(g) Jv) p = -D^2 g
|
| 27 |
+
|
| 28 |
+
where H is the Hessian matrix (or its J^T J approximation in least squares),
|
| 29 |
+
Jv is the Jacobian matrix of v with components -1, 1 or 0, such that all
|
| 30 |
+
elements of matrix C = diag(g) Jv are non-negative. Introduce the change
|
| 31 |
+
of the variables x = D x_h (_h would be "hat" in LaTeX). In the new variables,
|
| 32 |
+
we have a Newton step satisfying
|
| 33 |
+
|
| 34 |
+
B_h p_h = -g_h,
|
| 35 |
+
|
| 36 |
+
where B_h = D H D + C, g_h = D g. In least squares B_h = J_h^T J_h, where
|
| 37 |
+
J_h = J D. Note that J_h and g_h are proper Jacobian and gradient with respect
|
| 38 |
+
to "hat" variables. To guarantee global convergence we formulate a
|
| 39 |
+
trust-region problem based on the Newton step in the new variables:
|
| 40 |
+
|
| 41 |
+
0.5 * p_h^T B_h p + g_h^T p_h -> min, ||p_h|| <= Delta
|
| 42 |
+
|
| 43 |
+
In the original space B = H + D^{-1} C D^{-1}, and the equivalent trust-region
|
| 44 |
+
problem is
|
| 45 |
+
|
| 46 |
+
0.5 * p^T B p + g^T p -> min, ||D^{-1} p|| <= Delta
|
| 47 |
+
|
| 48 |
+
Here, the meaning of the matrix D becomes more clear: it alters the shape
|
| 49 |
+
of a trust-region, such that large steps towards the bounds are not allowed.
|
| 50 |
+
In the implementation, the trust-region problem is solved in "hat" space,
|
| 51 |
+
but handling of the bounds is done in the original space (see below and read
|
| 52 |
+
the code).
|
| 53 |
+
|
| 54 |
+
The introduction of the matrix D doesn't allow to ignore bounds, the algorithm
|
| 55 |
+
must keep iterates strictly feasible (to satisfy aforementioned
|
| 56 |
+
differentiability), the parameter theta controls step back from the boundary
|
| 57 |
+
(see the code for details).
|
| 58 |
+
|
| 59 |
+
The algorithm does another important trick. If the trust-region solution
|
| 60 |
+
doesn't fit into the bounds, then a reflected (from a firstly encountered
|
| 61 |
+
bound) search direction is considered. For motivation and analysis refer to
|
| 62 |
+
[STIR]_ paper (and other papers of the authors). In practice, it doesn't need
|
| 63 |
+
a lot of justifications, the algorithm simply chooses the best step among
|
| 64 |
+
three: a constrained trust-region step, a reflected step and a constrained
|
| 65 |
+
Cauchy step (a minimizer along -g_h in "hat" space, or -D^2 g in the original
|
| 66 |
+
space).
|
| 67 |
+
|
| 68 |
+
Another feature is that a trust-region radius control strategy is modified to
|
| 69 |
+
account for appearance of the diagonal C matrix (called diag_h in the code).
|
| 70 |
+
|
| 71 |
+
Note that all described peculiarities are completely gone as we consider
|
| 72 |
+
problems without bounds (the algorithm becomes a standard trust-region type
|
| 73 |
+
algorithm very similar to ones implemented in MINPACK).
|
| 74 |
+
|
| 75 |
+
The implementation supports two methods of solving the trust-region problem.
|
| 76 |
+
The first, called 'exact', applies SVD on Jacobian and then solves the problem
|
| 77 |
+
very accurately using the algorithm described in [JJMore]_. It is not
|
| 78 |
+
applicable to large problem. The second, called 'lsmr', uses the 2-D subspace
|
| 79 |
+
approach (sometimes called "indefinite dogleg"), where the problem is solved
|
| 80 |
+
in a subspace spanned by the gradient and the approximate Gauss-Newton step
|
| 81 |
+
found by ``scipy.sparse.linalg.lsmr``. A 2-D trust-region problem is
|
| 82 |
+
reformulated as a 4th order algebraic equation and solved very accurately by
|
| 83 |
+
``numpy.roots``. The subspace approach allows to solve very large problems
|
| 84 |
+
(up to couple of millions of residuals on a regular PC), provided the Jacobian
|
| 85 |
+
matrix is sufficiently sparse.
|
| 86 |
+
|
| 87 |
+
References
|
| 88 |
+
----------
|
| 89 |
+
.. [STIR] Branch, M.A., T.F. Coleman, and Y. Li, "A Subspace, Interior,
|
| 90 |
+
and Conjugate Gradient Method for Large-Scale Bound-Constrained
|
| 91 |
+
Minimization Problems," SIAM Journal on Scientific Computing,
|
| 92 |
+
Vol. 21, Number 1, pp 1-23, 1999.
|
| 93 |
+
.. [JJMore] More, J. J., "The Levenberg-Marquardt Algorithm: Implementation
|
| 94 |
+
and Theory," Numerical Analysis, ed. G. A. Watson, Lecture
|
| 95 |
+
"""
|
| 96 |
+
import numpy as np
|
| 97 |
+
from numpy.linalg import norm
|
| 98 |
+
from scipy.linalg import svd, qr
|
| 99 |
+
from scipy.sparse.linalg import lsmr
|
| 100 |
+
from scipy.optimize import OptimizeResult
|
| 101 |
+
|
| 102 |
+
from .common import (
|
| 103 |
+
step_size_to_bound, find_active_constraints, in_bounds,
|
| 104 |
+
make_strictly_feasible, intersect_trust_region, solve_lsq_trust_region,
|
| 105 |
+
solve_trust_region_2d, minimize_quadratic_1d, build_quadratic_1d,
|
| 106 |
+
evaluate_quadratic, right_multiplied_operator, regularized_lsq_operator,
|
| 107 |
+
CL_scaling_vector, compute_grad, compute_jac_scale, check_termination,
|
| 108 |
+
update_tr_radius, scale_for_robust_loss_function, print_header_nonlinear,
|
| 109 |
+
print_iteration_nonlinear)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def trf(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale,
|
| 113 |
+
loss_function, tr_solver, tr_options, verbose):
|
| 114 |
+
# For efficiency, it makes sense to run the simplified version of the
|
| 115 |
+
# algorithm when no bounds are imposed. We decided to write the two
|
| 116 |
+
# separate functions. It violates the DRY principle, but the individual
|
| 117 |
+
# functions are kept the most readable.
|
| 118 |
+
if np.all(lb == -np.inf) and np.all(ub == np.inf):
|
| 119 |
+
return trf_no_bounds(
|
| 120 |
+
fun, jac, x0, f0, J0, ftol, xtol, gtol, max_nfev, x_scale,
|
| 121 |
+
loss_function, tr_solver, tr_options, verbose)
|
| 122 |
+
else:
|
| 123 |
+
return trf_bounds(
|
| 124 |
+
fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale,
|
| 125 |
+
loss_function, tr_solver, tr_options, verbose)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def select_step(x, J_h, diag_h, g_h, p, p_h, d, Delta, lb, ub, theta):
|
| 129 |
+
"""Select the best step according to Trust Region Reflective algorithm."""
|
| 130 |
+
if in_bounds(x + p, lb, ub):
|
| 131 |
+
p_value = evaluate_quadratic(J_h, g_h, p_h, diag=diag_h)
|
| 132 |
+
return p, p_h, -p_value
|
| 133 |
+
|
| 134 |
+
p_stride, hits = step_size_to_bound(x, p, lb, ub)
|
| 135 |
+
|
| 136 |
+
# Compute the reflected direction.
|
| 137 |
+
r_h = np.copy(p_h)
|
| 138 |
+
r_h[hits.astype(bool)] *= -1
|
| 139 |
+
r = d * r_h
|
| 140 |
+
|
| 141 |
+
# Restrict trust-region step, such that it hits the bound.
|
| 142 |
+
p *= p_stride
|
| 143 |
+
p_h *= p_stride
|
| 144 |
+
x_on_bound = x + p
|
| 145 |
+
|
| 146 |
+
# Reflected direction will cross first either feasible region or trust
|
| 147 |
+
# region boundary.
|
| 148 |
+
_, to_tr = intersect_trust_region(p_h, r_h, Delta)
|
| 149 |
+
to_bound, _ = step_size_to_bound(x_on_bound, r, lb, ub)
|
| 150 |
+
|
| 151 |
+
# Find lower and upper bounds on a step size along the reflected
|
| 152 |
+
# direction, considering the strict feasibility requirement. There is no
|
| 153 |
+
# single correct way to do that, the chosen approach seems to work best
|
| 154 |
+
# on test problems.
|
| 155 |
+
r_stride = min(to_bound, to_tr)
|
| 156 |
+
if r_stride > 0:
|
| 157 |
+
r_stride_l = (1 - theta) * p_stride / r_stride
|
| 158 |
+
if r_stride == to_bound:
|
| 159 |
+
r_stride_u = theta * to_bound
|
| 160 |
+
else:
|
| 161 |
+
r_stride_u = to_tr
|
| 162 |
+
else:
|
| 163 |
+
r_stride_l = 0
|
| 164 |
+
r_stride_u = -1
|
| 165 |
+
|
| 166 |
+
# Check if reflection step is available.
|
| 167 |
+
if r_stride_l <= r_stride_u:
|
| 168 |
+
a, b, c = build_quadratic_1d(J_h, g_h, r_h, s0=p_h, diag=diag_h)
|
| 169 |
+
r_stride, r_value = minimize_quadratic_1d(
|
| 170 |
+
a, b, r_stride_l, r_stride_u, c=c)
|
| 171 |
+
r_h *= r_stride
|
| 172 |
+
r_h += p_h
|
| 173 |
+
r = r_h * d
|
| 174 |
+
else:
|
| 175 |
+
r_value = np.inf
|
| 176 |
+
|
| 177 |
+
# Now correct p_h to make it strictly interior.
|
| 178 |
+
p *= theta
|
| 179 |
+
p_h *= theta
|
| 180 |
+
p_value = evaluate_quadratic(J_h, g_h, p_h, diag=diag_h)
|
| 181 |
+
|
| 182 |
+
ag_h = -g_h
|
| 183 |
+
ag = d * ag_h
|
| 184 |
+
|
| 185 |
+
to_tr = Delta / norm(ag_h)
|
| 186 |
+
to_bound, _ = step_size_to_bound(x, ag, lb, ub)
|
| 187 |
+
if to_bound < to_tr:
|
| 188 |
+
ag_stride = theta * to_bound
|
| 189 |
+
else:
|
| 190 |
+
ag_stride = to_tr
|
| 191 |
+
|
| 192 |
+
a, b = build_quadratic_1d(J_h, g_h, ag_h, diag=diag_h)
|
| 193 |
+
ag_stride, ag_value = minimize_quadratic_1d(a, b, 0, ag_stride)
|
| 194 |
+
ag_h *= ag_stride
|
| 195 |
+
ag *= ag_stride
|
| 196 |
+
|
| 197 |
+
if p_value < r_value and p_value < ag_value:
|
| 198 |
+
return p, p_h, -p_value
|
| 199 |
+
elif r_value < p_value and r_value < ag_value:
|
| 200 |
+
return r, r_h, -r_value
|
| 201 |
+
else:
|
| 202 |
+
return ag, ag_h, -ag_value
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def trf_bounds(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev,
|
| 206 |
+
x_scale, loss_function, tr_solver, tr_options, verbose):
|
| 207 |
+
x = x0.copy()
|
| 208 |
+
|
| 209 |
+
f = f0
|
| 210 |
+
f_true = f.copy()
|
| 211 |
+
nfev = 1
|
| 212 |
+
|
| 213 |
+
J = J0
|
| 214 |
+
njev = 1
|
| 215 |
+
m, n = J.shape
|
| 216 |
+
|
| 217 |
+
if loss_function is not None:
|
| 218 |
+
rho = loss_function(f)
|
| 219 |
+
cost = 0.5 * np.sum(rho[0])
|
| 220 |
+
J, f = scale_for_robust_loss_function(J, f, rho)
|
| 221 |
+
else:
|
| 222 |
+
cost = 0.5 * np.dot(f, f)
|
| 223 |
+
|
| 224 |
+
g = compute_grad(J, f)
|
| 225 |
+
|
| 226 |
+
jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
|
| 227 |
+
if jac_scale:
|
| 228 |
+
scale, scale_inv = compute_jac_scale(J)
|
| 229 |
+
else:
|
| 230 |
+
scale, scale_inv = x_scale, 1 / x_scale
|
| 231 |
+
|
| 232 |
+
v, dv = CL_scaling_vector(x, g, lb, ub)
|
| 233 |
+
v[dv != 0] *= scale_inv[dv != 0]
|
| 234 |
+
Delta = norm(x0 * scale_inv / v**0.5)
|
| 235 |
+
if Delta == 0:
|
| 236 |
+
Delta = 1.0
|
| 237 |
+
|
| 238 |
+
g_norm = norm(g * v, ord=np.inf)
|
| 239 |
+
|
| 240 |
+
f_augmented = np.zeros(m + n)
|
| 241 |
+
if tr_solver == 'exact':
|
| 242 |
+
J_augmented = np.empty((m + n, n))
|
| 243 |
+
elif tr_solver == 'lsmr':
|
| 244 |
+
reg_term = 0.0
|
| 245 |
+
regularize = tr_options.pop('regularize', True)
|
| 246 |
+
|
| 247 |
+
if max_nfev is None:
|
| 248 |
+
max_nfev = x0.size * 100
|
| 249 |
+
|
| 250 |
+
alpha = 0.0 # "Levenberg-Marquardt" parameter
|
| 251 |
+
|
| 252 |
+
termination_status = None
|
| 253 |
+
iteration = 0
|
| 254 |
+
step_norm = None
|
| 255 |
+
actual_reduction = None
|
| 256 |
+
|
| 257 |
+
if verbose == 2:
|
| 258 |
+
print_header_nonlinear()
|
| 259 |
+
|
| 260 |
+
while True:
|
| 261 |
+
v, dv = CL_scaling_vector(x, g, lb, ub)
|
| 262 |
+
|
| 263 |
+
g_norm = norm(g * v, ord=np.inf)
|
| 264 |
+
if g_norm < gtol:
|
| 265 |
+
termination_status = 1
|
| 266 |
+
|
| 267 |
+
if verbose == 2:
|
| 268 |
+
print_iteration_nonlinear(iteration, nfev, cost, actual_reduction,
|
| 269 |
+
step_norm, g_norm)
|
| 270 |
+
|
| 271 |
+
if termination_status is not None or nfev == max_nfev:
|
| 272 |
+
break
|
| 273 |
+
|
| 274 |
+
# Now compute variables in "hat" space. Here, we also account for
|
| 275 |
+
# scaling introduced by `x_scale` parameter. This part is a bit tricky,
|
| 276 |
+
# you have to write down the formulas and see how the trust-region
|
| 277 |
+
# problem is formulated when the two types of scaling are applied.
|
| 278 |
+
# The idea is that first we apply `x_scale` and then apply Coleman-Li
|
| 279 |
+
# approach in the new variables.
|
| 280 |
+
|
| 281 |
+
# v is recomputed in the variables after applying `x_scale`, note that
|
| 282 |
+
# components which were identically 1 not affected.
|
| 283 |
+
v[dv != 0] *= scale_inv[dv != 0]
|
| 284 |
+
|
| 285 |
+
# Here, we apply two types of scaling.
|
| 286 |
+
d = v**0.5 * scale
|
| 287 |
+
|
| 288 |
+
# C = diag(g * scale) Jv
|
| 289 |
+
diag_h = g * dv * scale
|
| 290 |
+
|
| 291 |
+
# After all this has been done, we continue normally.
|
| 292 |
+
|
| 293 |
+
# "hat" gradient.
|
| 294 |
+
g_h = d * g
|
| 295 |
+
|
| 296 |
+
f_augmented[:m] = f
|
| 297 |
+
if tr_solver == 'exact':
|
| 298 |
+
J_augmented[:m] = J * d
|
| 299 |
+
J_h = J_augmented[:m] # Memory view.
|
| 300 |
+
J_augmented[m:] = np.diag(diag_h**0.5)
|
| 301 |
+
U, s, V = svd(J_augmented, full_matrices=False)
|
| 302 |
+
V = V.T
|
| 303 |
+
uf = U.T.dot(f_augmented)
|
| 304 |
+
elif tr_solver == 'lsmr':
|
| 305 |
+
J_h = right_multiplied_operator(J, d)
|
| 306 |
+
|
| 307 |
+
if regularize:
|
| 308 |
+
a, b = build_quadratic_1d(J_h, g_h, -g_h, diag=diag_h)
|
| 309 |
+
to_tr = Delta / norm(g_h)
|
| 310 |
+
ag_value = minimize_quadratic_1d(a, b, 0, to_tr)[1]
|
| 311 |
+
reg_term = -ag_value / Delta**2
|
| 312 |
+
|
| 313 |
+
lsmr_op = regularized_lsq_operator(J_h, (diag_h + reg_term)**0.5)
|
| 314 |
+
gn_h = lsmr(lsmr_op, f_augmented, **tr_options)[0]
|
| 315 |
+
S = np.vstack((g_h, gn_h)).T
|
| 316 |
+
S, _ = qr(S, mode='economic')
|
| 317 |
+
JS = J_h.dot(S) # LinearOperator does dot too.
|
| 318 |
+
B_S = np.dot(JS.T, JS) + np.dot(S.T * diag_h, S)
|
| 319 |
+
g_S = S.T.dot(g_h)
|
| 320 |
+
|
| 321 |
+
# theta controls step back step ratio from the bounds.
|
| 322 |
+
theta = max(0.995, 1 - g_norm)
|
| 323 |
+
|
| 324 |
+
actual_reduction = -1
|
| 325 |
+
while actual_reduction <= 0 and nfev < max_nfev:
|
| 326 |
+
if tr_solver == 'exact':
|
| 327 |
+
p_h, alpha, n_iter = solve_lsq_trust_region(
|
| 328 |
+
n, m, uf, s, V, Delta, initial_alpha=alpha)
|
| 329 |
+
elif tr_solver == 'lsmr':
|
| 330 |
+
p_S, _ = solve_trust_region_2d(B_S, g_S, Delta)
|
| 331 |
+
p_h = S.dot(p_S)
|
| 332 |
+
|
| 333 |
+
p = d * p_h # Trust-region solution in the original space.
|
| 334 |
+
step, step_h, predicted_reduction = select_step(
|
| 335 |
+
x, J_h, diag_h, g_h, p, p_h, d, Delta, lb, ub, theta)
|
| 336 |
+
|
| 337 |
+
x_new = make_strictly_feasible(x + step, lb, ub, rstep=0)
|
| 338 |
+
f_new = fun(x_new)
|
| 339 |
+
nfev += 1
|
| 340 |
+
|
| 341 |
+
step_h_norm = norm(step_h)
|
| 342 |
+
|
| 343 |
+
if not np.all(np.isfinite(f_new)):
|
| 344 |
+
Delta = 0.25 * step_h_norm
|
| 345 |
+
continue
|
| 346 |
+
|
| 347 |
+
# Usual trust-region step quality estimation.
|
| 348 |
+
if loss_function is not None:
|
| 349 |
+
cost_new = loss_function(f_new, cost_only=True)
|
| 350 |
+
else:
|
| 351 |
+
cost_new = 0.5 * np.dot(f_new, f_new)
|
| 352 |
+
actual_reduction = cost - cost_new
|
| 353 |
+
Delta_new, ratio = update_tr_radius(
|
| 354 |
+
Delta, actual_reduction, predicted_reduction,
|
| 355 |
+
step_h_norm, step_h_norm > 0.95 * Delta)
|
| 356 |
+
|
| 357 |
+
step_norm = norm(step)
|
| 358 |
+
termination_status = check_termination(
|
| 359 |
+
actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol)
|
| 360 |
+
if termination_status is not None:
|
| 361 |
+
break
|
| 362 |
+
|
| 363 |
+
alpha *= Delta / Delta_new
|
| 364 |
+
Delta = Delta_new
|
| 365 |
+
|
| 366 |
+
if actual_reduction > 0:
|
| 367 |
+
x = x_new
|
| 368 |
+
|
| 369 |
+
f = f_new
|
| 370 |
+
f_true = f.copy()
|
| 371 |
+
|
| 372 |
+
cost = cost_new
|
| 373 |
+
|
| 374 |
+
J = jac(x, f)
|
| 375 |
+
njev += 1
|
| 376 |
+
|
| 377 |
+
if loss_function is not None:
|
| 378 |
+
rho = loss_function(f)
|
| 379 |
+
J, f = scale_for_robust_loss_function(J, f, rho)
|
| 380 |
+
|
| 381 |
+
g = compute_grad(J, f)
|
| 382 |
+
|
| 383 |
+
if jac_scale:
|
| 384 |
+
scale, scale_inv = compute_jac_scale(J, scale_inv)
|
| 385 |
+
else:
|
| 386 |
+
step_norm = 0
|
| 387 |
+
actual_reduction = 0
|
| 388 |
+
|
| 389 |
+
iteration += 1
|
| 390 |
+
|
| 391 |
+
if termination_status is None:
|
| 392 |
+
termination_status = 0
|
| 393 |
+
|
| 394 |
+
active_mask = find_active_constraints(x, lb, ub, rtol=xtol)
|
| 395 |
+
return OptimizeResult(
|
| 396 |
+
x=x, cost=cost, fun=f_true, jac=J, grad=g, optimality=g_norm,
|
| 397 |
+
active_mask=active_mask, nfev=nfev, njev=njev,
|
| 398 |
+
status=termination_status)
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def trf_no_bounds(fun, jac, x0, f0, J0, ftol, xtol, gtol, max_nfev,
|
| 402 |
+
x_scale, loss_function, tr_solver, tr_options, verbose):
|
| 403 |
+
x = x0.copy()
|
| 404 |
+
|
| 405 |
+
f = f0
|
| 406 |
+
f_true = f.copy()
|
| 407 |
+
nfev = 1
|
| 408 |
+
|
| 409 |
+
J = J0
|
| 410 |
+
njev = 1
|
| 411 |
+
m, n = J.shape
|
| 412 |
+
|
| 413 |
+
if loss_function is not None:
|
| 414 |
+
rho = loss_function(f)
|
| 415 |
+
cost = 0.5 * np.sum(rho[0])
|
| 416 |
+
J, f = scale_for_robust_loss_function(J, f, rho)
|
| 417 |
+
else:
|
| 418 |
+
cost = 0.5 * np.dot(f, f)
|
| 419 |
+
|
| 420 |
+
g = compute_grad(J, f)
|
| 421 |
+
|
| 422 |
+
jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
|
| 423 |
+
if jac_scale:
|
| 424 |
+
scale, scale_inv = compute_jac_scale(J)
|
| 425 |
+
else:
|
| 426 |
+
scale, scale_inv = x_scale, 1 / x_scale
|
| 427 |
+
|
| 428 |
+
Delta = norm(x0 * scale_inv)
|
| 429 |
+
if Delta == 0:
|
| 430 |
+
Delta = 1.0
|
| 431 |
+
|
| 432 |
+
if tr_solver == 'lsmr':
|
| 433 |
+
reg_term = 0
|
| 434 |
+
damp = tr_options.pop('damp', 0.0)
|
| 435 |
+
regularize = tr_options.pop('regularize', True)
|
| 436 |
+
|
| 437 |
+
if max_nfev is None:
|
| 438 |
+
max_nfev = x0.size * 100
|
| 439 |
+
|
| 440 |
+
alpha = 0.0 # "Levenberg-Marquardt" parameter
|
| 441 |
+
|
| 442 |
+
termination_status = None
|
| 443 |
+
iteration = 0
|
| 444 |
+
step_norm = None
|
| 445 |
+
actual_reduction = None
|
| 446 |
+
|
| 447 |
+
if verbose == 2:
|
| 448 |
+
print_header_nonlinear()
|
| 449 |
+
|
| 450 |
+
while True:
|
| 451 |
+
g_norm = norm(g, ord=np.inf)
|
| 452 |
+
if g_norm < gtol:
|
| 453 |
+
termination_status = 1
|
| 454 |
+
|
| 455 |
+
if verbose == 2:
|
| 456 |
+
print_iteration_nonlinear(iteration, nfev, cost, actual_reduction,
|
| 457 |
+
step_norm, g_norm)
|
| 458 |
+
|
| 459 |
+
if termination_status is not None or nfev == max_nfev:
|
| 460 |
+
break
|
| 461 |
+
|
| 462 |
+
d = scale
|
| 463 |
+
g_h = d * g
|
| 464 |
+
|
| 465 |
+
if tr_solver == 'exact':
|
| 466 |
+
J_h = J * d
|
| 467 |
+
U, s, V = svd(J_h, full_matrices=False)
|
| 468 |
+
V = V.T
|
| 469 |
+
uf = U.T.dot(f)
|
| 470 |
+
elif tr_solver == 'lsmr':
|
| 471 |
+
J_h = right_multiplied_operator(J, d)
|
| 472 |
+
|
| 473 |
+
if regularize:
|
| 474 |
+
a, b = build_quadratic_1d(J_h, g_h, -g_h)
|
| 475 |
+
to_tr = Delta / norm(g_h)
|
| 476 |
+
ag_value = minimize_quadratic_1d(a, b, 0, to_tr)[1]
|
| 477 |
+
reg_term = -ag_value / Delta**2
|
| 478 |
+
|
| 479 |
+
damp_full = (damp**2 + reg_term)**0.5
|
| 480 |
+
gn_h = lsmr(J_h, f, damp=damp_full, **tr_options)[0]
|
| 481 |
+
S = np.vstack((g_h, gn_h)).T
|
| 482 |
+
S, _ = qr(S, mode='economic')
|
| 483 |
+
JS = J_h.dot(S)
|
| 484 |
+
B_S = np.dot(JS.T, JS)
|
| 485 |
+
g_S = S.T.dot(g_h)
|
| 486 |
+
|
| 487 |
+
actual_reduction = -1
|
| 488 |
+
while actual_reduction <= 0 and nfev < max_nfev:
|
| 489 |
+
if tr_solver == 'exact':
|
| 490 |
+
step_h, alpha, n_iter = solve_lsq_trust_region(
|
| 491 |
+
n, m, uf, s, V, Delta, initial_alpha=alpha)
|
| 492 |
+
elif tr_solver == 'lsmr':
|
| 493 |
+
p_S, _ = solve_trust_region_2d(B_S, g_S, Delta)
|
| 494 |
+
step_h = S.dot(p_S)
|
| 495 |
+
|
| 496 |
+
predicted_reduction = -evaluate_quadratic(J_h, g_h, step_h)
|
| 497 |
+
step = d * step_h
|
| 498 |
+
x_new = x + step
|
| 499 |
+
f_new = fun(x_new)
|
| 500 |
+
nfev += 1
|
| 501 |
+
|
| 502 |
+
step_h_norm = norm(step_h)
|
| 503 |
+
|
| 504 |
+
if not np.all(np.isfinite(f_new)):
|
| 505 |
+
Delta = 0.25 * step_h_norm
|
| 506 |
+
continue
|
| 507 |
+
|
| 508 |
+
# Usual trust-region step quality estimation.
|
| 509 |
+
if loss_function is not None:
|
| 510 |
+
cost_new = loss_function(f_new, cost_only=True)
|
| 511 |
+
else:
|
| 512 |
+
cost_new = 0.5 * np.dot(f_new, f_new)
|
| 513 |
+
actual_reduction = cost - cost_new
|
| 514 |
+
|
| 515 |
+
Delta_new, ratio = update_tr_radius(
|
| 516 |
+
Delta, actual_reduction, predicted_reduction,
|
| 517 |
+
step_h_norm, step_h_norm > 0.95 * Delta)
|
| 518 |
+
|
| 519 |
+
step_norm = norm(step)
|
| 520 |
+
termination_status = check_termination(
|
| 521 |
+
actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol)
|
| 522 |
+
if termination_status is not None:
|
| 523 |
+
break
|
| 524 |
+
|
| 525 |
+
alpha *= Delta / Delta_new
|
| 526 |
+
Delta = Delta_new
|
| 527 |
+
|
| 528 |
+
if actual_reduction > 0:
|
| 529 |
+
x = x_new
|
| 530 |
+
|
| 531 |
+
f = f_new
|
| 532 |
+
f_true = f.copy()
|
| 533 |
+
|
| 534 |
+
cost = cost_new
|
| 535 |
+
|
| 536 |
+
J = jac(x, f)
|
| 537 |
+
njev += 1
|
| 538 |
+
|
| 539 |
+
if loss_function is not None:
|
| 540 |
+
rho = loss_function(f)
|
| 541 |
+
J, f = scale_for_robust_loss_function(J, f, rho)
|
| 542 |
+
|
| 543 |
+
g = compute_grad(J, f)
|
| 544 |
+
|
| 545 |
+
if jac_scale:
|
| 546 |
+
scale, scale_inv = compute_jac_scale(J, scale_inv)
|
| 547 |
+
else:
|
| 548 |
+
step_norm = 0
|
| 549 |
+
actual_reduction = 0
|
| 550 |
+
|
| 551 |
+
iteration += 1
|
| 552 |
+
|
| 553 |
+
if termination_status is None:
|
| 554 |
+
termination_status = 0
|
| 555 |
+
|
| 556 |
+
active_mask = np.zeros_like(x)
|
| 557 |
+
return OptimizeResult(
|
| 558 |
+
x=x, cost=cost, fun=f_true, jac=J, grad=g, optimality=g_norm,
|
| 559 |
+
active_mask=active_mask, nfev=nfev, njev=njev,
|
| 560 |
+
status=termination_status)
|
shared/package-files/12/125db28cc971dffbcea2b7457e290284dbffa3ec1eed250b0e5f7a62ae6408aa/complex.h
ADDED
|
@@ -0,0 +1,618 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
|
| 3 |
+
#include <complex>
|
| 4 |
+
|
| 5 |
+
#include <c10/macros/Macros.h>
|
| 6 |
+
|
| 7 |
+
#if defined(__CUDACC__) || defined(__HIPCC__)
|
| 8 |
+
#include <thrust/complex.h>
|
| 9 |
+
#endif
|
| 10 |
+
|
| 11 |
+
C10_CLANG_DIAGNOSTIC_PUSH()
|
| 12 |
+
#if C10_CLANG_HAS_WARNING("-Wimplicit-float-conversion")
|
| 13 |
+
C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-float-conversion")
|
| 14 |
+
#endif
|
| 15 |
+
#if C10_CLANG_HAS_WARNING("-Wfloat-conversion")
|
| 16 |
+
C10_CLANG_DIAGNOSTIC_IGNORE("-Wfloat-conversion")
|
| 17 |
+
#endif
|
| 18 |
+
|
| 19 |
+
namespace c10 {
|
| 20 |
+
|
| 21 |
+
// c10::complex is an implementation of complex numbers that aims
|
| 22 |
+
// to work on all devices supported by PyTorch
|
| 23 |
+
//
|
| 24 |
+
// Most of the APIs duplicates std::complex
|
| 25 |
+
// Reference: https://en.cppreference.com/w/cpp/numeric/complex
|
| 26 |
+
//
|
| 27 |
+
// [NOTE: Complex Operator Unification]
|
| 28 |
+
// Operators currently use a mix of std::complex, thrust::complex, and
|
| 29 |
+
// c10::complex internally. The end state is that all operators will use
|
| 30 |
+
// c10::complex internally. Until then, there may be some hacks to support all
|
| 31 |
+
// variants.
|
| 32 |
+
//
|
| 33 |
+
//
|
| 34 |
+
// [Note on Constructors]
|
| 35 |
+
//
|
| 36 |
+
// The APIs of constructors are mostly copied from C++ standard:
|
| 37 |
+
// https://en.cppreference.com/w/cpp/numeric/complex/complex
|
| 38 |
+
//
|
| 39 |
+
// Since C++14, all constructors are constexpr in std::complex
|
| 40 |
+
//
|
| 41 |
+
// There are three types of constructors:
|
| 42 |
+
// - initializing from real and imag:
|
| 43 |
+
// `constexpr complex( const T& re = T(), const T& im = T() );`
|
| 44 |
+
// - implicitly-declared copy constructor
|
| 45 |
+
// - converting constructors
|
| 46 |
+
//
|
| 47 |
+
// Converting constructors:
|
| 48 |
+
// - std::complex defines converting constructor between float/double/long
|
| 49 |
+
// double,
|
| 50 |
+
// while we define converting constructor between float/double.
|
| 51 |
+
// - For these converting constructors, upcasting is implicit, downcasting is
|
| 52 |
+
// explicit.
|
| 53 |
+
// - We also define explicit casting from std::complex/thrust::complex
|
| 54 |
+
// - Note that the conversion from thrust is not constexpr, because
|
| 55 |
+
// thrust does not define them as constexpr ????
|
| 56 |
+
//
|
| 57 |
+
//
|
| 58 |
+
// [Operator =]
|
| 59 |
+
//
|
| 60 |
+
// The APIs of operator = are mostly copied from C++ standard:
|
| 61 |
+
// https://en.cppreference.com/w/cpp/numeric/complex/operator%3D
|
| 62 |
+
//
|
| 63 |
+
// Since C++20, all operator= are constexpr. Although we are not building with
|
| 64 |
+
// C++20, we also obey this behavior.
|
| 65 |
+
//
|
| 66 |
+
// There are three types of assign operator:
|
| 67 |
+
// - Assign a real value from the same scalar type
|
| 68 |
+
// - In std, this is templated as complex& operator=(const T& x)
|
| 69 |
+
// with specialization `complex& operator=(T x)` for float/double/long
|
| 70 |
+
// double Since we only support float and double, on will use `complex&
|
| 71 |
+
// operator=(T x)`
|
| 72 |
+
// - Copy assignment operator and converting assignment operator
|
| 73 |
+
// - There is no specialization of converting assignment operators, which type
|
| 74 |
+
// is
|
| 75 |
+
// convertible is solely dependent on whether the scalar type is convertible
|
| 76 |
+
//
|
| 77 |
+
// In addition to the standard assignment, we also provide assignment operators
|
| 78 |
+
// with std and thrust
|
| 79 |
+
//
|
| 80 |
+
//
|
| 81 |
+
// [Casting operators]
|
| 82 |
+
//
|
| 83 |
+
// std::complex does not have casting operators. We define casting operators
|
| 84 |
+
// casting to std::complex and thrust::complex
|
| 85 |
+
//
|
| 86 |
+
//
|
| 87 |
+
// [Operator ""]
|
| 88 |
+
//
|
| 89 |
+
// std::complex has custom literals `i`, `if` and `il` defined in namespace
|
| 90 |
+
// `std::literals::complex_literals`. We define our own custom literals in the
|
| 91 |
+
// namespace `c10::complex_literals`. Our custom literals does not follow the
|
| 92 |
+
// same behavior as in std::complex, instead, we define _if, _id to construct
|
| 93 |
+
// float/double complex literals.
|
| 94 |
+
//
|
| 95 |
+
//
|
| 96 |
+
// [real() and imag()]
|
| 97 |
+
//
|
| 98 |
+
// In C++20, there are two overload of these functions, one it to return the
|
| 99 |
+
// real/imag, another is to set real/imag, they are both constexpr. We follow
|
| 100 |
+
// this design.
|
| 101 |
+
//
|
| 102 |
+
//
|
| 103 |
+
// [Operator +=,-=,*=,/=]
|
| 104 |
+
//
|
| 105 |
+
// Since C++20, these operators become constexpr. In our implementation, they
|
| 106 |
+
// are also constexpr.
|
| 107 |
+
//
|
| 108 |
+
// There are two types of such operators: operating with a real number, or
|
| 109 |
+
// operating with another complex number. For the operating with a real number,
|
| 110 |
+
// the generic template form has argument type `const T &`, while the overload
|
| 111 |
+
// for float/double/long double has `T`. We will follow the same type as
|
| 112 |
+
// float/double/long double in std.
|
| 113 |
+
//
|
| 114 |
+
// [Unary operator +-]
|
| 115 |
+
//
|
| 116 |
+
// Since C++20, they are constexpr. We also make them expr
|
| 117 |
+
//
|
| 118 |
+
// [Binary operators +-*/]
|
| 119 |
+
//
|
| 120 |
+
// Each operator has three versions (taking + as example):
|
| 121 |
+
// - complex + complex
|
| 122 |
+
// - complex + real
|
| 123 |
+
// - real + complex
|
| 124 |
+
//
|
| 125 |
+
// [Operator ==, !=]
|
| 126 |
+
//
|
| 127 |
+
// Each operator has three versions (taking == as example):
|
| 128 |
+
// - complex == complex
|
| 129 |
+
// - complex == real
|
| 130 |
+
// - real == complex
|
| 131 |
+
//
|
| 132 |
+
// Some of them are removed on C++20, but we decide to keep them
|
| 133 |
+
//
|
| 134 |
+
// [Operator <<, >>]
|
| 135 |
+
//
|
| 136 |
+
// These are implemented by casting to std::complex
|
| 137 |
+
//
|
| 138 |
+
//
|
| 139 |
+
//
|
| 140 |
+
// TODO(@zasdfgbnm): c10::complex<c10::Half> is not currently supported,
|
| 141 |
+
// because:
|
| 142 |
+
// - lots of members and functions of c10::Half are not constexpr
|
| 143 |
+
// - thrust::complex only support float and double
|
| 144 |
+
|
| 145 |
+
template <typename T>
|
| 146 |
+
struct alignas(sizeof(T) * 2) complex {
|
| 147 |
+
using value_type = T;
|
| 148 |
+
|
| 149 |
+
T real_ = T(0);
|
| 150 |
+
T imag_ = T(0);
|
| 151 |
+
|
| 152 |
+
constexpr complex() = default;
|
| 153 |
+
C10_HOST_DEVICE constexpr complex(const T& re, const T& im = T())
|
| 154 |
+
: real_(re), imag_(im) {}
|
| 155 |
+
template <typename U>
|
| 156 |
+
explicit constexpr complex(const std::complex<U>& other)
|
| 157 |
+
: complex(other.real(), other.imag()) {}
|
| 158 |
+
#if defined(__CUDACC__) || defined(__HIPCC__)
|
| 159 |
+
template <typename U>
|
| 160 |
+
explicit C10_HOST_DEVICE complex(const thrust::complex<U>& other)
|
| 161 |
+
: real_(other.real()), imag_(other.imag()) {}
|
| 162 |
+
// NOTE can not be implemented as follow due to ROCm bug:
|
| 163 |
+
// explicit C10_HOST_DEVICE complex(const thrust::complex<U> &other):
|
| 164 |
+
// complex(other.real(), other.imag()) {}
|
| 165 |
+
#endif
|
| 166 |
+
|
| 167 |
+
// Use SFINAE to specialize casting constructor for c10::complex<float> and
|
| 168 |
+
// c10::complex<double>
|
| 169 |
+
template <typename U = T>
|
| 170 |
+
C10_HOST_DEVICE explicit constexpr complex(
|
| 171 |
+
const std::enable_if_t<std::is_same_v<U, float>, complex<double>>& other)
|
| 172 |
+
: real_(other.real_), imag_(other.imag_) {}
|
| 173 |
+
template <typename U = T>
|
| 174 |
+
C10_HOST_DEVICE constexpr complex(
|
| 175 |
+
const std::enable_if_t<std::is_same_v<U, double>, complex<float>>& other)
|
| 176 |
+
: real_(other.real_), imag_(other.imag_) {}
|
| 177 |
+
|
| 178 |
+
constexpr complex<T>& operator=(T re) {
|
| 179 |
+
real_ = re;
|
| 180 |
+
imag_ = 0;
|
| 181 |
+
return *this;
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
constexpr complex<T>& operator+=(T re) {
|
| 185 |
+
real_ += re;
|
| 186 |
+
return *this;
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
constexpr complex<T>& operator-=(T re) {
|
| 190 |
+
real_ -= re;
|
| 191 |
+
return *this;
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
constexpr complex<T>& operator*=(T re) {
|
| 195 |
+
real_ *= re;
|
| 196 |
+
imag_ *= re;
|
| 197 |
+
return *this;
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
constexpr complex<T>& operator/=(T re) {
|
| 201 |
+
real_ /= re;
|
| 202 |
+
imag_ /= re;
|
| 203 |
+
return *this;
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
template <typename U>
|
| 207 |
+
constexpr complex<T>& operator=(const complex<U>& rhs) {
|
| 208 |
+
real_ = rhs.real();
|
| 209 |
+
imag_ = rhs.imag();
|
| 210 |
+
return *this;
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
template <typename U>
|
| 214 |
+
constexpr complex<T>& operator+=(const complex<U>& rhs) {
|
| 215 |
+
real_ += rhs.real();
|
| 216 |
+
imag_ += rhs.imag();
|
| 217 |
+
return *this;
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
template <typename U>
|
| 221 |
+
constexpr complex<T>& operator-=(const complex<U>& rhs) {
|
| 222 |
+
real_ -= rhs.real();
|
| 223 |
+
imag_ -= rhs.imag();
|
| 224 |
+
return *this;
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
template <typename U>
|
| 228 |
+
constexpr complex<T>& operator*=(const complex<U>& rhs) {
|
| 229 |
+
// (a + bi) * (c + di) = (a*c - b*d) + (a * d + b * c) i
|
| 230 |
+
T a = real_;
|
| 231 |
+
T b = imag_;
|
| 232 |
+
U c = rhs.real();
|
| 233 |
+
U d = rhs.imag();
|
| 234 |
+
real_ = a * c - b * d;
|
| 235 |
+
imag_ = a * d + b * c;
|
| 236 |
+
return *this;
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
#ifdef __APPLE__
|
| 240 |
+
#define FORCE_INLINE_APPLE __attribute__((always_inline))
|
| 241 |
+
#else
|
| 242 |
+
#define FORCE_INLINE_APPLE
|
| 243 |
+
#endif
|
| 244 |
+
template <typename U>
|
| 245 |
+
constexpr FORCE_INLINE_APPLE complex<T>& operator/=(const complex<U>& rhs)
|
| 246 |
+
__ubsan_ignore_float_divide_by_zero__ {
|
| 247 |
+
// (a + bi) / (c + di) = (ac + bd)/(c^2 + d^2) + (bc - ad)/(c^2 + d^2) i
|
| 248 |
+
// the calculation below follows numpy's complex division
|
| 249 |
+
T a = real_;
|
| 250 |
+
T b = imag_;
|
| 251 |
+
U c = rhs.real();
|
| 252 |
+
U d = rhs.imag();
|
| 253 |
+
|
| 254 |
+
#if defined(__GNUC__) && !defined(__clang__)
|
| 255 |
+
// std::abs is already constexpr by gcc
|
| 256 |
+
auto abs_c = std::abs(c);
|
| 257 |
+
auto abs_d = std::abs(d);
|
| 258 |
+
#else
|
| 259 |
+
auto abs_c = c < 0 ? -c : c;
|
| 260 |
+
auto abs_d = d < 0 ? -d : d;
|
| 261 |
+
#endif
|
| 262 |
+
|
| 263 |
+
if (abs_c >= abs_d) {
|
| 264 |
+
if (abs_c == 0 && abs_d == 0) {
|
| 265 |
+
/* divide by zeros should yield a complex inf or nan */
|
| 266 |
+
real_ = a / abs_c;
|
| 267 |
+
imag_ = b / abs_d;
|
| 268 |
+
} else {
|
| 269 |
+
auto rat = d / c;
|
| 270 |
+
auto scl = 1.0 / (c + d * rat);
|
| 271 |
+
real_ = (a + b * rat) * scl;
|
| 272 |
+
imag_ = (b - a * rat) * scl;
|
| 273 |
+
}
|
| 274 |
+
} else {
|
| 275 |
+
auto rat = c / d;
|
| 276 |
+
auto scl = 1.0 / (d + c * rat);
|
| 277 |
+
real_ = (a * rat + b) * scl;
|
| 278 |
+
imag_ = (b * rat - a) * scl;
|
| 279 |
+
}
|
| 280 |
+
return *this;
|
| 281 |
+
}
|
| 282 |
+
#undef FORCE_INLINE_APPLE
|
| 283 |
+
|
| 284 |
+
template <typename U>
|
| 285 |
+
constexpr complex<T>& operator=(const std::complex<U>& rhs) {
|
| 286 |
+
real_ = rhs.real();
|
| 287 |
+
imag_ = rhs.imag();
|
| 288 |
+
return *this;
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
#if defined(__CUDACC__) || defined(__HIPCC__)
|
| 292 |
+
template <typename U>
|
| 293 |
+
C10_HOST_DEVICE complex<T>& operator=(const thrust::complex<U>& rhs) {
|
| 294 |
+
real_ = rhs.real();
|
| 295 |
+
imag_ = rhs.imag();
|
| 296 |
+
return *this;
|
| 297 |
+
}
|
| 298 |
+
#endif
|
| 299 |
+
|
| 300 |
+
template <typename U>
|
| 301 |
+
explicit constexpr operator std::complex<U>() const {
|
| 302 |
+
return std::complex<U>(std::complex<T>(real(), imag()));
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
#if defined(__CUDACC__) || defined(__HIPCC__)
|
| 306 |
+
template <typename U>
|
| 307 |
+
C10_HOST_DEVICE explicit operator thrust::complex<U>() const {
|
| 308 |
+
return static_cast<thrust::complex<U>>(thrust::complex<T>(real(), imag()));
|
| 309 |
+
}
|
| 310 |
+
#endif
|
| 311 |
+
|
| 312 |
+
// consistent with NumPy behavior
|
| 313 |
+
explicit constexpr operator bool() const {
|
| 314 |
+
return real() || imag();
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
C10_HOST_DEVICE constexpr T real() const {
|
| 318 |
+
return real_;
|
| 319 |
+
}
|
| 320 |
+
constexpr void real(T value) {
|
| 321 |
+
real_ = value;
|
| 322 |
+
}
|
| 323 |
+
C10_HOST_DEVICE constexpr T imag() const {
|
| 324 |
+
return imag_;
|
| 325 |
+
}
|
| 326 |
+
constexpr void imag(T value) {
|
| 327 |
+
imag_ = value;
|
| 328 |
+
}
|
| 329 |
+
};
|
| 330 |
+
|
| 331 |
+
namespace complex_literals {
|
| 332 |
+
|
| 333 |
+
constexpr complex<float> operator""_if(long double imag) {
|
| 334 |
+
return complex<float>(0.0f, static_cast<float>(imag));
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
constexpr complex<double> operator""_id(long double imag) {
|
| 338 |
+
return complex<double>(0.0, static_cast<double>(imag));
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
constexpr complex<float> operator""_if(unsigned long long imag) {
|
| 342 |
+
return complex<float>(0.0f, static_cast<float>(imag));
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
constexpr complex<double> operator""_id(unsigned long long imag) {
|
| 346 |
+
return complex<double>(0.0, static_cast<double>(imag));
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
} // namespace complex_literals
|
| 350 |
+
|
| 351 |
+
template <typename T>
|
| 352 |
+
constexpr complex<T> operator+(const complex<T>& val) {
|
| 353 |
+
return val;
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
template <typename T>
|
| 357 |
+
constexpr complex<T> operator-(const complex<T>& val) {
|
| 358 |
+
return complex<T>(-val.real(), -val.imag());
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
template <typename T>
|
| 362 |
+
constexpr complex<T> operator+(const complex<T>& lhs, const complex<T>& rhs) {
|
| 363 |
+
complex<T> result = lhs;
|
| 364 |
+
return result += rhs;
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
template <typename T>
|
| 368 |
+
constexpr complex<T> operator+(const complex<T>& lhs, const T& rhs) {
|
| 369 |
+
complex<T> result = lhs;
|
| 370 |
+
return result += rhs;
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
template <typename T>
|
| 374 |
+
constexpr complex<T> operator+(const T& lhs, const complex<T>& rhs) {
|
| 375 |
+
return complex<T>(lhs + rhs.real(), rhs.imag());
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
template <typename T>
|
| 379 |
+
constexpr complex<T> operator-(const complex<T>& lhs, const complex<T>& rhs) {
|
| 380 |
+
complex<T> result = lhs;
|
| 381 |
+
return result -= rhs;
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
template <typename T>
|
| 385 |
+
constexpr complex<T> operator-(const complex<T>& lhs, const T& rhs) {
|
| 386 |
+
complex<T> result = lhs;
|
| 387 |
+
return result -= rhs;
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
template <typename T>
|
| 391 |
+
constexpr complex<T> operator-(const T& lhs, const complex<T>& rhs) {
|
| 392 |
+
complex<T> result = -rhs;
|
| 393 |
+
return result += lhs;
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
template <typename T>
|
| 397 |
+
constexpr complex<T> operator*(const complex<T>& lhs, const complex<T>& rhs) {
|
| 398 |
+
complex<T> result = lhs;
|
| 399 |
+
return result *= rhs;
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
template <typename T>
|
| 403 |
+
constexpr complex<T> operator*(const complex<T>& lhs, const T& rhs) {
|
| 404 |
+
complex<T> result = lhs;
|
| 405 |
+
return result *= rhs;
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
template <typename T>
|
| 409 |
+
constexpr complex<T> operator*(const T& lhs, const complex<T>& rhs) {
|
| 410 |
+
complex<T> result = rhs;
|
| 411 |
+
return result *= lhs;
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
template <typename T>
|
| 415 |
+
constexpr complex<T> operator/(const complex<T>& lhs, const complex<T>& rhs) {
|
| 416 |
+
complex<T> result = lhs;
|
| 417 |
+
return result /= rhs;
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
template <typename T>
|
| 421 |
+
constexpr complex<T> operator/(const complex<T>& lhs, const T& rhs) {
|
| 422 |
+
complex<T> result = lhs;
|
| 423 |
+
return result /= rhs;
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
template <typename T>
|
| 427 |
+
constexpr complex<T> operator/(const T& lhs, const complex<T>& rhs) {
|
| 428 |
+
complex<T> result(lhs, T());
|
| 429 |
+
return result /= rhs;
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
// Define operators between integral scalars and c10::complex. std::complex does
|
| 433 |
+
// not support this when T is a floating-point number. This is useful because it
|
| 434 |
+
// saves a lot of "static_cast" when operate a complex and an integer. This
|
| 435 |
+
// makes the code both less verbose and potentially more efficient.
|
| 436 |
+
#define COMPLEX_INTEGER_OP_TEMPLATE_CONDITION \
|
| 437 |
+
typename std::enable_if_t< \
|
| 438 |
+
std::is_floating_point_v<fT> && std::is_integral_v<iT>, \
|
| 439 |
+
int> = 0
|
| 440 |
+
|
| 441 |
+
template <typename fT, typename iT, COMPLEX_INTEGER_OP_TEMPLATE_CONDITION>
|
| 442 |
+
constexpr c10::complex<fT> operator+(const c10::complex<fT>& a, const iT& b) {
|
| 443 |
+
return a + static_cast<fT>(b);
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
template <typename fT, typename iT, COMPLEX_INTEGER_OP_TEMPLATE_CONDITION>
|
| 447 |
+
constexpr c10::complex<fT> operator+(const iT& a, const c10::complex<fT>& b) {
|
| 448 |
+
return static_cast<fT>(a) + b;
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
template <typename fT, typename iT, COMPLEX_INTEGER_OP_TEMPLATE_CONDITION>
|
| 452 |
+
constexpr c10::complex<fT> operator-(const c10::complex<fT>& a, const iT& b) {
|
| 453 |
+
return a - static_cast<fT>(b);
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
template <typename fT, typename iT, COMPLEX_INTEGER_OP_TEMPLATE_CONDITION>
|
| 457 |
+
constexpr c10::complex<fT> operator-(const iT& a, const c10::complex<fT>& b) {
|
| 458 |
+
return static_cast<fT>(a) - b;
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
template <typename fT, typename iT, COMPLEX_INTEGER_OP_TEMPLATE_CONDITION>
|
| 462 |
+
constexpr c10::complex<fT> operator*(const c10::complex<fT>& a, const iT& b) {
|
| 463 |
+
return a * static_cast<fT>(b);
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
template <typename fT, typename iT, COMPLEX_INTEGER_OP_TEMPLATE_CONDITION>
|
| 467 |
+
constexpr c10::complex<fT> operator*(const iT& a, const c10::complex<fT>& b) {
|
| 468 |
+
return static_cast<fT>(a) * b;
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
template <typename fT, typename iT, COMPLEX_INTEGER_OP_TEMPLATE_CONDITION>
|
| 472 |
+
constexpr c10::complex<fT> operator/(const c10::complex<fT>& a, const iT& b) {
|
| 473 |
+
return a / static_cast<fT>(b);
|
| 474 |
+
}
|
| 475 |
+
|
| 476 |
+
template <typename fT, typename iT, COMPLEX_INTEGER_OP_TEMPLATE_CONDITION>
|
| 477 |
+
constexpr c10::complex<fT> operator/(const iT& a, const c10::complex<fT>& b) {
|
| 478 |
+
return static_cast<fT>(a) / b;
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
#undef COMPLEX_INTEGER_OP_TEMPLATE_CONDITION
|
| 482 |
+
|
| 483 |
+
template <typename T>
|
| 484 |
+
constexpr bool operator==(const complex<T>& lhs, const complex<T>& rhs) {
|
| 485 |
+
return (lhs.real() == rhs.real()) && (lhs.imag() == rhs.imag());
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
template <typename T>
|
| 489 |
+
constexpr bool operator==(const complex<T>& lhs, const T& rhs) {
|
| 490 |
+
return (lhs.real() == rhs) && (lhs.imag() == T());
|
| 491 |
+
}
|
| 492 |
+
|
| 493 |
+
template <typename T>
|
| 494 |
+
constexpr bool operator==(const T& lhs, const complex<T>& rhs) {
|
| 495 |
+
return (lhs == rhs.real()) && (T() == rhs.imag());
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
template <typename T>
|
| 499 |
+
constexpr bool operator!=(const complex<T>& lhs, const complex<T>& rhs) {
|
| 500 |
+
return !(lhs == rhs);
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
template <typename T>
|
| 504 |
+
constexpr bool operator!=(const complex<T>& lhs, const T& rhs) {
|
| 505 |
+
return !(lhs == rhs);
|
| 506 |
+
}
|
| 507 |
+
|
| 508 |
+
template <typename T>
|
| 509 |
+
constexpr bool operator!=(const T& lhs, const complex<T>& rhs) {
|
| 510 |
+
return !(lhs == rhs);
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
template <typename T, typename CharT, typename Traits>
|
| 514 |
+
std::basic_ostream<CharT, Traits>& operator<<(
|
| 515 |
+
std::basic_ostream<CharT, Traits>& os,
|
| 516 |
+
const complex<T>& x) {
|
| 517 |
+
return (os << static_cast<std::complex<T>>(x));
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
template <typename T, typename CharT, typename Traits>
|
| 521 |
+
std::basic_istream<CharT, Traits>& operator>>(
|
| 522 |
+
std::basic_istream<CharT, Traits>& is,
|
| 523 |
+
complex<T>& x) {
|
| 524 |
+
std::complex<T> tmp;
|
| 525 |
+
is >> tmp;
|
| 526 |
+
x = tmp;
|
| 527 |
+
return is;
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
} // namespace c10
|
| 531 |
+
|
| 532 |
+
// std functions
|
| 533 |
+
//
|
| 534 |
+
// The implementation of these functions also follow the design of C++20
|
| 535 |
+
|
| 536 |
+
namespace std {
|
| 537 |
+
|
| 538 |
+
template <typename T>
|
| 539 |
+
constexpr T real(const c10::complex<T>& z) {
|
| 540 |
+
return z.real();
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
template <typename T>
|
| 544 |
+
constexpr T imag(const c10::complex<T>& z) {
|
| 545 |
+
return z.imag();
|
| 546 |
+
}
|
| 547 |
+
|
| 548 |
+
template <typename T>
|
| 549 |
+
C10_HOST_DEVICE T abs(const c10::complex<T>& z) {
|
| 550 |
+
#if defined(__CUDACC__) || defined(__HIPCC__)
|
| 551 |
+
return thrust::abs(static_cast<thrust::complex<T>>(z));
|
| 552 |
+
#else
|
| 553 |
+
return std::abs(static_cast<std::complex<T>>(z));
|
| 554 |
+
#endif
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
#if defined(USE_ROCM)
|
| 558 |
+
#define ROCm_Bug(x)
|
| 559 |
+
#else
|
| 560 |
+
#define ROCm_Bug(x) x
|
| 561 |
+
#endif
|
| 562 |
+
|
| 563 |
+
template <typename T>
|
| 564 |
+
C10_HOST_DEVICE T arg(const c10::complex<T>& z) {
|
| 565 |
+
return ROCm_Bug(std)::atan2(std::imag(z), std::real(z));
|
| 566 |
+
}
|
| 567 |
+
|
| 568 |
+
#undef ROCm_Bug
|
| 569 |
+
|
| 570 |
+
template <typename T>
|
| 571 |
+
constexpr T norm(const c10::complex<T>& z) {
|
| 572 |
+
return z.real() * z.real() + z.imag() * z.imag();
|
| 573 |
+
}
|
| 574 |
+
|
| 575 |
+
// For std::conj, there are other versions of it:
|
| 576 |
+
// constexpr std::complex<float> conj( float z );
|
| 577 |
+
// template< class DoubleOrInteger >
|
| 578 |
+
// constexpr std::complex<double> conj( DoubleOrInteger z );
|
| 579 |
+
// constexpr std::complex<long double> conj( long double z );
|
| 580 |
+
// These are not implemented
|
| 581 |
+
// TODO(@zasdfgbnm): implement them as c10::conj
|
| 582 |
+
template <typename T>
|
| 583 |
+
constexpr c10::complex<T> conj(const c10::complex<T>& z) {
|
| 584 |
+
return c10::complex<T>(z.real(), -z.imag());
|
| 585 |
+
}
|
| 586 |
+
|
| 587 |
+
// Thrust does not have complex --> complex version of thrust::proj,
|
| 588 |
+
// so this function is not implemented at c10 right now.
|
| 589 |
+
// TODO(@zasdfgbnm): implement it by ourselves
|
| 590 |
+
|
| 591 |
+
// There is no c10 version of std::polar, because std::polar always
|
| 592 |
+
// returns std::complex. Use c10::polar instead;
|
| 593 |
+
|
| 594 |
+
} // namespace std
|
| 595 |
+
|
| 596 |
+
namespace c10 {
|
| 597 |
+
|
| 598 |
+
template <typename T>
|
| 599 |
+
C10_HOST_DEVICE complex<T> polar(const T& r, const T& theta = T()) {
|
| 600 |
+
#if defined(__CUDACC__) || defined(__HIPCC__)
|
| 601 |
+
return static_cast<complex<T>>(thrust::polar(r, theta));
|
| 602 |
+
#else
|
| 603 |
+
// std::polar() requires r >= 0, so spell out the explicit implementation to
|
| 604 |
+
// avoid a branch.
|
| 605 |
+
return complex<T>(r * std::cos(theta), r * std::sin(theta));
|
| 606 |
+
#endif
|
| 607 |
+
}
|
| 608 |
+
|
| 609 |
+
} // namespace c10
|
| 610 |
+
|
| 611 |
+
C10_CLANG_DIAGNOSTIC_POP()
|
| 612 |
+
|
| 613 |
+
#define C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H
|
| 614 |
+
// math functions are included in a separate file
|
| 615 |
+
#include <c10/util/complex_math.h> // IWYU pragma: keep
|
| 616 |
+
// utilities for complex types
|
| 617 |
+
#include <c10/util/complex_utils.h> // IWYU pragma: keep
|
| 618 |
+
#undef C10_INTERNAL_INCLUDE_COMPLEX_REMAINING_H
|
shared/package-files/12/125e7a772c88cc9932055ff5807f9b197f2217a2739f4121a662442b9ee0bcab/test_hyper.py
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.containers import Tuple
|
| 2 |
+
from sympy.core.function import Derivative
|
| 3 |
+
from sympy.core.numbers import (I, Rational, oo, pi)
|
| 4 |
+
from sympy.core.singleton import S
|
| 5 |
+
from sympy.core.symbol import symbols
|
| 6 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 7 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 8 |
+
from sympy.functions.elementary.trigonometric import cos
|
| 9 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 10 |
+
from sympy.functions.special.hyper import (appellf1, hyper, meijerg)
|
| 11 |
+
from sympy.series.order import O
|
| 12 |
+
from sympy.abc import x, z, k
|
| 13 |
+
from sympy.series.limits import limit
|
| 14 |
+
from sympy.testing.pytest import raises, slow
|
| 15 |
+
from sympy.core.random import (
|
| 16 |
+
random_complex_number as randcplx,
|
| 17 |
+
verify_numerically as tn,
|
| 18 |
+
test_derivative_numerically as td)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_TupleParametersBase():
|
| 22 |
+
# test that our implementation of the chain rule works
|
| 23 |
+
p = hyper((), (), z**2)
|
| 24 |
+
assert p.diff(z) == p*2*z
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_hyper():
|
| 28 |
+
raises(TypeError, lambda: hyper(1, 2, z))
|
| 29 |
+
|
| 30 |
+
assert hyper((1, 2), (1,), z) == hyper(Tuple(1, 2), Tuple(1), z)
|
| 31 |
+
|
| 32 |
+
h = hyper((1, 2), (3, 4, 5), z)
|
| 33 |
+
assert h.ap == Tuple(1, 2)
|
| 34 |
+
assert h.bq == Tuple(3, 4, 5)
|
| 35 |
+
assert h.argument == z
|
| 36 |
+
assert h.is_commutative is True
|
| 37 |
+
|
| 38 |
+
# just a few checks to make sure that all arguments go where they should
|
| 39 |
+
assert tn(hyper(Tuple(), Tuple(), z), exp(z), z)
|
| 40 |
+
assert tn(z*hyper((1, 1), Tuple(2), -z), log(1 + z), z)
|
| 41 |
+
|
| 42 |
+
# differentiation
|
| 43 |
+
h = hyper(
|
| 44 |
+
(randcplx(), randcplx(), randcplx()), (randcplx(), randcplx()), z)
|
| 45 |
+
assert td(h, z)
|
| 46 |
+
|
| 47 |
+
a1, a2, b1, b2, b3 = symbols('a1:3, b1:4')
|
| 48 |
+
assert hyper((a1, a2), (b1, b2, b3), z).diff(z) == \
|
| 49 |
+
a1*a2/(b1*b2*b3) * hyper((a1 + 1, a2 + 1), (b1 + 1, b2 + 1, b3 + 1), z)
|
| 50 |
+
|
| 51 |
+
# differentiation wrt parameters is not supported
|
| 52 |
+
assert hyper([z], [], z).diff(z) == Derivative(hyper([z], [], z), z)
|
| 53 |
+
|
| 54 |
+
# hyper is unbranched wrt parameters
|
| 55 |
+
from sympy.functions.elementary.complexes import polar_lift
|
| 56 |
+
assert hyper([polar_lift(z)], [polar_lift(k)], polar_lift(x)) == \
|
| 57 |
+
hyper([z], [k], polar_lift(x))
|
| 58 |
+
|
| 59 |
+
# hyper does not automatically evaluate anyway, but the test is to make
|
| 60 |
+
# sure that the evaluate keyword is accepted
|
| 61 |
+
assert hyper((1, 2), (1,), z, evaluate=False).func is hyper
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_expand_func():
|
| 65 |
+
# evaluation at 1 of Gauss' hypergeometric function:
|
| 66 |
+
from sympy.abc import a, b, c
|
| 67 |
+
from sympy.core.function import expand_func
|
| 68 |
+
a1, b1, c1 = randcplx(), randcplx(), randcplx() + 5
|
| 69 |
+
assert expand_func(hyper([a, b], [c], 1)) == \
|
| 70 |
+
gamma(c)*gamma(-a - b + c)/(gamma(-a + c)*gamma(-b + c))
|
| 71 |
+
assert abs(expand_func(hyper([a1, b1], [c1], 1)).n()
|
| 72 |
+
- hyper([a1, b1], [c1], 1).n()) < 1e-10
|
| 73 |
+
|
| 74 |
+
# hyperexpand wrapper for hyper:
|
| 75 |
+
assert expand_func(hyper([], [], z)) == exp(z)
|
| 76 |
+
assert expand_func(hyper([1, 2, 3], [], z)) == hyper([1, 2, 3], [], z)
|
| 77 |
+
assert expand_func(meijerg([[1, 1], []], [[1], [0]], z)) == log(z + 1)
|
| 78 |
+
assert expand_func(meijerg([[1, 1], []], [[], []], z)) == \
|
| 79 |
+
meijerg([[1, 1], []], [[], []], z)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def replace_dummy(expr, sym):
|
| 83 |
+
from sympy.core.symbol import Dummy
|
| 84 |
+
dum = expr.atoms(Dummy)
|
| 85 |
+
if not dum:
|
| 86 |
+
return expr
|
| 87 |
+
assert len(dum) == 1
|
| 88 |
+
return expr.xreplace({dum.pop(): sym})
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def test_hyper_rewrite_sum():
|
| 92 |
+
from sympy.concrete.summations import Sum
|
| 93 |
+
from sympy.core.symbol import Dummy
|
| 94 |
+
from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial)
|
| 95 |
+
_k = Dummy("k")
|
| 96 |
+
assert replace_dummy(hyper((1, 2), (1, 3), x).rewrite(Sum), _k) == \
|
| 97 |
+
Sum(x**_k / factorial(_k) * RisingFactorial(2, _k) /
|
| 98 |
+
RisingFactorial(3, _k), (_k, 0, oo))
|
| 99 |
+
|
| 100 |
+
assert hyper((1, 2, 3), (-1, 3), z).rewrite(Sum) == \
|
| 101 |
+
hyper((1, 2, 3), (-1, 3), z)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def test_radius_of_convergence():
|
| 105 |
+
assert hyper((1, 2), [3], z).radius_of_convergence == 1
|
| 106 |
+
assert hyper((1, 2), [3, 4], z).radius_of_convergence is oo
|
| 107 |
+
assert hyper((1, 2, 3), [4], z).radius_of_convergence == 0
|
| 108 |
+
assert hyper((0, 1, 2), [4], z).radius_of_convergence is oo
|
| 109 |
+
assert hyper((-1, 1, 2), [-4], z).radius_of_convergence == 0
|
| 110 |
+
assert hyper((-1, -2, 2), [-1], z).radius_of_convergence is oo
|
| 111 |
+
assert hyper((-1, 2), [-1, -2], z).radius_of_convergence == 0
|
| 112 |
+
assert hyper([-1, 1, 3], [-2, 2], z).radius_of_convergence == 1
|
| 113 |
+
assert hyper([-1, 1], [-2, 2], z).radius_of_convergence is oo
|
| 114 |
+
assert hyper([-1, 1, 3], [-2], z).radius_of_convergence == 0
|
| 115 |
+
assert hyper((-1, 2, 3, 4), [], z).radius_of_convergence is oo
|
| 116 |
+
|
| 117 |
+
assert hyper([1, 1], [3], 1).convergence_statement == True
|
| 118 |
+
assert hyper([1, 1], [2], 1).convergence_statement == False
|
| 119 |
+
assert hyper([1, 1], [2], -1).convergence_statement == True
|
| 120 |
+
assert hyper([1, 1], [1], -1).convergence_statement == False
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_meijer():
|
| 124 |
+
raises(TypeError, lambda: meijerg(1, z))
|
| 125 |
+
raises(TypeError, lambda: meijerg(((1,), (2,)), (3,), (4,), z))
|
| 126 |
+
|
| 127 |
+
assert meijerg(((1, 2), (3,)), ((4,), (5,)), z) == \
|
| 128 |
+
meijerg(Tuple(1, 2), Tuple(3), Tuple(4), Tuple(5), z)
|
| 129 |
+
|
| 130 |
+
g = meijerg((1, 2), (3, 4, 5), (6, 7, 8, 9), (10, 11, 12, 13, 14), z)
|
| 131 |
+
assert g.an == Tuple(1, 2)
|
| 132 |
+
assert g.ap == Tuple(1, 2, 3, 4, 5)
|
| 133 |
+
assert g.aother == Tuple(3, 4, 5)
|
| 134 |
+
assert g.bm == Tuple(6, 7, 8, 9)
|
| 135 |
+
assert g.bq == Tuple(6, 7, 8, 9, 10, 11, 12, 13, 14)
|
| 136 |
+
assert g.bother == Tuple(10, 11, 12, 13, 14)
|
| 137 |
+
assert g.argument == z
|
| 138 |
+
assert g.nu == 75
|
| 139 |
+
assert g.delta == -1
|
| 140 |
+
assert g.is_commutative is True
|
| 141 |
+
assert g.is_number is False
|
| 142 |
+
#issue 13071
|
| 143 |
+
assert meijerg([[],[]], [[S.Half],[0]], 1).is_number is True
|
| 144 |
+
|
| 145 |
+
assert meijerg([1, 2], [3], [4], [5], z).delta == S.Half
|
| 146 |
+
|
| 147 |
+
# just a few checks to make sure that all arguments go where they should
|
| 148 |
+
assert tn(meijerg(Tuple(), Tuple(), Tuple(0), Tuple(), -z), exp(z), z)
|
| 149 |
+
assert tn(sqrt(pi)*meijerg(Tuple(), Tuple(),
|
| 150 |
+
Tuple(0), Tuple(S.Half), z**2/4), cos(z), z)
|
| 151 |
+
assert tn(meijerg(Tuple(1, 1), Tuple(), Tuple(1), Tuple(0), z),
|
| 152 |
+
log(1 + z), z)
|
| 153 |
+
|
| 154 |
+
# test exceptions
|
| 155 |
+
raises(ValueError, lambda: meijerg(((3, 1), (2,)), ((oo,), (2, 0)), x))
|
| 156 |
+
raises(ValueError, lambda: meijerg(((3, 1), (2,)), ((1,), (2, 0)), x))
|
| 157 |
+
|
| 158 |
+
# differentiation
|
| 159 |
+
g = meijerg((randcplx(),), (randcplx() + 2*I,), Tuple(),
|
| 160 |
+
(randcplx(), randcplx()), z)
|
| 161 |
+
assert td(g, z)
|
| 162 |
+
|
| 163 |
+
g = meijerg(Tuple(), (randcplx(),), Tuple(),
|
| 164 |
+
(randcplx(), randcplx()), z)
|
| 165 |
+
assert td(g, z)
|
| 166 |
+
|
| 167 |
+
g = meijerg(Tuple(), Tuple(), Tuple(randcplx()),
|
| 168 |
+
Tuple(randcplx(), randcplx()), z)
|
| 169 |
+
assert td(g, z)
|
| 170 |
+
|
| 171 |
+
a1, a2, b1, b2, c1, c2, d1, d2 = symbols('a1:3, b1:3, c1:3, d1:3')
|
| 172 |
+
assert meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z).diff(z) == \
|
| 173 |
+
(meijerg((a1 - 1, a2), (b1, b2), (c1, c2), (d1, d2), z)
|
| 174 |
+
+ (a1 - 1)*meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z))/z
|
| 175 |
+
|
| 176 |
+
assert meijerg([z, z], [], [], [], z).diff(z) == \
|
| 177 |
+
Derivative(meijerg([z, z], [], [], [], z), z)
|
| 178 |
+
|
| 179 |
+
# meijerg is unbranched wrt parameters
|
| 180 |
+
from sympy.functions.elementary.complexes import polar_lift as pl
|
| 181 |
+
assert meijerg([pl(a1)], [pl(a2)], [pl(b1)], [pl(b2)], pl(z)) == \
|
| 182 |
+
meijerg([a1], [a2], [b1], [b2], pl(z))
|
| 183 |
+
|
| 184 |
+
# integrand
|
| 185 |
+
from sympy.abc import a, b, c, d, s
|
| 186 |
+
assert meijerg([a], [b], [c], [d], z).integrand(s) == \
|
| 187 |
+
z**s*gamma(c - s)*gamma(-a + s + 1)/(gamma(b - s)*gamma(-d + s + 1))
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_meijerg_derivative():
|
| 191 |
+
assert meijerg([], [1, 1], [0, 0, x], [], z).diff(x) == \
|
| 192 |
+
log(z)*meijerg([], [1, 1], [0, 0, x], [], z) \
|
| 193 |
+
+ 2*meijerg([], [1, 1, 1], [0, 0, x, 0], [], z)
|
| 194 |
+
|
| 195 |
+
y = randcplx()
|
| 196 |
+
a = 5 # mpmath chokes with non-real numbers, and Mod1 with floats
|
| 197 |
+
assert td(meijerg([x], [], [], [], y), x)
|
| 198 |
+
assert td(meijerg([x**2], [], [], [], y), x)
|
| 199 |
+
assert td(meijerg([], [x], [], [], y), x)
|
| 200 |
+
assert td(meijerg([], [], [x], [], y), x)
|
| 201 |
+
assert td(meijerg([], [], [], [x], y), x)
|
| 202 |
+
assert td(meijerg([x], [a], [a + 1], [], y), x)
|
| 203 |
+
assert td(meijerg([x], [a + 1], [a], [], y), x)
|
| 204 |
+
assert td(meijerg([x, a], [], [], [a + 1], y), x)
|
| 205 |
+
assert td(meijerg([x, a + 1], [], [], [a], y), x)
|
| 206 |
+
b = Rational(3, 2)
|
| 207 |
+
assert td(meijerg([a + 2], [b], [b - 3, x], [a], y), x)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def test_meijerg_period():
|
| 211 |
+
assert meijerg([], [1], [0], [], x).get_period() == 2*pi
|
| 212 |
+
assert meijerg([1], [], [], [0], x).get_period() == 2*pi
|
| 213 |
+
assert meijerg([], [], [0], [], x).get_period() == 2*pi # exp(x)
|
| 214 |
+
assert meijerg(
|
| 215 |
+
[], [], [0], [S.Half], x).get_period() == 2*pi # cos(sqrt(x))
|
| 216 |
+
assert meijerg(
|
| 217 |
+
[], [], [S.Half], [0], x).get_period() == 4*pi # sin(sqrt(x))
|
| 218 |
+
assert meijerg([1, 1], [], [1], [0], x).get_period() is oo # log(1 + x)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def test_hyper_unpolarify():
|
| 222 |
+
from sympy.functions.elementary.exponential import exp_polar
|
| 223 |
+
a = exp_polar(2*pi*I)*x
|
| 224 |
+
b = x
|
| 225 |
+
assert hyper([], [], a).argument == b
|
| 226 |
+
assert hyper([0], [], a).argument == a
|
| 227 |
+
assert hyper([0], [0], a).argument == b
|
| 228 |
+
assert hyper([0, 1], [0], a).argument == a
|
| 229 |
+
assert hyper([0, 1], [0], exp_polar(2*pi*I)).argument == 1
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
@slow
|
| 233 |
+
def test_hyperrep():
|
| 234 |
+
from sympy.functions.special.hyper import (HyperRep, HyperRep_atanh,
|
| 235 |
+
HyperRep_power1, HyperRep_power2, HyperRep_log1, HyperRep_asin1,
|
| 236 |
+
HyperRep_asin2, HyperRep_sqrts1, HyperRep_sqrts2, HyperRep_log2,
|
| 237 |
+
HyperRep_cosasin, HyperRep_sinasin)
|
| 238 |
+
# First test the base class works.
|
| 239 |
+
from sympy.functions.elementary.exponential import exp_polar
|
| 240 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 241 |
+
a, b, c, d, z = symbols('a b c d z')
|
| 242 |
+
|
| 243 |
+
class myrep(HyperRep):
|
| 244 |
+
@classmethod
|
| 245 |
+
def _expr_small(cls, x):
|
| 246 |
+
return a
|
| 247 |
+
|
| 248 |
+
@classmethod
|
| 249 |
+
def _expr_small_minus(cls, x):
|
| 250 |
+
return b
|
| 251 |
+
|
| 252 |
+
@classmethod
|
| 253 |
+
def _expr_big(cls, x, n):
|
| 254 |
+
return c*n
|
| 255 |
+
|
| 256 |
+
@classmethod
|
| 257 |
+
def _expr_big_minus(cls, x, n):
|
| 258 |
+
return d*n
|
| 259 |
+
assert myrep(z).rewrite('nonrep') == Piecewise((0, abs(z) > 1), (a, True))
|
| 260 |
+
assert myrep(exp_polar(I*pi)*z).rewrite('nonrep') == \
|
| 261 |
+
Piecewise((0, abs(z) > 1), (b, True))
|
| 262 |
+
assert myrep(exp_polar(2*I*pi)*z).rewrite('nonrep') == \
|
| 263 |
+
Piecewise((c, abs(z) > 1), (a, True))
|
| 264 |
+
assert myrep(exp_polar(3*I*pi)*z).rewrite('nonrep') == \
|
| 265 |
+
Piecewise((d, abs(z) > 1), (b, True))
|
| 266 |
+
assert myrep(exp_polar(4*I*pi)*z).rewrite('nonrep') == \
|
| 267 |
+
Piecewise((2*c, abs(z) > 1), (a, True))
|
| 268 |
+
assert myrep(exp_polar(5*I*pi)*z).rewrite('nonrep') == \
|
| 269 |
+
Piecewise((2*d, abs(z) > 1), (b, True))
|
| 270 |
+
assert myrep(z).rewrite('nonrepsmall') == a
|
| 271 |
+
assert myrep(exp_polar(I*pi)*z).rewrite('nonrepsmall') == b
|
| 272 |
+
|
| 273 |
+
def t(func, hyp, z):
|
| 274 |
+
""" Test that func is a valid representation of hyp. """
|
| 275 |
+
# First test that func agrees with hyp for small z
|
| 276 |
+
if not tn(func.rewrite('nonrepsmall'), hyp, z,
|
| 277 |
+
a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half):
|
| 278 |
+
return False
|
| 279 |
+
# Next check that the two small representations agree.
|
| 280 |
+
if not tn(
|
| 281 |
+
func.rewrite('nonrepsmall').subs(
|
| 282 |
+
z, exp_polar(I*pi)*z).replace(exp_polar, exp),
|
| 283 |
+
func.subs(z, exp_polar(I*pi)*z).rewrite('nonrepsmall'),
|
| 284 |
+
z, a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half):
|
| 285 |
+
return False
|
| 286 |
+
# Next check continuity along exp_polar(I*pi)*t
|
| 287 |
+
expr = func.subs(z, exp_polar(I*pi)*z).rewrite('nonrep')
|
| 288 |
+
if abs(expr.subs(z, 1 + 1e-15).n() - expr.subs(z, 1 - 1e-15).n()) > 1e-10:
|
| 289 |
+
return False
|
| 290 |
+
# Finally check continuity of the big reps.
|
| 291 |
+
|
| 292 |
+
def dosubs(func, a, b):
|
| 293 |
+
rv = func.subs(z, exp_polar(a)*z).rewrite('nonrep')
|
| 294 |
+
return rv.subs(z, exp_polar(b)*z).replace(exp_polar, exp)
|
| 295 |
+
for n in [0, 1, 2, 3, 4, -1, -2, -3, -4]:
|
| 296 |
+
expr1 = dosubs(func, 2*I*pi*n, I*pi/2)
|
| 297 |
+
expr2 = dosubs(func, 2*I*pi*n + I*pi, -I*pi/2)
|
| 298 |
+
if not tn(expr1, expr2, z):
|
| 299 |
+
return False
|
| 300 |
+
expr1 = dosubs(func, 2*I*pi*(n + 1), -I*pi/2)
|
| 301 |
+
expr2 = dosubs(func, 2*I*pi*n + I*pi, I*pi/2)
|
| 302 |
+
if not tn(expr1, expr2, z):
|
| 303 |
+
return False
|
| 304 |
+
return True
|
| 305 |
+
|
| 306 |
+
# Now test the various representatives.
|
| 307 |
+
a = Rational(1, 3)
|
| 308 |
+
assert t(HyperRep_atanh(z), hyper([S.Half, 1], [Rational(3, 2)], z), z)
|
| 309 |
+
assert t(HyperRep_power1(a, z), hyper([-a], [], z), z)
|
| 310 |
+
assert t(HyperRep_power2(a, z), hyper([a, a - S.Half], [2*a], z), z)
|
| 311 |
+
assert t(HyperRep_log1(z), -z*hyper([1, 1], [2], z), z)
|
| 312 |
+
assert t(HyperRep_asin1(z), hyper([S.Half, S.Half], [Rational(3, 2)], z), z)
|
| 313 |
+
assert t(HyperRep_asin2(z), hyper([1, 1], [Rational(3, 2)], z), z)
|
| 314 |
+
assert t(HyperRep_sqrts1(a, z), hyper([-a, S.Half - a], [S.Half], z), z)
|
| 315 |
+
assert t(HyperRep_sqrts2(a, z),
|
| 316 |
+
-2*z/(2*a + 1)*hyper([-a - S.Half, -a], [S.Half], z).diff(z), z)
|
| 317 |
+
assert t(HyperRep_log2(z), -z/4*hyper([Rational(3, 2), 1, 1], [2, 2], z), z)
|
| 318 |
+
assert t(HyperRep_cosasin(a, z), hyper([-a, a], [S.Half], z), z)
|
| 319 |
+
assert t(HyperRep_sinasin(a, z), 2*a*z*hyper([1 - a, 1 + a], [Rational(3, 2)], z), z)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
@slow
|
| 323 |
+
def test_meijerg_eval():
|
| 324 |
+
from sympy.functions.elementary.exponential import exp_polar
|
| 325 |
+
from sympy.functions.special.bessel import besseli
|
| 326 |
+
from sympy.abc import l
|
| 327 |
+
a = randcplx()
|
| 328 |
+
arg = x*exp_polar(k*pi*I)
|
| 329 |
+
expr1 = pi*meijerg([[], [(a + 1)/2]], [[a/2], [-a/2, (a + 1)/2]], arg**2/4)
|
| 330 |
+
expr2 = besseli(a, arg)
|
| 331 |
+
|
| 332 |
+
# Test that the two expressions agree for all arguments.
|
| 333 |
+
for x_ in [0.5, 1.5]:
|
| 334 |
+
for k_ in [0.0, 0.1, 0.3, 0.5, 0.8, 1, 5.751, 15.3]:
|
| 335 |
+
assert abs((expr1 - expr2).n(subs={x: x_, k: k_})) < 1e-10
|
| 336 |
+
assert abs((expr1 - expr2).n(subs={x: x_, k: -k_})) < 1e-10
|
| 337 |
+
|
| 338 |
+
# Test continuity independently
|
| 339 |
+
eps = 1e-13
|
| 340 |
+
expr2 = expr1.subs(k, l)
|
| 341 |
+
for x_ in [0.5, 1.5]:
|
| 342 |
+
for k_ in [0.5, Rational(1, 3), 0.25, 0.75, Rational(2, 3), 1.0, 1.5]:
|
| 343 |
+
assert abs((expr1 - expr2).n(
|
| 344 |
+
subs={x: x_, k: k_ + eps, l: k_ - eps})) < 1e-10
|
| 345 |
+
assert abs((expr1 - expr2).n(
|
| 346 |
+
subs={x: x_, k: -k_ + eps, l: -k_ - eps})) < 1e-10
|
| 347 |
+
|
| 348 |
+
expr = (meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(-I*pi)/4)
|
| 349 |
+
+ meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(I*pi)/4)) \
|
| 350 |
+
/(2*sqrt(pi))
|
| 351 |
+
assert (expr - pi/exp(1)).n(chop=True) == 0
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def test_limits():
|
| 355 |
+
k, x = symbols('k, x')
|
| 356 |
+
assert hyper((1,), (Rational(4, 3), Rational(5, 3)), k**2).series(k) == \
|
| 357 |
+
1 + 9*k**2/20 + 81*k**4/1120 + O(k**6) # issue 6350
|
| 358 |
+
|
| 359 |
+
# https://github.com/sympy/sympy/issues/11465
|
| 360 |
+
assert limit(1/hyper((1, ), (1, ), x), x, 0) == 1
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def test_appellf1():
|
| 364 |
+
a, b1, b2, c, x, y = symbols('a b1 b2 c x y')
|
| 365 |
+
assert appellf1(a, b2, b1, c, y, x) == appellf1(a, b1, b2, c, x, y)
|
| 366 |
+
assert appellf1(a, b1, b1, c, y, x) == appellf1(a, b1, b1, c, x, y)
|
| 367 |
+
assert appellf1(a, b1, b2, c, S.Zero, S.Zero) is S.One
|
| 368 |
+
|
| 369 |
+
f = appellf1(a, b1, b2, c, S.Zero, S.Zero, evaluate=False)
|
| 370 |
+
assert f.func is appellf1
|
| 371 |
+
assert f.doit() is S.One
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def test_derivative_appellf1():
|
| 375 |
+
from sympy.core.function import diff
|
| 376 |
+
a, b1, b2, c, x, y, z = symbols('a b1 b2 c x y z')
|
| 377 |
+
assert diff(appellf1(a, b1, b2, c, x, y), x) == a*b1*appellf1(a + 1, b2, b1 + 1, c + 1, y, x)/c
|
| 378 |
+
assert diff(appellf1(a, b1, b2, c, x, y), y) == a*b2*appellf1(a + 1, b1, b2 + 1, c + 1, x, y)/c
|
| 379 |
+
assert diff(appellf1(a, b1, b2, c, x, y), z) == 0
|
| 380 |
+
assert diff(appellf1(a, b1, b2, c, x, y), a) == Derivative(appellf1(a, b1, b2, c, x, y), a)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def test_eval_nseries():
|
| 384 |
+
a1, b1, a2, b2 = symbols('a1 b1 a2 b2')
|
| 385 |
+
assert hyper((1,2), (1,2,3), x**2)._eval_nseries(x, 7, None) == 1 + x**2/3 + x**4/24 + x**6/360 + O(x**7)
|
| 386 |
+
assert exp(x)._eval_nseries(x,7,None) == hyper((a1, b1), (a1, b1), x)._eval_nseries(x, 7, None)
|
| 387 |
+
assert hyper((a1, a2), (b1, b2), x)._eval_nseries(z, 7, None) == hyper((a1, a2), (b1, b2), x) + O(z**7)
|