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/16/1604a69d2d60921502b375a8af0d662702abe625987b773637a34c09c76a8a25/functools.py +992 -0
- shared/package-files/17/170374feae76894ea274b359357a34d3680f369570ffdc6bc4b89f1672bfb2cc/preview.py +390 -0
- shared/package-files/17/17042ba9d09eb176e0910f1b7d83e57f72df2be49dbee77da47102dad0a7c10d/test_align.py +484 -0
- shared/package-files/17/1707a57215415ca7f79dcefc52003d4b225b1ed6b710c76b2e7422cc8c52e521/thingsdb.py +116 -0
- shared/package-files/17/170a22363b185e20ae6054f7dc54d41455bffa88d2ef1819c020bf1ec1d3f5d1/_colorconv.py +222 -0
- shared/package-files/17/172d4e30d85b5513614db7549a2ca7dce0b6eb304067f8d3b2133d92b8d3993a/compare.py +320 -0
- shared/package-files/17/173208235bca43da20ef09451c72d42de5fd82f3b183884873a93c7a74da1094/slow_conv3d.h +91 -0
- shared/package-files/17/1735c710532f1b6f39dbdcd58183eabc85159a0bb86fa22d2479b22c339c8ec5/loader.pyi +31 -0
- shared/package-files/17/173f35914e71d60e8e9cd991adae8f45aacfa6ae47118b80f175f4b11ff2e8b2/test_base_indexer.py +519 -0
- shared/package-files/17/1745088ef9845a0e712982696a64a0fc9eb238f1f4c24a719fb5fa3a87c42f05/objects.py +49 -0
- shared/package-files/17/174d76b7c7645faf65fed700bf67998ff201afbb327c00ee635a5837dd871c6b/anchor.py +20 -0
- shared/package-files/17/17cf0752407210fe07e9c27f213bc87b46bf4f5047d8939d472b0c0aed57227d/test_defchararray.py +686 -0
- shared/package-files/17/17de9f3d36c6ccbd97ed4ca15a908ad06663a84aa5d485714b202db7fe8e171a/dylib.py +63 -0
- shared/package-files/98/980d45c9423cf89d78c99d557f949ed0e796daee27bfdfb5b34afd78e98ec671/test_round.py +383 -0
- shared/package-files/98/98178982f59c0d90663c54ad0cd12397379963768c0cc0875a88fb7429a0ba04/_constants.py +42 -0
- shared/package-files/98/9853cf796c52df2ab9b35b415405289e71e7baddefe1b177653f78a612cf4cf0/nan_to_num_ops.h +50 -0
- shared/package-files/98/9856346efdad114b43a74ca909e955abf460b5b81403f1d6ee68a452ae9ad3ef/LazyIr.h +19 -0
- shared/package-files/98/985a754c752be6a45c6bb515b463a2c3f3be1b06645a2e959fb6c78885dab9a9/superbrain +0 -0
- shared/package-files/98/987ff0da1e11da62c5fc63ff754af982106f33ae54f2d564fa00b9a4c6125506/conftest.py +2065 -0
- shared/package-files/98/98b8dde9c3de47c453617f8b041c745642d5bc05982716fa304dd3e19501b963/_warnings.py +114 -0
- shared/package-files/98/98bf278df7fbace3255edc6690ef155e9a36472c7ee7dbc306a84f8f07bafa61/nll_loss_nd_native.h +21 -0
- shared/package-files/98/98e0487d7357b3bc5df729d23ed1d391a66d9e2665f9ed328dabacc228d4bb83/_cast_Long_ops.h +28 -0
- shared/package-files/d1/d10ac70fd4d82a5499b8ef1dae75376d4149ad2bbcbf94a772ab6445258b8c63/euler.py +108 -0
- shared/package-files/d1/d1119423dda95126d93a1095b189e7832c14d70332dcdd2d0af063f26349bbdf/fbgemm_pack_quantized_matrix_native.h +22 -0
- shared/package-files/d1/d115718818e3e3367847ce35bb5ff0361d08993d9749d438c918f8eb87ad8814/mt.msg +27 -0
- shared/package-files/d1/d119859b1979b8decbc7beb0ac5349d90cade35b2e593dc7a9e7f4eb7b22c681/parfor_lowering.py +2068 -0
- shared/package-files/d1/d123e0b4c2614f680808b58cca0c140ba187494b2c8bcf8c604c7eb739c70882/zh_hk.msg +28 -0
- shared/package-files/d1/d12457044da126028937f45fe199f4d282970bf4e46b779f3d6338ef383a0686/diagnose.py +154 -0
- shared/package-files/d1/d1284cb753ddb8fdcafa7db41e3c6159140c39128ffeae2bb08458796ce80d1d/options.h +226 -0
- shared/package-files/d1/d12a142fcd22c0b3c7d8cf924e86421e5fde381cf52c77bf10b098e5cdcafef7/tmux-direct +0 -0
- shared/package-files/d1/d12ee45a23c42919a2d224bc250dcae530a1cd2a59361026d668f25d081a513f/_grid_sampler_2d_cpu_fallback_backward_compositeimplicitautograd_dispatch.h +23 -0
- shared/package-files/d1/d132f83197095d4a28f6a03bbaed2f2efede1eb5d17ab566c9f8bb3b5e3d213c/__init__.py +9 -0
- shared/package-files/d1/d136f12171747ea2f89913a16f452fafac4c411543f62b7c24523b3c41261c19/test_unicode.py +0 -0
- shared/package-files/d1/d13744c2cd7cd7bf54732637d88ce57fc6b8cd561beadeb62c4190df13ff3dd9/graph_executor.h +148 -0
- shared/package-files/d1/d13da4530fb2a70d9d66ee96508e6aa0de35f1c0e60a32e52b71b847cec9d292/quantize_pt2e.py +250 -0
- shared/package-files/d1/d143659ddde1ce57f6734122c0b24586d4f256ecb2932c02d13aa206ba4d9501/gnome-rh62 +0 -0
- shared/package-files/d1/d146208ff5159c304faa373716ee1096567fca252e416929c84c25fb34dd096f/__init__.py +0 -0
- shared/package-files/d1/d148cd156ed2cad8f5b77d500fdf5e6dfafe6a5ecd982a5684a50ecaaf55ccaf/_cm_multivar.py +166 -0
- shared/package-files/d1/d1492a222e1e8710f76a8037cfbcbcfb77693acea8df4fc6a7cad9bc55f55bd4/test_deprecate_nonkeyword_arguments.py +141 -0
- shared/package-files/d1/d14b4ebc1555a119f8520c4472cacb7d26258da29873ff2265f23fc5e38207a8/lstm_mps_backward_compositeexplicitautograd_dispatch.h +24 -0
- shared/package-files/d1/d14d03282c4a4f7523cf03d2722d0dd0d0384ec57515a9c3794822758a48797f/median_cuda_dispatch.h +25 -0
- shared/package-files/d1/d150b1972b1ee2e21c960ba945516ead85678037d1eef7c8e3749645425ab13b/cran.py +1799 -0
- shared/package-files/d1/d15889a91b4964b212ec87e31eb520608e9122f598d1c7e4d4e8c0969e3466cc/top_level.txt +1 -0
- shared/package-files/d1/d1648a9846ff3b8a687e05635aa0c20c867054f93762f02e49ba6514afe29139/max_native.h +32 -0
- shared/package-files/d1/d16861859d7ad6a76c11296ef77000e95f64d75330ce6365f679c1c88c0ecabd/libuuid.a +0 -0
- shared/package-files/d1/d173be07d5e60068962e11055bcc2e8c5a3e551d6beb64993fb313f83073d551/test_qcut.py +305 -0
- shared/package-files/d1/d17715b895804e35e43e4a58f764b71cfa6776456950d711dd3ec7a0899f0172/_nested_get_offsets.h +30 -0
- shared/package-files/d1/d18db3d2b95eba710fe685b9dd20c03708d8acca258ed48b297261c633dfedf6/dtypes.py +79 -0
- shared/package-files/d1/d19128733490ab9f7338677f79693ab1f002b7adaf7509ad87789aeeea961533/_matrix_io.py +167 -0
- shared/package-files/d1/d19a7033230c463a7a56d9db153d219ae5719f31ed260f694f10c961133c9fa6/selecting.py +96 -0
shared/package-files/16/1604a69d2d60921502b375a8af0d662702abe625987b773637a34c09c76a8a25/functools.py
ADDED
|
@@ -0,0 +1,992 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""functools.py - Tools for working with functions and callable objects
|
| 2 |
+
"""
|
| 3 |
+
# Python module wrapper for _functools C module
|
| 4 |
+
# to allow utilities written in Python to be added
|
| 5 |
+
# to the functools module.
|
| 6 |
+
# Written by Nick Coghlan <ncoghlan at gmail.com>,
|
| 7 |
+
# Raymond Hettinger <python at rcn.com>,
|
| 8 |
+
# and Łukasz Langa <lukasz at langa.pl>.
|
| 9 |
+
# Copyright (C) 2006-2013 Python Software Foundation.
|
| 10 |
+
# See C source code for _functools credits/copyright
|
| 11 |
+
|
| 12 |
+
__all__ = ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES',
|
| 13 |
+
'total_ordering', 'cache', 'cmp_to_key', 'lru_cache', 'reduce',
|
| 14 |
+
'partial', 'partialmethod', 'singledispatch', 'singledispatchmethod',
|
| 15 |
+
'cached_property']
|
| 16 |
+
|
| 17 |
+
from abc import get_cache_token
|
| 18 |
+
from collections import namedtuple
|
| 19 |
+
# import types, weakref # Deferred to single_dispatch()
|
| 20 |
+
from reprlib import recursive_repr
|
| 21 |
+
from _thread import RLock
|
| 22 |
+
from types import GenericAlias
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
################################################################################
|
| 26 |
+
### update_wrapper() and wraps() decorator
|
| 27 |
+
################################################################################
|
| 28 |
+
|
| 29 |
+
# update_wrapper() and wraps() are tools to help write
|
| 30 |
+
# wrapper functions that can handle naive introspection
|
| 31 |
+
|
| 32 |
+
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__',
|
| 33 |
+
'__annotations__')
|
| 34 |
+
WRAPPER_UPDATES = ('__dict__',)
|
| 35 |
+
def update_wrapper(wrapper,
|
| 36 |
+
wrapped,
|
| 37 |
+
assigned = WRAPPER_ASSIGNMENTS,
|
| 38 |
+
updated = WRAPPER_UPDATES):
|
| 39 |
+
"""Update a wrapper function to look like the wrapped function
|
| 40 |
+
|
| 41 |
+
wrapper is the function to be updated
|
| 42 |
+
wrapped is the original function
|
| 43 |
+
assigned is a tuple naming the attributes assigned directly
|
| 44 |
+
from the wrapped function to the wrapper function (defaults to
|
| 45 |
+
functools.WRAPPER_ASSIGNMENTS)
|
| 46 |
+
updated is a tuple naming the attributes of the wrapper that
|
| 47 |
+
are updated with the corresponding attribute from the wrapped
|
| 48 |
+
function (defaults to functools.WRAPPER_UPDATES)
|
| 49 |
+
"""
|
| 50 |
+
for attr in assigned:
|
| 51 |
+
try:
|
| 52 |
+
value = getattr(wrapped, attr)
|
| 53 |
+
except AttributeError:
|
| 54 |
+
pass
|
| 55 |
+
else:
|
| 56 |
+
setattr(wrapper, attr, value)
|
| 57 |
+
for attr in updated:
|
| 58 |
+
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
|
| 59 |
+
# Issue #17482: set __wrapped__ last so we don't inadvertently copy it
|
| 60 |
+
# from the wrapped function when updating __dict__
|
| 61 |
+
wrapper.__wrapped__ = wrapped
|
| 62 |
+
# Return the wrapper so this can be used as a decorator via partial()
|
| 63 |
+
return wrapper
|
| 64 |
+
|
| 65 |
+
def wraps(wrapped,
|
| 66 |
+
assigned = WRAPPER_ASSIGNMENTS,
|
| 67 |
+
updated = WRAPPER_UPDATES):
|
| 68 |
+
"""Decorator factory to apply update_wrapper() to a wrapper function
|
| 69 |
+
|
| 70 |
+
Returns a decorator that invokes update_wrapper() with the decorated
|
| 71 |
+
function as the wrapper argument and the arguments to wraps() as the
|
| 72 |
+
remaining arguments. Default arguments are as for update_wrapper().
|
| 73 |
+
This is a convenience function to simplify applying partial() to
|
| 74 |
+
update_wrapper().
|
| 75 |
+
"""
|
| 76 |
+
return partial(update_wrapper, wrapped=wrapped,
|
| 77 |
+
assigned=assigned, updated=updated)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
################################################################################
|
| 81 |
+
### total_ordering class decorator
|
| 82 |
+
################################################################################
|
| 83 |
+
|
| 84 |
+
# The total ordering functions all invoke the root magic method directly
|
| 85 |
+
# rather than using the corresponding operator. This avoids possible
|
| 86 |
+
# infinite recursion that could occur when the operator dispatch logic
|
| 87 |
+
# detects a NotImplemented result and then calls a reflected method.
|
| 88 |
+
|
| 89 |
+
def _gt_from_lt(self, other, NotImplemented=NotImplemented):
|
| 90 |
+
'Return a > b. Computed by @total_ordering from (not a < b) and (a != b).'
|
| 91 |
+
op_result = type(self).__lt__(self, other)
|
| 92 |
+
if op_result is NotImplemented:
|
| 93 |
+
return op_result
|
| 94 |
+
return not op_result and self != other
|
| 95 |
+
|
| 96 |
+
def _le_from_lt(self, other, NotImplemented=NotImplemented):
|
| 97 |
+
'Return a <= b. Computed by @total_ordering from (a < b) or (a == b).'
|
| 98 |
+
op_result = type(self).__lt__(self, other)
|
| 99 |
+
if op_result is NotImplemented:
|
| 100 |
+
return op_result
|
| 101 |
+
return op_result or self == other
|
| 102 |
+
|
| 103 |
+
def _ge_from_lt(self, other, NotImplemented=NotImplemented):
|
| 104 |
+
'Return a >= b. Computed by @total_ordering from (not a < b).'
|
| 105 |
+
op_result = type(self).__lt__(self, other)
|
| 106 |
+
if op_result is NotImplemented:
|
| 107 |
+
return op_result
|
| 108 |
+
return not op_result
|
| 109 |
+
|
| 110 |
+
def _ge_from_le(self, other, NotImplemented=NotImplemented):
|
| 111 |
+
'Return a >= b. Computed by @total_ordering from (not a <= b) or (a == b).'
|
| 112 |
+
op_result = type(self).__le__(self, other)
|
| 113 |
+
if op_result is NotImplemented:
|
| 114 |
+
return op_result
|
| 115 |
+
return not op_result or self == other
|
| 116 |
+
|
| 117 |
+
def _lt_from_le(self, other, NotImplemented=NotImplemented):
|
| 118 |
+
'Return a < b. Computed by @total_ordering from (a <= b) and (a != b).'
|
| 119 |
+
op_result = type(self).__le__(self, other)
|
| 120 |
+
if op_result is NotImplemented:
|
| 121 |
+
return op_result
|
| 122 |
+
return op_result and self != other
|
| 123 |
+
|
| 124 |
+
def _gt_from_le(self, other, NotImplemented=NotImplemented):
|
| 125 |
+
'Return a > b. Computed by @total_ordering from (not a <= b).'
|
| 126 |
+
op_result = type(self).__le__(self, other)
|
| 127 |
+
if op_result is NotImplemented:
|
| 128 |
+
return op_result
|
| 129 |
+
return not op_result
|
| 130 |
+
|
| 131 |
+
def _lt_from_gt(self, other, NotImplemented=NotImplemented):
|
| 132 |
+
'Return a < b. Computed by @total_ordering from (not a > b) and (a != b).'
|
| 133 |
+
op_result = type(self).__gt__(self, other)
|
| 134 |
+
if op_result is NotImplemented:
|
| 135 |
+
return op_result
|
| 136 |
+
return not op_result and self != other
|
| 137 |
+
|
| 138 |
+
def _ge_from_gt(self, other, NotImplemented=NotImplemented):
|
| 139 |
+
'Return a >= b. Computed by @total_ordering from (a > b) or (a == b).'
|
| 140 |
+
op_result = type(self).__gt__(self, other)
|
| 141 |
+
if op_result is NotImplemented:
|
| 142 |
+
return op_result
|
| 143 |
+
return op_result or self == other
|
| 144 |
+
|
| 145 |
+
def _le_from_gt(self, other, NotImplemented=NotImplemented):
|
| 146 |
+
'Return a <= b. Computed by @total_ordering from (not a > b).'
|
| 147 |
+
op_result = type(self).__gt__(self, other)
|
| 148 |
+
if op_result is NotImplemented:
|
| 149 |
+
return op_result
|
| 150 |
+
return not op_result
|
| 151 |
+
|
| 152 |
+
def _le_from_ge(self, other, NotImplemented=NotImplemented):
|
| 153 |
+
'Return a <= b. Computed by @total_ordering from (not a >= b) or (a == b).'
|
| 154 |
+
op_result = type(self).__ge__(self, other)
|
| 155 |
+
if op_result is NotImplemented:
|
| 156 |
+
return op_result
|
| 157 |
+
return not op_result or self == other
|
| 158 |
+
|
| 159 |
+
def _gt_from_ge(self, other, NotImplemented=NotImplemented):
|
| 160 |
+
'Return a > b. Computed by @total_ordering from (a >= b) and (a != b).'
|
| 161 |
+
op_result = type(self).__ge__(self, other)
|
| 162 |
+
if op_result is NotImplemented:
|
| 163 |
+
return op_result
|
| 164 |
+
return op_result and self != other
|
| 165 |
+
|
| 166 |
+
def _lt_from_ge(self, other, NotImplemented=NotImplemented):
|
| 167 |
+
'Return a < b. Computed by @total_ordering from (not a >= b).'
|
| 168 |
+
op_result = type(self).__ge__(self, other)
|
| 169 |
+
if op_result is NotImplemented:
|
| 170 |
+
return op_result
|
| 171 |
+
return not op_result
|
| 172 |
+
|
| 173 |
+
_convert = {
|
| 174 |
+
'__lt__': [('__gt__', _gt_from_lt),
|
| 175 |
+
('__le__', _le_from_lt),
|
| 176 |
+
('__ge__', _ge_from_lt)],
|
| 177 |
+
'__le__': [('__ge__', _ge_from_le),
|
| 178 |
+
('__lt__', _lt_from_le),
|
| 179 |
+
('__gt__', _gt_from_le)],
|
| 180 |
+
'__gt__': [('__lt__', _lt_from_gt),
|
| 181 |
+
('__ge__', _ge_from_gt),
|
| 182 |
+
('__le__', _le_from_gt)],
|
| 183 |
+
'__ge__': [('__le__', _le_from_ge),
|
| 184 |
+
('__gt__', _gt_from_ge),
|
| 185 |
+
('__lt__', _lt_from_ge)]
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
def total_ordering(cls):
|
| 189 |
+
"""Class decorator that fills in missing ordering methods"""
|
| 190 |
+
# Find user-defined comparisons (not those inherited from object).
|
| 191 |
+
roots = {op for op in _convert if getattr(cls, op, None) is not getattr(object, op, None)}
|
| 192 |
+
if not roots:
|
| 193 |
+
raise ValueError('must define at least one ordering operation: < > <= >=')
|
| 194 |
+
root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__
|
| 195 |
+
for opname, opfunc in _convert[root]:
|
| 196 |
+
if opname not in roots:
|
| 197 |
+
opfunc.__name__ = opname
|
| 198 |
+
setattr(cls, opname, opfunc)
|
| 199 |
+
return cls
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
################################################################################
|
| 203 |
+
### cmp_to_key() function converter
|
| 204 |
+
################################################################################
|
| 205 |
+
|
| 206 |
+
def cmp_to_key(mycmp):
|
| 207 |
+
"""Convert a cmp= function into a key= function"""
|
| 208 |
+
class K(object):
|
| 209 |
+
__slots__ = ['obj']
|
| 210 |
+
def __init__(self, obj):
|
| 211 |
+
self.obj = obj
|
| 212 |
+
def __lt__(self, other):
|
| 213 |
+
return mycmp(self.obj, other.obj) < 0
|
| 214 |
+
def __gt__(self, other):
|
| 215 |
+
return mycmp(self.obj, other.obj) > 0
|
| 216 |
+
def __eq__(self, other):
|
| 217 |
+
return mycmp(self.obj, other.obj) == 0
|
| 218 |
+
def __le__(self, other):
|
| 219 |
+
return mycmp(self.obj, other.obj) <= 0
|
| 220 |
+
def __ge__(self, other):
|
| 221 |
+
return mycmp(self.obj, other.obj) >= 0
|
| 222 |
+
__hash__ = None
|
| 223 |
+
return K
|
| 224 |
+
|
| 225 |
+
try:
|
| 226 |
+
from _functools import cmp_to_key
|
| 227 |
+
except ImportError:
|
| 228 |
+
pass
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
################################################################################
|
| 232 |
+
### reduce() sequence to a single item
|
| 233 |
+
################################################################################
|
| 234 |
+
|
| 235 |
+
_initial_missing = object()
|
| 236 |
+
|
| 237 |
+
def reduce(function, sequence, initial=_initial_missing):
|
| 238 |
+
"""
|
| 239 |
+
reduce(function, iterable[, initial]) -> value
|
| 240 |
+
|
| 241 |
+
Apply a function of two arguments cumulatively to the items of a sequence
|
| 242 |
+
or iterable, from left to right, so as to reduce the iterable to a single
|
| 243 |
+
value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
|
| 244 |
+
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
|
| 245 |
+
of the iterable in the calculation, and serves as a default when the
|
| 246 |
+
iterable is empty.
|
| 247 |
+
"""
|
| 248 |
+
|
| 249 |
+
it = iter(sequence)
|
| 250 |
+
|
| 251 |
+
if initial is _initial_missing:
|
| 252 |
+
try:
|
| 253 |
+
value = next(it)
|
| 254 |
+
except StopIteration:
|
| 255 |
+
raise TypeError(
|
| 256 |
+
"reduce() of empty iterable with no initial value") from None
|
| 257 |
+
else:
|
| 258 |
+
value = initial
|
| 259 |
+
|
| 260 |
+
for element in it:
|
| 261 |
+
value = function(value, element)
|
| 262 |
+
|
| 263 |
+
return value
|
| 264 |
+
|
| 265 |
+
try:
|
| 266 |
+
from _functools import reduce
|
| 267 |
+
except ImportError:
|
| 268 |
+
pass
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
################################################################################
|
| 272 |
+
### partial() argument application
|
| 273 |
+
################################################################################
|
| 274 |
+
|
| 275 |
+
# Purely functional, no descriptor behaviour
|
| 276 |
+
class partial:
|
| 277 |
+
"""New function with partial application of the given arguments
|
| 278 |
+
and keywords.
|
| 279 |
+
"""
|
| 280 |
+
|
| 281 |
+
__slots__ = "func", "args", "keywords", "__dict__", "__weakref__"
|
| 282 |
+
|
| 283 |
+
def __new__(cls, func, /, *args, **keywords):
|
| 284 |
+
if not callable(func):
|
| 285 |
+
raise TypeError("the first argument must be callable")
|
| 286 |
+
|
| 287 |
+
if hasattr(func, "func"):
|
| 288 |
+
args = func.args + args
|
| 289 |
+
keywords = {**func.keywords, **keywords}
|
| 290 |
+
func = func.func
|
| 291 |
+
|
| 292 |
+
self = super(partial, cls).__new__(cls)
|
| 293 |
+
|
| 294 |
+
self.func = func
|
| 295 |
+
self.args = args
|
| 296 |
+
self.keywords = keywords
|
| 297 |
+
return self
|
| 298 |
+
|
| 299 |
+
def __call__(self, /, *args, **keywords):
|
| 300 |
+
keywords = {**self.keywords, **keywords}
|
| 301 |
+
return self.func(*self.args, *args, **keywords)
|
| 302 |
+
|
| 303 |
+
@recursive_repr()
|
| 304 |
+
def __repr__(self):
|
| 305 |
+
qualname = type(self).__qualname__
|
| 306 |
+
args = [repr(self.func)]
|
| 307 |
+
args.extend(repr(x) for x in self.args)
|
| 308 |
+
args.extend(f"{k}={v!r}" for (k, v) in self.keywords.items())
|
| 309 |
+
if type(self).__module__ == "functools":
|
| 310 |
+
return f"functools.{qualname}({', '.join(args)})"
|
| 311 |
+
return f"{qualname}({', '.join(args)})"
|
| 312 |
+
|
| 313 |
+
def __reduce__(self):
|
| 314 |
+
return type(self), (self.func,), (self.func, self.args,
|
| 315 |
+
self.keywords or None, self.__dict__ or None)
|
| 316 |
+
|
| 317 |
+
def __setstate__(self, state):
|
| 318 |
+
if not isinstance(state, tuple):
|
| 319 |
+
raise TypeError("argument to __setstate__ must be a tuple")
|
| 320 |
+
if len(state) != 4:
|
| 321 |
+
raise TypeError(f"expected 4 items in state, got {len(state)}")
|
| 322 |
+
func, args, kwds, namespace = state
|
| 323 |
+
if (not callable(func) or not isinstance(args, tuple) or
|
| 324 |
+
(kwds is not None and not isinstance(kwds, dict)) or
|
| 325 |
+
(namespace is not None and not isinstance(namespace, dict))):
|
| 326 |
+
raise TypeError("invalid partial state")
|
| 327 |
+
|
| 328 |
+
args = tuple(args) # just in case it's a subclass
|
| 329 |
+
if kwds is None:
|
| 330 |
+
kwds = {}
|
| 331 |
+
elif type(kwds) is not dict: # XXX does it need to be *exactly* dict?
|
| 332 |
+
kwds = dict(kwds)
|
| 333 |
+
if namespace is None:
|
| 334 |
+
namespace = {}
|
| 335 |
+
|
| 336 |
+
self.__dict__ = namespace
|
| 337 |
+
self.func = func
|
| 338 |
+
self.args = args
|
| 339 |
+
self.keywords = kwds
|
| 340 |
+
|
| 341 |
+
try:
|
| 342 |
+
from _functools import partial
|
| 343 |
+
except ImportError:
|
| 344 |
+
pass
|
| 345 |
+
|
| 346 |
+
# Descriptor version
|
| 347 |
+
class partialmethod(object):
|
| 348 |
+
"""Method descriptor with partial application of the given arguments
|
| 349 |
+
and keywords.
|
| 350 |
+
|
| 351 |
+
Supports wrapping existing descriptors and handles non-descriptor
|
| 352 |
+
callables as instance methods.
|
| 353 |
+
"""
|
| 354 |
+
|
| 355 |
+
def __init__(self, func, /, *args, **keywords):
|
| 356 |
+
if not callable(func) and not hasattr(func, "__get__"):
|
| 357 |
+
raise TypeError("{!r} is not callable or a descriptor"
|
| 358 |
+
.format(func))
|
| 359 |
+
|
| 360 |
+
# func could be a descriptor like classmethod which isn't callable,
|
| 361 |
+
# so we can't inherit from partial (it verifies func is callable)
|
| 362 |
+
if isinstance(func, partialmethod):
|
| 363 |
+
# flattening is mandatory in order to place cls/self before all
|
| 364 |
+
# other arguments
|
| 365 |
+
# it's also more efficient since only one function will be called
|
| 366 |
+
self.func = func.func
|
| 367 |
+
self.args = func.args + args
|
| 368 |
+
self.keywords = {**func.keywords, **keywords}
|
| 369 |
+
else:
|
| 370 |
+
self.func = func
|
| 371 |
+
self.args = args
|
| 372 |
+
self.keywords = keywords
|
| 373 |
+
|
| 374 |
+
def __repr__(self):
|
| 375 |
+
args = ", ".join(map(repr, self.args))
|
| 376 |
+
keywords = ", ".join("{}={!r}".format(k, v)
|
| 377 |
+
for k, v in self.keywords.items())
|
| 378 |
+
format_string = "{module}.{cls}({func}, {args}, {keywords})"
|
| 379 |
+
return format_string.format(module=self.__class__.__module__,
|
| 380 |
+
cls=self.__class__.__qualname__,
|
| 381 |
+
func=self.func,
|
| 382 |
+
args=args,
|
| 383 |
+
keywords=keywords)
|
| 384 |
+
|
| 385 |
+
def _make_unbound_method(self):
|
| 386 |
+
def _method(cls_or_self, /, *args, **keywords):
|
| 387 |
+
keywords = {**self.keywords, **keywords}
|
| 388 |
+
return self.func(cls_or_self, *self.args, *args, **keywords)
|
| 389 |
+
_method.__isabstractmethod__ = self.__isabstractmethod__
|
| 390 |
+
_method._partialmethod = self
|
| 391 |
+
return _method
|
| 392 |
+
|
| 393 |
+
def __get__(self, obj, cls=None):
|
| 394 |
+
get = getattr(self.func, "__get__", None)
|
| 395 |
+
result = None
|
| 396 |
+
if get is not None:
|
| 397 |
+
new_func = get(obj, cls)
|
| 398 |
+
if new_func is not self.func:
|
| 399 |
+
# Assume __get__ returning something new indicates the
|
| 400 |
+
# creation of an appropriate callable
|
| 401 |
+
result = partial(new_func, *self.args, **self.keywords)
|
| 402 |
+
try:
|
| 403 |
+
result.__self__ = new_func.__self__
|
| 404 |
+
except AttributeError:
|
| 405 |
+
pass
|
| 406 |
+
if result is None:
|
| 407 |
+
# If the underlying descriptor didn't do anything, treat this
|
| 408 |
+
# like an instance method
|
| 409 |
+
result = self._make_unbound_method().__get__(obj, cls)
|
| 410 |
+
return result
|
| 411 |
+
|
| 412 |
+
@property
|
| 413 |
+
def __isabstractmethod__(self):
|
| 414 |
+
return getattr(self.func, "__isabstractmethod__", False)
|
| 415 |
+
|
| 416 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
# Helper functions
|
| 420 |
+
|
| 421 |
+
def _unwrap_partial(func):
|
| 422 |
+
while isinstance(func, partial):
|
| 423 |
+
func = func.func
|
| 424 |
+
return func
|
| 425 |
+
|
| 426 |
+
################################################################################
|
| 427 |
+
### LRU Cache function decorator
|
| 428 |
+
################################################################################
|
| 429 |
+
|
| 430 |
+
_CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"])
|
| 431 |
+
|
| 432 |
+
class _HashedSeq(list):
|
| 433 |
+
""" This class guarantees that hash() will be called no more than once
|
| 434 |
+
per element. This is important because the lru_cache() will hash
|
| 435 |
+
the key multiple times on a cache miss.
|
| 436 |
+
|
| 437 |
+
"""
|
| 438 |
+
|
| 439 |
+
__slots__ = 'hashvalue'
|
| 440 |
+
|
| 441 |
+
def __init__(self, tup, hash=hash):
|
| 442 |
+
self[:] = tup
|
| 443 |
+
self.hashvalue = hash(tup)
|
| 444 |
+
|
| 445 |
+
def __hash__(self):
|
| 446 |
+
return self.hashvalue
|
| 447 |
+
|
| 448 |
+
def _make_key(args, kwds, typed,
|
| 449 |
+
kwd_mark = (object(),),
|
| 450 |
+
fasttypes = {int, str},
|
| 451 |
+
tuple=tuple, type=type, len=len):
|
| 452 |
+
"""Make a cache key from optionally typed positional and keyword arguments
|
| 453 |
+
|
| 454 |
+
The key is constructed in a way that is flat as possible rather than
|
| 455 |
+
as a nested structure that would take more memory.
|
| 456 |
+
|
| 457 |
+
If there is only a single argument and its data type is known to cache
|
| 458 |
+
its hash value, then that argument is returned without a wrapper. This
|
| 459 |
+
saves space and improves lookup speed.
|
| 460 |
+
|
| 461 |
+
"""
|
| 462 |
+
# All of code below relies on kwds preserving the order input by the user.
|
| 463 |
+
# Formerly, we sorted() the kwds before looping. The new way is *much*
|
| 464 |
+
# faster; however, it means that f(x=1, y=2) will now be treated as a
|
| 465 |
+
# distinct call from f(y=2, x=1) which will be cached separately.
|
| 466 |
+
key = args
|
| 467 |
+
if kwds:
|
| 468 |
+
key += kwd_mark
|
| 469 |
+
for item in kwds.items():
|
| 470 |
+
key += item
|
| 471 |
+
if typed:
|
| 472 |
+
key += tuple(type(v) for v in args)
|
| 473 |
+
if kwds:
|
| 474 |
+
key += tuple(type(v) for v in kwds.values())
|
| 475 |
+
elif len(key) == 1 and type(key[0]) in fasttypes:
|
| 476 |
+
return key[0]
|
| 477 |
+
return _HashedSeq(key)
|
| 478 |
+
|
| 479 |
+
def lru_cache(maxsize=128, typed=False):
|
| 480 |
+
"""Least-recently-used cache decorator.
|
| 481 |
+
|
| 482 |
+
If *maxsize* is set to None, the LRU features are disabled and the cache
|
| 483 |
+
can grow without bound.
|
| 484 |
+
|
| 485 |
+
If *typed* is True, arguments of different types will be cached separately.
|
| 486 |
+
For example, f(3.0) and f(3) will be treated as distinct calls with
|
| 487 |
+
distinct results.
|
| 488 |
+
|
| 489 |
+
Arguments to the cached function must be hashable.
|
| 490 |
+
|
| 491 |
+
View the cache statistics named tuple (hits, misses, maxsize, currsize)
|
| 492 |
+
with f.cache_info(). Clear the cache and statistics with f.cache_clear().
|
| 493 |
+
Access the underlying function with f.__wrapped__.
|
| 494 |
+
|
| 495 |
+
See: https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)
|
| 496 |
+
|
| 497 |
+
"""
|
| 498 |
+
|
| 499 |
+
# Users should only access the lru_cache through its public API:
|
| 500 |
+
# cache_info, cache_clear, and f.__wrapped__
|
| 501 |
+
# The internals of the lru_cache are encapsulated for thread safety and
|
| 502 |
+
# to allow the implementation to change (including a possible C version).
|
| 503 |
+
|
| 504 |
+
if isinstance(maxsize, int):
|
| 505 |
+
# Negative maxsize is treated as 0
|
| 506 |
+
if maxsize < 0:
|
| 507 |
+
maxsize = 0
|
| 508 |
+
elif callable(maxsize) and isinstance(typed, bool):
|
| 509 |
+
# The user_function was passed in directly via the maxsize argument
|
| 510 |
+
user_function, maxsize = maxsize, 128
|
| 511 |
+
wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo)
|
| 512 |
+
wrapper.cache_parameters = lambda : {'maxsize': maxsize, 'typed': typed}
|
| 513 |
+
return update_wrapper(wrapper, user_function)
|
| 514 |
+
elif maxsize is not None:
|
| 515 |
+
raise TypeError(
|
| 516 |
+
'Expected first argument to be an integer, a callable, or None')
|
| 517 |
+
|
| 518 |
+
def decorating_function(user_function):
|
| 519 |
+
wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo)
|
| 520 |
+
wrapper.cache_parameters = lambda : {'maxsize': maxsize, 'typed': typed}
|
| 521 |
+
return update_wrapper(wrapper, user_function)
|
| 522 |
+
|
| 523 |
+
return decorating_function
|
| 524 |
+
|
| 525 |
+
def _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo):
|
| 526 |
+
# Constants shared by all lru cache instances:
|
| 527 |
+
sentinel = object() # unique object used to signal cache misses
|
| 528 |
+
make_key = _make_key # build a key from the function arguments
|
| 529 |
+
PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields
|
| 530 |
+
|
| 531 |
+
cache = {}
|
| 532 |
+
hits = misses = 0
|
| 533 |
+
full = False
|
| 534 |
+
cache_get = cache.get # bound method to lookup a key or return None
|
| 535 |
+
cache_len = cache.__len__ # get cache size without calling len()
|
| 536 |
+
lock = RLock() # because linkedlist updates aren't threadsafe
|
| 537 |
+
root = [] # root of the circular doubly linked list
|
| 538 |
+
root[:] = [root, root, None, None] # initialize by pointing to self
|
| 539 |
+
|
| 540 |
+
if maxsize == 0:
|
| 541 |
+
|
| 542 |
+
def wrapper(*args, **kwds):
|
| 543 |
+
# No caching -- just a statistics update
|
| 544 |
+
nonlocal misses
|
| 545 |
+
misses += 1
|
| 546 |
+
result = user_function(*args, **kwds)
|
| 547 |
+
return result
|
| 548 |
+
|
| 549 |
+
elif maxsize is None:
|
| 550 |
+
|
| 551 |
+
def wrapper(*args, **kwds):
|
| 552 |
+
# Simple caching without ordering or size limit
|
| 553 |
+
nonlocal hits, misses
|
| 554 |
+
key = make_key(args, kwds, typed)
|
| 555 |
+
result = cache_get(key, sentinel)
|
| 556 |
+
if result is not sentinel:
|
| 557 |
+
hits += 1
|
| 558 |
+
return result
|
| 559 |
+
misses += 1
|
| 560 |
+
result = user_function(*args, **kwds)
|
| 561 |
+
cache[key] = result
|
| 562 |
+
return result
|
| 563 |
+
|
| 564 |
+
else:
|
| 565 |
+
|
| 566 |
+
def wrapper(*args, **kwds):
|
| 567 |
+
# Size limited caching that tracks accesses by recency
|
| 568 |
+
nonlocal root, hits, misses, full
|
| 569 |
+
key = make_key(args, kwds, typed)
|
| 570 |
+
with lock:
|
| 571 |
+
link = cache_get(key)
|
| 572 |
+
if link is not None:
|
| 573 |
+
# Move the link to the front of the circular queue
|
| 574 |
+
link_prev, link_next, _key, result = link
|
| 575 |
+
link_prev[NEXT] = link_next
|
| 576 |
+
link_next[PREV] = link_prev
|
| 577 |
+
last = root[PREV]
|
| 578 |
+
last[NEXT] = root[PREV] = link
|
| 579 |
+
link[PREV] = last
|
| 580 |
+
link[NEXT] = root
|
| 581 |
+
hits += 1
|
| 582 |
+
return result
|
| 583 |
+
misses += 1
|
| 584 |
+
result = user_function(*args, **kwds)
|
| 585 |
+
with lock:
|
| 586 |
+
if key in cache:
|
| 587 |
+
# Getting here means that this same key was added to the
|
| 588 |
+
# cache while the lock was released. Since the link
|
| 589 |
+
# update is already done, we need only return the
|
| 590 |
+
# computed result and update the count of misses.
|
| 591 |
+
pass
|
| 592 |
+
elif full:
|
| 593 |
+
# Use the old root to store the new key and result.
|
| 594 |
+
oldroot = root
|
| 595 |
+
oldroot[KEY] = key
|
| 596 |
+
oldroot[RESULT] = result
|
| 597 |
+
# Empty the oldest link and make it the new root.
|
| 598 |
+
# Keep a reference to the old key and old result to
|
| 599 |
+
# prevent their ref counts from going to zero during the
|
| 600 |
+
# update. That will prevent potentially arbitrary object
|
| 601 |
+
# clean-up code (i.e. __del__) from running while we're
|
| 602 |
+
# still adjusting the links.
|
| 603 |
+
root = oldroot[NEXT]
|
| 604 |
+
oldkey = root[KEY]
|
| 605 |
+
oldresult = root[RESULT]
|
| 606 |
+
root[KEY] = root[RESULT] = None
|
| 607 |
+
# Now update the cache dictionary.
|
| 608 |
+
del cache[oldkey]
|
| 609 |
+
# Save the potentially reentrant cache[key] assignment
|
| 610 |
+
# for last, after the root and links have been put in
|
| 611 |
+
# a consistent state.
|
| 612 |
+
cache[key] = oldroot
|
| 613 |
+
else:
|
| 614 |
+
# Put result in a new link at the front of the queue.
|
| 615 |
+
last = root[PREV]
|
| 616 |
+
link = [last, root, key, result]
|
| 617 |
+
last[NEXT] = root[PREV] = cache[key] = link
|
| 618 |
+
# Use the cache_len bound method instead of the len() function
|
| 619 |
+
# which could potentially be wrapped in an lru_cache itself.
|
| 620 |
+
full = (cache_len() >= maxsize)
|
| 621 |
+
return result
|
| 622 |
+
|
| 623 |
+
def cache_info():
|
| 624 |
+
"""Report cache statistics"""
|
| 625 |
+
with lock:
|
| 626 |
+
return _CacheInfo(hits, misses, maxsize, cache_len())
|
| 627 |
+
|
| 628 |
+
def cache_clear():
|
| 629 |
+
"""Clear the cache and cache statistics"""
|
| 630 |
+
nonlocal hits, misses, full
|
| 631 |
+
with lock:
|
| 632 |
+
cache.clear()
|
| 633 |
+
root[:] = [root, root, None, None]
|
| 634 |
+
hits = misses = 0
|
| 635 |
+
full = False
|
| 636 |
+
|
| 637 |
+
wrapper.cache_info = cache_info
|
| 638 |
+
wrapper.cache_clear = cache_clear
|
| 639 |
+
return wrapper
|
| 640 |
+
|
| 641 |
+
try:
|
| 642 |
+
from _functools import _lru_cache_wrapper
|
| 643 |
+
except ImportError:
|
| 644 |
+
pass
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
################################################################################
|
| 648 |
+
### cache -- simplified access to the infinity cache
|
| 649 |
+
################################################################################
|
| 650 |
+
|
| 651 |
+
def cache(user_function, /):
|
| 652 |
+
'Simple lightweight unbounded cache. Sometimes called "memoize".'
|
| 653 |
+
return lru_cache(maxsize=None)(user_function)
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
################################################################################
|
| 657 |
+
### singledispatch() - single-dispatch generic function decorator
|
| 658 |
+
################################################################################
|
| 659 |
+
|
| 660 |
+
def _c3_merge(sequences):
|
| 661 |
+
"""Merges MROs in *sequences* to a single MRO using the C3 algorithm.
|
| 662 |
+
|
| 663 |
+
Adapted from https://www.python.org/download/releases/2.3/mro/.
|
| 664 |
+
|
| 665 |
+
"""
|
| 666 |
+
result = []
|
| 667 |
+
while True:
|
| 668 |
+
sequences = [s for s in sequences if s] # purge empty sequences
|
| 669 |
+
if not sequences:
|
| 670 |
+
return result
|
| 671 |
+
for s1 in sequences: # find merge candidates among seq heads
|
| 672 |
+
candidate = s1[0]
|
| 673 |
+
for s2 in sequences:
|
| 674 |
+
if candidate in s2[1:]:
|
| 675 |
+
candidate = None
|
| 676 |
+
break # reject the current head, it appears later
|
| 677 |
+
else:
|
| 678 |
+
break
|
| 679 |
+
if candidate is None:
|
| 680 |
+
raise RuntimeError("Inconsistent hierarchy")
|
| 681 |
+
result.append(candidate)
|
| 682 |
+
# remove the chosen candidate
|
| 683 |
+
for seq in sequences:
|
| 684 |
+
if seq[0] == candidate:
|
| 685 |
+
del seq[0]
|
| 686 |
+
|
| 687 |
+
def _c3_mro(cls, abcs=None):
|
| 688 |
+
"""Computes the method resolution order using extended C3 linearization.
|
| 689 |
+
|
| 690 |
+
If no *abcs* are given, the algorithm works exactly like the built-in C3
|
| 691 |
+
linearization used for method resolution.
|
| 692 |
+
|
| 693 |
+
If given, *abcs* is a list of abstract base classes that should be inserted
|
| 694 |
+
into the resulting MRO. Unrelated ABCs are ignored and don't end up in the
|
| 695 |
+
result. The algorithm inserts ABCs where their functionality is introduced,
|
| 696 |
+
i.e. issubclass(cls, abc) returns True for the class itself but returns
|
| 697 |
+
False for all its direct base classes. Implicit ABCs for a given class
|
| 698 |
+
(either registered or inferred from the presence of a special method like
|
| 699 |
+
__len__) are inserted directly after the last ABC explicitly listed in the
|
| 700 |
+
MRO of said class. If two implicit ABCs end up next to each other in the
|
| 701 |
+
resulting MRO, their ordering depends on the order of types in *abcs*.
|
| 702 |
+
|
| 703 |
+
"""
|
| 704 |
+
for i, base in enumerate(reversed(cls.__bases__)):
|
| 705 |
+
if hasattr(base, '__abstractmethods__'):
|
| 706 |
+
boundary = len(cls.__bases__) - i
|
| 707 |
+
break # Bases up to the last explicit ABC are considered first.
|
| 708 |
+
else:
|
| 709 |
+
boundary = 0
|
| 710 |
+
abcs = list(abcs) if abcs else []
|
| 711 |
+
explicit_bases = list(cls.__bases__[:boundary])
|
| 712 |
+
abstract_bases = []
|
| 713 |
+
other_bases = list(cls.__bases__[boundary:])
|
| 714 |
+
for base in abcs:
|
| 715 |
+
if issubclass(cls, base) and not any(
|
| 716 |
+
issubclass(b, base) for b in cls.__bases__
|
| 717 |
+
):
|
| 718 |
+
# If *cls* is the class that introduces behaviour described by
|
| 719 |
+
# an ABC *base*, insert said ABC to its MRO.
|
| 720 |
+
abstract_bases.append(base)
|
| 721 |
+
for base in abstract_bases:
|
| 722 |
+
abcs.remove(base)
|
| 723 |
+
explicit_c3_mros = [_c3_mro(base, abcs=abcs) for base in explicit_bases]
|
| 724 |
+
abstract_c3_mros = [_c3_mro(base, abcs=abcs) for base in abstract_bases]
|
| 725 |
+
other_c3_mros = [_c3_mro(base, abcs=abcs) for base in other_bases]
|
| 726 |
+
return _c3_merge(
|
| 727 |
+
[[cls]] +
|
| 728 |
+
explicit_c3_mros + abstract_c3_mros + other_c3_mros +
|
| 729 |
+
[explicit_bases] + [abstract_bases] + [other_bases]
|
| 730 |
+
)
|
| 731 |
+
|
| 732 |
+
def _compose_mro(cls, types):
|
| 733 |
+
"""Calculates the method resolution order for a given class *cls*.
|
| 734 |
+
|
| 735 |
+
Includes relevant abstract base classes (with their respective bases) from
|
| 736 |
+
the *types* iterable. Uses a modified C3 linearization algorithm.
|
| 737 |
+
|
| 738 |
+
"""
|
| 739 |
+
bases = set(cls.__mro__)
|
| 740 |
+
# Remove entries which are already present in the __mro__ or unrelated.
|
| 741 |
+
def is_related(typ):
|
| 742 |
+
return (typ not in bases and hasattr(typ, '__mro__')
|
| 743 |
+
and not isinstance(typ, GenericAlias)
|
| 744 |
+
and issubclass(cls, typ))
|
| 745 |
+
types = [n for n in types if is_related(n)]
|
| 746 |
+
# Remove entries which are strict bases of other entries (they will end up
|
| 747 |
+
# in the MRO anyway.
|
| 748 |
+
def is_strict_base(typ):
|
| 749 |
+
for other in types:
|
| 750 |
+
if typ != other and typ in other.__mro__:
|
| 751 |
+
return True
|
| 752 |
+
return False
|
| 753 |
+
types = [n for n in types if not is_strict_base(n)]
|
| 754 |
+
# Subclasses of the ABCs in *types* which are also implemented by
|
| 755 |
+
# *cls* can be used to stabilize ABC ordering.
|
| 756 |
+
type_set = set(types)
|
| 757 |
+
mro = []
|
| 758 |
+
for typ in types:
|
| 759 |
+
found = []
|
| 760 |
+
for sub in typ.__subclasses__():
|
| 761 |
+
if sub not in bases and issubclass(cls, sub):
|
| 762 |
+
found.append([s for s in sub.__mro__ if s in type_set])
|
| 763 |
+
if not found:
|
| 764 |
+
mro.append(typ)
|
| 765 |
+
continue
|
| 766 |
+
# Favor subclasses with the biggest number of useful bases
|
| 767 |
+
found.sort(key=len, reverse=True)
|
| 768 |
+
for sub in found:
|
| 769 |
+
for subcls in sub:
|
| 770 |
+
if subcls not in mro:
|
| 771 |
+
mro.append(subcls)
|
| 772 |
+
return _c3_mro(cls, abcs=mro)
|
| 773 |
+
|
| 774 |
+
def _find_impl(cls, registry):
|
| 775 |
+
"""Returns the best matching implementation from *registry* for type *cls*.
|
| 776 |
+
|
| 777 |
+
Where there is no registered implementation for a specific type, its method
|
| 778 |
+
resolution order is used to find a more generic implementation.
|
| 779 |
+
|
| 780 |
+
Note: if *registry* does not contain an implementation for the base
|
| 781 |
+
*object* type, this function may return None.
|
| 782 |
+
|
| 783 |
+
"""
|
| 784 |
+
mro = _compose_mro(cls, registry.keys())
|
| 785 |
+
match = None
|
| 786 |
+
for t in mro:
|
| 787 |
+
if match is not None:
|
| 788 |
+
# If *match* is an implicit ABC but there is another unrelated,
|
| 789 |
+
# equally matching implicit ABC, refuse the temptation to guess.
|
| 790 |
+
if (t in registry and t not in cls.__mro__
|
| 791 |
+
and match not in cls.__mro__
|
| 792 |
+
and not issubclass(match, t)):
|
| 793 |
+
raise RuntimeError("Ambiguous dispatch: {} or {}".format(
|
| 794 |
+
match, t))
|
| 795 |
+
break
|
| 796 |
+
if t in registry:
|
| 797 |
+
match = t
|
| 798 |
+
return registry.get(match)
|
| 799 |
+
|
| 800 |
+
def singledispatch(func):
|
| 801 |
+
"""Single-dispatch generic function decorator.
|
| 802 |
+
|
| 803 |
+
Transforms a function into a generic function, which can have different
|
| 804 |
+
behaviours depending upon the type of its first argument. The decorated
|
| 805 |
+
function acts as the default implementation, and additional
|
| 806 |
+
implementations can be registered using the register() attribute of the
|
| 807 |
+
generic function.
|
| 808 |
+
"""
|
| 809 |
+
# There are many programs that use functools without singledispatch, so we
|
| 810 |
+
# trade-off making singledispatch marginally slower for the benefit of
|
| 811 |
+
# making start-up of such applications slightly faster.
|
| 812 |
+
import types, weakref
|
| 813 |
+
|
| 814 |
+
registry = {}
|
| 815 |
+
dispatch_cache = weakref.WeakKeyDictionary()
|
| 816 |
+
cache_token = None
|
| 817 |
+
|
| 818 |
+
def dispatch(cls):
|
| 819 |
+
"""generic_func.dispatch(cls) -> <function implementation>
|
| 820 |
+
|
| 821 |
+
Runs the dispatch algorithm to return the best available implementation
|
| 822 |
+
for the given *cls* registered on *generic_func*.
|
| 823 |
+
|
| 824 |
+
"""
|
| 825 |
+
nonlocal cache_token
|
| 826 |
+
if cache_token is not None:
|
| 827 |
+
current_token = get_cache_token()
|
| 828 |
+
if cache_token != current_token:
|
| 829 |
+
dispatch_cache.clear()
|
| 830 |
+
cache_token = current_token
|
| 831 |
+
try:
|
| 832 |
+
impl = dispatch_cache[cls]
|
| 833 |
+
except KeyError:
|
| 834 |
+
try:
|
| 835 |
+
impl = registry[cls]
|
| 836 |
+
except KeyError:
|
| 837 |
+
impl = _find_impl(cls, registry)
|
| 838 |
+
dispatch_cache[cls] = impl
|
| 839 |
+
return impl
|
| 840 |
+
|
| 841 |
+
def _is_valid_dispatch_type(cls):
|
| 842 |
+
return isinstance(cls, type) and not isinstance(cls, GenericAlias)
|
| 843 |
+
|
| 844 |
+
def register(cls, func=None):
|
| 845 |
+
"""generic_func.register(cls, func) -> func
|
| 846 |
+
|
| 847 |
+
Registers a new implementation for the given *cls* on a *generic_func*.
|
| 848 |
+
|
| 849 |
+
"""
|
| 850 |
+
nonlocal cache_token
|
| 851 |
+
if _is_valid_dispatch_type(cls):
|
| 852 |
+
if func is None:
|
| 853 |
+
return lambda f: register(cls, f)
|
| 854 |
+
else:
|
| 855 |
+
if func is not None:
|
| 856 |
+
raise TypeError(
|
| 857 |
+
f"Invalid first argument to `register()`. "
|
| 858 |
+
f"{cls!r} is not a class."
|
| 859 |
+
)
|
| 860 |
+
ann = getattr(cls, '__annotations__', {})
|
| 861 |
+
if not ann:
|
| 862 |
+
raise TypeError(
|
| 863 |
+
f"Invalid first argument to `register()`: {cls!r}. "
|
| 864 |
+
f"Use either `@register(some_class)` or plain `@register` "
|
| 865 |
+
f"on an annotated function."
|
| 866 |
+
)
|
| 867 |
+
func = cls
|
| 868 |
+
|
| 869 |
+
# only import typing if annotation parsing is necessary
|
| 870 |
+
from typing import get_type_hints
|
| 871 |
+
argname, cls = next(iter(get_type_hints(func).items()))
|
| 872 |
+
if not _is_valid_dispatch_type(cls):
|
| 873 |
+
raise TypeError(
|
| 874 |
+
f"Invalid annotation for {argname!r}. "
|
| 875 |
+
f"{cls!r} is not a class."
|
| 876 |
+
)
|
| 877 |
+
|
| 878 |
+
registry[cls] = func
|
| 879 |
+
if cache_token is None and hasattr(cls, '__abstractmethods__'):
|
| 880 |
+
cache_token = get_cache_token()
|
| 881 |
+
dispatch_cache.clear()
|
| 882 |
+
return func
|
| 883 |
+
|
| 884 |
+
def wrapper(*args, **kw):
|
| 885 |
+
if not args:
|
| 886 |
+
raise TypeError(f'{funcname} requires at least '
|
| 887 |
+
'1 positional argument')
|
| 888 |
+
|
| 889 |
+
return dispatch(args[0].__class__)(*args, **kw)
|
| 890 |
+
|
| 891 |
+
funcname = getattr(func, '__name__', 'singledispatch function')
|
| 892 |
+
registry[object] = func
|
| 893 |
+
wrapper.register = register
|
| 894 |
+
wrapper.dispatch = dispatch
|
| 895 |
+
wrapper.registry = types.MappingProxyType(registry)
|
| 896 |
+
wrapper._clear_cache = dispatch_cache.clear
|
| 897 |
+
update_wrapper(wrapper, func)
|
| 898 |
+
return wrapper
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
# Descriptor version
|
| 902 |
+
class singledispatchmethod:
|
| 903 |
+
"""Single-dispatch generic method descriptor.
|
| 904 |
+
|
| 905 |
+
Supports wrapping existing descriptors and handles non-descriptor
|
| 906 |
+
callables as instance methods.
|
| 907 |
+
"""
|
| 908 |
+
|
| 909 |
+
def __init__(self, func):
|
| 910 |
+
if not callable(func) and not hasattr(func, "__get__"):
|
| 911 |
+
raise TypeError(f"{func!r} is not callable or a descriptor")
|
| 912 |
+
|
| 913 |
+
self.dispatcher = singledispatch(func)
|
| 914 |
+
self.func = func
|
| 915 |
+
|
| 916 |
+
def register(self, cls, method=None):
|
| 917 |
+
"""generic_method.register(cls, func) -> func
|
| 918 |
+
|
| 919 |
+
Registers a new implementation for the given *cls* on a *generic_method*.
|
| 920 |
+
"""
|
| 921 |
+
return self.dispatcher.register(cls, func=method)
|
| 922 |
+
|
| 923 |
+
def __get__(self, obj, cls=None):
|
| 924 |
+
def _method(*args, **kwargs):
|
| 925 |
+
method = self.dispatcher.dispatch(args[0].__class__)
|
| 926 |
+
return method.__get__(obj, cls)(*args, **kwargs)
|
| 927 |
+
|
| 928 |
+
_method.__isabstractmethod__ = self.__isabstractmethod__
|
| 929 |
+
_method.register = self.register
|
| 930 |
+
update_wrapper(_method, self.func)
|
| 931 |
+
return _method
|
| 932 |
+
|
| 933 |
+
@property
|
| 934 |
+
def __isabstractmethod__(self):
|
| 935 |
+
return getattr(self.func, '__isabstractmethod__', False)
|
| 936 |
+
|
| 937 |
+
|
| 938 |
+
################################################################################
|
| 939 |
+
### cached_property() - computed once per instance, cached as attribute
|
| 940 |
+
################################################################################
|
| 941 |
+
|
| 942 |
+
_NOT_FOUND = object()
|
| 943 |
+
|
| 944 |
+
|
| 945 |
+
class cached_property:
|
| 946 |
+
def __init__(self, func):
|
| 947 |
+
self.func = func
|
| 948 |
+
self.attrname = None
|
| 949 |
+
self.__doc__ = func.__doc__
|
| 950 |
+
self.lock = RLock()
|
| 951 |
+
|
| 952 |
+
def __set_name__(self, owner, name):
|
| 953 |
+
if self.attrname is None:
|
| 954 |
+
self.attrname = name
|
| 955 |
+
elif name != self.attrname:
|
| 956 |
+
raise TypeError(
|
| 957 |
+
"Cannot assign the same cached_property to two different names "
|
| 958 |
+
f"({self.attrname!r} and {name!r})."
|
| 959 |
+
)
|
| 960 |
+
|
| 961 |
+
def __get__(self, instance, owner=None):
|
| 962 |
+
if instance is None:
|
| 963 |
+
return self
|
| 964 |
+
if self.attrname is None:
|
| 965 |
+
raise TypeError(
|
| 966 |
+
"Cannot use cached_property instance without calling __set_name__ on it.")
|
| 967 |
+
try:
|
| 968 |
+
cache = instance.__dict__
|
| 969 |
+
except AttributeError: # not all objects have __dict__ (e.g. class defines slots)
|
| 970 |
+
msg = (
|
| 971 |
+
f"No '__dict__' attribute on {type(instance).__name__!r} "
|
| 972 |
+
f"instance to cache {self.attrname!r} property."
|
| 973 |
+
)
|
| 974 |
+
raise TypeError(msg) from None
|
| 975 |
+
val = cache.get(self.attrname, _NOT_FOUND)
|
| 976 |
+
if val is _NOT_FOUND:
|
| 977 |
+
with self.lock:
|
| 978 |
+
# check if another thread filled cache while we awaited lock
|
| 979 |
+
val = cache.get(self.attrname, _NOT_FOUND)
|
| 980 |
+
if val is _NOT_FOUND:
|
| 981 |
+
val = self.func(instance)
|
| 982 |
+
try:
|
| 983 |
+
cache[self.attrname] = val
|
| 984 |
+
except TypeError:
|
| 985 |
+
msg = (
|
| 986 |
+
f"The '__dict__' attribute on {type(instance).__name__!r} instance "
|
| 987 |
+
f"does not support item assignment for caching {self.attrname!r} property."
|
| 988 |
+
)
|
| 989 |
+
raise TypeError(msg) from None
|
| 990 |
+
return val
|
| 991 |
+
|
| 992 |
+
__class_getitem__ = classmethod(GenericAlias)
|
shared/package-files/17/170374feae76894ea274b359357a34d3680f369570ffdc6bc4b89f1672bfb2cc/preview.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from os.path import join
|
| 3 |
+
import shutil
|
| 4 |
+
import tempfile
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
from subprocess import STDOUT, CalledProcessError, check_output
|
| 8 |
+
except ImportError:
|
| 9 |
+
pass
|
| 10 |
+
|
| 11 |
+
from sympy.utilities.decorator import doctest_depends_on
|
| 12 |
+
from sympy.utilities.misc import debug
|
| 13 |
+
from .latex import latex
|
| 14 |
+
|
| 15 |
+
__doctest_requires__ = {('preview',): ['pyglet']}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _check_output_no_window(*args, **kwargs):
|
| 19 |
+
# Avoid showing a cmd.exe window when running this
|
| 20 |
+
# on Windows
|
| 21 |
+
if os.name == 'nt':
|
| 22 |
+
creation_flag = 0x08000000 # CREATE_NO_WINDOW
|
| 23 |
+
else:
|
| 24 |
+
creation_flag = 0 # Default value
|
| 25 |
+
return check_output(*args, creationflags=creation_flag, **kwargs)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def system_default_viewer(fname, fmt):
|
| 29 |
+
""" Open fname with the default system viewer.
|
| 30 |
+
|
| 31 |
+
In practice, it is impossible for python to know when the system viewer is
|
| 32 |
+
done. For this reason, we ensure the passed file will not be deleted under
|
| 33 |
+
it, and this function does not attempt to block.
|
| 34 |
+
"""
|
| 35 |
+
# copy to a new temporary file that will not be deleted
|
| 36 |
+
with tempfile.NamedTemporaryFile(prefix='sympy-preview-',
|
| 37 |
+
suffix=os.path.splitext(fname)[1],
|
| 38 |
+
delete=False) as temp_f:
|
| 39 |
+
with open(fname, 'rb') as f:
|
| 40 |
+
shutil.copyfileobj(f, temp_f)
|
| 41 |
+
|
| 42 |
+
import platform
|
| 43 |
+
if platform.system() == 'Darwin':
|
| 44 |
+
import subprocess
|
| 45 |
+
subprocess.call(('open', temp_f.name))
|
| 46 |
+
elif platform.system() == 'Windows':
|
| 47 |
+
os.startfile(temp_f.name)
|
| 48 |
+
else:
|
| 49 |
+
import subprocess
|
| 50 |
+
subprocess.call(('xdg-open', temp_f.name))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def pyglet_viewer(fname, fmt):
|
| 54 |
+
try:
|
| 55 |
+
from pyglet import window, image, gl
|
| 56 |
+
from pyglet.window import key
|
| 57 |
+
from pyglet.image.codecs import ImageDecodeException
|
| 58 |
+
except ImportError:
|
| 59 |
+
raise ImportError("pyglet is required for preview.\n visit https://pyglet.org/")
|
| 60 |
+
|
| 61 |
+
try:
|
| 62 |
+
img = image.load(fname)
|
| 63 |
+
except ImageDecodeException:
|
| 64 |
+
raise ValueError("pyglet preview does not work for '{}' files.".format(fmt))
|
| 65 |
+
|
| 66 |
+
offset = 25
|
| 67 |
+
|
| 68 |
+
config = gl.Config(double_buffer=False)
|
| 69 |
+
win = window.Window(
|
| 70 |
+
width=img.width + 2*offset,
|
| 71 |
+
height=img.height + 2*offset,
|
| 72 |
+
caption="SymPy",
|
| 73 |
+
resizable=False,
|
| 74 |
+
config=config
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
win.set_vsync(False)
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
def on_close():
|
| 81 |
+
win.has_exit = True
|
| 82 |
+
|
| 83 |
+
win.on_close = on_close
|
| 84 |
+
|
| 85 |
+
def on_key_press(symbol, modifiers):
|
| 86 |
+
if symbol in [key.Q, key.ESCAPE]:
|
| 87 |
+
on_close()
|
| 88 |
+
|
| 89 |
+
win.on_key_press = on_key_press
|
| 90 |
+
|
| 91 |
+
def on_expose():
|
| 92 |
+
gl.glClearColor(1.0, 1.0, 1.0, 1.0)
|
| 93 |
+
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
|
| 94 |
+
|
| 95 |
+
img.blit(
|
| 96 |
+
(win.width - img.width) / 2,
|
| 97 |
+
(win.height - img.height) / 2
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
win.on_expose = on_expose
|
| 101 |
+
|
| 102 |
+
while not win.has_exit:
|
| 103 |
+
win.dispatch_events()
|
| 104 |
+
win.flip()
|
| 105 |
+
except KeyboardInterrupt:
|
| 106 |
+
pass
|
| 107 |
+
|
| 108 |
+
win.close()
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _get_latex_main(expr, *, preamble=None, packages=(), extra_preamble=None,
|
| 112 |
+
euler=True, fontsize=None, **latex_settings):
|
| 113 |
+
"""
|
| 114 |
+
Generate string of a LaTeX document rendering ``expr``.
|
| 115 |
+
"""
|
| 116 |
+
if preamble is None:
|
| 117 |
+
actual_packages = packages + ("amsmath", "amsfonts")
|
| 118 |
+
if euler:
|
| 119 |
+
actual_packages += ("euler",)
|
| 120 |
+
package_includes = "\n" + "\n".join(["\\usepackage{%s}" % p
|
| 121 |
+
for p in actual_packages])
|
| 122 |
+
if extra_preamble:
|
| 123 |
+
package_includes += extra_preamble
|
| 124 |
+
|
| 125 |
+
if not fontsize:
|
| 126 |
+
fontsize = "12pt"
|
| 127 |
+
elif isinstance(fontsize, int):
|
| 128 |
+
fontsize = "{}pt".format(fontsize)
|
| 129 |
+
preamble = r"""\documentclass[varwidth,%s]{standalone}
|
| 130 |
+
%s
|
| 131 |
+
|
| 132 |
+
\begin{document}
|
| 133 |
+
""" % (fontsize, package_includes)
|
| 134 |
+
else:
|
| 135 |
+
if packages or extra_preamble:
|
| 136 |
+
raise ValueError("The \"packages\" or \"extra_preamble\" keywords"
|
| 137 |
+
"must not be set if a "
|
| 138 |
+
"custom LaTeX preamble was specified")
|
| 139 |
+
|
| 140 |
+
if isinstance(expr, str):
|
| 141 |
+
latex_string = expr
|
| 142 |
+
else:
|
| 143 |
+
latex_string = ('$\\displaystyle ' +
|
| 144 |
+
latex(expr, mode='plain', **latex_settings) +
|
| 145 |
+
'$')
|
| 146 |
+
|
| 147 |
+
return preamble + '\n' + latex_string + '\n\n' + r"\end{document}"
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',),
|
| 151 |
+
disable_viewers=('evince', 'gimp', 'superior-dvi-viewer'))
|
| 152 |
+
def preview(expr, output='png', viewer=None, euler=True, packages=(),
|
| 153 |
+
filename=None, outputbuffer=None, preamble=None, dvioptions=None,
|
| 154 |
+
outputTexFile=None, extra_preamble=None, fontsize=None,
|
| 155 |
+
**latex_settings):
|
| 156 |
+
r"""
|
| 157 |
+
View expression or LaTeX markup in PNG, DVI, PostScript or PDF form.
|
| 158 |
+
|
| 159 |
+
If the expr argument is an expression, it will be exported to LaTeX and
|
| 160 |
+
then compiled using the available TeX distribution. The first argument,
|
| 161 |
+
'expr', may also be a LaTeX string. The function will then run the
|
| 162 |
+
appropriate viewer for the given output format or use the user defined
|
| 163 |
+
one. By default png output is generated.
|
| 164 |
+
|
| 165 |
+
By default pretty Euler fonts are used for typesetting (they were used to
|
| 166 |
+
typeset the well known "Concrete Mathematics" book). For that to work, you
|
| 167 |
+
need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the
|
| 168 |
+
texlive-fonts-extra package). If you prefer default AMS fonts or your
|
| 169 |
+
system lacks 'eulervm' LaTeX package then unset the 'euler' keyword
|
| 170 |
+
argument.
|
| 171 |
+
|
| 172 |
+
To use viewer auto-detection, lets say for 'png' output, issue
|
| 173 |
+
|
| 174 |
+
>>> from sympy import symbols, preview, Symbol
|
| 175 |
+
>>> x, y = symbols("x,y")
|
| 176 |
+
|
| 177 |
+
>>> preview(x + y, output='png')
|
| 178 |
+
|
| 179 |
+
This will choose 'pyglet' by default. To select a different one, do
|
| 180 |
+
|
| 181 |
+
>>> preview(x + y, output='png', viewer='gimp')
|
| 182 |
+
|
| 183 |
+
The 'png' format is considered special. For all other formats the rules
|
| 184 |
+
are slightly different. As an example we will take 'dvi' output format. If
|
| 185 |
+
you would run
|
| 186 |
+
|
| 187 |
+
>>> preview(x + y, output='dvi')
|
| 188 |
+
|
| 189 |
+
then 'view' will look for available 'dvi' viewers on your system
|
| 190 |
+
(predefined in the function, so it will try evince, first, then kdvi and
|
| 191 |
+
xdvi). If nothing is found, it will fall back to using a system file
|
| 192 |
+
association (via ``open`` and ``xdg-open``). To always use your system file
|
| 193 |
+
association without searching for the above readers, use
|
| 194 |
+
|
| 195 |
+
>>> from sympy.printing.preview import system_default_viewer
|
| 196 |
+
>>> preview(x + y, output='dvi', viewer=system_default_viewer)
|
| 197 |
+
|
| 198 |
+
If this still does not find the viewer you want, it can be set explicitly.
|
| 199 |
+
|
| 200 |
+
>>> preview(x + y, output='dvi', viewer='superior-dvi-viewer')
|
| 201 |
+
|
| 202 |
+
This will skip auto-detection and will run user specified
|
| 203 |
+
'superior-dvi-viewer'. If ``view`` fails to find it on your system it will
|
| 204 |
+
gracefully raise an exception.
|
| 205 |
+
|
| 206 |
+
You may also enter ``'file'`` for the viewer argument. Doing so will cause
|
| 207 |
+
this function to return a file object in read-only mode, if ``filename``
|
| 208 |
+
is unset. However, if it was set, then 'preview' writes the generated
|
| 209 |
+
file to this filename instead.
|
| 210 |
+
|
| 211 |
+
There is also support for writing to a ``io.BytesIO`` like object, which
|
| 212 |
+
needs to be passed to the ``outputbuffer`` argument.
|
| 213 |
+
|
| 214 |
+
>>> from io import BytesIO
|
| 215 |
+
>>> obj = BytesIO()
|
| 216 |
+
>>> preview(x + y, output='png', viewer='BytesIO',
|
| 217 |
+
... outputbuffer=obj)
|
| 218 |
+
|
| 219 |
+
The LaTeX preamble can be customized by setting the 'preamble' keyword
|
| 220 |
+
argument. This can be used, e.g., to set a different font size, use a
|
| 221 |
+
custom documentclass or import certain set of LaTeX packages.
|
| 222 |
+
|
| 223 |
+
>>> preamble = "\\documentclass[10pt]{article}\n" \
|
| 224 |
+
... "\\usepackage{amsmath,amsfonts}\\begin{document}"
|
| 225 |
+
>>> preview(x + y, output='png', preamble=preamble)
|
| 226 |
+
|
| 227 |
+
It is also possible to use the standard preamble and provide additional
|
| 228 |
+
information to the preamble using the ``extra_preamble`` keyword argument.
|
| 229 |
+
|
| 230 |
+
>>> from sympy import sin
|
| 231 |
+
>>> extra_preamble = "\\renewcommand{\\sin}{\\cos}"
|
| 232 |
+
>>> preview(sin(x), output='png', extra_preamble=extra_preamble)
|
| 233 |
+
|
| 234 |
+
If the value of 'output' is different from 'dvi' then command line
|
| 235 |
+
options can be set ('dvioptions' argument) for the execution of the
|
| 236 |
+
'dvi'+output conversion tool. These options have to be in the form of a
|
| 237 |
+
list of strings (see ``subprocess.Popen``).
|
| 238 |
+
|
| 239 |
+
Additional keyword args will be passed to the :func:`~sympy.printing.latex.latex` call,
|
| 240 |
+
e.g., the ``symbol_names`` flag.
|
| 241 |
+
|
| 242 |
+
>>> phidd = Symbol('phidd')
|
| 243 |
+
>>> preview(phidd, symbol_names={phidd: r'\ddot{\varphi}'})
|
| 244 |
+
|
| 245 |
+
For post-processing the generated TeX File can be written to a file by
|
| 246 |
+
passing the desired filename to the 'outputTexFile' keyword
|
| 247 |
+
argument. To write the TeX code to a file named
|
| 248 |
+
``"sample.tex"`` and run the default png viewer to display the resulting
|
| 249 |
+
bitmap, do
|
| 250 |
+
|
| 251 |
+
>>> preview(x + y, outputTexFile="sample.tex")
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
"""
|
| 255 |
+
# pyglet is the default for png
|
| 256 |
+
if viewer is None and output == "png":
|
| 257 |
+
try:
|
| 258 |
+
import pyglet # noqa: F401
|
| 259 |
+
except ImportError:
|
| 260 |
+
pass
|
| 261 |
+
else:
|
| 262 |
+
viewer = pyglet_viewer
|
| 263 |
+
|
| 264 |
+
# look up a known application
|
| 265 |
+
if viewer is None:
|
| 266 |
+
# sorted in order from most pretty to most ugly
|
| 267 |
+
# very discussable, but indeed 'gv' looks awful :)
|
| 268 |
+
candidates = {
|
| 269 |
+
"dvi": [ "evince", "okular", "kdvi", "xdvi" ],
|
| 270 |
+
"ps": [ "evince", "okular", "gsview", "gv" ],
|
| 271 |
+
"pdf": [ "evince", "okular", "kpdf", "acroread", "xpdf", "gv" ],
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
for candidate in candidates.get(output, []):
|
| 275 |
+
path = shutil.which(candidate)
|
| 276 |
+
if path is not None:
|
| 277 |
+
viewer = path
|
| 278 |
+
break
|
| 279 |
+
|
| 280 |
+
# otherwise, use the system default for file association
|
| 281 |
+
if viewer is None:
|
| 282 |
+
viewer = system_default_viewer
|
| 283 |
+
|
| 284 |
+
if viewer == "file":
|
| 285 |
+
if filename is None:
|
| 286 |
+
raise ValueError("filename has to be specified if viewer=\"file\"")
|
| 287 |
+
elif viewer == "BytesIO":
|
| 288 |
+
if outputbuffer is None:
|
| 289 |
+
raise ValueError("outputbuffer has to be a BytesIO "
|
| 290 |
+
"compatible object if viewer=\"BytesIO\"")
|
| 291 |
+
elif not callable(viewer) and not shutil.which(viewer):
|
| 292 |
+
raise OSError("Unrecognized viewer: %s" % viewer)
|
| 293 |
+
|
| 294 |
+
latex_main = _get_latex_main(expr, preamble=preamble, packages=packages,
|
| 295 |
+
euler=euler, extra_preamble=extra_preamble,
|
| 296 |
+
fontsize=fontsize, **latex_settings)
|
| 297 |
+
|
| 298 |
+
debug("Latex code:")
|
| 299 |
+
debug(latex_main)
|
| 300 |
+
with tempfile.TemporaryDirectory() as workdir:
|
| 301 |
+
with open(join(workdir, 'texput.tex'), 'w', encoding='utf-8') as fh:
|
| 302 |
+
fh.write(latex_main)
|
| 303 |
+
|
| 304 |
+
if outputTexFile is not None:
|
| 305 |
+
shutil.copyfile(join(workdir, 'texput.tex'), outputTexFile)
|
| 306 |
+
|
| 307 |
+
if not shutil.which('latex'):
|
| 308 |
+
raise RuntimeError("latex program is not installed")
|
| 309 |
+
|
| 310 |
+
try:
|
| 311 |
+
_check_output_no_window(
|
| 312 |
+
['latex', '-halt-on-error', '-interaction=nonstopmode',
|
| 313 |
+
'texput.tex'],
|
| 314 |
+
cwd=workdir,
|
| 315 |
+
stderr=STDOUT)
|
| 316 |
+
except CalledProcessError as e:
|
| 317 |
+
raise RuntimeError(
|
| 318 |
+
"'latex' exited abnormally with the following output:\n%s" %
|
| 319 |
+
e.output)
|
| 320 |
+
|
| 321 |
+
src = "texput.%s" % (output)
|
| 322 |
+
|
| 323 |
+
if output != "dvi":
|
| 324 |
+
# in order of preference
|
| 325 |
+
commandnames = {
|
| 326 |
+
"ps": ["dvips"],
|
| 327 |
+
"pdf": ["dvipdfmx", "dvipdfm", "dvipdf"],
|
| 328 |
+
"png": ["dvipng"],
|
| 329 |
+
"svg": ["dvisvgm"],
|
| 330 |
+
}
|
| 331 |
+
try:
|
| 332 |
+
cmd_variants = commandnames[output]
|
| 333 |
+
except KeyError:
|
| 334 |
+
raise ValueError("Invalid output format: %s" % output) from None
|
| 335 |
+
|
| 336 |
+
# find an appropriate command
|
| 337 |
+
for cmd_variant in cmd_variants:
|
| 338 |
+
cmd_path = shutil.which(cmd_variant)
|
| 339 |
+
if cmd_path:
|
| 340 |
+
cmd = [cmd_path]
|
| 341 |
+
break
|
| 342 |
+
else:
|
| 343 |
+
if len(cmd_variants) > 1:
|
| 344 |
+
raise RuntimeError("None of %s are installed" % ", ".join(cmd_variants))
|
| 345 |
+
else:
|
| 346 |
+
raise RuntimeError("%s is not installed" % cmd_variants[0])
|
| 347 |
+
|
| 348 |
+
defaultoptions = {
|
| 349 |
+
"dvipng": ["-T", "tight", "-z", "9", "--truecolor"],
|
| 350 |
+
"dvisvgm": ["--no-fonts"],
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
commandend = {
|
| 354 |
+
"dvips": ["-o", src, "texput.dvi"],
|
| 355 |
+
"dvipdf": ["texput.dvi", src],
|
| 356 |
+
"dvipdfm": ["-o", src, "texput.dvi"],
|
| 357 |
+
"dvipdfmx": ["-o", src, "texput.dvi"],
|
| 358 |
+
"dvipng": ["-o", src, "texput.dvi"],
|
| 359 |
+
"dvisvgm": ["-o", src, "texput.dvi"],
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
if dvioptions is not None:
|
| 363 |
+
cmd.extend(dvioptions)
|
| 364 |
+
else:
|
| 365 |
+
cmd.extend(defaultoptions.get(cmd_variant, []))
|
| 366 |
+
cmd.extend(commandend[cmd_variant])
|
| 367 |
+
|
| 368 |
+
try:
|
| 369 |
+
_check_output_no_window(cmd, cwd=workdir, stderr=STDOUT)
|
| 370 |
+
except CalledProcessError as e:
|
| 371 |
+
raise RuntimeError(
|
| 372 |
+
"'%s' exited abnormally with the following output:\n%s" %
|
| 373 |
+
(' '.join(cmd), e.output))
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
if viewer == "file":
|
| 377 |
+
shutil.move(join(workdir, src), filename)
|
| 378 |
+
elif viewer == "BytesIO":
|
| 379 |
+
with open(join(workdir, src), 'rb') as fh:
|
| 380 |
+
outputbuffer.write(fh.read())
|
| 381 |
+
elif callable(viewer):
|
| 382 |
+
viewer(join(workdir, src), fmt=output)
|
| 383 |
+
else:
|
| 384 |
+
try:
|
| 385 |
+
_check_output_no_window(
|
| 386 |
+
[viewer, src], cwd=workdir, stderr=STDOUT)
|
| 387 |
+
except CalledProcessError as e:
|
| 388 |
+
raise RuntimeError(
|
| 389 |
+
"'%s %s' exited abnormally with the following output:\n%s" %
|
| 390 |
+
(viewer, src, e.output))
|
shared/package-files/17/17042ba9d09eb176e0910f1b7d83e57f72df2be49dbee77da47102dad0a7c10d/test_align.py
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import timezone
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from pandas import (
|
| 8 |
+
DataFrame,
|
| 9 |
+
Index,
|
| 10 |
+
Series,
|
| 11 |
+
date_range,
|
| 12 |
+
)
|
| 13 |
+
import pandas._testing as tm
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestDataFrameAlign:
|
| 17 |
+
def test_align_asfreq_method_raises(self):
|
| 18 |
+
df = DataFrame({"A": [1, np.nan, 2]})
|
| 19 |
+
msg = "Invalid fill method"
|
| 20 |
+
msg2 = "The 'method', 'limit', and 'fill_axis' keywords"
|
| 21 |
+
with pytest.raises(ValueError, match=msg):
|
| 22 |
+
with tm.assert_produces_warning(FutureWarning, match=msg2):
|
| 23 |
+
df.align(df.iloc[::-1], method="asfreq")
|
| 24 |
+
|
| 25 |
+
def test_frame_align_aware(self):
|
| 26 |
+
idx1 = date_range("2001", periods=5, freq="h", tz="US/Eastern")
|
| 27 |
+
idx2 = date_range("2001", periods=5, freq="2h", tz="US/Eastern")
|
| 28 |
+
df1 = DataFrame(np.random.default_rng(2).standard_normal((len(idx1), 3)), idx1)
|
| 29 |
+
df2 = DataFrame(np.random.default_rng(2).standard_normal((len(idx2), 3)), idx2)
|
| 30 |
+
new1, new2 = df1.align(df2)
|
| 31 |
+
assert df1.index.tz == new1.index.tz
|
| 32 |
+
assert df2.index.tz == new2.index.tz
|
| 33 |
+
|
| 34 |
+
# different timezones convert to UTC
|
| 35 |
+
|
| 36 |
+
# frame with frame
|
| 37 |
+
df1_central = df1.tz_convert("US/Central")
|
| 38 |
+
new1, new2 = df1.align(df1_central)
|
| 39 |
+
assert new1.index.tz is timezone.utc
|
| 40 |
+
assert new2.index.tz is timezone.utc
|
| 41 |
+
|
| 42 |
+
# frame with Series
|
| 43 |
+
new1, new2 = df1.align(df1_central[0], axis=0)
|
| 44 |
+
assert new1.index.tz is timezone.utc
|
| 45 |
+
assert new2.index.tz is timezone.utc
|
| 46 |
+
|
| 47 |
+
df1[0].align(df1_central, axis=0)
|
| 48 |
+
assert new1.index.tz is timezone.utc
|
| 49 |
+
assert new2.index.tz is timezone.utc
|
| 50 |
+
|
| 51 |
+
def test_align_float(self, float_frame, using_copy_on_write):
|
| 52 |
+
af, bf = float_frame.align(float_frame)
|
| 53 |
+
assert af._mgr is not float_frame._mgr
|
| 54 |
+
|
| 55 |
+
af, bf = float_frame.align(float_frame, copy=False)
|
| 56 |
+
if not using_copy_on_write:
|
| 57 |
+
assert af._mgr is float_frame._mgr
|
| 58 |
+
else:
|
| 59 |
+
assert af._mgr is not float_frame._mgr
|
| 60 |
+
|
| 61 |
+
# axis = 0
|
| 62 |
+
other = float_frame.iloc[:-5, :3]
|
| 63 |
+
af, bf = float_frame.align(other, axis=0, fill_value=-1)
|
| 64 |
+
|
| 65 |
+
tm.assert_index_equal(bf.columns, other.columns)
|
| 66 |
+
|
| 67 |
+
# test fill value
|
| 68 |
+
join_idx = float_frame.index.join(other.index)
|
| 69 |
+
diff_a = float_frame.index.difference(join_idx)
|
| 70 |
+
diff_a_vals = af.reindex(diff_a).values
|
| 71 |
+
assert (diff_a_vals == -1).all()
|
| 72 |
+
|
| 73 |
+
af, bf = float_frame.align(other, join="right", axis=0)
|
| 74 |
+
tm.assert_index_equal(bf.columns, other.columns)
|
| 75 |
+
tm.assert_index_equal(bf.index, other.index)
|
| 76 |
+
tm.assert_index_equal(af.index, other.index)
|
| 77 |
+
|
| 78 |
+
# axis = 1
|
| 79 |
+
other = float_frame.iloc[:-5, :3].copy()
|
| 80 |
+
af, bf = float_frame.align(other, axis=1)
|
| 81 |
+
tm.assert_index_equal(bf.columns, float_frame.columns)
|
| 82 |
+
tm.assert_index_equal(bf.index, other.index)
|
| 83 |
+
|
| 84 |
+
# test fill value
|
| 85 |
+
join_idx = float_frame.index.join(other.index)
|
| 86 |
+
diff_a = float_frame.index.difference(join_idx)
|
| 87 |
+
diff_a_vals = af.reindex(diff_a).values
|
| 88 |
+
|
| 89 |
+
assert (diff_a_vals == -1).all()
|
| 90 |
+
|
| 91 |
+
af, bf = float_frame.align(other, join="inner", axis=1)
|
| 92 |
+
tm.assert_index_equal(bf.columns, other.columns)
|
| 93 |
+
|
| 94 |
+
msg = (
|
| 95 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 96 |
+
"are deprecated"
|
| 97 |
+
)
|
| 98 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 99 |
+
af, bf = float_frame.align(other, join="inner", axis=1, method="pad")
|
| 100 |
+
tm.assert_index_equal(bf.columns, other.columns)
|
| 101 |
+
|
| 102 |
+
msg = (
|
| 103 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 104 |
+
"are deprecated"
|
| 105 |
+
)
|
| 106 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 107 |
+
af, bf = float_frame.align(
|
| 108 |
+
other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=None
|
| 109 |
+
)
|
| 110 |
+
tm.assert_index_equal(bf.index, Index([]).astype(bf.index.dtype))
|
| 111 |
+
|
| 112 |
+
msg = (
|
| 113 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 114 |
+
"are deprecated"
|
| 115 |
+
)
|
| 116 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 117 |
+
af, bf = float_frame.align(
|
| 118 |
+
other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=0
|
| 119 |
+
)
|
| 120 |
+
tm.assert_index_equal(bf.index, Index([]).astype(bf.index.dtype))
|
| 121 |
+
|
| 122 |
+
# Try to align DataFrame to Series along bad axis
|
| 123 |
+
msg = "No axis named 2 for object type DataFrame"
|
| 124 |
+
with pytest.raises(ValueError, match=msg):
|
| 125 |
+
float_frame.align(af.iloc[0, :3], join="inner", axis=2)
|
| 126 |
+
|
| 127 |
+
def test_align_frame_with_series(self, float_frame):
|
| 128 |
+
# align dataframe to series with broadcast or not
|
| 129 |
+
idx = float_frame.index
|
| 130 |
+
s = Series(range(len(idx)), index=idx)
|
| 131 |
+
|
| 132 |
+
left, right = float_frame.align(s, axis=0)
|
| 133 |
+
tm.assert_index_equal(left.index, float_frame.index)
|
| 134 |
+
tm.assert_index_equal(right.index, float_frame.index)
|
| 135 |
+
assert isinstance(right, Series)
|
| 136 |
+
|
| 137 |
+
msg = "The 'broadcast_axis' keyword in DataFrame.align is deprecated"
|
| 138 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 139 |
+
left, right = float_frame.align(s, broadcast_axis=1)
|
| 140 |
+
tm.assert_index_equal(left.index, float_frame.index)
|
| 141 |
+
expected = {c: s for c in float_frame.columns}
|
| 142 |
+
expected = DataFrame(
|
| 143 |
+
expected, index=float_frame.index, columns=float_frame.columns
|
| 144 |
+
)
|
| 145 |
+
tm.assert_frame_equal(right, expected)
|
| 146 |
+
|
| 147 |
+
def test_align_series_condition(self):
|
| 148 |
+
# see gh-9558
|
| 149 |
+
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
|
| 150 |
+
result = df[df["a"] == 2]
|
| 151 |
+
expected = DataFrame([[2, 5]], index=[1], columns=["a", "b"])
|
| 152 |
+
tm.assert_frame_equal(result, expected)
|
| 153 |
+
|
| 154 |
+
result = df.where(df["a"] == 2, 0)
|
| 155 |
+
expected = DataFrame({"a": [0, 2, 0], "b": [0, 5, 0]})
|
| 156 |
+
tm.assert_frame_equal(result, expected)
|
| 157 |
+
|
| 158 |
+
def test_align_int(self, int_frame):
|
| 159 |
+
# test other non-float types
|
| 160 |
+
other = DataFrame(index=range(5), columns=["A", "B", "C"])
|
| 161 |
+
|
| 162 |
+
msg = (
|
| 163 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 164 |
+
"are deprecated"
|
| 165 |
+
)
|
| 166 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 167 |
+
af, bf = int_frame.align(other, join="inner", axis=1, method="pad")
|
| 168 |
+
tm.assert_index_equal(bf.columns, other.columns)
|
| 169 |
+
|
| 170 |
+
def test_align_mixed_type(self, float_string_frame):
|
| 171 |
+
msg = (
|
| 172 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 173 |
+
"are deprecated"
|
| 174 |
+
)
|
| 175 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 176 |
+
af, bf = float_string_frame.align(
|
| 177 |
+
float_string_frame, join="inner", axis=1, method="pad"
|
| 178 |
+
)
|
| 179 |
+
tm.assert_index_equal(bf.columns, float_string_frame.columns)
|
| 180 |
+
|
| 181 |
+
def test_align_mixed_float(self, mixed_float_frame):
|
| 182 |
+
# mixed floats/ints
|
| 183 |
+
other = DataFrame(index=range(5), columns=["A", "B", "C"])
|
| 184 |
+
|
| 185 |
+
msg = (
|
| 186 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 187 |
+
"are deprecated"
|
| 188 |
+
)
|
| 189 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 190 |
+
af, bf = mixed_float_frame.align(
|
| 191 |
+
other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=0
|
| 192 |
+
)
|
| 193 |
+
tm.assert_index_equal(bf.index, Index([]))
|
| 194 |
+
|
| 195 |
+
def test_align_mixed_int(self, mixed_int_frame):
|
| 196 |
+
other = DataFrame(index=range(5), columns=["A", "B", "C"])
|
| 197 |
+
|
| 198 |
+
msg = (
|
| 199 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 200 |
+
"are deprecated"
|
| 201 |
+
)
|
| 202 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 203 |
+
af, bf = mixed_int_frame.align(
|
| 204 |
+
other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=0
|
| 205 |
+
)
|
| 206 |
+
tm.assert_index_equal(bf.index, Index([]))
|
| 207 |
+
|
| 208 |
+
@pytest.mark.parametrize(
|
| 209 |
+
"l_ordered,r_ordered,expected",
|
| 210 |
+
[
|
| 211 |
+
[True, True, pd.CategoricalIndex],
|
| 212 |
+
[True, False, Index],
|
| 213 |
+
[False, True, Index],
|
| 214 |
+
[False, False, pd.CategoricalIndex],
|
| 215 |
+
],
|
| 216 |
+
)
|
| 217 |
+
def test_align_categorical(self, l_ordered, r_ordered, expected):
|
| 218 |
+
# GH-28397
|
| 219 |
+
df_1 = DataFrame(
|
| 220 |
+
{
|
| 221 |
+
"A": np.arange(6, dtype="int64"),
|
| 222 |
+
"B": Series(list("aabbca")).astype(
|
| 223 |
+
pd.CategoricalDtype(list("cab"), ordered=l_ordered)
|
| 224 |
+
),
|
| 225 |
+
}
|
| 226 |
+
).set_index("B")
|
| 227 |
+
df_2 = DataFrame(
|
| 228 |
+
{
|
| 229 |
+
"A": np.arange(5, dtype="int64"),
|
| 230 |
+
"B": Series(list("babca")).astype(
|
| 231 |
+
pd.CategoricalDtype(list("cab"), ordered=r_ordered)
|
| 232 |
+
),
|
| 233 |
+
}
|
| 234 |
+
).set_index("B")
|
| 235 |
+
|
| 236 |
+
aligned_1, aligned_2 = df_1.align(df_2)
|
| 237 |
+
assert isinstance(aligned_1.index, expected)
|
| 238 |
+
assert isinstance(aligned_2.index, expected)
|
| 239 |
+
tm.assert_index_equal(aligned_1.index, aligned_2.index)
|
| 240 |
+
|
| 241 |
+
def test_align_multiindex(self):
|
| 242 |
+
# GH#10665
|
| 243 |
+
# same test cases as test_align_multiindex in test_series.py
|
| 244 |
+
|
| 245 |
+
midx = pd.MultiIndex.from_product(
|
| 246 |
+
[range(2), range(3), range(2)], names=("a", "b", "c")
|
| 247 |
+
)
|
| 248 |
+
idx = Index(range(2), name="b")
|
| 249 |
+
df1 = DataFrame(np.arange(12, dtype="int64"), index=midx)
|
| 250 |
+
df2 = DataFrame(np.arange(2, dtype="int64"), index=idx)
|
| 251 |
+
|
| 252 |
+
# these must be the same results (but flipped)
|
| 253 |
+
res1l, res1r = df1.align(df2, join="left")
|
| 254 |
+
res2l, res2r = df2.align(df1, join="right")
|
| 255 |
+
|
| 256 |
+
expl = df1
|
| 257 |
+
tm.assert_frame_equal(expl, res1l)
|
| 258 |
+
tm.assert_frame_equal(expl, res2r)
|
| 259 |
+
expr = DataFrame([0, 0, 1, 1, np.nan, np.nan] * 2, index=midx)
|
| 260 |
+
tm.assert_frame_equal(expr, res1r)
|
| 261 |
+
tm.assert_frame_equal(expr, res2l)
|
| 262 |
+
|
| 263 |
+
res1l, res1r = df1.align(df2, join="right")
|
| 264 |
+
res2l, res2r = df2.align(df1, join="left")
|
| 265 |
+
|
| 266 |
+
exp_idx = pd.MultiIndex.from_product(
|
| 267 |
+
[range(2), range(2), range(2)], names=("a", "b", "c")
|
| 268 |
+
)
|
| 269 |
+
expl = DataFrame([0, 1, 2, 3, 6, 7, 8, 9], index=exp_idx)
|
| 270 |
+
tm.assert_frame_equal(expl, res1l)
|
| 271 |
+
tm.assert_frame_equal(expl, res2r)
|
| 272 |
+
expr = DataFrame([0, 0, 1, 1] * 2, index=exp_idx)
|
| 273 |
+
tm.assert_frame_equal(expr, res1r)
|
| 274 |
+
tm.assert_frame_equal(expr, res2l)
|
| 275 |
+
|
| 276 |
+
def test_align_series_combinations(self):
|
| 277 |
+
df = DataFrame({"a": [1, 3, 5], "b": [1, 3, 5]}, index=list("ACE"))
|
| 278 |
+
s = Series([1, 2, 4], index=list("ABD"), name="x")
|
| 279 |
+
|
| 280 |
+
# frame + series
|
| 281 |
+
res1, res2 = df.align(s, axis=0)
|
| 282 |
+
exp1 = DataFrame(
|
| 283 |
+
{"a": [1, np.nan, 3, np.nan, 5], "b": [1, np.nan, 3, np.nan, 5]},
|
| 284 |
+
index=list("ABCDE"),
|
| 285 |
+
)
|
| 286 |
+
exp2 = Series([1, 2, np.nan, 4, np.nan], index=list("ABCDE"), name="x")
|
| 287 |
+
|
| 288 |
+
tm.assert_frame_equal(res1, exp1)
|
| 289 |
+
tm.assert_series_equal(res2, exp2)
|
| 290 |
+
|
| 291 |
+
# series + frame
|
| 292 |
+
res1, res2 = s.align(df)
|
| 293 |
+
tm.assert_series_equal(res1, exp2)
|
| 294 |
+
tm.assert_frame_equal(res2, exp1)
|
| 295 |
+
|
| 296 |
+
def test_multiindex_align_to_series_with_common_index_level(self):
|
| 297 |
+
# GH-46001
|
| 298 |
+
foo_index = Index([1, 2, 3], name="foo")
|
| 299 |
+
bar_index = Index([1, 2], name="bar")
|
| 300 |
+
|
| 301 |
+
series = Series([1, 2], index=bar_index, name="foo_series")
|
| 302 |
+
df = DataFrame(
|
| 303 |
+
{"col": np.arange(6)},
|
| 304 |
+
index=pd.MultiIndex.from_product([foo_index, bar_index]),
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
expected_r = Series([1, 2] * 3, index=df.index, name="foo_series")
|
| 308 |
+
result_l, result_r = df.align(series, axis=0)
|
| 309 |
+
|
| 310 |
+
tm.assert_frame_equal(result_l, df)
|
| 311 |
+
tm.assert_series_equal(result_r, expected_r)
|
| 312 |
+
|
| 313 |
+
def test_multiindex_align_to_series_with_common_index_level_missing_in_left(self):
|
| 314 |
+
# GH-46001
|
| 315 |
+
foo_index = Index([1, 2, 3], name="foo")
|
| 316 |
+
bar_index = Index([1, 2], name="bar")
|
| 317 |
+
|
| 318 |
+
series = Series(
|
| 319 |
+
[1, 2, 3, 4], index=Index([1, 2, 3, 4], name="bar"), name="foo_series"
|
| 320 |
+
)
|
| 321 |
+
df = DataFrame(
|
| 322 |
+
{"col": np.arange(6)},
|
| 323 |
+
index=pd.MultiIndex.from_product([foo_index, bar_index]),
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
expected_r = Series([1, 2] * 3, index=df.index, name="foo_series")
|
| 327 |
+
result_l, result_r = df.align(series, axis=0)
|
| 328 |
+
|
| 329 |
+
tm.assert_frame_equal(result_l, df)
|
| 330 |
+
tm.assert_series_equal(result_r, expected_r)
|
| 331 |
+
|
| 332 |
+
def test_multiindex_align_to_series_with_common_index_level_missing_in_right(self):
|
| 333 |
+
# GH-46001
|
| 334 |
+
foo_index = Index([1, 2, 3], name="foo")
|
| 335 |
+
bar_index = Index([1, 2, 3, 4], name="bar")
|
| 336 |
+
|
| 337 |
+
series = Series([1, 2], index=Index([1, 2], name="bar"), name="foo_series")
|
| 338 |
+
df = DataFrame(
|
| 339 |
+
{"col": np.arange(12)},
|
| 340 |
+
index=pd.MultiIndex.from_product([foo_index, bar_index]),
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
expected_r = Series(
|
| 344 |
+
[1, 2, np.nan, np.nan] * 3, index=df.index, name="foo_series"
|
| 345 |
+
)
|
| 346 |
+
result_l, result_r = df.align(series, axis=0)
|
| 347 |
+
|
| 348 |
+
tm.assert_frame_equal(result_l, df)
|
| 349 |
+
tm.assert_series_equal(result_r, expected_r)
|
| 350 |
+
|
| 351 |
+
def test_multiindex_align_to_series_with_common_index_level_missing_in_both(self):
|
| 352 |
+
# GH-46001
|
| 353 |
+
foo_index = Index([1, 2, 3], name="foo")
|
| 354 |
+
bar_index = Index([1, 3, 4], name="bar")
|
| 355 |
+
|
| 356 |
+
series = Series(
|
| 357 |
+
[1, 2, 3], index=Index([1, 2, 4], name="bar"), name="foo_series"
|
| 358 |
+
)
|
| 359 |
+
df = DataFrame(
|
| 360 |
+
{"col": np.arange(9)},
|
| 361 |
+
index=pd.MultiIndex.from_product([foo_index, bar_index]),
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
expected_r = Series([1, np.nan, 3] * 3, index=df.index, name="foo_series")
|
| 365 |
+
result_l, result_r = df.align(series, axis=0)
|
| 366 |
+
|
| 367 |
+
tm.assert_frame_equal(result_l, df)
|
| 368 |
+
tm.assert_series_equal(result_r, expected_r)
|
| 369 |
+
|
| 370 |
+
def test_multiindex_align_to_series_with_common_index_level_non_unique_cols(self):
|
| 371 |
+
# GH-46001
|
| 372 |
+
foo_index = Index([1, 2, 3], name="foo")
|
| 373 |
+
bar_index = Index([1, 2], name="bar")
|
| 374 |
+
|
| 375 |
+
series = Series([1, 2], index=bar_index, name="foo_series")
|
| 376 |
+
df = DataFrame(
|
| 377 |
+
np.arange(18).reshape(6, 3),
|
| 378 |
+
index=pd.MultiIndex.from_product([foo_index, bar_index]),
|
| 379 |
+
)
|
| 380 |
+
df.columns = ["cfoo", "cbar", "cfoo"]
|
| 381 |
+
|
| 382 |
+
expected = Series([1, 2] * 3, index=df.index, name="foo_series")
|
| 383 |
+
result_left, result_right = df.align(series, axis=0)
|
| 384 |
+
|
| 385 |
+
tm.assert_series_equal(result_right, expected)
|
| 386 |
+
tm.assert_index_equal(result_left.columns, df.columns)
|
| 387 |
+
|
| 388 |
+
def test_missing_axis_specification_exception(self):
|
| 389 |
+
df = DataFrame(np.arange(50).reshape((10, 5)))
|
| 390 |
+
series = Series(np.arange(5))
|
| 391 |
+
|
| 392 |
+
with pytest.raises(ValueError, match=r"axis=0 or 1"):
|
| 393 |
+
df.align(series)
|
| 394 |
+
|
| 395 |
+
@pytest.mark.parametrize("method", ["pad", "bfill"])
|
| 396 |
+
@pytest.mark.parametrize("axis", [0, 1, None])
|
| 397 |
+
@pytest.mark.parametrize("fill_axis", [0, 1])
|
| 398 |
+
@pytest.mark.parametrize("how", ["inner", "outer", "left", "right"])
|
| 399 |
+
@pytest.mark.parametrize(
|
| 400 |
+
"left_slice",
|
| 401 |
+
[
|
| 402 |
+
[slice(4), slice(10)],
|
| 403 |
+
[slice(0), slice(0)],
|
| 404 |
+
],
|
| 405 |
+
)
|
| 406 |
+
@pytest.mark.parametrize(
|
| 407 |
+
"right_slice",
|
| 408 |
+
[
|
| 409 |
+
[slice(2, None), slice(6, None)],
|
| 410 |
+
[slice(0), slice(0)],
|
| 411 |
+
],
|
| 412 |
+
)
|
| 413 |
+
@pytest.mark.parametrize("limit", [1, None])
|
| 414 |
+
def test_align_fill_method(
|
| 415 |
+
self, how, method, axis, fill_axis, float_frame, left_slice, right_slice, limit
|
| 416 |
+
):
|
| 417 |
+
frame = float_frame
|
| 418 |
+
left = frame.iloc[left_slice[0], left_slice[1]]
|
| 419 |
+
right = frame.iloc[right_slice[0], right_slice[1]]
|
| 420 |
+
|
| 421 |
+
msg = (
|
| 422 |
+
"The 'method', 'limit', and 'fill_axis' keywords in DataFrame.align "
|
| 423 |
+
"are deprecated"
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 427 |
+
aa, ab = left.align(
|
| 428 |
+
right,
|
| 429 |
+
axis=axis,
|
| 430 |
+
join=how,
|
| 431 |
+
method=method,
|
| 432 |
+
limit=limit,
|
| 433 |
+
fill_axis=fill_axis,
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
join_index, join_columns = None, None
|
| 437 |
+
|
| 438 |
+
ea, eb = left, right
|
| 439 |
+
if axis is None or axis == 0:
|
| 440 |
+
join_index = left.index.join(right.index, how=how)
|
| 441 |
+
ea = ea.reindex(index=join_index)
|
| 442 |
+
eb = eb.reindex(index=join_index)
|
| 443 |
+
|
| 444 |
+
if axis is None or axis == 1:
|
| 445 |
+
join_columns = left.columns.join(right.columns, how=how)
|
| 446 |
+
ea = ea.reindex(columns=join_columns)
|
| 447 |
+
eb = eb.reindex(columns=join_columns)
|
| 448 |
+
|
| 449 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 450 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 451 |
+
ea = ea.fillna(axis=fill_axis, method=method, limit=limit)
|
| 452 |
+
eb = eb.fillna(axis=fill_axis, method=method, limit=limit)
|
| 453 |
+
|
| 454 |
+
tm.assert_frame_equal(aa, ea)
|
| 455 |
+
tm.assert_frame_equal(ab, eb)
|
| 456 |
+
|
| 457 |
+
def test_align_series_check_copy(self):
|
| 458 |
+
# GH#
|
| 459 |
+
df = DataFrame({0: [1, 2]})
|
| 460 |
+
ser = Series([1], name=0)
|
| 461 |
+
expected = ser.copy()
|
| 462 |
+
result, other = df.align(ser, axis=1)
|
| 463 |
+
ser.iloc[0] = 100
|
| 464 |
+
tm.assert_series_equal(other, expected)
|
| 465 |
+
|
| 466 |
+
def test_align_identical_different_object(self):
|
| 467 |
+
# GH#51032
|
| 468 |
+
df = DataFrame({"a": [1, 2]})
|
| 469 |
+
ser = Series([3, 4])
|
| 470 |
+
result, result2 = df.align(ser, axis=0)
|
| 471 |
+
tm.assert_frame_equal(result, df)
|
| 472 |
+
tm.assert_series_equal(result2, ser)
|
| 473 |
+
assert df is not result
|
| 474 |
+
assert ser is not result2
|
| 475 |
+
|
| 476 |
+
def test_align_identical_different_object_columns(self):
|
| 477 |
+
# GH#51032
|
| 478 |
+
df = DataFrame({"a": [1, 2]})
|
| 479 |
+
ser = Series([1], index=["a"])
|
| 480 |
+
result, result2 = df.align(ser, axis=1)
|
| 481 |
+
tm.assert_frame_equal(result, df)
|
| 482 |
+
tm.assert_series_equal(result2, ser)
|
| 483 |
+
assert df is not result
|
| 484 |
+
assert ser is not result2
|
shared/package-files/17/1707a57215415ca7f79dcefc52003d4b225b1ed6b710c76b2e7422cc8c52e521/thingsdb.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.lexers.thingsdb
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
Lexers for the ThingsDB language.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from pygments.lexer import RegexLexer, include, bygroups
|
| 12 |
+
from pygments.token import Comment, Keyword, Name, Number, String, Text, \
|
| 13 |
+
Operator, Punctuation, Whitespace
|
| 14 |
+
|
| 15 |
+
__all__ = ['ThingsDBLexer']
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ThingsDBLexer(RegexLexer):
|
| 19 |
+
"""
|
| 20 |
+
Lexer for the ThingsDB programming language.
|
| 21 |
+
|
| 22 |
+
.. versionadded:: 2.9
|
| 23 |
+
"""
|
| 24 |
+
name = 'ThingsDB'
|
| 25 |
+
aliases = ['ti', 'thingsdb']
|
| 26 |
+
filenames = ['*.ti']
|
| 27 |
+
|
| 28 |
+
tokens = {
|
| 29 |
+
'root': [
|
| 30 |
+
include('expression'),
|
| 31 |
+
],
|
| 32 |
+
'expression': [
|
| 33 |
+
include('comments'),
|
| 34 |
+
include('whitespace'),
|
| 35 |
+
|
| 36 |
+
# numbers
|
| 37 |
+
(r'[-+]?0b[01]+', Number.Bin),
|
| 38 |
+
(r'[-+]?0o[0-8]+', Number.Oct),
|
| 39 |
+
(r'([-+]?0x[0-9a-fA-F]+)', Number.Hex),
|
| 40 |
+
(r'[-+]?[0-9]+', Number.Integer),
|
| 41 |
+
(r'[-+]?((inf|nan)([^0-9A-Za-z_]|$)|[0-9]*\.[0-9]+(e[+-][0-9]+)?)',
|
| 42 |
+
Number.Float),
|
| 43 |
+
|
| 44 |
+
# strings
|
| 45 |
+
(r'(?:"(?:[^"]*)")+', String.Double),
|
| 46 |
+
(r"(?:'(?:[^']*)')+", String.Single),
|
| 47 |
+
|
| 48 |
+
# literals
|
| 49 |
+
(r'(true|false|nil)\b', Keyword.Constant),
|
| 50 |
+
|
| 51 |
+
# regular expressions
|
| 52 |
+
(r'(/[^/\\]*(?:\\.[^/\\]*)*/i?)', String.Regex),
|
| 53 |
+
|
| 54 |
+
# thing id's
|
| 55 |
+
(r'#[0-9]+', Comment.Preproc),
|
| 56 |
+
|
| 57 |
+
# name, assignments and functions
|
| 58 |
+
include('names'),
|
| 59 |
+
|
| 60 |
+
(r'[(){}\[\],;]', Punctuation),
|
| 61 |
+
(r'[+\-*/%&|<>^!~@=:?]', Operator),
|
| 62 |
+
],
|
| 63 |
+
'names': [
|
| 64 |
+
(r'(\.)'
|
| 65 |
+
r'(add|call|contains|del|endswith|extend|filter|find|findindex|'
|
| 66 |
+
r'get|has|id|indexof|keys|len|lower|map|pop|push|remove|set|sort|'
|
| 67 |
+
r'splice|startswith|test|unwrap|upper|values|wrap)'
|
| 68 |
+
r'(\()',
|
| 69 |
+
bygroups(Name.Function, Name.Function, Punctuation), 'arguments'),
|
| 70 |
+
(r'(array|assert|assert_err|auth_err|backup_info|backups_info|'
|
| 71 |
+
r'bad_data_err|bool|closure|collection_info|collections_info|'
|
| 72 |
+
r'counters|deep|del_backup|del_collection|del_expired|del_node|'
|
| 73 |
+
r'del_procedure|del_token|del_type|del_user|err|float|'
|
| 74 |
+
r'forbidden_err|grant|int|isarray|isascii|isbool|isbytes|iserr|'
|
| 75 |
+
r'isfloat|isinf|isint|islist|isnan|isnil|israw|isset|isstr|'
|
| 76 |
+
r'isthing|istuple|isutf8|lookup_err|max_quota_err|mod_type|new|'
|
| 77 |
+
r'new_backup|new_collection|new_node|new_procedure|new_token|'
|
| 78 |
+
r'new_type|new_user|node_err|node_info|nodes_info|now|'
|
| 79 |
+
r'num_arguments_err|operation_err|overflow_err|procedure_doc|'
|
| 80 |
+
r'procedure_info|procedures_info|raise|refs|rename_collection|'
|
| 81 |
+
r'rename_user|reset_counters|return|revoke|run|set_log_level|set|'
|
| 82 |
+
r'set_quota|set_type|shutdown|str|syntax_err|thing|try|type|'
|
| 83 |
+
r'type_err|type_count|type_info|types_info|user_info|users_info|'
|
| 84 |
+
r'value_err|wse|zero_div_err)'
|
| 85 |
+
r'(\()',
|
| 86 |
+
bygroups(Name.Function, Punctuation),
|
| 87 |
+
'arguments'),
|
| 88 |
+
(r'(\.[A-Za-z_][0-9A-Za-z_]*)'
|
| 89 |
+
r'(\s*)(=)',
|
| 90 |
+
bygroups(Name.Attribute, Text, Operator)),
|
| 91 |
+
(r'\.[A-Za-z_][0-9A-Za-z_]*', Name.Attribute),
|
| 92 |
+
(r'([A-Za-z_][0-9A-Za-z_]*)(\s*)(=)',
|
| 93 |
+
bygroups(Name.Variable, Text, Operator)),
|
| 94 |
+
(r'[A-Za-z_][0-9A-Za-z_]*', Name.Variable),
|
| 95 |
+
],
|
| 96 |
+
'whitespace': [
|
| 97 |
+
(r'\n', Whitespace),
|
| 98 |
+
(r'\s+', Whitespace),
|
| 99 |
+
],
|
| 100 |
+
'comments': [
|
| 101 |
+
(r'//(.*?)\n', Comment.Single),
|
| 102 |
+
(r'/\*', Comment.Multiline, 'comment'),
|
| 103 |
+
],
|
| 104 |
+
'comment': [
|
| 105 |
+
(r'[^*/]+', Comment.Multiline),
|
| 106 |
+
(r'/\*', Comment.Multiline, '#push'),
|
| 107 |
+
(r'\*/', Comment.Multiline, '#pop'),
|
| 108 |
+
(r'[*/]', Comment.Multiline),
|
| 109 |
+
],
|
| 110 |
+
'arguments': [
|
| 111 |
+
include('expression'),
|
| 112 |
+
(',', Punctuation),
|
| 113 |
+
(r'\(', Punctuation, '#push'),
|
| 114 |
+
(r'\)', Punctuation, '#pop'),
|
| 115 |
+
],
|
| 116 |
+
}
|
shared/package-files/17/170a22363b185e20ae6054f7dc54d41455bffa88d2ef1819c020bf1ec1d3f5d1/_colorconv.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
### ------------ vendored from skimage.color.colorconv -------------
|
| 2 |
+
# This is a small chunk of code from the skimage package. It is reproduced
|
| 3 |
+
# here because all we need is a couple color conversion routines (lab2rgb, lch2lab)
|
| 4 |
+
# and adding all of skimage as dependency is really heavy.
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# Copyright: 2009-2022 the scikit-image team
|
| 8 |
+
# All rights reserved.
|
| 9 |
+
|
| 10 |
+
# License: BSD-3-Clause
|
| 11 |
+
|
| 12 |
+
# Redistribution and use in source and binary forms, with or without
|
| 13 |
+
# modification, are permitted provided that the following conditions
|
| 14 |
+
# are met:
|
| 15 |
+
# 1. Redistributions of source code must retain the above copyright
|
| 16 |
+
# notice, this list of conditions and the following disclaimer.
|
| 17 |
+
# 2. Redistributions in binary form must reproduce the above copyright
|
| 18 |
+
# notice, this list of conditions and the following disclaimer in the
|
| 19 |
+
# documentation and/or other materials provided with the distribution.
|
| 20 |
+
# 3. Neither the name of the University nor the names of its contributors
|
| 21 |
+
# may be used to endorse or promote products derived from this software
|
| 22 |
+
# without specific prior written permission.
|
| 23 |
+
# .
|
| 24 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 25 |
+
# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 26 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 27 |
+
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE HOLDERS OR
|
| 28 |
+
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
| 29 |
+
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
| 30 |
+
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
| 31 |
+
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
| 32 |
+
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
| 33 |
+
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 34 |
+
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 35 |
+
|
| 36 |
+
from warnings import warn
|
| 37 |
+
|
| 38 |
+
import numpy as np
|
| 39 |
+
from scipy import linalg
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _prepare_colorarray(arr, *, channel_axis=-1):
|
| 43 |
+
"""Check the shape of the array and convert it to
|
| 44 |
+
floating point representation.
|
| 45 |
+
"""
|
| 46 |
+
arr = np.asanyarray(arr)
|
| 47 |
+
|
| 48 |
+
if arr.shape[channel_axis] != 3:
|
| 49 |
+
msg = f"the input array must have size 3 along `channel_axis`, got {arr.shape}"
|
| 50 |
+
raise ValueError(msg)
|
| 51 |
+
|
| 52 |
+
return arr.astype(np.float64)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
xyz_from_rgb = np.array(
|
| 56 |
+
[
|
| 57 |
+
[0.412453, 0.357580, 0.180423],
|
| 58 |
+
[0.212671, 0.715160, 0.072169],
|
| 59 |
+
[0.019334, 0.119193, 0.950227],
|
| 60 |
+
]
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
rgb_from_xyz = linalg.inv(xyz_from_rgb)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _convert(matrix, arr):
|
| 67 |
+
"""Do the color space conversion.
|
| 68 |
+
|
| 69 |
+
Parameters
|
| 70 |
+
----------
|
| 71 |
+
matrix : array_like
|
| 72 |
+
The 3x3 matrix to use.
|
| 73 |
+
arr : (..., C=3, ...) array_like
|
| 74 |
+
The input array. By default, the final dimension denotes
|
| 75 |
+
channels.
|
| 76 |
+
|
| 77 |
+
Returns
|
| 78 |
+
-------
|
| 79 |
+
out : (..., C=3, ...) ndarray
|
| 80 |
+
The converted array. Same dimensions as input.
|
| 81 |
+
"""
|
| 82 |
+
arr = _prepare_colorarray(arr)
|
| 83 |
+
|
| 84 |
+
return arr @ matrix.T.astype(arr.dtype)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def xyz2rgb(xyz):
|
| 88 |
+
"""XYZ to RGB color space conversion.
|
| 89 |
+
|
| 90 |
+
Parameters
|
| 91 |
+
----------
|
| 92 |
+
xyz : (..., C=3, ...) array_like
|
| 93 |
+
The image in XYZ format. By default, the final dimension denotes
|
| 94 |
+
channels.
|
| 95 |
+
|
| 96 |
+
Returns
|
| 97 |
+
-------
|
| 98 |
+
out : (..., C=3, ...) ndarray
|
| 99 |
+
The image in RGB format. Same dimensions as input.
|
| 100 |
+
|
| 101 |
+
"""
|
| 102 |
+
# Follow the algorithm from http://www.easyrgb.com/index.php
|
| 103 |
+
# except we don't multiply/divide by 100 in the conversion
|
| 104 |
+
arr = _convert(rgb_from_xyz, xyz)
|
| 105 |
+
mask = arr > 0.0031308
|
| 106 |
+
arr[mask] = 1.055 * np.power(arr[mask], 1 / 2.4) - 0.055
|
| 107 |
+
arr[~mask] *= 12.92
|
| 108 |
+
np.clip(arr, 0, 1, out=arr)
|
| 109 |
+
return arr
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _lab2xyz(lab):
|
| 113 |
+
"""Convert CIE-LAB to XYZ color space.
|
| 114 |
+
|
| 115 |
+
Internal function for :func:`~.lab2xyz` and others. In addition to the
|
| 116 |
+
converted image, return the number of invalid pixels in the Z channel for
|
| 117 |
+
correct warning propagation.
|
| 118 |
+
|
| 119 |
+
Returns
|
| 120 |
+
-------
|
| 121 |
+
out : (..., C=3, ...) ndarray
|
| 122 |
+
The image in XYZ format. Same dimensions as input.
|
| 123 |
+
n_invalid : int
|
| 124 |
+
Number of invalid pixels in the Z channel after conversion.
|
| 125 |
+
"""
|
| 126 |
+
arr = _prepare_colorarray(lab, channel_axis=-1).copy()
|
| 127 |
+
|
| 128 |
+
L, a, b = arr[..., 0], arr[..., 1], arr[..., 2]
|
| 129 |
+
y = (L + 16.0) / 116.0
|
| 130 |
+
x = (a / 500.0) + y
|
| 131 |
+
z = y - (b / 200.0)
|
| 132 |
+
|
| 133 |
+
invalid = np.atleast_1d(z < 0).nonzero()
|
| 134 |
+
n_invalid = invalid[0].size
|
| 135 |
+
if n_invalid != 0:
|
| 136 |
+
# Warning should be emitted by caller
|
| 137 |
+
if z.ndim > 0:
|
| 138 |
+
z[invalid] = 0
|
| 139 |
+
else:
|
| 140 |
+
z = 0
|
| 141 |
+
|
| 142 |
+
out = np.stack([x, y, z], axis=-1)
|
| 143 |
+
|
| 144 |
+
mask = out > 0.2068966
|
| 145 |
+
out[mask] = np.power(out[mask], 3.0)
|
| 146 |
+
out[~mask] = (out[~mask] - 16.0 / 116.0) / 7.787
|
| 147 |
+
|
| 148 |
+
# rescale to the reference white (illuminant)
|
| 149 |
+
xyz_ref_white = np.array([0.95047, 1.0, 1.08883])
|
| 150 |
+
out *= xyz_ref_white
|
| 151 |
+
return out, n_invalid
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def lab2rgb(lab):
|
| 155 |
+
"""Convert image in CIE-LAB to sRGB color space.
|
| 156 |
+
|
| 157 |
+
Parameters
|
| 158 |
+
----------
|
| 159 |
+
lab : (..., C=3, ...) array_like
|
| 160 |
+
The input image in CIE-LAB color space.
|
| 161 |
+
Unless `channel_axis` is set, the final dimension denotes the CIE-LAB
|
| 162 |
+
channels.
|
| 163 |
+
|
| 164 |
+
Returns
|
| 165 |
+
-------
|
| 166 |
+
out : (..., C=3, ...) ndarray
|
| 167 |
+
The image in sRGB color space, of same shape as input.
|
| 168 |
+
|
| 169 |
+
Raises
|
| 170 |
+
------
|
| 171 |
+
ValueError
|
| 172 |
+
If `lab` is not at least 2-D with shape (..., C=3, ...).
|
| 173 |
+
"""
|
| 174 |
+
xyz, n_invalid = _lab2xyz(lab)
|
| 175 |
+
if n_invalid != 0:
|
| 176 |
+
warn(
|
| 177 |
+
"Conversion from CIE-LAB, via XYZ to sRGB color space resulted in "
|
| 178 |
+
f"{n_invalid} negative Z values that have been clipped to zero",
|
| 179 |
+
stacklevel=3,
|
| 180 |
+
)
|
| 181 |
+
return xyz2rgb(xyz)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def lch2lab(lch):
|
| 185 |
+
"""Convert image in CIE-LCh to CIE-LAB color space.
|
| 186 |
+
|
| 187 |
+
CIE-LCh is the cylindrical representation of the CIE-LAB (Cartesian) color
|
| 188 |
+
space.
|
| 189 |
+
|
| 190 |
+
Parameters
|
| 191 |
+
----------
|
| 192 |
+
lch : (..., C=3, ...) array_like
|
| 193 |
+
The input image in CIE-LCh color space.
|
| 194 |
+
Unless `channel_axis` is set, the final dimension denotes the CIE-LAB
|
| 195 |
+
channels.
|
| 196 |
+
The L* values range from 0 to 100;
|
| 197 |
+
the C values range from 0 to 100;
|
| 198 |
+
the h values range from 0 to ``2*pi``.
|
| 199 |
+
|
| 200 |
+
Returns
|
| 201 |
+
-------
|
| 202 |
+
out : (..., C=3, ...) ndarray
|
| 203 |
+
The image in CIE-LAB format, of same shape as input.
|
| 204 |
+
"""
|
| 205 |
+
lch = _prepare_lab_array(lch)
|
| 206 |
+
|
| 207 |
+
c, h = lch[..., 1], lch[..., 2]
|
| 208 |
+
lch[..., 1], lch[..., 2] = c * np.cos(h), c * np.sin(h)
|
| 209 |
+
return lch
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _prepare_lab_array(arr):
|
| 213 |
+
"""Ensure input for lab2lch and lch2lab is well-formed.
|
| 214 |
+
|
| 215 |
+
Input array must be in floating point and have at least 3 elements in the
|
| 216 |
+
last dimension. Returns a new array by default.
|
| 217 |
+
"""
|
| 218 |
+
arr = np.asarray(arr, dtype=np.float64)
|
| 219 |
+
shape = arr.shape
|
| 220 |
+
if shape[-1] < 3:
|
| 221 |
+
raise ValueError("Input image has less than 3 channels.")
|
| 222 |
+
return arr
|
shared/package-files/17/172d4e30d85b5513614db7549a2ca7dce0b6eb304067f8d3b2133d92b8d3993a/compare.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Display class to aggregate and print the results of many measurements."""
|
| 2 |
+
import collections
|
| 3 |
+
import enum
|
| 4 |
+
import itertools as it
|
| 5 |
+
from typing import DefaultDict, List, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
from torch.utils.benchmark.utils import common
|
| 8 |
+
from torch import tensor as _tensor
|
| 9 |
+
|
| 10 |
+
__all__ = ["Colorize", "Compare"]
|
| 11 |
+
|
| 12 |
+
BEST = "\033[92m"
|
| 13 |
+
GOOD = "\033[34m"
|
| 14 |
+
BAD = "\033[2m\033[91m"
|
| 15 |
+
VERY_BAD = "\033[31m"
|
| 16 |
+
BOLD = "\033[1m"
|
| 17 |
+
TERMINATE = "\033[0m"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Colorize(enum.Enum):
|
| 21 |
+
NONE = "none"
|
| 22 |
+
COLUMNWISE = "columnwise"
|
| 23 |
+
ROWWISE = "rowwise"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Classes to separate internal bookkeeping from what is rendered.
|
| 27 |
+
class _Column:
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
grouped_results: List[Tuple[Optional[common.Measurement], ...]],
|
| 31 |
+
time_scale: float,
|
| 32 |
+
time_unit: str,
|
| 33 |
+
trim_significant_figures: bool,
|
| 34 |
+
highlight_warnings: bool,
|
| 35 |
+
):
|
| 36 |
+
self._grouped_results = grouped_results
|
| 37 |
+
self._flat_results = list(it.chain(*grouped_results))
|
| 38 |
+
self._time_scale = time_scale
|
| 39 |
+
self._time_unit = time_unit
|
| 40 |
+
self._trim_significant_figures = trim_significant_figures
|
| 41 |
+
self._highlight_warnings = (
|
| 42 |
+
highlight_warnings
|
| 43 |
+
and any(r.has_warnings for r in self._flat_results if r)
|
| 44 |
+
)
|
| 45 |
+
leading_digits = [
|
| 46 |
+
int(_tensor(r.median / self._time_scale).log10().ceil()) if r else None
|
| 47 |
+
for r in self._flat_results
|
| 48 |
+
]
|
| 49 |
+
unit_digits = max(d for d in leading_digits if d is not None)
|
| 50 |
+
decimal_digits = min(
|
| 51 |
+
max(m.significant_figures - digits, 0)
|
| 52 |
+
for digits, m in zip(leading_digits, self._flat_results)
|
| 53 |
+
if (m is not None) and (digits is not None)
|
| 54 |
+
) if self._trim_significant_figures else 1
|
| 55 |
+
length = unit_digits + decimal_digits + (1 if decimal_digits else 0)
|
| 56 |
+
self._template = f"{{:>{length}.{decimal_digits}f}}{{:>{7 if self._highlight_warnings else 0}}}"
|
| 57 |
+
|
| 58 |
+
def get_results_for(self, group):
|
| 59 |
+
return self._grouped_results[group]
|
| 60 |
+
|
| 61 |
+
def num_to_str(self, value: Optional[float], estimated_sigfigs: int, spread: Optional[float]):
|
| 62 |
+
if value is None:
|
| 63 |
+
return " " * len(self.num_to_str(1, estimated_sigfigs, None))
|
| 64 |
+
|
| 65 |
+
if self._trim_significant_figures:
|
| 66 |
+
value = common.trim_sigfig(value, estimated_sigfigs)
|
| 67 |
+
|
| 68 |
+
return self._template.format(
|
| 69 |
+
value,
|
| 70 |
+
f" (! {spread * 100:.0f}%)" if self._highlight_warnings and spread is not None else "")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def optional_min(seq):
|
| 74 |
+
l = list(seq)
|
| 75 |
+
return None if len(l) == 0 else min(l)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class _Row:
|
| 79 |
+
def __init__(self, results, row_group, render_env, env_str_len,
|
| 80 |
+
row_name_str_len, time_scale, colorize, num_threads=None):
|
| 81 |
+
super().__init__()
|
| 82 |
+
self._results = results
|
| 83 |
+
self._row_group = row_group
|
| 84 |
+
self._render_env = render_env
|
| 85 |
+
self._env_str_len = env_str_len
|
| 86 |
+
self._row_name_str_len = row_name_str_len
|
| 87 |
+
self._time_scale = time_scale
|
| 88 |
+
self._colorize = colorize
|
| 89 |
+
self._columns: Tuple[_Column, ...] = ()
|
| 90 |
+
self._num_threads = num_threads
|
| 91 |
+
|
| 92 |
+
def register_columns(self, columns: Tuple[_Column, ...]):
|
| 93 |
+
self._columns = columns
|
| 94 |
+
|
| 95 |
+
def as_column_strings(self):
|
| 96 |
+
concrete_results = [r for r in self._results if r is not None]
|
| 97 |
+
env = f"({concrete_results[0].env})" if self._render_env else ""
|
| 98 |
+
env = env.ljust(self._env_str_len + 4)
|
| 99 |
+
output = [" " + env + concrete_results[0].as_row_name]
|
| 100 |
+
for m, col in zip(self._results, self._columns or ()):
|
| 101 |
+
if m is None:
|
| 102 |
+
output.append(col.num_to_str(None, 1, None))
|
| 103 |
+
else:
|
| 104 |
+
output.append(col.num_to_str(
|
| 105 |
+
m.median / self._time_scale,
|
| 106 |
+
m.significant_figures,
|
| 107 |
+
m.iqr / m.median if m.has_warnings else None
|
| 108 |
+
))
|
| 109 |
+
return output
|
| 110 |
+
|
| 111 |
+
@staticmethod
|
| 112 |
+
def color_segment(segment, value, best_value):
|
| 113 |
+
if value <= best_value * 1.01 or value <= best_value + 100e-9:
|
| 114 |
+
return BEST + BOLD + segment + TERMINATE * 2
|
| 115 |
+
if value <= best_value * 1.1:
|
| 116 |
+
return GOOD + BOLD + segment + TERMINATE * 2
|
| 117 |
+
if value >= best_value * 5:
|
| 118 |
+
return VERY_BAD + BOLD + segment + TERMINATE * 2
|
| 119 |
+
if value >= best_value * 2:
|
| 120 |
+
return BAD + segment + TERMINATE * 2
|
| 121 |
+
|
| 122 |
+
return segment
|
| 123 |
+
|
| 124 |
+
def row_separator(self, overall_width):
|
| 125 |
+
return (
|
| 126 |
+
[f"{self._num_threads} threads: ".ljust(overall_width, "-")]
|
| 127 |
+
if self._num_threads is not None else []
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
def finalize_column_strings(self, column_strings, col_widths):
|
| 131 |
+
best_values = [-1 for _ in column_strings]
|
| 132 |
+
if self._colorize == Colorize.ROWWISE:
|
| 133 |
+
row_min = min(r.median for r in self._results if r is not None)
|
| 134 |
+
best_values = [row_min for _ in column_strings]
|
| 135 |
+
elif self._colorize == Colorize.COLUMNWISE:
|
| 136 |
+
best_values = [
|
| 137 |
+
optional_min(r.median for r in column.get_results_for(self._row_group) if r is not None)
|
| 138 |
+
for column in (self._columns or ())
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
row_contents = [column_strings[0].ljust(col_widths[0])]
|
| 142 |
+
for col_str, width, result, best_value in zip(column_strings[1:], col_widths[1:], self._results, best_values):
|
| 143 |
+
col_str = col_str.center(width)
|
| 144 |
+
if self._colorize != Colorize.NONE and result is not None and best_value is not None:
|
| 145 |
+
col_str = self.color_segment(col_str, result.median, best_value)
|
| 146 |
+
row_contents.append(col_str)
|
| 147 |
+
return row_contents
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class Table:
|
| 151 |
+
def __init__(
|
| 152 |
+
self,
|
| 153 |
+
results: List[common.Measurement],
|
| 154 |
+
colorize: Colorize,
|
| 155 |
+
trim_significant_figures: bool,
|
| 156 |
+
highlight_warnings: bool
|
| 157 |
+
):
|
| 158 |
+
assert len({r.label for r in results}) == 1
|
| 159 |
+
|
| 160 |
+
self.results = results
|
| 161 |
+
self._colorize = colorize
|
| 162 |
+
self._trim_significant_figures = trim_significant_figures
|
| 163 |
+
self._highlight_warnings = highlight_warnings
|
| 164 |
+
self.label = results[0].label
|
| 165 |
+
self.time_unit, self.time_scale = common.select_unit(
|
| 166 |
+
min(r.median for r in results)
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
self.row_keys = common.ordered_unique([self.row_fn(i) for i in results])
|
| 170 |
+
self.row_keys.sort(key=lambda args: args[:2]) # preserve stmt order
|
| 171 |
+
self.column_keys = common.ordered_unique([self.col_fn(i) for i in results])
|
| 172 |
+
self.rows, self.columns = self.populate_rows_and_columns()
|
| 173 |
+
|
| 174 |
+
@staticmethod
|
| 175 |
+
def row_fn(m: common.Measurement) -> Tuple[int, Optional[str], str]:
|
| 176 |
+
return m.num_threads, m.env, m.as_row_name
|
| 177 |
+
|
| 178 |
+
@staticmethod
|
| 179 |
+
def col_fn(m: common.Measurement) -> Optional[str]:
|
| 180 |
+
return m.description
|
| 181 |
+
|
| 182 |
+
def populate_rows_and_columns(self) -> Tuple[Tuple[_Row, ...], Tuple[_Column, ...]]:
|
| 183 |
+
rows: List[_Row] = []
|
| 184 |
+
columns: List[_Column] = []
|
| 185 |
+
ordered_results: List[List[Optional[common.Measurement]]] = [
|
| 186 |
+
[None for _ in self.column_keys]
|
| 187 |
+
for _ in self.row_keys
|
| 188 |
+
]
|
| 189 |
+
row_position = {key: i for i, key in enumerate(self.row_keys)}
|
| 190 |
+
col_position = {key: i for i, key in enumerate(self.column_keys)}
|
| 191 |
+
for r in self.results:
|
| 192 |
+
i = row_position[self.row_fn(r)]
|
| 193 |
+
j = col_position[self.col_fn(r)]
|
| 194 |
+
ordered_results[i][j] = r
|
| 195 |
+
|
| 196 |
+
unique_envs = {r.env for r in self.results}
|
| 197 |
+
render_env = len(unique_envs) > 1
|
| 198 |
+
env_str_len = max(len(i) for i in unique_envs) if render_env else 0
|
| 199 |
+
|
| 200 |
+
row_name_str_len = max(len(r.as_row_name) for r in self.results)
|
| 201 |
+
|
| 202 |
+
prior_num_threads = -1
|
| 203 |
+
prior_env = ""
|
| 204 |
+
row_group = -1
|
| 205 |
+
rows_by_group: List[List[List[Optional[common.Measurement]]]] = []
|
| 206 |
+
for (num_threads, env, _), row in zip(self.row_keys, ordered_results):
|
| 207 |
+
thread_transition = (num_threads != prior_num_threads)
|
| 208 |
+
if thread_transition:
|
| 209 |
+
prior_num_threads = num_threads
|
| 210 |
+
prior_env = ""
|
| 211 |
+
row_group += 1
|
| 212 |
+
rows_by_group.append([])
|
| 213 |
+
rows.append(
|
| 214 |
+
_Row(
|
| 215 |
+
results=row,
|
| 216 |
+
row_group=row_group,
|
| 217 |
+
render_env=(render_env and env != prior_env),
|
| 218 |
+
env_str_len=env_str_len,
|
| 219 |
+
row_name_str_len=row_name_str_len,
|
| 220 |
+
time_scale=self.time_scale,
|
| 221 |
+
colorize=self._colorize,
|
| 222 |
+
num_threads=num_threads if thread_transition else None,
|
| 223 |
+
)
|
| 224 |
+
)
|
| 225 |
+
rows_by_group[-1].append(row)
|
| 226 |
+
prior_env = env
|
| 227 |
+
|
| 228 |
+
for i in range(len(self.column_keys)):
|
| 229 |
+
grouped_results = [tuple(row[i] for row in g) for g in rows_by_group]
|
| 230 |
+
column = _Column(
|
| 231 |
+
grouped_results=grouped_results,
|
| 232 |
+
time_scale=self.time_scale,
|
| 233 |
+
time_unit=self.time_unit,
|
| 234 |
+
trim_significant_figures=self._trim_significant_figures,
|
| 235 |
+
highlight_warnings=self._highlight_warnings,)
|
| 236 |
+
columns.append(column)
|
| 237 |
+
|
| 238 |
+
rows_tuple, columns_tuple = tuple(rows), tuple(columns)
|
| 239 |
+
for ri in rows_tuple:
|
| 240 |
+
ri.register_columns(columns_tuple)
|
| 241 |
+
return rows_tuple, columns_tuple
|
| 242 |
+
|
| 243 |
+
def render(self) -> str:
|
| 244 |
+
string_rows = [[""] + self.column_keys]
|
| 245 |
+
for r in self.rows:
|
| 246 |
+
string_rows.append(r.as_column_strings())
|
| 247 |
+
num_cols = max(len(i) for i in string_rows)
|
| 248 |
+
for sr in string_rows:
|
| 249 |
+
sr.extend(["" for _ in range(num_cols - len(sr))])
|
| 250 |
+
|
| 251 |
+
col_widths = [max(len(j) for j in i) for i in zip(*string_rows)]
|
| 252 |
+
finalized_columns = [" | ".join(i.center(w) for i, w in zip(string_rows[0], col_widths))]
|
| 253 |
+
overall_width = len(finalized_columns[0])
|
| 254 |
+
for string_row, row in zip(string_rows[1:], self.rows):
|
| 255 |
+
finalized_columns.extend(row.row_separator(overall_width))
|
| 256 |
+
finalized_columns.append(" | ".join(row.finalize_column_strings(string_row, col_widths)))
|
| 257 |
+
|
| 258 |
+
newline = "\n"
|
| 259 |
+
has_warnings = self._highlight_warnings and any(ri.has_warnings for ri in self.results)
|
| 260 |
+
return f"""
|
| 261 |
+
[{(' ' + (self.label or '') + ' ').center(overall_width - 2, '-')}]
|
| 262 |
+
{newline.join(finalized_columns)}
|
| 263 |
+
|
| 264 |
+
Times are in {common.unit_to_english(self.time_unit)}s ({self.time_unit}).
|
| 265 |
+
{'(! XX%) Measurement has high variance, where XX is the IQR / median * 100.' + newline if has_warnings else ""}"""[1:]
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class Compare:
|
| 269 |
+
def __init__(self, results: List[common.Measurement]):
|
| 270 |
+
self._results: List[common.Measurement] = []
|
| 271 |
+
self.extend_results(results)
|
| 272 |
+
self._trim_significant_figures = False
|
| 273 |
+
self._colorize = Colorize.NONE
|
| 274 |
+
self._highlight_warnings = False
|
| 275 |
+
|
| 276 |
+
def __str__(self):
|
| 277 |
+
return "\n".join(self._render())
|
| 278 |
+
|
| 279 |
+
def extend_results(self, results):
|
| 280 |
+
for r in results:
|
| 281 |
+
if not isinstance(r, common.Measurement):
|
| 282 |
+
raise ValueError(
|
| 283 |
+
"Expected an instance of `Measurement`, " f"got {type(r)} instead."
|
| 284 |
+
)
|
| 285 |
+
self._results.extend(results)
|
| 286 |
+
|
| 287 |
+
def trim_significant_figures(self):
|
| 288 |
+
self._trim_significant_figures = True
|
| 289 |
+
|
| 290 |
+
def colorize(self, rowwise=False):
|
| 291 |
+
self._colorize = Colorize.ROWWISE if rowwise else Colorize.COLUMNWISE
|
| 292 |
+
|
| 293 |
+
def highlight_warnings(self):
|
| 294 |
+
self._highlight_warnings = True
|
| 295 |
+
|
| 296 |
+
def print(self):
|
| 297 |
+
print(str(self))
|
| 298 |
+
|
| 299 |
+
def _render(self):
|
| 300 |
+
results = common.Measurement.merge(self._results)
|
| 301 |
+
grouped_results = self._group_by_label(results)
|
| 302 |
+
output = []
|
| 303 |
+
for group in grouped_results.values():
|
| 304 |
+
output.append(self._layout(group))
|
| 305 |
+
return output
|
| 306 |
+
|
| 307 |
+
def _group_by_label(self, results: List[common.Measurement]):
|
| 308 |
+
grouped_results: DefaultDict[str, List[common.Measurement]] = collections.defaultdict(list)
|
| 309 |
+
for r in results:
|
| 310 |
+
grouped_results[r.label].append(r)
|
| 311 |
+
return grouped_results
|
| 312 |
+
|
| 313 |
+
def _layout(self, results: List[common.Measurement]):
|
| 314 |
+
table = Table(
|
| 315 |
+
results,
|
| 316 |
+
self._colorize,
|
| 317 |
+
self._trim_significant_figures,
|
| 318 |
+
self._highlight_warnings
|
| 319 |
+
)
|
| 320 |
+
return table.render()
|
shared/package-files/17/173208235bca43da20ef09451c72d42de5fd82f3b183884873a93c7a74da1094/slow_conv3d.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/slow_conv3d_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::slow_conv3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, *, Tensor(a!) out) -> Tensor(a!)
|
| 26 |
+
inline at::Tensor & slow_conv3d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional<at::Tensor> & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0) {
|
| 27 |
+
return at::_ops::slow_conv3d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), out);
|
| 28 |
+
}
|
| 29 |
+
namespace symint {
|
| 30 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
|
| 31 |
+
at::Tensor & slow_conv3d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional<at::Tensor> & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0) {
|
| 32 |
+
return at::_ops::slow_conv3d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), out);
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
// aten::slow_conv3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, *, Tensor(a!) out) -> Tensor(a!)
|
| 37 |
+
inline at::Tensor & slow_conv3d_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional<at::Tensor> & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::Tensor & out) {
|
| 38 |
+
return at::_ops::slow_conv3d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), out);
|
| 39 |
+
}
|
| 40 |
+
namespace symint {
|
| 41 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
|
| 42 |
+
at::Tensor & slow_conv3d_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional<at::Tensor> & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::Tensor & out) {
|
| 43 |
+
return at::_ops::slow_conv3d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), out);
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// aten::slow_conv3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, *, Tensor(a!) out) -> Tensor(a!)
|
| 48 |
+
inline at::Tensor & slow_conv3d_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional<at::Tensor> & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0)) {
|
| 49 |
+
return at::_ops::slow_conv3d_out::call(self, weight, kernel_size, bias, stride, padding, out);
|
| 50 |
+
}
|
| 51 |
+
namespace symint {
|
| 52 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
|
| 53 |
+
at::Tensor & slow_conv3d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional<at::Tensor> & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0)) {
|
| 54 |
+
return at::_ops::slow_conv3d_out::call(self, weight, kernel_size, bias, stride, padding, out);
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
// aten::slow_conv3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, *, Tensor(a!) out) -> Tensor(a!)
|
| 59 |
+
inline at::Tensor & slow_conv3d_symint_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, at::Tensor & out) {
|
| 60 |
+
return at::_ops::slow_conv3d_out::call(self, weight, kernel_size, bias, stride, padding, out);
|
| 61 |
+
}
|
| 62 |
+
namespace symint {
|
| 63 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
|
| 64 |
+
at::Tensor & slow_conv3d_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, at::Tensor & out) {
|
| 65 |
+
return at::_ops::slow_conv3d_out::call(self, weight, kernel_size, bias, stride, padding, out);
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
// aten::slow_conv3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0) -> Tensor
|
| 70 |
+
inline at::Tensor slow_conv3d(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional<at::Tensor> & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0) {
|
| 71 |
+
return at::_ops::slow_conv3d::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding));
|
| 72 |
+
}
|
| 73 |
+
namespace symint {
|
| 74 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
|
| 75 |
+
at::Tensor slow_conv3d(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional<at::Tensor> & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0) {
|
| 76 |
+
return at::_ops::slow_conv3d::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding));
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
// aten::slow_conv3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0) -> Tensor
|
| 81 |
+
inline at::Tensor slow_conv3d_symint(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional<at::Tensor> & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0)) {
|
| 82 |
+
return at::_ops::slow_conv3d::call(self, weight, kernel_size, bias, stride, padding);
|
| 83 |
+
}
|
| 84 |
+
namespace symint {
|
| 85 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
|
| 86 |
+
at::Tensor slow_conv3d(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional<at::Tensor> & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0)) {
|
| 87 |
+
return at::_ops::slow_conv3d::call(self, weight, kernel_size, bias, stride, padding);
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
}
|
shared/package-files/17/1735c710532f1b6f39dbdcd58183eabc85159a0bb86fa22d2479b22c339c8ec5/loader.pyi
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, Optional, Sequence, Set, Tuple, Union
|
| 2 |
+
|
| 3 |
+
from django.db.migrations.migration import Migration
|
| 4 |
+
from django.db.migrations.state import ProjectState
|
| 5 |
+
|
| 6 |
+
MIGRATIONS_MODULE_NAME: str
|
| 7 |
+
|
| 8 |
+
class MigrationLoader:
|
| 9 |
+
connection: Any = ...
|
| 10 |
+
disk_migrations: Dict[Tuple[str, str], Migration] = ...
|
| 11 |
+
applied_migrations: Set[Tuple[str, str]] = ...
|
| 12 |
+
ignore_no_migrations: bool = ...
|
| 13 |
+
def __init__(self, connection: Any, load: bool = ..., ignore_no_migrations: bool = ...) -> None: ...
|
| 14 |
+
@classmethod
|
| 15 |
+
def migrations_module(cls, app_label: str) -> Tuple[Optional[str], bool]: ...
|
| 16 |
+
unmigrated_apps: Set[str] = ...
|
| 17 |
+
migrated_apps: Set[str] = ...
|
| 18 |
+
def load_disk(self) -> None: ...
|
| 19 |
+
def get_migration(self, app_label: str, name_prefix: str) -> Migration: ...
|
| 20 |
+
def get_migration_by_prefix(self, app_label: str, name_prefix: str) -> Migration: ...
|
| 21 |
+
def check_key(self, key: Tuple[str, str], current_app: str) -> Optional[Tuple[str, str]]: ...
|
| 22 |
+
def add_internal_dependencies(self, key: Tuple[str, str], migration: Migration) -> None: ...
|
| 23 |
+
def add_external_dependencies(self, key: Tuple[str, str], migration: Migration) -> None: ...
|
| 24 |
+
graph: Any = ...
|
| 25 |
+
replacements: Any = ...
|
| 26 |
+
def build_graph(self) -> None: ...
|
| 27 |
+
def check_consistent_history(self, connection: Any) -> None: ...
|
| 28 |
+
def detect_conflicts(self) -> Dict[str, Set[str]]: ...
|
| 29 |
+
def project_state(
|
| 30 |
+
self, nodes: Optional[Union[Tuple[str, str], Sequence[Tuple[str, str]]]] = ..., at_end: bool = ...
|
| 31 |
+
) -> ProjectState: ...
|
shared/package-files/17/173f35914e71d60e8e9cd991adae8f45aacfa6ae47118b80f175f4b11ff2e8b2/test_base_indexer.py
ADDED
|
@@ -0,0 +1,519 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas import (
|
| 5 |
+
DataFrame,
|
| 6 |
+
MultiIndex,
|
| 7 |
+
Series,
|
| 8 |
+
concat,
|
| 9 |
+
date_range,
|
| 10 |
+
)
|
| 11 |
+
import pandas._testing as tm
|
| 12 |
+
from pandas.api.indexers import (
|
| 13 |
+
BaseIndexer,
|
| 14 |
+
FixedForwardWindowIndexer,
|
| 15 |
+
)
|
| 16 |
+
from pandas.core.indexers.objects import (
|
| 17 |
+
ExpandingIndexer,
|
| 18 |
+
FixedWindowIndexer,
|
| 19 |
+
VariableOffsetWindowIndexer,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
from pandas.tseries.offsets import BusinessDay
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_bad_get_window_bounds_signature():
|
| 26 |
+
class BadIndexer(BaseIndexer):
|
| 27 |
+
def get_window_bounds(self):
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
indexer = BadIndexer()
|
| 31 |
+
with pytest.raises(ValueError, match="BadIndexer does not implement"):
|
| 32 |
+
Series(range(5)).rolling(indexer)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_expanding_indexer():
|
| 36 |
+
s = Series(range(10))
|
| 37 |
+
indexer = ExpandingIndexer()
|
| 38 |
+
result = s.rolling(indexer).mean()
|
| 39 |
+
expected = s.expanding().mean()
|
| 40 |
+
tm.assert_series_equal(result, expected)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_indexer_constructor_arg():
|
| 44 |
+
# Example found in computation.rst
|
| 45 |
+
use_expanding = [True, False, True, False, True]
|
| 46 |
+
df = DataFrame({"values": range(5)})
|
| 47 |
+
|
| 48 |
+
class CustomIndexer(BaseIndexer):
|
| 49 |
+
def get_window_bounds(self, num_values, min_periods, center, closed, step):
|
| 50 |
+
start = np.empty(num_values, dtype=np.int64)
|
| 51 |
+
end = np.empty(num_values, dtype=np.int64)
|
| 52 |
+
for i in range(num_values):
|
| 53 |
+
if self.use_expanding[i]:
|
| 54 |
+
start[i] = 0
|
| 55 |
+
end[i] = i + 1
|
| 56 |
+
else:
|
| 57 |
+
start[i] = i
|
| 58 |
+
end[i] = i + self.window_size
|
| 59 |
+
return start, end
|
| 60 |
+
|
| 61 |
+
indexer = CustomIndexer(window_size=1, use_expanding=use_expanding)
|
| 62 |
+
result = df.rolling(indexer).sum()
|
| 63 |
+
expected = DataFrame({"values": [0.0, 1.0, 3.0, 3.0, 10.0]})
|
| 64 |
+
tm.assert_frame_equal(result, expected)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_indexer_accepts_rolling_args():
|
| 68 |
+
df = DataFrame({"values": range(5)})
|
| 69 |
+
|
| 70 |
+
class CustomIndexer(BaseIndexer):
|
| 71 |
+
def get_window_bounds(self, num_values, min_periods, center, closed, step):
|
| 72 |
+
start = np.empty(num_values, dtype=np.int64)
|
| 73 |
+
end = np.empty(num_values, dtype=np.int64)
|
| 74 |
+
for i in range(num_values):
|
| 75 |
+
if (
|
| 76 |
+
center
|
| 77 |
+
and min_periods == 1
|
| 78 |
+
and closed == "both"
|
| 79 |
+
and step == 1
|
| 80 |
+
and i == 2
|
| 81 |
+
):
|
| 82 |
+
start[i] = 0
|
| 83 |
+
end[i] = num_values
|
| 84 |
+
else:
|
| 85 |
+
start[i] = i
|
| 86 |
+
end[i] = i + self.window_size
|
| 87 |
+
return start, end
|
| 88 |
+
|
| 89 |
+
indexer = CustomIndexer(window_size=1)
|
| 90 |
+
result = df.rolling(
|
| 91 |
+
indexer, center=True, min_periods=1, closed="both", step=1
|
| 92 |
+
).sum()
|
| 93 |
+
expected = DataFrame({"values": [0.0, 1.0, 10.0, 3.0, 4.0]})
|
| 94 |
+
tm.assert_frame_equal(result, expected)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@pytest.mark.parametrize(
|
| 98 |
+
"func,np_func,expected,np_kwargs",
|
| 99 |
+
[
|
| 100 |
+
("count", len, [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 2.0, np.nan], {}),
|
| 101 |
+
("min", np.min, [0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 6.0, 7.0, 8.0, np.nan], {}),
|
| 102 |
+
(
|
| 103 |
+
"max",
|
| 104 |
+
np.max,
|
| 105 |
+
[2.0, 3.0, 4.0, 100.0, 100.0, 100.0, 8.0, 9.0, 9.0, np.nan],
|
| 106 |
+
{},
|
| 107 |
+
),
|
| 108 |
+
(
|
| 109 |
+
"std",
|
| 110 |
+
np.std,
|
| 111 |
+
[
|
| 112 |
+
1.0,
|
| 113 |
+
1.0,
|
| 114 |
+
1.0,
|
| 115 |
+
55.71654452,
|
| 116 |
+
54.85739087,
|
| 117 |
+
53.9845657,
|
| 118 |
+
1.0,
|
| 119 |
+
1.0,
|
| 120 |
+
0.70710678,
|
| 121 |
+
np.nan,
|
| 122 |
+
],
|
| 123 |
+
{"ddof": 1},
|
| 124 |
+
),
|
| 125 |
+
(
|
| 126 |
+
"var",
|
| 127 |
+
np.var,
|
| 128 |
+
[
|
| 129 |
+
1.0,
|
| 130 |
+
1.0,
|
| 131 |
+
1.0,
|
| 132 |
+
3104.333333,
|
| 133 |
+
3009.333333,
|
| 134 |
+
2914.333333,
|
| 135 |
+
1.0,
|
| 136 |
+
1.0,
|
| 137 |
+
0.500000,
|
| 138 |
+
np.nan,
|
| 139 |
+
],
|
| 140 |
+
{"ddof": 1},
|
| 141 |
+
),
|
| 142 |
+
(
|
| 143 |
+
"median",
|
| 144 |
+
np.median,
|
| 145 |
+
[1.0, 2.0, 3.0, 4.0, 6.0, 7.0, 7.0, 8.0, 8.5, np.nan],
|
| 146 |
+
{},
|
| 147 |
+
),
|
| 148 |
+
],
|
| 149 |
+
)
|
| 150 |
+
def test_rolling_forward_window(
|
| 151 |
+
frame_or_series, func, np_func, expected, np_kwargs, step
|
| 152 |
+
):
|
| 153 |
+
# GH 32865
|
| 154 |
+
values = np.arange(10.0)
|
| 155 |
+
values[5] = 100.0
|
| 156 |
+
|
| 157 |
+
indexer = FixedForwardWindowIndexer(window_size=3)
|
| 158 |
+
|
| 159 |
+
match = "Forward-looking windows can't have center=True"
|
| 160 |
+
with pytest.raises(ValueError, match=match):
|
| 161 |
+
rolling = frame_or_series(values).rolling(window=indexer, center=True)
|
| 162 |
+
getattr(rolling, func)()
|
| 163 |
+
|
| 164 |
+
match = "Forward-looking windows don't support setting the closed argument"
|
| 165 |
+
with pytest.raises(ValueError, match=match):
|
| 166 |
+
rolling = frame_or_series(values).rolling(window=indexer, closed="right")
|
| 167 |
+
getattr(rolling, func)()
|
| 168 |
+
|
| 169 |
+
rolling = frame_or_series(values).rolling(window=indexer, min_periods=2, step=step)
|
| 170 |
+
result = getattr(rolling, func)()
|
| 171 |
+
|
| 172 |
+
# Check that the function output matches the explicitly provided array
|
| 173 |
+
expected = frame_or_series(expected)[::step]
|
| 174 |
+
tm.assert_equal(result, expected)
|
| 175 |
+
|
| 176 |
+
# Check that the rolling function output matches applying an alternative
|
| 177 |
+
# function to the rolling window object
|
| 178 |
+
expected2 = frame_or_series(rolling.apply(lambda x: np_func(x, **np_kwargs)))
|
| 179 |
+
tm.assert_equal(result, expected2)
|
| 180 |
+
|
| 181 |
+
# Check that the function output matches applying an alternative function
|
| 182 |
+
# if min_periods isn't specified
|
| 183 |
+
# GH 39604: After count-min_periods deprecation, apply(lambda x: len(x))
|
| 184 |
+
# is equivalent to count after setting min_periods=0
|
| 185 |
+
min_periods = 0 if func == "count" else None
|
| 186 |
+
rolling3 = frame_or_series(values).rolling(window=indexer, min_periods=min_periods)
|
| 187 |
+
result3 = getattr(rolling3, func)()
|
| 188 |
+
expected3 = frame_or_series(rolling3.apply(lambda x: np_func(x, **np_kwargs)))
|
| 189 |
+
tm.assert_equal(result3, expected3)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def test_rolling_forward_skewness(frame_or_series, step):
|
| 193 |
+
values = np.arange(10.0)
|
| 194 |
+
values[5] = 100.0
|
| 195 |
+
|
| 196 |
+
indexer = FixedForwardWindowIndexer(window_size=5)
|
| 197 |
+
rolling = frame_or_series(values).rolling(window=indexer, min_periods=3, step=step)
|
| 198 |
+
result = rolling.skew()
|
| 199 |
+
|
| 200 |
+
expected = frame_or_series(
|
| 201 |
+
[
|
| 202 |
+
0.0,
|
| 203 |
+
2.232396,
|
| 204 |
+
2.229508,
|
| 205 |
+
2.228340,
|
| 206 |
+
2.229091,
|
| 207 |
+
2.231989,
|
| 208 |
+
0.0,
|
| 209 |
+
0.0,
|
| 210 |
+
np.nan,
|
| 211 |
+
np.nan,
|
| 212 |
+
]
|
| 213 |
+
)[::step]
|
| 214 |
+
tm.assert_equal(result, expected)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@pytest.mark.parametrize(
|
| 218 |
+
"func,expected",
|
| 219 |
+
[
|
| 220 |
+
("cov", [2.0, 2.0, 2.0, 97.0, 2.0, -93.0, 2.0, 2.0, np.nan, np.nan]),
|
| 221 |
+
(
|
| 222 |
+
"corr",
|
| 223 |
+
[
|
| 224 |
+
1.0,
|
| 225 |
+
1.0,
|
| 226 |
+
1.0,
|
| 227 |
+
0.8704775290207161,
|
| 228 |
+
0.018229084250926637,
|
| 229 |
+
-0.861357304646493,
|
| 230 |
+
1.0,
|
| 231 |
+
1.0,
|
| 232 |
+
np.nan,
|
| 233 |
+
np.nan,
|
| 234 |
+
],
|
| 235 |
+
),
|
| 236 |
+
],
|
| 237 |
+
)
|
| 238 |
+
def test_rolling_forward_cov_corr(func, expected):
|
| 239 |
+
values1 = np.arange(10).reshape(-1, 1)
|
| 240 |
+
values2 = values1 * 2
|
| 241 |
+
values1[5, 0] = 100
|
| 242 |
+
values = np.concatenate([values1, values2], axis=1)
|
| 243 |
+
|
| 244 |
+
indexer = FixedForwardWindowIndexer(window_size=3)
|
| 245 |
+
rolling = DataFrame(values).rolling(window=indexer, min_periods=3)
|
| 246 |
+
# We are interested in checking only pairwise covariance / correlation
|
| 247 |
+
result = getattr(rolling, func)().loc[(slice(None), 1), 0]
|
| 248 |
+
result = result.reset_index(drop=True)
|
| 249 |
+
expected = Series(expected).reset_index(drop=True)
|
| 250 |
+
expected.name = result.name
|
| 251 |
+
tm.assert_equal(result, expected)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
@pytest.mark.parametrize(
|
| 255 |
+
"closed,expected_data",
|
| 256 |
+
[
|
| 257 |
+
["right", [0.0, 1.0, 2.0, 3.0, 7.0, 12.0, 6.0, 7.0, 8.0, 9.0]],
|
| 258 |
+
["left", [0.0, 0.0, 1.0, 2.0, 5.0, 9.0, 5.0, 6.0, 7.0, 8.0]],
|
| 259 |
+
],
|
| 260 |
+
)
|
| 261 |
+
def test_non_fixed_variable_window_indexer(closed, expected_data):
|
| 262 |
+
index = date_range("2020", periods=10)
|
| 263 |
+
df = DataFrame(range(10), index=index)
|
| 264 |
+
offset = BusinessDay(1)
|
| 265 |
+
indexer = VariableOffsetWindowIndexer(index=index, offset=offset)
|
| 266 |
+
result = df.rolling(indexer, closed=closed).sum()
|
| 267 |
+
expected = DataFrame(expected_data, index=index)
|
| 268 |
+
tm.assert_frame_equal(result, expected)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def test_variableoffsetwindowindexer_not_dti():
|
| 272 |
+
# GH 54379
|
| 273 |
+
with pytest.raises(ValueError, match="index must be a DatetimeIndex."):
|
| 274 |
+
VariableOffsetWindowIndexer(index="foo", offset=BusinessDay(1))
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def test_variableoffsetwindowindexer_not_offset():
|
| 278 |
+
# GH 54379
|
| 279 |
+
idx = date_range("2020", periods=10)
|
| 280 |
+
with pytest.raises(ValueError, match="offset must be a DateOffset-like object."):
|
| 281 |
+
VariableOffsetWindowIndexer(index=idx, offset="foo")
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def test_fixed_forward_indexer_count(step):
|
| 285 |
+
# GH: 35579
|
| 286 |
+
df = DataFrame({"b": [None, None, None, 7]})
|
| 287 |
+
indexer = FixedForwardWindowIndexer(window_size=2)
|
| 288 |
+
result = df.rolling(window=indexer, min_periods=0, step=step).count()
|
| 289 |
+
expected = DataFrame({"b": [0.0, 0.0, 1.0, 1.0]})[::step]
|
| 290 |
+
tm.assert_frame_equal(result, expected)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
@pytest.mark.parametrize(
|
| 294 |
+
("end_value", "values"), [(1, [0.0, 1, 1, 3, 2]), (-1, [0.0, 1, 0, 3, 1])]
|
| 295 |
+
)
|
| 296 |
+
@pytest.mark.parametrize(("func", "args"), [("median", []), ("quantile", [0.5])])
|
| 297 |
+
def test_indexer_quantile_sum(end_value, values, func, args):
|
| 298 |
+
# GH 37153
|
| 299 |
+
class CustomIndexer(BaseIndexer):
|
| 300 |
+
def get_window_bounds(self, num_values, min_periods, center, closed, step):
|
| 301 |
+
start = np.empty(num_values, dtype=np.int64)
|
| 302 |
+
end = np.empty(num_values, dtype=np.int64)
|
| 303 |
+
for i in range(num_values):
|
| 304 |
+
if self.use_expanding[i]:
|
| 305 |
+
start[i] = 0
|
| 306 |
+
end[i] = max(i + end_value, 1)
|
| 307 |
+
else:
|
| 308 |
+
start[i] = i
|
| 309 |
+
end[i] = i + self.window_size
|
| 310 |
+
return start, end
|
| 311 |
+
|
| 312 |
+
use_expanding = [True, False, True, False, True]
|
| 313 |
+
df = DataFrame({"values": range(5)})
|
| 314 |
+
|
| 315 |
+
indexer = CustomIndexer(window_size=1, use_expanding=use_expanding)
|
| 316 |
+
result = getattr(df.rolling(indexer), func)(*args)
|
| 317 |
+
expected = DataFrame({"values": values})
|
| 318 |
+
tm.assert_frame_equal(result, expected)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
@pytest.mark.parametrize(
|
| 322 |
+
"indexer_class", [FixedWindowIndexer, FixedForwardWindowIndexer, ExpandingIndexer]
|
| 323 |
+
)
|
| 324 |
+
@pytest.mark.parametrize("window_size", [1, 2, 12])
|
| 325 |
+
@pytest.mark.parametrize(
|
| 326 |
+
"df_data",
|
| 327 |
+
[
|
| 328 |
+
{"a": [1, 1], "b": [0, 1]},
|
| 329 |
+
{"a": [1, 2], "b": [0, 1]},
|
| 330 |
+
{"a": [1] * 16, "b": [np.nan, 1, 2, np.nan] + list(range(4, 16))},
|
| 331 |
+
],
|
| 332 |
+
)
|
| 333 |
+
def test_indexers_are_reusable_after_groupby_rolling(
|
| 334 |
+
indexer_class, window_size, df_data
|
| 335 |
+
):
|
| 336 |
+
# GH 43267
|
| 337 |
+
df = DataFrame(df_data)
|
| 338 |
+
num_trials = 3
|
| 339 |
+
indexer = indexer_class(window_size=window_size)
|
| 340 |
+
original_window_size = indexer.window_size
|
| 341 |
+
for i in range(num_trials):
|
| 342 |
+
df.groupby("a")["b"].rolling(window=indexer, min_periods=1).mean()
|
| 343 |
+
assert indexer.window_size == original_window_size
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
@pytest.mark.parametrize(
|
| 347 |
+
"window_size, num_values, expected_start, expected_end",
|
| 348 |
+
[
|
| 349 |
+
(1, 1, [0], [1]),
|
| 350 |
+
(1, 2, [0, 1], [1, 2]),
|
| 351 |
+
(2, 1, [0], [1]),
|
| 352 |
+
(2, 2, [0, 1], [2, 2]),
|
| 353 |
+
(5, 12, range(12), list(range(5, 12)) + [12] * 5),
|
| 354 |
+
(12, 5, range(5), [5] * 5),
|
| 355 |
+
(0, 0, np.array([]), np.array([])),
|
| 356 |
+
(1, 0, np.array([]), np.array([])),
|
| 357 |
+
(0, 1, [0], [0]),
|
| 358 |
+
],
|
| 359 |
+
)
|
| 360 |
+
def test_fixed_forward_indexer_bounds(
|
| 361 |
+
window_size, num_values, expected_start, expected_end, step
|
| 362 |
+
):
|
| 363 |
+
# GH 43267
|
| 364 |
+
indexer = FixedForwardWindowIndexer(window_size=window_size)
|
| 365 |
+
start, end = indexer.get_window_bounds(num_values=num_values, step=step)
|
| 366 |
+
|
| 367 |
+
tm.assert_numpy_array_equal(
|
| 368 |
+
start, np.array(expected_start[::step]), check_dtype=False
|
| 369 |
+
)
|
| 370 |
+
tm.assert_numpy_array_equal(end, np.array(expected_end[::step]), check_dtype=False)
|
| 371 |
+
assert len(start) == len(end)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
@pytest.mark.parametrize(
|
| 375 |
+
"df, window_size, expected",
|
| 376 |
+
[
|
| 377 |
+
(
|
| 378 |
+
DataFrame({"b": [0, 1, 2], "a": [1, 2, 2]}),
|
| 379 |
+
2,
|
| 380 |
+
Series(
|
| 381 |
+
[0, 1.5, 2.0],
|
| 382 |
+
index=MultiIndex.from_arrays([[1, 2, 2], range(3)], names=["a", None]),
|
| 383 |
+
name="b",
|
| 384 |
+
dtype=np.float64,
|
| 385 |
+
),
|
| 386 |
+
),
|
| 387 |
+
(
|
| 388 |
+
DataFrame(
|
| 389 |
+
{
|
| 390 |
+
"b": [np.nan, 1, 2, np.nan] + list(range(4, 18)),
|
| 391 |
+
"a": [1] * 7 + [2] * 11,
|
| 392 |
+
"c": range(18),
|
| 393 |
+
}
|
| 394 |
+
),
|
| 395 |
+
12,
|
| 396 |
+
Series(
|
| 397 |
+
[
|
| 398 |
+
3.6,
|
| 399 |
+
3.6,
|
| 400 |
+
4.25,
|
| 401 |
+
5.0,
|
| 402 |
+
5.0,
|
| 403 |
+
5.5,
|
| 404 |
+
6.0,
|
| 405 |
+
12.0,
|
| 406 |
+
12.5,
|
| 407 |
+
13.0,
|
| 408 |
+
13.5,
|
| 409 |
+
14.0,
|
| 410 |
+
14.5,
|
| 411 |
+
15.0,
|
| 412 |
+
15.5,
|
| 413 |
+
16.0,
|
| 414 |
+
16.5,
|
| 415 |
+
17.0,
|
| 416 |
+
],
|
| 417 |
+
index=MultiIndex.from_arrays(
|
| 418 |
+
[[1] * 7 + [2] * 11, range(18)], names=["a", None]
|
| 419 |
+
),
|
| 420 |
+
name="b",
|
| 421 |
+
dtype=np.float64,
|
| 422 |
+
),
|
| 423 |
+
),
|
| 424 |
+
],
|
| 425 |
+
)
|
| 426 |
+
def test_rolling_groupby_with_fixed_forward_specific(df, window_size, expected):
|
| 427 |
+
# GH 43267
|
| 428 |
+
indexer = FixedForwardWindowIndexer(window_size=window_size)
|
| 429 |
+
result = df.groupby("a")["b"].rolling(window=indexer, min_periods=1).mean()
|
| 430 |
+
tm.assert_series_equal(result, expected)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
@pytest.mark.parametrize(
|
| 434 |
+
"group_keys",
|
| 435 |
+
[
|
| 436 |
+
(1,),
|
| 437 |
+
(1, 2),
|
| 438 |
+
(2, 1),
|
| 439 |
+
(1, 1, 2),
|
| 440 |
+
(1, 2, 1),
|
| 441 |
+
(1, 1, 2, 2),
|
| 442 |
+
(1, 2, 3, 2, 3),
|
| 443 |
+
(1, 1, 2) * 4,
|
| 444 |
+
(1, 2, 3) * 5,
|
| 445 |
+
],
|
| 446 |
+
)
|
| 447 |
+
@pytest.mark.parametrize("window_size", [1, 2, 3, 4, 5, 8, 20])
|
| 448 |
+
def test_rolling_groupby_with_fixed_forward_many(group_keys, window_size):
|
| 449 |
+
# GH 43267
|
| 450 |
+
df = DataFrame(
|
| 451 |
+
{
|
| 452 |
+
"a": np.array(list(group_keys)),
|
| 453 |
+
"b": np.arange(len(group_keys), dtype=np.float64) + 17,
|
| 454 |
+
"c": np.arange(len(group_keys), dtype=np.int64),
|
| 455 |
+
}
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
indexer = FixedForwardWindowIndexer(window_size=window_size)
|
| 459 |
+
result = df.groupby("a")["b"].rolling(window=indexer, min_periods=1).sum()
|
| 460 |
+
result.index.names = ["a", "c"]
|
| 461 |
+
|
| 462 |
+
groups = df.groupby("a")[["a", "b", "c"]]
|
| 463 |
+
manual = concat(
|
| 464 |
+
[
|
| 465 |
+
g.assign(
|
| 466 |
+
b=[
|
| 467 |
+
g["b"].iloc[i : i + window_size].sum(min_count=1)
|
| 468 |
+
for i in range(len(g))
|
| 469 |
+
]
|
| 470 |
+
)
|
| 471 |
+
for _, g in groups
|
| 472 |
+
]
|
| 473 |
+
)
|
| 474 |
+
manual = manual.set_index(["a", "c"])["b"]
|
| 475 |
+
|
| 476 |
+
tm.assert_series_equal(result, manual)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def test_unequal_start_end_bounds():
|
| 480 |
+
class CustomIndexer(BaseIndexer):
|
| 481 |
+
def get_window_bounds(self, num_values, min_periods, center, closed, step):
|
| 482 |
+
return np.array([1]), np.array([1, 2])
|
| 483 |
+
|
| 484 |
+
indexer = CustomIndexer()
|
| 485 |
+
roll = Series(1).rolling(indexer)
|
| 486 |
+
match = "start"
|
| 487 |
+
with pytest.raises(ValueError, match=match):
|
| 488 |
+
roll.mean()
|
| 489 |
+
|
| 490 |
+
with pytest.raises(ValueError, match=match):
|
| 491 |
+
next(iter(roll))
|
| 492 |
+
|
| 493 |
+
with pytest.raises(ValueError, match=match):
|
| 494 |
+
roll.corr(pairwise=True)
|
| 495 |
+
|
| 496 |
+
with pytest.raises(ValueError, match=match):
|
| 497 |
+
roll.cov(pairwise=True)
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def test_unequal_bounds_to_object():
|
| 501 |
+
# GH 44470
|
| 502 |
+
class CustomIndexer(BaseIndexer):
|
| 503 |
+
def get_window_bounds(self, num_values, min_periods, center, closed, step):
|
| 504 |
+
return np.array([1]), np.array([2])
|
| 505 |
+
|
| 506 |
+
indexer = CustomIndexer()
|
| 507 |
+
roll = Series([1, 1]).rolling(indexer)
|
| 508 |
+
match = "start and end"
|
| 509 |
+
with pytest.raises(ValueError, match=match):
|
| 510 |
+
roll.mean()
|
| 511 |
+
|
| 512 |
+
with pytest.raises(ValueError, match=match):
|
| 513 |
+
next(iter(roll))
|
| 514 |
+
|
| 515 |
+
with pytest.raises(ValueError, match=match):
|
| 516 |
+
roll.corr(pairwise=True)
|
| 517 |
+
|
| 518 |
+
with pytest.raises(ValueError, match=match):
|
| 519 |
+
roll.cov(pairwise=True)
|
shared/package-files/17/1745088ef9845a0e712982696a64a0fc9eb238f1f4c24a719fb5fa3a87c42f05/objects.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A declarative, object-oriented interface for creating statistical graphics.
|
| 3 |
+
|
| 4 |
+
The seaborn.objects namespace contains a number of classes that can be composed
|
| 5 |
+
together to build a customized visualization.
|
| 6 |
+
|
| 7 |
+
The main object is :class:`Plot`, which is the starting point for all figures.
|
| 8 |
+
Pass :class:`Plot` a dataset and specify assignments from its variables to
|
| 9 |
+
roles in the plot. Build up the visualization by calling its methods.
|
| 10 |
+
|
| 11 |
+
There are four other general types of objects in this interface:
|
| 12 |
+
|
| 13 |
+
- :class:`Mark` subclasses, which create matplotlib artists for visualization
|
| 14 |
+
- :class:`Stat` subclasses, which apply statistical transforms before plotting
|
| 15 |
+
- :class:`Move` subclasses, which make further adjustments to reduce overplotting
|
| 16 |
+
|
| 17 |
+
These classes are passed to :meth:`Plot.add` to define a layer in the plot.
|
| 18 |
+
Each layer has a :class:`Mark` and optional :class:`Stat` and/or :class:`Move`.
|
| 19 |
+
Plots can have multiple layers.
|
| 20 |
+
|
| 21 |
+
The other general type of object is a :class:`Scale` subclass, which provide an
|
| 22 |
+
interface for controlling the mappings between data values and visual properties.
|
| 23 |
+
Pass :class:`Scale` objects to :meth:`Plot.scale`.
|
| 24 |
+
|
| 25 |
+
See the documentation for other :class:`Plot` methods to learn about the many
|
| 26 |
+
ways that a plot can be enhanced and customized.
|
| 27 |
+
|
| 28 |
+
"""
|
| 29 |
+
from seaborn._core.plot import Plot # noqa: F401
|
| 30 |
+
|
| 31 |
+
from seaborn._marks.base import Mark # noqa: F401
|
| 32 |
+
from seaborn._marks.area import Area, Band # noqa: F401
|
| 33 |
+
from seaborn._marks.bar import Bar, Bars # noqa: F401
|
| 34 |
+
from seaborn._marks.dot import Dot, Dots # noqa: F401
|
| 35 |
+
from seaborn._marks.line import Dash, Line, Lines, Path, Paths, Range # noqa: F401
|
| 36 |
+
from seaborn._marks.text import Text # noqa: F401
|
| 37 |
+
|
| 38 |
+
from seaborn._stats.base import Stat # noqa: F401
|
| 39 |
+
from seaborn._stats.aggregation import Agg, Est # noqa: F401
|
| 40 |
+
from seaborn._stats.counting import Count, Hist # noqa: F401
|
| 41 |
+
from seaborn._stats.density import KDE # noqa: F401
|
| 42 |
+
from seaborn._stats.order import Perc # noqa: F401
|
| 43 |
+
from seaborn._stats.regression import PolyFit # noqa: F401
|
| 44 |
+
|
| 45 |
+
from seaborn._core.moves import Dodge, Jitter, Norm, Shift, Stack, Move # noqa: F401
|
| 46 |
+
|
| 47 |
+
from seaborn._core.scales import ( # noqa: F401
|
| 48 |
+
Boolean, Continuous, Nominal, Temporal, Scale
|
| 49 |
+
)
|
shared/package-files/17/174d76b7c7645faf65fed700bf67998ff201afbb327c00ee635a5837dd871c6b/anchor.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding: utf-8
|
| 2 |
+
if False: # MYPY
|
| 3 |
+
from typing import Any, Dict, Optional, List, Union, Optional, Iterator # NOQA
|
| 4 |
+
|
| 5 |
+
anchor_attrib = '_yaml_anchor'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Anchor:
|
| 9 |
+
__slots__ = 'value', 'always_dump'
|
| 10 |
+
attrib = anchor_attrib
|
| 11 |
+
|
| 12 |
+
def __init__(self):
|
| 13 |
+
# type: () -> None
|
| 14 |
+
self.value = None
|
| 15 |
+
self.always_dump = False
|
| 16 |
+
|
| 17 |
+
def __repr__(self):
|
| 18 |
+
# type: () -> Any
|
| 19 |
+
ad = ', (always dump)' if self.always_dump else ""
|
| 20 |
+
return 'Anchor({!r}{})'.format(self.value, ad)
|
shared/package-files/17/17cf0752407210fe07e9c27f213bc87b46bf4f5047d8939d472b0c0aed57227d/test_defchararray.py
ADDED
|
@@ -0,0 +1,686 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from numpy.core.multiarray import _vec_string
|
| 5 |
+
from numpy.testing import (
|
| 6 |
+
assert_, assert_equal, assert_array_equal, assert_raises,
|
| 7 |
+
assert_raises_regex
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
kw_unicode_true = {'unicode': True} # make 2to3 work properly
|
| 11 |
+
kw_unicode_false = {'unicode': False}
|
| 12 |
+
|
| 13 |
+
class TestBasic:
|
| 14 |
+
def test_from_object_array(self):
|
| 15 |
+
A = np.array([['abc', 2],
|
| 16 |
+
['long ', '0123456789']], dtype='O')
|
| 17 |
+
B = np.char.array(A)
|
| 18 |
+
assert_equal(B.dtype.itemsize, 10)
|
| 19 |
+
assert_array_equal(B, [[b'abc', b'2'],
|
| 20 |
+
[b'long', b'0123456789']])
|
| 21 |
+
|
| 22 |
+
def test_from_object_array_unicode(self):
|
| 23 |
+
A = np.array([['abc', 'Sigma \u03a3'],
|
| 24 |
+
['long ', '0123456789']], dtype='O')
|
| 25 |
+
assert_raises(ValueError, np.char.array, (A,))
|
| 26 |
+
B = np.char.array(A, **kw_unicode_true)
|
| 27 |
+
assert_equal(B.dtype.itemsize, 10 * np.array('a', 'U').dtype.itemsize)
|
| 28 |
+
assert_array_equal(B, [['abc', 'Sigma \u03a3'],
|
| 29 |
+
['long', '0123456789']])
|
| 30 |
+
|
| 31 |
+
def test_from_string_array(self):
|
| 32 |
+
A = np.array([[b'abc', b'foo'],
|
| 33 |
+
[b'long ', b'0123456789']])
|
| 34 |
+
assert_equal(A.dtype.type, np.bytes_)
|
| 35 |
+
B = np.char.array(A)
|
| 36 |
+
assert_array_equal(B, A)
|
| 37 |
+
assert_equal(B.dtype, A.dtype)
|
| 38 |
+
assert_equal(B.shape, A.shape)
|
| 39 |
+
B[0, 0] = 'changed'
|
| 40 |
+
assert_(B[0, 0] != A[0, 0])
|
| 41 |
+
C = np.char.asarray(A)
|
| 42 |
+
assert_array_equal(C, A)
|
| 43 |
+
assert_equal(C.dtype, A.dtype)
|
| 44 |
+
C[0, 0] = 'changed again'
|
| 45 |
+
assert_(C[0, 0] != B[0, 0])
|
| 46 |
+
assert_(C[0, 0] == A[0, 0])
|
| 47 |
+
|
| 48 |
+
def test_from_unicode_array(self):
|
| 49 |
+
A = np.array([['abc', 'Sigma \u03a3'],
|
| 50 |
+
['long ', '0123456789']])
|
| 51 |
+
assert_equal(A.dtype.type, np.str_)
|
| 52 |
+
B = np.char.array(A)
|
| 53 |
+
assert_array_equal(B, A)
|
| 54 |
+
assert_equal(B.dtype, A.dtype)
|
| 55 |
+
assert_equal(B.shape, A.shape)
|
| 56 |
+
B = np.char.array(A, **kw_unicode_true)
|
| 57 |
+
assert_array_equal(B, A)
|
| 58 |
+
assert_equal(B.dtype, A.dtype)
|
| 59 |
+
assert_equal(B.shape, A.shape)
|
| 60 |
+
|
| 61 |
+
def fail():
|
| 62 |
+
np.char.array(A, **kw_unicode_false)
|
| 63 |
+
|
| 64 |
+
assert_raises(UnicodeEncodeError, fail)
|
| 65 |
+
|
| 66 |
+
def test_unicode_upconvert(self):
|
| 67 |
+
A = np.char.array(['abc'])
|
| 68 |
+
B = np.char.array(['\u03a3'])
|
| 69 |
+
assert_(issubclass((A + B).dtype.type, np.str_))
|
| 70 |
+
|
| 71 |
+
def test_from_string(self):
|
| 72 |
+
A = np.char.array(b'abc')
|
| 73 |
+
assert_equal(len(A), 1)
|
| 74 |
+
assert_equal(len(A[0]), 3)
|
| 75 |
+
assert_(issubclass(A.dtype.type, np.bytes_))
|
| 76 |
+
|
| 77 |
+
def test_from_unicode(self):
|
| 78 |
+
A = np.char.array('\u03a3')
|
| 79 |
+
assert_equal(len(A), 1)
|
| 80 |
+
assert_equal(len(A[0]), 1)
|
| 81 |
+
assert_equal(A.itemsize, 4)
|
| 82 |
+
assert_(issubclass(A.dtype.type, np.str_))
|
| 83 |
+
|
| 84 |
+
class TestVecString:
|
| 85 |
+
def test_non_existent_method(self):
|
| 86 |
+
|
| 87 |
+
def fail():
|
| 88 |
+
_vec_string('a', np.bytes_, 'bogus')
|
| 89 |
+
|
| 90 |
+
assert_raises(AttributeError, fail)
|
| 91 |
+
|
| 92 |
+
def test_non_string_array(self):
|
| 93 |
+
|
| 94 |
+
def fail():
|
| 95 |
+
_vec_string(1, np.bytes_, 'strip')
|
| 96 |
+
|
| 97 |
+
assert_raises(TypeError, fail)
|
| 98 |
+
|
| 99 |
+
def test_invalid_args_tuple(self):
|
| 100 |
+
|
| 101 |
+
def fail():
|
| 102 |
+
_vec_string(['a'], np.bytes_, 'strip', 1)
|
| 103 |
+
|
| 104 |
+
assert_raises(TypeError, fail)
|
| 105 |
+
|
| 106 |
+
def test_invalid_type_descr(self):
|
| 107 |
+
|
| 108 |
+
def fail():
|
| 109 |
+
_vec_string(['a'], 'BOGUS', 'strip')
|
| 110 |
+
|
| 111 |
+
assert_raises(TypeError, fail)
|
| 112 |
+
|
| 113 |
+
def test_invalid_function_args(self):
|
| 114 |
+
|
| 115 |
+
def fail():
|
| 116 |
+
_vec_string(['a'], np.bytes_, 'strip', (1,))
|
| 117 |
+
|
| 118 |
+
assert_raises(TypeError, fail)
|
| 119 |
+
|
| 120 |
+
def test_invalid_result_type(self):
|
| 121 |
+
|
| 122 |
+
def fail():
|
| 123 |
+
_vec_string(['a'], np.int_, 'strip')
|
| 124 |
+
|
| 125 |
+
assert_raises(TypeError, fail)
|
| 126 |
+
|
| 127 |
+
def test_broadcast_error(self):
|
| 128 |
+
|
| 129 |
+
def fail():
|
| 130 |
+
_vec_string([['abc', 'def']], np.int_, 'find', (['a', 'd', 'j'],))
|
| 131 |
+
|
| 132 |
+
assert_raises(ValueError, fail)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class TestWhitespace:
|
| 136 |
+
def setup_method(self):
|
| 137 |
+
self.A = np.array([['abc ', '123 '],
|
| 138 |
+
['789 ', 'xyz ']]).view(np.chararray)
|
| 139 |
+
self.B = np.array([['abc', '123'],
|
| 140 |
+
['789', 'xyz']]).view(np.chararray)
|
| 141 |
+
|
| 142 |
+
def test1(self):
|
| 143 |
+
assert_(np.all(self.A == self.B))
|
| 144 |
+
assert_(np.all(self.A >= self.B))
|
| 145 |
+
assert_(np.all(self.A <= self.B))
|
| 146 |
+
assert_(not np.any(self.A > self.B))
|
| 147 |
+
assert_(not np.any(self.A < self.B))
|
| 148 |
+
assert_(not np.any(self.A != self.B))
|
| 149 |
+
|
| 150 |
+
class TestChar:
|
| 151 |
+
def setup_method(self):
|
| 152 |
+
self.A = np.array('abc1', dtype='c').view(np.chararray)
|
| 153 |
+
|
| 154 |
+
def test_it(self):
|
| 155 |
+
assert_equal(self.A.shape, (4,))
|
| 156 |
+
assert_equal(self.A.upper()[:2].tobytes(), b'AB')
|
| 157 |
+
|
| 158 |
+
class TestComparisons:
|
| 159 |
+
def setup_method(self):
|
| 160 |
+
self.A = np.array([['abc', '123'],
|
| 161 |
+
['789', 'xyz']]).view(np.chararray)
|
| 162 |
+
self.B = np.array([['efg', '123 '],
|
| 163 |
+
['051', 'tuv']]).view(np.chararray)
|
| 164 |
+
|
| 165 |
+
def test_not_equal(self):
|
| 166 |
+
assert_array_equal((self.A != self.B), [[True, False], [True, True]])
|
| 167 |
+
|
| 168 |
+
def test_equal(self):
|
| 169 |
+
assert_array_equal((self.A == self.B), [[False, True], [False, False]])
|
| 170 |
+
|
| 171 |
+
def test_greater_equal(self):
|
| 172 |
+
assert_array_equal((self.A >= self.B), [[False, True], [True, True]])
|
| 173 |
+
|
| 174 |
+
def test_less_equal(self):
|
| 175 |
+
assert_array_equal((self.A <= self.B), [[True, True], [False, False]])
|
| 176 |
+
|
| 177 |
+
def test_greater(self):
|
| 178 |
+
assert_array_equal((self.A > self.B), [[False, False], [True, True]])
|
| 179 |
+
|
| 180 |
+
def test_less(self):
|
| 181 |
+
assert_array_equal((self.A < self.B), [[True, False], [False, False]])
|
| 182 |
+
|
| 183 |
+
def test_type(self):
|
| 184 |
+
out1 = np.char.equal(self.A, self.B)
|
| 185 |
+
out2 = np.char.equal('a', 'a')
|
| 186 |
+
assert_(isinstance(out1, np.ndarray))
|
| 187 |
+
assert_(isinstance(out2, np.ndarray))
|
| 188 |
+
|
| 189 |
+
class TestComparisonsMixed1(TestComparisons):
|
| 190 |
+
"""Ticket #1276"""
|
| 191 |
+
|
| 192 |
+
def setup_method(self):
|
| 193 |
+
TestComparisons.setup_method(self)
|
| 194 |
+
self.B = np.array([['efg', '123 '],
|
| 195 |
+
['051', 'tuv']], np.str_).view(np.chararray)
|
| 196 |
+
|
| 197 |
+
class TestComparisonsMixed2(TestComparisons):
|
| 198 |
+
"""Ticket #1276"""
|
| 199 |
+
|
| 200 |
+
def setup_method(self):
|
| 201 |
+
TestComparisons.setup_method(self)
|
| 202 |
+
self.A = np.array([['abc', '123'],
|
| 203 |
+
['789', 'xyz']], np.str_).view(np.chararray)
|
| 204 |
+
|
| 205 |
+
class TestInformation:
|
| 206 |
+
def setup_method(self):
|
| 207 |
+
self.A = np.array([[' abc ', ''],
|
| 208 |
+
['12345', 'MixedCase'],
|
| 209 |
+
['123 \t 345 \0 ', 'UPPER']]).view(np.chararray)
|
| 210 |
+
self.B = np.array([[' \u03a3 ', ''],
|
| 211 |
+
['12345', 'MixedCase'],
|
| 212 |
+
['123 \t 345 \0 ', 'UPPER']]).view(np.chararray)
|
| 213 |
+
|
| 214 |
+
def test_len(self):
|
| 215 |
+
assert_(issubclass(np.char.str_len(self.A).dtype.type, np.integer))
|
| 216 |
+
assert_array_equal(np.char.str_len(self.A), [[5, 0], [5, 9], [12, 5]])
|
| 217 |
+
assert_array_equal(np.char.str_len(self.B), [[3, 0], [5, 9], [12, 5]])
|
| 218 |
+
|
| 219 |
+
def test_count(self):
|
| 220 |
+
assert_(issubclass(self.A.count('').dtype.type, np.integer))
|
| 221 |
+
assert_array_equal(self.A.count('a'), [[1, 0], [0, 1], [0, 0]])
|
| 222 |
+
assert_array_equal(self.A.count('123'), [[0, 0], [1, 0], [1, 0]])
|
| 223 |
+
# Python doesn't seem to like counting NULL characters
|
| 224 |
+
# assert_array_equal(self.A.count('\0'), [[0, 0], [0, 0], [1, 0]])
|
| 225 |
+
assert_array_equal(self.A.count('a', 0, 2), [[1, 0], [0, 0], [0, 0]])
|
| 226 |
+
assert_array_equal(self.B.count('a'), [[0, 0], [0, 1], [0, 0]])
|
| 227 |
+
assert_array_equal(self.B.count('123'), [[0, 0], [1, 0], [1, 0]])
|
| 228 |
+
# assert_array_equal(self.B.count('\0'), [[0, 0], [0, 0], [1, 0]])
|
| 229 |
+
|
| 230 |
+
def test_endswith(self):
|
| 231 |
+
assert_(issubclass(self.A.endswith('').dtype.type, np.bool_))
|
| 232 |
+
assert_array_equal(self.A.endswith(' '), [[1, 0], [0, 0], [1, 0]])
|
| 233 |
+
assert_array_equal(self.A.endswith('3', 0, 3), [[0, 0], [1, 0], [1, 0]])
|
| 234 |
+
|
| 235 |
+
def fail():
|
| 236 |
+
self.A.endswith('3', 'fdjk')
|
| 237 |
+
|
| 238 |
+
assert_raises(TypeError, fail)
|
| 239 |
+
|
| 240 |
+
def test_find(self):
|
| 241 |
+
assert_(issubclass(self.A.find('a').dtype.type, np.integer))
|
| 242 |
+
assert_array_equal(self.A.find('a'), [[1, -1], [-1, 6], [-1, -1]])
|
| 243 |
+
assert_array_equal(self.A.find('3'), [[-1, -1], [2, -1], [2, -1]])
|
| 244 |
+
assert_array_equal(self.A.find('a', 0, 2), [[1, -1], [-1, -1], [-1, -1]])
|
| 245 |
+
assert_array_equal(self.A.find(['1', 'P']), [[-1, -1], [0, -1], [0, 1]])
|
| 246 |
+
|
| 247 |
+
def test_index(self):
|
| 248 |
+
|
| 249 |
+
def fail():
|
| 250 |
+
self.A.index('a')
|
| 251 |
+
|
| 252 |
+
assert_raises(ValueError, fail)
|
| 253 |
+
assert_(np.char.index('abcba', 'b') == 1)
|
| 254 |
+
assert_(issubclass(np.char.index('abcba', 'b').dtype.type, np.integer))
|
| 255 |
+
|
| 256 |
+
def test_isalnum(self):
|
| 257 |
+
assert_(issubclass(self.A.isalnum().dtype.type, np.bool_))
|
| 258 |
+
assert_array_equal(self.A.isalnum(), [[False, False], [True, True], [False, True]])
|
| 259 |
+
|
| 260 |
+
def test_isalpha(self):
|
| 261 |
+
assert_(issubclass(self.A.isalpha().dtype.type, np.bool_))
|
| 262 |
+
assert_array_equal(self.A.isalpha(), [[False, False], [False, True], [False, True]])
|
| 263 |
+
|
| 264 |
+
def test_isdigit(self):
|
| 265 |
+
assert_(issubclass(self.A.isdigit().dtype.type, np.bool_))
|
| 266 |
+
assert_array_equal(self.A.isdigit(), [[False, False], [True, False], [False, False]])
|
| 267 |
+
|
| 268 |
+
def test_islower(self):
|
| 269 |
+
assert_(issubclass(self.A.islower().dtype.type, np.bool_))
|
| 270 |
+
assert_array_equal(self.A.islower(), [[True, False], [False, False], [False, False]])
|
| 271 |
+
|
| 272 |
+
def test_isspace(self):
|
| 273 |
+
assert_(issubclass(self.A.isspace().dtype.type, np.bool_))
|
| 274 |
+
assert_array_equal(self.A.isspace(), [[False, False], [False, False], [False, False]])
|
| 275 |
+
|
| 276 |
+
def test_istitle(self):
|
| 277 |
+
assert_(issubclass(self.A.istitle().dtype.type, np.bool_))
|
| 278 |
+
assert_array_equal(self.A.istitle(), [[False, False], [False, False], [False, False]])
|
| 279 |
+
|
| 280 |
+
def test_isupper(self):
|
| 281 |
+
assert_(issubclass(self.A.isupper().dtype.type, np.bool_))
|
| 282 |
+
assert_array_equal(self.A.isupper(), [[False, False], [False, False], [False, True]])
|
| 283 |
+
|
| 284 |
+
def test_rfind(self):
|
| 285 |
+
assert_(issubclass(self.A.rfind('a').dtype.type, np.integer))
|
| 286 |
+
assert_array_equal(self.A.rfind('a'), [[1, -1], [-1, 6], [-1, -1]])
|
| 287 |
+
assert_array_equal(self.A.rfind('3'), [[-1, -1], [2, -1], [6, -1]])
|
| 288 |
+
assert_array_equal(self.A.rfind('a', 0, 2), [[1, -1], [-1, -1], [-1, -1]])
|
| 289 |
+
assert_array_equal(self.A.rfind(['1', 'P']), [[-1, -1], [0, -1], [0, 2]])
|
| 290 |
+
|
| 291 |
+
def test_rindex(self):
|
| 292 |
+
|
| 293 |
+
def fail():
|
| 294 |
+
self.A.rindex('a')
|
| 295 |
+
|
| 296 |
+
assert_raises(ValueError, fail)
|
| 297 |
+
assert_(np.char.rindex('abcba', 'b') == 3)
|
| 298 |
+
assert_(issubclass(np.char.rindex('abcba', 'b').dtype.type, np.integer))
|
| 299 |
+
|
| 300 |
+
def test_startswith(self):
|
| 301 |
+
assert_(issubclass(self.A.startswith('').dtype.type, np.bool_))
|
| 302 |
+
assert_array_equal(self.A.startswith(' '), [[1, 0], [0, 0], [0, 0]])
|
| 303 |
+
assert_array_equal(self.A.startswith('1', 0, 3), [[0, 0], [1, 0], [1, 0]])
|
| 304 |
+
|
| 305 |
+
def fail():
|
| 306 |
+
self.A.startswith('3', 'fdjk')
|
| 307 |
+
|
| 308 |
+
assert_raises(TypeError, fail)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class TestMethods:
|
| 312 |
+
def setup_method(self):
|
| 313 |
+
self.A = np.array([[' abc ', ''],
|
| 314 |
+
['12345', 'MixedCase'],
|
| 315 |
+
['123 \t 345 \0 ', 'UPPER']],
|
| 316 |
+
dtype='S').view(np.chararray)
|
| 317 |
+
self.B = np.array([[' \u03a3 ', ''],
|
| 318 |
+
['12345', 'MixedCase'],
|
| 319 |
+
['123 \t 345 \0 ', 'UPPER']]).view(np.chararray)
|
| 320 |
+
|
| 321 |
+
def test_capitalize(self):
|
| 322 |
+
tgt = [[b' abc ', b''],
|
| 323 |
+
[b'12345', b'Mixedcase'],
|
| 324 |
+
[b'123 \t 345 \0 ', b'Upper']]
|
| 325 |
+
assert_(issubclass(self.A.capitalize().dtype.type, np.bytes_))
|
| 326 |
+
assert_array_equal(self.A.capitalize(), tgt)
|
| 327 |
+
|
| 328 |
+
tgt = [[' \u03c3 ', ''],
|
| 329 |
+
['12345', 'Mixedcase'],
|
| 330 |
+
['123 \t 345 \0 ', 'Upper']]
|
| 331 |
+
assert_(issubclass(self.B.capitalize().dtype.type, np.str_))
|
| 332 |
+
assert_array_equal(self.B.capitalize(), tgt)
|
| 333 |
+
|
| 334 |
+
def test_center(self):
|
| 335 |
+
assert_(issubclass(self.A.center(10).dtype.type, np.bytes_))
|
| 336 |
+
C = self.A.center([10, 20])
|
| 337 |
+
assert_array_equal(np.char.str_len(C), [[10, 20], [10, 20], [12, 20]])
|
| 338 |
+
|
| 339 |
+
C = self.A.center(20, b'#')
|
| 340 |
+
assert_(np.all(C.startswith(b'#')))
|
| 341 |
+
assert_(np.all(C.endswith(b'#')))
|
| 342 |
+
|
| 343 |
+
C = np.char.center(b'FOO', [[10, 20], [15, 8]])
|
| 344 |
+
tgt = [[b' FOO ', b' FOO '],
|
| 345 |
+
[b' FOO ', b' FOO ']]
|
| 346 |
+
assert_(issubclass(C.dtype.type, np.bytes_))
|
| 347 |
+
assert_array_equal(C, tgt)
|
| 348 |
+
|
| 349 |
+
def test_decode(self):
|
| 350 |
+
A = np.char.array([b'\\u03a3'])
|
| 351 |
+
assert_(A.decode('unicode-escape')[0] == '\u03a3')
|
| 352 |
+
|
| 353 |
+
def test_encode(self):
|
| 354 |
+
B = self.B.encode('unicode_escape')
|
| 355 |
+
assert_(B[0][0] == str(' \\u03a3 ').encode('latin1'))
|
| 356 |
+
|
| 357 |
+
def test_expandtabs(self):
|
| 358 |
+
T = self.A.expandtabs()
|
| 359 |
+
assert_(T[2, 0] == b'123 345 \0')
|
| 360 |
+
|
| 361 |
+
def test_join(self):
|
| 362 |
+
# NOTE: list(b'123') == [49, 50, 51]
|
| 363 |
+
# so that b','.join(b'123') results to an error on Py3
|
| 364 |
+
A0 = self.A.decode('ascii')
|
| 365 |
+
|
| 366 |
+
A = np.char.join([',', '#'], A0)
|
| 367 |
+
assert_(issubclass(A.dtype.type, np.str_))
|
| 368 |
+
tgt = np.array([[' ,a,b,c, ', ''],
|
| 369 |
+
['1,2,3,4,5', 'M#i#x#e#d#C#a#s#e'],
|
| 370 |
+
['1,2,3, ,\t, ,3,4,5, ,\x00, ', 'U#P#P#E#R']])
|
| 371 |
+
assert_array_equal(np.char.join([',', '#'], A0), tgt)
|
| 372 |
+
|
| 373 |
+
def test_ljust(self):
|
| 374 |
+
assert_(issubclass(self.A.ljust(10).dtype.type, np.bytes_))
|
| 375 |
+
|
| 376 |
+
C = self.A.ljust([10, 20])
|
| 377 |
+
assert_array_equal(np.char.str_len(C), [[10, 20], [10, 20], [12, 20]])
|
| 378 |
+
|
| 379 |
+
C = self.A.ljust(20, b'#')
|
| 380 |
+
assert_array_equal(C.startswith(b'#'), [
|
| 381 |
+
[False, True], [False, False], [False, False]])
|
| 382 |
+
assert_(np.all(C.endswith(b'#')))
|
| 383 |
+
|
| 384 |
+
C = np.char.ljust(b'FOO', [[10, 20], [15, 8]])
|
| 385 |
+
tgt = [[b'FOO ', b'FOO '],
|
| 386 |
+
[b'FOO ', b'FOO ']]
|
| 387 |
+
assert_(issubclass(C.dtype.type, np.bytes_))
|
| 388 |
+
assert_array_equal(C, tgt)
|
| 389 |
+
|
| 390 |
+
def test_lower(self):
|
| 391 |
+
tgt = [[b' abc ', b''],
|
| 392 |
+
[b'12345', b'mixedcase'],
|
| 393 |
+
[b'123 \t 345 \0 ', b'upper']]
|
| 394 |
+
assert_(issubclass(self.A.lower().dtype.type, np.bytes_))
|
| 395 |
+
assert_array_equal(self.A.lower(), tgt)
|
| 396 |
+
|
| 397 |
+
tgt = [[' \u03c3 ', ''],
|
| 398 |
+
['12345', 'mixedcase'],
|
| 399 |
+
['123 \t 345 \0 ', 'upper']]
|
| 400 |
+
assert_(issubclass(self.B.lower().dtype.type, np.str_))
|
| 401 |
+
assert_array_equal(self.B.lower(), tgt)
|
| 402 |
+
|
| 403 |
+
def test_lstrip(self):
|
| 404 |
+
tgt = [[b'abc ', b''],
|
| 405 |
+
[b'12345', b'MixedCase'],
|
| 406 |
+
[b'123 \t 345 \0 ', b'UPPER']]
|
| 407 |
+
assert_(issubclass(self.A.lstrip().dtype.type, np.bytes_))
|
| 408 |
+
assert_array_equal(self.A.lstrip(), tgt)
|
| 409 |
+
|
| 410 |
+
tgt = [[b' abc', b''],
|
| 411 |
+
[b'2345', b'ixedCase'],
|
| 412 |
+
[b'23 \t 345 \x00', b'UPPER']]
|
| 413 |
+
assert_array_equal(self.A.lstrip([b'1', b'M']), tgt)
|
| 414 |
+
|
| 415 |
+
tgt = [['\u03a3 ', ''],
|
| 416 |
+
['12345', 'MixedCase'],
|
| 417 |
+
['123 \t 345 \0 ', 'UPPER']]
|
| 418 |
+
assert_(issubclass(self.B.lstrip().dtype.type, np.str_))
|
| 419 |
+
assert_array_equal(self.B.lstrip(), tgt)
|
| 420 |
+
|
| 421 |
+
def test_partition(self):
|
| 422 |
+
P = self.A.partition([b'3', b'M'])
|
| 423 |
+
tgt = [[(b' abc ', b'', b''), (b'', b'', b'')],
|
| 424 |
+
[(b'12', b'3', b'45'), (b'', b'M', b'ixedCase')],
|
| 425 |
+
[(b'12', b'3', b' \t 345 \0 '), (b'UPPER', b'', b'')]]
|
| 426 |
+
assert_(issubclass(P.dtype.type, np.bytes_))
|
| 427 |
+
assert_array_equal(P, tgt)
|
| 428 |
+
|
| 429 |
+
def test_replace(self):
|
| 430 |
+
R = self.A.replace([b'3', b'a'],
|
| 431 |
+
[b'##########', b'@'])
|
| 432 |
+
tgt = [[b' abc ', b''],
|
| 433 |
+
[b'12##########45', b'MixedC@se'],
|
| 434 |
+
[b'12########## \t ##########45 \x00', b'UPPER']]
|
| 435 |
+
assert_(issubclass(R.dtype.type, np.bytes_))
|
| 436 |
+
assert_array_equal(R, tgt)
|
| 437 |
+
|
| 438 |
+
def test_rjust(self):
|
| 439 |
+
assert_(issubclass(self.A.rjust(10).dtype.type, np.bytes_))
|
| 440 |
+
|
| 441 |
+
C = self.A.rjust([10, 20])
|
| 442 |
+
assert_array_equal(np.char.str_len(C), [[10, 20], [10, 20], [12, 20]])
|
| 443 |
+
|
| 444 |
+
C = self.A.rjust(20, b'#')
|
| 445 |
+
assert_(np.all(C.startswith(b'#')))
|
| 446 |
+
assert_array_equal(C.endswith(b'#'),
|
| 447 |
+
[[False, True], [False, False], [False, False]])
|
| 448 |
+
|
| 449 |
+
C = np.char.rjust(b'FOO', [[10, 20], [15, 8]])
|
| 450 |
+
tgt = [[b' FOO', b' FOO'],
|
| 451 |
+
[b' FOO', b' FOO']]
|
| 452 |
+
assert_(issubclass(C.dtype.type, np.bytes_))
|
| 453 |
+
assert_array_equal(C, tgt)
|
| 454 |
+
|
| 455 |
+
def test_rpartition(self):
|
| 456 |
+
P = self.A.rpartition([b'3', b'M'])
|
| 457 |
+
tgt = [[(b'', b'', b' abc '), (b'', b'', b'')],
|
| 458 |
+
[(b'12', b'3', b'45'), (b'', b'M', b'ixedCase')],
|
| 459 |
+
[(b'123 \t ', b'3', b'45 \0 '), (b'', b'', b'UPPER')]]
|
| 460 |
+
assert_(issubclass(P.dtype.type, np.bytes_))
|
| 461 |
+
assert_array_equal(P, tgt)
|
| 462 |
+
|
| 463 |
+
def test_rsplit(self):
|
| 464 |
+
A = self.A.rsplit(b'3')
|
| 465 |
+
tgt = [[[b' abc '], [b'']],
|
| 466 |
+
[[b'12', b'45'], [b'MixedCase']],
|
| 467 |
+
[[b'12', b' \t ', b'45 \x00 '], [b'UPPER']]]
|
| 468 |
+
assert_(issubclass(A.dtype.type, np.object_))
|
| 469 |
+
assert_equal(A.tolist(), tgt)
|
| 470 |
+
|
| 471 |
+
def test_rstrip(self):
|
| 472 |
+
assert_(issubclass(self.A.rstrip().dtype.type, np.bytes_))
|
| 473 |
+
|
| 474 |
+
tgt = [[b' abc', b''],
|
| 475 |
+
[b'12345', b'MixedCase'],
|
| 476 |
+
[b'123 \t 345', b'UPPER']]
|
| 477 |
+
assert_array_equal(self.A.rstrip(), tgt)
|
| 478 |
+
|
| 479 |
+
tgt = [[b' abc ', b''],
|
| 480 |
+
[b'1234', b'MixedCase'],
|
| 481 |
+
[b'123 \t 345 \x00', b'UPP']
|
| 482 |
+
]
|
| 483 |
+
assert_array_equal(self.A.rstrip([b'5', b'ER']), tgt)
|
| 484 |
+
|
| 485 |
+
tgt = [[' \u03a3', ''],
|
| 486 |
+
['12345', 'MixedCase'],
|
| 487 |
+
['123 \t 345', 'UPPER']]
|
| 488 |
+
assert_(issubclass(self.B.rstrip().dtype.type, np.str_))
|
| 489 |
+
assert_array_equal(self.B.rstrip(), tgt)
|
| 490 |
+
|
| 491 |
+
def test_strip(self):
|
| 492 |
+
tgt = [[b'abc', b''],
|
| 493 |
+
[b'12345', b'MixedCase'],
|
| 494 |
+
[b'123 \t 345', b'UPPER']]
|
| 495 |
+
assert_(issubclass(self.A.strip().dtype.type, np.bytes_))
|
| 496 |
+
assert_array_equal(self.A.strip(), tgt)
|
| 497 |
+
|
| 498 |
+
tgt = [[b' abc ', b''],
|
| 499 |
+
[b'234', b'ixedCas'],
|
| 500 |
+
[b'23 \t 345 \x00', b'UPP']]
|
| 501 |
+
assert_array_equal(self.A.strip([b'15', b'EReM']), tgt)
|
| 502 |
+
|
| 503 |
+
tgt = [['\u03a3', ''],
|
| 504 |
+
['12345', 'MixedCase'],
|
| 505 |
+
['123 \t 345', 'UPPER']]
|
| 506 |
+
assert_(issubclass(self.B.strip().dtype.type, np.str_))
|
| 507 |
+
assert_array_equal(self.B.strip(), tgt)
|
| 508 |
+
|
| 509 |
+
def test_split(self):
|
| 510 |
+
A = self.A.split(b'3')
|
| 511 |
+
tgt = [
|
| 512 |
+
[[b' abc '], [b'']],
|
| 513 |
+
[[b'12', b'45'], [b'MixedCase']],
|
| 514 |
+
[[b'12', b' \t ', b'45 \x00 '], [b'UPPER']]]
|
| 515 |
+
assert_(issubclass(A.dtype.type, np.object_))
|
| 516 |
+
assert_equal(A.tolist(), tgt)
|
| 517 |
+
|
| 518 |
+
def test_splitlines(self):
|
| 519 |
+
A = np.char.array(['abc\nfds\nwer']).splitlines()
|
| 520 |
+
assert_(issubclass(A.dtype.type, np.object_))
|
| 521 |
+
assert_(A.shape == (1,))
|
| 522 |
+
assert_(len(A[0]) == 3)
|
| 523 |
+
|
| 524 |
+
def test_swapcase(self):
|
| 525 |
+
tgt = [[b' ABC ', b''],
|
| 526 |
+
[b'12345', b'mIXEDcASE'],
|
| 527 |
+
[b'123 \t 345 \0 ', b'upper']]
|
| 528 |
+
assert_(issubclass(self.A.swapcase().dtype.type, np.bytes_))
|
| 529 |
+
assert_array_equal(self.A.swapcase(), tgt)
|
| 530 |
+
|
| 531 |
+
tgt = [[' \u03c3 ', ''],
|
| 532 |
+
['12345', 'mIXEDcASE'],
|
| 533 |
+
['123 \t 345 \0 ', 'upper']]
|
| 534 |
+
assert_(issubclass(self.B.swapcase().dtype.type, np.str_))
|
| 535 |
+
assert_array_equal(self.B.swapcase(), tgt)
|
| 536 |
+
|
| 537 |
+
def test_title(self):
|
| 538 |
+
tgt = [[b' Abc ', b''],
|
| 539 |
+
[b'12345', b'Mixedcase'],
|
| 540 |
+
[b'123 \t 345 \0 ', b'Upper']]
|
| 541 |
+
assert_(issubclass(self.A.title().dtype.type, np.bytes_))
|
| 542 |
+
assert_array_equal(self.A.title(), tgt)
|
| 543 |
+
|
| 544 |
+
tgt = [[' \u03a3 ', ''],
|
| 545 |
+
['12345', 'Mixedcase'],
|
| 546 |
+
['123 \t 345 \0 ', 'Upper']]
|
| 547 |
+
assert_(issubclass(self.B.title().dtype.type, np.str_))
|
| 548 |
+
assert_array_equal(self.B.title(), tgt)
|
| 549 |
+
|
| 550 |
+
def test_upper(self):
|
| 551 |
+
tgt = [[b' ABC ', b''],
|
| 552 |
+
[b'12345', b'MIXEDCASE'],
|
| 553 |
+
[b'123 \t 345 \0 ', b'UPPER']]
|
| 554 |
+
assert_(issubclass(self.A.upper().dtype.type, np.bytes_))
|
| 555 |
+
assert_array_equal(self.A.upper(), tgt)
|
| 556 |
+
|
| 557 |
+
tgt = [[' \u03a3 ', ''],
|
| 558 |
+
['12345', 'MIXEDCASE'],
|
| 559 |
+
['123 \t 345 \0 ', 'UPPER']]
|
| 560 |
+
assert_(issubclass(self.B.upper().dtype.type, np.str_))
|
| 561 |
+
assert_array_equal(self.B.upper(), tgt)
|
| 562 |
+
|
| 563 |
+
def test_isnumeric(self):
|
| 564 |
+
|
| 565 |
+
def fail():
|
| 566 |
+
self.A.isnumeric()
|
| 567 |
+
|
| 568 |
+
assert_raises(TypeError, fail)
|
| 569 |
+
assert_(issubclass(self.B.isnumeric().dtype.type, np.bool_))
|
| 570 |
+
assert_array_equal(self.B.isnumeric(), [
|
| 571 |
+
[False, False], [True, False], [False, False]])
|
| 572 |
+
|
| 573 |
+
def test_isdecimal(self):
|
| 574 |
+
|
| 575 |
+
def fail():
|
| 576 |
+
self.A.isdecimal()
|
| 577 |
+
|
| 578 |
+
assert_raises(TypeError, fail)
|
| 579 |
+
assert_(issubclass(self.B.isdecimal().dtype.type, np.bool_))
|
| 580 |
+
assert_array_equal(self.B.isdecimal(), [
|
| 581 |
+
[False, False], [True, False], [False, False]])
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
class TestOperations:
|
| 585 |
+
def setup_method(self):
|
| 586 |
+
self.A = np.array([['abc', '123'],
|
| 587 |
+
['789', 'xyz']]).view(np.chararray)
|
| 588 |
+
self.B = np.array([['efg', '456'],
|
| 589 |
+
['051', 'tuv']]).view(np.chararray)
|
| 590 |
+
|
| 591 |
+
def test_add(self):
|
| 592 |
+
AB = np.array([['abcefg', '123456'],
|
| 593 |
+
['789051', 'xyztuv']]).view(np.chararray)
|
| 594 |
+
assert_array_equal(AB, (self.A + self.B))
|
| 595 |
+
assert_(len((self.A + self.B)[0][0]) == 6)
|
| 596 |
+
|
| 597 |
+
def test_radd(self):
|
| 598 |
+
QA = np.array([['qabc', 'q123'],
|
| 599 |
+
['q789', 'qxyz']]).view(np.chararray)
|
| 600 |
+
assert_array_equal(QA, ('q' + self.A))
|
| 601 |
+
|
| 602 |
+
def test_mul(self):
|
| 603 |
+
A = self.A
|
| 604 |
+
for r in (2, 3, 5, 7, 197):
|
| 605 |
+
Ar = np.array([[A[0, 0]*r, A[0, 1]*r],
|
| 606 |
+
[A[1, 0]*r, A[1, 1]*r]]).view(np.chararray)
|
| 607 |
+
|
| 608 |
+
assert_array_equal(Ar, (self.A * r))
|
| 609 |
+
|
| 610 |
+
for ob in [object(), 'qrs']:
|
| 611 |
+
with assert_raises_regex(ValueError,
|
| 612 |
+
'Can only multiply by integers'):
|
| 613 |
+
A*ob
|
| 614 |
+
|
| 615 |
+
def test_rmul(self):
|
| 616 |
+
A = self.A
|
| 617 |
+
for r in (2, 3, 5, 7, 197):
|
| 618 |
+
Ar = np.array([[A[0, 0]*r, A[0, 1]*r],
|
| 619 |
+
[A[1, 0]*r, A[1, 1]*r]]).view(np.chararray)
|
| 620 |
+
assert_array_equal(Ar, (r * self.A))
|
| 621 |
+
|
| 622 |
+
for ob in [object(), 'qrs']:
|
| 623 |
+
with assert_raises_regex(ValueError,
|
| 624 |
+
'Can only multiply by integers'):
|
| 625 |
+
ob * A
|
| 626 |
+
|
| 627 |
+
def test_mod(self):
|
| 628 |
+
"""Ticket #856"""
|
| 629 |
+
F = np.array([['%d', '%f'], ['%s', '%r']]).view(np.chararray)
|
| 630 |
+
C = np.array([[3, 7], [19, 1]])
|
| 631 |
+
FC = np.array([['3', '7.000000'],
|
| 632 |
+
['19', '1']]).view(np.chararray)
|
| 633 |
+
assert_array_equal(FC, F % C)
|
| 634 |
+
|
| 635 |
+
A = np.array([['%.3f', '%d'], ['%s', '%r']]).view(np.chararray)
|
| 636 |
+
A1 = np.array([['1.000', '1'], ['1', '1']]).view(np.chararray)
|
| 637 |
+
assert_array_equal(A1, (A % 1))
|
| 638 |
+
|
| 639 |
+
A2 = np.array([['1.000', '2'], ['3', '4']]).view(np.chararray)
|
| 640 |
+
assert_array_equal(A2, (A % [[1, 2], [3, 4]]))
|
| 641 |
+
|
| 642 |
+
def test_rmod(self):
|
| 643 |
+
assert_(("%s" % self.A) == str(self.A))
|
| 644 |
+
assert_(("%r" % self.A) == repr(self.A))
|
| 645 |
+
|
| 646 |
+
for ob in [42, object()]:
|
| 647 |
+
with assert_raises_regex(
|
| 648 |
+
TypeError, "unsupported operand type.* and 'chararray'"):
|
| 649 |
+
ob % self.A
|
| 650 |
+
|
| 651 |
+
def test_slice(self):
|
| 652 |
+
"""Regression test for https://github.com/numpy/numpy/issues/5982"""
|
| 653 |
+
|
| 654 |
+
arr = np.array([['abc ', 'def '], ['geh ', 'ijk ']],
|
| 655 |
+
dtype='S4').view(np.chararray)
|
| 656 |
+
sl1 = arr[:]
|
| 657 |
+
assert_array_equal(sl1, arr)
|
| 658 |
+
assert_(sl1.base is arr)
|
| 659 |
+
assert_(sl1.base.base is arr.base)
|
| 660 |
+
|
| 661 |
+
sl2 = arr[:, :]
|
| 662 |
+
assert_array_equal(sl2, arr)
|
| 663 |
+
assert_(sl2.base is arr)
|
| 664 |
+
assert_(sl2.base.base is arr.base)
|
| 665 |
+
|
| 666 |
+
assert_(arr[0, 0] == b'abc')
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
def test_empty_indexing():
|
| 670 |
+
"""Regression test for ticket 1948."""
|
| 671 |
+
# Check that indexing a chararray with an empty list/array returns an
|
| 672 |
+
# empty chararray instead of a chararray with a single empty string in it.
|
| 673 |
+
s = np.chararray((4,))
|
| 674 |
+
assert_(s[[]].size == 0)
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
@pytest.mark.parametrize(["dt1", "dt2"],
|
| 678 |
+
[("S", "U"), ("U", "S"), ("S", "O"), ("U", "O"),
|
| 679 |
+
("S", "d"), ("S", "V")])
|
| 680 |
+
def test_add_types(dt1, dt2):
|
| 681 |
+
arr1 = np.array([1234234], dtype=dt1)
|
| 682 |
+
# If the following fails, e.g. use a number and test "V" explicitly
|
| 683 |
+
arr2 = np.array([b"423"], dtype=dt2)
|
| 684 |
+
with pytest.raises(TypeError,
|
| 685 |
+
match=f".*same dtype kind.*{arr1.dtype}.*{arr2.dtype}"):
|
| 686 |
+
np.char.add(arr1, arr2)
|
shared/package-files/17/17de9f3d36c6ccbd97ed4ca15a908ad06663a84aa5d485714b202db7fe8e171a/dylib.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Generic dylib path manipulation
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
__all__ = ['dylib_info']
|
| 8 |
+
|
| 9 |
+
DYLIB_RE = re.compile(r"""(?x)
|
| 10 |
+
(?P<location>^.*)(?:^|/)
|
| 11 |
+
(?P<name>
|
| 12 |
+
(?P<shortname>\w+?)
|
| 13 |
+
(?:\.(?P<version>[^._]+))?
|
| 14 |
+
(?:_(?P<suffix>[^._]+))?
|
| 15 |
+
\.dylib$
|
| 16 |
+
)
|
| 17 |
+
""")
|
| 18 |
+
|
| 19 |
+
def dylib_info(filename):
|
| 20 |
+
"""
|
| 21 |
+
A dylib name can take one of the following four forms:
|
| 22 |
+
Location/Name.SomeVersion_Suffix.dylib
|
| 23 |
+
Location/Name.SomeVersion.dylib
|
| 24 |
+
Location/Name_Suffix.dylib
|
| 25 |
+
Location/Name.dylib
|
| 26 |
+
|
| 27 |
+
returns None if not found or a mapping equivalent to:
|
| 28 |
+
dict(
|
| 29 |
+
location='Location',
|
| 30 |
+
name='Name.SomeVersion_Suffix.dylib',
|
| 31 |
+
shortname='Name',
|
| 32 |
+
version='SomeVersion',
|
| 33 |
+
suffix='Suffix',
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
Note that SomeVersion and Suffix are optional and may be None
|
| 37 |
+
if not present.
|
| 38 |
+
"""
|
| 39 |
+
is_dylib = DYLIB_RE.match(filename)
|
| 40 |
+
if not is_dylib:
|
| 41 |
+
return None
|
| 42 |
+
return is_dylib.groupdict()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_dylib_info():
|
| 46 |
+
def d(location=None, name=None, shortname=None, version=None, suffix=None):
|
| 47 |
+
return dict(
|
| 48 |
+
location=location,
|
| 49 |
+
name=name,
|
| 50 |
+
shortname=shortname,
|
| 51 |
+
version=version,
|
| 52 |
+
suffix=suffix
|
| 53 |
+
)
|
| 54 |
+
assert dylib_info('completely/invalid') is None
|
| 55 |
+
assert dylib_info('completely/invalide_debug') is None
|
| 56 |
+
assert dylib_info('P/Foo.dylib') == d('P', 'Foo.dylib', 'Foo')
|
| 57 |
+
assert dylib_info('P/Foo_debug.dylib') == d('P', 'Foo_debug.dylib', 'Foo', suffix='debug')
|
| 58 |
+
assert dylib_info('P/Foo.A.dylib') == d('P', 'Foo.A.dylib', 'Foo', 'A')
|
| 59 |
+
assert dylib_info('P/Foo_debug.A.dylib') == d('P', 'Foo_debug.A.dylib', 'Foo_debug', 'A')
|
| 60 |
+
assert dylib_info('P/Foo.A_debug.dylib') == d('P', 'Foo.A_debug.dylib', 'Foo', 'A', 'debug')
|
| 61 |
+
|
| 62 |
+
if __name__ == '__main__':
|
| 63 |
+
test_dylib_info()
|
shared/package-files/98/980d45c9423cf89d78c99d557f949ed0e796daee27bfdfb5b34afd78e98ec671/test_round.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 7 |
+
import pytz
|
| 8 |
+
|
| 9 |
+
from pandas._libs import lib
|
| 10 |
+
from pandas._libs.tslibs import (
|
| 11 |
+
NaT,
|
| 12 |
+
OutOfBoundsDatetime,
|
| 13 |
+
Timedelta,
|
| 14 |
+
Timestamp,
|
| 15 |
+
iNaT,
|
| 16 |
+
to_offset,
|
| 17 |
+
)
|
| 18 |
+
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
|
| 19 |
+
from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG
|
| 20 |
+
|
| 21 |
+
import pandas._testing as tm
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class TestTimestampRound:
|
| 25 |
+
def test_round_division_by_zero_raises(self):
|
| 26 |
+
ts = Timestamp("2016-01-01")
|
| 27 |
+
|
| 28 |
+
msg = "Division by zero in rounding"
|
| 29 |
+
with pytest.raises(ValueError, match=msg):
|
| 30 |
+
ts.round("0ns")
|
| 31 |
+
|
| 32 |
+
@pytest.mark.parametrize(
|
| 33 |
+
"timestamp, freq, expected",
|
| 34 |
+
[
|
| 35 |
+
("20130101 09:10:11", "D", "20130101"),
|
| 36 |
+
("20130101 19:10:11", "D", "20130102"),
|
| 37 |
+
("20130201 12:00:00", "D", "20130202"),
|
| 38 |
+
("20130104 12:00:00", "D", "20130105"),
|
| 39 |
+
("2000-01-05 05:09:15.13", "D", "2000-01-05 00:00:00"),
|
| 40 |
+
("2000-01-05 05:09:15.13", "h", "2000-01-05 05:00:00"),
|
| 41 |
+
("2000-01-05 05:09:15.13", "s", "2000-01-05 05:09:15"),
|
| 42 |
+
],
|
| 43 |
+
)
|
| 44 |
+
def test_round_frequencies(self, timestamp, freq, expected):
|
| 45 |
+
dt = Timestamp(timestamp)
|
| 46 |
+
result = dt.round(freq)
|
| 47 |
+
expected = Timestamp(expected)
|
| 48 |
+
assert result == expected
|
| 49 |
+
|
| 50 |
+
def test_round_tzaware(self):
|
| 51 |
+
dt = Timestamp("20130101 09:10:11", tz="US/Eastern")
|
| 52 |
+
result = dt.round("D")
|
| 53 |
+
expected = Timestamp("20130101", tz="US/Eastern")
|
| 54 |
+
assert result == expected
|
| 55 |
+
|
| 56 |
+
dt = Timestamp("20130101 09:10:11", tz="US/Eastern")
|
| 57 |
+
result = dt.round("s")
|
| 58 |
+
assert result == dt
|
| 59 |
+
|
| 60 |
+
def test_round_30min(self):
|
| 61 |
+
# round
|
| 62 |
+
dt = Timestamp("20130104 12:32:00")
|
| 63 |
+
result = dt.round("30Min")
|
| 64 |
+
expected = Timestamp("20130104 12:30:00")
|
| 65 |
+
assert result == expected
|
| 66 |
+
|
| 67 |
+
def test_round_subsecond(self):
|
| 68 |
+
# GH#14440 & GH#15578
|
| 69 |
+
result = Timestamp("2016-10-17 12:00:00.0015").round("ms")
|
| 70 |
+
expected = Timestamp("2016-10-17 12:00:00.002000")
|
| 71 |
+
assert result == expected
|
| 72 |
+
|
| 73 |
+
result = Timestamp("2016-10-17 12:00:00.00149").round("ms")
|
| 74 |
+
expected = Timestamp("2016-10-17 12:00:00.001000")
|
| 75 |
+
assert result == expected
|
| 76 |
+
|
| 77 |
+
ts = Timestamp("2016-10-17 12:00:00.0015")
|
| 78 |
+
for freq in ["us", "ns"]:
|
| 79 |
+
assert ts == ts.round(freq)
|
| 80 |
+
|
| 81 |
+
result = Timestamp("2016-10-17 12:00:00.001501031").round("10ns")
|
| 82 |
+
expected = Timestamp("2016-10-17 12:00:00.001501030")
|
| 83 |
+
assert result == expected
|
| 84 |
+
|
| 85 |
+
def test_round_nonstandard_freq(self):
|
| 86 |
+
with tm.assert_produces_warning(False):
|
| 87 |
+
Timestamp("2016-10-17 12:00:00.001501031").round("1010ns")
|
| 88 |
+
|
| 89 |
+
def test_round_invalid_arg(self):
|
| 90 |
+
stamp = Timestamp("2000-01-05 05:09:15.13")
|
| 91 |
+
with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG):
|
| 92 |
+
stamp.round("foo")
|
| 93 |
+
|
| 94 |
+
@pytest.mark.parametrize(
|
| 95 |
+
"test_input, rounder, freq, expected",
|
| 96 |
+
[
|
| 97 |
+
("2117-01-01 00:00:45", "floor", "15s", "2117-01-01 00:00:45"),
|
| 98 |
+
("2117-01-01 00:00:45", "ceil", "15s", "2117-01-01 00:00:45"),
|
| 99 |
+
(
|
| 100 |
+
"2117-01-01 00:00:45.000000012",
|
| 101 |
+
"floor",
|
| 102 |
+
"10ns",
|
| 103 |
+
"2117-01-01 00:00:45.000000010",
|
| 104 |
+
),
|
| 105 |
+
(
|
| 106 |
+
"1823-01-01 00:00:01.000000012",
|
| 107 |
+
"ceil",
|
| 108 |
+
"10ns",
|
| 109 |
+
"1823-01-01 00:00:01.000000020",
|
| 110 |
+
),
|
| 111 |
+
("1823-01-01 00:00:01", "floor", "1s", "1823-01-01 00:00:01"),
|
| 112 |
+
("1823-01-01 00:00:01", "ceil", "1s", "1823-01-01 00:00:01"),
|
| 113 |
+
("NaT", "floor", "1s", "NaT"),
|
| 114 |
+
("NaT", "ceil", "1s", "NaT"),
|
| 115 |
+
],
|
| 116 |
+
)
|
| 117 |
+
def test_ceil_floor_edge(self, test_input, rounder, freq, expected):
|
| 118 |
+
dt = Timestamp(test_input)
|
| 119 |
+
func = getattr(dt, rounder)
|
| 120 |
+
result = func(freq)
|
| 121 |
+
|
| 122 |
+
if dt is NaT:
|
| 123 |
+
assert result is NaT
|
| 124 |
+
else:
|
| 125 |
+
expected = Timestamp(expected)
|
| 126 |
+
assert result == expected
|
| 127 |
+
|
| 128 |
+
@pytest.mark.parametrize(
|
| 129 |
+
"test_input, freq, expected",
|
| 130 |
+
[
|
| 131 |
+
("2018-01-01 00:02:06", "2s", "2018-01-01 00:02:06"),
|
| 132 |
+
("2018-01-01 00:02:00", "2min", "2018-01-01 00:02:00"),
|
| 133 |
+
("2018-01-01 00:04:00", "4min", "2018-01-01 00:04:00"),
|
| 134 |
+
("2018-01-01 00:15:00", "15min", "2018-01-01 00:15:00"),
|
| 135 |
+
("2018-01-01 00:20:00", "20min", "2018-01-01 00:20:00"),
|
| 136 |
+
("2018-01-01 03:00:00", "3h", "2018-01-01 03:00:00"),
|
| 137 |
+
],
|
| 138 |
+
)
|
| 139 |
+
@pytest.mark.parametrize("rounder", ["ceil", "floor", "round"])
|
| 140 |
+
def test_round_minute_freq(self, test_input, freq, expected, rounder):
|
| 141 |
+
# Ensure timestamps that shouldn't round dont!
|
| 142 |
+
# GH#21262
|
| 143 |
+
|
| 144 |
+
dt = Timestamp(test_input)
|
| 145 |
+
expected = Timestamp(expected)
|
| 146 |
+
func = getattr(dt, rounder)
|
| 147 |
+
result = func(freq)
|
| 148 |
+
assert result == expected
|
| 149 |
+
|
| 150 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
| 151 |
+
def test_ceil(self, unit):
|
| 152 |
+
dt = Timestamp("20130101 09:10:11").as_unit(unit)
|
| 153 |
+
result = dt.ceil("D")
|
| 154 |
+
expected = Timestamp("20130102")
|
| 155 |
+
assert result == expected
|
| 156 |
+
assert result._creso == dt._creso
|
| 157 |
+
|
| 158 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
| 159 |
+
def test_floor(self, unit):
|
| 160 |
+
dt = Timestamp("20130101 09:10:11").as_unit(unit)
|
| 161 |
+
result = dt.floor("D")
|
| 162 |
+
expected = Timestamp("20130101")
|
| 163 |
+
assert result == expected
|
| 164 |
+
assert result._creso == dt._creso
|
| 165 |
+
|
| 166 |
+
@pytest.mark.parametrize("method", ["ceil", "round", "floor"])
|
| 167 |
+
@pytest.mark.parametrize(
|
| 168 |
+
"unit",
|
| 169 |
+
["ns", "us", "ms", "s"],
|
| 170 |
+
)
|
| 171 |
+
def test_round_dst_border_ambiguous(self, method, unit):
|
| 172 |
+
# GH 18946 round near "fall back" DST
|
| 173 |
+
ts = Timestamp("2017-10-29 00:00:00", tz="UTC").tz_convert("Europe/Madrid")
|
| 174 |
+
ts = ts.as_unit(unit)
|
| 175 |
+
#
|
| 176 |
+
result = getattr(ts, method)("h", ambiguous=True)
|
| 177 |
+
assert result == ts
|
| 178 |
+
assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value
|
| 179 |
+
|
| 180 |
+
result = getattr(ts, method)("h", ambiguous=False)
|
| 181 |
+
expected = Timestamp("2017-10-29 01:00:00", tz="UTC").tz_convert(
|
| 182 |
+
"Europe/Madrid"
|
| 183 |
+
)
|
| 184 |
+
assert result == expected
|
| 185 |
+
assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value
|
| 186 |
+
|
| 187 |
+
result = getattr(ts, method)("h", ambiguous="NaT")
|
| 188 |
+
assert result is NaT
|
| 189 |
+
|
| 190 |
+
msg = "Cannot infer dst time"
|
| 191 |
+
with pytest.raises(pytz.AmbiguousTimeError, match=msg):
|
| 192 |
+
getattr(ts, method)("h", ambiguous="raise")
|
| 193 |
+
|
| 194 |
+
@pytest.mark.parametrize(
|
| 195 |
+
"method, ts_str, freq",
|
| 196 |
+
[
|
| 197 |
+
["ceil", "2018-03-11 01:59:00-0600", "5min"],
|
| 198 |
+
["round", "2018-03-11 01:59:00-0600", "5min"],
|
| 199 |
+
["floor", "2018-03-11 03:01:00-0500", "2h"],
|
| 200 |
+
],
|
| 201 |
+
)
|
| 202 |
+
@pytest.mark.parametrize(
|
| 203 |
+
"unit",
|
| 204 |
+
["ns", "us", "ms", "s"],
|
| 205 |
+
)
|
| 206 |
+
def test_round_dst_border_nonexistent(self, method, ts_str, freq, unit):
|
| 207 |
+
# GH 23324 round near "spring forward" DST
|
| 208 |
+
ts = Timestamp(ts_str, tz="America/Chicago").as_unit(unit)
|
| 209 |
+
result = getattr(ts, method)(freq, nonexistent="shift_forward")
|
| 210 |
+
expected = Timestamp("2018-03-11 03:00:00", tz="America/Chicago")
|
| 211 |
+
assert result == expected
|
| 212 |
+
assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value
|
| 213 |
+
|
| 214 |
+
result = getattr(ts, method)(freq, nonexistent="NaT")
|
| 215 |
+
assert result is NaT
|
| 216 |
+
|
| 217 |
+
msg = "2018-03-11 02:00:00"
|
| 218 |
+
with pytest.raises(pytz.NonExistentTimeError, match=msg):
|
| 219 |
+
getattr(ts, method)(freq, nonexistent="raise")
|
| 220 |
+
|
| 221 |
+
@pytest.mark.parametrize(
|
| 222 |
+
"timestamp",
|
| 223 |
+
[
|
| 224 |
+
"2018-01-01 0:0:0.124999360",
|
| 225 |
+
"2018-01-01 0:0:0.125000367",
|
| 226 |
+
"2018-01-01 0:0:0.125500",
|
| 227 |
+
"2018-01-01 0:0:0.126500",
|
| 228 |
+
"2018-01-01 12:00:00",
|
| 229 |
+
"2019-01-01 12:00:00",
|
| 230 |
+
],
|
| 231 |
+
)
|
| 232 |
+
@pytest.mark.parametrize(
|
| 233 |
+
"freq",
|
| 234 |
+
[
|
| 235 |
+
"2ns",
|
| 236 |
+
"3ns",
|
| 237 |
+
"4ns",
|
| 238 |
+
"5ns",
|
| 239 |
+
"6ns",
|
| 240 |
+
"7ns",
|
| 241 |
+
"250ns",
|
| 242 |
+
"500ns",
|
| 243 |
+
"750ns",
|
| 244 |
+
"1us",
|
| 245 |
+
"19us",
|
| 246 |
+
"250us",
|
| 247 |
+
"500us",
|
| 248 |
+
"750us",
|
| 249 |
+
"1s",
|
| 250 |
+
"2s",
|
| 251 |
+
"3s",
|
| 252 |
+
"1D",
|
| 253 |
+
],
|
| 254 |
+
)
|
| 255 |
+
def test_round_int64(self, timestamp, freq):
|
| 256 |
+
# check that all rounding modes are accurate to int64 precision
|
| 257 |
+
# see GH#22591
|
| 258 |
+
dt = Timestamp(timestamp).as_unit("ns")
|
| 259 |
+
unit = to_offset(freq).nanos
|
| 260 |
+
|
| 261 |
+
# test floor
|
| 262 |
+
result = dt.floor(freq)
|
| 263 |
+
assert result._value % unit == 0, f"floor not a {freq} multiple"
|
| 264 |
+
assert 0 <= dt._value - result._value < unit, "floor error"
|
| 265 |
+
|
| 266 |
+
# test ceil
|
| 267 |
+
result = dt.ceil(freq)
|
| 268 |
+
assert result._value % unit == 0, f"ceil not a {freq} multiple"
|
| 269 |
+
assert 0 <= result._value - dt._value < unit, "ceil error"
|
| 270 |
+
|
| 271 |
+
# test round
|
| 272 |
+
result = dt.round(freq)
|
| 273 |
+
assert result._value % unit == 0, f"round not a {freq} multiple"
|
| 274 |
+
assert abs(result._value - dt._value) <= unit // 2, "round error"
|
| 275 |
+
if unit % 2 == 0 and abs(result._value - dt._value) == unit // 2:
|
| 276 |
+
# round half to even
|
| 277 |
+
assert result._value // unit % 2 == 0, "round half to even error"
|
| 278 |
+
|
| 279 |
+
def test_round_implementation_bounds(self):
|
| 280 |
+
# See also: analogous test for Timedelta
|
| 281 |
+
result = Timestamp.min.ceil("s")
|
| 282 |
+
expected = Timestamp(1677, 9, 21, 0, 12, 44)
|
| 283 |
+
assert result == expected
|
| 284 |
+
|
| 285 |
+
result = Timestamp.max.floor("s")
|
| 286 |
+
expected = Timestamp.max - Timedelta(854775807)
|
| 287 |
+
assert result == expected
|
| 288 |
+
|
| 289 |
+
msg = "Cannot round 1677-09-21 00:12:43.145224193 to freq=<Second>"
|
| 290 |
+
with pytest.raises(OutOfBoundsDatetime, match=msg):
|
| 291 |
+
Timestamp.min.floor("s")
|
| 292 |
+
|
| 293 |
+
with pytest.raises(OutOfBoundsDatetime, match=msg):
|
| 294 |
+
Timestamp.min.round("s")
|
| 295 |
+
|
| 296 |
+
msg = "Cannot round 2262-04-11 23:47:16.854775807 to freq=<Second>"
|
| 297 |
+
with pytest.raises(OutOfBoundsDatetime, match=msg):
|
| 298 |
+
Timestamp.max.ceil("s")
|
| 299 |
+
|
| 300 |
+
with pytest.raises(OutOfBoundsDatetime, match=msg):
|
| 301 |
+
Timestamp.max.round("s")
|
| 302 |
+
|
| 303 |
+
@given(val=st.integers(iNaT + 1, lib.i8max))
|
| 304 |
+
@pytest.mark.parametrize(
|
| 305 |
+
"method", [Timestamp.round, Timestamp.floor, Timestamp.ceil]
|
| 306 |
+
)
|
| 307 |
+
def test_round_sanity(self, val, method):
|
| 308 |
+
cls = Timestamp
|
| 309 |
+
err_cls = OutOfBoundsDatetime
|
| 310 |
+
|
| 311 |
+
val = np.int64(val)
|
| 312 |
+
ts = cls(val)
|
| 313 |
+
|
| 314 |
+
def checker(ts, nanos, unit):
|
| 315 |
+
# First check that we do raise in cases where we should
|
| 316 |
+
if nanos == 1:
|
| 317 |
+
pass
|
| 318 |
+
else:
|
| 319 |
+
div, mod = divmod(ts._value, nanos)
|
| 320 |
+
diff = int(nanos - mod)
|
| 321 |
+
lb = ts._value - mod
|
| 322 |
+
assert lb <= ts._value # i.e. no overflows with python ints
|
| 323 |
+
ub = ts._value + diff
|
| 324 |
+
assert ub > ts._value # i.e. no overflows with python ints
|
| 325 |
+
|
| 326 |
+
msg = "without overflow"
|
| 327 |
+
if mod == 0:
|
| 328 |
+
# We should never be raising in this
|
| 329 |
+
pass
|
| 330 |
+
elif method is cls.ceil:
|
| 331 |
+
if ub > cls.max._value:
|
| 332 |
+
with pytest.raises(err_cls, match=msg):
|
| 333 |
+
method(ts, unit)
|
| 334 |
+
return
|
| 335 |
+
elif method is cls.floor:
|
| 336 |
+
if lb < cls.min._value:
|
| 337 |
+
with pytest.raises(err_cls, match=msg):
|
| 338 |
+
method(ts, unit)
|
| 339 |
+
return
|
| 340 |
+
elif mod >= diff:
|
| 341 |
+
if ub > cls.max._value:
|
| 342 |
+
with pytest.raises(err_cls, match=msg):
|
| 343 |
+
method(ts, unit)
|
| 344 |
+
return
|
| 345 |
+
elif lb < cls.min._value:
|
| 346 |
+
with pytest.raises(err_cls, match=msg):
|
| 347 |
+
method(ts, unit)
|
| 348 |
+
return
|
| 349 |
+
|
| 350 |
+
res = method(ts, unit)
|
| 351 |
+
|
| 352 |
+
td = res - ts
|
| 353 |
+
diff = abs(td._value)
|
| 354 |
+
assert diff < nanos
|
| 355 |
+
assert res._value % nanos == 0
|
| 356 |
+
|
| 357 |
+
if method is cls.round:
|
| 358 |
+
assert diff <= nanos / 2
|
| 359 |
+
elif method is cls.floor:
|
| 360 |
+
assert res <= ts
|
| 361 |
+
elif method is cls.ceil:
|
| 362 |
+
assert res >= ts
|
| 363 |
+
|
| 364 |
+
nanos = 1
|
| 365 |
+
checker(ts, nanos, "ns")
|
| 366 |
+
|
| 367 |
+
nanos = 1000
|
| 368 |
+
checker(ts, nanos, "us")
|
| 369 |
+
|
| 370 |
+
nanos = 1_000_000
|
| 371 |
+
checker(ts, nanos, "ms")
|
| 372 |
+
|
| 373 |
+
nanos = 1_000_000_000
|
| 374 |
+
checker(ts, nanos, "s")
|
| 375 |
+
|
| 376 |
+
nanos = 60 * 1_000_000_000
|
| 377 |
+
checker(ts, nanos, "min")
|
| 378 |
+
|
| 379 |
+
nanos = 60 * 60 * 1_000_000_000
|
| 380 |
+
checker(ts, nanos, "h")
|
| 381 |
+
|
| 382 |
+
nanos = 24 * 60 * 60 * 1_000_000_000
|
| 383 |
+
checker(ts, nanos, "D")
|
shared/package-files/98/98178982f59c0d90663c54ad0cd12397379963768c0cc0875a88fb7429a0ba04/_constants.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Statistics-related constants.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# The smallest representable positive number such that 1.0 + _EPS != 1.0.
|
| 9 |
+
_EPS = np.finfo(float).eps
|
| 10 |
+
|
| 11 |
+
# The largest [in magnitude] usable floating value.
|
| 12 |
+
_XMAX = np.finfo(float).max
|
| 13 |
+
|
| 14 |
+
# The log of the largest usable floating value; useful for knowing
|
| 15 |
+
# when exp(something) will overflow
|
| 16 |
+
_LOGXMAX = np.log(_XMAX)
|
| 17 |
+
|
| 18 |
+
# The smallest [in magnitude] usable (i.e. not subnormal) double precision
|
| 19 |
+
# floating value.
|
| 20 |
+
_XMIN = np.finfo(float).tiny
|
| 21 |
+
|
| 22 |
+
# The log of the smallest [in magnitude] usable (i.e not subnormal)
|
| 23 |
+
# double precision floating value.
|
| 24 |
+
_LOGXMIN = np.log(_XMIN)
|
| 25 |
+
|
| 26 |
+
# -special.psi(1)
|
| 27 |
+
_EULER = 0.577215664901532860606512090082402431042
|
| 28 |
+
|
| 29 |
+
# special.zeta(3, 1) Apery's constant
|
| 30 |
+
_ZETA3 = 1.202056903159594285399738161511449990765
|
| 31 |
+
|
| 32 |
+
# sqrt(pi)
|
| 33 |
+
_SQRT_PI = 1.772453850905516027298167483341145182798
|
| 34 |
+
|
| 35 |
+
# sqrt(2/pi)
|
| 36 |
+
_SQRT_2_OVER_PI = 0.7978845608028654
|
| 37 |
+
|
| 38 |
+
# log(pi)
|
| 39 |
+
_LOG_PI = 1.1447298858494002
|
| 40 |
+
|
| 41 |
+
# log(sqrt(2/pi))
|
| 42 |
+
_LOG_SQRT_2_OVER_PI = -0.22579135264472744
|
shared/package-files/98/9853cf796c52df2ab9b35b415405289e71e7baddefe1b177653f78a612cf4cf0/nan_to_num_ops.h
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 nan_to_num {
|
| 18 |
+
using schema = at::Tensor (const at::Tensor &, c10::optional<double>, c10::optional<double>, c10::optional<double>);
|
| 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::nan_to_num")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "nan_to_num(Tensor self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor")
|
| 24 |
+
static at::Tensor call(const at::Tensor & self, c10::optional<double> nan, c10::optional<double> posinf, c10::optional<double> neginf);
|
| 25 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional<double> nan, c10::optional<double> posinf, c10::optional<double> neginf);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API nan_to_num_ {
|
| 29 |
+
using schema = at::Tensor & (at::Tensor &, c10::optional<double>, c10::optional<double>, c10::optional<double>);
|
| 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::nan_to_num_")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "nan_to_num_(Tensor(a!) self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor(a!)")
|
| 35 |
+
static at::Tensor & call(at::Tensor & self, c10::optional<double> nan, c10::optional<double> posinf, c10::optional<double> neginf);
|
| 36 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, c10::optional<double> nan, c10::optional<double> posinf, c10::optional<double> neginf);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
struct TORCH_API nan_to_num_out {
|
| 40 |
+
using schema = at::Tensor & (const at::Tensor &, c10::optional<double>, c10::optional<double>, c10::optional<double>, at::Tensor &);
|
| 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::nan_to_num")
|
| 44 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 45 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "nan_to_num.out(Tensor self, float? nan=None, float? posinf=None, float? neginf=None, *, Tensor(a!) out) -> Tensor(a!)")
|
| 46 |
+
static at::Tensor & call(const at::Tensor & self, c10::optional<double> nan, c10::optional<double> posinf, c10::optional<double> neginf, at::Tensor & out);
|
| 47 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional<double> nan, c10::optional<double> posinf, c10::optional<double> neginf, at::Tensor & out);
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
}} // namespace at::_ops
|
shared/package-files/98/9856346efdad114b43a74ca909e955abf460b5b81403f1d6ee68a452ae9ad3ef/LazyIr.h
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// This file contains autogenerated LazyTensor IR nodes
|
| 4 |
+
${lazy_ir_sysinc}
|
| 5 |
+
${lazy_ir_inc}
|
| 6 |
+
|
| 7 |
+
${namespace_prologue}
|
| 8 |
+
using at::operator<<;
|
| 9 |
+
|
| 10 |
+
// kNullValue is used to contribute a static hash value any time
|
| 11 |
+
// a node has an Optional<Value> input that is nullopt. It is important
|
| 12 |
+
// to differentiate between HASH(nullopt, something) and HASH(something, nullopt),
|
| 13 |
+
// and using kNullValue in the hash function in the order of arguments
|
| 14 |
+
// serves this purpose.
|
| 15 |
+
static const torch::lazy::Value kNullValue = torch::lazy::Value();
|
| 16 |
+
|
| 17 |
+
${ir_declarations}
|
| 18 |
+
|
| 19 |
+
${namespace_epilogue}
|
shared/package-files/98/985a754c752be6a45c6bb515b463a2c3f3be1b06645a2e959fb6c78885dab9a9/superbrain
ADDED
|
Binary file (969 Bytes). View file
|
|
|
shared/package-files/98/987ff0da1e11da62c5fc63ff754af982106f33ae54f2d564fa00b9a4c6125506/conftest.py
ADDED
|
@@ -0,0 +1,2065 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This file is very long and growing, but it was decided to not split it yet, as
|
| 3 |
+
it's still manageable (2020-03-17, ~1.1k LoC). See gh-31989
|
| 4 |
+
|
| 5 |
+
Instead of splitting it was decided to define sections here:
|
| 6 |
+
- Configuration / Settings
|
| 7 |
+
- Autouse fixtures
|
| 8 |
+
- Common arguments
|
| 9 |
+
- Missing values & co.
|
| 10 |
+
- Classes
|
| 11 |
+
- Indices
|
| 12 |
+
- Series'
|
| 13 |
+
- DataFrames
|
| 14 |
+
- Operators & Operations
|
| 15 |
+
- Data sets/files
|
| 16 |
+
- Time zones
|
| 17 |
+
- Dtypes
|
| 18 |
+
- Misc
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
from collections import abc
|
| 23 |
+
from datetime import (
|
| 24 |
+
date,
|
| 25 |
+
datetime,
|
| 26 |
+
time,
|
| 27 |
+
timedelta,
|
| 28 |
+
timezone,
|
| 29 |
+
)
|
| 30 |
+
from decimal import Decimal
|
| 31 |
+
import operator
|
| 32 |
+
import os
|
| 33 |
+
from typing import (
|
| 34 |
+
TYPE_CHECKING,
|
| 35 |
+
Callable,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
from dateutil.tz import (
|
| 39 |
+
tzlocal,
|
| 40 |
+
tzutc,
|
| 41 |
+
)
|
| 42 |
+
import hypothesis
|
| 43 |
+
from hypothesis import strategies as st
|
| 44 |
+
import numpy as np
|
| 45 |
+
import pytest
|
| 46 |
+
from pytz import (
|
| 47 |
+
FixedOffset,
|
| 48 |
+
utc,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
from pandas._config.config import _get_option
|
| 52 |
+
|
| 53 |
+
import pandas.util._test_decorators as td
|
| 54 |
+
|
| 55 |
+
from pandas.core.dtypes.dtypes import (
|
| 56 |
+
DatetimeTZDtype,
|
| 57 |
+
IntervalDtype,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
import pandas as pd
|
| 61 |
+
from pandas import (
|
| 62 |
+
CategoricalIndex,
|
| 63 |
+
DataFrame,
|
| 64 |
+
Interval,
|
| 65 |
+
IntervalIndex,
|
| 66 |
+
Period,
|
| 67 |
+
RangeIndex,
|
| 68 |
+
Series,
|
| 69 |
+
Timedelta,
|
| 70 |
+
Timestamp,
|
| 71 |
+
date_range,
|
| 72 |
+
period_range,
|
| 73 |
+
timedelta_range,
|
| 74 |
+
)
|
| 75 |
+
import pandas._testing as tm
|
| 76 |
+
from pandas.core import ops
|
| 77 |
+
from pandas.core.indexes.api import (
|
| 78 |
+
Index,
|
| 79 |
+
MultiIndex,
|
| 80 |
+
)
|
| 81 |
+
from pandas.util.version import Version
|
| 82 |
+
|
| 83 |
+
if TYPE_CHECKING:
|
| 84 |
+
from collections.abc import (
|
| 85 |
+
Hashable,
|
| 86 |
+
Iterator,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
try:
|
| 90 |
+
import pyarrow as pa
|
| 91 |
+
except ImportError:
|
| 92 |
+
has_pyarrow = False
|
| 93 |
+
else:
|
| 94 |
+
del pa
|
| 95 |
+
has_pyarrow = True
|
| 96 |
+
|
| 97 |
+
import zoneinfo
|
| 98 |
+
|
| 99 |
+
try:
|
| 100 |
+
zoneinfo.ZoneInfo("UTC")
|
| 101 |
+
except zoneinfo.ZoneInfoNotFoundError:
|
| 102 |
+
zoneinfo = None # type: ignore[assignment]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# ----------------------------------------------------------------
|
| 106 |
+
# Configuration / Settings
|
| 107 |
+
# ----------------------------------------------------------------
|
| 108 |
+
# pytest
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def pytest_addoption(parser) -> None:
|
| 112 |
+
parser.addoption(
|
| 113 |
+
"--no-strict-data-files",
|
| 114 |
+
action="store_false",
|
| 115 |
+
help="Don't fail if a test is skipped for missing data file.",
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def ignore_doctest_warning(item: pytest.Item, path: str, message: str) -> None:
|
| 120 |
+
"""Ignore doctest warning.
|
| 121 |
+
|
| 122 |
+
Parameters
|
| 123 |
+
----------
|
| 124 |
+
item : pytest.Item
|
| 125 |
+
pytest test item.
|
| 126 |
+
path : str
|
| 127 |
+
Module path to Python object, e.g. "pandas.core.frame.DataFrame.append". A
|
| 128 |
+
warning will be filtered when item.name ends with in given path. So it is
|
| 129 |
+
sufficient to specify e.g. "DataFrame.append".
|
| 130 |
+
message : str
|
| 131 |
+
Message to be filtered.
|
| 132 |
+
"""
|
| 133 |
+
if item.name.endswith(path):
|
| 134 |
+
item.add_marker(pytest.mark.filterwarnings(f"ignore:{message}"))
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def pytest_collection_modifyitems(items, config) -> None:
|
| 138 |
+
is_doctest = config.getoption("--doctest-modules") or config.getoption(
|
| 139 |
+
"--doctest-cython", default=False
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
# Warnings from doctests that can be ignored; place reason in comment above.
|
| 143 |
+
# Each entry specifies (path, message) - see the ignore_doctest_warning function
|
| 144 |
+
ignored_doctest_warnings = [
|
| 145 |
+
("is_int64_dtype", "is_int64_dtype is deprecated"),
|
| 146 |
+
("is_interval_dtype", "is_interval_dtype is deprecated"),
|
| 147 |
+
("is_period_dtype", "is_period_dtype is deprecated"),
|
| 148 |
+
("is_datetime64tz_dtype", "is_datetime64tz_dtype is deprecated"),
|
| 149 |
+
("is_categorical_dtype", "is_categorical_dtype is deprecated"),
|
| 150 |
+
("is_sparse", "is_sparse is deprecated"),
|
| 151 |
+
("DataFrameGroupBy.fillna", "DataFrameGroupBy.fillna is deprecated"),
|
| 152 |
+
("NDFrame.replace", "The 'method' keyword"),
|
| 153 |
+
("NDFrame.replace", "Series.replace without 'value'"),
|
| 154 |
+
("NDFrame.clip", "Downcasting behavior in Series and DataFrame methods"),
|
| 155 |
+
("Series.idxmin", "The behavior of Series.idxmin"),
|
| 156 |
+
("Series.idxmax", "The behavior of Series.idxmax"),
|
| 157 |
+
("SeriesGroupBy.fillna", "SeriesGroupBy.fillna is deprecated"),
|
| 158 |
+
("SeriesGroupBy.idxmin", "The behavior of Series.idxmin"),
|
| 159 |
+
("SeriesGroupBy.idxmax", "The behavior of Series.idxmax"),
|
| 160 |
+
# Docstring divides by zero to show behavior difference
|
| 161 |
+
("missing.mask_zero_div_zero", "divide by zero encountered"),
|
| 162 |
+
(
|
| 163 |
+
"to_pydatetime",
|
| 164 |
+
"The behavior of DatetimeProperties.to_pydatetime is deprecated",
|
| 165 |
+
),
|
| 166 |
+
(
|
| 167 |
+
"pandas.core.generic.NDFrame.bool",
|
| 168 |
+
"(Series|DataFrame).bool is now deprecated and will be removed "
|
| 169 |
+
"in future version of pandas",
|
| 170 |
+
),
|
| 171 |
+
(
|
| 172 |
+
"pandas.core.generic.NDFrame.first",
|
| 173 |
+
"first is deprecated and will be removed in a future version. "
|
| 174 |
+
"Please create a mask and filter using `.loc` instead",
|
| 175 |
+
),
|
| 176 |
+
(
|
| 177 |
+
"Resampler.fillna",
|
| 178 |
+
"DatetimeIndexResampler.fillna is deprecated",
|
| 179 |
+
),
|
| 180 |
+
(
|
| 181 |
+
"DataFrameGroupBy.fillna",
|
| 182 |
+
"DataFrameGroupBy.fillna with 'method' is deprecated",
|
| 183 |
+
),
|
| 184 |
+
(
|
| 185 |
+
"DataFrameGroupBy.fillna",
|
| 186 |
+
"DataFrame.fillna with 'method' is deprecated",
|
| 187 |
+
),
|
| 188 |
+
("read_parquet", "Passing a BlockManager to DataFrame is deprecated"),
|
| 189 |
+
]
|
| 190 |
+
|
| 191 |
+
if is_doctest:
|
| 192 |
+
for item in items:
|
| 193 |
+
for path, message in ignored_doctest_warnings:
|
| 194 |
+
ignore_doctest_warning(item, path, message)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
hypothesis_health_checks = [hypothesis.HealthCheck.too_slow]
|
| 198 |
+
if Version(hypothesis.__version__) >= Version("6.83.2"):
|
| 199 |
+
hypothesis_health_checks.append(hypothesis.HealthCheck.differing_executors)
|
| 200 |
+
|
| 201 |
+
# Hypothesis
|
| 202 |
+
hypothesis.settings.register_profile(
|
| 203 |
+
"ci",
|
| 204 |
+
# Hypothesis timing checks are tuned for scalars by default, so we bump
|
| 205 |
+
# them from 200ms to 500ms per test case as the global default. If this
|
| 206 |
+
# is too short for a specific test, (a) try to make it faster, and (b)
|
| 207 |
+
# if it really is slow add `@settings(deadline=...)` with a working value,
|
| 208 |
+
# or `deadline=None` to entirely disable timeouts for that test.
|
| 209 |
+
# 2022-02-09: Changed deadline from 500 -> None. Deadline leads to
|
| 210 |
+
# non-actionable, flaky CI failures (# GH 24641, 44969, 45118, 44969)
|
| 211 |
+
deadline=None,
|
| 212 |
+
suppress_health_check=tuple(hypothesis_health_checks),
|
| 213 |
+
)
|
| 214 |
+
hypothesis.settings.load_profile("ci")
|
| 215 |
+
|
| 216 |
+
# Registering these strategies makes them globally available via st.from_type,
|
| 217 |
+
# which is use for offsets in tests/tseries/offsets/test_offsets_properties.py
|
| 218 |
+
for name in "MonthBegin MonthEnd BMonthBegin BMonthEnd".split():
|
| 219 |
+
cls = getattr(pd.tseries.offsets, name)
|
| 220 |
+
st.register_type_strategy(
|
| 221 |
+
cls, st.builds(cls, n=st.integers(-99, 99), normalize=st.booleans())
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
for name in "YearBegin YearEnd BYearBegin BYearEnd".split():
|
| 225 |
+
cls = getattr(pd.tseries.offsets, name)
|
| 226 |
+
st.register_type_strategy(
|
| 227 |
+
cls,
|
| 228 |
+
st.builds(
|
| 229 |
+
cls,
|
| 230 |
+
n=st.integers(-5, 5),
|
| 231 |
+
normalize=st.booleans(),
|
| 232 |
+
month=st.integers(min_value=1, max_value=12),
|
| 233 |
+
),
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
for name in "QuarterBegin QuarterEnd BQuarterBegin BQuarterEnd".split():
|
| 237 |
+
cls = getattr(pd.tseries.offsets, name)
|
| 238 |
+
st.register_type_strategy(
|
| 239 |
+
cls,
|
| 240 |
+
st.builds(
|
| 241 |
+
cls,
|
| 242 |
+
n=st.integers(-24, 24),
|
| 243 |
+
normalize=st.booleans(),
|
| 244 |
+
startingMonth=st.integers(min_value=1, max_value=12),
|
| 245 |
+
),
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
# ----------------------------------------------------------------
|
| 250 |
+
# Autouse fixtures
|
| 251 |
+
# ----------------------------------------------------------------
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
# https://github.com/pytest-dev/pytest/issues/11873
|
| 255 |
+
# Would like to avoid autouse=True, but cannot as of pytest 8.0.0
|
| 256 |
+
@pytest.fixture(autouse=True)
|
| 257 |
+
def add_doctest_imports(doctest_namespace) -> None:
|
| 258 |
+
"""
|
| 259 |
+
Make `np` and `pd` names available for doctests.
|
| 260 |
+
"""
|
| 261 |
+
doctest_namespace["np"] = np
|
| 262 |
+
doctest_namespace["pd"] = pd
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@pytest.fixture(autouse=True)
|
| 266 |
+
def configure_tests() -> None:
|
| 267 |
+
"""
|
| 268 |
+
Configure settings for all tests and test modules.
|
| 269 |
+
"""
|
| 270 |
+
pd.set_option("chained_assignment", "raise")
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
# ----------------------------------------------------------------
|
| 274 |
+
# Common arguments
|
| 275 |
+
# ----------------------------------------------------------------
|
| 276 |
+
@pytest.fixture(params=[0, 1, "index", "columns"], ids=lambda x: f"axis={repr(x)}")
|
| 277 |
+
def axis(request):
|
| 278 |
+
"""
|
| 279 |
+
Fixture for returning the axis numbers of a DataFrame.
|
| 280 |
+
"""
|
| 281 |
+
return request.param
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
axis_frame = axis
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@pytest.fixture(params=[1, "columns"], ids=lambda x: f"axis={repr(x)}")
|
| 288 |
+
def axis_1(request):
|
| 289 |
+
"""
|
| 290 |
+
Fixture for returning aliases of axis 1 of a DataFrame.
|
| 291 |
+
"""
|
| 292 |
+
return request.param
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
@pytest.fixture(params=[True, False, None])
|
| 296 |
+
def observed(request):
|
| 297 |
+
"""
|
| 298 |
+
Pass in the observed keyword to groupby for [True, False]
|
| 299 |
+
This indicates whether categoricals should return values for
|
| 300 |
+
values which are not in the grouper [False / None], or only values which
|
| 301 |
+
appear in the grouper [True]. [None] is supported for future compatibility
|
| 302 |
+
if we decide to change the default (and would need to warn if this
|
| 303 |
+
parameter is not passed).
|
| 304 |
+
"""
|
| 305 |
+
return request.param
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
@pytest.fixture(params=[True, False, None])
|
| 309 |
+
def ordered(request):
|
| 310 |
+
"""
|
| 311 |
+
Boolean 'ordered' parameter for Categorical.
|
| 312 |
+
"""
|
| 313 |
+
return request.param
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
@pytest.fixture(params=[True, False])
|
| 317 |
+
def skipna(request):
|
| 318 |
+
"""
|
| 319 |
+
Boolean 'skipna' parameter.
|
| 320 |
+
"""
|
| 321 |
+
return request.param
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
@pytest.fixture(params=["first", "last", False])
|
| 325 |
+
def keep(request):
|
| 326 |
+
"""
|
| 327 |
+
Valid values for the 'keep' parameter used in
|
| 328 |
+
.duplicated or .drop_duplicates
|
| 329 |
+
"""
|
| 330 |
+
return request.param
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
@pytest.fixture(params=["both", "neither", "left", "right"])
|
| 334 |
+
def inclusive_endpoints_fixture(request):
|
| 335 |
+
"""
|
| 336 |
+
Fixture for trying all interval 'inclusive' parameters.
|
| 337 |
+
"""
|
| 338 |
+
return request.param
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
@pytest.fixture(params=["left", "right", "both", "neither"])
|
| 342 |
+
def closed(request):
|
| 343 |
+
"""
|
| 344 |
+
Fixture for trying all interval closed parameters.
|
| 345 |
+
"""
|
| 346 |
+
return request.param
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
@pytest.fixture(params=["left", "right", "both", "neither"])
|
| 350 |
+
def other_closed(request):
|
| 351 |
+
"""
|
| 352 |
+
Secondary closed fixture to allow parametrizing over all pairs of closed.
|
| 353 |
+
"""
|
| 354 |
+
return request.param
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
@pytest.fixture(
|
| 358 |
+
params=[
|
| 359 |
+
None,
|
| 360 |
+
"gzip",
|
| 361 |
+
"bz2",
|
| 362 |
+
"zip",
|
| 363 |
+
"xz",
|
| 364 |
+
"tar",
|
| 365 |
+
pytest.param("zstd", marks=td.skip_if_no("zstandard")),
|
| 366 |
+
]
|
| 367 |
+
)
|
| 368 |
+
def compression(request):
|
| 369 |
+
"""
|
| 370 |
+
Fixture for trying common compression types in compression tests.
|
| 371 |
+
"""
|
| 372 |
+
return request.param
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
@pytest.fixture(
|
| 376 |
+
params=[
|
| 377 |
+
"gzip",
|
| 378 |
+
"bz2",
|
| 379 |
+
"zip",
|
| 380 |
+
"xz",
|
| 381 |
+
"tar",
|
| 382 |
+
pytest.param("zstd", marks=td.skip_if_no("zstandard")),
|
| 383 |
+
]
|
| 384 |
+
)
|
| 385 |
+
def compression_only(request):
|
| 386 |
+
"""
|
| 387 |
+
Fixture for trying common compression types in compression tests excluding
|
| 388 |
+
uncompressed case.
|
| 389 |
+
"""
|
| 390 |
+
return request.param
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
@pytest.fixture(params=[True, False])
|
| 394 |
+
def writable(request):
|
| 395 |
+
"""
|
| 396 |
+
Fixture that an array is writable.
|
| 397 |
+
"""
|
| 398 |
+
return request.param
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
@pytest.fixture(params=["inner", "outer", "left", "right"])
|
| 402 |
+
def join_type(request):
|
| 403 |
+
"""
|
| 404 |
+
Fixture for trying all types of join operations.
|
| 405 |
+
"""
|
| 406 |
+
return request.param
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@pytest.fixture(params=["nlargest", "nsmallest"])
|
| 410 |
+
def nselect_method(request):
|
| 411 |
+
"""
|
| 412 |
+
Fixture for trying all nselect methods.
|
| 413 |
+
"""
|
| 414 |
+
return request.param
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
# ----------------------------------------------------------------
|
| 418 |
+
# Missing values & co.
|
| 419 |
+
# ----------------------------------------------------------------
|
| 420 |
+
@pytest.fixture(params=tm.NULL_OBJECTS, ids=lambda x: type(x).__name__)
|
| 421 |
+
def nulls_fixture(request):
|
| 422 |
+
"""
|
| 423 |
+
Fixture for each null type in pandas.
|
| 424 |
+
"""
|
| 425 |
+
return request.param
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
nulls_fixture2 = nulls_fixture # Generate cartesian product of nulls_fixture
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
@pytest.fixture(params=[None, np.nan, pd.NaT])
|
| 432 |
+
def unique_nulls_fixture(request):
|
| 433 |
+
"""
|
| 434 |
+
Fixture for each null type in pandas, each null type exactly once.
|
| 435 |
+
"""
|
| 436 |
+
return request.param
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
# Generate cartesian product of unique_nulls_fixture:
|
| 440 |
+
unique_nulls_fixture2 = unique_nulls_fixture
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
@pytest.fixture(params=tm.NP_NAT_OBJECTS, ids=lambda x: type(x).__name__)
|
| 444 |
+
def np_nat_fixture(request):
|
| 445 |
+
"""
|
| 446 |
+
Fixture for each NaT type in numpy.
|
| 447 |
+
"""
|
| 448 |
+
return request.param
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
# Generate cartesian product of np_nat_fixture:
|
| 452 |
+
np_nat_fixture2 = np_nat_fixture
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
# ----------------------------------------------------------------
|
| 456 |
+
# Classes
|
| 457 |
+
# ----------------------------------------------------------------
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
@pytest.fixture(params=[DataFrame, Series])
|
| 461 |
+
def frame_or_series(request):
|
| 462 |
+
"""
|
| 463 |
+
Fixture to parametrize over DataFrame and Series.
|
| 464 |
+
"""
|
| 465 |
+
return request.param
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
@pytest.fixture(params=[Index, Series], ids=["index", "series"])
|
| 469 |
+
def index_or_series(request):
|
| 470 |
+
"""
|
| 471 |
+
Fixture to parametrize over Index and Series, made necessary by a mypy
|
| 472 |
+
bug, giving an error:
|
| 473 |
+
|
| 474 |
+
List item 0 has incompatible type "Type[Series]"; expected "Type[PandasObject]"
|
| 475 |
+
|
| 476 |
+
See GH#29725
|
| 477 |
+
"""
|
| 478 |
+
return request.param
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
# Generate cartesian product of index_or_series fixture:
|
| 482 |
+
index_or_series2 = index_or_series
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
@pytest.fixture(params=[Index, Series, pd.array], ids=["index", "series", "array"])
|
| 486 |
+
def index_or_series_or_array(request):
|
| 487 |
+
"""
|
| 488 |
+
Fixture to parametrize over Index, Series, and ExtensionArray
|
| 489 |
+
"""
|
| 490 |
+
return request.param
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
@pytest.fixture(params=[Index, Series, DataFrame, pd.array], ids=lambda x: x.__name__)
|
| 494 |
+
def box_with_array(request):
|
| 495 |
+
"""
|
| 496 |
+
Fixture to test behavior for Index, Series, DataFrame, and pandas Array
|
| 497 |
+
classes
|
| 498 |
+
"""
|
| 499 |
+
return request.param
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
box_with_array2 = box_with_array
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
@pytest.fixture
|
| 506 |
+
def dict_subclass() -> type[dict]:
|
| 507 |
+
"""
|
| 508 |
+
Fixture for a dictionary subclass.
|
| 509 |
+
"""
|
| 510 |
+
|
| 511 |
+
class TestSubDict(dict):
|
| 512 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 513 |
+
dict.__init__(self, *args, **kwargs)
|
| 514 |
+
|
| 515 |
+
return TestSubDict
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
@pytest.fixture
|
| 519 |
+
def non_dict_mapping_subclass() -> type[abc.Mapping]:
|
| 520 |
+
"""
|
| 521 |
+
Fixture for a non-mapping dictionary subclass.
|
| 522 |
+
"""
|
| 523 |
+
|
| 524 |
+
class TestNonDictMapping(abc.Mapping):
|
| 525 |
+
def __init__(self, underlying_dict) -> None:
|
| 526 |
+
self._data = underlying_dict
|
| 527 |
+
|
| 528 |
+
def __getitem__(self, key):
|
| 529 |
+
return self._data.__getitem__(key)
|
| 530 |
+
|
| 531 |
+
def __iter__(self) -> Iterator:
|
| 532 |
+
return self._data.__iter__()
|
| 533 |
+
|
| 534 |
+
def __len__(self) -> int:
|
| 535 |
+
return self._data.__len__()
|
| 536 |
+
|
| 537 |
+
return TestNonDictMapping
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
# ----------------------------------------------------------------
|
| 541 |
+
# Indices
|
| 542 |
+
# ----------------------------------------------------------------
|
| 543 |
+
@pytest.fixture
|
| 544 |
+
def multiindex_year_month_day_dataframe_random_data():
|
| 545 |
+
"""
|
| 546 |
+
DataFrame with 3 level MultiIndex (year, month, day) covering
|
| 547 |
+
first 100 business days from 2000-01-01 with random data
|
| 548 |
+
"""
|
| 549 |
+
tdf = DataFrame(
|
| 550 |
+
np.random.default_rng(2).standard_normal((100, 4)),
|
| 551 |
+
columns=Index(list("ABCD")),
|
| 552 |
+
index=date_range("2000-01-01", periods=100, freq="B"),
|
| 553 |
+
)
|
| 554 |
+
ymd = tdf.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]).sum()
|
| 555 |
+
# use int64 Index, to make sure things work
|
| 556 |
+
ymd.index = ymd.index.set_levels([lev.astype("i8") for lev in ymd.index.levels])
|
| 557 |
+
ymd.index.set_names(["year", "month", "day"], inplace=True)
|
| 558 |
+
return ymd
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
@pytest.fixture
|
| 562 |
+
def lexsorted_two_level_string_multiindex() -> MultiIndex:
|
| 563 |
+
"""
|
| 564 |
+
2-level MultiIndex, lexsorted, with string names.
|
| 565 |
+
"""
|
| 566 |
+
return MultiIndex(
|
| 567 |
+
levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]],
|
| 568 |
+
codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
|
| 569 |
+
names=["first", "second"],
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
@pytest.fixture
|
| 574 |
+
def multiindex_dataframe_random_data(
|
| 575 |
+
lexsorted_two_level_string_multiindex,
|
| 576 |
+
) -> DataFrame:
|
| 577 |
+
"""DataFrame with 2 level MultiIndex with random data"""
|
| 578 |
+
index = lexsorted_two_level_string_multiindex
|
| 579 |
+
return DataFrame(
|
| 580 |
+
np.random.default_rng(2).standard_normal((10, 3)),
|
| 581 |
+
index=index,
|
| 582 |
+
columns=Index(["A", "B", "C"], name="exp"),
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def _create_multiindex():
|
| 587 |
+
"""
|
| 588 |
+
MultiIndex used to test the general functionality of this object
|
| 589 |
+
"""
|
| 590 |
+
|
| 591 |
+
# See Also: tests.multi.conftest.idx
|
| 592 |
+
major_axis = Index(["foo", "bar", "baz", "qux"])
|
| 593 |
+
minor_axis = Index(["one", "two"])
|
| 594 |
+
|
| 595 |
+
major_codes = np.array([0, 0, 1, 2, 3, 3])
|
| 596 |
+
minor_codes = np.array([0, 1, 0, 1, 0, 1])
|
| 597 |
+
index_names = ["first", "second"]
|
| 598 |
+
return MultiIndex(
|
| 599 |
+
levels=[major_axis, minor_axis],
|
| 600 |
+
codes=[major_codes, minor_codes],
|
| 601 |
+
names=index_names,
|
| 602 |
+
verify_integrity=False,
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def _create_mi_with_dt64tz_level():
|
| 607 |
+
"""
|
| 608 |
+
MultiIndex with a level that is a tzaware DatetimeIndex.
|
| 609 |
+
"""
|
| 610 |
+
# GH#8367 round trip with pickle
|
| 611 |
+
return MultiIndex.from_product(
|
| 612 |
+
[[1, 2], ["a", "b"], date_range("20130101", periods=3, tz="US/Eastern")],
|
| 613 |
+
names=["one", "two", "three"],
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
indices_dict = {
|
| 618 |
+
"object": Index([f"pandas_{i}" for i in range(100)], dtype=object),
|
| 619 |
+
"string": Index([f"pandas_{i}" for i in range(100)], dtype="str"),
|
| 620 |
+
"datetime": date_range("2020-01-01", periods=100),
|
| 621 |
+
"datetime-tz": date_range("2020-01-01", periods=100, tz="US/Pacific"),
|
| 622 |
+
"period": period_range("2020-01-01", periods=100, freq="D"),
|
| 623 |
+
"timedelta": timedelta_range(start="1 day", periods=100, freq="D"),
|
| 624 |
+
"range": RangeIndex(100),
|
| 625 |
+
"int8": Index(np.arange(100), dtype="int8"),
|
| 626 |
+
"int16": Index(np.arange(100), dtype="int16"),
|
| 627 |
+
"int32": Index(np.arange(100), dtype="int32"),
|
| 628 |
+
"int64": Index(np.arange(100), dtype="int64"),
|
| 629 |
+
"uint8": Index(np.arange(100), dtype="uint8"),
|
| 630 |
+
"uint16": Index(np.arange(100), dtype="uint16"),
|
| 631 |
+
"uint32": Index(np.arange(100), dtype="uint32"),
|
| 632 |
+
"uint64": Index(np.arange(100), dtype="uint64"),
|
| 633 |
+
"float32": Index(np.arange(100), dtype="float32"),
|
| 634 |
+
"float64": Index(np.arange(100), dtype="float64"),
|
| 635 |
+
"bool-object": Index([True, False] * 5, dtype=object),
|
| 636 |
+
"bool-dtype": Index([True, False] * 5, dtype=bool),
|
| 637 |
+
"complex64": Index(
|
| 638 |
+
np.arange(100, dtype="complex64") + 1.0j * np.arange(100, dtype="complex64")
|
| 639 |
+
),
|
| 640 |
+
"complex128": Index(
|
| 641 |
+
np.arange(100, dtype="complex128") + 1.0j * np.arange(100, dtype="complex128")
|
| 642 |
+
),
|
| 643 |
+
"categorical": CategoricalIndex(list("abcd") * 25),
|
| 644 |
+
"interval": IntervalIndex.from_breaks(np.linspace(0, 100, num=101)),
|
| 645 |
+
"empty": Index([]),
|
| 646 |
+
"tuples": MultiIndex.from_tuples(zip(["foo", "bar", "baz"], [1, 2, 3])),
|
| 647 |
+
"mi-with-dt64tz-level": _create_mi_with_dt64tz_level(),
|
| 648 |
+
"multi": _create_multiindex(),
|
| 649 |
+
"repeats": Index([0, 0, 1, 1, 2, 2]),
|
| 650 |
+
"nullable_int": Index(np.arange(100), dtype="Int64"),
|
| 651 |
+
"nullable_uint": Index(np.arange(100), dtype="UInt16"),
|
| 652 |
+
"nullable_float": Index(np.arange(100), dtype="Float32"),
|
| 653 |
+
"nullable_bool": Index(np.arange(100).astype(bool), dtype="boolean"),
|
| 654 |
+
"string-python": Index(
|
| 655 |
+
pd.array([f"pandas_{i}" for i in range(100)], dtype="string[python]")
|
| 656 |
+
),
|
| 657 |
+
}
|
| 658 |
+
if has_pyarrow:
|
| 659 |
+
idx = Index(pd.array([f"pandas_{i}" for i in range(100)], dtype="string[pyarrow]"))
|
| 660 |
+
indices_dict["string-pyarrow"] = idx
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
@pytest.fixture(params=indices_dict.keys())
|
| 664 |
+
def index(request):
|
| 665 |
+
"""
|
| 666 |
+
Fixture for many "simple" kinds of indices.
|
| 667 |
+
|
| 668 |
+
These indices are unlikely to cover corner cases, e.g.
|
| 669 |
+
- no names
|
| 670 |
+
- no NaTs/NaNs
|
| 671 |
+
- no values near implementation bounds
|
| 672 |
+
- ...
|
| 673 |
+
"""
|
| 674 |
+
# copy to avoid mutation, e.g. setting .name
|
| 675 |
+
return indices_dict[request.param].copy()
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
# Needed to generate cartesian product of indices
|
| 679 |
+
index_fixture2 = index
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
@pytest.fixture(
|
| 683 |
+
params=[
|
| 684 |
+
key for key, value in indices_dict.items() if not isinstance(value, MultiIndex)
|
| 685 |
+
]
|
| 686 |
+
)
|
| 687 |
+
def index_flat(request):
|
| 688 |
+
"""
|
| 689 |
+
index fixture, but excluding MultiIndex cases.
|
| 690 |
+
"""
|
| 691 |
+
key = request.param
|
| 692 |
+
return indices_dict[key].copy()
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
# Alias so we can test with cartesian product of index_flat
|
| 696 |
+
index_flat2 = index_flat
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
@pytest.fixture(
|
| 700 |
+
params=[
|
| 701 |
+
key
|
| 702 |
+
for key, value in indices_dict.items()
|
| 703 |
+
if not (
|
| 704 |
+
key.startswith(("int", "uint", "float"))
|
| 705 |
+
or key in ["range", "empty", "repeats", "bool-dtype"]
|
| 706 |
+
)
|
| 707 |
+
and not isinstance(value, MultiIndex)
|
| 708 |
+
]
|
| 709 |
+
)
|
| 710 |
+
def index_with_missing(request):
|
| 711 |
+
"""
|
| 712 |
+
Fixture for indices with missing values.
|
| 713 |
+
|
| 714 |
+
Integer-dtype and empty cases are excluded because they cannot hold missing
|
| 715 |
+
values.
|
| 716 |
+
|
| 717 |
+
MultiIndex is excluded because isna() is not defined for MultiIndex.
|
| 718 |
+
"""
|
| 719 |
+
|
| 720 |
+
# GH 35538. Use deep copy to avoid illusive bug on np-dev
|
| 721 |
+
# GHA pipeline that writes into indices_dict despite copy
|
| 722 |
+
ind = indices_dict[request.param].copy(deep=True)
|
| 723 |
+
vals = ind.values.copy()
|
| 724 |
+
if request.param in ["tuples", "mi-with-dt64tz-level", "multi"]:
|
| 725 |
+
# For setting missing values in the top level of MultiIndex
|
| 726 |
+
vals = ind.tolist()
|
| 727 |
+
vals[0] = (None,) + vals[0][1:]
|
| 728 |
+
vals[-1] = (None,) + vals[-1][1:]
|
| 729 |
+
return MultiIndex.from_tuples(vals)
|
| 730 |
+
else:
|
| 731 |
+
vals[0] = None
|
| 732 |
+
vals[-1] = None
|
| 733 |
+
return type(ind)(vals)
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
# ----------------------------------------------------------------
|
| 737 |
+
# Series'
|
| 738 |
+
# ----------------------------------------------------------------
|
| 739 |
+
@pytest.fixture
|
| 740 |
+
def string_series() -> Series:
|
| 741 |
+
"""
|
| 742 |
+
Fixture for Series of floats with Index of unique strings
|
| 743 |
+
"""
|
| 744 |
+
return Series(
|
| 745 |
+
np.arange(30, dtype=np.float64) * 1.1,
|
| 746 |
+
index=Index([f"i_{i}" for i in range(30)]),
|
| 747 |
+
name="series",
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
@pytest.fixture
|
| 752 |
+
def object_series() -> Series:
|
| 753 |
+
"""
|
| 754 |
+
Fixture for Series of dtype object with Index of unique strings
|
| 755 |
+
"""
|
| 756 |
+
data = [f"foo_{i}" for i in range(30)]
|
| 757 |
+
index = Index([f"bar_{i}" for i in range(30)])
|
| 758 |
+
return Series(data, index=index, name="objects", dtype=object)
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
@pytest.fixture
|
| 762 |
+
def datetime_series() -> Series:
|
| 763 |
+
"""
|
| 764 |
+
Fixture for Series of floats with DatetimeIndex
|
| 765 |
+
"""
|
| 766 |
+
return Series(
|
| 767 |
+
np.random.default_rng(2).standard_normal(30),
|
| 768 |
+
index=date_range("2000-01-01", periods=30, freq="B"),
|
| 769 |
+
name="ts",
|
| 770 |
+
)
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
def _create_series(index):
|
| 774 |
+
"""Helper for the _series dict"""
|
| 775 |
+
size = len(index)
|
| 776 |
+
data = np.random.default_rng(2).standard_normal(size)
|
| 777 |
+
return Series(data, index=index, name="a", copy=False)
|
| 778 |
+
|
| 779 |
+
|
| 780 |
+
_series = {
|
| 781 |
+
f"series-with-{index_id}-index": _create_series(index)
|
| 782 |
+
for index_id, index in indices_dict.items()
|
| 783 |
+
}
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
@pytest.fixture
|
| 787 |
+
def series_with_simple_index(index) -> Series:
|
| 788 |
+
"""
|
| 789 |
+
Fixture for tests on series with changing types of indices.
|
| 790 |
+
"""
|
| 791 |
+
return _create_series(index)
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
_narrow_series = {
|
| 795 |
+
f"{dtype.__name__}-series": Series(
|
| 796 |
+
range(30), index=[f"i-{i}" for i in range(30)], name="a", dtype=dtype
|
| 797 |
+
)
|
| 798 |
+
for dtype in tm.NARROW_NP_DTYPES
|
| 799 |
+
}
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
_index_or_series_objs = {**indices_dict, **_series, **_narrow_series}
|
| 803 |
+
|
| 804 |
+
|
| 805 |
+
@pytest.fixture(params=_index_or_series_objs.keys())
|
| 806 |
+
def index_or_series_obj(request):
|
| 807 |
+
"""
|
| 808 |
+
Fixture for tests on indexes, series and series with a narrow dtype
|
| 809 |
+
copy to avoid mutation, e.g. setting .name
|
| 810 |
+
"""
|
| 811 |
+
return _index_or_series_objs[request.param].copy(deep=True)
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
_typ_objects_series = {
|
| 815 |
+
f"{dtype.__name__}-series": Series(dtype) for dtype in tm.PYTHON_DATA_TYPES
|
| 816 |
+
}
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
_index_or_series_memory_objs = {
|
| 820 |
+
**indices_dict,
|
| 821 |
+
**_series,
|
| 822 |
+
**_narrow_series,
|
| 823 |
+
**_typ_objects_series,
|
| 824 |
+
}
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
@pytest.fixture(params=_index_or_series_memory_objs.keys())
|
| 828 |
+
def index_or_series_memory_obj(request):
|
| 829 |
+
"""
|
| 830 |
+
Fixture for tests on indexes, series, series with a narrow dtype and
|
| 831 |
+
series with empty objects type
|
| 832 |
+
copy to avoid mutation, e.g. setting .name
|
| 833 |
+
"""
|
| 834 |
+
return _index_or_series_memory_objs[request.param].copy(deep=True)
|
| 835 |
+
|
| 836 |
+
|
| 837 |
+
# ----------------------------------------------------------------
|
| 838 |
+
# DataFrames
|
| 839 |
+
# ----------------------------------------------------------------
|
| 840 |
+
@pytest.fixture
|
| 841 |
+
def int_frame() -> DataFrame:
|
| 842 |
+
"""
|
| 843 |
+
Fixture for DataFrame of ints with index of unique strings
|
| 844 |
+
|
| 845 |
+
Columns are ['A', 'B', 'C', 'D']
|
| 846 |
+
"""
|
| 847 |
+
return DataFrame(
|
| 848 |
+
np.ones((30, 4), dtype=np.int64),
|
| 849 |
+
index=Index([f"foo_{i}" for i in range(30)]),
|
| 850 |
+
columns=Index(list("ABCD")),
|
| 851 |
+
)
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
@pytest.fixture
|
| 855 |
+
def float_frame() -> DataFrame:
|
| 856 |
+
"""
|
| 857 |
+
Fixture for DataFrame of floats with index of unique strings
|
| 858 |
+
|
| 859 |
+
Columns are ['A', 'B', 'C', 'D'].
|
| 860 |
+
"""
|
| 861 |
+
return DataFrame(
|
| 862 |
+
np.random.default_rng(2).standard_normal((30, 4)),
|
| 863 |
+
index=Index([f"foo_{i}" for i in range(30)]),
|
| 864 |
+
columns=Index(list("ABCD")),
|
| 865 |
+
)
|
| 866 |
+
|
| 867 |
+
|
| 868 |
+
@pytest.fixture
|
| 869 |
+
def rand_series_with_duplicate_datetimeindex() -> Series:
|
| 870 |
+
"""
|
| 871 |
+
Fixture for Series with a DatetimeIndex that has duplicates.
|
| 872 |
+
"""
|
| 873 |
+
dates = [
|
| 874 |
+
datetime(2000, 1, 2),
|
| 875 |
+
datetime(2000, 1, 2),
|
| 876 |
+
datetime(2000, 1, 2),
|
| 877 |
+
datetime(2000, 1, 3),
|
| 878 |
+
datetime(2000, 1, 3),
|
| 879 |
+
datetime(2000, 1, 3),
|
| 880 |
+
datetime(2000, 1, 4),
|
| 881 |
+
datetime(2000, 1, 4),
|
| 882 |
+
datetime(2000, 1, 4),
|
| 883 |
+
datetime(2000, 1, 5),
|
| 884 |
+
]
|
| 885 |
+
|
| 886 |
+
return Series(np.random.default_rng(2).standard_normal(len(dates)), index=dates)
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
# ----------------------------------------------------------------
|
| 890 |
+
# Scalars
|
| 891 |
+
# ----------------------------------------------------------------
|
| 892 |
+
@pytest.fixture(
|
| 893 |
+
params=[
|
| 894 |
+
(Interval(left=0, right=5), IntervalDtype("int64", "right")),
|
| 895 |
+
(Interval(left=0.1, right=0.5), IntervalDtype("float64", "right")),
|
| 896 |
+
(Period("2012-01", freq="M"), "period[M]"),
|
| 897 |
+
(Period("2012-02-01", freq="D"), "period[D]"),
|
| 898 |
+
(
|
| 899 |
+
Timestamp("2011-01-01", tz="US/Eastern"),
|
| 900 |
+
DatetimeTZDtype(unit="s", tz="US/Eastern"),
|
| 901 |
+
),
|
| 902 |
+
(Timedelta(seconds=500), "timedelta64[ns]"),
|
| 903 |
+
]
|
| 904 |
+
)
|
| 905 |
+
def ea_scalar_and_dtype(request):
|
| 906 |
+
return request.param
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
# ----------------------------------------------------------------
|
| 910 |
+
# Operators & Operations
|
| 911 |
+
# ----------------------------------------------------------------
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
@pytest.fixture(params=tm.arithmetic_dunder_methods)
|
| 915 |
+
def all_arithmetic_operators(request):
|
| 916 |
+
"""
|
| 917 |
+
Fixture for dunder names for common arithmetic operations.
|
| 918 |
+
"""
|
| 919 |
+
return request.param
|
| 920 |
+
|
| 921 |
+
|
| 922 |
+
@pytest.fixture(
|
| 923 |
+
params=[
|
| 924 |
+
operator.add,
|
| 925 |
+
ops.radd,
|
| 926 |
+
operator.sub,
|
| 927 |
+
ops.rsub,
|
| 928 |
+
operator.mul,
|
| 929 |
+
ops.rmul,
|
| 930 |
+
operator.truediv,
|
| 931 |
+
ops.rtruediv,
|
| 932 |
+
operator.floordiv,
|
| 933 |
+
ops.rfloordiv,
|
| 934 |
+
operator.mod,
|
| 935 |
+
ops.rmod,
|
| 936 |
+
operator.pow,
|
| 937 |
+
ops.rpow,
|
| 938 |
+
operator.eq,
|
| 939 |
+
operator.ne,
|
| 940 |
+
operator.lt,
|
| 941 |
+
operator.le,
|
| 942 |
+
operator.gt,
|
| 943 |
+
operator.ge,
|
| 944 |
+
operator.and_,
|
| 945 |
+
ops.rand_,
|
| 946 |
+
operator.xor,
|
| 947 |
+
ops.rxor,
|
| 948 |
+
operator.or_,
|
| 949 |
+
ops.ror_,
|
| 950 |
+
]
|
| 951 |
+
)
|
| 952 |
+
def all_binary_operators(request):
|
| 953 |
+
"""
|
| 954 |
+
Fixture for operator and roperator arithmetic, comparison, and logical ops.
|
| 955 |
+
"""
|
| 956 |
+
return request.param
|
| 957 |
+
|
| 958 |
+
|
| 959 |
+
@pytest.fixture(
|
| 960 |
+
params=[
|
| 961 |
+
operator.add,
|
| 962 |
+
ops.radd,
|
| 963 |
+
operator.sub,
|
| 964 |
+
ops.rsub,
|
| 965 |
+
operator.mul,
|
| 966 |
+
ops.rmul,
|
| 967 |
+
operator.truediv,
|
| 968 |
+
ops.rtruediv,
|
| 969 |
+
operator.floordiv,
|
| 970 |
+
ops.rfloordiv,
|
| 971 |
+
operator.mod,
|
| 972 |
+
ops.rmod,
|
| 973 |
+
operator.pow,
|
| 974 |
+
ops.rpow,
|
| 975 |
+
]
|
| 976 |
+
)
|
| 977 |
+
def all_arithmetic_functions(request):
|
| 978 |
+
"""
|
| 979 |
+
Fixture for operator and roperator arithmetic functions.
|
| 980 |
+
|
| 981 |
+
Notes
|
| 982 |
+
-----
|
| 983 |
+
This includes divmod and rdivmod, whereas all_arithmetic_operators
|
| 984 |
+
does not.
|
| 985 |
+
"""
|
| 986 |
+
return request.param
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
_all_numeric_reductions = [
|
| 990 |
+
"count",
|
| 991 |
+
"sum",
|
| 992 |
+
"max",
|
| 993 |
+
"min",
|
| 994 |
+
"mean",
|
| 995 |
+
"prod",
|
| 996 |
+
"std",
|
| 997 |
+
"var",
|
| 998 |
+
"median",
|
| 999 |
+
"kurt",
|
| 1000 |
+
"skew",
|
| 1001 |
+
"sem",
|
| 1002 |
+
]
|
| 1003 |
+
|
| 1004 |
+
|
| 1005 |
+
@pytest.fixture(params=_all_numeric_reductions)
|
| 1006 |
+
def all_numeric_reductions(request):
|
| 1007 |
+
"""
|
| 1008 |
+
Fixture for numeric reduction names.
|
| 1009 |
+
"""
|
| 1010 |
+
return request.param
|
| 1011 |
+
|
| 1012 |
+
|
| 1013 |
+
_all_boolean_reductions = ["all", "any"]
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
@pytest.fixture(params=_all_boolean_reductions)
|
| 1017 |
+
def all_boolean_reductions(request):
|
| 1018 |
+
"""
|
| 1019 |
+
Fixture for boolean reduction names.
|
| 1020 |
+
"""
|
| 1021 |
+
return request.param
|
| 1022 |
+
|
| 1023 |
+
|
| 1024 |
+
_all_reductions = _all_numeric_reductions + _all_boolean_reductions
|
| 1025 |
+
|
| 1026 |
+
|
| 1027 |
+
@pytest.fixture(params=_all_reductions)
|
| 1028 |
+
def all_reductions(request):
|
| 1029 |
+
"""
|
| 1030 |
+
Fixture for all (boolean + numeric) reduction names.
|
| 1031 |
+
"""
|
| 1032 |
+
return request.param
|
| 1033 |
+
|
| 1034 |
+
|
| 1035 |
+
@pytest.fixture(
|
| 1036 |
+
params=[
|
| 1037 |
+
operator.eq,
|
| 1038 |
+
operator.ne,
|
| 1039 |
+
operator.gt,
|
| 1040 |
+
operator.ge,
|
| 1041 |
+
operator.lt,
|
| 1042 |
+
operator.le,
|
| 1043 |
+
]
|
| 1044 |
+
)
|
| 1045 |
+
def comparison_op(request):
|
| 1046 |
+
"""
|
| 1047 |
+
Fixture for operator module comparison functions.
|
| 1048 |
+
"""
|
| 1049 |
+
return request.param
|
| 1050 |
+
|
| 1051 |
+
|
| 1052 |
+
@pytest.fixture(params=["__le__", "__lt__", "__ge__", "__gt__"])
|
| 1053 |
+
def compare_operators_no_eq_ne(request):
|
| 1054 |
+
"""
|
| 1055 |
+
Fixture for dunder names for compare operations except == and !=
|
| 1056 |
+
|
| 1057 |
+
* >=
|
| 1058 |
+
* >
|
| 1059 |
+
* <
|
| 1060 |
+
* <=
|
| 1061 |
+
"""
|
| 1062 |
+
return request.param
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
@pytest.fixture(
|
| 1066 |
+
params=["__and__", "__rand__", "__or__", "__ror__", "__xor__", "__rxor__"]
|
| 1067 |
+
)
|
| 1068 |
+
def all_logical_operators(request):
|
| 1069 |
+
"""
|
| 1070 |
+
Fixture for dunder names for common logical operations
|
| 1071 |
+
|
| 1072 |
+
* |
|
| 1073 |
+
* &
|
| 1074 |
+
* ^
|
| 1075 |
+
"""
|
| 1076 |
+
return request.param
|
| 1077 |
+
|
| 1078 |
+
|
| 1079 |
+
_all_numeric_accumulations = ["cumsum", "cumprod", "cummin", "cummax"]
|
| 1080 |
+
|
| 1081 |
+
|
| 1082 |
+
@pytest.fixture(params=_all_numeric_accumulations)
|
| 1083 |
+
def all_numeric_accumulations(request):
|
| 1084 |
+
"""
|
| 1085 |
+
Fixture for numeric accumulation names
|
| 1086 |
+
"""
|
| 1087 |
+
return request.param
|
| 1088 |
+
|
| 1089 |
+
|
| 1090 |
+
# ----------------------------------------------------------------
|
| 1091 |
+
# Data sets/files
|
| 1092 |
+
# ----------------------------------------------------------------
|
| 1093 |
+
@pytest.fixture
|
| 1094 |
+
def strict_data_files(pytestconfig):
|
| 1095 |
+
"""
|
| 1096 |
+
Returns the configuration for the test setting `--no-strict-data-files`.
|
| 1097 |
+
"""
|
| 1098 |
+
return pytestconfig.getoption("--no-strict-data-files")
|
| 1099 |
+
|
| 1100 |
+
|
| 1101 |
+
@pytest.fixture
|
| 1102 |
+
def datapath(strict_data_files: str) -> Callable[..., str]:
|
| 1103 |
+
"""
|
| 1104 |
+
Get the path to a data file.
|
| 1105 |
+
|
| 1106 |
+
Parameters
|
| 1107 |
+
----------
|
| 1108 |
+
path : str
|
| 1109 |
+
Path to the file, relative to ``pandas/tests/``
|
| 1110 |
+
|
| 1111 |
+
Returns
|
| 1112 |
+
-------
|
| 1113 |
+
path including ``pandas/tests``.
|
| 1114 |
+
|
| 1115 |
+
Raises
|
| 1116 |
+
------
|
| 1117 |
+
ValueError
|
| 1118 |
+
If the path doesn't exist and the --no-strict-data-files option is not set.
|
| 1119 |
+
"""
|
| 1120 |
+
BASE_PATH = os.path.join(os.path.dirname(__file__), "tests")
|
| 1121 |
+
|
| 1122 |
+
def deco(*args):
|
| 1123 |
+
path = os.path.join(BASE_PATH, *args)
|
| 1124 |
+
if not os.path.exists(path):
|
| 1125 |
+
if strict_data_files:
|
| 1126 |
+
raise ValueError(
|
| 1127 |
+
f"Could not find file {path} and --no-strict-data-files is not set."
|
| 1128 |
+
)
|
| 1129 |
+
pytest.skip(f"Could not find {path}.")
|
| 1130 |
+
return path
|
| 1131 |
+
|
| 1132 |
+
return deco
|
| 1133 |
+
|
| 1134 |
+
|
| 1135 |
+
# ----------------------------------------------------------------
|
| 1136 |
+
# Time zones
|
| 1137 |
+
# ----------------------------------------------------------------
|
| 1138 |
+
TIMEZONES = [
|
| 1139 |
+
None,
|
| 1140 |
+
"UTC",
|
| 1141 |
+
"US/Eastern",
|
| 1142 |
+
"Asia/Tokyo",
|
| 1143 |
+
"dateutil/US/Pacific",
|
| 1144 |
+
"dateutil/Asia/Singapore",
|
| 1145 |
+
"+01:15",
|
| 1146 |
+
"-02:15",
|
| 1147 |
+
"UTC+01:15",
|
| 1148 |
+
"UTC-02:15",
|
| 1149 |
+
tzutc(),
|
| 1150 |
+
tzlocal(),
|
| 1151 |
+
FixedOffset(300),
|
| 1152 |
+
FixedOffset(0),
|
| 1153 |
+
FixedOffset(-300),
|
| 1154 |
+
timezone.utc,
|
| 1155 |
+
timezone(timedelta(hours=1)),
|
| 1156 |
+
timezone(timedelta(hours=-1), name="foo"),
|
| 1157 |
+
]
|
| 1158 |
+
if zoneinfo is not None:
|
| 1159 |
+
TIMEZONES.extend(
|
| 1160 |
+
[
|
| 1161 |
+
zoneinfo.ZoneInfo("US/Pacific"), # type: ignore[list-item]
|
| 1162 |
+
zoneinfo.ZoneInfo("UTC"), # type: ignore[list-item]
|
| 1163 |
+
]
|
| 1164 |
+
)
|
| 1165 |
+
TIMEZONE_IDS = [repr(i) for i in TIMEZONES]
|
| 1166 |
+
|
| 1167 |
+
|
| 1168 |
+
@td.parametrize_fixture_doc(str(TIMEZONE_IDS))
|
| 1169 |
+
@pytest.fixture(params=TIMEZONES, ids=TIMEZONE_IDS)
|
| 1170 |
+
def tz_naive_fixture(request):
|
| 1171 |
+
"""
|
| 1172 |
+
Fixture for trying timezones including default (None): {0}
|
| 1173 |
+
"""
|
| 1174 |
+
return request.param
|
| 1175 |
+
|
| 1176 |
+
|
| 1177 |
+
@td.parametrize_fixture_doc(str(TIMEZONE_IDS[1:]))
|
| 1178 |
+
@pytest.fixture(params=TIMEZONES[1:], ids=TIMEZONE_IDS[1:])
|
| 1179 |
+
def tz_aware_fixture(request):
|
| 1180 |
+
"""
|
| 1181 |
+
Fixture for trying explicit timezones: {0}
|
| 1182 |
+
"""
|
| 1183 |
+
return request.param
|
| 1184 |
+
|
| 1185 |
+
|
| 1186 |
+
# Generate cartesian product of tz_aware_fixture:
|
| 1187 |
+
tz_aware_fixture2 = tz_aware_fixture
|
| 1188 |
+
|
| 1189 |
+
|
| 1190 |
+
_UTCS = ["utc", "dateutil/UTC", utc, tzutc(), timezone.utc]
|
| 1191 |
+
if zoneinfo is not None:
|
| 1192 |
+
_UTCS.append(zoneinfo.ZoneInfo("UTC"))
|
| 1193 |
+
|
| 1194 |
+
|
| 1195 |
+
@pytest.fixture(params=_UTCS)
|
| 1196 |
+
def utc_fixture(request):
|
| 1197 |
+
"""
|
| 1198 |
+
Fixture to provide variants of UTC timezone strings and tzinfo objects.
|
| 1199 |
+
"""
|
| 1200 |
+
return request.param
|
| 1201 |
+
|
| 1202 |
+
|
| 1203 |
+
utc_fixture2 = utc_fixture
|
| 1204 |
+
|
| 1205 |
+
|
| 1206 |
+
@pytest.fixture(params=["s", "ms", "us", "ns"])
|
| 1207 |
+
def unit(request):
|
| 1208 |
+
"""
|
| 1209 |
+
datetime64 units we support.
|
| 1210 |
+
"""
|
| 1211 |
+
return request.param
|
| 1212 |
+
|
| 1213 |
+
|
| 1214 |
+
unit2 = unit
|
| 1215 |
+
|
| 1216 |
+
|
| 1217 |
+
# ----------------------------------------------------------------
|
| 1218 |
+
# Dtypes
|
| 1219 |
+
# ----------------------------------------------------------------
|
| 1220 |
+
@pytest.fixture(params=tm.STRING_DTYPES)
|
| 1221 |
+
def string_dtype(request):
|
| 1222 |
+
"""
|
| 1223 |
+
Parametrized fixture for string dtypes.
|
| 1224 |
+
|
| 1225 |
+
* str
|
| 1226 |
+
* 'str'
|
| 1227 |
+
* 'U'
|
| 1228 |
+
"""
|
| 1229 |
+
return request.param
|
| 1230 |
+
|
| 1231 |
+
|
| 1232 |
+
@pytest.fixture(
|
| 1233 |
+
params=[
|
| 1234 |
+
("python", pd.NA),
|
| 1235 |
+
pytest.param(("pyarrow", pd.NA), marks=td.skip_if_no("pyarrow")),
|
| 1236 |
+
pytest.param(("pyarrow", np.nan), marks=td.skip_if_no("pyarrow")),
|
| 1237 |
+
("python", np.nan),
|
| 1238 |
+
],
|
| 1239 |
+
ids=[
|
| 1240 |
+
"string=string[python]",
|
| 1241 |
+
"string=string[pyarrow]",
|
| 1242 |
+
"string=str[pyarrow]",
|
| 1243 |
+
"string=str[python]",
|
| 1244 |
+
],
|
| 1245 |
+
)
|
| 1246 |
+
def string_dtype_no_object(request):
|
| 1247 |
+
"""
|
| 1248 |
+
Parametrized fixture for string dtypes.
|
| 1249 |
+
* 'string[python]' (NA variant)
|
| 1250 |
+
* 'string[pyarrow]' (NA variant)
|
| 1251 |
+
* 'str' (NaN variant, with pyarrow)
|
| 1252 |
+
* 'str' (NaN variant, without pyarrow)
|
| 1253 |
+
"""
|
| 1254 |
+
# need to instantiate the StringDtype here instead of in the params
|
| 1255 |
+
# to avoid importing pyarrow during test collection
|
| 1256 |
+
storage, na_value = request.param
|
| 1257 |
+
return pd.StringDtype(storage, na_value)
|
| 1258 |
+
|
| 1259 |
+
|
| 1260 |
+
@pytest.fixture(
|
| 1261 |
+
params=[
|
| 1262 |
+
"string[python]",
|
| 1263 |
+
pytest.param("string[pyarrow]", marks=td.skip_if_no("pyarrow")),
|
| 1264 |
+
]
|
| 1265 |
+
)
|
| 1266 |
+
def nullable_string_dtype(request):
|
| 1267 |
+
"""
|
| 1268 |
+
Parametrized fixture for string dtypes.
|
| 1269 |
+
|
| 1270 |
+
* 'string[python]'
|
| 1271 |
+
* 'string[pyarrow]'
|
| 1272 |
+
"""
|
| 1273 |
+
return request.param
|
| 1274 |
+
|
| 1275 |
+
|
| 1276 |
+
@pytest.fixture(
|
| 1277 |
+
params=[
|
| 1278 |
+
pytest.param(("pyarrow", np.nan), marks=td.skip_if_no("pyarrow")),
|
| 1279 |
+
pytest.param(("pyarrow", pd.NA), marks=td.skip_if_no("pyarrow")),
|
| 1280 |
+
]
|
| 1281 |
+
)
|
| 1282 |
+
def pyarrow_string_dtype(request):
|
| 1283 |
+
"""
|
| 1284 |
+
Parametrized fixture for string dtypes backed by Pyarrow.
|
| 1285 |
+
|
| 1286 |
+
* 'str[pyarrow]'
|
| 1287 |
+
* 'string[pyarrow]'
|
| 1288 |
+
"""
|
| 1289 |
+
return pd.StringDtype(*request.param)
|
| 1290 |
+
|
| 1291 |
+
|
| 1292 |
+
@pytest.fixture(
|
| 1293 |
+
params=[
|
| 1294 |
+
"python",
|
| 1295 |
+
pytest.param("pyarrow", marks=td.skip_if_no("pyarrow")),
|
| 1296 |
+
]
|
| 1297 |
+
)
|
| 1298 |
+
def string_storage(request):
|
| 1299 |
+
"""
|
| 1300 |
+
Parametrized fixture for pd.options.mode.string_storage.
|
| 1301 |
+
|
| 1302 |
+
* 'python'
|
| 1303 |
+
* 'pyarrow'
|
| 1304 |
+
"""
|
| 1305 |
+
return request.param
|
| 1306 |
+
|
| 1307 |
+
|
| 1308 |
+
@pytest.fixture(
|
| 1309 |
+
params=[
|
| 1310 |
+
("python", pd.NA),
|
| 1311 |
+
pytest.param(("pyarrow", pd.NA), marks=td.skip_if_no("pyarrow")),
|
| 1312 |
+
pytest.param(("pyarrow", np.nan), marks=td.skip_if_no("pyarrow")),
|
| 1313 |
+
("python", np.nan),
|
| 1314 |
+
],
|
| 1315 |
+
ids=[
|
| 1316 |
+
"string=string[python]",
|
| 1317 |
+
"string=string[pyarrow]",
|
| 1318 |
+
"string=str[pyarrow]",
|
| 1319 |
+
"string=str[python]",
|
| 1320 |
+
],
|
| 1321 |
+
)
|
| 1322 |
+
def string_dtype_arguments(request):
|
| 1323 |
+
"""
|
| 1324 |
+
Parametrized fixture for StringDtype storage and na_value.
|
| 1325 |
+
|
| 1326 |
+
* 'python' + pd.NA
|
| 1327 |
+
* 'pyarrow' + pd.NA
|
| 1328 |
+
* 'pyarrow' + np.nan
|
| 1329 |
+
"""
|
| 1330 |
+
return request.param
|
| 1331 |
+
|
| 1332 |
+
|
| 1333 |
+
@pytest.fixture(
|
| 1334 |
+
params=[
|
| 1335 |
+
"numpy_nullable",
|
| 1336 |
+
pytest.param("pyarrow", marks=td.skip_if_no("pyarrow")),
|
| 1337 |
+
]
|
| 1338 |
+
)
|
| 1339 |
+
def dtype_backend(request):
|
| 1340 |
+
"""
|
| 1341 |
+
Parametrized fixture for pd.options.mode.string_storage.
|
| 1342 |
+
|
| 1343 |
+
* 'python'
|
| 1344 |
+
* 'pyarrow'
|
| 1345 |
+
"""
|
| 1346 |
+
return request.param
|
| 1347 |
+
|
| 1348 |
+
|
| 1349 |
+
# Alias so we can test with cartesian product of string_storage
|
| 1350 |
+
string_storage2 = string_storage
|
| 1351 |
+
string_dtype_arguments2 = string_dtype_arguments
|
| 1352 |
+
|
| 1353 |
+
|
| 1354 |
+
@pytest.fixture(params=tm.BYTES_DTYPES)
|
| 1355 |
+
def bytes_dtype(request):
|
| 1356 |
+
"""
|
| 1357 |
+
Parametrized fixture for bytes dtypes.
|
| 1358 |
+
|
| 1359 |
+
* bytes
|
| 1360 |
+
* 'bytes'
|
| 1361 |
+
"""
|
| 1362 |
+
return request.param
|
| 1363 |
+
|
| 1364 |
+
|
| 1365 |
+
@pytest.fixture(params=tm.OBJECT_DTYPES)
|
| 1366 |
+
def object_dtype(request):
|
| 1367 |
+
"""
|
| 1368 |
+
Parametrized fixture for object dtypes.
|
| 1369 |
+
|
| 1370 |
+
* object
|
| 1371 |
+
* 'object'
|
| 1372 |
+
"""
|
| 1373 |
+
return request.param
|
| 1374 |
+
|
| 1375 |
+
|
| 1376 |
+
@pytest.fixture(
|
| 1377 |
+
params=[
|
| 1378 |
+
np.dtype("object"),
|
| 1379 |
+
("python", pd.NA),
|
| 1380 |
+
pytest.param(("pyarrow", pd.NA), marks=td.skip_if_no("pyarrow")),
|
| 1381 |
+
pytest.param(("pyarrow", np.nan), marks=td.skip_if_no("pyarrow")),
|
| 1382 |
+
("python", np.nan),
|
| 1383 |
+
],
|
| 1384 |
+
ids=[
|
| 1385 |
+
"string=object",
|
| 1386 |
+
"string=string[python]",
|
| 1387 |
+
"string=string[pyarrow]",
|
| 1388 |
+
"string=str[pyarrow]",
|
| 1389 |
+
"string=str[python]",
|
| 1390 |
+
],
|
| 1391 |
+
)
|
| 1392 |
+
def any_string_dtype(request):
|
| 1393 |
+
"""
|
| 1394 |
+
Parametrized fixture for string dtypes.
|
| 1395 |
+
* 'object'
|
| 1396 |
+
* 'string[python]' (NA variant)
|
| 1397 |
+
* 'string[pyarrow]' (NA variant)
|
| 1398 |
+
* 'str' (NaN variant, with pyarrow)
|
| 1399 |
+
* 'str' (NaN variant, without pyarrow)
|
| 1400 |
+
"""
|
| 1401 |
+
if isinstance(request.param, np.dtype):
|
| 1402 |
+
return request.param
|
| 1403 |
+
else:
|
| 1404 |
+
# need to instantiate the StringDtype here instead of in the params
|
| 1405 |
+
# to avoid importing pyarrow during test collection
|
| 1406 |
+
storage, na_value = request.param
|
| 1407 |
+
return pd.StringDtype(storage, na_value)
|
| 1408 |
+
|
| 1409 |
+
|
| 1410 |
+
@pytest.fixture(params=tm.DATETIME64_DTYPES)
|
| 1411 |
+
def datetime64_dtype(request):
|
| 1412 |
+
"""
|
| 1413 |
+
Parametrized fixture for datetime64 dtypes.
|
| 1414 |
+
|
| 1415 |
+
* 'datetime64[ns]'
|
| 1416 |
+
* 'M8[ns]'
|
| 1417 |
+
"""
|
| 1418 |
+
return request.param
|
| 1419 |
+
|
| 1420 |
+
|
| 1421 |
+
@pytest.fixture(params=tm.TIMEDELTA64_DTYPES)
|
| 1422 |
+
def timedelta64_dtype(request):
|
| 1423 |
+
"""
|
| 1424 |
+
Parametrized fixture for timedelta64 dtypes.
|
| 1425 |
+
|
| 1426 |
+
* 'timedelta64[ns]'
|
| 1427 |
+
* 'm8[ns]'
|
| 1428 |
+
"""
|
| 1429 |
+
return request.param
|
| 1430 |
+
|
| 1431 |
+
|
| 1432 |
+
@pytest.fixture
|
| 1433 |
+
def fixed_now_ts() -> Timestamp:
|
| 1434 |
+
"""
|
| 1435 |
+
Fixture emits fixed Timestamp.now()
|
| 1436 |
+
"""
|
| 1437 |
+
return Timestamp( # pyright: ignore[reportGeneralTypeIssues]
|
| 1438 |
+
year=2021, month=1, day=1, hour=12, minute=4, second=13, microsecond=22
|
| 1439 |
+
)
|
| 1440 |
+
|
| 1441 |
+
|
| 1442 |
+
@pytest.fixture(params=tm.FLOAT_NUMPY_DTYPES)
|
| 1443 |
+
def float_numpy_dtype(request):
|
| 1444 |
+
"""
|
| 1445 |
+
Parameterized fixture for float dtypes.
|
| 1446 |
+
|
| 1447 |
+
* float
|
| 1448 |
+
* 'float32'
|
| 1449 |
+
* 'float64'
|
| 1450 |
+
"""
|
| 1451 |
+
return request.param
|
| 1452 |
+
|
| 1453 |
+
|
| 1454 |
+
@pytest.fixture(params=tm.FLOAT_EA_DTYPES)
|
| 1455 |
+
def float_ea_dtype(request):
|
| 1456 |
+
"""
|
| 1457 |
+
Parameterized fixture for float dtypes.
|
| 1458 |
+
|
| 1459 |
+
* 'Float32'
|
| 1460 |
+
* 'Float64'
|
| 1461 |
+
"""
|
| 1462 |
+
return request.param
|
| 1463 |
+
|
| 1464 |
+
|
| 1465 |
+
@pytest.fixture(params=tm.ALL_FLOAT_DTYPES)
|
| 1466 |
+
def any_float_dtype(request):
|
| 1467 |
+
"""
|
| 1468 |
+
Parameterized fixture for float dtypes.
|
| 1469 |
+
|
| 1470 |
+
* float
|
| 1471 |
+
* 'float32'
|
| 1472 |
+
* 'float64'
|
| 1473 |
+
* 'Float32'
|
| 1474 |
+
* 'Float64'
|
| 1475 |
+
"""
|
| 1476 |
+
return request.param
|
| 1477 |
+
|
| 1478 |
+
|
| 1479 |
+
@pytest.fixture(params=tm.COMPLEX_DTYPES)
|
| 1480 |
+
def complex_dtype(request):
|
| 1481 |
+
"""
|
| 1482 |
+
Parameterized fixture for complex dtypes.
|
| 1483 |
+
|
| 1484 |
+
* complex
|
| 1485 |
+
* 'complex64'
|
| 1486 |
+
* 'complex128'
|
| 1487 |
+
"""
|
| 1488 |
+
return request.param
|
| 1489 |
+
|
| 1490 |
+
|
| 1491 |
+
@pytest.fixture(params=tm.COMPLEX_FLOAT_DTYPES)
|
| 1492 |
+
def complex_or_float_dtype(request):
|
| 1493 |
+
"""
|
| 1494 |
+
Parameterized fixture for complex and numpy float dtypes.
|
| 1495 |
+
|
| 1496 |
+
* complex
|
| 1497 |
+
* 'complex64'
|
| 1498 |
+
* 'complex128'
|
| 1499 |
+
* float
|
| 1500 |
+
* 'float32'
|
| 1501 |
+
* 'float64'
|
| 1502 |
+
"""
|
| 1503 |
+
return request.param
|
| 1504 |
+
|
| 1505 |
+
|
| 1506 |
+
@pytest.fixture(params=tm.SIGNED_INT_NUMPY_DTYPES)
|
| 1507 |
+
def any_signed_int_numpy_dtype(request):
|
| 1508 |
+
"""
|
| 1509 |
+
Parameterized fixture for signed integer dtypes.
|
| 1510 |
+
|
| 1511 |
+
* int
|
| 1512 |
+
* 'int8'
|
| 1513 |
+
* 'int16'
|
| 1514 |
+
* 'int32'
|
| 1515 |
+
* 'int64'
|
| 1516 |
+
"""
|
| 1517 |
+
return request.param
|
| 1518 |
+
|
| 1519 |
+
|
| 1520 |
+
@pytest.fixture(params=tm.UNSIGNED_INT_NUMPY_DTYPES)
|
| 1521 |
+
def any_unsigned_int_numpy_dtype(request):
|
| 1522 |
+
"""
|
| 1523 |
+
Parameterized fixture for unsigned integer dtypes.
|
| 1524 |
+
|
| 1525 |
+
* 'uint8'
|
| 1526 |
+
* 'uint16'
|
| 1527 |
+
* 'uint32'
|
| 1528 |
+
* 'uint64'
|
| 1529 |
+
"""
|
| 1530 |
+
return request.param
|
| 1531 |
+
|
| 1532 |
+
|
| 1533 |
+
@pytest.fixture(params=tm.ALL_INT_NUMPY_DTYPES)
|
| 1534 |
+
def any_int_numpy_dtype(request):
|
| 1535 |
+
"""
|
| 1536 |
+
Parameterized fixture for any integer dtype.
|
| 1537 |
+
|
| 1538 |
+
* int
|
| 1539 |
+
* 'int8'
|
| 1540 |
+
* 'uint8'
|
| 1541 |
+
* 'int16'
|
| 1542 |
+
* 'uint16'
|
| 1543 |
+
* 'int32'
|
| 1544 |
+
* 'uint32'
|
| 1545 |
+
* 'int64'
|
| 1546 |
+
* 'uint64'
|
| 1547 |
+
"""
|
| 1548 |
+
return request.param
|
| 1549 |
+
|
| 1550 |
+
|
| 1551 |
+
@pytest.fixture(params=tm.ALL_INT_EA_DTYPES)
|
| 1552 |
+
def any_int_ea_dtype(request):
|
| 1553 |
+
"""
|
| 1554 |
+
Parameterized fixture for any nullable integer dtype.
|
| 1555 |
+
|
| 1556 |
+
* 'UInt8'
|
| 1557 |
+
* 'Int8'
|
| 1558 |
+
* 'UInt16'
|
| 1559 |
+
* 'Int16'
|
| 1560 |
+
* 'UInt32'
|
| 1561 |
+
* 'Int32'
|
| 1562 |
+
* 'UInt64'
|
| 1563 |
+
* 'Int64'
|
| 1564 |
+
"""
|
| 1565 |
+
return request.param
|
| 1566 |
+
|
| 1567 |
+
|
| 1568 |
+
@pytest.fixture(params=tm.ALL_INT_DTYPES)
|
| 1569 |
+
def any_int_dtype(request):
|
| 1570 |
+
"""
|
| 1571 |
+
Parameterized fixture for any nullable integer dtype.
|
| 1572 |
+
|
| 1573 |
+
* int
|
| 1574 |
+
* 'int8'
|
| 1575 |
+
* 'uint8'
|
| 1576 |
+
* 'int16'
|
| 1577 |
+
* 'uint16'
|
| 1578 |
+
* 'int32'
|
| 1579 |
+
* 'uint32'
|
| 1580 |
+
* 'int64'
|
| 1581 |
+
* 'uint64'
|
| 1582 |
+
* 'UInt8'
|
| 1583 |
+
* 'Int8'
|
| 1584 |
+
* 'UInt16'
|
| 1585 |
+
* 'Int16'
|
| 1586 |
+
* 'UInt32'
|
| 1587 |
+
* 'Int32'
|
| 1588 |
+
* 'UInt64'
|
| 1589 |
+
* 'Int64'
|
| 1590 |
+
"""
|
| 1591 |
+
return request.param
|
| 1592 |
+
|
| 1593 |
+
|
| 1594 |
+
@pytest.fixture(params=tm.ALL_INT_EA_DTYPES + tm.FLOAT_EA_DTYPES)
|
| 1595 |
+
def any_numeric_ea_dtype(request):
|
| 1596 |
+
"""
|
| 1597 |
+
Parameterized fixture for any nullable integer dtype and
|
| 1598 |
+
any float ea dtypes.
|
| 1599 |
+
|
| 1600 |
+
* 'UInt8'
|
| 1601 |
+
* 'Int8'
|
| 1602 |
+
* 'UInt16'
|
| 1603 |
+
* 'Int16'
|
| 1604 |
+
* 'UInt32'
|
| 1605 |
+
* 'Int32'
|
| 1606 |
+
* 'UInt64'
|
| 1607 |
+
* 'Int64'
|
| 1608 |
+
* 'Float32'
|
| 1609 |
+
* 'Float64'
|
| 1610 |
+
"""
|
| 1611 |
+
return request.param
|
| 1612 |
+
|
| 1613 |
+
|
| 1614 |
+
# Unsupported operand types for + ("List[Union[str, ExtensionDtype, dtype[Any],
|
| 1615 |
+
# Type[object]]]" and "List[str]")
|
| 1616 |
+
@pytest.fixture(
|
| 1617 |
+
params=tm.ALL_INT_EA_DTYPES
|
| 1618 |
+
+ tm.FLOAT_EA_DTYPES
|
| 1619 |
+
+ tm.ALL_INT_PYARROW_DTYPES_STR_REPR
|
| 1620 |
+
+ tm.FLOAT_PYARROW_DTYPES_STR_REPR # type: ignore[operator]
|
| 1621 |
+
)
|
| 1622 |
+
def any_numeric_ea_and_arrow_dtype(request):
|
| 1623 |
+
"""
|
| 1624 |
+
Parameterized fixture for any nullable integer dtype and
|
| 1625 |
+
any float ea dtypes.
|
| 1626 |
+
|
| 1627 |
+
* 'UInt8'
|
| 1628 |
+
* 'Int8'
|
| 1629 |
+
* 'UInt16'
|
| 1630 |
+
* 'Int16'
|
| 1631 |
+
* 'UInt32'
|
| 1632 |
+
* 'Int32'
|
| 1633 |
+
* 'UInt64'
|
| 1634 |
+
* 'Int64'
|
| 1635 |
+
* 'Float32'
|
| 1636 |
+
* 'Float64'
|
| 1637 |
+
* 'uint8[pyarrow]'
|
| 1638 |
+
* 'int8[pyarrow]'
|
| 1639 |
+
* 'uint16[pyarrow]'
|
| 1640 |
+
* 'int16[pyarrow]'
|
| 1641 |
+
* 'uint32[pyarrow]'
|
| 1642 |
+
* 'int32[pyarrow]'
|
| 1643 |
+
* 'uint64[pyarrow]'
|
| 1644 |
+
* 'int64[pyarrow]'
|
| 1645 |
+
* 'float32[pyarrow]'
|
| 1646 |
+
* 'float64[pyarrow]'
|
| 1647 |
+
"""
|
| 1648 |
+
return request.param
|
| 1649 |
+
|
| 1650 |
+
|
| 1651 |
+
@pytest.fixture(params=tm.SIGNED_INT_EA_DTYPES)
|
| 1652 |
+
def any_signed_int_ea_dtype(request):
|
| 1653 |
+
"""
|
| 1654 |
+
Parameterized fixture for any signed nullable integer dtype.
|
| 1655 |
+
|
| 1656 |
+
* 'Int8'
|
| 1657 |
+
* 'Int16'
|
| 1658 |
+
* 'Int32'
|
| 1659 |
+
* 'Int64'
|
| 1660 |
+
"""
|
| 1661 |
+
return request.param
|
| 1662 |
+
|
| 1663 |
+
|
| 1664 |
+
@pytest.fixture(params=tm.ALL_REAL_NUMPY_DTYPES)
|
| 1665 |
+
def any_real_numpy_dtype(request):
|
| 1666 |
+
"""
|
| 1667 |
+
Parameterized fixture for any (purely) real numeric dtype.
|
| 1668 |
+
|
| 1669 |
+
* int
|
| 1670 |
+
* 'int8'
|
| 1671 |
+
* 'uint8'
|
| 1672 |
+
* 'int16'
|
| 1673 |
+
* 'uint16'
|
| 1674 |
+
* 'int32'
|
| 1675 |
+
* 'uint32'
|
| 1676 |
+
* 'int64'
|
| 1677 |
+
* 'uint64'
|
| 1678 |
+
* float
|
| 1679 |
+
* 'float32'
|
| 1680 |
+
* 'float64'
|
| 1681 |
+
"""
|
| 1682 |
+
return request.param
|
| 1683 |
+
|
| 1684 |
+
|
| 1685 |
+
@pytest.fixture(params=tm.ALL_REAL_DTYPES)
|
| 1686 |
+
def any_real_numeric_dtype(request):
|
| 1687 |
+
"""
|
| 1688 |
+
Parameterized fixture for any (purely) real numeric dtype.
|
| 1689 |
+
|
| 1690 |
+
* int
|
| 1691 |
+
* 'int8'
|
| 1692 |
+
* 'uint8'
|
| 1693 |
+
* 'int16'
|
| 1694 |
+
* 'uint16'
|
| 1695 |
+
* 'int32'
|
| 1696 |
+
* 'uint32'
|
| 1697 |
+
* 'int64'
|
| 1698 |
+
* 'uint64'
|
| 1699 |
+
* float
|
| 1700 |
+
* 'float32'
|
| 1701 |
+
* 'float64'
|
| 1702 |
+
|
| 1703 |
+
and associated ea dtypes.
|
| 1704 |
+
"""
|
| 1705 |
+
return request.param
|
| 1706 |
+
|
| 1707 |
+
|
| 1708 |
+
@pytest.fixture(params=tm.ALL_NUMPY_DTYPES)
|
| 1709 |
+
def any_numpy_dtype(request):
|
| 1710 |
+
"""
|
| 1711 |
+
Parameterized fixture for all numpy dtypes.
|
| 1712 |
+
|
| 1713 |
+
* bool
|
| 1714 |
+
* 'bool'
|
| 1715 |
+
* int
|
| 1716 |
+
* 'int8'
|
| 1717 |
+
* 'uint8'
|
| 1718 |
+
* 'int16'
|
| 1719 |
+
* 'uint16'
|
| 1720 |
+
* 'int32'
|
| 1721 |
+
* 'uint32'
|
| 1722 |
+
* 'int64'
|
| 1723 |
+
* 'uint64'
|
| 1724 |
+
* float
|
| 1725 |
+
* 'float32'
|
| 1726 |
+
* 'float64'
|
| 1727 |
+
* complex
|
| 1728 |
+
* 'complex64'
|
| 1729 |
+
* 'complex128'
|
| 1730 |
+
* str
|
| 1731 |
+
* 'str'
|
| 1732 |
+
* 'U'
|
| 1733 |
+
* bytes
|
| 1734 |
+
* 'bytes'
|
| 1735 |
+
* 'datetime64[ns]'
|
| 1736 |
+
* 'M8[ns]'
|
| 1737 |
+
* 'timedelta64[ns]'
|
| 1738 |
+
* 'm8[ns]'
|
| 1739 |
+
* object
|
| 1740 |
+
* 'object'
|
| 1741 |
+
"""
|
| 1742 |
+
return request.param
|
| 1743 |
+
|
| 1744 |
+
|
| 1745 |
+
@pytest.fixture(params=tm.ALL_REAL_NULLABLE_DTYPES)
|
| 1746 |
+
def any_real_nullable_dtype(request):
|
| 1747 |
+
"""
|
| 1748 |
+
Parameterized fixture for all real dtypes that can hold NA.
|
| 1749 |
+
|
| 1750 |
+
* float
|
| 1751 |
+
* 'float32'
|
| 1752 |
+
* 'float64'
|
| 1753 |
+
* 'Float32'
|
| 1754 |
+
* 'Float64'
|
| 1755 |
+
* 'UInt8'
|
| 1756 |
+
* 'UInt16'
|
| 1757 |
+
* 'UInt32'
|
| 1758 |
+
* 'UInt64'
|
| 1759 |
+
* 'Int8'
|
| 1760 |
+
* 'Int16'
|
| 1761 |
+
* 'Int32'
|
| 1762 |
+
* 'Int64'
|
| 1763 |
+
* 'uint8[pyarrow]'
|
| 1764 |
+
* 'uint16[pyarrow]'
|
| 1765 |
+
* 'uint32[pyarrow]'
|
| 1766 |
+
* 'uint64[pyarrow]'
|
| 1767 |
+
* 'int8[pyarrow]'
|
| 1768 |
+
* 'int16[pyarrow]'
|
| 1769 |
+
* 'int32[pyarrow]'
|
| 1770 |
+
* 'int64[pyarrow]'
|
| 1771 |
+
* 'float[pyarrow]'
|
| 1772 |
+
* 'double[pyarrow]'
|
| 1773 |
+
"""
|
| 1774 |
+
return request.param
|
| 1775 |
+
|
| 1776 |
+
|
| 1777 |
+
@pytest.fixture(params=tm.ALL_NUMERIC_DTYPES)
|
| 1778 |
+
def any_numeric_dtype(request):
|
| 1779 |
+
"""
|
| 1780 |
+
Parameterized fixture for all numeric dtypes.
|
| 1781 |
+
|
| 1782 |
+
* int
|
| 1783 |
+
* 'int8'
|
| 1784 |
+
* 'uint8'
|
| 1785 |
+
* 'int16'
|
| 1786 |
+
* 'uint16'
|
| 1787 |
+
* 'int32'
|
| 1788 |
+
* 'uint32'
|
| 1789 |
+
* 'int64'
|
| 1790 |
+
* 'uint64'
|
| 1791 |
+
* float
|
| 1792 |
+
* 'float32'
|
| 1793 |
+
* 'float64'
|
| 1794 |
+
* complex
|
| 1795 |
+
* 'complex64'
|
| 1796 |
+
* 'complex128'
|
| 1797 |
+
* 'UInt8'
|
| 1798 |
+
* 'Int8'
|
| 1799 |
+
* 'UInt16'
|
| 1800 |
+
* 'Int16'
|
| 1801 |
+
* 'UInt32'
|
| 1802 |
+
* 'Int32'
|
| 1803 |
+
* 'UInt64'
|
| 1804 |
+
* 'Int64'
|
| 1805 |
+
* 'Float32'
|
| 1806 |
+
* 'Float64'
|
| 1807 |
+
"""
|
| 1808 |
+
return request.param
|
| 1809 |
+
|
| 1810 |
+
|
| 1811 |
+
# categoricals are handled separately
|
| 1812 |
+
_any_skipna_inferred_dtype = [
|
| 1813 |
+
("string", ["a", np.nan, "c"]),
|
| 1814 |
+
("string", ["a", pd.NA, "c"]),
|
| 1815 |
+
("mixed", ["a", pd.NaT, "c"]), # pd.NaT not considered valid by is_string_array
|
| 1816 |
+
("bytes", [b"a", np.nan, b"c"]),
|
| 1817 |
+
("empty", [np.nan, np.nan, np.nan]),
|
| 1818 |
+
("empty", []),
|
| 1819 |
+
("mixed-integer", ["a", np.nan, 2]),
|
| 1820 |
+
("mixed", ["a", np.nan, 2.0]),
|
| 1821 |
+
("floating", [1.0, np.nan, 2.0]),
|
| 1822 |
+
("integer", [1, np.nan, 2]),
|
| 1823 |
+
("mixed-integer-float", [1, np.nan, 2.0]),
|
| 1824 |
+
("decimal", [Decimal(1), np.nan, Decimal(2)]),
|
| 1825 |
+
("boolean", [True, np.nan, False]),
|
| 1826 |
+
("boolean", [True, pd.NA, False]),
|
| 1827 |
+
("datetime64", [np.datetime64("2013-01-01"), np.nan, np.datetime64("2018-01-01")]),
|
| 1828 |
+
("datetime", [Timestamp("20130101"), np.nan, Timestamp("20180101")]),
|
| 1829 |
+
("date", [date(2013, 1, 1), np.nan, date(2018, 1, 1)]),
|
| 1830 |
+
("complex", [1 + 1j, np.nan, 2 + 2j]),
|
| 1831 |
+
# The following dtype is commented out due to GH 23554
|
| 1832 |
+
# ('timedelta64', [np.timedelta64(1, 'D'),
|
| 1833 |
+
# np.nan, np.timedelta64(2, 'D')]),
|
| 1834 |
+
("timedelta", [timedelta(1), np.nan, timedelta(2)]),
|
| 1835 |
+
("time", [time(1), np.nan, time(2)]),
|
| 1836 |
+
("period", [Period(2013), pd.NaT, Period(2018)]),
|
| 1837 |
+
("interval", [Interval(0, 1), np.nan, Interval(0, 2)]),
|
| 1838 |
+
]
|
| 1839 |
+
ids, _ = zip(*_any_skipna_inferred_dtype) # use inferred type as fixture-id
|
| 1840 |
+
|
| 1841 |
+
|
| 1842 |
+
@pytest.fixture(params=_any_skipna_inferred_dtype, ids=ids)
|
| 1843 |
+
def any_skipna_inferred_dtype(request):
|
| 1844 |
+
"""
|
| 1845 |
+
Fixture for all inferred dtypes from _libs.lib.infer_dtype
|
| 1846 |
+
|
| 1847 |
+
The covered (inferred) types are:
|
| 1848 |
+
* 'string'
|
| 1849 |
+
* 'empty'
|
| 1850 |
+
* 'bytes'
|
| 1851 |
+
* 'mixed'
|
| 1852 |
+
* 'mixed-integer'
|
| 1853 |
+
* 'mixed-integer-float'
|
| 1854 |
+
* 'floating'
|
| 1855 |
+
* 'integer'
|
| 1856 |
+
* 'decimal'
|
| 1857 |
+
* 'boolean'
|
| 1858 |
+
* 'datetime64'
|
| 1859 |
+
* 'datetime'
|
| 1860 |
+
* 'date'
|
| 1861 |
+
* 'timedelta'
|
| 1862 |
+
* 'time'
|
| 1863 |
+
* 'period'
|
| 1864 |
+
* 'interval'
|
| 1865 |
+
|
| 1866 |
+
Returns
|
| 1867 |
+
-------
|
| 1868 |
+
inferred_dtype : str
|
| 1869 |
+
The string for the inferred dtype from _libs.lib.infer_dtype
|
| 1870 |
+
values : np.ndarray
|
| 1871 |
+
An array of object dtype that will be inferred to have
|
| 1872 |
+
`inferred_dtype`
|
| 1873 |
+
|
| 1874 |
+
Examples
|
| 1875 |
+
--------
|
| 1876 |
+
>>> from pandas._libs import lib
|
| 1877 |
+
>>>
|
| 1878 |
+
>>> def test_something(any_skipna_inferred_dtype):
|
| 1879 |
+
... inferred_dtype, values = any_skipna_inferred_dtype
|
| 1880 |
+
... # will pass
|
| 1881 |
+
... assert lib.infer_dtype(values, skipna=True) == inferred_dtype
|
| 1882 |
+
"""
|
| 1883 |
+
inferred_dtype, values = request.param
|
| 1884 |
+
values = np.array(values, dtype=object) # object dtype to avoid casting
|
| 1885 |
+
|
| 1886 |
+
# correctness of inference tested in tests/dtypes/test_inference.py
|
| 1887 |
+
return inferred_dtype, values
|
| 1888 |
+
|
| 1889 |
+
|
| 1890 |
+
# ----------------------------------------------------------------
|
| 1891 |
+
# Misc
|
| 1892 |
+
# ----------------------------------------------------------------
|
| 1893 |
+
@pytest.fixture
|
| 1894 |
+
def ip():
|
| 1895 |
+
"""
|
| 1896 |
+
Get an instance of IPython.InteractiveShell.
|
| 1897 |
+
|
| 1898 |
+
Will raise a skip if IPython is not installed.
|
| 1899 |
+
"""
|
| 1900 |
+
pytest.importorskip("IPython", minversion="6.0.0")
|
| 1901 |
+
from IPython.core.interactiveshell import InteractiveShell
|
| 1902 |
+
|
| 1903 |
+
# GH#35711 make sure sqlite history file handle is not leaked
|
| 1904 |
+
from traitlets.config import Config # isort:skip
|
| 1905 |
+
|
| 1906 |
+
c = Config()
|
| 1907 |
+
c.HistoryManager.hist_file = ":memory:"
|
| 1908 |
+
|
| 1909 |
+
return InteractiveShell(config=c)
|
| 1910 |
+
|
| 1911 |
+
|
| 1912 |
+
@pytest.fixture(params=["bsr", "coo", "csc", "csr", "dia", "dok", "lil"])
|
| 1913 |
+
def spmatrix(request):
|
| 1914 |
+
"""
|
| 1915 |
+
Yields scipy sparse matrix classes.
|
| 1916 |
+
"""
|
| 1917 |
+
sparse = pytest.importorskip("scipy.sparse")
|
| 1918 |
+
|
| 1919 |
+
return getattr(sparse, request.param + "_matrix")
|
| 1920 |
+
|
| 1921 |
+
|
| 1922 |
+
@pytest.fixture(
|
| 1923 |
+
params=[
|
| 1924 |
+
getattr(pd.offsets, o)
|
| 1925 |
+
for o in pd.offsets.__all__
|
| 1926 |
+
if issubclass(getattr(pd.offsets, o), pd.offsets.Tick) and o != "Tick"
|
| 1927 |
+
]
|
| 1928 |
+
)
|
| 1929 |
+
def tick_classes(request):
|
| 1930 |
+
"""
|
| 1931 |
+
Fixture for Tick based datetime offsets available for a time series.
|
| 1932 |
+
"""
|
| 1933 |
+
return request.param
|
| 1934 |
+
|
| 1935 |
+
|
| 1936 |
+
@pytest.fixture(params=[None, lambda x: x])
|
| 1937 |
+
def sort_by_key(request):
|
| 1938 |
+
"""
|
| 1939 |
+
Simple fixture for testing keys in sorting methods.
|
| 1940 |
+
Tests None (no key) and the identity key.
|
| 1941 |
+
"""
|
| 1942 |
+
return request.param
|
| 1943 |
+
|
| 1944 |
+
|
| 1945 |
+
@pytest.fixture(
|
| 1946 |
+
params=[
|
| 1947 |
+
("foo", None, None),
|
| 1948 |
+
("Egon", "Venkman", None),
|
| 1949 |
+
("NCC1701D", "NCC1701D", "NCC1701D"),
|
| 1950 |
+
# possibly-matching NAs
|
| 1951 |
+
(np.nan, np.nan, np.nan),
|
| 1952 |
+
(np.nan, pd.NaT, None),
|
| 1953 |
+
(np.nan, pd.NA, None),
|
| 1954 |
+
(pd.NA, pd.NA, pd.NA),
|
| 1955 |
+
]
|
| 1956 |
+
)
|
| 1957 |
+
def names(request) -> tuple[Hashable, Hashable, Hashable]:
|
| 1958 |
+
"""
|
| 1959 |
+
A 3-tuple of names, the first two for operands, the last for a result.
|
| 1960 |
+
"""
|
| 1961 |
+
return request.param
|
| 1962 |
+
|
| 1963 |
+
|
| 1964 |
+
@pytest.fixture(params=[tm.setitem, tm.loc, tm.iloc])
|
| 1965 |
+
def indexer_sli(request):
|
| 1966 |
+
"""
|
| 1967 |
+
Parametrize over __setitem__, loc.__setitem__, iloc.__setitem__
|
| 1968 |
+
"""
|
| 1969 |
+
return request.param
|
| 1970 |
+
|
| 1971 |
+
|
| 1972 |
+
@pytest.fixture(params=[tm.loc, tm.iloc])
|
| 1973 |
+
def indexer_li(request):
|
| 1974 |
+
"""
|
| 1975 |
+
Parametrize over loc.__getitem__, iloc.__getitem__
|
| 1976 |
+
"""
|
| 1977 |
+
return request.param
|
| 1978 |
+
|
| 1979 |
+
|
| 1980 |
+
@pytest.fixture(params=[tm.setitem, tm.iloc])
|
| 1981 |
+
def indexer_si(request):
|
| 1982 |
+
"""
|
| 1983 |
+
Parametrize over __setitem__, iloc.__setitem__
|
| 1984 |
+
"""
|
| 1985 |
+
return request.param
|
| 1986 |
+
|
| 1987 |
+
|
| 1988 |
+
@pytest.fixture(params=[tm.setitem, tm.loc])
|
| 1989 |
+
def indexer_sl(request):
|
| 1990 |
+
"""
|
| 1991 |
+
Parametrize over __setitem__, loc.__setitem__
|
| 1992 |
+
"""
|
| 1993 |
+
return request.param
|
| 1994 |
+
|
| 1995 |
+
|
| 1996 |
+
@pytest.fixture(params=[tm.at, tm.loc])
|
| 1997 |
+
def indexer_al(request):
|
| 1998 |
+
"""
|
| 1999 |
+
Parametrize over at.__setitem__, loc.__setitem__
|
| 2000 |
+
"""
|
| 2001 |
+
return request.param
|
| 2002 |
+
|
| 2003 |
+
|
| 2004 |
+
@pytest.fixture(params=[tm.iat, tm.iloc])
|
| 2005 |
+
def indexer_ial(request):
|
| 2006 |
+
"""
|
| 2007 |
+
Parametrize over iat.__setitem__, iloc.__setitem__
|
| 2008 |
+
"""
|
| 2009 |
+
return request.param
|
| 2010 |
+
|
| 2011 |
+
|
| 2012 |
+
@pytest.fixture
|
| 2013 |
+
def using_array_manager() -> bool:
|
| 2014 |
+
"""
|
| 2015 |
+
Fixture to check if the array manager is being used.
|
| 2016 |
+
"""
|
| 2017 |
+
return _get_option("mode.data_manager", silent=True) == "array"
|
| 2018 |
+
|
| 2019 |
+
|
| 2020 |
+
@pytest.fixture
|
| 2021 |
+
def using_copy_on_write() -> bool:
|
| 2022 |
+
"""
|
| 2023 |
+
Fixture to check if Copy-on-Write is enabled.
|
| 2024 |
+
"""
|
| 2025 |
+
return (
|
| 2026 |
+
pd.options.mode.copy_on_write is True
|
| 2027 |
+
and _get_option("mode.data_manager", silent=True) == "block"
|
| 2028 |
+
)
|
| 2029 |
+
|
| 2030 |
+
|
| 2031 |
+
@pytest.fixture
|
| 2032 |
+
def warn_copy_on_write() -> bool:
|
| 2033 |
+
"""
|
| 2034 |
+
Fixture to check if Copy-on-Write is in warning mode.
|
| 2035 |
+
"""
|
| 2036 |
+
return (
|
| 2037 |
+
pd.options.mode.copy_on_write == "warn"
|
| 2038 |
+
and _get_option("mode.data_manager", silent=True) == "block"
|
| 2039 |
+
)
|
| 2040 |
+
|
| 2041 |
+
|
| 2042 |
+
@pytest.fixture
|
| 2043 |
+
def using_infer_string() -> bool:
|
| 2044 |
+
"""
|
| 2045 |
+
Fixture to check if infer string option is enabled.
|
| 2046 |
+
"""
|
| 2047 |
+
return pd.options.future.infer_string is True
|
| 2048 |
+
|
| 2049 |
+
|
| 2050 |
+
warsaws = ["Europe/Warsaw", "dateutil/Europe/Warsaw"]
|
| 2051 |
+
if zoneinfo is not None:
|
| 2052 |
+
warsaws.append(zoneinfo.ZoneInfo("Europe/Warsaw")) # type: ignore[arg-type]
|
| 2053 |
+
|
| 2054 |
+
|
| 2055 |
+
@pytest.fixture(params=warsaws)
|
| 2056 |
+
def warsaw(request) -> str:
|
| 2057 |
+
"""
|
| 2058 |
+
tzinfo for Europe/Warsaw using pytz, dateutil, or zoneinfo.
|
| 2059 |
+
"""
|
| 2060 |
+
return request.param
|
| 2061 |
+
|
| 2062 |
+
|
| 2063 |
+
@pytest.fixture()
|
| 2064 |
+
def arrow_string_storage():
|
| 2065 |
+
return ("pyarrow", "pyarrow_numpy")
|
shared/package-files/98/98b8dde9c3de47c453617f8b041c745642d5bc05982716fa304dd3e19501b963/_warnings.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# From scikit-image: https://github.com/scikit-image/scikit-image/blob/c2f8c4ab123ebe5f7b827bc495625a32bb225c10/skimage/_shared/_warnings.py
|
| 2 |
+
# Licensed under modified BSD license
|
| 3 |
+
|
| 4 |
+
__all__ = ["all_warnings", "expected_warnings"]
|
| 5 |
+
|
| 6 |
+
import inspect
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
import sys
|
| 10 |
+
import warnings
|
| 11 |
+
from contextlib import contextmanager
|
| 12 |
+
from unittest import mock
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@contextmanager
|
| 16 |
+
def all_warnings():
|
| 17 |
+
"""
|
| 18 |
+
Context for use in testing to ensure that all warnings are raised.
|
| 19 |
+
Examples
|
| 20 |
+
--------
|
| 21 |
+
>>> import warnings
|
| 22 |
+
>>> def foo():
|
| 23 |
+
... warnings.warn(RuntimeWarning("bar"))
|
| 24 |
+
|
| 25 |
+
We raise the warning once, while the warning filter is set to "once".
|
| 26 |
+
Hereafter, the warning is invisible, even with custom filters:
|
| 27 |
+
>>> with warnings.catch_warnings():
|
| 28 |
+
... warnings.simplefilter('once')
|
| 29 |
+
... foo()
|
| 30 |
+
|
| 31 |
+
We can now run ``foo()`` without a warning being raised:
|
| 32 |
+
>>> from numpy.testing import assert_warns # doctest: +SKIP
|
| 33 |
+
>>> foo() # doctest: +SKIP
|
| 34 |
+
|
| 35 |
+
To catch the warning, we call in the help of ``all_warnings``:
|
| 36 |
+
>>> with all_warnings(): # doctest: +SKIP
|
| 37 |
+
... assert_warns(RuntimeWarning, foo)
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
# Whenever a warning is triggered, Python adds a __warningregistry__
|
| 41 |
+
# member to the *calling* module. The exercize here is to find
|
| 42 |
+
# and eradicate all those breadcrumbs that were left lying around.
|
| 43 |
+
#
|
| 44 |
+
# We proceed by first searching all parent calling frames and explicitly
|
| 45 |
+
# clearing their warning registries (necessary for the doctests above to
|
| 46 |
+
# pass). Then, we search for all submodules of skimage and clear theirs
|
| 47 |
+
# as well (necessary for the skimage test suite to pass).
|
| 48 |
+
|
| 49 |
+
frame = inspect.currentframe()
|
| 50 |
+
if frame:
|
| 51 |
+
for f in inspect.getouterframes(frame):
|
| 52 |
+
f[0].f_locals["__warningregistry__"] = {}
|
| 53 |
+
del frame
|
| 54 |
+
|
| 55 |
+
for _, mod in list(sys.modules.items()):
|
| 56 |
+
try:
|
| 57 |
+
mod.__warningregistry__.clear()
|
| 58 |
+
except AttributeError:
|
| 59 |
+
pass
|
| 60 |
+
|
| 61 |
+
with warnings.catch_warnings(record=True) as w, mock.patch.dict(
|
| 62 |
+
os.environ, {"TRAITLETS_ALL_DEPRECATIONS": "1"}
|
| 63 |
+
):
|
| 64 |
+
warnings.simplefilter("always")
|
| 65 |
+
yield w
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@contextmanager
|
| 69 |
+
def expected_warnings(matching):
|
| 70 |
+
r"""Context for use in testing to catch known warnings matching regexes
|
| 71 |
+
|
| 72 |
+
Parameters
|
| 73 |
+
----------
|
| 74 |
+
matching : list of strings or compiled regexes
|
| 75 |
+
Regexes for the desired warning to catch
|
| 76 |
+
|
| 77 |
+
Examples
|
| 78 |
+
--------
|
| 79 |
+
>>> from skimage import data, img_as_ubyte, img_as_float # doctest: +SKIP
|
| 80 |
+
>>> with expected_warnings(["precision loss"]): # doctest: +SKIP
|
| 81 |
+
... d = img_as_ubyte(img_as_float(data.coins())) # doctest: +SKIP
|
| 82 |
+
|
| 83 |
+
Notes
|
| 84 |
+
-----
|
| 85 |
+
Uses `all_warnings` to ensure all warnings are raised.
|
| 86 |
+
Upon exiting, it checks the recorded warnings for the desired matching
|
| 87 |
+
pattern(s).
|
| 88 |
+
Raises a ValueError if any match was not found or an unexpected
|
| 89 |
+
warning was raised.
|
| 90 |
+
Allows for three types of behaviors: "and", "or", and "optional" matches.
|
| 91 |
+
This is done to accomodate different build enviroments or loop conditions
|
| 92 |
+
that may produce different warnings. The behaviors can be combined.
|
| 93 |
+
If you pass multiple patterns, you get an orderless "and", where all of the
|
| 94 |
+
warnings must be raised.
|
| 95 |
+
If you use the "|" operator in a pattern, you can catch one of several warnings.
|
| 96 |
+
Finally, you can use "|\A\Z" in a pattern to signify it as optional.
|
| 97 |
+
"""
|
| 98 |
+
with all_warnings() as w:
|
| 99 |
+
# enter context
|
| 100 |
+
yield w
|
| 101 |
+
# exited user context, check the recorded warnings
|
| 102 |
+
remaining = [m for m in matching if r"\A\Z" not in m.split("|")]
|
| 103 |
+
for warn in w:
|
| 104 |
+
found = False
|
| 105 |
+
for match in matching:
|
| 106 |
+
if re.search(match, str(warn.message)) is not None:
|
| 107 |
+
found = True
|
| 108 |
+
if match in remaining:
|
| 109 |
+
remaining.remove(match)
|
| 110 |
+
if not found:
|
| 111 |
+
raise ValueError("Unexpected warning: %s" % str(warn.message))
|
| 112 |
+
if len(remaining) > 0:
|
| 113 |
+
msg = "No warning raised matching:\n%s" % "\n".join(remaining)
|
| 114 |
+
raise ValueError(msg)
|
shared/package-files/98/98bf278df7fbace3255edc6690ef155e9a36472c7ee7dbc306a84f8f07bafa61/nll_loss_nd_native.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor nll_loss_nd_symint(const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight={}, int64_t reduction=at::Reduction::Mean, c10::SymInt ignore_index=-100);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
shared/package-files/98/98e0487d7357b3bc5df729d23ed1d391a66d9e2665f9ed328dabacc228d4bb83/_cast_Long_ops.h
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API _cast_Long {
|
| 18 |
+
using schema = at::Tensor (const at::Tensor &, bool);
|
| 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::_cast_Long")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_cast_Long(Tensor self, bool non_blocking=False) -> Tensor")
|
| 24 |
+
static at::Tensor call(const at::Tensor & self, bool non_blocking);
|
| 25 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, bool non_blocking);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
}} // namespace at::_ops
|
shared/package-files/d1/d10ac70fd4d82a5499b8ef1dae75376d4149ad2bbcbf94a772ab6445258b8c63/euler.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module implements a method to find
|
| 3 |
+
Euler-Lagrange Equations for given Lagrangian.
|
| 4 |
+
"""
|
| 5 |
+
from itertools import combinations_with_replacement
|
| 6 |
+
from sympy.core.function import (Derivative, Function, diff)
|
| 7 |
+
from sympy.core.relational import Eq
|
| 8 |
+
from sympy.core.singleton import S
|
| 9 |
+
from sympy.core.symbol import Symbol
|
| 10 |
+
from sympy.core.sympify import sympify
|
| 11 |
+
from sympy.utilities.iterables import iterable
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def euler_equations(L, funcs=(), vars=()):
|
| 15 |
+
r"""
|
| 16 |
+
Find the Euler-Lagrange equations [1]_ for a given Lagrangian.
|
| 17 |
+
|
| 18 |
+
Parameters
|
| 19 |
+
==========
|
| 20 |
+
|
| 21 |
+
L : Expr
|
| 22 |
+
The Lagrangian that should be a function of the functions listed
|
| 23 |
+
in the second argument and their derivatives.
|
| 24 |
+
|
| 25 |
+
For example, in the case of two functions $f(x,y)$, $g(x,y)$ and
|
| 26 |
+
two independent variables $x$, $y$ the Lagrangian has the form:
|
| 27 |
+
|
| 28 |
+
.. math:: L\left(f(x,y),g(x,y),\frac{\partial f(x,y)}{\partial x},
|
| 29 |
+
\frac{\partial f(x,y)}{\partial y},
|
| 30 |
+
\frac{\partial g(x,y)}{\partial x},
|
| 31 |
+
\frac{\partial g(x,y)}{\partial y},x,y\right)
|
| 32 |
+
|
| 33 |
+
In many cases it is not necessary to provide anything, except the
|
| 34 |
+
Lagrangian, it will be auto-detected (and an error raised if this
|
| 35 |
+
cannot be done).
|
| 36 |
+
|
| 37 |
+
funcs : Function or an iterable of Functions
|
| 38 |
+
The functions that the Lagrangian depends on. The Euler equations
|
| 39 |
+
are differential equations for each of these functions.
|
| 40 |
+
|
| 41 |
+
vars : Symbol or an iterable of Symbols
|
| 42 |
+
The Symbols that are the independent variables of the functions.
|
| 43 |
+
|
| 44 |
+
Returns
|
| 45 |
+
=======
|
| 46 |
+
|
| 47 |
+
eqns : list of Eq
|
| 48 |
+
The list of differential equations, one for each function.
|
| 49 |
+
|
| 50 |
+
Examples
|
| 51 |
+
========
|
| 52 |
+
|
| 53 |
+
>>> from sympy import euler_equations, Symbol, Function
|
| 54 |
+
>>> x = Function('x')
|
| 55 |
+
>>> t = Symbol('t')
|
| 56 |
+
>>> L = (x(t).diff(t))**2/2 - x(t)**2/2
|
| 57 |
+
>>> euler_equations(L, x(t), t)
|
| 58 |
+
[Eq(-x(t) - Derivative(x(t), (t, 2)), 0)]
|
| 59 |
+
>>> u = Function('u')
|
| 60 |
+
>>> x = Symbol('x')
|
| 61 |
+
>>> L = (u(t, x).diff(t))**2/2 - (u(t, x).diff(x))**2/2
|
| 62 |
+
>>> euler_equations(L, u(t, x), [t, x])
|
| 63 |
+
[Eq(-Derivative(u(t, x), (t, 2)) + Derivative(u(t, x), (x, 2)), 0)]
|
| 64 |
+
|
| 65 |
+
References
|
| 66 |
+
==========
|
| 67 |
+
|
| 68 |
+
.. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Lagrange_equation
|
| 69 |
+
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
funcs = tuple(funcs) if iterable(funcs) else (funcs,)
|
| 73 |
+
|
| 74 |
+
if not funcs:
|
| 75 |
+
funcs = tuple(L.atoms(Function))
|
| 76 |
+
else:
|
| 77 |
+
for f in funcs:
|
| 78 |
+
if not isinstance(f, Function):
|
| 79 |
+
raise TypeError('Function expected, got: %s' % f)
|
| 80 |
+
|
| 81 |
+
vars = tuple(vars) if iterable(vars) else (vars,)
|
| 82 |
+
|
| 83 |
+
if not vars:
|
| 84 |
+
vars = funcs[0].args
|
| 85 |
+
else:
|
| 86 |
+
vars = tuple(sympify(var) for var in vars)
|
| 87 |
+
|
| 88 |
+
if not all(isinstance(v, Symbol) for v in vars):
|
| 89 |
+
raise TypeError('Variables are not symbols, got %s' % vars)
|
| 90 |
+
|
| 91 |
+
for f in funcs:
|
| 92 |
+
if not vars == f.args:
|
| 93 |
+
raise ValueError("Variables %s do not match args: %s" % (vars, f))
|
| 94 |
+
|
| 95 |
+
order = max([len(d.variables) for d in L.atoms(Derivative)
|
| 96 |
+
if d.expr in funcs] + [0])
|
| 97 |
+
|
| 98 |
+
eqns = []
|
| 99 |
+
for f in funcs:
|
| 100 |
+
eq = diff(L, f)
|
| 101 |
+
for i in range(1, order + 1):
|
| 102 |
+
for p in combinations_with_replacement(vars, i):
|
| 103 |
+
eq = eq + S.NegativeOne**i*diff(L, diff(f, *p), *p)
|
| 104 |
+
new_eq = Eq(eq, 0)
|
| 105 |
+
if isinstance(new_eq, Eq):
|
| 106 |
+
eqns.append(new_eq)
|
| 107 |
+
|
| 108 |
+
return eqns
|
shared/package-files/d1/d1119423dda95126d93a1095b189e7832c14d70332dcdd2d0af063f26349bbdf/fbgemm_pack_quantized_matrix_native.h
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor fbgemm_pack_quantized_matrix(const at::Tensor & input);
|
| 20 |
+
TORCH_API at::Tensor fbgemm_pack_quantized_matrix(const at::Tensor & input, int64_t K, int64_t N);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
shared/package-files/d1/d115718818e3e3367847ce35bb5ff0361d08993d9749d438c918f8eb87ad8814/mt.msg
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# created by tools/loadICU.tcl -- do not edit
|
| 2 |
+
namespace eval ::tcl::clock {
|
| 3 |
+
::msgcat::mcset mt DAYS_OF_WEEK_ABBREV [list \
|
| 4 |
+
"\u0126ad"\
|
| 5 |
+
"Tne"\
|
| 6 |
+
"Tli"\
|
| 7 |
+
"Erb"\
|
| 8 |
+
"\u0126am"\
|
| 9 |
+
"\u0120im"]
|
| 10 |
+
::msgcat::mcset mt MONTHS_ABBREV [list \
|
| 11 |
+
"Jan"\
|
| 12 |
+
"Fra"\
|
| 13 |
+
"Mar"\
|
| 14 |
+
"Apr"\
|
| 15 |
+
"Mej"\
|
| 16 |
+
"\u0120un"\
|
| 17 |
+
"Lul"\
|
| 18 |
+
"Awi"\
|
| 19 |
+
"Set"\
|
| 20 |
+
"Ott"\
|
| 21 |
+
"Nov"]
|
| 22 |
+
::msgcat::mcset mt BCE "QK"
|
| 23 |
+
::msgcat::mcset mt CE ""
|
| 24 |
+
::msgcat::mcset mt DATE_FORMAT "%A, %e ta %B, %Y"
|
| 25 |
+
::msgcat::mcset mt TIME_FORMAT_12 "%l:%M:%S %P"
|
| 26 |
+
::msgcat::mcset mt DATE_TIME_FORMAT "%A, %e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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import operator
|
| 3 |
+
|
| 4 |
+
import types as pytypes
|
| 5 |
+
import operator
|
| 6 |
+
import warnings
|
| 7 |
+
from dataclasses import make_dataclass
|
| 8 |
+
|
| 9 |
+
import llvmlite.ir
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
import numba
|
| 13 |
+
from numba.parfors import parfor
|
| 14 |
+
from numba.core import types, ir, config, compiler, sigutils, cgutils
|
| 15 |
+
from numba.core.ir_utils import (
|
| 16 |
+
add_offset_to_labels,
|
| 17 |
+
replace_var_names,
|
| 18 |
+
remove_dels,
|
| 19 |
+
legalize_names,
|
| 20 |
+
rename_labels,
|
| 21 |
+
get_name_var_table,
|
| 22 |
+
visit_vars_inner,
|
| 23 |
+
get_definition,
|
| 24 |
+
guard,
|
| 25 |
+
get_call_table,
|
| 26 |
+
is_pure,
|
| 27 |
+
get_np_ufunc_typ,
|
| 28 |
+
get_unused_var_name,
|
| 29 |
+
is_const_call,
|
| 30 |
+
fixup_var_define_in_scope,
|
| 31 |
+
transfer_scope,
|
| 32 |
+
find_max_label,
|
| 33 |
+
get_global_func_typ,
|
| 34 |
+
find_topo_order,
|
| 35 |
+
)
|
| 36 |
+
from numba.core.typing import signature
|
| 37 |
+
from numba.core import lowering
|
| 38 |
+
from numba.parfors.parfor import ensure_parallel_support
|
| 39 |
+
from numba.core.errors import (
|
| 40 |
+
NumbaParallelSafetyWarning, NotDefinedError, CompilerError, InternalError,
|
| 41 |
+
)
|
| 42 |
+
from numba.parfors.parfor_lowering_utils import ParforLoweringBuilder
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class ParforLower(lowering.Lower):
|
| 46 |
+
"""This is a custom lowering class that extends standard lowering so as
|
| 47 |
+
to accommodate parfor.Parfor nodes."""
|
| 48 |
+
|
| 49 |
+
# custom instruction lowering to handle parfor nodes
|
| 50 |
+
def lower_inst(self, inst):
|
| 51 |
+
if isinstance(inst, parfor.Parfor):
|
| 52 |
+
_lower_parfor_parallel(self, inst)
|
| 53 |
+
else:
|
| 54 |
+
super().lower_inst(inst)
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def _disable_sroa_like_opt(self):
|
| 58 |
+
"""
|
| 59 |
+
Force disable this because Parfor use-defs is incompatible---it only
|
| 60 |
+
considers use-defs in blocks that must be executing.
|
| 61 |
+
See https://github.com/numba/numba/commit/017e2ff9db87fc34149b49dd5367ecbf0bb45268
|
| 62 |
+
"""
|
| 63 |
+
return True
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _lower_parfor_parallel(lowerer, parfor):
|
| 67 |
+
if parfor.lowerer is None:
|
| 68 |
+
return _lower_parfor_parallel_std(lowerer, parfor)
|
| 69 |
+
else:
|
| 70 |
+
return parfor.lowerer(lowerer, parfor)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _lower_parfor_parallel_std(lowerer, parfor):
|
| 74 |
+
"""Lowerer that handles LLVM code generation for parfor.
|
| 75 |
+
This function lowers a parfor IR node to LLVM.
|
| 76 |
+
The general approach is as follows:
|
| 77 |
+
1) The code from the parfor's init block is lowered normally
|
| 78 |
+
in the context of the current function.
|
| 79 |
+
2) The body of the parfor is transformed into a gufunc function.
|
| 80 |
+
3) Code is inserted into the main function that calls do_scheduling
|
| 81 |
+
to divide the iteration space for each thread, allocates
|
| 82 |
+
reduction arrays, calls the gufunc function, and then invokes
|
| 83 |
+
the reduction function across the reduction arrays to produce
|
| 84 |
+
the final reduction values.
|
| 85 |
+
"""
|
| 86 |
+
from numba.np.ufunc.parallel import get_thread_count
|
| 87 |
+
|
| 88 |
+
ensure_parallel_support()
|
| 89 |
+
typingctx = lowerer.context.typing_context
|
| 90 |
+
targetctx = lowerer.context
|
| 91 |
+
builder = lowerer.builder
|
| 92 |
+
# We copy the typemap here because for race condition variable we'll
|
| 93 |
+
# update their type to array so they can be updated by the gufunc.
|
| 94 |
+
orig_typemap = lowerer.fndesc.typemap
|
| 95 |
+
# replace original typemap with copy and restore the original at the end.
|
| 96 |
+
lowerer.fndesc.typemap = copy.copy(orig_typemap)
|
| 97 |
+
if config.DEBUG_ARRAY_OPT:
|
| 98 |
+
print("lowerer.fndesc", lowerer.fndesc, type(lowerer.fndesc))
|
| 99 |
+
typemap = lowerer.fndesc.typemap
|
| 100 |
+
varmap = lowerer.varmap
|
| 101 |
+
|
| 102 |
+
if config.DEBUG_ARRAY_OPT:
|
| 103 |
+
print("_lower_parfor_parallel")
|
| 104 |
+
parfor.dump()
|
| 105 |
+
|
| 106 |
+
loc = parfor.init_block.loc
|
| 107 |
+
scope = parfor.init_block.scope
|
| 108 |
+
|
| 109 |
+
# produce instructions for init_block
|
| 110 |
+
if config.DEBUG_ARRAY_OPT:
|
| 111 |
+
print("init_block = ", parfor.init_block, " ", type(parfor.init_block))
|
| 112 |
+
for instr in parfor.init_block.body:
|
| 113 |
+
if config.DEBUG_ARRAY_OPT:
|
| 114 |
+
print("lower init_block instr = ", instr)
|
| 115 |
+
lowerer.lower_inst(instr)
|
| 116 |
+
|
| 117 |
+
for racevar in parfor.races:
|
| 118 |
+
if racevar not in varmap:
|
| 119 |
+
rvtyp = typemap[racevar]
|
| 120 |
+
rv = ir.Var(scope, racevar, loc)
|
| 121 |
+
lowerer._alloca_var(rv.name, rvtyp)
|
| 122 |
+
|
| 123 |
+
alias_map = {}
|
| 124 |
+
arg_aliases = {}
|
| 125 |
+
numba.parfors.parfor.find_potential_aliases_parfor(parfor, parfor.params, typemap,
|
| 126 |
+
lowerer.func_ir, alias_map, arg_aliases)
|
| 127 |
+
if config.DEBUG_ARRAY_OPT:
|
| 128 |
+
print("alias_map", alias_map)
|
| 129 |
+
print("arg_aliases", arg_aliases)
|
| 130 |
+
|
| 131 |
+
# run get_parfor_outputs() and get_parfor_reductions() before gufunc creation
|
| 132 |
+
# since Jumps are modified so CFG of loop_body dict will become invalid
|
| 133 |
+
assert parfor.params is not None
|
| 134 |
+
|
| 135 |
+
parfor_output_arrays = numba.parfors.parfor.get_parfor_outputs(
|
| 136 |
+
parfor, parfor.params)
|
| 137 |
+
parfor_redvars, parfor_reddict = parfor.redvars, parfor.reddict
|
| 138 |
+
if config.DEBUG_ARRAY_OPT:
|
| 139 |
+
print("parfor_redvars:", parfor_redvars)
|
| 140 |
+
print("parfor_reddict:", parfor_reddict)
|
| 141 |
+
|
| 142 |
+
# init reduction array allocation here.
|
| 143 |
+
nredvars = len(parfor_redvars)
|
| 144 |
+
redarrs = {}
|
| 145 |
+
to_cleanup = []
|
| 146 |
+
if nredvars > 0:
|
| 147 |
+
# reduction arrays outer dimension equal to thread count
|
| 148 |
+
scope = parfor.init_block.scope
|
| 149 |
+
loc = parfor.init_block.loc
|
| 150 |
+
pfbdr = ParforLoweringBuilder(lowerer=lowerer, scope=scope, loc=loc)
|
| 151 |
+
|
| 152 |
+
# Get the Numba internal function to call to get the thread count.
|
| 153 |
+
get_num_threads = pfbdr.bind_global_function(
|
| 154 |
+
fobj=numba.np.ufunc.parallel._iget_num_threads,
|
| 155 |
+
ftype=get_global_func_typ(numba.np.ufunc.parallel._iget_num_threads),
|
| 156 |
+
args=()
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
# Insert the call to assign the thread count to a variable.
|
| 160 |
+
num_threads_var = pfbdr.assign(
|
| 161 |
+
rhs=pfbdr.call(get_num_threads, args=[]),
|
| 162 |
+
typ=types.intp,
|
| 163 |
+
name="num_threads_var")
|
| 164 |
+
|
| 165 |
+
# For each reduction variable...
|
| 166 |
+
for i in range(nredvars):
|
| 167 |
+
red_name = parfor_redvars[i]
|
| 168 |
+
# Get the type of the reduction variable.
|
| 169 |
+
redvar_typ = lowerer.fndesc.typemap[red_name]
|
| 170 |
+
# Get the ir.Var for the reduction variable.
|
| 171 |
+
redvar = ir.Var(scope, red_name, loc)
|
| 172 |
+
# Get the type of the array that holds the per-thread
|
| 173 |
+
# reduction variables.
|
| 174 |
+
redarrvar_typ = redtyp_to_redarraytype(redvar_typ)
|
| 175 |
+
reddtype = redarrvar_typ.dtype
|
| 176 |
+
if config.DEBUG_ARRAY_OPT:
|
| 177 |
+
print(
|
| 178 |
+
"reduction_info",
|
| 179 |
+
red_name,
|
| 180 |
+
redvar_typ,
|
| 181 |
+
redarrvar_typ,
|
| 182 |
+
reddtype,
|
| 183 |
+
types.DType(reddtype),
|
| 184 |
+
num_threads_var,
|
| 185 |
+
type(num_threads_var)
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
# If this is reduction over an array,
|
| 189 |
+
# the reduction array has just one added per-worker dimension.
|
| 190 |
+
if isinstance(redvar_typ, types.npytypes.Array):
|
| 191 |
+
redarrdim = redvar_typ.ndim + 1
|
| 192 |
+
else:
|
| 193 |
+
redarrdim = 1
|
| 194 |
+
|
| 195 |
+
# Reduction array is created and initialized to the initial reduction value.
|
| 196 |
+
|
| 197 |
+
# First create a var for the numpy empty ufunc.
|
| 198 |
+
glbl_np_empty = pfbdr.bind_global_function(
|
| 199 |
+
fobj=np.empty,
|
| 200 |
+
ftype=get_np_ufunc_typ(np.empty, pfbdr._typingctx),
|
| 201 |
+
args=(
|
| 202 |
+
types.UniTuple(types.intp, redarrdim),
|
| 203 |
+
),
|
| 204 |
+
kws={'dtype': types.DType(reddtype)}
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
size_var_list = [num_threads_var]
|
| 208 |
+
|
| 209 |
+
# If this is a reduction over an array...
|
| 210 |
+
if isinstance(redvar_typ, types.npytypes.Array):
|
| 211 |
+
# Add code to get the shape of the array being reduced over.
|
| 212 |
+
redshape_var = pfbdr.assign(
|
| 213 |
+
rhs=ir.Expr.getattr(redvar, "shape", loc),
|
| 214 |
+
typ=types.UniTuple(types.intp, redvar_typ.ndim),
|
| 215 |
+
name="redarr_shape",
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
# Add the dimension sizes of the array being reduced over to the tuple of sizes pass to empty.
|
| 219 |
+
for j in range(redvar_typ.ndim):
|
| 220 |
+
onedimvar = pfbdr.assign(
|
| 221 |
+
rhs=ir.Expr.static_getitem(redshape_var, j, None, loc),
|
| 222 |
+
typ=types.intp,
|
| 223 |
+
name="redshapeonedim",
|
| 224 |
+
)
|
| 225 |
+
size_var_list.append(onedimvar)
|
| 226 |
+
|
| 227 |
+
# Empty call takes tuple of sizes. Create here and fill in outer dimension (num threads).
|
| 228 |
+
size_var = pfbdr.make_tuple_variable(
|
| 229 |
+
size_var_list, name='tuple_size_var',
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
# Resolve dtype
|
| 233 |
+
cval = pfbdr._typingctx.resolve_value_type(reddtype)
|
| 234 |
+
dt = pfbdr.make_const_variable(cval=cval, typ=types.DType(reddtype))
|
| 235 |
+
# Add call to empty passing the size var tuple.
|
| 236 |
+
empty_call = pfbdr.call(glbl_np_empty, args=[size_var, dt])
|
| 237 |
+
|
| 238 |
+
redarr_var = pfbdr.assign(
|
| 239 |
+
rhs=empty_call, typ=redarrvar_typ, name="redarr",
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# Remember mapping of original reduction array to the newly created per-worker reduction array.
|
| 243 |
+
redarrs[redvar.name] = redarr_var
|
| 244 |
+
to_cleanup.append(redarr_var)
|
| 245 |
+
|
| 246 |
+
init_val = parfor_reddict[red_name].init_val
|
| 247 |
+
|
| 248 |
+
if init_val is not None:
|
| 249 |
+
if isinstance(redvar_typ, types.npytypes.Array):
|
| 250 |
+
# Create an array of identity values for the reduction.
|
| 251 |
+
# First, create a variable for np.full.
|
| 252 |
+
full_func_node = pfbdr.bind_global_function(
|
| 253 |
+
fobj=np.full,
|
| 254 |
+
ftype=get_np_ufunc_typ(np.full, pfbdr._typingctx),
|
| 255 |
+
args=(
|
| 256 |
+
types.UniTuple(types.intp, redvar_typ.ndim),
|
| 257 |
+
reddtype,
|
| 258 |
+
),
|
| 259 |
+
kws={'dtype': types.DType(reddtype)},
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
# Then create a var with the identify value.
|
| 263 |
+
init_val_var = pfbdr.make_const_variable(
|
| 264 |
+
cval=init_val,
|
| 265 |
+
typ=reddtype,
|
| 266 |
+
name="init_val",
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
# Then, call np.full with the shape of the reduction array and the identity value.
|
| 270 |
+
full_call = pfbdr.call(
|
| 271 |
+
full_func_node, args=[redshape_var, init_val_var, dt],
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
redtoset = pfbdr.assign(
|
| 275 |
+
rhs=full_call,
|
| 276 |
+
typ=redvar_typ,
|
| 277 |
+
name="redtoset",
|
| 278 |
+
)
|
| 279 |
+
# rettoset is an array from np.full() and must be released
|
| 280 |
+
to_cleanup.append(redtoset)
|
| 281 |
+
else:
|
| 282 |
+
redtoset = pfbdr.make_const_variable(
|
| 283 |
+
cval=init_val,
|
| 284 |
+
typ=reddtype,
|
| 285 |
+
name="redtoset",
|
| 286 |
+
)
|
| 287 |
+
else:
|
| 288 |
+
redtoset = redvar
|
| 289 |
+
|
| 290 |
+
if config.DEBUG_ARRAY_OPT_RUNTIME:
|
| 291 |
+
res_print_str = "res_print1 for redvar " + str(redvar) + ":"
|
| 292 |
+
strconsttyp = types.StringLiteral(res_print_str)
|
| 293 |
+
|
| 294 |
+
lhs = pfbdr.make_const_variable(
|
| 295 |
+
cval=res_print_str,
|
| 296 |
+
typ=strconsttyp,
|
| 297 |
+
name="str_const",
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
res_print = ir.Print(args=[lhs, redvar],
|
| 301 |
+
vararg=None, loc=loc)
|
| 302 |
+
lowerer.fndesc.calltypes[res_print] = signature(types.none,
|
| 303 |
+
typemap[lhs.name],
|
| 304 |
+
typemap[redvar.name])
|
| 305 |
+
print("res_print_redvar", res_print)
|
| 306 |
+
lowerer.lower_inst(res_print)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
# For each thread, initialize the per-worker reduction array to
|
| 310 |
+
# the current reduction array value.
|
| 311 |
+
|
| 312 |
+
# Get the Numba type of the variable that holds the thread count.
|
| 313 |
+
num_thread_type = typemap[num_threads_var.name]
|
| 314 |
+
# Get the LLVM type of the thread count variable.
|
| 315 |
+
ntllvm_type = targetctx.get_value_type(num_thread_type)
|
| 316 |
+
# Create a LLVM variable to hold the loop index.
|
| 317 |
+
alloc_loop_var = cgutils.alloca_once(builder, ntllvm_type)
|
| 318 |
+
# Associate this LLVM variable to a Numba IR variable so that
|
| 319 |
+
# we can use setitem IR builder.
|
| 320 |
+
# Create a Numba IR variable.
|
| 321 |
+
numba_ir_loop_index_var = scope.redefine("$loop_index", loc)
|
| 322 |
+
# Give that variable the right type.
|
| 323 |
+
typemap[numba_ir_loop_index_var.name] = num_thread_type
|
| 324 |
+
# Associate this Numba variable to the LLVM variable in the
|
| 325 |
+
# lowerer's varmap.
|
| 326 |
+
lowerer.varmap[numba_ir_loop_index_var.name] = alloc_loop_var
|
| 327 |
+
# Insert a loop into the outputed LLVM that goes from 0 to
|
| 328 |
+
# the current thread count.
|
| 329 |
+
with cgutils.for_range(builder, lowerer.loadvar(num_threads_var.name), intp=ntllvm_type) as loop:
|
| 330 |
+
# Store the loop index into the alloca'd LLVM loop index variable.
|
| 331 |
+
builder.store(loop.index, alloc_loop_var)
|
| 332 |
+
# Initialize one element of the reduction array using the Numba
|
| 333 |
+
# IR variable associated with this loop's index.
|
| 334 |
+
pfbdr.setitem(obj=redarr_var, index=numba_ir_loop_index_var, val=redtoset)
|
| 335 |
+
|
| 336 |
+
# compile parfor body as a separate function to be used with GUFuncWrapper
|
| 337 |
+
flags = parfor.flags.copy()
|
| 338 |
+
flags.error_model = "numpy"
|
| 339 |
+
# Can't get here unless flags.auto_parallel == ParallelOptions(True)
|
| 340 |
+
index_var_typ = typemap[parfor.loop_nests[0].index_variable.name]
|
| 341 |
+
# index variables should have the same type, check rest of indices
|
| 342 |
+
for l in parfor.loop_nests[1:]:
|
| 343 |
+
assert typemap[l.index_variable.name] == index_var_typ
|
| 344 |
+
numba.parfors.parfor.sequential_parfor_lowering = True
|
| 345 |
+
try:
|
| 346 |
+
(func,
|
| 347 |
+
func_args,
|
| 348 |
+
func_sig,
|
| 349 |
+
func_arg_types,
|
| 350 |
+
exp_name_to_tuple_var) = _create_gufunc_for_parfor_body(
|
| 351 |
+
lowerer, parfor, typemap, typingctx, targetctx, flags, {},
|
| 352 |
+
bool(alias_map), index_var_typ, parfor.races)
|
| 353 |
+
finally:
|
| 354 |
+
numba.parfors.parfor.sequential_parfor_lowering = False
|
| 355 |
+
|
| 356 |
+
# get the shape signature
|
| 357 |
+
func_args = ['sched'] + func_args
|
| 358 |
+
num_reductions = len(parfor_redvars)
|
| 359 |
+
num_inputs = len(func_args) - len(parfor_output_arrays) - num_reductions
|
| 360 |
+
if config.DEBUG_ARRAY_OPT:
|
| 361 |
+
print("func_args = ", func_args)
|
| 362 |
+
print("num_inputs = ", num_inputs)
|
| 363 |
+
print("parfor_outputs = ", parfor_output_arrays)
|
| 364 |
+
print("parfor_redvars = ", parfor_redvars)
|
| 365 |
+
print("num_reductions = ", num_reductions)
|
| 366 |
+
gu_signature = _create_shape_signature(
|
| 367 |
+
parfor.get_shape_classes,
|
| 368 |
+
num_inputs,
|
| 369 |
+
num_reductions,
|
| 370 |
+
func_args,
|
| 371 |
+
func_sig,
|
| 372 |
+
parfor.races,
|
| 373 |
+
typemap)
|
| 374 |
+
if config.DEBUG_ARRAY_OPT:
|
| 375 |
+
print("gu_signature = ", gu_signature)
|
| 376 |
+
|
| 377 |
+
# call the func in parallel by wrapping it with ParallelGUFuncBuilder
|
| 378 |
+
loop_ranges = [(l.start, l.stop, l.step) for l in parfor.loop_nests]
|
| 379 |
+
if config.DEBUG_ARRAY_OPT:
|
| 380 |
+
print("loop_nests = ", parfor.loop_nests)
|
| 381 |
+
print("loop_ranges = ", loop_ranges)
|
| 382 |
+
call_parallel_gufunc(
|
| 383 |
+
lowerer,
|
| 384 |
+
func,
|
| 385 |
+
gu_signature,
|
| 386 |
+
func_sig,
|
| 387 |
+
func_args,
|
| 388 |
+
func_arg_types,
|
| 389 |
+
loop_ranges,
|
| 390 |
+
parfor_redvars,
|
| 391 |
+
parfor_reddict,
|
| 392 |
+
redarrs,
|
| 393 |
+
parfor.init_block,
|
| 394 |
+
index_var_typ,
|
| 395 |
+
parfor.races,
|
| 396 |
+
exp_name_to_tuple_var)
|
| 397 |
+
|
| 398 |
+
if nredvars > 0:
|
| 399 |
+
_parfor_lowering_finalize_reduction(
|
| 400 |
+
parfor, redarrs, lowerer, parfor_reddict, num_threads_var,
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
# Cleanup reduction variable
|
| 404 |
+
for v in to_cleanup:
|
| 405 |
+
lowerer.lower_inst(ir.Del(v.name, loc=loc))
|
| 406 |
+
# Restore the original typemap of the function that was replaced temporarily at the
|
| 407 |
+
# Beginning of this function.
|
| 408 |
+
lowerer.fndesc.typemap = orig_typemap
|
| 409 |
+
|
| 410 |
+
if config.DEBUG_ARRAY_OPT:
|
| 411 |
+
print("_lower_parfor_parallel done")
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
_ReductionInfo = make_dataclass(
|
| 415 |
+
"_ReductionInfo",
|
| 416 |
+
[
|
| 417 |
+
"redvar_info",
|
| 418 |
+
"redvar_name",
|
| 419 |
+
"redvar_typ",
|
| 420 |
+
"redarr_var",
|
| 421 |
+
"redarr_typ",
|
| 422 |
+
"init_val",
|
| 423 |
+
],
|
| 424 |
+
frozen=True,
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def _parfor_lowering_finalize_reduction(
|
| 429 |
+
parfor,
|
| 430 |
+
redarrs,
|
| 431 |
+
lowerer,
|
| 432 |
+
parfor_reddict,
|
| 433 |
+
thread_count_var,
|
| 434 |
+
):
|
| 435 |
+
"""Emit code to finalize the reduction from the intermediate values of
|
| 436 |
+
each thread.
|
| 437 |
+
"""
|
| 438 |
+
# For each reduction variable
|
| 439 |
+
for redvar_name, redarr_var in redarrs.items():
|
| 440 |
+
# Pseudo-code for this loop body:
|
| 441 |
+
# tmp = redarr[0]
|
| 442 |
+
# for i in range(1, thread_count):
|
| 443 |
+
# tmp = reduce_op(redarr[i], tmp)
|
| 444 |
+
# reduction_result = tmp
|
| 445 |
+
redvar_typ = lowerer.fndesc.typemap[redvar_name]
|
| 446 |
+
redarr_typ = lowerer.fndesc.typemap[redarr_var.name]
|
| 447 |
+
init_val = lowerer.loadvar(redvar_name)
|
| 448 |
+
|
| 449 |
+
reduce_info = _ReductionInfo(
|
| 450 |
+
redvar_info = parfor_reddict[redvar_name],
|
| 451 |
+
redvar_name=redvar_name,
|
| 452 |
+
redvar_typ=redvar_typ,
|
| 453 |
+
redarr_var=redarr_var,
|
| 454 |
+
redarr_typ=redarr_typ,
|
| 455 |
+
init_val=init_val,
|
| 456 |
+
)
|
| 457 |
+
# generate code for combining reduction variable with thread output
|
| 458 |
+
handler = (_lower_trivial_inplace_binops
|
| 459 |
+
if reduce_info.redvar_info.redop is not None
|
| 460 |
+
else _lower_non_trivial_reduce)
|
| 461 |
+
handler(parfor, lowerer, thread_count_var, reduce_info)
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
class ParforsUnexpectedReduceNodeError(InternalError):
|
| 465 |
+
def __init__(self, inst):
|
| 466 |
+
super().__init__(f"Unknown reduce instruction node: {inst}")
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _lower_trivial_inplace_binops(parfor, lowerer, thread_count_var, reduce_info):
|
| 470 |
+
"""Lower trivial inplace-binop reduction.
|
| 471 |
+
"""
|
| 472 |
+
for inst in reduce_info.redvar_info.reduce_nodes:
|
| 473 |
+
# Var assigns to Var?
|
| 474 |
+
if _lower_var_to_var_assign(lowerer, inst):
|
| 475 |
+
pass
|
| 476 |
+
# Is inplace-binop for the reduction?
|
| 477 |
+
elif _is_right_op_and_rhs_is_init(inst, reduce_info.redvar_name, "inplace_binop"):
|
| 478 |
+
fn = inst.value.fn
|
| 479 |
+
redvar_result = _emit_binop_reduce_call(
|
| 480 |
+
fn, lowerer, thread_count_var, reduce_info,
|
| 481 |
+
)
|
| 482 |
+
lowerer.storevar(redvar_result, name=inst.target.name)
|
| 483 |
+
# Is binop for the reduction?
|
| 484 |
+
elif _is_right_op_and_rhs_is_init(inst, reduce_info.redvar_name, "binop"):
|
| 485 |
+
fn = inst.value.fn
|
| 486 |
+
redvar_result = _emit_binop_reduce_call(
|
| 487 |
+
fn, lowerer, thread_count_var, reduce_info,
|
| 488 |
+
)
|
| 489 |
+
lowerer.storevar(redvar_result, name=inst.target.name)
|
| 490 |
+
# Otherwise?
|
| 491 |
+
else:
|
| 492 |
+
raise ParforsUnexpectedReduceNodeError(inst)
|
| 493 |
+
|
| 494 |
+
# XXX: This seems like a hack to stop the loop with this condition.
|
| 495 |
+
if _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst,
|
| 496 |
+
reduce_info.redvar_name):
|
| 497 |
+
break
|
| 498 |
+
if config.DEBUG_ARRAY_OPT_RUNTIME:
|
| 499 |
+
varname = reduce_info.redvar_name
|
| 500 |
+
lowerer.print_variable(
|
| 501 |
+
f"{parfor.loc}: parfor {fn.__name__} reduction {varname} =",
|
| 502 |
+
varname,
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def _lower_non_trivial_reduce(parfor, lowerer, thread_count_var, reduce_info):
|
| 507 |
+
"""Lower non-trivial reduction such as call to `functools.reduce()`.
|
| 508 |
+
"""
|
| 509 |
+
init_name = f"{reduce_info.redvar_name}#init"
|
| 510 |
+
# The init_name variable is not defined at this point.
|
| 511 |
+
lowerer.fndesc.typemap.setdefault(init_name, reduce_info.redvar_typ)
|
| 512 |
+
# Emit a sequence of the reduction operation for each intermediate result
|
| 513 |
+
# of each thread.
|
| 514 |
+
num_thread_llval = lowerer.loadvar(thread_count_var.name)
|
| 515 |
+
with cgutils.for_range(lowerer.builder, num_thread_llval) as loop:
|
| 516 |
+
tid = loop.index
|
| 517 |
+
for inst in reduce_info.redvar_info.reduce_nodes:
|
| 518 |
+
# Var assigns to Var?
|
| 519 |
+
if _lower_var_to_var_assign(lowerer, inst):
|
| 520 |
+
pass
|
| 521 |
+
# The reduction operation?
|
| 522 |
+
elif (isinstance(inst, ir.Assign)
|
| 523 |
+
and any(var.name == init_name for var in inst.list_vars())):
|
| 524 |
+
elem = _emit_getitem_call(tid, lowerer, reduce_info)
|
| 525 |
+
lowerer.storevar(elem, init_name)
|
| 526 |
+
lowerer.lower_inst(inst)
|
| 527 |
+
|
| 528 |
+
# Otherwise?
|
| 529 |
+
else:
|
| 530 |
+
raise ParforsUnexpectedReduceNodeError(inst)
|
| 531 |
+
|
| 532 |
+
# XXX: This seems like a hack to stop the loop with this condition.
|
| 533 |
+
if _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst,
|
| 534 |
+
reduce_info.redvar_name):
|
| 535 |
+
break
|
| 536 |
+
|
| 537 |
+
if config.DEBUG_ARRAY_OPT_RUNTIME:
|
| 538 |
+
varname = reduce_info.redvar_name
|
| 539 |
+
lowerer.print_variable(
|
| 540 |
+
f"{parfor.loc}: parfor non-trivial reduction {varname} =",
|
| 541 |
+
varname,
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
def _lower_var_to_var_assign(lowerer, inst):
|
| 545 |
+
"""Lower Var->Var assignment.
|
| 546 |
+
|
| 547 |
+
Returns True if-and-only-if `inst` is a Var->Var assignment.
|
| 548 |
+
"""
|
| 549 |
+
if isinstance(inst, ir.Assign) and isinstance(inst.value, ir.Var):
|
| 550 |
+
loaded = lowerer.loadvar(inst.value.name)
|
| 551 |
+
lowerer.storevar(loaded, name=inst.target.name)
|
| 552 |
+
return True
|
| 553 |
+
return False
|
| 554 |
+
|
| 555 |
+
def _emit_getitem_call(idx, lowerer, reduce_info):
|
| 556 |
+
"""Emit call to ``redarr_var[idx]``
|
| 557 |
+
"""
|
| 558 |
+
def reducer_getitem(redarr, index):
|
| 559 |
+
return redarr[index]
|
| 560 |
+
|
| 561 |
+
builder = lowerer.builder
|
| 562 |
+
ctx = lowerer.context
|
| 563 |
+
redarr_typ = reduce_info.redarr_typ
|
| 564 |
+
arg_arr = lowerer.loadvar(reduce_info.redarr_var.name)
|
| 565 |
+
args = (arg_arr, idx)
|
| 566 |
+
sig = signature(reduce_info.redvar_typ, redarr_typ, types.intp)
|
| 567 |
+
elem = ctx.compile_internal(builder, reducer_getitem, sig, args)
|
| 568 |
+
return elem
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def _emit_binop_reduce_call(binop, lowerer, thread_count_var, reduce_info):
|
| 572 |
+
"""Emit call to the ``binop`` for the reduction variable.
|
| 573 |
+
"""
|
| 574 |
+
|
| 575 |
+
def reduction_add(thread_count, redarr, init):
|
| 576 |
+
c = init
|
| 577 |
+
for i in range(thread_count):
|
| 578 |
+
c += redarr[i]
|
| 579 |
+
return c
|
| 580 |
+
|
| 581 |
+
def reduction_mul(thread_count, redarr, init):
|
| 582 |
+
c = init
|
| 583 |
+
for i in range(thread_count):
|
| 584 |
+
c *= redarr[i]
|
| 585 |
+
return c
|
| 586 |
+
|
| 587 |
+
kernel = {
|
| 588 |
+
operator.iadd: reduction_add,
|
| 589 |
+
operator.isub: reduction_add,
|
| 590 |
+
operator.add: reduction_add,
|
| 591 |
+
operator.sub: reduction_add,
|
| 592 |
+
operator.imul: reduction_mul,
|
| 593 |
+
operator.ifloordiv: reduction_mul,
|
| 594 |
+
operator.itruediv: reduction_mul,
|
| 595 |
+
operator.mul: reduction_mul,
|
| 596 |
+
operator.floordiv: reduction_mul,
|
| 597 |
+
operator.truediv: reduction_mul,
|
| 598 |
+
}[binop]
|
| 599 |
+
|
| 600 |
+
ctx = lowerer.context
|
| 601 |
+
builder = lowerer.builder
|
| 602 |
+
redarr_typ = reduce_info.redarr_typ
|
| 603 |
+
arg_arr = lowerer.loadvar(reduce_info.redarr_var.name)
|
| 604 |
+
|
| 605 |
+
if config.DEBUG_ARRAY_OPT_RUNTIME:
|
| 606 |
+
init_var = reduce_info.redarr_var.scope.get(reduce_info.redvar_name)
|
| 607 |
+
res_print = ir.Print(
|
| 608 |
+
args=[reduce_info.redarr_var, init_var], vararg=None,
|
| 609 |
+
loc=lowerer.loc,
|
| 610 |
+
)
|
| 611 |
+
typemap = lowerer.fndesc.typemap
|
| 612 |
+
lowerer.fndesc.calltypes[res_print] = signature(
|
| 613 |
+
types.none, typemap[reduce_info.redarr_var.name],
|
| 614 |
+
typemap[init_var.name],
|
| 615 |
+
)
|
| 616 |
+
lowerer.lower_inst(res_print)
|
| 617 |
+
|
| 618 |
+
arg_thread_count = lowerer.loadvar(thread_count_var.name)
|
| 619 |
+
args = (arg_thread_count, arg_arr, reduce_info.init_val)
|
| 620 |
+
sig = signature(
|
| 621 |
+
reduce_info.redvar_typ, types.uintp, redarr_typ, reduce_info.redvar_typ,
|
| 622 |
+
)
|
| 623 |
+
|
| 624 |
+
redvar_result = ctx.compile_internal(builder, kernel, sig, args)
|
| 625 |
+
return redvar_result
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
def _is_right_op_and_rhs_is_init(inst, redvar_name, op):
|
| 629 |
+
"""Is ``inst`` an inplace-binop and the RHS is the reduction init?
|
| 630 |
+
"""
|
| 631 |
+
if not isinstance(inst, ir.Assign):
|
| 632 |
+
return False
|
| 633 |
+
rhs = inst.value
|
| 634 |
+
if not isinstance(rhs, ir.Expr):
|
| 635 |
+
return False
|
| 636 |
+
if rhs.op != op:
|
| 637 |
+
return False
|
| 638 |
+
if rhs.rhs.name != f"{redvar_name}#init":
|
| 639 |
+
return False
|
| 640 |
+
return True
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
def _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst, redvar_name):
|
| 644 |
+
"""Fix reduction variable name mismatch due to SSA.
|
| 645 |
+
"""
|
| 646 |
+
# Only process reduction statements post-gufunc execution
|
| 647 |
+
# until we see an assignment with a left-hand side to the
|
| 648 |
+
# reduction variable's name. This fixes problems with
|
| 649 |
+
# cases where there are multiple assignments to the
|
| 650 |
+
# reduction variable in the parfor.
|
| 651 |
+
scope = parfor.init_block.scope
|
| 652 |
+
if isinstance(inst, ir.Assign):
|
| 653 |
+
try:
|
| 654 |
+
reduction_var = scope.get_exact(redvar_name)
|
| 655 |
+
except NotDefinedError:
|
| 656 |
+
# Ideally, this shouldn't happen. The redvar name
|
| 657 |
+
# missing from scope indicates an error from
|
| 658 |
+
# other rewrite passes.
|
| 659 |
+
is_same_source_var = redvar_name == inst.target.name
|
| 660 |
+
else:
|
| 661 |
+
# Because of SSA, the redvar and target var of
|
| 662 |
+
# the current assignment would be different even
|
| 663 |
+
# though they refer to the same source-level var.
|
| 664 |
+
redvar_unver_name = reduction_var.unversioned_name
|
| 665 |
+
target_unver_name = inst.target.unversioned_name
|
| 666 |
+
is_same_source_var = redvar_unver_name == target_unver_name
|
| 667 |
+
|
| 668 |
+
if is_same_source_var:
|
| 669 |
+
# If redvar is different from target var, add an
|
| 670 |
+
# assignment to put target var into redvar.
|
| 671 |
+
if redvar_name != inst.target.name:
|
| 672 |
+
val = lowerer.loadvar(inst.target.name)
|
| 673 |
+
lowerer.storevar(val, name=redvar_name)
|
| 674 |
+
return True
|
| 675 |
+
|
| 676 |
+
return False
|
| 677 |
+
|
| 678 |
+
def _create_shape_signature(
|
| 679 |
+
get_shape_classes,
|
| 680 |
+
num_inputs,
|
| 681 |
+
num_reductions,
|
| 682 |
+
args,
|
| 683 |
+
func_sig,
|
| 684 |
+
races,
|
| 685 |
+
typemap):
|
| 686 |
+
'''Create shape signature for GUFunc
|
| 687 |
+
'''
|
| 688 |
+
if config.DEBUG_ARRAY_OPT:
|
| 689 |
+
print("_create_shape_signature", num_inputs, num_reductions, args, races)
|
| 690 |
+
for i in args[1:]:
|
| 691 |
+
print("argument", i, type(i), get_shape_classes(i, typemap=typemap))
|
| 692 |
+
|
| 693 |
+
num_inouts = len(args) - num_reductions
|
| 694 |
+
# maximum class number for array shapes
|
| 695 |
+
classes = [get_shape_classes(var, typemap=typemap) if var not in races else (-1,) for var in args[1:]]
|
| 696 |
+
class_set = set()
|
| 697 |
+
for _class in classes:
|
| 698 |
+
if _class:
|
| 699 |
+
for i in _class:
|
| 700 |
+
class_set.add(i)
|
| 701 |
+
max_class = max(class_set) + 1 if class_set else 0
|
| 702 |
+
classes.insert(0, (max_class,)) # force set the class of 'sched' argument
|
| 703 |
+
class_set.add(max_class)
|
| 704 |
+
thread_num_class = max_class + 1
|
| 705 |
+
class_set.add(thread_num_class)
|
| 706 |
+
class_map = {}
|
| 707 |
+
# TODO: use prefix + class number instead of single char
|
| 708 |
+
alphabet = ord('a')
|
| 709 |
+
for n in class_set:
|
| 710 |
+
if n >= 0:
|
| 711 |
+
class_map[n] = chr(alphabet)
|
| 712 |
+
alphabet += 1
|
| 713 |
+
threadcount_ordinal = chr(alphabet)
|
| 714 |
+
|
| 715 |
+
alpha_dict = {'latest_alpha' : alphabet}
|
| 716 |
+
|
| 717 |
+
def bump_alpha(c, class_map):
|
| 718 |
+
if c >= 0:
|
| 719 |
+
return class_map[c]
|
| 720 |
+
else:
|
| 721 |
+
alpha_dict['latest_alpha'] += 1
|
| 722 |
+
return chr(alpha_dict['latest_alpha'])
|
| 723 |
+
|
| 724 |
+
gu_sin = []
|
| 725 |
+
gu_sout = []
|
| 726 |
+
count = 0
|
| 727 |
+
syms_sin = ()
|
| 728 |
+
if config.DEBUG_ARRAY_OPT:
|
| 729 |
+
print("args", args)
|
| 730 |
+
print("classes", classes)
|
| 731 |
+
print("threadcount_ordinal", threadcount_ordinal)
|
| 732 |
+
for cls, arg in zip(classes, args):
|
| 733 |
+
count = count + 1
|
| 734 |
+
if cls:
|
| 735 |
+
dim_syms = tuple(bump_alpha(c, class_map) for c in cls)
|
| 736 |
+
else:
|
| 737 |
+
dim_syms = ()
|
| 738 |
+
if (count > num_inouts):
|
| 739 |
+
# Add the threadcount_ordinal to represent the thread count
|
| 740 |
+
# to the start of the reduction array.
|
| 741 |
+
gu_sin.append(tuple([threadcount_ordinal] + list(dim_syms[1:])))
|
| 742 |
+
else:
|
| 743 |
+
gu_sin.append(dim_syms)
|
| 744 |
+
syms_sin += dim_syms
|
| 745 |
+
return (gu_sin, gu_sout)
|
| 746 |
+
|
| 747 |
+
def _print_block(block):
|
| 748 |
+
for i, inst in enumerate(block.body):
|
| 749 |
+
print(" ", i, " ", inst)
|
| 750 |
+
|
| 751 |
+
def _print_body(body_dict):
|
| 752 |
+
'''Pretty-print a set of IR blocks.
|
| 753 |
+
'''
|
| 754 |
+
topo_order = wrap_find_topo(body_dict)
|
| 755 |
+
for label in topo_order:
|
| 756 |
+
block = body_dict[label]
|
| 757 |
+
print("label: ", label)
|
| 758 |
+
_print_block(block)
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
def wrap_loop_body(loop_body):
|
| 762 |
+
blocks = loop_body.copy() # shallow copy is enough
|
| 763 |
+
first_label = min(blocks.keys())
|
| 764 |
+
last_label = max(blocks.keys())
|
| 765 |
+
loc = blocks[last_label].loc
|
| 766 |
+
blocks[last_label].body.append(ir.Jump(first_label, loc))
|
| 767 |
+
return blocks
|
| 768 |
+
|
| 769 |
+
def unwrap_loop_body(loop_body):
|
| 770 |
+
last_label = max(loop_body.keys())
|
| 771 |
+
loop_body[last_label].body = loop_body[last_label].body[:-1]
|
| 772 |
+
|
| 773 |
+
def add_to_def_once_sets(a_def, def_once, def_more):
|
| 774 |
+
'''If the variable is already defined more than once, do nothing.
|
| 775 |
+
Else if defined exactly once previously then transition this
|
| 776 |
+
variable to the defined more than once set (remove it from
|
| 777 |
+
def_once set and add to def_more set).
|
| 778 |
+
Else this must be the first time we've seen this variable defined
|
| 779 |
+
so add to def_once set.
|
| 780 |
+
'''
|
| 781 |
+
if a_def in def_more:
|
| 782 |
+
pass
|
| 783 |
+
elif a_def in def_once:
|
| 784 |
+
def_more.add(a_def)
|
| 785 |
+
def_once.remove(a_def)
|
| 786 |
+
else:
|
| 787 |
+
def_once.add(a_def)
|
| 788 |
+
|
| 789 |
+
def compute_def_once_block(block, def_once, def_more, getattr_taken, typemap, module_assigns):
|
| 790 |
+
'''Effect changes to the set of variables defined once or more than once
|
| 791 |
+
for a single block.
|
| 792 |
+
block - the block to process
|
| 793 |
+
def_once - set of variable names known to be defined exactly once
|
| 794 |
+
def_more - set of variable names known to be defined more than once
|
| 795 |
+
getattr_taken - dict mapping variable name to tuple of object and attribute taken
|
| 796 |
+
module_assigns - dict mapping variable name to the Global that they came from
|
| 797 |
+
'''
|
| 798 |
+
# The only "defs" occur in assignments, so find such instructions.
|
| 799 |
+
assignments = block.find_insts(ir.Assign)
|
| 800 |
+
# For each assignment...
|
| 801 |
+
for one_assign in assignments:
|
| 802 |
+
# Get the LHS/target of the assignment.
|
| 803 |
+
a_def = one_assign.target.name
|
| 804 |
+
# Add variable to def sets.
|
| 805 |
+
add_to_def_once_sets(a_def, def_once, def_more)
|
| 806 |
+
|
| 807 |
+
rhs = one_assign.value
|
| 808 |
+
if isinstance(rhs, ir.Global):
|
| 809 |
+
# Remember assignments of the form "a = Global(...)"
|
| 810 |
+
# Is this a module?
|
| 811 |
+
if isinstance(rhs.value, pytypes.ModuleType):
|
| 812 |
+
module_assigns[a_def] = rhs.value.__name__
|
| 813 |
+
if isinstance(rhs, ir.Expr) and rhs.op == 'getattr' and rhs.value.name in def_once:
|
| 814 |
+
# Remember assignments of the form "a = b.c"
|
| 815 |
+
getattr_taken[a_def] = (rhs.value.name, rhs.attr)
|
| 816 |
+
if isinstance(rhs, ir.Expr) and rhs.op == 'call' and rhs.func.name in getattr_taken:
|
| 817 |
+
# If "a" is being called then lookup the getattr definition of "a"
|
| 818 |
+
# as above, getting the module variable "b" (base_obj)
|
| 819 |
+
# and the attribute "c" (base_attr).
|
| 820 |
+
base_obj, base_attr = getattr_taken[rhs.func.name]
|
| 821 |
+
if base_obj in module_assigns:
|
| 822 |
+
# If we know the definition of the module variable then get the module
|
| 823 |
+
# name from module_assigns.
|
| 824 |
+
base_mod_name = module_assigns[base_obj]
|
| 825 |
+
if not is_const_call(base_mod_name, base_attr):
|
| 826 |
+
# Calling a method on an object could modify the object and is thus
|
| 827 |
+
# like a def of that object. We call is_const_call to see if this module/attribute
|
| 828 |
+
# combination is known to not modify the module state. If we don't know that
|
| 829 |
+
# the combination is safe then we have to assume there could be a modification to
|
| 830 |
+
# the module and thus add the module variable as defined more than once.
|
| 831 |
+
add_to_def_once_sets(base_obj, def_once, def_more)
|
| 832 |
+
else:
|
| 833 |
+
# Assume the worst and say that base_obj could be modified by the call.
|
| 834 |
+
add_to_def_once_sets(base_obj, def_once, def_more)
|
| 835 |
+
if isinstance(rhs, ir.Expr) and rhs.op == 'call':
|
| 836 |
+
# If a mutable object is passed to a function, then it may be changed and
|
| 837 |
+
# therefore can't be hoisted.
|
| 838 |
+
# For each argument to the function...
|
| 839 |
+
for argvar in rhs.args:
|
| 840 |
+
# Get the argument's type.
|
| 841 |
+
if isinstance(argvar, ir.Var):
|
| 842 |
+
argvar = argvar.name
|
| 843 |
+
avtype = typemap[argvar]
|
| 844 |
+
# If that type doesn't have a mutable attribute or it does and it's set to
|
| 845 |
+
# not mutable then this usage is safe for hoisting.
|
| 846 |
+
if getattr(avtype, 'mutable', False):
|
| 847 |
+
# Here we have a mutable variable passed to a function so add this variable
|
| 848 |
+
# to the def lists.
|
| 849 |
+
add_to_def_once_sets(argvar, def_once, def_more)
|
| 850 |
+
|
| 851 |
+
def wrap_find_topo(loop_body):
|
| 852 |
+
blocks = wrap_loop_body(loop_body)
|
| 853 |
+
topo_order = find_topo_order(blocks)
|
| 854 |
+
unwrap_loop_body(loop_body)
|
| 855 |
+
return topo_order
|
| 856 |
+
|
| 857 |
+
def compute_def_once_internal(loop_body, def_once, def_more, getattr_taken, typemap, module_assigns):
|
| 858 |
+
'''Compute the set of variables defined exactly once in the given set of blocks
|
| 859 |
+
and use the given sets for storing which variables are defined once, more than
|
| 860 |
+
once and which have had a getattr call on them.
|
| 861 |
+
'''
|
| 862 |
+
# For each block in topological order...
|
| 863 |
+
topo_order = wrap_find_topo(loop_body)
|
| 864 |
+
for label in topo_order:
|
| 865 |
+
block = loop_body[label]
|
| 866 |
+
# Scan this block and effect changes to def_once, def_more, and getattr_taken
|
| 867 |
+
# based on the instructions in that block.
|
| 868 |
+
compute_def_once_block(block, def_once, def_more, getattr_taken, typemap, module_assigns)
|
| 869 |
+
# Have to recursively process parfors manually here.
|
| 870 |
+
for inst in block.body:
|
| 871 |
+
if isinstance(inst, parfor.Parfor):
|
| 872 |
+
# Recursively compute for the parfor's init block.
|
| 873 |
+
compute_def_once_block(inst.init_block, def_once, def_more, getattr_taken, typemap, module_assigns)
|
| 874 |
+
# Recursively compute for the parfor's loop body.
|
| 875 |
+
compute_def_once_internal(inst.loop_body, def_once, def_more, getattr_taken, typemap, module_assigns)
|
| 876 |
+
|
| 877 |
+
def compute_def_once(loop_body, typemap):
|
| 878 |
+
'''Compute the set of variables defined exactly once in the given set of blocks.
|
| 879 |
+
'''
|
| 880 |
+
def_once = set() # set to hold variables defined exactly once
|
| 881 |
+
def_more = set() # set to hold variables defined more than once
|
| 882 |
+
getattr_taken = {}
|
| 883 |
+
module_assigns = {}
|
| 884 |
+
compute_def_once_internal(loop_body, def_once, def_more, getattr_taken, typemap, module_assigns)
|
| 885 |
+
return def_once, def_more
|
| 886 |
+
|
| 887 |
+
def find_vars(var, varset):
|
| 888 |
+
assert isinstance(var, ir.Var)
|
| 889 |
+
varset.add(var.name)
|
| 890 |
+
return var
|
| 891 |
+
|
| 892 |
+
def _hoist_internal(inst, dep_on_param, call_table, hoisted, not_hoisted,
|
| 893 |
+
typemap, stored_arrays):
|
| 894 |
+
if inst.target.name in stored_arrays:
|
| 895 |
+
not_hoisted.append((inst, "stored array"))
|
| 896 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 897 |
+
print("Instruction", inst, "could not be hoisted because the created array is stored.")
|
| 898 |
+
return False
|
| 899 |
+
|
| 900 |
+
target_type = typemap[inst.target.name]
|
| 901 |
+
|
| 902 |
+
uses = set()
|
| 903 |
+
# Get vars used by this statement.
|
| 904 |
+
visit_vars_inner(inst.value, find_vars, uses)
|
| 905 |
+
# Filter out input parameters from the set of variable usages.
|
| 906 |
+
unhoistable = {assgn.target.name for assgn, _ in not_hoisted}
|
| 907 |
+
use_unhoist = uses & unhoistable
|
| 908 |
+
diff = uses.difference(dep_on_param)
|
| 909 |
+
diff |= use_unhoist
|
| 910 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 911 |
+
print("_hoist_internal:", inst, "uses:", uses, "diff:", diff)
|
| 912 |
+
if len(diff) == 0 and is_pure(inst.value, None, call_table):
|
| 913 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 914 |
+
print("Will hoist instruction", inst, target_type)
|
| 915 |
+
hoisted.append(inst)
|
| 916 |
+
if not isinstance(target_type, types.npytypes.Array):
|
| 917 |
+
dep_on_param += [inst.target.name]
|
| 918 |
+
return True
|
| 919 |
+
else:
|
| 920 |
+
if len(diff) > 0:
|
| 921 |
+
not_hoisted.append((inst, "dependency"))
|
| 922 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 923 |
+
print("Instruction", inst, "could not be hoisted because of a dependency.")
|
| 924 |
+
else:
|
| 925 |
+
not_hoisted.append((inst, "not pure"))
|
| 926 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 927 |
+
print("Instruction", inst, "could not be hoisted because it isn't pure.")
|
| 928 |
+
return False
|
| 929 |
+
|
| 930 |
+
def find_setitems_block(setitems, itemsset, block, typemap):
|
| 931 |
+
for inst in block.body:
|
| 932 |
+
if isinstance(inst, (ir.StaticSetItem, ir.SetItem)):
|
| 933 |
+
setitems.add(inst.target.name)
|
| 934 |
+
# If we store a non-mutable object into an array then that is safe to hoist.
|
| 935 |
+
# If the stored object is mutable and you hoist then multiple entries in the
|
| 936 |
+
# outer array could reference the same object and changing one index would then
|
| 937 |
+
# change other indices.
|
| 938 |
+
if getattr(typemap[inst.value.name], "mutable", False):
|
| 939 |
+
itemsset.add(inst.value.name)
|
| 940 |
+
elif isinstance(inst, parfor.Parfor):
|
| 941 |
+
find_setitems_block(setitems, itemsset, inst.init_block, typemap)
|
| 942 |
+
find_setitems_body(setitems, itemsset, inst.loop_body, typemap)
|
| 943 |
+
elif isinstance(inst, ir.Assign):
|
| 944 |
+
# If something of mutable type is given to a build_tuple or
|
| 945 |
+
# used in a call then consider it unanalyzable and so
|
| 946 |
+
# unavailable for hoisting.
|
| 947 |
+
rhs = inst.value
|
| 948 |
+
def add_to_itemset(item):
|
| 949 |
+
assert isinstance(item, ir.Var), rhs
|
| 950 |
+
if getattr(typemap[item.name], "mutable", False):
|
| 951 |
+
itemsset.add(item.name)
|
| 952 |
+
|
| 953 |
+
if isinstance(rhs, ir.Expr):
|
| 954 |
+
if rhs.op in ["build_tuple", "build_list", "build_set"]:
|
| 955 |
+
for item in rhs.items:
|
| 956 |
+
add_to_itemset(item)
|
| 957 |
+
elif rhs.op == "build_map":
|
| 958 |
+
for pair in rhs.items:
|
| 959 |
+
for item in pair:
|
| 960 |
+
add_to_itemset(item)
|
| 961 |
+
elif rhs.op == "call":
|
| 962 |
+
for item in list(rhs.args) + [x[1] for x in rhs.kws]:
|
| 963 |
+
add_to_itemset(item)
|
| 964 |
+
|
| 965 |
+
def find_setitems_body(setitems, itemsset, loop_body, typemap):
|
| 966 |
+
"""
|
| 967 |
+
Find the arrays that are written into (goes into setitems) and the
|
| 968 |
+
mutable objects (mostly arrays) that are written into other arrays
|
| 969 |
+
(goes into itemsset).
|
| 970 |
+
"""
|
| 971 |
+
for label, block in loop_body.items():
|
| 972 |
+
find_setitems_block(setitems, itemsset, block, typemap)
|
| 973 |
+
|
| 974 |
+
def empty_container_allocator_hoist(inst, dep_on_param, call_table, hoisted,
|
| 975 |
+
not_hoisted, typemap, stored_arrays):
|
| 976 |
+
if (isinstance(inst, ir.Assign) and
|
| 977 |
+
isinstance(inst.value, ir.Expr) and
|
| 978 |
+
inst.value.op == 'call' and
|
| 979 |
+
inst.value.func.name in call_table):
|
| 980 |
+
call_list = call_table[inst.value.func.name]
|
| 981 |
+
if call_list == ['empty', np]:
|
| 982 |
+
return _hoist_internal(inst, dep_on_param, call_table, hoisted,
|
| 983 |
+
not_hoisted, typemap, stored_arrays)
|
| 984 |
+
return False
|
| 985 |
+
|
| 986 |
+
def hoist(parfor_params, loop_body, typemap, wrapped_blocks):
|
| 987 |
+
dep_on_param = copy.copy(parfor_params)
|
| 988 |
+
hoisted = []
|
| 989 |
+
not_hoisted = []
|
| 990 |
+
|
| 991 |
+
# Compute the set of variable defined exactly once in the loop body.
|
| 992 |
+
def_once, def_more = compute_def_once(loop_body, typemap)
|
| 993 |
+
(call_table, reverse_call_table) = get_call_table(wrapped_blocks)
|
| 994 |
+
|
| 995 |
+
setitems = set()
|
| 996 |
+
itemsset = set()
|
| 997 |
+
find_setitems_body(setitems, itemsset, loop_body, typemap)
|
| 998 |
+
dep_on_param = list(set(dep_on_param).difference(setitems))
|
| 999 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 1000 |
+
print("hoist - def_once:", def_once, "setitems:", setitems, "itemsset:", itemsset, "dep_on_param:", dep_on_param, "parfor_params:", parfor_params)
|
| 1001 |
+
for si in setitems:
|
| 1002 |
+
add_to_def_once_sets(si, def_once, def_more)
|
| 1003 |
+
|
| 1004 |
+
for label, block in loop_body.items():
|
| 1005 |
+
new_block = []
|
| 1006 |
+
for inst in block.body:
|
| 1007 |
+
if empty_container_allocator_hoist(inst, dep_on_param, call_table,
|
| 1008 |
+
hoisted, not_hoisted, typemap, itemsset):
|
| 1009 |
+
continue
|
| 1010 |
+
elif isinstance(inst, ir.Assign) and inst.target.name in def_once:
|
| 1011 |
+
if _hoist_internal(inst, dep_on_param, call_table,
|
| 1012 |
+
hoisted, not_hoisted, typemap, itemsset):
|
| 1013 |
+
# don't add this instruction to the block since it is
|
| 1014 |
+
# hoisted
|
| 1015 |
+
continue
|
| 1016 |
+
elif isinstance(inst, parfor.Parfor):
|
| 1017 |
+
new_init_block = []
|
| 1018 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 1019 |
+
print("parfor")
|
| 1020 |
+
inst.dump()
|
| 1021 |
+
for ib_inst in inst.init_block.body:
|
| 1022 |
+
if empty_container_allocator_hoist(ib_inst, dep_on_param,
|
| 1023 |
+
call_table, hoisted, not_hoisted, typemap, itemsset):
|
| 1024 |
+
continue
|
| 1025 |
+
elif (isinstance(ib_inst, ir.Assign) and
|
| 1026 |
+
ib_inst.target.name in def_once):
|
| 1027 |
+
if _hoist_internal(ib_inst, dep_on_param, call_table,
|
| 1028 |
+
hoisted, not_hoisted, typemap,
|
| 1029 |
+
itemsset):
|
| 1030 |
+
# don't add this instruction to the block since it is hoisted
|
| 1031 |
+
continue
|
| 1032 |
+
new_init_block.append(ib_inst)
|
| 1033 |
+
inst.init_block.body = new_init_block
|
| 1034 |
+
|
| 1035 |
+
new_block.append(inst)
|
| 1036 |
+
block.body = new_block
|
| 1037 |
+
return hoisted, not_hoisted
|
| 1038 |
+
|
| 1039 |
+
def redtyp_is_scalar(redtype):
|
| 1040 |
+
return not isinstance(redtype, types.npytypes.Array)
|
| 1041 |
+
|
| 1042 |
+
def redtyp_to_redarraytype(redtyp):
|
| 1043 |
+
"""Go from a reducation variable type to a reduction array type used to hold
|
| 1044 |
+
per-worker results.
|
| 1045 |
+
"""
|
| 1046 |
+
redarrdim = 1
|
| 1047 |
+
# If the reduction type is an array then allocate reduction array with ndim+1 dimensions.
|
| 1048 |
+
if isinstance(redtyp, types.npytypes.Array):
|
| 1049 |
+
redarrdim += redtyp.ndim
|
| 1050 |
+
# We don't create array of array but multi-dimensional reduction array with same dtype.
|
| 1051 |
+
redtyp = redtyp.dtype
|
| 1052 |
+
return types.npytypes.Array(redtyp, redarrdim, "C")
|
| 1053 |
+
|
| 1054 |
+
def redarraytype_to_sig(redarraytyp):
|
| 1055 |
+
"""Given a reduction array type, find the type of the reduction argument to the gufunc.
|
| 1056 |
+
"""
|
| 1057 |
+
assert isinstance(redarraytyp, types.npytypes.Array)
|
| 1058 |
+
return types.npytypes.Array(redarraytyp.dtype, redarraytyp.ndim, redarraytyp.layout)
|
| 1059 |
+
|
| 1060 |
+
def legalize_names_with_typemap(names, typemap):
|
| 1061 |
+
""" We use ir_utils.legalize_names to replace internal IR variable names
|
| 1062 |
+
containing illegal characters (e.g. period) with a legal character
|
| 1063 |
+
(underscore) so as to create legal variable names.
|
| 1064 |
+
The original variable names are in the typemap so we also
|
| 1065 |
+
need to add the legalized name to the typemap as well.
|
| 1066 |
+
"""
|
| 1067 |
+
outdict = legalize_names(names)
|
| 1068 |
+
# For each pair in the dict of legalized names...
|
| 1069 |
+
for x, y in outdict.items():
|
| 1070 |
+
# If the name had some legalization change to it...
|
| 1071 |
+
if x != y:
|
| 1072 |
+
# Set the type of the new name the same as the type of the old name.
|
| 1073 |
+
typemap[y] = typemap[x]
|
| 1074 |
+
return outdict
|
| 1075 |
+
|
| 1076 |
+
def to_scalar_from_0d(x):
|
| 1077 |
+
if isinstance(x, types.ArrayCompatible):
|
| 1078 |
+
if x.ndim == 0:
|
| 1079 |
+
return x.dtype
|
| 1080 |
+
return x
|
| 1081 |
+
|
| 1082 |
+
def _create_gufunc_for_parfor_body(
|
| 1083 |
+
lowerer,
|
| 1084 |
+
parfor,
|
| 1085 |
+
typemap,
|
| 1086 |
+
typingctx,
|
| 1087 |
+
targetctx,
|
| 1088 |
+
flags,
|
| 1089 |
+
locals,
|
| 1090 |
+
has_aliases,
|
| 1091 |
+
index_var_typ,
|
| 1092 |
+
races):
|
| 1093 |
+
'''
|
| 1094 |
+
Takes a parfor and creates a gufunc function for its body.
|
| 1095 |
+
There are two parts to this function.
|
| 1096 |
+
1) Code to iterate across the iteration space as defined by the schedule.
|
| 1097 |
+
2) The parfor body that does the work for a single point in the iteration space.
|
| 1098 |
+
Part 1 is created as Python text for simplicity with a sentinel assignment to mark the point
|
| 1099 |
+
in the IR where the parfor body should be added.
|
| 1100 |
+
This Python text is 'exec'ed into existence and its IR retrieved with run_frontend.
|
| 1101 |
+
The IR is scanned for the sentinel assignment where that basic block is split and the IR
|
| 1102 |
+
for the parfor body inserted.
|
| 1103 |
+
'''
|
| 1104 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 1105 |
+
print("starting _create_gufunc_for_parfor_body")
|
| 1106 |
+
|
| 1107 |
+
loc = parfor.init_block.loc
|
| 1108 |
+
|
| 1109 |
+
# The parfor body and the main function body share ir.Var nodes.
|
| 1110 |
+
# We have to do some replacements of Var names in the parfor body to make them
|
| 1111 |
+
# legal parameter names. If we don't copy then the Vars in the main function also
|
| 1112 |
+
# would incorrectly change their name.
|
| 1113 |
+
loop_body = copy.copy(parfor.loop_body)
|
| 1114 |
+
remove_dels(loop_body)
|
| 1115 |
+
|
| 1116 |
+
parfor_dim = len(parfor.loop_nests)
|
| 1117 |
+
loop_indices = [l.index_variable.name for l in parfor.loop_nests]
|
| 1118 |
+
|
| 1119 |
+
# Get all the parfor params.
|
| 1120 |
+
parfor_params = parfor.params
|
| 1121 |
+
# Get just the outputs of the parfor.
|
| 1122 |
+
parfor_outputs = numba.parfors.parfor.get_parfor_outputs(parfor, parfor_params)
|
| 1123 |
+
# Get all parfor reduction vars, and operators.
|
| 1124 |
+
typemap = lowerer.fndesc.typemap
|
| 1125 |
+
parfor_redvars, parfor_reddict = numba.parfors.parfor.get_parfor_reductions(
|
| 1126 |
+
lowerer.func_ir, parfor, parfor_params, lowerer.fndesc.calltypes)
|
| 1127 |
+
# Compute just the parfor inputs as a set difference.
|
| 1128 |
+
parfor_inputs = sorted(
|
| 1129 |
+
list(
|
| 1130 |
+
set(parfor_params) -
|
| 1131 |
+
set(parfor_outputs) -
|
| 1132 |
+
set(parfor_redvars)))
|
| 1133 |
+
|
| 1134 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 1135 |
+
print("parfor_params = ", parfor_params, " ", type(parfor_params))
|
| 1136 |
+
print("parfor_outputs = ", parfor_outputs, " ", type(parfor_outputs))
|
| 1137 |
+
print("parfor_inputs = ", parfor_inputs, " ", type(parfor_inputs))
|
| 1138 |
+
print("parfor_redvars = ", parfor_redvars, " ", type(parfor_redvars))
|
| 1139 |
+
|
| 1140 |
+
# -------------------------------------------------------------------------
|
| 1141 |
+
# Convert tuples to individual parameters.
|
| 1142 |
+
tuple_expanded_parfor_inputs = []
|
| 1143 |
+
tuple_var_to_expanded_names = {}
|
| 1144 |
+
expanded_name_to_tuple_var = {}
|
| 1145 |
+
next_expanded_tuple_var = 0
|
| 1146 |
+
parfor_tuple_params = []
|
| 1147 |
+
# For each input to the parfor.
|
| 1148 |
+
for pi in parfor_inputs:
|
| 1149 |
+
# Get the type of the input.
|
| 1150 |
+
pi_type = typemap[pi]
|
| 1151 |
+
# If it is a UniTuple or Tuple we will do the conversion.
|
| 1152 |
+
if isinstance(pi_type, types.UniTuple) or isinstance(pi_type, types.NamedUniTuple):
|
| 1153 |
+
# Get the size and dtype of the tuple.
|
| 1154 |
+
tuple_count = pi_type.count
|
| 1155 |
+
tuple_dtype = pi_type.dtype
|
| 1156 |
+
# Only do tuples up to config.PARFOR_MAX_TUPLE_SIZE length.
|
| 1157 |
+
assert(tuple_count <= config.PARFOR_MAX_TUPLE_SIZE)
|
| 1158 |
+
this_var_expansion = []
|
| 1159 |
+
for i in range(tuple_count):
|
| 1160 |
+
# Generate a new name for the individual part of the tuple var.
|
| 1161 |
+
expanded_name = "expanded_tuple_var_" + str(next_expanded_tuple_var)
|
| 1162 |
+
# Add that name to the new list of inputs to the gufunc.
|
| 1163 |
+
tuple_expanded_parfor_inputs.append(expanded_name)
|
| 1164 |
+
this_var_expansion.append(expanded_name)
|
| 1165 |
+
# Remember a mapping from new param name to original tuple
|
| 1166 |
+
# var and the index within the tuple.
|
| 1167 |
+
expanded_name_to_tuple_var[expanded_name] = (pi, i)
|
| 1168 |
+
next_expanded_tuple_var += 1
|
| 1169 |
+
# Set the type of the new parameter.
|
| 1170 |
+
typemap[expanded_name] = tuple_dtype
|
| 1171 |
+
# Remember a mapping from the original tuple var to the
|
| 1172 |
+
# individual parts.
|
| 1173 |
+
tuple_var_to_expanded_names[pi] = this_var_expansion
|
| 1174 |
+
parfor_tuple_params.append(pi)
|
| 1175 |
+
elif isinstance(pi_type, types.Tuple) or isinstance(pi_type, types.NamedTuple):
|
| 1176 |
+
# This is the same as above for UniTuple except that each part of
|
| 1177 |
+
# the tuple can have a different type and we fetch that type with
|
| 1178 |
+
# pi_type.types[offset].
|
| 1179 |
+
tuple_count = pi_type.count
|
| 1180 |
+
tuple_types = pi_type.types
|
| 1181 |
+
# Only do tuples up to config.PARFOR_MAX_TUPLE_SIZE length.
|
| 1182 |
+
assert(tuple_count <= config.PARFOR_MAX_TUPLE_SIZE)
|
| 1183 |
+
this_var_expansion = []
|
| 1184 |
+
for i in range(tuple_count):
|
| 1185 |
+
expanded_name = "expanded_tuple_var_" + str(next_expanded_tuple_var)
|
| 1186 |
+
tuple_expanded_parfor_inputs.append(expanded_name)
|
| 1187 |
+
this_var_expansion.append(expanded_name)
|
| 1188 |
+
expanded_name_to_tuple_var[expanded_name] = (pi, i)
|
| 1189 |
+
next_expanded_tuple_var += 1
|
| 1190 |
+
typemap[expanded_name] = tuple_types[i]
|
| 1191 |
+
tuple_var_to_expanded_names[pi] = this_var_expansion
|
| 1192 |
+
parfor_tuple_params.append(pi)
|
| 1193 |
+
else:
|
| 1194 |
+
tuple_expanded_parfor_inputs.append(pi)
|
| 1195 |
+
parfor_inputs = tuple_expanded_parfor_inputs
|
| 1196 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 1197 |
+
print("parfor_inputs post tuple handling = ", parfor_inputs, " ", type(parfor_inputs))
|
| 1198 |
+
# -------------------------------------------------------------------------
|
| 1199 |
+
|
| 1200 |
+
races = races.difference(set(parfor_redvars))
|
| 1201 |
+
for race in races:
|
| 1202 |
+
msg = ("Variable %s used in parallel loop may be written "
|
| 1203 |
+
"to simultaneously by multiple workers and may result "
|
| 1204 |
+
"in non-deterministic or unintended results." % race)
|
| 1205 |
+
warnings.warn(NumbaParallelSafetyWarning(msg, loc))
|
| 1206 |
+
replace_var_with_array(races, loop_body, typemap, lowerer.fndesc.calltypes)
|
| 1207 |
+
|
| 1208 |
+
# Reduction variables are represented as arrays, so they go under
|
| 1209 |
+
# different names.
|
| 1210 |
+
parfor_redarrs = []
|
| 1211 |
+
parfor_red_arg_types = []
|
| 1212 |
+
for var in parfor_redvars:
|
| 1213 |
+
arr = var + "_arr"
|
| 1214 |
+
parfor_redarrs.append(arr)
|
| 1215 |
+
redarraytype = redtyp_to_redarraytype(typemap[var])
|
| 1216 |
+
parfor_red_arg_types.append(redarraytype)
|
| 1217 |
+
redarrsig = redarraytype_to_sig(redarraytype)
|
| 1218 |
+
if arr in typemap:
|
| 1219 |
+
assert(typemap[arr] == redarrsig)
|
| 1220 |
+
else:
|
| 1221 |
+
typemap[arr] = redarrsig
|
| 1222 |
+
|
| 1223 |
+
# Reorder all the params so that inputs go first then outputs.
|
| 1224 |
+
parfor_params = parfor_inputs + parfor_outputs + parfor_redarrs
|
| 1225 |
+
|
| 1226 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 1227 |
+
print("parfor_params = ", parfor_params, " ", type(parfor_params))
|
| 1228 |
+
print("loop_indices = ", loop_indices, " ", type(loop_indices))
|
| 1229 |
+
print("loop_body = ", loop_body, " ", type(loop_body))
|
| 1230 |
+
_print_body(loop_body)
|
| 1231 |
+
|
| 1232 |
+
# Some Var are not legal parameter names so create a dict of potentially illegal
|
| 1233 |
+
# param name to guaranteed legal name.
|
| 1234 |
+
param_dict = legalize_names_with_typemap(parfor_params + parfor_redvars + parfor_tuple_params, typemap)
|
| 1235 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 1236 |
+
print(
|
| 1237 |
+
"param_dict = ",
|
| 1238 |
+
sorted(
|
| 1239 |
+
param_dict.items()),
|
| 1240 |
+
" ",
|
| 1241 |
+
type(param_dict))
|
| 1242 |
+
|
| 1243 |
+
# Some loop_indices are not legal parameter names so create a dict of potentially illegal
|
| 1244 |
+
# loop index to guaranteed legal name.
|
| 1245 |
+
ind_dict = legalize_names_with_typemap(loop_indices, typemap)
|
| 1246 |
+
# Compute a new list of legal loop index names.
|
| 1247 |
+
legal_loop_indices = [ind_dict[v] for v in loop_indices]
|
| 1248 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 1249 |
+
print("ind_dict = ", sorted(ind_dict.items()), " ", type(ind_dict))
|
| 1250 |
+
print(
|
| 1251 |
+
"legal_loop_indices = ",
|
| 1252 |
+
legal_loop_indices,
|
| 1253 |
+
" ",
|
| 1254 |
+
type(legal_loop_indices))
|
| 1255 |
+
for pd in parfor_params:
|
| 1256 |
+
print("pd = ", pd)
|
| 1257 |
+
print("pd type = ", typemap[pd], " ", type(typemap[pd]))
|
| 1258 |
+
|
| 1259 |
+
# Get the types of each parameter.
|
| 1260 |
+
param_types = [to_scalar_from_0d(typemap[v]) for v in parfor_params]
|
| 1261 |
+
# Calculate types of args passed to gufunc.
|
| 1262 |
+
func_arg_types = [typemap[v] for v in (parfor_inputs + parfor_outputs)] + parfor_red_arg_types
|
| 1263 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 1264 |
+
print("new param_types:", param_types)
|
| 1265 |
+
print("new func_arg_types:", func_arg_types)
|
| 1266 |
+
|
| 1267 |
+
# Replace illegal parameter names in the loop body with legal ones.
|
| 1268 |
+
replace_var_names(loop_body, param_dict)
|
| 1269 |
+
# remember the name before legalizing as the actual arguments
|
| 1270 |
+
parfor_args = parfor_params
|
| 1271 |
+
# Change parfor_params to be legal names.
|
| 1272 |
+
parfor_params = [param_dict[v] for v in parfor_params]
|
| 1273 |
+
parfor_params_orig = parfor_params
|
| 1274 |
+
|
| 1275 |
+
parfor_params = []
|
| 1276 |
+
ascontig = False
|
| 1277 |
+
for pindex in range(len(parfor_params_orig)):
|
| 1278 |
+
if (ascontig and
|
| 1279 |
+
pindex < len(parfor_inputs) and
|
| 1280 |
+
isinstance(param_types[pindex], types.npytypes.Array)):
|
| 1281 |
+
parfor_params.append(parfor_params_orig[pindex]+"param")
|
| 1282 |
+
else:
|
| 1283 |
+
parfor_params.append(parfor_params_orig[pindex])
|
| 1284 |
+
|
| 1285 |
+
# Change parfor body to replace illegal loop index vars with legal ones.
|
| 1286 |
+
replace_var_names(loop_body, ind_dict)
|
| 1287 |
+
loop_body_var_table = get_name_var_table(loop_body)
|
| 1288 |
+
sentinel_name = get_unused_var_name("__sentinel__", loop_body_var_table)
|
| 1289 |
+
|
| 1290 |
+
if config.DEBUG_ARRAY_OPT >= 1:
|
| 1291 |
+
print(
|
| 1292 |
+
"legal parfor_params = ",
|
| 1293 |
+
parfor_params,
|
| 1294 |
+
" ",
|
| 1295 |
+
type(parfor_params))
|
| 1296 |
+
|
| 1297 |
+
# Determine the unique names of the scheduling and gufunc functions.
|
| 1298 |
+
# sched_func_name = "__numba_parfor_sched_%s" % (hex(hash(parfor)).replace("-", "_"))
|
| 1299 |
+
gufunc_name = "__numba_parfor_gufunc_%s" % (
|
| 1300 |
+
hex(hash(parfor)).replace("-", "_"))
|
| 1301 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1302 |
+
# print("sched_func_name ", type(sched_func_name), " ", sched_func_name)
|
| 1303 |
+
print("gufunc_name ", type(gufunc_name), " ", gufunc_name)
|
| 1304 |
+
|
| 1305 |
+
gufunc_txt = ""
|
| 1306 |
+
|
| 1307 |
+
# Create the gufunc function.
|
| 1308 |
+
gufunc_txt += "def " + gufunc_name + \
|
| 1309 |
+
"(sched, " + (", ".join(parfor_params)) + "):\n"
|
| 1310 |
+
|
| 1311 |
+
globls = {"np": np, "numba": numba}
|
| 1312 |
+
|
| 1313 |
+
# First thing in the gufunc, we reconstruct tuples from their
|
| 1314 |
+
# individual parts, e.g., orig_tup_name = (part1, part2,).
|
| 1315 |
+
# The rest of the code of the function will use the original tuple name.
|
| 1316 |
+
for tup_var, exp_names in tuple_var_to_expanded_names.items():
|
| 1317 |
+
tup_type = typemap[tup_var]
|
| 1318 |
+
gufunc_txt += " " + param_dict[tup_var]
|
| 1319 |
+
# Determine if the tuple is a named tuple.
|
| 1320 |
+
if (isinstance(tup_type, types.NamedTuple) or
|
| 1321 |
+
isinstance(tup_type, types.NamedUniTuple)):
|
| 1322 |
+
named_tup = True
|
| 1323 |
+
else:
|
| 1324 |
+
named_tup = False
|
| 1325 |
+
|
| 1326 |
+
if named_tup:
|
| 1327 |
+
# It is a named tuple so try to find the global that defines the
|
| 1328 |
+
# named tuple.
|
| 1329 |
+
func_def = guard(get_definition, lowerer.func_ir, tup_var)
|
| 1330 |
+
named_tuple_def = None
|
| 1331 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1332 |
+
print("func_def:", func_def, type(func_def))
|
| 1333 |
+
if func_def is not None:
|
| 1334 |
+
if (isinstance(func_def, ir.Expr) and
|
| 1335 |
+
func_def.op == 'call'):
|
| 1336 |
+
named_tuple_def = guard(get_definition, lowerer.func_ir, func_def.func)
|
| 1337 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1338 |
+
print("named_tuple_def:", named_tuple_def, type(named_tuple_def))
|
| 1339 |
+
elif isinstance(func_def, ir.Arg):
|
| 1340 |
+
named_tuple_def = typemap[func_def.name]
|
| 1341 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1342 |
+
print("named_tuple_def:", named_tuple_def,
|
| 1343 |
+
type(named_tuple_def), named_tuple_def.name)
|
| 1344 |
+
if named_tuple_def is not None:
|
| 1345 |
+
if (isinstance(named_tuple_def, ir.Global) or
|
| 1346 |
+
isinstance(named_tuple_def, ir.FreeVar)):
|
| 1347 |
+
gval = named_tuple_def.value
|
| 1348 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1349 |
+
print("gval:", gval, type(gval))
|
| 1350 |
+
globls[named_tuple_def.name] = gval
|
| 1351 |
+
elif isinstance(named_tuple_def, types.containers.BaseNamedTuple):
|
| 1352 |
+
named_tuple_name = named_tuple_def.name.split('(')[0]
|
| 1353 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1354 |
+
print("name:", named_tuple_name,
|
| 1355 |
+
named_tuple_def.instance_class,
|
| 1356 |
+
type(named_tuple_def.instance_class))
|
| 1357 |
+
globls[named_tuple_name] = named_tuple_def.instance_class
|
| 1358 |
+
else:
|
| 1359 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1360 |
+
print("Didn't find definition of namedtuple for globls.")
|
| 1361 |
+
raise CompilerError("Could not find definition of " + str(tup_var),
|
| 1362 |
+
tup_var.loc)
|
| 1363 |
+
gufunc_txt += " = " + tup_type.instance_class.__name__ + "("
|
| 1364 |
+
for name, field_name in zip(exp_names, tup_type.fields):
|
| 1365 |
+
gufunc_txt += field_name + "=" + param_dict[name] + ","
|
| 1366 |
+
else:
|
| 1367 |
+
# Just a regular tuple so use (part0, part1, ...)
|
| 1368 |
+
gufunc_txt += " = (" + ", ".join([param_dict[x] for x in exp_names])
|
| 1369 |
+
if len(exp_names) == 1:
|
| 1370 |
+
# Add comma for tuples with singular values. We can't unilaterally
|
| 1371 |
+
# add a comma always because (,) isn't valid.
|
| 1372 |
+
gufunc_txt += ","
|
| 1373 |
+
|
| 1374 |
+
gufunc_txt += ")\n"
|
| 1375 |
+
|
| 1376 |
+
for pindex in range(len(parfor_inputs)):
|
| 1377 |
+
if ascontig and isinstance(param_types[pindex], types.npytypes.Array):
|
| 1378 |
+
gufunc_txt += (" " + parfor_params_orig[pindex]
|
| 1379 |
+
+ " = np.ascontiguousarray(" + parfor_params[pindex] + ")\n")
|
| 1380 |
+
|
| 1381 |
+
gufunc_thread_id_var = "ParallelAcceleratorGufuncThreadId"
|
| 1382 |
+
|
| 1383 |
+
if len(parfor_redarrs) > 0:
|
| 1384 |
+
gufunc_txt += " " + gufunc_thread_id_var + " = "
|
| 1385 |
+
gufunc_txt += "numba.np.ufunc.parallel._iget_thread_id()\n"
|
| 1386 |
+
|
| 1387 |
+
# Add initialization of reduction variables
|
| 1388 |
+
for arr, var in zip(parfor_redarrs, parfor_redvars):
|
| 1389 |
+
gufunc_txt += " " + param_dict[var] + \
|
| 1390 |
+
"=" + param_dict[arr] + "[" + gufunc_thread_id_var + "]\n"
|
| 1391 |
+
if config.DEBUG_ARRAY_OPT_RUNTIME:
|
| 1392 |
+
gufunc_txt += " print(\"thread id =\", ParallelAcceleratorGufuncThreadId)\n"
|
| 1393 |
+
gufunc_txt += " print(\"initial reduction value\",ParallelAcceleratorGufuncThreadId," + param_dict[var] + "," + param_dict[var] + ".shape)\n"
|
| 1394 |
+
gufunc_txt += " print(\"reduction array\",ParallelAcceleratorGufuncThreadId," + param_dict[arr] + "," + param_dict[arr] + ".shape)\n"
|
| 1395 |
+
|
| 1396 |
+
# For each dimension of the parfor, create a for loop in the generated gufunc function.
|
| 1397 |
+
# Iterate across the proper values extracted from the schedule.
|
| 1398 |
+
# The form of the schedule is start_dim0, start_dim1, ..., start_dimN, end_dim0,
|
| 1399 |
+
# end_dim1, ..., end_dimN
|
| 1400 |
+
for eachdim in range(parfor_dim):
|
| 1401 |
+
for indent in range(eachdim + 1):
|
| 1402 |
+
gufunc_txt += " "
|
| 1403 |
+
sched_dim = eachdim
|
| 1404 |
+
gufunc_txt += ("for " +
|
| 1405 |
+
legal_loop_indices[eachdim] +
|
| 1406 |
+
" in range(sched[" +
|
| 1407 |
+
str(sched_dim) +
|
| 1408 |
+
"], sched[" +
|
| 1409 |
+
str(sched_dim +
|
| 1410 |
+
parfor_dim) +
|
| 1411 |
+
"] + np.uint8(1)):\n")
|
| 1412 |
+
|
| 1413 |
+
if config.DEBUG_ARRAY_OPT_RUNTIME:
|
| 1414 |
+
for indent in range(parfor_dim + 1):
|
| 1415 |
+
gufunc_txt += " "
|
| 1416 |
+
gufunc_txt += "print("
|
| 1417 |
+
for eachdim in range(parfor_dim):
|
| 1418 |
+
gufunc_txt += "\"" + legal_loop_indices[eachdim] + "\"," + legal_loop_indices[eachdim] + ","
|
| 1419 |
+
gufunc_txt += ")\n"
|
| 1420 |
+
|
| 1421 |
+
# Add the sentinel assignment so that we can find the loop body position
|
| 1422 |
+
# in the IR.
|
| 1423 |
+
for indent in range(parfor_dim + 1):
|
| 1424 |
+
gufunc_txt += " "
|
| 1425 |
+
gufunc_txt += sentinel_name + " = 0\n"
|
| 1426 |
+
# Add assignments of reduction variables (for returning the value)
|
| 1427 |
+
for arr, var in zip(parfor_redarrs, parfor_redvars):
|
| 1428 |
+
if config.DEBUG_ARRAY_OPT_RUNTIME:
|
| 1429 |
+
gufunc_txt += " print(\"final reduction value\",ParallelAcceleratorGufuncThreadId," + param_dict[var] + ")\n"
|
| 1430 |
+
gufunc_txt += " print(\"final reduction array\",ParallelAcceleratorGufuncThreadId," + param_dict[arr] + ")\n"
|
| 1431 |
+
# After the gufunc loops, copy the accumulated temp value back to reduction array.
|
| 1432 |
+
gufunc_txt += " " + param_dict[arr] + \
|
| 1433 |
+
"[" + gufunc_thread_id_var + "] = " + param_dict[var] + "\n"
|
| 1434 |
+
gufunc_txt += " return None\n"
|
| 1435 |
+
|
| 1436 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1437 |
+
print("gufunc_txt = ", type(gufunc_txt), "\n", gufunc_txt)
|
| 1438 |
+
print("globls:", globls, type(globls))
|
| 1439 |
+
# Force gufunc outline into existence.
|
| 1440 |
+
locls = {}
|
| 1441 |
+
exec(gufunc_txt, globls, locls)
|
| 1442 |
+
gufunc_func = locls[gufunc_name]
|
| 1443 |
+
|
| 1444 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1445 |
+
print("gufunc_func = ", type(gufunc_func), "\n", gufunc_func)
|
| 1446 |
+
# Get the IR for the gufunc outline.
|
| 1447 |
+
gufunc_ir = compiler.run_frontend(gufunc_func)
|
| 1448 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1449 |
+
print("gufunc_ir dump ", type(gufunc_ir))
|
| 1450 |
+
gufunc_ir.dump()
|
| 1451 |
+
print("loop_body dump ", type(loop_body))
|
| 1452 |
+
_print_body(loop_body)
|
| 1453 |
+
|
| 1454 |
+
# rename all variables in gufunc_ir afresh
|
| 1455 |
+
var_table = get_name_var_table(gufunc_ir.blocks)
|
| 1456 |
+
new_var_dict = {}
|
| 1457 |
+
reserved_names = [sentinel_name] + \
|
| 1458 |
+
list(param_dict.values()) + legal_loop_indices
|
| 1459 |
+
for name, var in var_table.items():
|
| 1460 |
+
if not (name in reserved_names):
|
| 1461 |
+
new_var_dict[name] = parfor.init_block.scope.redefine(name, loc).name
|
| 1462 |
+
replace_var_names(gufunc_ir.blocks, new_var_dict)
|
| 1463 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1464 |
+
print("gufunc_ir dump after renaming ")
|
| 1465 |
+
gufunc_ir.dump()
|
| 1466 |
+
gufunc_param_types = [types.npytypes.Array(
|
| 1467 |
+
index_var_typ, 1, "C")] + param_types
|
| 1468 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1469 |
+
print(
|
| 1470 |
+
"gufunc_param_types = ",
|
| 1471 |
+
type(gufunc_param_types),
|
| 1472 |
+
"\n",
|
| 1473 |
+
gufunc_param_types)
|
| 1474 |
+
|
| 1475 |
+
gufunc_stub_last_label = find_max_label(gufunc_ir.blocks) + 1
|
| 1476 |
+
|
| 1477 |
+
# Add gufunc stub last label to each parfor.loop_body label to prevent
|
| 1478 |
+
# label conflicts.
|
| 1479 |
+
loop_body = add_offset_to_labels(loop_body, gufunc_stub_last_label)
|
| 1480 |
+
# new label for splitting sentinel block
|
| 1481 |
+
new_label = find_max_label(loop_body) + 1
|
| 1482 |
+
|
| 1483 |
+
# If enabled, add a print statement after every assignment.
|
| 1484 |
+
if config.DEBUG_ARRAY_OPT_RUNTIME:
|
| 1485 |
+
for label, block in loop_body.items():
|
| 1486 |
+
new_block = block.copy()
|
| 1487 |
+
new_block.clear()
|
| 1488 |
+
loc = block.loc
|
| 1489 |
+
scope = block.scope
|
| 1490 |
+
for inst in block.body:
|
| 1491 |
+
new_block.append(inst)
|
| 1492 |
+
# Append print after assignment
|
| 1493 |
+
if isinstance(inst, ir.Assign):
|
| 1494 |
+
# Only apply to numbers
|
| 1495 |
+
if typemap[inst.target.name] not in types.number_domain:
|
| 1496 |
+
continue
|
| 1497 |
+
|
| 1498 |
+
# Make constant string
|
| 1499 |
+
strval = "{} =".format(inst.target.name)
|
| 1500 |
+
strconsttyp = types.StringLiteral(strval)
|
| 1501 |
+
|
| 1502 |
+
lhs = scope.redefine("str_const", loc)
|
| 1503 |
+
# lhs = ir.Var(scope, mk_unique_var("str_const"), loc)
|
| 1504 |
+
assign_lhs = ir.Assign(value=ir.Const(value=strval, loc=loc),
|
| 1505 |
+
target=lhs, loc=loc)
|
| 1506 |
+
typemap[lhs.name] = strconsttyp
|
| 1507 |
+
new_block.append(assign_lhs)
|
| 1508 |
+
|
| 1509 |
+
# Make print node
|
| 1510 |
+
print_node = ir.Print(args=[lhs, inst.target], vararg=None, loc=loc)
|
| 1511 |
+
new_block.append(print_node)
|
| 1512 |
+
sig = numba.core.typing.signature(types.none,
|
| 1513 |
+
typemap[lhs.name],
|
| 1514 |
+
typemap[inst.target.name])
|
| 1515 |
+
lowerer.fndesc.calltypes[print_node] = sig
|
| 1516 |
+
loop_body[label] = new_block
|
| 1517 |
+
|
| 1518 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1519 |
+
print("parfor loop body")
|
| 1520 |
+
_print_body(loop_body)
|
| 1521 |
+
|
| 1522 |
+
wrapped_blocks = wrap_loop_body(loop_body)
|
| 1523 |
+
hoisted, not_hoisted = hoist(parfor_params, loop_body, typemap, wrapped_blocks)
|
| 1524 |
+
start_block = gufunc_ir.blocks[min(gufunc_ir.blocks.keys())]
|
| 1525 |
+
start_block.body = start_block.body[:-1] + hoisted + [start_block.body[-1]]
|
| 1526 |
+
unwrap_loop_body(loop_body)
|
| 1527 |
+
|
| 1528 |
+
# store hoisted into diagnostics
|
| 1529 |
+
diagnostics = lowerer.metadata['parfor_diagnostics']
|
| 1530 |
+
diagnostics.hoist_info[parfor.id] = {'hoisted': hoisted,
|
| 1531 |
+
'not_hoisted': not_hoisted}
|
| 1532 |
+
|
| 1533 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1534 |
+
print("After hoisting")
|
| 1535 |
+
_print_body(loop_body)
|
| 1536 |
+
|
| 1537 |
+
# Search all the block in the gufunc outline for the sentinel assignment.
|
| 1538 |
+
for label, block in gufunc_ir.blocks.items():
|
| 1539 |
+
for i, inst in enumerate(block.body):
|
| 1540 |
+
if isinstance(
|
| 1541 |
+
inst,
|
| 1542 |
+
ir.Assign) and inst.target.name == sentinel_name:
|
| 1543 |
+
# We found the sentinel assignment.
|
| 1544 |
+
loc = inst.loc
|
| 1545 |
+
scope = block.scope
|
| 1546 |
+
# split block across __sentinel__
|
| 1547 |
+
# A new block is allocated for the statements prior to the sentinel
|
| 1548 |
+
# but the new block maintains the current block label.
|
| 1549 |
+
prev_block = ir.Block(scope, loc)
|
| 1550 |
+
prev_block.body = block.body[:i]
|
| 1551 |
+
# The current block is used for statements after the sentinel.
|
| 1552 |
+
block.body = block.body[i + 1:]
|
| 1553 |
+
# But the current block gets a new label.
|
| 1554 |
+
body_first_label = min(loop_body.keys())
|
| 1555 |
+
|
| 1556 |
+
# The previous block jumps to the minimum labelled block of the
|
| 1557 |
+
# parfor body.
|
| 1558 |
+
prev_block.append(ir.Jump(body_first_label, loc))
|
| 1559 |
+
# Add all the parfor loop body blocks to the gufunc function's
|
| 1560 |
+
# IR.
|
| 1561 |
+
for (l, b) in loop_body.items():
|
| 1562 |
+
gufunc_ir.blocks[l] = transfer_scope(b, scope)
|
| 1563 |
+
body_last_label = max(loop_body.keys())
|
| 1564 |
+
gufunc_ir.blocks[new_label] = block
|
| 1565 |
+
gufunc_ir.blocks[label] = prev_block
|
| 1566 |
+
# Add a jump from the last parfor body block to the block containing
|
| 1567 |
+
# statements after the sentinel.
|
| 1568 |
+
gufunc_ir.blocks[body_last_label].append(
|
| 1569 |
+
ir.Jump(new_label, loc))
|
| 1570 |
+
break
|
| 1571 |
+
else:
|
| 1572 |
+
continue
|
| 1573 |
+
break
|
| 1574 |
+
|
| 1575 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1576 |
+
print("gufunc_ir last dump before renaming")
|
| 1577 |
+
gufunc_ir.dump()
|
| 1578 |
+
|
| 1579 |
+
gufunc_ir.blocks = rename_labels(gufunc_ir.blocks)
|
| 1580 |
+
remove_dels(gufunc_ir.blocks)
|
| 1581 |
+
|
| 1582 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1583 |
+
print("gufunc_ir last dump")
|
| 1584 |
+
gufunc_ir.dump()
|
| 1585 |
+
print("flags", flags)
|
| 1586 |
+
print("typemap", typemap)
|
| 1587 |
+
|
| 1588 |
+
old_alias = flags.noalias
|
| 1589 |
+
if not has_aliases:
|
| 1590 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1591 |
+
print("No aliases found so adding noalias flag.")
|
| 1592 |
+
flags.noalias = True
|
| 1593 |
+
|
| 1594 |
+
fixup_var_define_in_scope(gufunc_ir.blocks)
|
| 1595 |
+
|
| 1596 |
+
class ParforGufuncCompiler(compiler.CompilerBase):
|
| 1597 |
+
def define_pipelines(self):
|
| 1598 |
+
from numba.core.compiler_machinery import PassManager
|
| 1599 |
+
dpb = compiler.DefaultPassBuilder
|
| 1600 |
+
pm = PassManager("full_parfor_gufunc")
|
| 1601 |
+
parfor_gufunc_passes = dpb.define_parfor_gufunc_pipeline(self.state)
|
| 1602 |
+
pm.passes.extend(parfor_gufunc_passes.passes)
|
| 1603 |
+
lowering_passes = dpb.define_parfor_gufunc_nopython_lowering_pipeline(self.state)
|
| 1604 |
+
pm.passes.extend(lowering_passes.passes)
|
| 1605 |
+
|
| 1606 |
+
pm.finalize()
|
| 1607 |
+
return [pm]
|
| 1608 |
+
|
| 1609 |
+
kernel_func = compiler.compile_ir(
|
| 1610 |
+
typingctx,
|
| 1611 |
+
targetctx,
|
| 1612 |
+
gufunc_ir,
|
| 1613 |
+
gufunc_param_types,
|
| 1614 |
+
types.none,
|
| 1615 |
+
flags,
|
| 1616 |
+
locals,
|
| 1617 |
+
pipeline_class=ParforGufuncCompiler)
|
| 1618 |
+
|
| 1619 |
+
flags.noalias = old_alias
|
| 1620 |
+
|
| 1621 |
+
kernel_sig = signature(types.none, *gufunc_param_types)
|
| 1622 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1623 |
+
print("finished create_gufunc_for_parfor_body. kernel_sig = ", kernel_sig)
|
| 1624 |
+
|
| 1625 |
+
return kernel_func, parfor_args, kernel_sig, func_arg_types, expanded_name_to_tuple_var
|
| 1626 |
+
|
| 1627 |
+
def replace_var_with_array_in_block(vars, block, typemap, calltypes):
|
| 1628 |
+
new_block = []
|
| 1629 |
+
for inst in block.body:
|
| 1630 |
+
if isinstance(inst, ir.Assign) and inst.target.name in vars:
|
| 1631 |
+
loc = inst.loc
|
| 1632 |
+
scope = inst.target.scope
|
| 1633 |
+
|
| 1634 |
+
const_node = ir.Const(0, loc)
|
| 1635 |
+
const_var = scope.redefine("$const_ind_0", loc)
|
| 1636 |
+
typemap[const_var.name] = types.uintp
|
| 1637 |
+
const_assign = ir.Assign(const_node, const_var, loc)
|
| 1638 |
+
new_block.append(const_assign)
|
| 1639 |
+
|
| 1640 |
+
val_var = scope.redefine("$val", loc)
|
| 1641 |
+
typemap[val_var.name] = typemap[inst.target.name]
|
| 1642 |
+
new_block.append(ir.Assign(inst.value, val_var, loc))
|
| 1643 |
+
setitem_node = ir.SetItem(inst.target, const_var, val_var, loc)
|
| 1644 |
+
calltypes[setitem_node] = signature(
|
| 1645 |
+
types.none, types.npytypes.Array(typemap[inst.target.name], 1, "C"), types.intp, typemap[inst.target.name])
|
| 1646 |
+
new_block.append(setitem_node)
|
| 1647 |
+
continue
|
| 1648 |
+
elif isinstance(inst, parfor.Parfor):
|
| 1649 |
+
replace_var_with_array_internal(vars, {0: inst.init_block}, typemap, calltypes)
|
| 1650 |
+
replace_var_with_array_internal(vars, inst.loop_body, typemap, calltypes)
|
| 1651 |
+
|
| 1652 |
+
new_block.append(inst)
|
| 1653 |
+
return new_block
|
| 1654 |
+
|
| 1655 |
+
def replace_var_with_array_internal(vars, loop_body, typemap, calltypes):
|
| 1656 |
+
for label, block in loop_body.items():
|
| 1657 |
+
block.body = replace_var_with_array_in_block(vars, block, typemap, calltypes)
|
| 1658 |
+
|
| 1659 |
+
def replace_var_with_array(vars, loop_body, typemap, calltypes):
|
| 1660 |
+
replace_var_with_array_internal(vars, loop_body, typemap, calltypes)
|
| 1661 |
+
for v in vars:
|
| 1662 |
+
el_typ = typemap[v]
|
| 1663 |
+
typemap.pop(v, None)
|
| 1664 |
+
typemap[v] = types.npytypes.Array(el_typ, 1, "C")
|
| 1665 |
+
|
| 1666 |
+
def call_parallel_gufunc(lowerer, cres, gu_signature, outer_sig, expr_args, expr_arg_types,
|
| 1667 |
+
loop_ranges, redvars, reddict, redarrdict, init_block, index_var_typ, races,
|
| 1668 |
+
exp_name_to_tuple_var):
|
| 1669 |
+
'''
|
| 1670 |
+
Adds the call to the gufunc function from the main function.
|
| 1671 |
+
'''
|
| 1672 |
+
context = lowerer.context
|
| 1673 |
+
builder = lowerer.builder
|
| 1674 |
+
|
| 1675 |
+
from numba.np.ufunc.parallel import (build_gufunc_wrapper,
|
| 1676 |
+
_launch_threads)
|
| 1677 |
+
|
| 1678 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1679 |
+
print("make_parallel_loop")
|
| 1680 |
+
print("outer_sig = ", outer_sig.args, outer_sig.return_type,
|
| 1681 |
+
outer_sig.recvr, outer_sig.pysig)
|
| 1682 |
+
print("loop_ranges = ", loop_ranges)
|
| 1683 |
+
print("expr_args", expr_args)
|
| 1684 |
+
print("expr_arg_types", expr_arg_types)
|
| 1685 |
+
print("gu_signature", gu_signature)
|
| 1686 |
+
|
| 1687 |
+
# Build the wrapper for GUFunc
|
| 1688 |
+
args, return_type = sigutils.normalize_signature(outer_sig)
|
| 1689 |
+
llvm_func = cres.library.get_function(cres.fndesc.llvm_func_name)
|
| 1690 |
+
sin, sout = gu_signature
|
| 1691 |
+
|
| 1692 |
+
# These are necessary for build_gufunc_wrapper to find external symbols
|
| 1693 |
+
_launch_threads()
|
| 1694 |
+
|
| 1695 |
+
info = build_gufunc_wrapper(llvm_func, cres, sin, sout,
|
| 1696 |
+
cache=False, is_parfors=True)
|
| 1697 |
+
wrapper_name = info.name
|
| 1698 |
+
cres.library._ensure_finalized()
|
| 1699 |
+
|
| 1700 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1701 |
+
print("parallel function = ", wrapper_name, cres)
|
| 1702 |
+
|
| 1703 |
+
# loadvars for loop_ranges
|
| 1704 |
+
def load_range(v):
|
| 1705 |
+
if isinstance(v, ir.Var):
|
| 1706 |
+
return lowerer.loadvar(v.name)
|
| 1707 |
+
else:
|
| 1708 |
+
return context.get_constant(types.uintp, v)
|
| 1709 |
+
|
| 1710 |
+
num_dim = len(loop_ranges)
|
| 1711 |
+
for i in range(num_dim):
|
| 1712 |
+
start, stop, step = loop_ranges[i]
|
| 1713 |
+
start = load_range(start)
|
| 1714 |
+
stop = load_range(stop)
|
| 1715 |
+
assert(step == 1) # We do not support loop steps other than 1
|
| 1716 |
+
step = load_range(step)
|
| 1717 |
+
loop_ranges[i] = (start, stop, step)
|
| 1718 |
+
|
| 1719 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1720 |
+
print("call_parallel_gufunc loop_ranges[{}] = ".format(i), start,
|
| 1721 |
+
stop, step)
|
| 1722 |
+
cgutils.printf(builder, "loop range[{}]: %d %d (%d)\n".format(i),
|
| 1723 |
+
start, stop, step)
|
| 1724 |
+
|
| 1725 |
+
# Commonly used LLVM types and constants
|
| 1726 |
+
byte_t = llvmlite.ir.IntType(8)
|
| 1727 |
+
byte_ptr_t = llvmlite.ir.PointerType(byte_t)
|
| 1728 |
+
byte_ptr_ptr_t = llvmlite.ir.PointerType(byte_ptr_t)
|
| 1729 |
+
intp_t = context.get_value_type(types.intp)
|
| 1730 |
+
uintp_t = context.get_value_type(types.uintp)
|
| 1731 |
+
intp_ptr_t = llvmlite.ir.PointerType(intp_t)
|
| 1732 |
+
intp_ptr_ptr_t = llvmlite.ir.PointerType(intp_ptr_t)
|
| 1733 |
+
uintp_ptr_t = llvmlite.ir.PointerType(uintp_t)
|
| 1734 |
+
uintp_ptr_ptr_t = llvmlite.ir.PointerType(uintp_ptr_t)
|
| 1735 |
+
zero = context.get_constant(types.uintp, 0)
|
| 1736 |
+
one = context.get_constant(types.uintp, 1)
|
| 1737 |
+
one_type = one.type
|
| 1738 |
+
sizeof_intp = context.get_abi_sizeof(intp_t)
|
| 1739 |
+
|
| 1740 |
+
# Prepare sched, first pop it out of expr_args, outer_sig, and gu_signature
|
| 1741 |
+
expr_args.pop(0)
|
| 1742 |
+
sched_sig = sin.pop(0)
|
| 1743 |
+
|
| 1744 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1745 |
+
print("Parfor has potentially negative start", index_var_typ.signed)
|
| 1746 |
+
|
| 1747 |
+
if index_var_typ.signed:
|
| 1748 |
+
sched_type = intp_t
|
| 1749 |
+
sched_ptr_type = intp_ptr_t
|
| 1750 |
+
sched_ptr_ptr_type = intp_ptr_ptr_t
|
| 1751 |
+
else:
|
| 1752 |
+
sched_type = uintp_t
|
| 1753 |
+
sched_ptr_type = uintp_ptr_t
|
| 1754 |
+
sched_ptr_ptr_type = uintp_ptr_ptr_t
|
| 1755 |
+
|
| 1756 |
+
# Call do_scheduling with appropriate arguments
|
| 1757 |
+
dim_starts = cgutils.alloca_once(
|
| 1758 |
+
builder, sched_type, size=context.get_constant(
|
| 1759 |
+
types.uintp, num_dim), name="dim_starts")
|
| 1760 |
+
dim_stops = cgutils.alloca_once(
|
| 1761 |
+
builder, sched_type, size=context.get_constant(
|
| 1762 |
+
types.uintp, num_dim), name="dim_stops")
|
| 1763 |
+
for i in range(num_dim):
|
| 1764 |
+
start, stop, step = loop_ranges[i]
|
| 1765 |
+
if start.type != one_type:
|
| 1766 |
+
start = builder.sext(start, one_type)
|
| 1767 |
+
if stop.type != one_type:
|
| 1768 |
+
stop = builder.sext(stop, one_type)
|
| 1769 |
+
if step.type != one_type:
|
| 1770 |
+
step = builder.sext(step, one_type)
|
| 1771 |
+
# substract 1 because do-scheduling takes inclusive ranges
|
| 1772 |
+
stop = builder.sub(stop, one)
|
| 1773 |
+
builder.store(
|
| 1774 |
+
start, builder.gep(
|
| 1775 |
+
dim_starts, [
|
| 1776 |
+
context.get_constant(
|
| 1777 |
+
types.uintp, i)]))
|
| 1778 |
+
builder.store(stop, builder.gep(dim_stops,
|
| 1779 |
+
[context.get_constant(types.uintp, i)]))
|
| 1780 |
+
|
| 1781 |
+
# Prepare to call get/set parallel_chunksize and get the number of threads.
|
| 1782 |
+
get_chunksize = cgutils.get_or_insert_function(
|
| 1783 |
+
builder.module,
|
| 1784 |
+
llvmlite.ir.FunctionType(uintp_t, []),
|
| 1785 |
+
name="get_parallel_chunksize")
|
| 1786 |
+
|
| 1787 |
+
set_chunksize = cgutils.get_or_insert_function(
|
| 1788 |
+
builder.module,
|
| 1789 |
+
llvmlite.ir.FunctionType(llvmlite.ir.VoidType(), [uintp_t]),
|
| 1790 |
+
name="set_parallel_chunksize")
|
| 1791 |
+
|
| 1792 |
+
get_num_threads = cgutils.get_or_insert_function(
|
| 1793 |
+
builder.module,
|
| 1794 |
+
llvmlite.ir.FunctionType(llvmlite.ir.IntType(types.intp.bitwidth), []),
|
| 1795 |
+
"get_num_threads")
|
| 1796 |
+
|
| 1797 |
+
# Get the current number of threads.
|
| 1798 |
+
num_threads = builder.call(get_num_threads, [])
|
| 1799 |
+
# Get the current chunksize so we can use it and restore the value later.
|
| 1800 |
+
current_chunksize = builder.call(get_chunksize, [])
|
| 1801 |
+
|
| 1802 |
+
with cgutils.if_unlikely(builder, builder.icmp_signed('<=', num_threads,
|
| 1803 |
+
num_threads.type(0))):
|
| 1804 |
+
cgutils.printf(builder, "num_threads: %d\n", num_threads)
|
| 1805 |
+
context.call_conv.return_user_exc(builder, RuntimeError,
|
| 1806 |
+
("Invalid number of threads. "
|
| 1807 |
+
"This likely indicates a bug in Numba.",))
|
| 1808 |
+
|
| 1809 |
+
# Call get_sched_size from gufunc_scheduler.cpp that incorporates the size of the work,
|
| 1810 |
+
# the number of threads and the selected chunk size. This will tell us how many entries
|
| 1811 |
+
# in the schedule we will need.
|
| 1812 |
+
get_sched_size_fnty = llvmlite.ir.FunctionType(uintp_t, [uintp_t, uintp_t, intp_ptr_t, intp_ptr_t])
|
| 1813 |
+
get_sched_size = cgutils.get_or_insert_function(
|
| 1814 |
+
builder.module,
|
| 1815 |
+
get_sched_size_fnty,
|
| 1816 |
+
name="get_sched_size")
|
| 1817 |
+
num_divisions = builder.call(get_sched_size, [num_threads,
|
| 1818 |
+
context.get_constant(types.uintp, num_dim),
|
| 1819 |
+
dim_starts,
|
| 1820 |
+
dim_stops])
|
| 1821 |
+
# Set the chunksize to zero so that any nested calls get the default chunk size behavior.
|
| 1822 |
+
builder.call(set_chunksize, [zero])
|
| 1823 |
+
|
| 1824 |
+
# Each entry in the schedule is 2 times the number of dimensions long.
|
| 1825 |
+
multiplier = context.get_constant(types.uintp, num_dim * 2)
|
| 1826 |
+
# Compute the total number of entries in the schedule.
|
| 1827 |
+
sched_size = builder.mul(num_divisions, multiplier)
|
| 1828 |
+
|
| 1829 |
+
# Prepare to dynamically allocate memory to hold the schedule.
|
| 1830 |
+
alloc_sched_fnty = llvmlite.ir.FunctionType(sched_ptr_type, [uintp_t])
|
| 1831 |
+
alloc_sched_func = cgutils.get_or_insert_function(
|
| 1832 |
+
builder.module,
|
| 1833 |
+
alloc_sched_fnty,
|
| 1834 |
+
name="allocate_sched")
|
| 1835 |
+
# Call gufunc_scheduler.cpp to allocate the schedule.
|
| 1836 |
+
# This may or may not do pooling.
|
| 1837 |
+
alloc_space = builder.call(alloc_sched_func, [sched_size])
|
| 1838 |
+
# Allocate a slot in the entry block to store the schedule pointer.
|
| 1839 |
+
sched = cgutils.alloca_once(builder, sched_ptr_type)
|
| 1840 |
+
# Store the schedule pointer into that slot.
|
| 1841 |
+
builder.store(alloc_space, sched)
|
| 1842 |
+
|
| 1843 |
+
debug_flag = 1 if config.DEBUG_ARRAY_OPT else 0
|
| 1844 |
+
scheduling_fnty = llvmlite.ir.FunctionType(
|
| 1845 |
+
intp_ptr_t, [uintp_t, intp_ptr_t, intp_ptr_t, uintp_t, sched_ptr_type, intp_t])
|
| 1846 |
+
if index_var_typ.signed:
|
| 1847 |
+
do_scheduling = cgutils.get_or_insert_function(builder.module,
|
| 1848 |
+
scheduling_fnty,
|
| 1849 |
+
name="do_scheduling_signed")
|
| 1850 |
+
else:
|
| 1851 |
+
do_scheduling = cgutils.get_or_insert_function(builder.module,
|
| 1852 |
+
scheduling_fnty,
|
| 1853 |
+
name="do_scheduling_unsigned")
|
| 1854 |
+
|
| 1855 |
+
# Call the scheduling routine that decides how to break up the work.
|
| 1856 |
+
builder.call(
|
| 1857 |
+
do_scheduling, [
|
| 1858 |
+
context.get_constant(
|
| 1859 |
+
types.uintp, num_dim), dim_starts, dim_stops, num_divisions,
|
| 1860 |
+
builder.load(sched), context.get_constant(
|
| 1861 |
+
types.intp, debug_flag)])
|
| 1862 |
+
|
| 1863 |
+
# Get the LLVM vars for the Numba IR reduction array vars.
|
| 1864 |
+
redarrs = [lowerer.loadvar(redarrdict[x].name) for x in redvars]
|
| 1865 |
+
|
| 1866 |
+
nredvars = len(redvars)
|
| 1867 |
+
ninouts = len(expr_args) - nredvars
|
| 1868 |
+
|
| 1869 |
+
def load_potential_tuple_var(x):
|
| 1870 |
+
"""Given a variable name, if that variable is not a new name
|
| 1871 |
+
introduced as the extracted part of a tuple then just return
|
| 1872 |
+
the variable loaded from its name. However, if the variable
|
| 1873 |
+
does represent part of a tuple, as recognized by the name of
|
| 1874 |
+
the variable being present in the exp_name_to_tuple_var dict,
|
| 1875 |
+
then we load the original tuple var instead that we get from
|
| 1876 |
+
the dict and then extract the corresponding element of the
|
| 1877 |
+
tuple, also stored and returned to use in the dict (i.e., offset).
|
| 1878 |
+
"""
|
| 1879 |
+
if x in exp_name_to_tuple_var:
|
| 1880 |
+
orig_tup, offset = exp_name_to_tuple_var[x]
|
| 1881 |
+
tup_var = lowerer.loadvar(orig_tup)
|
| 1882 |
+
res = builder.extract_value(tup_var, offset)
|
| 1883 |
+
return res
|
| 1884 |
+
else:
|
| 1885 |
+
return lowerer.loadvar(x)
|
| 1886 |
+
|
| 1887 |
+
# ----------------------------------------------------------------------------
|
| 1888 |
+
# Prepare arguments: args, shapes, steps, data
|
| 1889 |
+
all_args = [load_potential_tuple_var(x) for x in expr_args[:ninouts]] + redarrs
|
| 1890 |
+
num_args = len(all_args)
|
| 1891 |
+
num_inps = len(sin) + 1
|
| 1892 |
+
args = cgutils.alloca_once(
|
| 1893 |
+
builder,
|
| 1894 |
+
byte_ptr_t,
|
| 1895 |
+
size=context.get_constant(
|
| 1896 |
+
types.intp,
|
| 1897 |
+
1 + num_args),
|
| 1898 |
+
name="pargs")
|
| 1899 |
+
array_strides = []
|
| 1900 |
+
# sched goes first
|
| 1901 |
+
builder.store(builder.bitcast(builder.load(sched), byte_ptr_t), args)
|
| 1902 |
+
array_strides.append(context.get_constant(types.intp, sizeof_intp))
|
| 1903 |
+
rv_to_arg_dict = {}
|
| 1904 |
+
# followed by other arguments
|
| 1905 |
+
for i in range(num_args):
|
| 1906 |
+
arg = all_args[i]
|
| 1907 |
+
var = expr_args[i]
|
| 1908 |
+
aty = expr_arg_types[i]
|
| 1909 |
+
dst = builder.gep(args, [context.get_constant(types.intp, i + 1)])
|
| 1910 |
+
if i >= ninouts: # reduction variables
|
| 1911 |
+
ary = context.make_array(aty)(context, builder, arg)
|
| 1912 |
+
strides = cgutils.unpack_tuple(builder, ary.strides, aty.ndim)
|
| 1913 |
+
# Start from 1 because we skip the first dimension of length num_threads just like sched.
|
| 1914 |
+
for j in range(len(strides)):
|
| 1915 |
+
array_strides.append(strides[j])
|
| 1916 |
+
builder.store(builder.bitcast(ary.data, byte_ptr_t), dst)
|
| 1917 |
+
elif isinstance(aty, types.ArrayCompatible):
|
| 1918 |
+
if var in races:
|
| 1919 |
+
typ = (context.get_data_type(aty.dtype)
|
| 1920 |
+
if aty.dtype != types.boolean
|
| 1921 |
+
else llvmlite.ir.IntType(1))
|
| 1922 |
+
|
| 1923 |
+
rv_arg = cgutils.alloca_once(builder, typ)
|
| 1924 |
+
builder.store(arg, rv_arg)
|
| 1925 |
+
builder.store(builder.bitcast(rv_arg, byte_ptr_t), dst)
|
| 1926 |
+
rv_to_arg_dict[var] = (arg, rv_arg)
|
| 1927 |
+
|
| 1928 |
+
array_strides.append(context.get_constant(types.intp, context.get_abi_sizeof(typ)))
|
| 1929 |
+
else:
|
| 1930 |
+
ary = context.make_array(aty)(context, builder, arg)
|
| 1931 |
+
strides = cgutils.unpack_tuple(builder, ary.strides, aty.ndim)
|
| 1932 |
+
for j in range(len(strides)):
|
| 1933 |
+
array_strides.append(strides[j])
|
| 1934 |
+
builder.store(builder.bitcast(ary.data, byte_ptr_t), dst)
|
| 1935 |
+
else:
|
| 1936 |
+
if i < num_inps:
|
| 1937 |
+
# Scalar input, need to store the value in an array of size 1
|
| 1938 |
+
if isinstance(aty, types.Optional):
|
| 1939 |
+
# Unpack optional type
|
| 1940 |
+
unpacked_aty = aty.type
|
| 1941 |
+
arg = context.cast(builder, arg, aty, unpacked_aty)
|
| 1942 |
+
else:
|
| 1943 |
+
unpacked_aty = aty
|
| 1944 |
+
typ = (context.get_data_type(unpacked_aty)
|
| 1945 |
+
if not isinstance(unpacked_aty, types.Boolean)
|
| 1946 |
+
else llvmlite.ir.IntType(1))
|
| 1947 |
+
ptr = cgutils.alloca_once(builder, typ)
|
| 1948 |
+
builder.store(arg, ptr)
|
| 1949 |
+
else:
|
| 1950 |
+
# Scalar output, must allocate
|
| 1951 |
+
typ = (context.get_data_type(aty)
|
| 1952 |
+
if not isinstance(aty, types.Boolean)
|
| 1953 |
+
else llvmlite.ir.IntType(1))
|
| 1954 |
+
ptr = cgutils.alloca_once(builder, typ)
|
| 1955 |
+
builder.store(builder.bitcast(ptr, byte_ptr_t), dst)
|
| 1956 |
+
|
| 1957 |
+
# ----------------------------------------------------------------------------
|
| 1958 |
+
# Next, we prepare the individual dimension info recorded in gu_signature
|
| 1959 |
+
sig_dim_dict = {}
|
| 1960 |
+
occurrences = []
|
| 1961 |
+
occurrences = [sched_sig[0]]
|
| 1962 |
+
sig_dim_dict[sched_sig[0]] = context.get_constant(types.intp, 2 * num_dim)
|
| 1963 |
+
assert len(expr_args) == len(all_args)
|
| 1964 |
+
assert len(expr_args) == len(expr_arg_types)
|
| 1965 |
+
assert len(expr_args) == len(sin + sout)
|
| 1966 |
+
assert len(expr_args) == len(outer_sig.args[1:])
|
| 1967 |
+
for var, arg, aty, gu_sig in zip(expr_args, all_args,
|
| 1968 |
+
expr_arg_types, sin + sout):
|
| 1969 |
+
if isinstance(aty, types.npytypes.Array):
|
| 1970 |
+
i = aty.ndim - len(gu_sig)
|
| 1971 |
+
else:
|
| 1972 |
+
i = 0
|
| 1973 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1974 |
+
print("var =", var, "gu_sig =", gu_sig, "type =", aty, "i =", i)
|
| 1975 |
+
|
| 1976 |
+
for dim_sym in gu_sig:
|
| 1977 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1978 |
+
print("var = ", var, " type = ", aty)
|
| 1979 |
+
if var in races:
|
| 1980 |
+
sig_dim_dict[dim_sym] = context.get_constant(types.intp, 1)
|
| 1981 |
+
else:
|
| 1982 |
+
ary = context.make_array(aty)(context, builder, arg)
|
| 1983 |
+
shapes = cgutils.unpack_tuple(builder, ary.shape, aty.ndim)
|
| 1984 |
+
sig_dim_dict[dim_sym] = shapes[i]
|
| 1985 |
+
|
| 1986 |
+
if not (dim_sym in occurrences):
|
| 1987 |
+
if config.DEBUG_ARRAY_OPT:
|
| 1988 |
+
print("dim_sym = ", dim_sym, ", i = ", i)
|
| 1989 |
+
cgutils.printf(builder, dim_sym + " = %d\n", sig_dim_dict[dim_sym])
|
| 1990 |
+
occurrences.append(dim_sym)
|
| 1991 |
+
i = i + 1
|
| 1992 |
+
|
| 1993 |
+
# ----------------------------------------------------------------------------
|
| 1994 |
+
# Prepare shapes, which is a single number (outer loop size), followed by
|
| 1995 |
+
# the size of individual shape variables.
|
| 1996 |
+
nshapes = len(sig_dim_dict) + 1
|
| 1997 |
+
shapes = cgutils.alloca_once(builder, intp_t, size=nshapes, name="pshape")
|
| 1998 |
+
# For now, outer loop size is the same as number of threads
|
| 1999 |
+
builder.store(num_divisions, shapes)
|
| 2000 |
+
# Individual shape variables go next
|
| 2001 |
+
i = 1
|
| 2002 |
+
for dim_sym in occurrences:
|
| 2003 |
+
if config.DEBUG_ARRAY_OPT:
|
| 2004 |
+
cgutils.printf(builder, dim_sym + " = %d\n", sig_dim_dict[dim_sym])
|
| 2005 |
+
builder.store(
|
| 2006 |
+
sig_dim_dict[dim_sym], builder.gep(
|
| 2007 |
+
shapes, [
|
| 2008 |
+
context.get_constant(
|
| 2009 |
+
types.intp, i)]))
|
| 2010 |
+
i = i + 1
|
| 2011 |
+
|
| 2012 |
+
# ----------------------------------------------------------------------------
|
| 2013 |
+
# Prepare steps for each argument. Note that all steps are counted in
|
| 2014 |
+
# bytes.
|
| 2015 |
+
num_steps = num_args + 1 + len(array_strides)
|
| 2016 |
+
steps = cgutils.alloca_once(
|
| 2017 |
+
builder, intp_t, size=context.get_constant(
|
| 2018 |
+
types.intp, num_steps), name="psteps")
|
| 2019 |
+
# First goes the step size for sched, which is 2 * num_dim
|
| 2020 |
+
builder.store(context.get_constant(types.intp, 2 * num_dim * sizeof_intp),
|
| 2021 |
+
steps)
|
| 2022 |
+
# The steps for all others are 0, except for reduction results.
|
| 2023 |
+
for i in range(num_args):
|
| 2024 |
+
# steps are strides from one thread to the next
|
| 2025 |
+
stepsize = zero
|
| 2026 |
+
|
| 2027 |
+
dst = builder.gep(steps, [context.get_constant(types.intp, 1 + i)])
|
| 2028 |
+
builder.store(stepsize, dst)
|
| 2029 |
+
for j in range(len(array_strides)):
|
| 2030 |
+
dst = builder.gep(
|
| 2031 |
+
steps, [
|
| 2032 |
+
context.get_constant(
|
| 2033 |
+
types.intp, 1 + num_args + j)])
|
| 2034 |
+
builder.store(array_strides[j], dst)
|
| 2035 |
+
|
| 2036 |
+
# ----------------------------------------------------------------------------
|
| 2037 |
+
# prepare data
|
| 2038 |
+
data = cgutils.get_null_value(byte_ptr_t)
|
| 2039 |
+
|
| 2040 |
+
fnty = llvmlite.ir.FunctionType(llvmlite.ir.VoidType(),
|
| 2041 |
+
[byte_ptr_ptr_t, intp_ptr_t,
|
| 2042 |
+
intp_ptr_t, byte_ptr_t])
|
| 2043 |
+
|
| 2044 |
+
fn = cgutils.get_or_insert_function(builder.module, fnty, wrapper_name)
|
| 2045 |
+
context.active_code_library.add_linking_library(info.library)
|
| 2046 |
+
|
| 2047 |
+
if config.DEBUG_ARRAY_OPT:
|
| 2048 |
+
cgutils.printf(builder, "before calling kernel %p\n", fn)
|
| 2049 |
+
builder.call(fn, [args, shapes, steps, data])
|
| 2050 |
+
if config.DEBUG_ARRAY_OPT:
|
| 2051 |
+
cgutils.printf(builder, "after calling kernel %p\n", fn)
|
| 2052 |
+
|
| 2053 |
+
builder.call(set_chunksize, [current_chunksize])
|
| 2054 |
+
|
| 2055 |
+
# Deallocate the schedule's memory.
|
| 2056 |
+
dealloc_sched_fnty = llvmlite.ir.FunctionType(llvmlite.ir.VoidType(), [sched_ptr_type])
|
| 2057 |
+
dealloc_sched_func = cgutils.get_or_insert_function(
|
| 2058 |
+
builder.module,
|
| 2059 |
+
dealloc_sched_fnty,
|
| 2060 |
+
name="deallocate_sched")
|
| 2061 |
+
builder.call(dealloc_sched_func, [builder.load(sched)])
|
| 2062 |
+
|
| 2063 |
+
for k, v in rv_to_arg_dict.items():
|
| 2064 |
+
arg, rv_arg = v
|
| 2065 |
+
only_elem_ptr = builder.gep(rv_arg, [context.get_constant(types.intp, 0)])
|
| 2066 |
+
builder.store(builder.load(only_elem_ptr), lowerer.getvar(k))
|
| 2067 |
+
|
| 2068 |
+
context.active_code_library.add_linking_library(cres.library)
|
shared/package-files/d1/d123e0b4c2614f680808b58cca0c140ba187494b2c8bcf8c604c7eb739c70882/zh_hk.msg
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# created by tools/loadICU.tcl -- do not edit
|
| 2 |
+
namespace eval ::tcl::clock {
|
| 3 |
+
::msgcat::mcset zh_HK DAYS_OF_WEEK_ABBREV [list \
|
| 4 |
+
"\u65e5"\
|
| 5 |
+
"\u4e00"\
|
| 6 |
+
"\u4e8c"\
|
| 7 |
+
"\u4e09"\
|
| 8 |
+
"\u56db"\
|
| 9 |
+
"\u4e94"\
|
| 10 |
+
"\u516d"]
|
| 11 |
+
::msgcat::mcset zh_HK MONTHS_ABBREV [list \
|
| 12 |
+
"1\u6708"\
|
| 13 |
+
"2\u6708"\
|
| 14 |
+
"3\u6708"\
|
| 15 |
+
"4\u6708"\
|
| 16 |
+
"5\u6708"\
|
| 17 |
+
"6\u6708"\
|
| 18 |
+
"7\u6708"\
|
| 19 |
+
"8\u6708"\
|
| 20 |
+
"9\u6708"\
|
| 21 |
+
"10\u6708"\
|
| 22 |
+
"11\u6708"\
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import tempfile
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def run_command(cmd):
|
| 8 |
+
print('Running %r:' % (cmd))
|
| 9 |
+
os.system(cmd)
|
| 10 |
+
print('------')
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def run():
|
| 14 |
+
_path = os.getcwd()
|
| 15 |
+
os.chdir(tempfile.gettempdir())
|
| 16 |
+
print('------')
|
| 17 |
+
print('os.name=%r' % (os.name))
|
| 18 |
+
print('------')
|
| 19 |
+
print('sys.platform=%r' % (sys.platform))
|
| 20 |
+
print('------')
|
| 21 |
+
print('sys.version:')
|
| 22 |
+
print(sys.version)
|
| 23 |
+
print('------')
|
| 24 |
+
print('sys.prefix:')
|
| 25 |
+
print(sys.prefix)
|
| 26 |
+
print('------')
|
| 27 |
+
print('sys.path=%r' % (':'.join(sys.path)))
|
| 28 |
+
print('------')
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
import numpy
|
| 32 |
+
has_newnumpy = 1
|
| 33 |
+
except ImportError as e:
|
| 34 |
+
print('Failed to import new numpy:', e)
|
| 35 |
+
has_newnumpy = 0
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
from numpy.f2py import f2py2e
|
| 39 |
+
has_f2py2e = 1
|
| 40 |
+
except ImportError as e:
|
| 41 |
+
print('Failed to import f2py2e:', e)
|
| 42 |
+
has_f2py2e = 0
|
| 43 |
+
|
| 44 |
+
try:
|
| 45 |
+
import numpy.distutils
|
| 46 |
+
has_numpy_distutils = 2
|
| 47 |
+
except ImportError:
|
| 48 |
+
try:
|
| 49 |
+
import numpy_distutils
|
| 50 |
+
has_numpy_distutils = 1
|
| 51 |
+
except ImportError as e:
|
| 52 |
+
print('Failed to import numpy_distutils:', e)
|
| 53 |
+
has_numpy_distutils = 0
|
| 54 |
+
|
| 55 |
+
if has_newnumpy:
|
| 56 |
+
try:
|
| 57 |
+
print('Found new numpy version %r in %s' %
|
| 58 |
+
(numpy.__version__, numpy.__file__))
|
| 59 |
+
except Exception as msg:
|
| 60 |
+
print('error:', msg)
|
| 61 |
+
print('------')
|
| 62 |
+
|
| 63 |
+
if has_f2py2e:
|
| 64 |
+
try:
|
| 65 |
+
print('Found f2py2e version %r in %s' %
|
| 66 |
+
(f2py2e.__version__.version, f2py2e.__file__))
|
| 67 |
+
except Exception as msg:
|
| 68 |
+
print('error:', msg)
|
| 69 |
+
print('------')
|
| 70 |
+
|
| 71 |
+
if has_numpy_distutils:
|
| 72 |
+
try:
|
| 73 |
+
if has_numpy_distutils == 2:
|
| 74 |
+
print('Found numpy.distutils version %r in %r' % (
|
| 75 |
+
numpy.distutils.__version__,
|
| 76 |
+
numpy.distutils.__file__))
|
| 77 |
+
else:
|
| 78 |
+
print('Found numpy_distutils version %r in %r' % (
|
| 79 |
+
numpy_distutils.numpy_distutils_version.numpy_distutils_version,
|
| 80 |
+
numpy_distutils.__file__))
|
| 81 |
+
print('------')
|
| 82 |
+
except Exception as msg:
|
| 83 |
+
print('error:', msg)
|
| 84 |
+
print('------')
|
| 85 |
+
try:
|
| 86 |
+
if has_numpy_distutils == 1:
|
| 87 |
+
print(
|
| 88 |
+
'Importing numpy_distutils.command.build_flib ...', end=' ')
|
| 89 |
+
import numpy_distutils.command.build_flib as build_flib
|
| 90 |
+
print('ok')
|
| 91 |
+
print('------')
|
| 92 |
+
try:
|
| 93 |
+
print(
|
| 94 |
+
'Checking availability of supported Fortran compilers:')
|
| 95 |
+
for compiler_class in build_flib.all_compilers:
|
| 96 |
+
compiler_class(verbose=1).is_available()
|
| 97 |
+
print('------')
|
| 98 |
+
except Exception as msg:
|
| 99 |
+
print('error:', msg)
|
| 100 |
+
print('------')
|
| 101 |
+
except Exception as msg:
|
| 102 |
+
print(
|
| 103 |
+
'error:', msg, '(ignore it, build_flib is obsolute for numpy.distutils 0.2.2 and up)')
|
| 104 |
+
print('------')
|
| 105 |
+
try:
|
| 106 |
+
if has_numpy_distutils == 2:
|
| 107 |
+
print('Importing numpy.distutils.fcompiler ...', end=' ')
|
| 108 |
+
import numpy.distutils.fcompiler as fcompiler
|
| 109 |
+
else:
|
| 110 |
+
print('Importing numpy_distutils.fcompiler ...', end=' ')
|
| 111 |
+
import numpy_distutils.fcompiler as fcompiler
|
| 112 |
+
print('ok')
|
| 113 |
+
print('------')
|
| 114 |
+
try:
|
| 115 |
+
print('Checking availability of supported Fortran compilers:')
|
| 116 |
+
fcompiler.show_fcompilers()
|
| 117 |
+
print('------')
|
| 118 |
+
except Exception as msg:
|
| 119 |
+
print('error:', msg)
|
| 120 |
+
print('------')
|
| 121 |
+
except Exception as msg:
|
| 122 |
+
print('error:', msg)
|
| 123 |
+
print('------')
|
| 124 |
+
try:
|
| 125 |
+
if has_numpy_distutils == 2:
|
| 126 |
+
print('Importing numpy.distutils.cpuinfo ...', end=' ')
|
| 127 |
+
from numpy.distutils.cpuinfo import cpuinfo
|
| 128 |
+
print('ok')
|
| 129 |
+
print('------')
|
| 130 |
+
else:
|
| 131 |
+
try:
|
| 132 |
+
print(
|
| 133 |
+
'Importing numpy_distutils.command.cpuinfo ...', end=' ')
|
| 134 |
+
from numpy_distutils.command.cpuinfo import cpuinfo
|
| 135 |
+
print('ok')
|
| 136 |
+
print('------')
|
| 137 |
+
except Exception as msg:
|
| 138 |
+
print('error:', msg, '(ignore it)')
|
| 139 |
+
print('Importing numpy_distutils.cpuinfo ...', end=' ')
|
| 140 |
+
from numpy_distutils.cpuinfo import cpuinfo
|
| 141 |
+
print('ok')
|
| 142 |
+
print('------')
|
| 143 |
+
cpu = cpuinfo()
|
| 144 |
+
print('CPU information:', end=' ')
|
| 145 |
+
for name in dir(cpuinfo):
|
| 146 |
+
if name[0] == '_' and name[1] != '_' and getattr(cpu, name[1:])():
|
| 147 |
+
print(name[1:], end=' ')
|
| 148 |
+
print('------')
|
| 149 |
+
except Exception as msg:
|
| 150 |
+
print('error:', msg)
|
| 151 |
+
print('------')
|
| 152 |
+
os.chdir(_path)
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
run()
|
shared/package-files/d1/d1284cb753ddb8fdcafa7db41e3c6159140c39128ffeae2bb08458796ce80d1d/options.h
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
// or more contributor license agreements. See the NOTICE file
|
| 3 |
+
// distributed with this work for additional information
|
| 4 |
+
// regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
// to you under the Apache License, Version 2.0 (the
|
| 6 |
+
// "License"); you may not use this file except in compliance
|
| 7 |
+
// with the License. You may obtain a copy of the License at
|
| 8 |
+
//
|
| 9 |
+
// http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
//
|
| 11 |
+
// Unless required by applicable law or agreed to in writing,
|
| 12 |
+
// software distributed under the License is distributed on an
|
| 13 |
+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
// KIND, either express or implied. See the License for the
|
| 15 |
+
// specific language governing permissions and limitations
|
| 16 |
+
// under the License.
|
| 17 |
+
|
| 18 |
+
#pragma once
|
| 19 |
+
|
| 20 |
+
#include <cstdint>
|
| 21 |
+
#include <memory>
|
| 22 |
+
#include <string>
|
| 23 |
+
#include <unordered_map>
|
| 24 |
+
#include <vector>
|
| 25 |
+
|
| 26 |
+
#include "arrow/csv/invalid_row.h"
|
| 27 |
+
#include "arrow/csv/type_fwd.h"
|
| 28 |
+
#include "arrow/io/interfaces.h"
|
| 29 |
+
#include "arrow/status.h"
|
| 30 |
+
#include "arrow/util/visibility.h"
|
| 31 |
+
|
| 32 |
+
namespace arrow {
|
| 33 |
+
|
| 34 |
+
class DataType;
|
| 35 |
+
class TimestampParser;
|
| 36 |
+
|
| 37 |
+
namespace csv {
|
| 38 |
+
|
| 39 |
+
// Silly workaround for https://github.com/michaeljones/breathe/issues/453
|
| 40 |
+
constexpr char kDefaultEscapeChar = '\\';
|
| 41 |
+
|
| 42 |
+
struct ARROW_EXPORT ParseOptions {
|
| 43 |
+
// Parsing options
|
| 44 |
+
|
| 45 |
+
/// Field delimiter
|
| 46 |
+
char delimiter = ',';
|
| 47 |
+
/// Whether quoting is used
|
| 48 |
+
bool quoting = true;
|
| 49 |
+
/// Quoting character (if `quoting` is true)
|
| 50 |
+
char quote_char = '"';
|
| 51 |
+
/// Whether a quote inside a value is double-quoted
|
| 52 |
+
bool double_quote = true;
|
| 53 |
+
/// Whether escaping is used
|
| 54 |
+
bool escaping = false;
|
| 55 |
+
/// Escaping character (if `escaping` is true)
|
| 56 |
+
char escape_char = kDefaultEscapeChar;
|
| 57 |
+
/// Whether values are allowed to contain CR (0x0d) and LF (0x0a) characters
|
| 58 |
+
bool newlines_in_values = false;
|
| 59 |
+
/// Whether empty lines are ignored. If false, an empty line represents
|
| 60 |
+
/// a single empty value (assuming a one-column CSV file).
|
| 61 |
+
bool ignore_empty_lines = true;
|
| 62 |
+
/// A handler function for rows which do not have the correct number of columns
|
| 63 |
+
InvalidRowHandler invalid_row_handler;
|
| 64 |
+
|
| 65 |
+
/// Create parsing options with default values
|
| 66 |
+
static ParseOptions Defaults();
|
| 67 |
+
|
| 68 |
+
/// \brief Test that all set options are valid
|
| 69 |
+
Status Validate() const;
|
| 70 |
+
};
|
| 71 |
+
|
| 72 |
+
struct ARROW_EXPORT ConvertOptions {
|
| 73 |
+
// Conversion options
|
| 74 |
+
|
| 75 |
+
/// Whether to check UTF8 validity of string columns
|
| 76 |
+
bool check_utf8 = true;
|
| 77 |
+
/// Optional per-column types (disabling type inference on those columns)
|
| 78 |
+
std::unordered_map<std::string, std::shared_ptr<DataType>> column_types;
|
| 79 |
+
/// Recognized spellings for null values
|
| 80 |
+
std::vector<std::string> null_values;
|
| 81 |
+
/// Recognized spellings for boolean true values
|
| 82 |
+
std::vector<std::string> true_values;
|
| 83 |
+
/// Recognized spellings for boolean false values
|
| 84 |
+
std::vector<std::string> false_values;
|
| 85 |
+
|
| 86 |
+
/// Whether string / binary columns can have null values.
|
| 87 |
+
///
|
| 88 |
+
/// If true, then strings in "null_values" are considered null for string columns.
|
| 89 |
+
/// If false, then all strings are valid string values.
|
| 90 |
+
bool strings_can_be_null = false;
|
| 91 |
+
|
| 92 |
+
/// Whether quoted values can be null.
|
| 93 |
+
///
|
| 94 |
+
/// If true, then strings in "null_values" are also considered null when they
|
| 95 |
+
/// appear quoted in the CSV file. Otherwise, quoted values are never considered null.
|
| 96 |
+
bool quoted_strings_can_be_null = true;
|
| 97 |
+
|
| 98 |
+
/// Whether to try to automatically dict-encode string / binary data.
|
| 99 |
+
/// If true, then when type inference detects a string or binary column,
|
| 100 |
+
/// it is dict-encoded up to `auto_dict_max_cardinality` distinct values
|
| 101 |
+
/// (per chunk), after which it switches to regular encoding.
|
| 102 |
+
///
|
| 103 |
+
/// This setting is ignored for non-inferred columns (those in `column_types`).
|
| 104 |
+
bool auto_dict_encode = false;
|
| 105 |
+
int32_t auto_dict_max_cardinality = 50;
|
| 106 |
+
|
| 107 |
+
/// Decimal point character for floating-point and decimal data
|
| 108 |
+
char decimal_point = '.';
|
| 109 |
+
|
| 110 |
+
// XXX Should we have a separate FilterOptions?
|
| 111 |
+
|
| 112 |
+
/// If non-empty, indicates the names of columns from the CSV file that should
|
| 113 |
+
/// be actually read and converted (in the vector's order).
|
| 114 |
+
/// Columns not in this vector will be ignored.
|
| 115 |
+
std::vector<std::string> include_columns;
|
| 116 |
+
/// If false, columns in `include_columns` but not in the CSV file will error out.
|
| 117 |
+
/// If true, columns in `include_columns` but not in the CSV file will produce
|
| 118 |
+
/// a column of nulls (whose type is selected using `column_types`,
|
| 119 |
+
/// or null by default)
|
| 120 |
+
/// This option is ignored if `include_columns` is empty.
|
| 121 |
+
bool include_missing_columns = false;
|
| 122 |
+
|
| 123 |
+
/// User-defined timestamp parsers, using the virtual parser interface in
|
| 124 |
+
/// arrow/util/value_parsing.h. More than one parser can be specified, and
|
| 125 |
+
/// the CSV conversion logic will try parsing values starting from the
|
| 126 |
+
/// beginning of this vector. If no parsers are specified, we use the default
|
| 127 |
+
/// built-in ISO-8601 parser.
|
| 128 |
+
std::vector<std::shared_ptr<TimestampParser>> timestamp_parsers;
|
| 129 |
+
|
| 130 |
+
/// Create conversion options with default values, including conventional
|
| 131 |
+
/// values for `null_values`, `true_values` and `false_values`
|
| 132 |
+
static ConvertOptions Defaults();
|
| 133 |
+
|
| 134 |
+
/// \brief Test that all set options are valid
|
| 135 |
+
Status Validate() const;
|
| 136 |
+
};
|
| 137 |
+
|
| 138 |
+
struct ARROW_EXPORT ReadOptions {
|
| 139 |
+
// Reader options
|
| 140 |
+
|
| 141 |
+
/// Whether to use the global CPU thread pool
|
| 142 |
+
bool use_threads = true;
|
| 143 |
+
|
| 144 |
+
/// \brief Block size we request from the IO layer.
|
| 145 |
+
///
|
| 146 |
+
/// This will determine multi-threading granularity as well as
|
| 147 |
+
/// the size of individual record batches.
|
| 148 |
+
/// Minimum valid value for block size is 1
|
| 149 |
+
int32_t block_size = 1 << 20; // 1 MB
|
| 150 |
+
|
| 151 |
+
/// Number of header rows to skip (not including the row of column names, if any)
|
| 152 |
+
int32_t skip_rows = 0;
|
| 153 |
+
|
| 154 |
+
/// Number of rows to skip after the column names are read, if any
|
| 155 |
+
int32_t skip_rows_after_names = 0;
|
| 156 |
+
|
| 157 |
+
/// Column names for the target table.
|
| 158 |
+
/// If empty, fall back on autogenerate_column_names.
|
| 159 |
+
std::vector<std::string> column_names;
|
| 160 |
+
|
| 161 |
+
/// Whether to autogenerate column names if `column_names` is empty.
|
| 162 |
+
/// If true, column names will be of the form "f0", "f1"...
|
| 163 |
+
/// If false, column names will be read from the first CSV row after `skip_rows`.
|
| 164 |
+
bool autogenerate_column_names = false;
|
| 165 |
+
|
| 166 |
+
/// Create read options with default values
|
| 167 |
+
static ReadOptions Defaults();
|
| 168 |
+
|
| 169 |
+
/// \brief Test that all set options are valid
|
| 170 |
+
Status Validate() const;
|
| 171 |
+
};
|
| 172 |
+
|
| 173 |
+
/// \brief Quoting style for CSV writing
|
| 174 |
+
enum class ARROW_EXPORT QuotingStyle {
|
| 175 |
+
/// Only enclose values in quotes which need them, because their CSV rendering can
|
| 176 |
+
/// contain quotes itself (e.g. strings or binary values)
|
| 177 |
+
Needed,
|
| 178 |
+
/// Enclose all valid values in quotes. Nulls are not quoted. May cause readers to
|
| 179 |
+
/// interpret all values as strings if schema is inferred.
|
| 180 |
+
AllValid,
|
| 181 |
+
/// Do not enclose any values in quotes. Prevents values from containing quotes ("),
|
| 182 |
+
/// cell delimiters (,) or line endings (\\r, \\n), (following RFC4180). If values
|
| 183 |
+
/// contain these characters, an error is caused when attempting to write.
|
| 184 |
+
None
|
| 185 |
+
};
|
| 186 |
+
|
| 187 |
+
struct ARROW_EXPORT WriteOptions {
|
| 188 |
+
/// Whether to write an initial header line with column names
|
| 189 |
+
bool include_header = true;
|
| 190 |
+
|
| 191 |
+
/// \brief Maximum number of rows processed at a time
|
| 192 |
+
///
|
| 193 |
+
/// The CSV writer converts and writes data in batches of N rows.
|
| 194 |
+
/// This number can impact performance.
|
| 195 |
+
int32_t batch_size = 1024;
|
| 196 |
+
|
| 197 |
+
/// Field delimiter
|
| 198 |
+
char delimiter = ',';
|
| 199 |
+
|
| 200 |
+
/// \brief The string to write for null values. Quotes are not allowed in this string.
|
| 201 |
+
std::string null_string;
|
| 202 |
+
|
| 203 |
+
/// \brief IO context for writing.
|
| 204 |
+
io::IOContext io_context;
|
| 205 |
+
|
| 206 |
+
/// \brief The end of line character to use for ending rows
|
| 207 |
+
std::string eol = "\n";
|
| 208 |
+
|
| 209 |
+
/// \brief Quoting style
|
| 210 |
+
QuotingStyle quoting_style = QuotingStyle::Needed;
|
| 211 |
+
|
| 212 |
+
/// \brief Quoting style of header
|
| 213 |
+
///
|
| 214 |
+
/// Note that `QuotingStyle::Needed` and `QuotingStyle::AllValid` have the same
|
| 215 |
+
/// effect of quoting all column names.
|
| 216 |
+
QuotingStyle quoting_header = QuotingStyle::Needed;
|
| 217 |
+
|
| 218 |
+
/// Create write options with default values
|
| 219 |
+
static WriteOptions Defaults();
|
| 220 |
+
|
| 221 |
+
/// \brief Test that all set options are valid
|
| 222 |
+
Status Validate() const;
|
| 223 |
+
};
|
| 224 |
+
|
| 225 |
+
} // namespace csv
|
| 226 |
+
} // namespace arrow
|
shared/package-files/d1/d12a142fcd22c0b3c7d8cf924e86421e5fde381cf52c77bf10b098e5cdcafef7/tmux-direct
ADDED
|
Binary file (3.45 kB). View file
|
|
|
shared/package-files/d1/d12ee45a23c42919a2d224bc250dcae530a1cd2a59361026d668f25d081a513f/_grid_sampler_2d_cpu_fallback_backward_compositeimplicitautograd_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 compositeimplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor> _grid_sampler_2d_cpu_fallback_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners);
|
| 21 |
+
|
| 22 |
+
} // namespace compositeimplicitautograd
|
| 23 |
+
} // namespace at
|
shared/package-files/d1/d132f83197095d4a28f6a03bbaed2f2efede1eb5d17ab566c9f8bb3b5e3d213c/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CUDA Driver
|
| 2 |
+
|
| 3 |
+
- Driver API binding
|
| 4 |
+
- NVVM API binding
|
| 5 |
+
- Device array implementation
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
from numba.core import config
|
| 9 |
+
assert not config.ENABLE_CUDASIM, 'Cannot use real driver API with simulator'
|
shared/package-files/d1/d136f12171747ea2f89913a16f452fafac4c411543f62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|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <atomic>
|
| 4 |
+
#include <memory>
|
| 5 |
+
|
| 6 |
+
#include <torch/csrc/jit/ir/ir.h>
|
| 7 |
+
#include <torch/csrc/jit/python/update_graph_executor_opt.h>
|
| 8 |
+
#include <torch/csrc/jit/runtime/argument_spec.h>
|
| 9 |
+
#include <torch/csrc/jit/runtime/interpreter.h>
|
| 10 |
+
#include <torch/csrc/jit/runtime/variable_tensor_list.h>
|
| 11 |
+
|
| 12 |
+
C10_DECLARE_bool(torch_jit_enable_new_executor);
|
| 13 |
+
|
| 14 |
+
C10_DECLARE_bool(torch_jit_execution_plan_reuse_code_graph);
|
| 15 |
+
|
| 16 |
+
namespace torch::jit {
|
| 17 |
+
struct GraphExecutorState;
|
| 18 |
+
struct Code;
|
| 19 |
+
|
| 20 |
+
enum ExecutorExecutionMode {
|
| 21 |
+
SIMPLE,
|
| 22 |
+
PROFILING,
|
| 23 |
+
};
|
| 24 |
+
|
| 25 |
+
struct ExecutionPlan {
|
| 26 |
+
ExecutionPlan() = default;
|
| 27 |
+
ExecutionPlan(std::shared_ptr<Graph> graph, std::string function_name)
|
| 28 |
+
: code(graph, std::move(function_name)),
|
| 29 |
+
graph(
|
| 30 |
+
FLAGS_torch_jit_execution_plan_reuse_code_graph
|
| 31 |
+
? code.graph()
|
| 32 |
+
: std::move(graph)) {}
|
| 33 |
+
|
| 34 |
+
operator bool() const {
|
| 35 |
+
return static_cast<bool>(graph);
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
Code code;
|
| 39 |
+
std::shared_ptr<Graph> graph;
|
| 40 |
+
};
|
| 41 |
+
|
| 42 |
+
// Notice that those structs don't manage lifetime of their members.
|
| 43 |
+
// They are only valid only right after you call getDebugState() and should
|
| 44 |
+
// never be used again once another GraphExecutor function is called.
|
| 45 |
+
|
| 46 |
+
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
|
| 47 |
+
struct GraphExecutorState {
|
| 48 |
+
const Graph* graph = nullptr;
|
| 49 |
+
ExecutionPlan fallback; // XXX: members of this field are optional
|
| 50 |
+
std::unordered_map<ArgumentSpec, ExecutionPlan> execution_plans;
|
| 51 |
+
};
|
| 52 |
+
|
| 53 |
+
struct TORCH_API EnableProfilingGuard {
|
| 54 |
+
EnableProfilingGuard();
|
| 55 |
+
~EnableProfilingGuard();
|
| 56 |
+
|
| 57 |
+
private:
|
| 58 |
+
bool old_executor_mode = false;
|
| 59 |
+
bool old_get_optimize = false;
|
| 60 |
+
};
|
| 61 |
+
|
| 62 |
+
struct GraphExecutorImplBase;
|
| 63 |
+
struct TORCH_API GraphExecutor {
|
| 64 |
+
GraphExecutor() = default;
|
| 65 |
+
GraphExecutor(const std::shared_ptr<Graph>& graph, std::string function_name);
|
| 66 |
+
|
| 67 |
+
GraphExecutor(
|
| 68 |
+
const std::shared_ptr<Graph>& graph,
|
| 69 |
+
std::string function_name,
|
| 70 |
+
ExecutorExecutionMode executor_mode);
|
| 71 |
+
|
| 72 |
+
void run(Stack& inputs);
|
| 73 |
+
c10::intrusive_ptr<Future> runAsync(
|
| 74 |
+
Stack& stack,
|
| 75 |
+
TaskLauncher taskLauncher = at::launch);
|
| 76 |
+
|
| 77 |
+
// `remaining_bailout_depth` stands for the maximum number of profiled and
|
| 78 |
+
// specialized recompilations allowed for the current `GraphExecutor`. if
|
| 79 |
+
// remaining_bailout_depth is equal to 0, `GraphExecutor` won't perform any
|
| 80 |
+
// profiling and specialization. This is also equivalent to the
|
| 81 |
+
// SIMPLE_EXECUTOR mode. if remaining_bailout_depth is greater than 0,
|
| 82 |
+
// `GraphExecutor` will profile and specialize its input graph based on the
|
| 83 |
+
// profiled information whenever a bailout check is failed/triggered, a new
|
| 84 |
+
// `GraphExecutor` will be created. This new `GraphExecutor`'s
|
| 85 |
+
// remaining_bailout_depth will be reduced by 1.
|
| 86 |
+
// If no bailout depth is passed, the depth will be initialized from the
|
| 87 |
+
// current global fusion strategy settings.
|
| 88 |
+
const ExecutionPlan& getPlanFor(
|
| 89 |
+
Stack& inputs,
|
| 90 |
+
c10::optional<size_t> remaining_bailout_depth = c10::nullopt);
|
| 91 |
+
GraphExecutorState getDebugState();
|
| 92 |
+
|
| 93 |
+
void debugFlushCompilationCache();
|
| 94 |
+
|
| 95 |
+
bool isOptimized() const;
|
| 96 |
+
|
| 97 |
+
private:
|
| 98 |
+
std::shared_ptr<GraphExecutorImplBase> pImpl;
|
| 99 |
+
};
|
| 100 |
+
|
| 101 |
+
TORCH_API Node* replaceBlockWithFallbackGraph(
|
| 102 |
+
Block* b,
|
| 103 |
+
ArrayRef<Value*> inputs);
|
| 104 |
+
|
| 105 |
+
// These passes need to run before it is valid to pass to the interpreter
|
| 106 |
+
// regardless of whether sizes have been specialized or not.
|
| 107 |
+
TORCH_API void runRequiredPasses(const std::shared_ptr<Graph>& g);
|
| 108 |
+
|
| 109 |
+
TORCH_API void debugSetFusionGroupInlining(bool state);
|
| 110 |
+
TORCH_API bool getFusionGroupInlining();
|
| 111 |
+
|
| 112 |
+
TORCH_API void debugSetAutodiffSubgraphInlining(bool state);
|
| 113 |
+
TORCH_API std::shared_ptr<Graph> lastExecutedOptimizedGraph();
|
| 114 |
+
|
| 115 |
+
TORCH_API std::atomic<bool>& getProfilingMode();
|
| 116 |
+
TORCH_API std::atomic<bool>& getExecutorMode();
|
| 117 |
+
TORCH_API std::atomic<size_t>& getNumProfiledRuns();
|
| 118 |
+
TORCH_API size_t getBailoutDepth();
|
| 119 |
+
TORCH_API bool IsNewExecutorEnabled();
|
| 120 |
+
|
| 121 |
+
struct TORCH_API GraphOptimizerEnabledGuard {
|
| 122 |
+
GraphOptimizerEnabledGuard(bool state)
|
| 123 |
+
: old_state_(getGraphExecutorOptimize()) {
|
| 124 |
+
setGraphExecutorOptimize(state);
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
~GraphOptimizerEnabledGuard() {
|
| 128 |
+
setGraphExecutorOptimize(old_state_);
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
bool old_state_;
|
| 132 |
+
};
|
| 133 |
+
|
| 134 |
+
namespace detail {
|
| 135 |
+
|
| 136 |
+
GraphExecutor* getGradExecutor(Operation& op);
|
| 137 |
+
|
| 138 |
+
GraphExecutor* getDifferentiableGraphOpExecutor(Operation& op);
|
| 139 |
+
|
| 140 |
+
// for debugging information we expose a way to get the last actually
|
| 141 |
+
// run graph. Previous approaches allowed querying the GraphExecutor
|
| 142 |
+
// for what graph it would run in certain circumstances (graphFor), but
|
| 143 |
+
// this is fragile because we sometimes change how these decisions are made.
|
| 144 |
+
// This interface still allows our tests to look at optimized graphs, but
|
| 145 |
+
// with less plumbing.
|
| 146 |
+
} // namespace detail
|
| 147 |
+
|
| 148 |
+
} // namespace torch::jit
|
shared/package-files/d1/d13da4530fb2a70d9d66ee96508e6aa0de35f1c0e60a32e52b71b847cec9d292/quantize_pt2e.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
from torch.fx import Node
|
| 4 |
+
|
| 5 |
+
from .pt2e.prepare import prepare
|
| 6 |
+
from .pt2e.qat_utils import (
|
| 7 |
+
_fuse_conv_bn_qat,
|
| 8 |
+
_fold_conv_bn_qat,
|
| 9 |
+
)
|
| 10 |
+
from .pt2e.utils import (
|
| 11 |
+
_get_node_name_to_scope,
|
| 12 |
+
_fuse_conv_bn_,
|
| 13 |
+
_disallow_eval_train,
|
| 14 |
+
)
|
| 15 |
+
from .pt2e.representation import reference_representation_rewrite
|
| 16 |
+
from .quantize_fx import _convert_to_reference_decomposed_fx
|
| 17 |
+
from torch.ao.quantization.quantizer import ( # noqa: F401
|
| 18 |
+
Quantizer,
|
| 19 |
+
QuantizationSpecBase,
|
| 20 |
+
QuantizationSpec,
|
| 21 |
+
FixedQParamsQuantizationSpec,
|
| 22 |
+
SharedQuantizationSpec,
|
| 23 |
+
DerivedQuantizationSpec,
|
| 24 |
+
QuantizationAnnotation,
|
| 25 |
+
)
|
| 26 |
+
from torch.fx.passes.infra.pass_manager import PassManager
|
| 27 |
+
from torch.ao.quantization.pt2e.duplicate_dq_pass import DuplicateDQPass
|
| 28 |
+
from torch.ao.quantization.pt2e.port_metadata_pass import PortNodeMetaForQDQ
|
| 29 |
+
from torch._inductor.constant_folding import constant_fold
|
| 30 |
+
|
| 31 |
+
__all__ = [
|
| 32 |
+
"prepare_pt2e",
|
| 33 |
+
"prepare_qat_pt2e",
|
| 34 |
+
"convert_pt2e",
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def prepare_pt2e(
|
| 39 |
+
model: GraphModule,
|
| 40 |
+
quantizer: Quantizer,
|
| 41 |
+
) -> GraphModule:
|
| 42 |
+
"""Prepare a model for post training quantization
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
* `model` (torch.fx.GraphModule): a model captured by `torch.export` API
|
| 46 |
+
in the short term we are using `torch._export.capture_pre_autograd_graph`,
|
| 47 |
+
in the long term we'll migrate to some `torch.export` API
|
| 48 |
+
* `quantizer`: A backend specific quantizer that conveys how user want the
|
| 49 |
+
model to be quantized. Tutorial for how to write a quantizer can be found here:
|
| 50 |
+
https://pytorch.org/tutorials/prototype/pt2e_quantizer.html
|
| 51 |
+
|
| 52 |
+
Return:
|
| 53 |
+
A GraphModule with observer (based on quantizer annotation), ready for calibration
|
| 54 |
+
|
| 55 |
+
Example::
|
| 56 |
+
|
| 57 |
+
import torch
|
| 58 |
+
from torch.ao.quantization.quantize_pt2e import prepare_pt2e
|
| 59 |
+
from torch._export import capture_pre_autograd_graph
|
| 60 |
+
from torch.ao.quantization.quantizer import (
|
| 61 |
+
XNNPACKQuantizer,
|
| 62 |
+
get_symmetric_quantization_config,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
class M(torch.nn.Module):
|
| 66 |
+
def __init__(self):
|
| 67 |
+
super().__init__()
|
| 68 |
+
self.linear = torch.nn.Linear(5, 10)
|
| 69 |
+
|
| 70 |
+
def forward(self, x):
|
| 71 |
+
return self.linear(x)
|
| 72 |
+
|
| 73 |
+
# initialize a floating point model
|
| 74 |
+
float_model = M().eval()
|
| 75 |
+
|
| 76 |
+
# define calibration function
|
| 77 |
+
def calibrate(model, data_loader):
|
| 78 |
+
model.eval()
|
| 79 |
+
with torch.no_grad():
|
| 80 |
+
for image, target in data_loader:
|
| 81 |
+
model(image)
|
| 82 |
+
|
| 83 |
+
# Step 1. program capture
|
| 84 |
+
# NOTE: this API will be updated to torch.export API in the future, but the captured
|
| 85 |
+
# result shoud mostly stay the same
|
| 86 |
+
m = capture_pre_autograd_graph(m, *example_inputs)
|
| 87 |
+
# we get a model with aten ops
|
| 88 |
+
|
| 89 |
+
# Step 2. quantization
|
| 90 |
+
# backend developer will write their own Quantizer and expose methods to allow
|
| 91 |
+
# users to express how they
|
| 92 |
+
# want the model to be quantized
|
| 93 |
+
quantizer = XNNPACKQuantizer().set_global(get_symmetric_quantization_config())
|
| 94 |
+
m = prepare_pt2e(m, quantizer)
|
| 95 |
+
|
| 96 |
+
# run calibration
|
| 97 |
+
# calibrate(m, sample_inference_data)
|
| 98 |
+
"""
|
| 99 |
+
torch._C._log_api_usage_once("quantization_api.quantize_pt2e.prepare_pt2e")
|
| 100 |
+
original_graph_meta = model.meta
|
| 101 |
+
node_name_to_scope = _get_node_name_to_scope(model)
|
| 102 |
+
# TODO: check qconfig_mapping to make sure conv and bn are both configured
|
| 103 |
+
# to be quantized before fusion
|
| 104 |
+
# TODO: (maybe) rewrite this with subgraph_rewriter
|
| 105 |
+
_fuse_conv_bn_(model)
|
| 106 |
+
quantizer.transform_for_annotation(model)
|
| 107 |
+
quantizer.annotate(model)
|
| 108 |
+
quantizer.validate(model)
|
| 109 |
+
model = prepare(model, node_name_to_scope, is_qat=False)
|
| 110 |
+
model.meta.update(original_graph_meta)
|
| 111 |
+
model = _disallow_eval_train(model)
|
| 112 |
+
return model
|
| 113 |
+
|
| 114 |
+
def prepare_qat_pt2e(
|
| 115 |
+
model: GraphModule,
|
| 116 |
+
quantizer: Quantizer,
|
| 117 |
+
) -> GraphModule:
|
| 118 |
+
"""Prepare a model for quantization aware training
|
| 119 |
+
|
| 120 |
+
Args:
|
| 121 |
+
* `model` (torch.fx.GraphModule): see :func:`~torch.ao.quantization.quantize_pt2e.prepare_pt2e`
|
| 122 |
+
* `quantizer`: see :func:`~torch.ao.quantization.quantize_pt2e.prepare_pt2e`
|
| 123 |
+
|
| 124 |
+
Return:
|
| 125 |
+
A GraphModule with fake quant modules (based on quantizer annotation), ready for
|
| 126 |
+
quantization aware training
|
| 127 |
+
|
| 128 |
+
Example::
|
| 129 |
+
import torch
|
| 130 |
+
from torch.ao.quantization.quantize_pt2e import prepare_qat_pt2e
|
| 131 |
+
from torch._export import capture_pre_autograd_graph
|
| 132 |
+
from torch.ao.quantization.quantizer import (
|
| 133 |
+
XNNPACKQuantizer,
|
| 134 |
+
get_symmetric_quantization_config,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
class M(torch.nn.Module):
|
| 138 |
+
def __init__(self):
|
| 139 |
+
super().__init__()
|
| 140 |
+
self.linear = torch.nn.Linear(5, 10)
|
| 141 |
+
|
| 142 |
+
def forward(self, x):
|
| 143 |
+
return self.linear(x)
|
| 144 |
+
|
| 145 |
+
# initialize a floating point model
|
| 146 |
+
float_model = M().eval()
|
| 147 |
+
|
| 148 |
+
# define the training loop for quantization aware training
|
| 149 |
+
def train_loop(model, train_data):
|
| 150 |
+
model.train()
|
| 151 |
+
for image, target in data_loader:
|
| 152 |
+
...
|
| 153 |
+
|
| 154 |
+
# Step 1. program capture
|
| 155 |
+
# NOTE: this API will be updated to torch.export API in the future, but the captured
|
| 156 |
+
# result shoud mostly stay the same
|
| 157 |
+
m = capture_pre_autograd_graph(m, *example_inputs)
|
| 158 |
+
# we get a model with aten ops
|
| 159 |
+
|
| 160 |
+
# Step 2. quantization
|
| 161 |
+
# backend developer will write their own Quantizer and expose methods to allow
|
| 162 |
+
# users to express how they
|
| 163 |
+
# want the model to be quantized
|
| 164 |
+
quantizer = XNNPACKQuantizer().set_global(get_symmetric_quantization_config())
|
| 165 |
+
m = prepare_qat_pt2e(m, quantizer)
|
| 166 |
+
|
| 167 |
+
# run quantization aware training
|
| 168 |
+
train_loop(prepared_model, train_loop)
|
| 169 |
+
|
| 170 |
+
"""
|
| 171 |
+
torch._C._log_api_usage_once("quantization_api.quantize_pt2e.prepare_qat_pt2e")
|
| 172 |
+
original_graph_meta = model.meta
|
| 173 |
+
node_name_to_scope = _get_node_name_to_scope(model)
|
| 174 |
+
quantizer.transform_for_annotation(model)
|
| 175 |
+
quantizer.annotate(model)
|
| 176 |
+
quantizer.validate(model)
|
| 177 |
+
# Perform fusion after annotate to avoid quantizing ops in the new
|
| 178 |
+
# subgraph that don't need to be quantized
|
| 179 |
+
# TODO: only fuse if conv and bn are both configured to be quantized
|
| 180 |
+
_fuse_conv_bn_qat(model)
|
| 181 |
+
model = prepare(model, node_name_to_scope, is_qat=True)
|
| 182 |
+
model.meta.update(original_graph_meta)
|
| 183 |
+
model = _disallow_eval_train(model)
|
| 184 |
+
return model
|
| 185 |
+
|
| 186 |
+
_QUANT_OPS = [
|
| 187 |
+
torch.ops.quantized_decomposed.quantize_per_tensor.default,
|
| 188 |
+
torch.ops.quantized_decomposed.quantize_per_tensor.tensor,
|
| 189 |
+
torch.ops.quantized_decomposed.quantize_per_channel.default,
|
| 190 |
+
]
|
| 191 |
+
def _quant_node_constraint(n: Node) -> bool:
|
| 192 |
+
"""If there is any pure ops between get_attr and quantize op they will be const propagated
|
| 193 |
+
e.g. get_attr(weight) -> transpose -> quantize -> dequantize*
|
| 194 |
+
(Note: dequantize op is not going to be constant propagated)
|
| 195 |
+
|
| 196 |
+
This filter is added because we don't want to constant fold the things that are not
|
| 197 |
+
related to quantization
|
| 198 |
+
"""
|
| 199 |
+
return n.op == "call_function" and n.target in _QUANT_OPS
|
| 200 |
+
|
| 201 |
+
def convert_pt2e(
|
| 202 |
+
model: GraphModule,
|
| 203 |
+
use_reference_representation: bool = False,
|
| 204 |
+
fold_quantize: bool = True,
|
| 205 |
+
) -> GraphModule:
|
| 206 |
+
"""Convert a calibrated/trained model to a quantized model
|
| 207 |
+
|
| 208 |
+
Args:
|
| 209 |
+
* `model` (torch.fx.GraphModule): calibrated/trained model
|
| 210 |
+
* `use_reference_representation` (bool): boolean flag to indicate whether to produce referece representation or not
|
| 211 |
+
* `fold_quantize` (bool): boolean flag for whether fold the quantize op or not
|
| 212 |
+
|
| 213 |
+
Returns:
|
| 214 |
+
quantized model, either in q/dq representation or reference representation
|
| 215 |
+
|
| 216 |
+
Example::
|
| 217 |
+
|
| 218 |
+
# prepared_model: the model produced by `prepare_pt2e`/`prepare_qat_pt2e` and calibration/training
|
| 219 |
+
# `convert_pt2e` produces a quantized model that represents quantized computation with
|
| 220 |
+
# quantize dequantize ops and fp32 ops by default.
|
| 221 |
+
# Please refer to
|
| 222 |
+
# https://pytorch.org/tutorials/prototype/pt2e_quant_ptq_static.html#convert-the-calibrated-model-to-a-quantized-model
|
| 223 |
+
# for detailed explanation of output quantized model
|
| 224 |
+
quantized_model = convert_pt2e(prepared_model)
|
| 225 |
+
|
| 226 |
+
""" # flake8: noqa
|
| 227 |
+
torch._C._log_api_usage_once("quantization_api.quantize_pt2e.convert_pt2e")
|
| 228 |
+
if not isinstance(use_reference_representation, bool):
|
| 229 |
+
raise ValueError(
|
| 230 |
+
"Unexpected argument type for `use_reference_representation`, "
|
| 231 |
+
f"please make sure you intend to pass argument {use_reference_representation} to convert_pt2e")
|
| 232 |
+
original_graph_meta = model.meta
|
| 233 |
+
model = _convert_to_reference_decomposed_fx(model)
|
| 234 |
+
model = _fold_conv_bn_qat(model)
|
| 235 |
+
|
| 236 |
+
pm = PassManager([DuplicateDQPass()])
|
| 237 |
+
model = pm(model).graph_module
|
| 238 |
+
|
| 239 |
+
pm = PassManager([PortNodeMetaForQDQ()])
|
| 240 |
+
model = pm(model).graph_module
|
| 241 |
+
|
| 242 |
+
if fold_quantize:
|
| 243 |
+
constant_fold(model, _quant_node_constraint)
|
| 244 |
+
|
| 245 |
+
if use_reference_representation:
|
| 246 |
+
model = reference_representation_rewrite(model)
|
| 247 |
+
|
| 248 |
+
model.meta.update(original_graph_meta)
|
| 249 |
+
model = _disallow_eval_train(model)
|
| 250 |
+
return model
|
shared/package-files/d1/d143659ddde1ce57f6734122c0b24586d4f256ecb2932c02d13aa206ba4d9501/gnome-rh62
ADDED
|
Binary file (1.52 kB). View file
|
|
|
shared/package-files/d1/d146208ff5159c304faa373716ee1096567fca252e416929c84c25fb34dd096f/__init__.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
shared/package-files/d1/d148cd156ed2cad8f5b77d500fdf5e6dfafe6a5ecd982a5684a50ecaaf55ccaf/_cm_multivar.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 5 |
+
import matplotlib as mpl
|
| 6 |
+
_LUTSIZE = mpl.rcParams['image.lut']
|
| 7 |
+
|
| 8 |
+
_2VarAddA0_data = [[0.000, 0.000, 0.000],
|
| 9 |
+
[0.020, 0.026, 0.031],
|
| 10 |
+
[0.049, 0.068, 0.085],
|
| 11 |
+
[0.075, 0.107, 0.135],
|
| 12 |
+
[0.097, 0.144, 0.183],
|
| 13 |
+
[0.116, 0.178, 0.231],
|
| 14 |
+
[0.133, 0.212, 0.279],
|
| 15 |
+
[0.148, 0.244, 0.326],
|
| 16 |
+
[0.161, 0.276, 0.374],
|
| 17 |
+
[0.173, 0.308, 0.422],
|
| 18 |
+
[0.182, 0.339, 0.471],
|
| 19 |
+
[0.190, 0.370, 0.521],
|
| 20 |
+
[0.197, 0.400, 0.572],
|
| 21 |
+
[0.201, 0.431, 0.623],
|
| 22 |
+
[0.204, 0.461, 0.675],
|
| 23 |
+
[0.204, 0.491, 0.728],
|
| 24 |
+
[0.202, 0.520, 0.783],
|
| 25 |
+
[0.197, 0.549, 0.838],
|
| 26 |
+
[0.187, 0.577, 0.895]]
|
| 27 |
+
|
| 28 |
+
_2VarAddA1_data = [[0.000, 0.000, 0.000],
|
| 29 |
+
[0.030, 0.023, 0.018],
|
| 30 |
+
[0.079, 0.060, 0.043],
|
| 31 |
+
[0.125, 0.093, 0.065],
|
| 32 |
+
[0.170, 0.123, 0.083],
|
| 33 |
+
[0.213, 0.151, 0.098],
|
| 34 |
+
[0.255, 0.177, 0.110],
|
| 35 |
+
[0.298, 0.202, 0.120],
|
| 36 |
+
[0.341, 0.226, 0.128],
|
| 37 |
+
[0.384, 0.249, 0.134],
|
| 38 |
+
[0.427, 0.271, 0.138],
|
| 39 |
+
[0.472, 0.292, 0.141],
|
| 40 |
+
[0.517, 0.313, 0.142],
|
| 41 |
+
[0.563, 0.333, 0.141],
|
| 42 |
+
[0.610, 0.353, 0.139],
|
| 43 |
+
[0.658, 0.372, 0.134],
|
| 44 |
+
[0.708, 0.390, 0.127],
|
| 45 |
+
[0.759, 0.407, 0.118],
|
| 46 |
+
[0.813, 0.423, 0.105]]
|
| 47 |
+
|
| 48 |
+
_2VarSubA0_data = [[1.000, 1.000, 1.000],
|
| 49 |
+
[0.959, 0.973, 0.986],
|
| 50 |
+
[0.916, 0.948, 0.974],
|
| 51 |
+
[0.874, 0.923, 0.965],
|
| 52 |
+
[0.832, 0.899, 0.956],
|
| 53 |
+
[0.790, 0.875, 0.948],
|
| 54 |
+
[0.748, 0.852, 0.940],
|
| 55 |
+
[0.707, 0.829, 0.934],
|
| 56 |
+
[0.665, 0.806, 0.927],
|
| 57 |
+
[0.624, 0.784, 0.921],
|
| 58 |
+
[0.583, 0.762, 0.916],
|
| 59 |
+
[0.541, 0.740, 0.910],
|
| 60 |
+
[0.500, 0.718, 0.905],
|
| 61 |
+
[0.457, 0.697, 0.901],
|
| 62 |
+
[0.414, 0.675, 0.896],
|
| 63 |
+
[0.369, 0.652, 0.892],
|
| 64 |
+
[0.320, 0.629, 0.888],
|
| 65 |
+
[0.266, 0.604, 0.884],
|
| 66 |
+
[0.199, 0.574, 0.881]]
|
| 67 |
+
|
| 68 |
+
_2VarSubA1_data = [[1.000, 1.000, 1.000],
|
| 69 |
+
[0.982, 0.967, 0.955],
|
| 70 |
+
[0.966, 0.935, 0.908],
|
| 71 |
+
[0.951, 0.902, 0.860],
|
| 72 |
+
[0.937, 0.870, 0.813],
|
| 73 |
+
[0.923, 0.838, 0.765],
|
| 74 |
+
[0.910, 0.807, 0.718],
|
| 75 |
+
[0.898, 0.776, 0.671],
|
| 76 |
+
[0.886, 0.745, 0.624],
|
| 77 |
+
[0.874, 0.714, 0.577],
|
| 78 |
+
[0.862, 0.683, 0.530],
|
| 79 |
+
[0.851, 0.653, 0.483],
|
| 80 |
+
[0.841, 0.622, 0.435],
|
| 81 |
+
[0.831, 0.592, 0.388],
|
| 82 |
+
[0.822, 0.561, 0.340],
|
| 83 |
+
[0.813, 0.530, 0.290],
|
| 84 |
+
[0.806, 0.498, 0.239],
|
| 85 |
+
[0.802, 0.464, 0.184],
|
| 86 |
+
[0.801, 0.426, 0.119]]
|
| 87 |
+
|
| 88 |
+
_3VarAddA0_data = [[0.000, 0.000, 0.000],
|
| 89 |
+
[0.018, 0.023, 0.028],
|
| 90 |
+
[0.040, 0.056, 0.071],
|
| 91 |
+
[0.059, 0.087, 0.110],
|
| 92 |
+
[0.074, 0.114, 0.147],
|
| 93 |
+
[0.086, 0.139, 0.183],
|
| 94 |
+
[0.095, 0.163, 0.219],
|
| 95 |
+
[0.101, 0.187, 0.255],
|
| 96 |
+
[0.105, 0.209, 0.290],
|
| 97 |
+
[0.107, 0.230, 0.326],
|
| 98 |
+
[0.105, 0.251, 0.362],
|
| 99 |
+
[0.101, 0.271, 0.398],
|
| 100 |
+
[0.091, 0.291, 0.434],
|
| 101 |
+
[0.075, 0.309, 0.471],
|
| 102 |
+
[0.046, 0.325, 0.507],
|
| 103 |
+
[0.021, 0.341, 0.546],
|
| 104 |
+
[0.021, 0.363, 0.584],
|
| 105 |
+
[0.022, 0.385, 0.622],
|
| 106 |
+
[0.023, 0.408, 0.661]]
|
| 107 |
+
|
| 108 |
+
_3VarAddA1_data = [[0.000, 0.000, 0.000],
|
| 109 |
+
[0.020, 0.024, 0.016],
|
| 110 |
+
[0.047, 0.058, 0.034],
|
| 111 |
+
[0.072, 0.088, 0.048],
|
| 112 |
+
[0.093, 0.116, 0.059],
|
| 113 |
+
[0.113, 0.142, 0.067],
|
| 114 |
+
[0.131, 0.167, 0.071],
|
| 115 |
+
[0.149, 0.190, 0.074],
|
| 116 |
+
[0.166, 0.213, 0.074],
|
| 117 |
+
[0.182, 0.235, 0.072],
|
| 118 |
+
[0.198, 0.256, 0.068],
|
| 119 |
+
[0.215, 0.276, 0.061],
|
| 120 |
+
[0.232, 0.296, 0.051],
|
| 121 |
+
[0.249, 0.314, 0.037],
|
| 122 |
+
[0.270, 0.330, 0.018],
|
| 123 |
+
[0.288, 0.347, 0.000],
|
| 124 |
+
[0.302, 0.369, 0.000],
|
| 125 |
+
[0.315, 0.391, 0.000],
|
| 126 |
+
[0.328, 0.414, 0.000]]
|
| 127 |
+
|
| 128 |
+
_3VarAddA2_data = [[0.000, 0.000, 0.000],
|
| 129 |
+
[0.029, 0.020, 0.023],
|
| 130 |
+
[0.072, 0.045, 0.055],
|
| 131 |
+
[0.111, 0.067, 0.084],
|
| 132 |
+
[0.148, 0.085, 0.109],
|
| 133 |
+
[0.184, 0.101, 0.133],
|
| 134 |
+
[0.219, 0.115, 0.155],
|
| 135 |
+
[0.254, 0.127, 0.176],
|
| 136 |
+
[0.289, 0.138, 0.195],
|
| 137 |
+
[0.323, 0.147, 0.214],
|
| 138 |
+
[0.358, 0.155, 0.232],
|
| 139 |
+
[0.393, 0.161, 0.250],
|
| 140 |
+
[0.429, 0.166, 0.267],
|
| 141 |
+
[0.467, 0.169, 0.283],
|
| 142 |
+
[0.507, 0.168, 0.298],
|
| 143 |
+
[0.546, 0.168, 0.313],
|
| 144 |
+
[0.580, 0.172, 0.328],
|
| 145 |
+
[0.615, 0.175, 0.341],
|
| 146 |
+
[0.649, 0.178, 0.355]]
|
| 147 |
+
|
| 148 |
+
cmaps = {
|
| 149 |
+
name: LinearSegmentedColormap.from_list(name, data, _LUTSIZE) for name, data in [
|
| 150 |
+
('2VarAddA0', _2VarAddA0_data),
|
| 151 |
+
('2VarAddA1', _2VarAddA1_data),
|
| 152 |
+
('2VarSubA0', _2VarSubA0_data),
|
| 153 |
+
('2VarSubA1', _2VarSubA1_data),
|
| 154 |
+
('3VarAddA0', _3VarAddA0_data),
|
| 155 |
+
('3VarAddA1', _3VarAddA1_data),
|
| 156 |
+
('3VarAddA2', _3VarAddA2_data),
|
| 157 |
+
]}
|
| 158 |
+
|
| 159 |
+
cmap_families = {
|
| 160 |
+
'2VarAddA': MultivarColormap([cmaps[f'2VarAddA{i}'] for i in range(2)],
|
| 161 |
+
'sRGB_add', name='2VarAddA'),
|
| 162 |
+
'2VarSubA': MultivarColormap([cmaps[f'2VarSubA{i}'] for i in range(2)],
|
| 163 |
+
'sRGB_sub', name='2VarSubA'),
|
| 164 |
+
'3VarAddA': MultivarColormap([cmaps[f'3VarAddA{i}'] for i in range(3)],
|
| 165 |
+
'sRGB_add', name='3VarAddA'),
|
| 166 |
+
}
|
shared/package-files/d1/d1492a222e1e8710f76a8037cfbcbcfb77693acea8df4fc6a7cad9bc55f55bd4/test_deprecate_nonkeyword_arguments.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests for the `deprecate_nonkeyword_arguments` decorator
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import inspect
|
| 6 |
+
|
| 7 |
+
from pandas.util._decorators import deprecate_nonkeyword_arguments
|
| 8 |
+
|
| 9 |
+
import pandas._testing as tm
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@deprecate_nonkeyword_arguments(
|
| 13 |
+
version="1.1", allowed_args=["a", "b"], name="f_add_inputs"
|
| 14 |
+
)
|
| 15 |
+
def f(a, b=0, c=0, d=0):
|
| 16 |
+
return a + b + c + d
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_f_signature():
|
| 20 |
+
assert str(inspect.signature(f)) == "(a, b=0, *, c=0, d=0)"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_one_argument():
|
| 24 |
+
with tm.assert_produces_warning(None):
|
| 25 |
+
assert f(19) == 19
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_one_and_one_arguments():
|
| 29 |
+
with tm.assert_produces_warning(None):
|
| 30 |
+
assert f(19, d=6) == 25
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_two_arguments():
|
| 34 |
+
with tm.assert_produces_warning(None):
|
| 35 |
+
assert f(1, 5) == 6
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_two_and_two_arguments():
|
| 39 |
+
with tm.assert_produces_warning(None):
|
| 40 |
+
assert f(1, 3, c=3, d=5) == 12
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_three_arguments():
|
| 44 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 45 |
+
assert f(6, 3, 3) == 12
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_four_arguments():
|
| 49 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 50 |
+
assert f(1, 2, 3, 4) == 10
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_three_arguments_with_name_in_warning():
|
| 54 |
+
msg = (
|
| 55 |
+
"Starting with pandas version 1.1 all arguments of f_add_inputs "
|
| 56 |
+
"except for the arguments 'a' and 'b' will be keyword-only."
|
| 57 |
+
)
|
| 58 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 59 |
+
assert f(6, 3, 3) == 12
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@deprecate_nonkeyword_arguments(version="1.1")
|
| 63 |
+
def g(a, b=0, c=0, d=0):
|
| 64 |
+
with tm.assert_produces_warning(None):
|
| 65 |
+
return a + b + c + d
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_g_signature():
|
| 69 |
+
assert str(inspect.signature(g)) == "(a, *, b=0, c=0, d=0)"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_one_and_three_arguments_default_allowed_args():
|
| 73 |
+
with tm.assert_produces_warning(None):
|
| 74 |
+
assert g(1, b=3, c=3, d=5) == 12
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_three_arguments_default_allowed_args():
|
| 78 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 79 |
+
assert g(6, 3, 3) == 12
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_three_positional_argument_with_warning_message_analysis():
|
| 83 |
+
msg = (
|
| 84 |
+
"Starting with pandas version 1.1 all arguments of g "
|
| 85 |
+
"except for the argument 'a' will be keyword-only."
|
| 86 |
+
)
|
| 87 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 88 |
+
assert g(6, 3, 3) == 12
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@deprecate_nonkeyword_arguments(version="1.1")
|
| 92 |
+
def h(a=0, b=0, c=0, d=0):
|
| 93 |
+
return a + b + c + d
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_h_signature():
|
| 97 |
+
assert str(inspect.signature(h)) == "(*, a=0, b=0, c=0, d=0)"
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def test_all_keyword_arguments():
|
| 101 |
+
with tm.assert_produces_warning(None):
|
| 102 |
+
assert h(a=1, b=2) == 3
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def test_one_positional_argument():
|
| 106 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 107 |
+
assert h(23) == 23
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_one_positional_argument_with_warning_message_analysis():
|
| 111 |
+
msg = "Starting with pandas version 1.1 all arguments of h will be keyword-only."
|
| 112 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 113 |
+
assert h(19) == 19
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@deprecate_nonkeyword_arguments(version="1.1")
|
| 117 |
+
def i(a=0, /, b=0, *, c=0, d=0):
|
| 118 |
+
return a + b + c + d
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def test_i_signature():
|
| 122 |
+
assert str(inspect.signature(i)) == "(*, a=0, b=0, c=0, d=0)"
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class Foo:
|
| 126 |
+
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "bar"])
|
| 127 |
+
def baz(self, bar=None, foobar=None): # pylint: disable=disallowed-name
|
| 128 |
+
...
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def test_foo_signature():
|
| 132 |
+
assert str(inspect.signature(Foo.baz)) == "(self, bar=None, *, foobar=None)"
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def test_class():
|
| 136 |
+
msg = (
|
| 137 |
+
r"In a future version of pandas all arguments of Foo\.baz "
|
| 138 |
+
r"except for the argument \'bar\' will be keyword-only"
|
| 139 |
+
)
|
| 140 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 141 |
+
Foo().baz("qux", "quox")
|
shared/package-files/d1/d14b4ebc1555a119f8520c4472cacb7d26258da29873ff2265f23fc5e38207a8/lstm_mps_backward_compositeexplicitautograd_dispatch.h
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace compositeexplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API void lstm_mps_backward_out(at::Tensor & out0, at::TensorList out1, at::TensorList out2, const c10::optional<at::Tensor> & grad_y, const c10::optional<at::Tensor> & grad_hy, const c10::optional<at::Tensor> & grad_cy, const at::Tensor & z_state, const at::Tensor & cell_state_fwd, const at::Tensor & input, const at::Tensor & layersOutputs, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first);
|
| 21 |
+
TORCH_API void lstm_mps_backward_outf(const c10::optional<at::Tensor> & grad_y, const c10::optional<at::Tensor> & grad_hy, const c10::optional<at::Tensor> & grad_cy, const at::Tensor & z_state, const at::Tensor & cell_state_fwd, const at::Tensor & input, const at::Tensor & layersOutputs, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first, at::Tensor & out0, at::TensorList out1, at::TensorList out2);
|
| 22 |
+
|
| 23 |
+
} // namespace compositeexplicitautograd
|
| 24 |
+
} // namespace at
|
shared/package-files/d1/d14d03282c4a4f7523cf03d2722d0dd0d0384ec57515a9c3794822758a48797f/median_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 median(const at::Tensor & self);
|
| 21 |
+
TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> median_out(at::Tensor & values, at::Tensor & indices, const at::Tensor & self, int64_t dim, bool keepdim=false);
|
| 22 |
+
TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> median_outf(const at::Tensor & self, int64_t dim, bool keep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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2014 Anaconda, Inc
|
| 2 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 3 |
+
"""
|
| 4 |
+
Tools for converting Cran packages to conda recipes.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import copy
|
| 10 |
+
import hashlib
|
| 11 |
+
import re
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
import tarfile
|
| 15 |
+
import unicodedata
|
| 16 |
+
import zipfile
|
| 17 |
+
from itertools import chain
|
| 18 |
+
from os import environ, listdir, makedirs, sep
|
| 19 |
+
from os.path import (
|
| 20 |
+
basename,
|
| 21 |
+
commonprefix,
|
| 22 |
+
exists,
|
| 23 |
+
isabs,
|
| 24 |
+
isdir,
|
| 25 |
+
isfile,
|
| 26 |
+
join,
|
| 27 |
+
normpath,
|
| 28 |
+
realpath,
|
| 29 |
+
relpath,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
import requests
|
| 33 |
+
import yaml
|
| 34 |
+
|
| 35 |
+
# try to import C dumper
|
| 36 |
+
try:
|
| 37 |
+
from yaml import CSafeDumper as SafeDumper
|
| 38 |
+
except ImportError:
|
| 39 |
+
from yaml import SafeDumper
|
| 40 |
+
|
| 41 |
+
from typing import TYPE_CHECKING
|
| 42 |
+
|
| 43 |
+
from conda.common.io import dashlist
|
| 44 |
+
|
| 45 |
+
from .. import source
|
| 46 |
+
from ..conda_interface import TemporaryDirectory, cc_conda_build
|
| 47 |
+
from ..config import get_or_merge_config
|
| 48 |
+
from ..license_family import allowed_license_families, guess_license_family
|
| 49 |
+
from ..metadata import MetaData
|
| 50 |
+
from ..utils import ensure_list, rm_rf
|
| 51 |
+
from ..variants import DEFAULT_VARIANTS, get_package_variants
|
| 52 |
+
|
| 53 |
+
if TYPE_CHECKING:
|
| 54 |
+
from typing import Literal
|
| 55 |
+
|
| 56 |
+
SOURCE_META = """\
|
| 57 |
+
{archive_keys}
|
| 58 |
+
{git_url_key} {git_url}
|
| 59 |
+
{git_tag_key} {git_tag}
|
| 60 |
+
{patches}
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
BINARY_META = """\
|
| 64 |
+
url: {cranurl}{sel}
|
| 65 |
+
{hash_entry}{sel}
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
VERSION_META = """\
|
| 69 |
+
{{% set version = '{cran_version}' %}}{sel}"""
|
| 70 |
+
|
| 71 |
+
CRAN_META = """\
|
| 72 |
+
{version_source}
|
| 73 |
+
{version_binary1}
|
| 74 |
+
{version_binary2}
|
| 75 |
+
|
| 76 |
+
{{% set posix = 'm2-' if win else '' %}}
|
| 77 |
+
{{% set native = 'm2w64-' if win else '' %}}
|
| 78 |
+
|
| 79 |
+
package:
|
| 80 |
+
name: {packagename}
|
| 81 |
+
version: {{{{ version|replace("-", "_") }}}}
|
| 82 |
+
|
| 83 |
+
source:
|
| 84 |
+
{source}
|
| 85 |
+
{binary1}
|
| 86 |
+
{binary2}
|
| 87 |
+
|
| 88 |
+
build:
|
| 89 |
+
merge_build_host: True{sel_src_and_win}
|
| 90 |
+
# If this is a new build for the same version, increment the build number.
|
| 91 |
+
number: {build_number}
|
| 92 |
+
{skip_os}
|
| 93 |
+
{noarch_generic}
|
| 94 |
+
|
| 95 |
+
# This is required to make R link correctly on Linux.
|
| 96 |
+
rpaths:
|
| 97 |
+
- lib/R/lib/
|
| 98 |
+
- lib/
|
| 99 |
+
{script_env}
|
| 100 |
+
{suggests}
|
| 101 |
+
requirements:
|
| 102 |
+
build:{build_depends}
|
| 103 |
+
|
| 104 |
+
host:{host_depends}
|
| 105 |
+
|
| 106 |
+
run:{run_depends}
|
| 107 |
+
|
| 108 |
+
test:
|
| 109 |
+
commands:
|
| 110 |
+
# You can put additional test commands to be run here.
|
| 111 |
+
- $R -e "library('{cran_packagename}')" # [not win]
|
| 112 |
+
- "\\"%R%\\" -e \\"library('{cran_packagename}')\\"" # [win]
|
| 113 |
+
|
| 114 |
+
# You can also put a file called run_test.py, run_test.sh, or run_test.bat
|
| 115 |
+
# in the recipe that will be run at test time.
|
| 116 |
+
|
| 117 |
+
# requires:
|
| 118 |
+
# Put any additional test requirements here.
|
| 119 |
+
|
| 120 |
+
about:
|
| 121 |
+
{home_comment}home:{homeurl}
|
| 122 |
+
license: {license}
|
| 123 |
+
{summary_comment}summary:{summary}
|
| 124 |
+
license_family: {license_family}
|
| 125 |
+
{license_file}
|
| 126 |
+
|
| 127 |
+
{extra_recipe_maintainers}
|
| 128 |
+
|
| 129 |
+
# The original CRAN metadata for this package was:
|
| 130 |
+
|
| 131 |
+
{cran_metadata}
|
| 132 |
+
|
| 133 |
+
# See
|
| 134 |
+
# https://docs.conda.io/projects/conda-build for
|
| 135 |
+
# more information about meta.yaml
|
| 136 |
+
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
CRAN_BUILD_SH_SOURCE = """\
|
| 140 |
+
#!/bin/bash
|
| 141 |
+
|
| 142 |
+
# 'Autobrew' is being used by more and more packages these days
|
| 143 |
+
# to grab static libraries from Homebrew bottles. These bottles
|
| 144 |
+
# are fetched via Homebrew's --force-bottle option which grabs
|
| 145 |
+
# a bottle for the build machine which may not be macOS 10.9.
|
| 146 |
+
# Also, we want to use conda packages (and shared libraries) for
|
| 147 |
+
# these 'system' dependencies. See:
|
| 148 |
+
# https://github.com/jeroen/autobrew/issues/3
|
| 149 |
+
export DISABLE_AUTOBREW=1
|
| 150 |
+
|
| 151 |
+
# R refuses to build packages that mark themselves as Priority: Recommended
|
| 152 |
+
mv DESCRIPTION DESCRIPTION.old
|
| 153 |
+
grep -va '^Priority: ' DESCRIPTION.old > DESCRIPTION
|
| 154 |
+
# shellcheck disable=SC2086
|
| 155 |
+
${{R}} CMD INSTALL --build . ${{R_ARGS}}
|
| 156 |
+
|
| 157 |
+
# Add more build steps here, if they are necessary.
|
| 158 |
+
|
| 159 |
+
# See
|
| 160 |
+
# https://docs.conda.io/projects/conda-build
|
| 161 |
+
# for a list of environment variables that are set during the build process.
|
| 162 |
+
"""
|
| 163 |
+
|
| 164 |
+
CRAN_BUILD_SH_MIXED = """\
|
| 165 |
+
#!/bin/bash
|
| 166 |
+
|
| 167 |
+
set -o errexit -o pipefail
|
| 168 |
+
|
| 169 |
+
if {source_pf_bash}; then
|
| 170 |
+
export DISABLE_AUTOBREW=1
|
| 171 |
+
mv DESCRIPTION DESCRIPTION.old
|
| 172 |
+
grep -va '^Priority: ' DESCRIPTION.old > DESCRIPTION
|
| 173 |
+
# shellcheck disable=SC2086
|
| 174 |
+
${{R}} CMD INSTALL --build . ${{R_ARGS}}
|
| 175 |
+
else
|
| 176 |
+
mkdir -p "${{PREFIX}}"/lib/R/library/{cran_packagename}
|
| 177 |
+
mv ./* "${{PREFIX}}"/lib/R/library/{cran_packagename}
|
| 178 |
+
|
| 179 |
+
if [[ ${{target_platform}} == osx-64 ]]; then
|
| 180 |
+
pushd "${{PREFIX}}"
|
| 181 |
+
for libdir in lib/R/lib lib/R/modules lib/R/library lib/R/bin/exec sysroot/usr/lib; do
|
| 182 |
+
pushd "${{libdir}}" || exit 1
|
| 183 |
+
while IFS= read -r -d '' SHARED_LIB
|
| 184 |
+
do
|
| 185 |
+
echo "fixing SHARED_LIB ${{SHARED_LIB}}"
|
| 186 |
+
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5.0-MRO/Resources/lib/libR.dylib "${{PREFIX}}"/lib/R/lib/libR.dylib "${{SHARED_LIB}}" || true
|
| 187 |
+
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libR.dylib "${{PREFIX}}"/lib/R/lib/libR.dylib "${{SHARED_LIB}}" || true
|
| 188 |
+
install_name_tool -change /usr/local/clang4/lib/libomp.dylib "${{PREFIX}}"/lib/libomp.dylib "${{SHARED_LIB}}" || true
|
| 189 |
+
install_name_tool -change /usr/local/gfortran/lib/libgfortran.3.dylib "${{PREFIX}}"/lib/libgfortran.3.dylib "${{SHARED_LIB}}" || true
|
| 190 |
+
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libquadmath.0.dylib "${{PREFIX}}"/lib/libquadmath.0.dylib "${{SHARED_LIB}}" || true
|
| 191 |
+
install_name_tool -change /usr/local/gfortran/lib/libquadmath.0.dylib "${{PREFIX}}"/lib/libquadmath.0.dylib "${{SHARED_LIB}}" || true
|
| 192 |
+
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libgfortran.3.dylib "${{PREFIX}}"/lib/libgfortran.3.dylib "${{SHARED_LIB}}" || true
|
| 193 |
+
install_name_tool -change /usr/lib/libgcc_s.1.dylib "${{PREFIX}}"/lib/libgcc_s.1.dylib "${{SHARED_LIB}}" || true
|
| 194 |
+
install_name_tool -change /usr/lib/libiconv.2.dylib "${{PREFIX}}"/sysroot/usr/lib/libiconv.2.dylib "${{SHARED_LIB}}" || true
|
| 195 |
+
install_name_tool -change /usr/lib/libncurses.5.4.dylib "${{PREFIX}}"/sysroot/usr/lib/libncurses.5.4.dylib "${{SHARED_LIB}}" || true
|
| 196 |
+
install_name_tool -change /usr/lib/libicucore.A.dylib "${{PREFIX}}"/sysroot/usr/lib/libicucore.A.dylib "${{SHARED_LIB}}" || true
|
| 197 |
+
install_name_tool -change /usr/lib/libexpat.1.dylib "${{PREFIX}}"/lib/libexpat.1.dylib "${{SHARED_LIB}}" || true
|
| 198 |
+
install_name_tool -change /usr/lib/libcurl.4.dylib "${{PREFIX}}"/lib/libcurl.4.dylib "${{SHARED_LIB}}" || true
|
| 199 |
+
install_name_tool -change /usr/lib/libc++.1.dylib "${{PREFIX}}"/lib/libc++.1.dylib "${{SHARED_LIB}}" || true
|
| 200 |
+
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libc++.1.dylib "${{PREFIX}}"/lib/libc++.1.dylib "${{SHARED_LIB}}" || true
|
| 201 |
+
done < <(find . \\( -type f -iname "*.dylib" -or -iname "*.so" -or -iname "R" \\) -print0)
|
| 202 |
+
popd
|
| 203 |
+
done
|
| 204 |
+
popd
|
| 205 |
+
fi
|
| 206 |
+
fi
|
| 207 |
+
""" # noqa: E501
|
| 208 |
+
|
| 209 |
+
CRAN_BUILD_SH_BINARY = """\
|
| 210 |
+
#!/bin/bash
|
| 211 |
+
|
| 212 |
+
set -o errexit -o pipefail
|
| 213 |
+
|
| 214 |
+
mkdir -p "${{PREFIX}}"/lib/R/library/{cran_packagename}
|
| 215 |
+
mv ./* "${{PREFIX}}"/lib/R/library/{cran_packagename}
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
CRAN_BLD_BAT_SOURCE = """\
|
| 219 |
+
"%R%" CMD INSTALL --build . %R_ARGS%
|
| 220 |
+
IF %ERRORLEVEL% NEQ 0 exit /B 1
|
| 221 |
+
"""
|
| 222 |
+
|
| 223 |
+
# We hardcode the fact that CRAN does not provide win32 binaries here.
|
| 224 |
+
CRAN_BLD_BAT_MIXED = """\
|
| 225 |
+
if "%target_platform%" == "win-64" goto skip_source_build
|
| 226 |
+
"%R%" CMD INSTALL --build . %R_ARGS%
|
| 227 |
+
IF %ERRORLEVEL% NEQ 0 exit /B 1
|
| 228 |
+
exit 0
|
| 229 |
+
:skip_source_build
|
| 230 |
+
mkdir %PREFIX%\\lib\\R\\library
|
| 231 |
+
robocopy /E . "%PREFIX%\\lib\\R\\library\\{cran_packagename}"
|
| 232 |
+
if %ERRORLEVEL% NEQ 1 exit /B 1
|
| 233 |
+
exit 0
|
| 234 |
+
"""
|
| 235 |
+
|
| 236 |
+
INDENT = "\n - "
|
| 237 |
+
|
| 238 |
+
CRAN_KEYS = [
|
| 239 |
+
"Site",
|
| 240 |
+
"Archs",
|
| 241 |
+
"Depends",
|
| 242 |
+
"Enhances",
|
| 243 |
+
"Imports",
|
| 244 |
+
"License",
|
| 245 |
+
"License_is_FOSS",
|
| 246 |
+
"License_restricts_use",
|
| 247 |
+
"LinkingTo",
|
| 248 |
+
"MD5sum",
|
| 249 |
+
"NeedsCompilation",
|
| 250 |
+
"OS_type",
|
| 251 |
+
"Package",
|
| 252 |
+
"Path",
|
| 253 |
+
"Priority",
|
| 254 |
+
"Suggests",
|
| 255 |
+
"Version",
|
| 256 |
+
"Title",
|
| 257 |
+
"Author",
|
| 258 |
+
"Maintainer",
|
| 259 |
+
]
|
| 260 |
+
|
| 261 |
+
# The following base/recommended package names are derived from R's source
|
| 262 |
+
# tree (R-3.0.2/share/make/vars.mk). Hopefully they don't change too much
|
| 263 |
+
# between versions.
|
| 264 |
+
R_BASE_PACKAGE_NAMES = (
|
| 265 |
+
"base",
|
| 266 |
+
"compiler",
|
| 267 |
+
"datasets",
|
| 268 |
+
"graphics",
|
| 269 |
+
"grDevices",
|
| 270 |
+
"grid",
|
| 271 |
+
"methods",
|
| 272 |
+
"parallel",
|
| 273 |
+
"splines",
|
| 274 |
+
"stats",
|
| 275 |
+
"stats4",
|
| 276 |
+
"tcltk",
|
| 277 |
+
"tools",
|
| 278 |
+
"utils",
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
R_RECOMMENDED_PACKAGE_NAMES = (
|
| 282 |
+
"MASS",
|
| 283 |
+
"lattice",
|
| 284 |
+
"Matrix",
|
| 285 |
+
"nlme",
|
| 286 |
+
"survival",
|
| 287 |
+
"boot",
|
| 288 |
+
"cluster",
|
| 289 |
+
"codetools",
|
| 290 |
+
"foreign",
|
| 291 |
+
"KernSmooth",
|
| 292 |
+
"rpart",
|
| 293 |
+
"class",
|
| 294 |
+
"nnet",
|
| 295 |
+
"spatial",
|
| 296 |
+
"mgcv",
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
# Stolen then tweaked from debian.deb822.PkgRelation.__dep_RE.
|
| 300 |
+
VERSION_DEPENDENCY_REGEX = re.compile(
|
| 301 |
+
r"^\s*(?P<name>[a-zA-Z0-9.+\-]{1,})"
|
| 302 |
+
r"(\s*\(\s*(?P<relop>[>=<]+)\s*"
|
| 303 |
+
r"(?P<version>[0-9a-zA-Z:\-+~.]+)\s*\))"
|
| 304 |
+
r"?(\s*\[(?P<archs>[\s!\w\-]+)\])?\s*$"
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
target_platform_bash_test_by_sel = {
|
| 308 |
+
"linux": "=~ linux.*",
|
| 309 |
+
"linux32": "== linux-32",
|
| 310 |
+
"linux64": "== linux-64",
|
| 311 |
+
"win32": "== win-32",
|
| 312 |
+
"win64": "== win-64",
|
| 313 |
+
"osx": "== osx-64",
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def package_exists(package_name):
|
| 318 |
+
# TODO: how can we get cran to spit out package presence?
|
| 319 |
+
# available.packages() is probably a start, but no channels are working on mac right now?
|
| 320 |
+
return True
|
| 321 |
+
# install_output = subprocess.check_output([join(sys.prefix, "r"), "-e",
|
| 322 |
+
# # ind=2 arbitrarily chooses some CRAN mirror to try.
|
| 323 |
+
# "chooseCRANmirror(ind=2);install.packages('{}')".format(package_name)])
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def add_parser(repos):
|
| 327 |
+
# for loading default variant info
|
| 328 |
+
cran = repos.add_parser(
|
| 329 |
+
"cran",
|
| 330 |
+
help="""
|
| 331 |
+
Create recipe skeleton for packages hosted on the Comprehensive R Archive
|
| 332 |
+
Network (CRAN) (cran.r-project.org).
|
| 333 |
+
""",
|
| 334 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 335 |
+
)
|
| 336 |
+
cran.add_argument(
|
| 337 |
+
"packages",
|
| 338 |
+
nargs="+",
|
| 339 |
+
help="""CRAN packages to create recipe skeletons for.""",
|
| 340 |
+
)
|
| 341 |
+
cran.add_argument(
|
| 342 |
+
"--output-dir",
|
| 343 |
+
help="Directory to write recipes to (default: %(default)s).",
|
| 344 |
+
default=".",
|
| 345 |
+
)
|
| 346 |
+
cran.add_argument(
|
| 347 |
+
"--output-suffix",
|
| 348 |
+
help="Suffix to add to recipe dir, can contain other dirs (eg: -feedstock/recipe).",
|
| 349 |
+
default="",
|
| 350 |
+
)
|
| 351 |
+
cran.add_argument(
|
| 352 |
+
"--add-maintainer",
|
| 353 |
+
help="Add this github username as a maintainer if not already present.",
|
| 354 |
+
)
|
| 355 |
+
cran.add_argument(
|
| 356 |
+
"--version",
|
| 357 |
+
help="Version to use. Applies to all packages.",
|
| 358 |
+
)
|
| 359 |
+
cran.add_argument(
|
| 360 |
+
"--git-tag",
|
| 361 |
+
help="Git tag to use for GitHub recipes.",
|
| 362 |
+
)
|
| 363 |
+
cran.add_argument(
|
| 364 |
+
"--all-urls",
|
| 365 |
+
action="store_true",
|
| 366 |
+
help="""Look at all URLs, not just source URLs. Use this if it can't
|
| 367 |
+
find the right URL.""",
|
| 368 |
+
)
|
| 369 |
+
cran.add_argument(
|
| 370 |
+
"--cran-url",
|
| 371 |
+
help="URL to use for as source package repository",
|
| 372 |
+
)
|
| 373 |
+
cran.add_argument(
|
| 374 |
+
"--r-interp",
|
| 375 |
+
default="r-base",
|
| 376 |
+
help="Declare R interpreter package",
|
| 377 |
+
)
|
| 378 |
+
cran.add_argument(
|
| 379 |
+
"--use-binaries-ver",
|
| 380 |
+
help=(
|
| 381 |
+
"Repackage binaries from version provided by argument instead of building "
|
| 382 |
+
"from source."
|
| 383 |
+
),
|
| 384 |
+
)
|
| 385 |
+
cran.add_argument(
|
| 386 |
+
"--use-when-no-binary",
|
| 387 |
+
choices=("src", "old", "src-old", "old-src", "error"),
|
| 388 |
+
default="src",
|
| 389 |
+
help="""Sometimes binaries are not available at the correct version for
|
| 390 |
+
a given platform (macOS). You can use this flag to specify what
|
| 391 |
+
fallback to take, either compiling from source or using an older
|
| 392 |
+
binary or trying one then the other.""",
|
| 393 |
+
)
|
| 394 |
+
cran.add_argument(
|
| 395 |
+
"--use-noarch-generic",
|
| 396 |
+
action="store_true",
|
| 397 |
+
dest="use_noarch_generic",
|
| 398 |
+
help="Mark packages that do not need compilation as `noarch: generic`",
|
| 399 |
+
)
|
| 400 |
+
cran.add_argument(
|
| 401 |
+
"--use-rtools-win",
|
| 402 |
+
action="store_true",
|
| 403 |
+
help="Use Rtools when building from source on Windows",
|
| 404 |
+
)
|
| 405 |
+
cran.add_argument(
|
| 406 |
+
"--recursive",
|
| 407 |
+
action="store_true",
|
| 408 |
+
help="Create recipes for dependencies if they do not already exist.",
|
| 409 |
+
)
|
| 410 |
+
cran.add_argument(
|
| 411 |
+
"--no-recursive",
|
| 412 |
+
action="store_false",
|
| 413 |
+
dest="recursive",
|
| 414 |
+
help="Don't create recipes for dependencies if they do not already exist.",
|
| 415 |
+
)
|
| 416 |
+
cran.add_argument(
|
| 417 |
+
"--no-archive",
|
| 418 |
+
action="store_false",
|
| 419 |
+
dest="archive",
|
| 420 |
+
help="Don't include an Archive download url.",
|
| 421 |
+
)
|
| 422 |
+
cran.add_argument(
|
| 423 |
+
"--allow-archived",
|
| 424 |
+
action="store_true",
|
| 425 |
+
dest="allow_archived",
|
| 426 |
+
help="If the package has been archived, download the latest version.",
|
| 427 |
+
)
|
| 428 |
+
cran.add_argument(
|
| 429 |
+
"--version-compare",
|
| 430 |
+
action="store_true",
|
| 431 |
+
help="""Compare the package version of the recipe with the one available
|
| 432 |
+
on CRAN. Exits 1 if a newer version is available and 0 otherwise.""",
|
| 433 |
+
)
|
| 434 |
+
cran.add_argument(
|
| 435 |
+
"--update-policy",
|
| 436 |
+
action="store",
|
| 437 |
+
choices=(
|
| 438 |
+
"error",
|
| 439 |
+
"skip-up-to-date",
|
| 440 |
+
"skip-existing",
|
| 441 |
+
"overwrite",
|
| 442 |
+
"merge-keep-build-num",
|
| 443 |
+
"merge-incr-build-num",
|
| 444 |
+
),
|
| 445 |
+
default="error",
|
| 446 |
+
help="""Dictates what to do when existing packages are encountered in the
|
| 447 |
+
output directory (set by --output-dir). In the present implementation, the
|
| 448 |
+
merge options avoid overwriting bld.bat and build.sh and only manage copying
|
| 449 |
+
across patches, and the `build/{number,script_env}` fields. When the version
|
| 450 |
+
changes, both merge options reset `build/number` to 0. When the version does
|
| 451 |
+
not change they either keep the old `build/number` or else increase it by one.""",
|
| 452 |
+
)
|
| 453 |
+
cran.add_argument(
|
| 454 |
+
"-m",
|
| 455 |
+
"--variant-config-files",
|
| 456 |
+
default=cc_conda_build.get("skeleton_config_yaml", None),
|
| 457 |
+
help="""Variant config file to add. These yaml files can contain
|
| 458 |
+
keys such as `cran_mirror`. Only one can be provided here.""",
|
| 459 |
+
)
|
| 460 |
+
cran.add_argument(
|
| 461 |
+
"--add-cross-r-base",
|
| 462 |
+
action="store_true",
|
| 463 |
+
default=False,
|
| 464 |
+
help="""Add cross-r-base to build requirements for cross compiling""",
|
| 465 |
+
)
|
| 466 |
+
cran.add_argument(
|
| 467 |
+
"--no-comments",
|
| 468 |
+
action="store_true",
|
| 469 |
+
default=False,
|
| 470 |
+
help="""Do not include instructional comments in recipe files""",
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def dict_from_cran_lines(lines):
|
| 475 |
+
d = {}
|
| 476 |
+
for line in lines:
|
| 477 |
+
if not line:
|
| 478 |
+
continue
|
| 479 |
+
try:
|
| 480 |
+
if ": " in line:
|
| 481 |
+
(k, v) = line.split(": ", 1)
|
| 482 |
+
else:
|
| 483 |
+
# Sometimes fields are included but left blank, e.g.:
|
| 484 |
+
# - Enhances in data.tree
|
| 485 |
+
# - Suggests in corpcor
|
| 486 |
+
(k, v) = line.split(":", 1)
|
| 487 |
+
except ValueError:
|
| 488 |
+
sys.exit("Error: Could not parse metadata (%s)" % line)
|
| 489 |
+
d[k] = v
|
| 490 |
+
# if k not in CRAN_KEYS:
|
| 491 |
+
# print("Warning: Unknown key %s" % k)
|
| 492 |
+
d["orig_lines"] = lines
|
| 493 |
+
return d
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def remove_package_line_continuations(chunk):
|
| 497 |
+
"""
|
| 498 |
+
>>> chunk = [
|
| 499 |
+
'Package: A3',
|
| 500 |
+
'Version: 0.9.2',
|
| 501 |
+
'Depends: R (>= 2.15.0), xtable, pbapply',
|
| 502 |
+
'Suggests: randomForest, e1071',
|
| 503 |
+
'Imports: MASS, R.methodsS3 (>= 1.5.2), R.oo (>= 1.15.8), R.utils (>=',
|
| 504 |
+
' 1.27.1), matrixStats (>= 0.8.12), R.filesets (>= 2.3.0), ',
|
| 505 |
+
' sampleSelection, scatterplot3d, strucchange, systemfit',
|
| 506 |
+
'License: GPL (>= 2)',
|
| 507 |
+
'NeedsCompilation: no']
|
| 508 |
+
>>> remove_package_line_continuations(chunk)
|
| 509 |
+
['Package: A3',
|
| 510 |
+
'Version: 0.9.2',
|
| 511 |
+
'Depends: R (>= 2.15.0), xtable, pbapply',
|
| 512 |
+
'Suggests: randomForest, e1071',
|
| 513 |
+
'Imports: MASS, R.methodsS3 (>= 1.5.2), R.oo (>= 1.15.8), R.utils (>= 1.27.1), matrixStats (>= 0.8.12), R.filesets (>= 2.3.0), sampleSelection, scatterplot3d, strucchange, systemfit, rgl,'
|
| 514 |
+
'License: GPL (>= 2)',
|
| 515 |
+
'NeedsCompilation: no']
|
| 516 |
+
""" # NOQA
|
| 517 |
+
continuation = (" ", "\t")
|
| 518 |
+
continued_ix = None
|
| 519 |
+
continued_line = None
|
| 520 |
+
had_continuation = False
|
| 521 |
+
accumulating_continuations = False
|
| 522 |
+
|
| 523 |
+
chunk.append("")
|
| 524 |
+
|
| 525 |
+
for i, line in enumerate(chunk):
|
| 526 |
+
if line.startswith(continuation):
|
| 527 |
+
line = " " + line.lstrip()
|
| 528 |
+
if accumulating_continuations:
|
| 529 |
+
assert had_continuation
|
| 530 |
+
continued_line += line
|
| 531 |
+
chunk[i] = None
|
| 532 |
+
else:
|
| 533 |
+
accumulating_continuations = True
|
| 534 |
+
continued_ix = i - 1
|
| 535 |
+
continued_line = chunk[continued_ix] + line
|
| 536 |
+
had_continuation = True
|
| 537 |
+
chunk[i] = None
|
| 538 |
+
else:
|
| 539 |
+
if accumulating_continuations:
|
| 540 |
+
assert had_continuation
|
| 541 |
+
chunk[continued_ix] = continued_line
|
| 542 |
+
accumulating_continuations = False
|
| 543 |
+
continued_line = None
|
| 544 |
+
continued_ix = None
|
| 545 |
+
|
| 546 |
+
if had_continuation:
|
| 547 |
+
# Remove the None(s).
|
| 548 |
+
chunk = [c for c in chunk if c]
|
| 549 |
+
|
| 550 |
+
chunk.append("")
|
| 551 |
+
|
| 552 |
+
return chunk
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def yaml_quote_string(string):
|
| 556 |
+
"""
|
| 557 |
+
Quote a string for use in YAML.
|
| 558 |
+
|
| 559 |
+
We can't just use yaml.dump because it adds ellipses to the end of the
|
| 560 |
+
string, and it in general doesn't handle being placed inside an existing
|
| 561 |
+
document very well.
|
| 562 |
+
|
| 563 |
+
Note that this function is NOT general.
|
| 564 |
+
"""
|
| 565 |
+
return (
|
| 566 |
+
yaml.dump(string, indent=True, Dumper=SafeDumper)
|
| 567 |
+
.replace("\n...\n", "")
|
| 568 |
+
.replace("\n", "\n ")
|
| 569 |
+
.rstrip("\n ")
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
# Due to how we render the metadata there can be significant areas of repeated newlines.
|
| 574 |
+
# This collapses them and also strips any trailing spaces.
|
| 575 |
+
def clear_whitespace(string):
|
| 576 |
+
lines = []
|
| 577 |
+
last_line = ""
|
| 578 |
+
for line in string.splitlines():
|
| 579 |
+
line = line.rstrip()
|
| 580 |
+
if not (line == "" and last_line == ""):
|
| 581 |
+
lines.append(line)
|
| 582 |
+
last_line = line
|
| 583 |
+
return "\n".join(lines)
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def read_description_contents(fp):
|
| 587 |
+
bytes = fp.read()
|
| 588 |
+
text = bytes.decode("utf-8", errors="replace")
|
| 589 |
+
text = clear_whitespace(text)
|
| 590 |
+
lines = remove_package_line_continuations(text.splitlines())
|
| 591 |
+
return dict_from_cran_lines(lines)
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def get_archive_metadata(path, verbose=True):
|
| 595 |
+
if verbose:
|
| 596 |
+
print("Reading package metadata from %s" % path)
|
| 597 |
+
if basename(path) == "DESCRIPTION":
|
| 598 |
+
with open(path, "rb") as fp:
|
| 599 |
+
return read_description_contents(fp)
|
| 600 |
+
elif tarfile.is_tarfile(path):
|
| 601 |
+
with tarfile.open(path, "r") as tf:
|
| 602 |
+
for member in tf:
|
| 603 |
+
if re.match(r"^[^/]+/DESCRIPTION$", member.name):
|
| 604 |
+
fp = tf.extractfile(member)
|
| 605 |
+
return read_description_contents(fp)
|
| 606 |
+
elif path.endswith(".zip"):
|
| 607 |
+
with zipfile.ZipFile(path, "r") as zf:
|
| 608 |
+
for member in zf.infolist():
|
| 609 |
+
if re.match(r"^[^/]+/DESCRIPTION$", member.filename):
|
| 610 |
+
fp = zf.open(member, "r")
|
| 611 |
+
return read_description_contents(fp)
|
| 612 |
+
else:
|
| 613 |
+
sys.exit("Cannot extract a DESCRIPTION from file %s" % path)
|
| 614 |
+
sys.exit("%s does not seem to be a CRAN package (no DESCRIPTION) file" % path)
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
def get_latest_git_tag(config):
|
| 618 |
+
# SO says to use taggerdate instead of committerdate, but that is invalid for lightweight tags.
|
| 619 |
+
p = subprocess.Popen(
|
| 620 |
+
[
|
| 621 |
+
"git",
|
| 622 |
+
"for-each-ref",
|
| 623 |
+
"refs/tags",
|
| 624 |
+
"--sort=-committerdate",
|
| 625 |
+
"--format=%(refname:short)",
|
| 626 |
+
"--count=1",
|
| 627 |
+
],
|
| 628 |
+
stdout=subprocess.PIPE,
|
| 629 |
+
stderr=subprocess.PIPE,
|
| 630 |
+
cwd=config.work_dir,
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
stdout, stderr = p.communicate()
|
| 634 |
+
stdout = stdout.decode("utf-8")
|
| 635 |
+
stderr = stderr.decode("utf-8")
|
| 636 |
+
if stderr or p.returncode:
|
| 637 |
+
sys.exit("Error: git tag failed (%s)" % stderr)
|
| 638 |
+
tags = stdout.strip().splitlines()
|
| 639 |
+
if not tags:
|
| 640 |
+
sys.exit("Error: no tags found")
|
| 641 |
+
|
| 642 |
+
print("Using tag %s" % tags[-1])
|
| 643 |
+
return tags[-1]
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def _ssl_no_verify():
|
| 647 |
+
"""Gets whether the SSL_NO_VERIFY environment variable is set to 1 or True.
|
| 648 |
+
|
| 649 |
+
This provides a workaround for users in some corporate environments where
|
| 650 |
+
MITM style proxies make it difficult to fetch data over HTTPS.
|
| 651 |
+
"""
|
| 652 |
+
return environ.get("SSL_NO_VERIFY", "").strip().lower() in ("1", "true")
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
def get_session(output_dir, verbose=True):
|
| 656 |
+
session = requests.Session()
|
| 657 |
+
session.verify = _ssl_no_verify()
|
| 658 |
+
try:
|
| 659 |
+
import cachecontrol
|
| 660 |
+
import cachecontrol.caches
|
| 661 |
+
except ImportError:
|
| 662 |
+
if verbose:
|
| 663 |
+
print(
|
| 664 |
+
"Tip: install CacheControl and lockfile (conda packages) to cache the "
|
| 665 |
+
"CRAN metadata"
|
| 666 |
+
)
|
| 667 |
+
else:
|
| 668 |
+
session = cachecontrol.CacheControl(
|
| 669 |
+
session, cache=cachecontrol.caches.FileCache(join(output_dir, ".web_cache"))
|
| 670 |
+
)
|
| 671 |
+
return session
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def get_cran_archive_versions(cran_url, session, package, verbose=True):
|
| 675 |
+
if verbose:
|
| 676 |
+
print(f"Fetching archived versions for package {package} from {cran_url}")
|
| 677 |
+
r = session.get(cran_url + "/src/contrib/Archive/" + package + "/")
|
| 678 |
+
try:
|
| 679 |
+
r.raise_for_status()
|
| 680 |
+
except requests.exceptions.HTTPError as e:
|
| 681 |
+
if e.response.status_code == 404:
|
| 682 |
+
print("No archive directory for package %s" % package)
|
| 683 |
+
return []
|
| 684 |
+
raise
|
| 685 |
+
versions = []
|
| 686 |
+
for p, dt in re.findall(
|
| 687 |
+
r'<td><a href="([^"]+)">\1</a></td>\s*<td[^>]*>([^<]*)</td>', r.text
|
| 688 |
+
):
|
| 689 |
+
if p.endswith(".tar.gz") and "_" in p:
|
| 690 |
+
name, version = p.rsplit(".", 2)[0].split("_", 1)
|
| 691 |
+
versions.append((dt.strip(), version))
|
| 692 |
+
return [v for dt, v in sorted(versions, reverse=True)]
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def get_cran_index(cran_url, session, verbose=True):
|
| 696 |
+
if verbose:
|
| 697 |
+
print("Fetching main index from %s" % cran_url)
|
| 698 |
+
r = session.get(cran_url + "/src/contrib/")
|
| 699 |
+
r.raise_for_status()
|
| 700 |
+
records = {}
|
| 701 |
+
for p in re.findall(r'<td><a href="([^"]+)">\1</a></td>', r.text):
|
| 702 |
+
if p.endswith(".tar.gz") and "_" in p:
|
| 703 |
+
name, version = p.rsplit(".", 2)[0].split("_", 1)
|
| 704 |
+
records[name.lower()] = (name, version)
|
| 705 |
+
r = session.get(cran_url + "/src/contrib/Archive/")
|
| 706 |
+
r.raise_for_status()
|
| 707 |
+
for p in re.findall(r'<td><a href="([^"]+)/">\1/</a></td>', r.text):
|
| 708 |
+
if re.match(r"^[A-Za-z]", p):
|
| 709 |
+
records.setdefault(p.lower(), (p, None))
|
| 710 |
+
return records
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
def make_array(m, key, allow_empty=False):
|
| 714 |
+
result = []
|
| 715 |
+
try:
|
| 716 |
+
old_vals = m.get_value(key, [])
|
| 717 |
+
except:
|
| 718 |
+
old_vals = []
|
| 719 |
+
if old_vals or allow_empty:
|
| 720 |
+
result.append(key.split("/")[-1] + ":")
|
| 721 |
+
for old_val in old_vals:
|
| 722 |
+
result.append(f"{INDENT}{old_val}")
|
| 723 |
+
return result
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
def existing_recipe_dir(output_dir, output_suffix, package, version):
|
| 727 |
+
result = None
|
| 728 |
+
if version:
|
| 729 |
+
package = package + "-" + version.replace("-", "_")
|
| 730 |
+
if exists(join(output_dir, package)):
|
| 731 |
+
result = normpath(join(output_dir, package))
|
| 732 |
+
elif exists(join(output_dir, package + output_suffix)):
|
| 733 |
+
result = normpath(join(output_dir, package + output_suffix))
|
| 734 |
+
elif exists(join(output_dir, "r-" + package + output_suffix)):
|
| 735 |
+
result = normpath(join(output_dir, "r-" + package + output_suffix))
|
| 736 |
+
return result
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
def strip_end(string, end):
|
| 740 |
+
if string.endswith(end):
|
| 741 |
+
return string[: -len(end)]
|
| 742 |
+
return string
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
def package_to_inputs_dict(
|
| 746 |
+
output_dir, output_suffix, git_tag, package: str, version=None
|
| 747 |
+
):
|
| 748 |
+
"""
|
| 749 |
+
Converts `package` (*) into a tuple of:
|
| 750 |
+
|
| 751 |
+
pkg_name (without leading 'r-')
|
| 752 |
+
location (in a subdir of output_dir - may not exist - or at GitHub)
|
| 753 |
+
old_git_rev (from existing metadata, so corresponds to the *old* version)
|
| 754 |
+
metadata or None (if a recipe does *not* already exist)
|
| 755 |
+
|
| 756 |
+
(*) `package` could be:
|
| 757 |
+
1. A package name beginning (or not) with 'r-'
|
| 758 |
+
2. A GitHub URL
|
| 759 |
+
3. A file:// URL to a tarball
|
| 760 |
+
4. A relative path to a recipe from output_dir
|
| 761 |
+
5. An absolute path to a recipe (fatal unless in the output_dir hierarchy)
|
| 762 |
+
6. Any of the above ending (or not) in sep or '/'
|
| 763 |
+
|
| 764 |
+
So this function cleans all that up:
|
| 765 |
+
|
| 766 |
+
Some packages may be from GitHub but we'd like the user not to have to worry
|
| 767 |
+
about that on the command-line (for pre-existing recipes). Also, we may want
|
| 768 |
+
to get version information from them (or existing metadata to merge) so lets
|
| 769 |
+
load *all* existing recipes (later we will add or replace this metadata with
|
| 770 |
+
any that we create).
|
| 771 |
+
"""
|
| 772 |
+
if isfile(package):
|
| 773 |
+
return None
|
| 774 |
+
print("Parsing input package %s:" % package)
|
| 775 |
+
package = strip_end(package, "/")
|
| 776 |
+
package = strip_end(package, sep)
|
| 777 |
+
if "github.com" in package:
|
| 778 |
+
package = strip_end(package, ".git")
|
| 779 |
+
pkg_name = basename(package).lower()
|
| 780 |
+
pkg_name = strip_end(pkg_name, "-feedstock")
|
| 781 |
+
if output_suffix:
|
| 782 |
+
pkg_name = strip_end(pkg_name, output_suffix)
|
| 783 |
+
if pkg_name.startswith("r-"):
|
| 784 |
+
pkg_name = pkg_name[2:]
|
| 785 |
+
if package.startswith("file://"):
|
| 786 |
+
location = package.replace("file://", "")
|
| 787 |
+
pkg_filename = basename(location)
|
| 788 |
+
pkg_name = re.match(r"(.*)_(.*)", pkg_filename).group(1).lower()
|
| 789 |
+
existing_location = existing_recipe_dir(
|
| 790 |
+
output_dir, output_suffix, "r-" + pkg_name, version
|
| 791 |
+
)
|
| 792 |
+
elif isabs(package):
|
| 793 |
+
commp = commonprefix((package, output_dir))
|
| 794 |
+
if commp != output_dir:
|
| 795 |
+
raise RuntimeError(
|
| 796 |
+
f"package {package} specified with abs path outside of output-dir {output_dir}"
|
| 797 |
+
)
|
| 798 |
+
location = package
|
| 799 |
+
existing_location = existing_recipe_dir(
|
| 800 |
+
output_dir, output_suffix, "r-" + pkg_name, version
|
| 801 |
+
)
|
| 802 |
+
elif "github.com" in package:
|
| 803 |
+
location = package
|
| 804 |
+
existing_location = existing_recipe_dir(
|
| 805 |
+
output_dir, output_suffix, "r-" + pkg_name, version
|
| 806 |
+
)
|
| 807 |
+
else:
|
| 808 |
+
location = existing_location = existing_recipe_dir(
|
| 809 |
+
output_dir, output_suffix, package, version
|
| 810 |
+
)
|
| 811 |
+
m: MetaData | None
|
| 812 |
+
if existing_location:
|
| 813 |
+
try:
|
| 814 |
+
m = MetaData(existing_location)
|
| 815 |
+
except:
|
| 816 |
+
# Happens when the folder exists but contains no recipe.
|
| 817 |
+
m = None
|
| 818 |
+
else:
|
| 819 |
+
m = None
|
| 820 |
+
|
| 821 |
+
# It can still be the case that a package without 'github.com' in the location does really
|
| 822 |
+
# come from there, for that we need to inspect the existing metadata's source/git_url.
|
| 823 |
+
old_git_rev = git_tag
|
| 824 |
+
if location and m and "github.com" not in location:
|
| 825 |
+
git_url = m.get_value("source/git_url", "")
|
| 826 |
+
if "github.com" in git_url:
|
| 827 |
+
location = git_url
|
| 828 |
+
old_git_rev = m.get_value("source/git_rev", None)
|
| 829 |
+
|
| 830 |
+
vstr = "-" + version.replace("-", "_") if version else ""
|
| 831 |
+
new_location = join(output_dir, "r-" + pkg_name + vstr + output_suffix)
|
| 832 |
+
print(f".. name: {pkg_name} location: {location} new_location: {new_location}")
|
| 833 |
+
|
| 834 |
+
return {
|
| 835 |
+
"pkg-name": pkg_name,
|
| 836 |
+
"location": location,
|
| 837 |
+
"old-git-rev": old_git_rev,
|
| 838 |
+
"old-metadata": m,
|
| 839 |
+
"new-location": new_location,
|
| 840 |
+
"version": version,
|
| 841 |
+
}
|
| 842 |
+
|
| 843 |
+
|
| 844 |
+
def get_available_binaries(cran_url, details):
|
| 845 |
+
url = cran_url + "/" + details["dir"]
|
| 846 |
+
response = requests.get(url)
|
| 847 |
+
response.raise_for_status()
|
| 848 |
+
ext = details["ext"]
|
| 849 |
+
for filename in re.findall(r'<a href="([^"]*)">\1</a>', response.text):
|
| 850 |
+
if filename.endswith(ext):
|
| 851 |
+
pkg, _, ver = filename.rpartition("_")
|
| 852 |
+
ver, _, _ = ver.rpartition(ext)
|
| 853 |
+
details["binaries"].setdefault(pkg, []).append((ver, url + filename))
|
| 854 |
+
|
| 855 |
+
|
| 856 |
+
def remove_comments(template):
|
| 857 |
+
re_comment = re.compile(r"^\s*#\s")
|
| 858 |
+
lines = template.split("\n")
|
| 859 |
+
lines_no_comments = [line for line in lines if not re_comment.match(line)]
|
| 860 |
+
return "\n".join(lines_no_comments)
|
| 861 |
+
|
| 862 |
+
|
| 863 |
+
def skeletonize(
|
| 864 |
+
in_packages,
|
| 865 |
+
output_dir=".",
|
| 866 |
+
output_suffix="",
|
| 867 |
+
add_maintainer=None,
|
| 868 |
+
version=None,
|
| 869 |
+
git_tag=None,
|
| 870 |
+
cran_url=None,
|
| 871 |
+
recursive=False,
|
| 872 |
+
archive=True,
|
| 873 |
+
version_compare=False,
|
| 874 |
+
update_policy="",
|
| 875 |
+
r_interp="r-base",
|
| 876 |
+
use_binaries_ver=None,
|
| 877 |
+
use_noarch_generic=False,
|
| 878 |
+
use_when_no_binary: Literal["error" | "src" | "old" | "old-src"] = "src",
|
| 879 |
+
use_rtools_win=False,
|
| 880 |
+
config=None,
|
| 881 |
+
variant_config_files=None,
|
| 882 |
+
allow_archived=False,
|
| 883 |
+
add_cross_r_base=False,
|
| 884 |
+
no_comments=False,
|
| 885 |
+
):
|
| 886 |
+
if (
|
| 887 |
+
use_when_no_binary != "error"
|
| 888 |
+
and use_when_no_binary != "src"
|
| 889 |
+
and use_when_no_binary != "old"
|
| 890 |
+
and use_when_no_binary != "old-src"
|
| 891 |
+
):
|
| 892 |
+
print(f"ERROR: --use_when_no_binary={use_when_no_binary} not yet implemented")
|
| 893 |
+
sys.exit(1)
|
| 894 |
+
|
| 895 |
+
m: MetaData
|
| 896 |
+
|
| 897 |
+
output_dir = realpath(output_dir)
|
| 898 |
+
config = get_or_merge_config(config, variant_config_files=variant_config_files)
|
| 899 |
+
|
| 900 |
+
if allow_archived and not archive:
|
| 901 |
+
print("ERROR: --no-archive and --allow-archived conflict")
|
| 902 |
+
sys.exit(1)
|
| 903 |
+
|
| 904 |
+
if not cran_url:
|
| 905 |
+
with TemporaryDirectory() as t:
|
| 906 |
+
_variant = get_package_variants(t, config)[0]
|
| 907 |
+
cran_url = ensure_list(
|
| 908 |
+
_variant.get("cran_mirror", DEFAULT_VARIANTS["cran_mirror"])
|
| 909 |
+
)[0]
|
| 910 |
+
|
| 911 |
+
if len(in_packages) > 1 and version_compare:
|
| 912 |
+
raise ValueError("--version-compare only works with one package at a time")
|
| 913 |
+
if update_policy == "error" and not in_packages:
|
| 914 |
+
raise ValueError("At least one package must be supplied")
|
| 915 |
+
|
| 916 |
+
package_dicts = {}
|
| 917 |
+
package_list = []
|
| 918 |
+
|
| 919 |
+
cran_url = cran_url.rstrip("/")
|
| 920 |
+
|
| 921 |
+
# Get cran index lazily so we don't have to go to CRAN
|
| 922 |
+
# for a github repo or a local tarball
|
| 923 |
+
cran_index = None
|
| 924 |
+
|
| 925 |
+
cran_layout_template = {
|
| 926 |
+
"source": {
|
| 927 |
+
"selector": "{others}",
|
| 928 |
+
"dir": "src/contrib/",
|
| 929 |
+
"ext": ".tar.gz",
|
| 930 |
+
# If we had platform filters we would change this to:
|
| 931 |
+
# build_for_linux or is_github_url or is_tarfile
|
| 932 |
+
"use_this": True,
|
| 933 |
+
},
|
| 934 |
+
"win-64": {
|
| 935 |
+
"selector": "win64",
|
| 936 |
+
"dir": f"bin/windows/contrib/{use_binaries_ver}/",
|
| 937 |
+
"ext": ".zip",
|
| 938 |
+
"use_this": True if use_binaries_ver else False,
|
| 939 |
+
},
|
| 940 |
+
"osx-64": {
|
| 941 |
+
"selector": "osx",
|
| 942 |
+
"dir": f"bin/macosx/el-capitan/contrib/{use_binaries_ver}/",
|
| 943 |
+
"ext": ".tgz",
|
| 944 |
+
"use_this": True if use_binaries_ver else False,
|
| 945 |
+
},
|
| 946 |
+
}
|
| 947 |
+
|
| 948 |
+
# Figure out what binaries are available once:
|
| 949 |
+
for archive_type, archive_details in cran_layout_template.items():
|
| 950 |
+
archive_details["binaries"] = dict()
|
| 951 |
+
if archive_type != "source" and archive_details["use_this"]:
|
| 952 |
+
get_available_binaries(cran_url, archive_details)
|
| 953 |
+
|
| 954 |
+
for package in in_packages:
|
| 955 |
+
inputs_dict = package_to_inputs_dict(
|
| 956 |
+
output_dir, output_suffix, git_tag, package, version
|
| 957 |
+
)
|
| 958 |
+
if inputs_dict:
|
| 959 |
+
package_dicts.update({inputs_dict["pkg-name"]: {"inputs": inputs_dict}})
|
| 960 |
+
|
| 961 |
+
for package_name, package_dict in package_dicts.items():
|
| 962 |
+
package_list.append(package_name)
|
| 963 |
+
|
| 964 |
+
while package_list:
|
| 965 |
+
inputs = package_dicts[package_list.pop()]["inputs"]
|
| 966 |
+
location = inputs["location"]
|
| 967 |
+
pkg_name = inputs["pkg-name"]
|
| 968 |
+
version = inputs["version"]
|
| 969 |
+
is_github_url = location and "github.com" in location
|
| 970 |
+
is_tarfile = location and isfile(location) and tarfile.is_tarfile(location)
|
| 971 |
+
is_archive = False
|
| 972 |
+
url = inputs["location"]
|
| 973 |
+
|
| 974 |
+
dir_path = inputs["new-location"]
|
| 975 |
+
print(f"Making/refreshing recipe for {pkg_name}")
|
| 976 |
+
|
| 977 |
+
# Bodges GitHub packages into cran_metadata
|
| 978 |
+
if is_tarfile:
|
| 979 |
+
cran_package = get_archive_metadata(location)
|
| 980 |
+
|
| 981 |
+
elif is_github_url or is_tarfile:
|
| 982 |
+
rm_rf(config.work_dir)
|
| 983 |
+
m = MetaData.fromdict({"source": {"git_url": location}}, config=config)
|
| 984 |
+
source.git_source(
|
| 985 |
+
m.get_section("source"), m.config.git_cache, m.config.work_dir
|
| 986 |
+
)
|
| 987 |
+
new_git_tag = git_tag if git_tag else get_latest_git_tag(config)
|
| 988 |
+
p = subprocess.Popen(
|
| 989 |
+
["git", "checkout", new_git_tag],
|
| 990 |
+
stdout=subprocess.PIPE,
|
| 991 |
+
stderr=subprocess.PIPE,
|
| 992 |
+
cwd=config.work_dir,
|
| 993 |
+
)
|
| 994 |
+
stdout, stderr = p.communicate()
|
| 995 |
+
stdout = stdout.decode("utf-8")
|
| 996 |
+
stderr = stderr.decode("utf-8")
|
| 997 |
+
if p.returncode:
|
| 998 |
+
sys.exit(
|
| 999 |
+
f"Error: 'git checkout {new_git_tag}' failed ({stderr.strip()}).\n"
|
| 1000 |
+
"Invalid tag?"
|
| 1001 |
+
)
|
| 1002 |
+
if stdout:
|
| 1003 |
+
print(stdout, file=sys.stdout)
|
| 1004 |
+
if stderr:
|
| 1005 |
+
print(stderr, file=sys.stderr)
|
| 1006 |
+
DESCRIPTION = join(config.work_dir, "DESCRIPTION")
|
| 1007 |
+
if not isfile(DESCRIPTION):
|
| 1008 |
+
sub_description_pkg = join(config.work_dir, "pkg", "DESCRIPTION")
|
| 1009 |
+
sub_description_name = join(
|
| 1010 |
+
config.work_dir, location.split("/")[-1], "DESCRIPTION"
|
| 1011 |
+
)
|
| 1012 |
+
if isfile(sub_description_pkg):
|
| 1013 |
+
DESCRIPTION = sub_description_pkg
|
| 1014 |
+
elif isfile(sub_description_name):
|
| 1015 |
+
DESCRIPTION = sub_description_name
|
| 1016 |
+
else:
|
| 1017 |
+
sys.exit(
|
| 1018 |
+
f"{location} does not appear to be a valid R package "
|
| 1019 |
+
f"(no DESCRIPTION file in {sub_description_pkg}, {sub_description_name})"
|
| 1020 |
+
)
|
| 1021 |
+
cran_package = get_archive_metadata(DESCRIPTION)
|
| 1022 |
+
|
| 1023 |
+
else:
|
| 1024 |
+
if cran_index is None:
|
| 1025 |
+
session = get_session(output_dir)
|
| 1026 |
+
cran_index = get_cran_index(cran_url, session)
|
| 1027 |
+
if pkg_name.lower() not in cran_index:
|
| 1028 |
+
sys.exit("Package %s not found" % pkg_name)
|
| 1029 |
+
package, cran_version = cran_index[pkg_name.lower()]
|
| 1030 |
+
if cran_version and (not version or version == cran_version):
|
| 1031 |
+
version = cran_version
|
| 1032 |
+
elif version and not archive:
|
| 1033 |
+
print(
|
| 1034 |
+
f"ERROR: Version {version} of package {package} is archived, but --no-archive was selected"
|
| 1035 |
+
)
|
| 1036 |
+
sys.exit(1)
|
| 1037 |
+
elif not version and not cran_version and not allow_archived:
|
| 1038 |
+
print(
|
| 1039 |
+
"ERROR: Package %s is archived; to build, use --allow-archived or a --version value"
|
| 1040 |
+
% pkg_name
|
| 1041 |
+
)
|
| 1042 |
+
sys.exit(1)
|
| 1043 |
+
else:
|
| 1044 |
+
is_archive = True
|
| 1045 |
+
all_versions = get_cran_archive_versions(cran_url, session, package)
|
| 1046 |
+
if cran_version:
|
| 1047 |
+
all_versions = [cran_version] + all_versions
|
| 1048 |
+
if not version:
|
| 1049 |
+
version = all_versions[0]
|
| 1050 |
+
elif version not in all_versions:
|
| 1051 |
+
msg = f"ERROR: Version {version} of package {package} not found.\n Available versions: "
|
| 1052 |
+
print(msg + ", ".join(all_versions))
|
| 1053 |
+
sys.exit(1)
|
| 1054 |
+
cran_package = None
|
| 1055 |
+
|
| 1056 |
+
if cran_package is not None:
|
| 1057 |
+
package = cran_package["Package"]
|
| 1058 |
+
version = cran_package["Version"]
|
| 1059 |
+
plower = package.lower()
|
| 1060 |
+
d = package_dicts[pkg_name]
|
| 1061 |
+
d.update(
|
| 1062 |
+
{
|
| 1063 |
+
"cran_packagename": package,
|
| 1064 |
+
"cran_version": version,
|
| 1065 |
+
"packagename": "r-" + plower,
|
| 1066 |
+
# Conda versions cannot have -. Conda (verlib) will treat _ as a .
|
| 1067 |
+
"conda_version": version.replace("-", "_"),
|
| 1068 |
+
"patches": "",
|
| 1069 |
+
"build_number": 0,
|
| 1070 |
+
"build_depends": "",
|
| 1071 |
+
"host_depends": "",
|
| 1072 |
+
"run_depends": "",
|
| 1073 |
+
# CRAN doesn't seem to have this metadata :(
|
| 1074 |
+
"home_comment": "#",
|
| 1075 |
+
"homeurl": "",
|
| 1076 |
+
"summary_comment": "#",
|
| 1077 |
+
"summary": "",
|
| 1078 |
+
"binary1": "",
|
| 1079 |
+
"binary2": "",
|
| 1080 |
+
}
|
| 1081 |
+
)
|
| 1082 |
+
|
| 1083 |
+
if version_compare:
|
| 1084 |
+
sys.exit(not version_compare(dir_path, d["conda_version"]))
|
| 1085 |
+
|
| 1086 |
+
patches = []
|
| 1087 |
+
script_env = []
|
| 1088 |
+
extra_recipe_maintainers = []
|
| 1089 |
+
build_number = 0
|
| 1090 |
+
if update_policy.startswith("merge") and inputs["old-metadata"]:
|
| 1091 |
+
m = inputs["old-metadata"]
|
| 1092 |
+
patches = make_array(m, "source/patches")
|
| 1093 |
+
script_env = make_array(m, "build/script_env")
|
| 1094 |
+
extra_recipe_maintainers = make_array(
|
| 1095 |
+
m, "extra/recipe-maintainers", add_maintainer
|
| 1096 |
+
)
|
| 1097 |
+
if m.version() == d["conda_version"]:
|
| 1098 |
+
build_number = m.build_number()
|
| 1099 |
+
build_number += 1 if update_policy == "merge-incr-build-num" else 0
|
| 1100 |
+
if add_maintainer:
|
| 1101 |
+
new_maintainer = f"{INDENT}{add_maintainer}"
|
| 1102 |
+
if new_maintainer not in extra_recipe_maintainers:
|
| 1103 |
+
if not len(extra_recipe_maintainers):
|
| 1104 |
+
# We hit this case when there is no existing recipe.
|
| 1105 |
+
extra_recipe_maintainers = make_array(
|
| 1106 |
+
{}, "extra/recipe-maintainers", True
|
| 1107 |
+
)
|
| 1108 |
+
extra_recipe_maintainers.append(new_maintainer)
|
| 1109 |
+
if len(extra_recipe_maintainers):
|
| 1110 |
+
extra_recipe_maintainers[1:].sort()
|
| 1111 |
+
extra_recipe_maintainers.insert(0, "extra:\n ")
|
| 1112 |
+
d["extra_recipe_maintainers"] = "".join(extra_recipe_maintainers)
|
| 1113 |
+
d["patches"] = "".join(patches)
|
| 1114 |
+
d["script_env"] = "".join(script_env)
|
| 1115 |
+
d["build_number"] = build_number
|
| 1116 |
+
|
| 1117 |
+
cached_path = None
|
| 1118 |
+
cran_layout = copy.deepcopy(cran_layout_template)
|
| 1119 |
+
available = {}
|
| 1120 |
+
|
| 1121 |
+
description_path = None
|
| 1122 |
+
for archive_type, archive_details in cran_layout.items():
|
| 1123 |
+
contrib_url = ""
|
| 1124 |
+
archive_details["cran_version"] = d["cran_version"]
|
| 1125 |
+
archive_details["conda_version"] = d["conda_version"]
|
| 1126 |
+
if is_archive and archive_type == "source":
|
| 1127 |
+
archive_details["dir"] += "Archive/" + package + "/"
|
| 1128 |
+
available_artefact = (
|
| 1129 |
+
True
|
| 1130 |
+
if archive_type == "source"
|
| 1131 |
+
else package in archive_details["binaries"]
|
| 1132 |
+
and any(
|
| 1133 |
+
d["cran_version"] == v
|
| 1134 |
+
for v, _ in archive_details["binaries"][package]
|
| 1135 |
+
)
|
| 1136 |
+
)
|
| 1137 |
+
if not available_artefact:
|
| 1138 |
+
if use_when_no_binary == "error":
|
| 1139 |
+
print(
|
| 1140 |
+
"ERROR: --use-when-no-binary is error (and there is no binary)"
|
| 1141 |
+
)
|
| 1142 |
+
sys.exit(1)
|
| 1143 |
+
elif use_when_no_binary.startswith("old"):
|
| 1144 |
+
if package not in archive_details["binaries"]:
|
| 1145 |
+
if use_when_no_binary.endswith("src"):
|
| 1146 |
+
available_artefact = False
|
| 1147 |
+
archive_details["use_this"] = False
|
| 1148 |
+
continue
|
| 1149 |
+
else:
|
| 1150 |
+
print(
|
| 1151 |
+
"ERROR: No binary nor old binary found "
|
| 1152 |
+
"(maybe pass --use-when-no-binary=old-src to fallback to source?)"
|
| 1153 |
+
)
|
| 1154 |
+
sys.exit(1)
|
| 1155 |
+
# Version needs to be stored in archive_details.
|
| 1156 |
+
archive_details["cranurl"] = archive_details["binaries"][package][
|
| 1157 |
+
-1
|
| 1158 |
+
][1]
|
| 1159 |
+
archive_details["conda_version"] = archive_details["binaries"][
|
| 1160 |
+
package
|
| 1161 |
+
][-1][0]
|
| 1162 |
+
archive_details["cran_version"] = archive_details[
|
| 1163 |
+
"conda_version"
|
| 1164 |
+
].replace("_", "-")
|
| 1165 |
+
available_artefact = True
|
| 1166 |
+
# We may need to inspect the file later to determine which compilers are needed.
|
| 1167 |
+
cached_path = None
|
| 1168 |
+
sha256 = hashlib.sha256()
|
| 1169 |
+
if archive_details["use_this"] and available_artefact:
|
| 1170 |
+
if is_tarfile:
|
| 1171 |
+
filename = basename(location)
|
| 1172 |
+
contrib_url = relpath(location, dir_path)
|
| 1173 |
+
contrib_url_rendered = package_url = contrib_url
|
| 1174 |
+
cached_path = location
|
| 1175 |
+
elif not is_github_url or archive_type != "source":
|
| 1176 |
+
filename_rendered = "{}_{}{}".format(
|
| 1177 |
+
package, archive_details["cran_version"], archive_details["ext"]
|
| 1178 |
+
)
|
| 1179 |
+
filename = f"{package}_{{{{ version }}}}" + archive_details["ext"]
|
| 1180 |
+
contrib_url = "{{{{ cran_mirror }}}}/{}".format(
|
| 1181 |
+
archive_details["dir"]
|
| 1182 |
+
)
|
| 1183 |
+
contrib_url_rendered = cran_url + "/{}".format(
|
| 1184 |
+
archive_details["dir"]
|
| 1185 |
+
)
|
| 1186 |
+
package_url = contrib_url_rendered + filename_rendered
|
| 1187 |
+
print(f"Downloading {archive_type} from {package_url}")
|
| 1188 |
+
try:
|
| 1189 |
+
cached_path, _ = source.download_to_cache(
|
| 1190 |
+
config.src_cache,
|
| 1191 |
+
"",
|
| 1192 |
+
{
|
| 1193 |
+
"url": package_url,
|
| 1194 |
+
"fn": archive_type + "-" + filename_rendered,
|
| 1195 |
+
},
|
| 1196 |
+
)
|
| 1197 |
+
except:
|
| 1198 |
+
print(
|
| 1199 |
+
f"logic error, file {package_url} should exist, we found it in a dir listing earlier."
|
| 1200 |
+
)
|
| 1201 |
+
sys.exit(1)
|
| 1202 |
+
if description_path is None or archive_type == "source":
|
| 1203 |
+
description_path = cached_path
|
| 1204 |
+
available_details = {}
|
| 1205 |
+
available_details["selector"] = archive_details["selector"]
|
| 1206 |
+
available_details["cran_version"] = archive_details["cran_version"]
|
| 1207 |
+
available_details["conda_version"] = archive_details["conda_version"]
|
| 1208 |
+
if cached_path:
|
| 1209 |
+
sha256.update(open(cached_path, "rb").read())
|
| 1210 |
+
archive_details["cranurl"] = package_url
|
| 1211 |
+
available_details["filename"] = filename
|
| 1212 |
+
available_details["contrib_url"] = contrib_url
|
| 1213 |
+
available_details["contrib_url_rendered"] = contrib_url_rendered
|
| 1214 |
+
available_details["hash_entry"] = f"sha256: {sha256.hexdigest()}"
|
| 1215 |
+
available_details["cached_path"] = cached_path
|
| 1216 |
+
# This is rubbish; d[] should be renamed global[] and should be
|
| 1217 |
+
# merged into source and binaryN.
|
| 1218 |
+
if archive_type == "source":
|
| 1219 |
+
if is_github_url:
|
| 1220 |
+
available_details["url_key"] = ""
|
| 1221 |
+
available_details["git_url_key"] = "git_url:"
|
| 1222 |
+
available_details["git_tag_key"] = "git_tag:"
|
| 1223 |
+
hash_msg = "# You can add a hash for the file here, (md5, sha1 or sha256)"
|
| 1224 |
+
available_details["hash_entry"] = hash_msg
|
| 1225 |
+
available_details["filename"] = ""
|
| 1226 |
+
available_details["cranurl"] = ""
|
| 1227 |
+
available_details["git_url"] = url
|
| 1228 |
+
available_details["git_tag"] = new_git_tag
|
| 1229 |
+
available_details["archive_keys"] = ""
|
| 1230 |
+
else:
|
| 1231 |
+
available_details["url_key"] = "url:"
|
| 1232 |
+
available_details["git_url_key"] = ""
|
| 1233 |
+
available_details["git_tag_key"] = ""
|
| 1234 |
+
available_details["cranurl"] = " " + contrib_url + filename
|
| 1235 |
+
available_details["git_url"] = ""
|
| 1236 |
+
available_details["git_tag"] = ""
|
| 1237 |
+
else:
|
| 1238 |
+
available_details["cranurl"] = archive_details["cranurl"]
|
| 1239 |
+
|
| 1240 |
+
available_details["patches"] = d["patches"]
|
| 1241 |
+
available[archive_type] = available_details
|
| 1242 |
+
|
| 1243 |
+
# Figure out the selectors according to what is available.
|
| 1244 |
+
_all = ["linux", "win32", "win64", "osx"]
|
| 1245 |
+
from_source = _all[:]
|
| 1246 |
+
binary_id = 1
|
| 1247 |
+
for archive_type, archive_details in available.items():
|
| 1248 |
+
if archive_type == "source":
|
| 1249 |
+
for k, v in archive_details.items():
|
| 1250 |
+
d[k] = v
|
| 1251 |
+
else:
|
| 1252 |
+
sel = archive_details["selector"]
|
| 1253 |
+
# Does the file exist? If not we need to build from source.
|
| 1254 |
+
from_source.remove(sel)
|
| 1255 |
+
binary_id += 1
|
| 1256 |
+
if from_source == _all:
|
| 1257 |
+
sel_src = ""
|
| 1258 |
+
sel_src_and_win = " # [win]"
|
| 1259 |
+
sel_src_not_win = " # [not win]"
|
| 1260 |
+
else:
|
| 1261 |
+
sel_src = " # [" + " or ".join(from_source) + "]"
|
| 1262 |
+
sel_src_and_win = (
|
| 1263 |
+
" # ["
|
| 1264 |
+
+ " or ".join(fs for fs in from_source if fs.startswith("win"))
|
| 1265 |
+
+ "]"
|
| 1266 |
+
)
|
| 1267 |
+
sel_src_not_win = (
|
| 1268 |
+
" # ["
|
| 1269 |
+
+ " or ".join(fs for fs in from_source if not fs.startswith("win"))
|
| 1270 |
+
+ "]"
|
| 1271 |
+
)
|
| 1272 |
+
sel_cross = " # [build_platform != target_platform]"
|
| 1273 |
+
d["sel_src"] = sel_src
|
| 1274 |
+
d["sel_src_and_win"] = sel_src_and_win
|
| 1275 |
+
d["sel_src_not_win"] = sel_src_not_win
|
| 1276 |
+
d["from_source"] = from_source
|
| 1277 |
+
|
| 1278 |
+
if "source" in available:
|
| 1279 |
+
available_details = available["source"]
|
| 1280 |
+
available_details["sel"] = sel_src
|
| 1281 |
+
filename = available_details["filename"]
|
| 1282 |
+
if "contrib_url" in available_details:
|
| 1283 |
+
contrib_url = available_details["contrib_url"]
|
| 1284 |
+
if archive:
|
| 1285 |
+
if is_tarfile:
|
| 1286 |
+
available_details["cranurl"] = INDENT + contrib_url
|
| 1287 |
+
elif not is_archive:
|
| 1288 |
+
available_details["cranurl"] = (
|
| 1289 |
+
INDENT
|
| 1290 |
+
+ contrib_url
|
| 1291 |
+
+ filename
|
| 1292 |
+
+ sel_src
|
| 1293 |
+
+ INDENT
|
| 1294 |
+
+ contrib_url
|
| 1295 |
+
+ f"Archive/{package}/"
|
| 1296 |
+
+ filename
|
| 1297 |
+
+ sel_src
|
| 1298 |
+
)
|
| 1299 |
+
else:
|
| 1300 |
+
available_details["cranurl"] = (
|
| 1301 |
+
" " + contrib_url + filename + sel_src
|
| 1302 |
+
)
|
| 1303 |
+
if not is_github_url:
|
| 1304 |
+
available_details["archive_keys"] = (
|
| 1305 |
+
"{url_key}{sel} {cranurl}\n {hash_entry}{sel}"
|
| 1306 |
+
).format(**available_details)
|
| 1307 |
+
|
| 1308 |
+
# Extract the DESCRIPTION data from the source
|
| 1309 |
+
if cran_package is None:
|
| 1310 |
+
cran_package = get_archive_metadata(description_path)
|
| 1311 |
+
d["cran_metadata"] = "\n".join(
|
| 1312 |
+
["# %s" % line for line in cran_package["orig_lines"] if line]
|
| 1313 |
+
)
|
| 1314 |
+
|
| 1315 |
+
# Render the source and binaryN keys
|
| 1316 |
+
binary_id = 1
|
| 1317 |
+
d["version_binary1"] = d["version_binary2"] = ""
|
| 1318 |
+
for archive_type, archive_details in available.items():
|
| 1319 |
+
if archive_type == "source":
|
| 1320 |
+
d["source"] = SOURCE_META.format(**archive_details)
|
| 1321 |
+
d["version_source"] = VERSION_META.format(**archive_details)
|
| 1322 |
+
else:
|
| 1323 |
+
archive_details["sel"] = " # [" + archive_details["selector"] + "]"
|
| 1324 |
+
d["binary" + str(binary_id)] = BINARY_META.format(**archive_details)
|
| 1325 |
+
d["version_binary" + str(binary_id)] = VERSION_META.format(
|
| 1326 |
+
**archive_details
|
| 1327 |
+
)
|
| 1328 |
+
binary_id += 1
|
| 1329 |
+
|
| 1330 |
+
license_info = get_license_info(
|
| 1331 |
+
cran_package.get("License", "None"), allowed_license_families
|
| 1332 |
+
)
|
| 1333 |
+
d["license"], d["license_file"], d["license_family"] = license_info
|
| 1334 |
+
|
| 1335 |
+
if "License_is_FOSS" in cran_package:
|
| 1336 |
+
d["license"] += " (FOSS)"
|
| 1337 |
+
if cran_package.get("License_restricts_use") == "yes":
|
| 1338 |
+
d["license"] += " (Restricts use)"
|
| 1339 |
+
|
| 1340 |
+
if "URL" in cran_package:
|
| 1341 |
+
d["home_comment"] = ""
|
| 1342 |
+
d["homeurl"] = " " + yaml_quote_string(cran_package["URL"])
|
| 1343 |
+
else:
|
| 1344 |
+
# use CRAN page as homepage if nothing has been specified
|
| 1345 |
+
d["home_comment"] = ""
|
| 1346 |
+
if is_github_url:
|
| 1347 |
+
d["homeurl"] = f" {location}"
|
| 1348 |
+
else:
|
| 1349 |
+
d["homeurl"] = f" https://CRAN.R-project.org/package={package}"
|
| 1350 |
+
|
| 1351 |
+
if (
|
| 1352 |
+
not use_noarch_generic
|
| 1353 |
+
or cran_package.get("NeedsCompilation", "no") == "yes"
|
| 1354 |
+
):
|
| 1355 |
+
d["noarch_generic"] = ""
|
| 1356 |
+
else:
|
| 1357 |
+
d["noarch_generic"] = "noarch: generic"
|
| 1358 |
+
|
| 1359 |
+
if "Description" in cran_package:
|
| 1360 |
+
d["summary_comment"] = ""
|
| 1361 |
+
d["summary"] = " " + yaml_quote_string(cran_package["Description"])
|
| 1362 |
+
|
| 1363 |
+
if "Suggests" in cran_package and not no_comments:
|
| 1364 |
+
d["suggests"] = "# Suggests: %s" % cran_package["Suggests"]
|
| 1365 |
+
else:
|
| 1366 |
+
d["suggests"] = ""
|
| 1367 |
+
|
| 1368 |
+
# Every package depends on at least R.
|
| 1369 |
+
# I'm not sure what the difference between depends and imports is.
|
| 1370 |
+
depends = [
|
| 1371 |
+
s.strip() for s in cran_package.get("Depends", "").split(",") if s.strip()
|
| 1372 |
+
]
|
| 1373 |
+
imports = [
|
| 1374 |
+
s.strip() for s in cran_package.get("Imports", "").split(",") if s.strip()
|
| 1375 |
+
]
|
| 1376 |
+
links = [
|
| 1377 |
+
s.strip() for s in cran_package.get("LinkingTo", "").split(",") if s.strip()
|
| 1378 |
+
]
|
| 1379 |
+
|
| 1380 |
+
dep_dict = {}
|
| 1381 |
+
|
| 1382 |
+
seen = set()
|
| 1383 |
+
for s in list(chain(imports, depends, links)):
|
| 1384 |
+
match = VERSION_DEPENDENCY_REGEX.match(s)
|
| 1385 |
+
if not match:
|
| 1386 |
+
sys.exit(f"Could not parse version from dependency of {package}: {s}")
|
| 1387 |
+
name = match.group("name")
|
| 1388 |
+
if name in seen:
|
| 1389 |
+
continue
|
| 1390 |
+
seen.add(name)
|
| 1391 |
+
archs = match.group("archs")
|
| 1392 |
+
relop = match.group("relop") or ""
|
| 1393 |
+
ver = match.group("version") or ""
|
| 1394 |
+
ver = ver.replace("-", "_")
|
| 1395 |
+
# If there is a relop there should be a version
|
| 1396 |
+
assert not relop or ver
|
| 1397 |
+
|
| 1398 |
+
if archs:
|
| 1399 |
+
sys.exit(
|
| 1400 |
+
"Don't know how to handle archs from dependency of "
|
| 1401 |
+
f"package {package}: {s}"
|
| 1402 |
+
)
|
| 1403 |
+
|
| 1404 |
+
dep_dict[name] = f"{relop}{ver}"
|
| 1405 |
+
|
| 1406 |
+
if "R" not in dep_dict:
|
| 1407 |
+
dep_dict["R"] = ""
|
| 1408 |
+
|
| 1409 |
+
os_type = cran_package.get("OS_type", "")
|
| 1410 |
+
if os_type != "unix" and os_type != "windows" and os_type != "":
|
| 1411 |
+
print(f"Unknown OS_type: {os_type} in CRAN package")
|
| 1412 |
+
os_type = ""
|
| 1413 |
+
if os_type == "unix":
|
| 1414 |
+
d["skip_os"] = "skip: True # [not unix]"
|
| 1415 |
+
d["noarch_generic"] = ""
|
| 1416 |
+
if os_type == "windows":
|
| 1417 |
+
d["skip_os"] = "skip: True # [not win]"
|
| 1418 |
+
d["noarch_generic"] = ""
|
| 1419 |
+
if os_type == "" and no_comments:
|
| 1420 |
+
d["skip_os"] = ""
|
| 1421 |
+
elif os_type == "":
|
| 1422 |
+
d["skip_os"] = "# no skip"
|
| 1423 |
+
|
| 1424 |
+
need_git = is_github_url
|
| 1425 |
+
if cran_package.get("NeedsCompilation", "no") == "yes":
|
| 1426 |
+
with tarfile.open(available["source"]["cached_path"]) as tf:
|
| 1427 |
+
need_f = any(
|
| 1428 |
+
[
|
| 1429 |
+
f.name.lower().endswith((".f", ".f90", ".f77", ".f95", ".f03"))
|
| 1430 |
+
for f in tf
|
| 1431 |
+
]
|
| 1432 |
+
)
|
| 1433 |
+
# Fortran builds use CC to perform the link (they do not call the linker directly).
|
| 1434 |
+
need_c = (
|
| 1435 |
+
True if need_f else any([f.name.lower().endswith(".c") for f in tf])
|
| 1436 |
+
)
|
| 1437 |
+
need_cxx = any(
|
| 1438 |
+
[
|
| 1439 |
+
f.name.lower().endswith((".cxx", ".cpp", ".cc", ".c++"))
|
| 1440 |
+
for f in tf
|
| 1441 |
+
]
|
| 1442 |
+
)
|
| 1443 |
+
need_autotools = any(
|
| 1444 |
+
[f.name.lower().endswith("/configure") for f in tf]
|
| 1445 |
+
)
|
| 1446 |
+
need_make = (
|
| 1447 |
+
True
|
| 1448 |
+
if any((need_autotools, need_f, need_cxx, need_c))
|
| 1449 |
+
else any(
|
| 1450 |
+
[
|
| 1451 |
+
f.name.lower().endswith(("/makefile", "/makevars"))
|
| 1452 |
+
for f in tf
|
| 1453 |
+
]
|
| 1454 |
+
)
|
| 1455 |
+
)
|
| 1456 |
+
else:
|
| 1457 |
+
need_c = need_cxx = need_f = need_autotools = need_make = False
|
| 1458 |
+
|
| 1459 |
+
if "Rcpp" in dep_dict or "RcppArmadillo" in dep_dict:
|
| 1460 |
+
need_cxx = True
|
| 1461 |
+
|
| 1462 |
+
if need_cxx:
|
| 1463 |
+
need_c = True
|
| 1464 |
+
|
| 1465 |
+
for dep_type in ["build", "host", "run"]:
|
| 1466 |
+
deps = []
|
| 1467 |
+
# Put non-R dependencies first.
|
| 1468 |
+
if dep_type == "build":
|
| 1469 |
+
if need_c:
|
| 1470 |
+
deps.append(
|
| 1471 |
+
f"{INDENT}{{{{ compiler('c') }}}} {sel_src_not_win}"
|
| 1472 |
+
)
|
| 1473 |
+
deps.append(
|
| 1474 |
+
f"{INDENT}{{{{ compiler('m2w64_c') }}}} {sel_src_and_win}"
|
| 1475 |
+
)
|
| 1476 |
+
if need_cxx:
|
| 1477 |
+
deps.append(
|
| 1478 |
+
f"{INDENT}{{{{ compiler('cxx') }}}} {sel_src_not_win}"
|
| 1479 |
+
)
|
| 1480 |
+
deps.append(
|
| 1481 |
+
f"{INDENT}{{{{ compiler('m2w64_cxx') }}}} {sel_src_and_win}"
|
| 1482 |
+
)
|
| 1483 |
+
if need_f:
|
| 1484 |
+
deps.append(
|
| 1485 |
+
f"{INDENT}{{{{ compiler('fortran') }}}} {sel_src_not_win}"
|
| 1486 |
+
)
|
| 1487 |
+
deps.append(
|
| 1488 |
+
f"{INDENT}{{{{ compiler('m2w64_fortran') }}}}{sel_src_and_win}"
|
| 1489 |
+
)
|
| 1490 |
+
if use_rtools_win:
|
| 1491 |
+
need_c = need_cxx = need_f = need_autotools = need_make = False
|
| 1492 |
+
deps.append(f"{INDENT}rtools {sel_src_and_win}")
|
| 1493 |
+
# extsoft is legacy. R packages will download rwinlib subprojects
|
| 1494 |
+
# as necessary according to Jeroen Ooms. (may need to disable that
|
| 1495 |
+
# for non-MRO builds or maybe switch to Jeroen's toolchain?)
|
| 1496 |
+
# deps.append("{indent}{{{{native}}}}extsoft {sel}".format(
|
| 1497 |
+
# indent=INDENT, sel=sel_src_and_win))
|
| 1498 |
+
if need_autotools or need_make or need_git:
|
| 1499 |
+
deps.append(
|
| 1500 |
+
f"{INDENT}{{{{ posix }}}}filesystem {sel_src_and_win}"
|
| 1501 |
+
)
|
| 1502 |
+
if need_git:
|
| 1503 |
+
deps.append(f"{INDENT}{{{{ posix }}}}git")
|
| 1504 |
+
if need_autotools:
|
| 1505 |
+
deps.append(
|
| 1506 |
+
f"{INDENT}{{{{ posix }}}}sed {sel_src_and_win}"
|
| 1507 |
+
)
|
| 1508 |
+
deps.append(
|
| 1509 |
+
f"{INDENT}{{{{ posix }}}}grep {sel_src_and_win}"
|
| 1510 |
+
)
|
| 1511 |
+
deps.append(f"{INDENT}{{{{ posix }}}}autoconf {sel_src}")
|
| 1512 |
+
deps.append(
|
| 1513 |
+
f"{INDENT}{{{{ posix }}}}automake {sel_src_not_win}"
|
| 1514 |
+
)
|
| 1515 |
+
deps.append(
|
| 1516 |
+
f"{INDENT}{{{{ posix }}}}automake-wrapper{sel_src_and_win}"
|
| 1517 |
+
)
|
| 1518 |
+
deps.append(f"{INDENT}{{{{ posix }}}}pkg-config")
|
| 1519 |
+
if need_make:
|
| 1520 |
+
deps.append(f"{INDENT}{{{{ posix }}}}make {sel_src}")
|
| 1521 |
+
if not need_autotools:
|
| 1522 |
+
deps.append(
|
| 1523 |
+
f"{INDENT}{{{{ posix }}}}sed {sel_src_and_win}"
|
| 1524 |
+
)
|
| 1525 |
+
deps.append(
|
| 1526 |
+
f"{INDENT}{{{{ posix }}}}coreutils {sel_src_and_win}"
|
| 1527 |
+
)
|
| 1528 |
+
deps.append(f"{INDENT}{{{{ posix }}}}zip {sel_src_and_win}")
|
| 1529 |
+
if add_cross_r_base:
|
| 1530 |
+
deps.append(f"{INDENT}cross-r-base {{{{ r_base }}}} {sel_cross}")
|
| 1531 |
+
elif dep_type == "run":
|
| 1532 |
+
if need_c or need_cxx or need_f:
|
| 1533 |
+
deps.append(
|
| 1534 |
+
f"{INDENT}{{{{native}}}}gcc-libs {sel_src_and_win}"
|
| 1535 |
+
)
|
| 1536 |
+
|
| 1537 |
+
if dep_type == "host" or dep_type == "run":
|
| 1538 |
+
for name in sorted(dep_dict):
|
| 1539 |
+
if name in R_BASE_PACKAGE_NAMES:
|
| 1540 |
+
continue
|
| 1541 |
+
if name == "R":
|
| 1542 |
+
# Put R first
|
| 1543 |
+
# Regarless of build or run, and whether this is a
|
| 1544 |
+
# recommended package or not, it can only depend on
|
| 1545 |
+
# r_interp since anything else can and will cause
|
| 1546 |
+
# cycles in the dependency graph. The cran metadata
|
| 1547 |
+
# lists all dependencies anyway, even those packages
|
| 1548 |
+
# that are in the recommended group.
|
| 1549 |
+
# We don't include any R version restrictions because
|
| 1550 |
+
# conda-build always pins r-base and mro-base version.
|
| 1551 |
+
deps.insert(0, f"{INDENT}{r_interp}")
|
| 1552 |
+
else:
|
| 1553 |
+
conda_name = "r-" + name.lower()
|
| 1554 |
+
|
| 1555 |
+
if dep_dict[name]:
|
| 1556 |
+
deps.append(f"{INDENT}{conda_name} {dep_dict[name]}")
|
| 1557 |
+
else:
|
| 1558 |
+
deps.append(f"{INDENT}{conda_name}")
|
| 1559 |
+
if recursive:
|
| 1560 |
+
lower_name = name.lower()
|
| 1561 |
+
if lower_name not in package_dicts:
|
| 1562 |
+
inputs_dict = package_to_inputs_dict(
|
| 1563 |
+
output_dir, output_suffix, git_tag, lower_name, None
|
| 1564 |
+
)
|
| 1565 |
+
assert (
|
| 1566 |
+
lower_name == inputs_dict["pkg-name"]
|
| 1567 |
+
), "name {} != inputs_dict['pkg-name'] {}".format(
|
| 1568 |
+
name, inputs_dict["pkg-name"]
|
| 1569 |
+
)
|
| 1570 |
+
assert lower_name not in package_list
|
| 1571 |
+
package_dicts.update(
|
| 1572 |
+
{lower_name: {"inputs": inputs_dict}}
|
| 1573 |
+
)
|
| 1574 |
+
package_list.append(lower_name)
|
| 1575 |
+
|
| 1576 |
+
d["%s_depends" % dep_type] = "".join(deps)
|
| 1577 |
+
|
| 1578 |
+
if no_comments:
|
| 1579 |
+
global CRAN_BUILD_SH_SOURCE, CRAN_META
|
| 1580 |
+
CRAN_BUILD_SH_SOURCE = remove_comments(CRAN_BUILD_SH_SOURCE)
|
| 1581 |
+
CRAN_META = remove_comments(CRAN_META)
|
| 1582 |
+
|
| 1583 |
+
for package in package_dicts:
|
| 1584 |
+
d = package_dicts[package]
|
| 1585 |
+
dir_path = d["inputs"]["new-location"]
|
| 1586 |
+
if exists(dir_path) and not version_compare:
|
| 1587 |
+
if update_policy == "error":
|
| 1588 |
+
raise RuntimeError(
|
| 1589 |
+
"directory already exists "
|
| 1590 |
+
"(and --update-policy is 'error'): %s" % dir_path
|
| 1591 |
+
)
|
| 1592 |
+
elif update_policy == "overwrite":
|
| 1593 |
+
rm_rf(dir_path)
|
| 1594 |
+
elif update_policy == "skip-up-to-date":
|
| 1595 |
+
if cran_index is None:
|
| 1596 |
+
session = get_session(output_dir)
|
| 1597 |
+
cran_index = get_cran_index(cran_url, session)
|
| 1598 |
+
if up_to_date(cran_index, d["inputs"]["old-metadata"]):
|
| 1599 |
+
continue
|
| 1600 |
+
elif update_policy == "skip-existing" and d["inputs"]["old-metadata"]:
|
| 1601 |
+
continue
|
| 1602 |
+
|
| 1603 |
+
from_sources = d["from_source"]
|
| 1604 |
+
# Normalize the metadata values
|
| 1605 |
+
d = {
|
| 1606 |
+
k: unicodedata.normalize("NFKD", str(v)).encode("ascii", "ignore").decode()
|
| 1607 |
+
for k, v in d.items()
|
| 1608 |
+
}
|
| 1609 |
+
try:
|
| 1610 |
+
makedirs(join(dir_path))
|
| 1611 |
+
except:
|
| 1612 |
+
pass
|
| 1613 |
+
print("Writing recipe for %s" % package.lower())
|
| 1614 |
+
with open(join(dir_path, "meta.yaml"), "w") as f:
|
| 1615 |
+
f.write(clear_whitespace(CRAN_META.format(**d)))
|
| 1616 |
+
if not exists(join(dir_path, "build.sh")) or update_policy == "overwrite":
|
| 1617 |
+
with open(join(dir_path, "build.sh"), "wb") as f:
|
| 1618 |
+
if from_sources == _all:
|
| 1619 |
+
f.write(CRAN_BUILD_SH_SOURCE.format(**d).encode("utf-8"))
|
| 1620 |
+
elif from_sources == []:
|
| 1621 |
+
f.write(CRAN_BUILD_SH_BINARY.format(**d).encode("utf-8"))
|
| 1622 |
+
else:
|
| 1623 |
+
tpbt = [target_platform_bash_test_by_sel[t] for t in from_sources]
|
| 1624 |
+
d["source_pf_bash"] = " || ".join(
|
| 1625 |
+
["[[ ${target_platform} " + s + " ]]" for s in tpbt]
|
| 1626 |
+
)
|
| 1627 |
+
f.write(CRAN_BUILD_SH_MIXED.format(**d).encode("utf-8"))
|
| 1628 |
+
|
| 1629 |
+
if not exists(join(dir_path, "bld.bat")) or update_policy == "overwrite":
|
| 1630 |
+
with open(join(dir_path, "bld.bat"), "wb") as f:
|
| 1631 |
+
if len([fs for fs in from_sources if fs.startswith("win")]) == 2:
|
| 1632 |
+
f.write(
|
| 1633 |
+
CRAN_BLD_BAT_SOURCE.format(**d)
|
| 1634 |
+
.replace("\n", "\r\n")
|
| 1635 |
+
.encode("utf-8")
|
| 1636 |
+
)
|
| 1637 |
+
else:
|
| 1638 |
+
f.write(
|
| 1639 |
+
CRAN_BLD_BAT_MIXED.format(**d)
|
| 1640 |
+
.replace("\n", "\r\n")
|
| 1641 |
+
.encode("utf-8")
|
| 1642 |
+
)
|
| 1643 |
+
|
| 1644 |
+
|
| 1645 |
+
def version_compare(recipe_dir: str, newest_conda_version):
|
| 1646 |
+
m = MetaData(recipe_dir)
|
| 1647 |
+
local_version = m.version()
|
| 1648 |
+
package = basename(recipe_dir)
|
| 1649 |
+
|
| 1650 |
+
print(f"Local recipe for {package} has version {local_version}.")
|
| 1651 |
+
|
| 1652 |
+
print(f"The version on CRAN for {package} is {newest_conda_version}.")
|
| 1653 |
+
|
| 1654 |
+
return local_version == newest_conda_version
|
| 1655 |
+
|
| 1656 |
+
|
| 1657 |
+
def get_outdated(output_dir, cran_index, packages=()):
|
| 1658 |
+
to_update = []
|
| 1659 |
+
recipes = listdir(output_dir)
|
| 1660 |
+
for recipe in recipes:
|
| 1661 |
+
if not recipe.startswith("r-") or not isdir(recipe):
|
| 1662 |
+
continue
|
| 1663 |
+
|
| 1664 |
+
recipe_name = recipe[2:]
|
| 1665 |
+
|
| 1666 |
+
if packages and not (recipe_name in packages or recipe in packages):
|
| 1667 |
+
continue
|
| 1668 |
+
|
| 1669 |
+
if recipe_name not in cran_index:
|
| 1670 |
+
print("Skipping %s, not found on CRAN" % recipe)
|
| 1671 |
+
continue
|
| 1672 |
+
|
| 1673 |
+
version_compare(
|
| 1674 |
+
join(output_dir, recipe), cran_index[recipe_name][1].replace("-", "_")
|
| 1675 |
+
)
|
| 1676 |
+
|
| 1677 |
+
print("Updating %s" % recipe)
|
| 1678 |
+
to_update.append(recipe_name)
|
| 1679 |
+
|
| 1680 |
+
return to_update
|
| 1681 |
+
|
| 1682 |
+
|
| 1683 |
+
def get_existing(output_dir, cran_index, packages=()):
|
| 1684 |
+
existing = []
|
| 1685 |
+
recipes = listdir(output_dir)
|
| 1686 |
+
for recipe in recipes:
|
| 1687 |
+
if not recipe.startswith("r-") or not isdir(recipe):
|
| 1688 |
+
continue
|
| 1689 |
+
|
| 1690 |
+
recipe_name = recipe[2:]
|
| 1691 |
+
|
| 1692 |
+
if packages and not (recipe_name in packages or recipe in packages):
|
| 1693 |
+
continue
|
| 1694 |
+
|
| 1695 |
+
existing.append(recipe_name)
|
| 1696 |
+
|
| 1697 |
+
return existing
|
| 1698 |
+
|
| 1699 |
+
|
| 1700 |
+
def up_to_date(cran_index, package):
|
| 1701 |
+
r_pkg_name, location, old_git_rev, m = package
|
| 1702 |
+
cran_pkg_name = r_pkg_name[2:]
|
| 1703 |
+
|
| 1704 |
+
# Does not exist, so is not up to date.
|
| 1705 |
+
if not m:
|
| 1706 |
+
return False
|
| 1707 |
+
|
| 1708 |
+
# For now. We can do better; need to collect *all* information upfront.
|
| 1709 |
+
if "github.com" in location:
|
| 1710 |
+
return False
|
| 1711 |
+
else:
|
| 1712 |
+
if cran_pkg_name not in cran_index:
|
| 1713 |
+
return False
|
| 1714 |
+
|
| 1715 |
+
name, version = cran_index[cran_pkg_name]
|
| 1716 |
+
if version and m.version() != version:
|
| 1717 |
+
return False
|
| 1718 |
+
|
| 1719 |
+
return True
|
| 1720 |
+
|
| 1721 |
+
|
| 1722 |
+
def get_license_info(license_text, allowed_license_families):
|
| 1723 |
+
"""
|
| 1724 |
+
Most R packages on CRAN do not include a license file. Instead, to avoid
|
| 1725 |
+
duplication, R base ships with common software licenses:
|
| 1726 |
+
|
| 1727 |
+
complete: AGPL-3, Artistic-2.0, GPL-2, GPL-3, LGPL-2, LGPL-2.1, LGPL-3
|
| 1728 |
+
template: BSD_2_clause BSD_3_clause, MIT
|
| 1729 |
+
|
| 1730 |
+
The complete licenses can be included in conda binaries by pointing to the
|
| 1731 |
+
license file shipped with R base. The template files are more complicated
|
| 1732 |
+
because they would need to be combined with the license information provided
|
| 1733 |
+
by the package authors. In this case, the template file and the license
|
| 1734 |
+
information file are both packaged. All optional ('|' seperated) licenses
|
| 1735 |
+
are included, if they are matching.
|
| 1736 |
+
|
| 1737 |
+
This function returns the path to the license file for the unambiguous
|
| 1738 |
+
cases.
|
| 1739 |
+
"""
|
| 1740 |
+
|
| 1741 |
+
# The list order matters. The first element should be the name of the
|
| 1742 |
+
# license file shipped with r-base.
|
| 1743 |
+
d_license = {
|
| 1744 |
+
"agpl3": ["AGPL-3", "AGPL (>= 3)", "AGPL", "GNU Affero General Public License"],
|
| 1745 |
+
"artistic2": ["Artistic-2.0", "Artistic License 2.0"],
|
| 1746 |
+
"gpl2": ["GPL-2", "GPL (>= 2)", "GNU General Public License (>= 2)"],
|
| 1747 |
+
"gpl3": [
|
| 1748 |
+
"GPL-3",
|
| 1749 |
+
"GPL (>= 3)",
|
| 1750 |
+
"GNU General Public License (>= 3)",
|
| 1751 |
+
"GPL",
|
| 1752 |
+
"GNU General Public License",
|
| 1753 |
+
],
|
| 1754 |
+
"lgpl2": ["LGPL-2", "LGPL (>= 2)"],
|
| 1755 |
+
"lgpl21": ["LGPL-2.1", "LGPL (>= 2.1)"],
|
| 1756 |
+
"lgpl3": ["LGPL-3", "LGPL (>= 3)", "LGPL", "GNU Lesser General Public License"],
|
| 1757 |
+
"bsd2": ["BSD_2_clause", "BSD_2_Clause", "BSD 2-clause License"],
|
| 1758 |
+
"bsd3": ["BSD_3_clause", "BSD_3_Clause", "BSD 3-clause License"],
|
| 1759 |
+
"mit": ["MIT"],
|
| 1760 |
+
}
|
| 1761 |
+
|
| 1762 |
+
license_file_template = (
|
| 1763 |
+
"'{{{{ environ[\"PREFIX\"] }}}}/lib/R/share/licenses/{license_id}'"
|
| 1764 |
+
)
|
| 1765 |
+
|
| 1766 |
+
license_texts = []
|
| 1767 |
+
license_files = []
|
| 1768 |
+
|
| 1769 |
+
# split license_text by "|" and "+" into parts for further matching
|
| 1770 |
+
license_text_parts = [l_opt.strip() for l_opt in re.split(r"\||\+", license_text)]
|
| 1771 |
+
for l_opt in license_text_parts:
|
| 1772 |
+
# the file case
|
| 1773 |
+
if l_opt.startswith("file "):
|
| 1774 |
+
license_files.append(l_opt[5:])
|
| 1775 |
+
continue
|
| 1776 |
+
|
| 1777 |
+
# license id string to match
|
| 1778 |
+
for license_id in d_license.keys():
|
| 1779 |
+
if l_opt in d_license[license_id]:
|
| 1780 |
+
l_opt_text = d_license[license_id][0]
|
| 1781 |
+
|
| 1782 |
+
license_texts.append(l_opt_text)
|
| 1783 |
+
license_files.append(
|
| 1784 |
+
license_file_template.format(license_id=l_opt_text)
|
| 1785 |
+
)
|
| 1786 |
+
break
|
| 1787 |
+
|
| 1788 |
+
# Join or fallback to original license_text if matched license_texts is empty
|
| 1789 |
+
license_text = " | ".join(license_texts) or license_text
|
| 1790 |
+
|
| 1791 |
+
# Build the license_file entry and ensure it is empty if no license file
|
| 1792 |
+
license_file = ""
|
| 1793 |
+
if license_files:
|
| 1794 |
+
license_file = f"license_file:{dashlist(license_files, indent=4)}\n"
|
| 1795 |
+
|
| 1796 |
+
# Only one family is allowed, so guessing it once
|
| 1797 |
+
license_family = guess_license_family(license_text, allowed_license_families)
|
| 1798 |
+
|
| 1799 |
+
return license_text, license_file, license_family
|
shared/package-files/d1/d15889a91b4964b212ec87e31eb520608e9122f598d1c7e4d4e8c0969e3466cc/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
matplotlib_inline
|
shared/package-files/d1/d1648a9846ff3b8a687e05635aa0c20c867054f93762f02e49ba6514afe29139/max_native.h
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
#include <ATen/ops/max_meta.h>
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
struct TORCH_API structured_max_out : public at::meta::structured_max_dim {
|
| 20 |
+
void impl(const at::Tensor & self, int64_t dim, bool keepdim, const at::Tensor & max, const at::Tensor & max_values);
|
| 21 |
+
};
|
| 22 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor> qmax(const at::Tensor & self, int64_t dim, bool keepdim=false);
|
| 23 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor> max(const at::Tensor & self, at::Dimname dim, bool keepdim=false);
|
| 24 |
+
TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> max_out(const at::Tensor & self, at::Dimname dim, bool keepdim, at::Tensor & max, at::Tensor & max_values);
|
| 25 |
+
TORCH_API at::Tensor max(const at::Tensor & self);
|
| 26 |
+
TORCH_API at::Tensor & max_unary_out(const at::Tensor & self, at::Tensor & out);
|
| 27 |
+
TORCH_API at::Tensor max_quantized_cpu(const at::Tensor & self);
|
| 28 |
+
TORCH_API at::Tensor & max_quantized_unary_out(const at::Tensor & self, at::Tensor & out);
|
| 29 |
+
TORCH_API at::Tensor max(const at::Tensor & self, const at::Tensor & other);
|
| 30 |
+
TORCH_API at::Tensor & max_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
|
| 31 |
+
} // namespace native
|
| 32 |
+
} // namespace at
|
shared/package-files/d1/d16861859d7ad6a76c11296ef77000e95f64d75330ce6365f679c1c88c0ecabd/libuuid.a
ADDED
|
Binary file (53.4 kB). View file
|
|
|
shared/package-files/d1/d173be07d5e60068962e11055bcc2e8c5a3e551d6beb64993fb313f83073d551/test_qcut.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from pandas import (
|
| 8 |
+
Categorical,
|
| 9 |
+
DatetimeIndex,
|
| 10 |
+
Interval,
|
| 11 |
+
IntervalIndex,
|
| 12 |
+
NaT,
|
| 13 |
+
Series,
|
| 14 |
+
Timedelta,
|
| 15 |
+
TimedeltaIndex,
|
| 16 |
+
Timestamp,
|
| 17 |
+
cut,
|
| 18 |
+
date_range,
|
| 19 |
+
isna,
|
| 20 |
+
qcut,
|
| 21 |
+
timedelta_range,
|
| 22 |
+
)
|
| 23 |
+
import pandas._testing as tm
|
| 24 |
+
from pandas.api.types import CategoricalDtype
|
| 25 |
+
|
| 26 |
+
from pandas.tseries.offsets import Day
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_qcut():
|
| 30 |
+
arr = np.random.default_rng(2).standard_normal(1000)
|
| 31 |
+
|
| 32 |
+
# We store the bins as Index that have been
|
| 33 |
+
# rounded to comparisons are a bit tricky.
|
| 34 |
+
labels, _ = qcut(arr, 4, retbins=True)
|
| 35 |
+
ex_bins = np.quantile(arr, [0, 0.25, 0.5, 0.75, 1.0])
|
| 36 |
+
|
| 37 |
+
result = labels.categories.left.values
|
| 38 |
+
assert np.allclose(result, ex_bins[:-1], atol=1e-2)
|
| 39 |
+
|
| 40 |
+
result = labels.categories.right.values
|
| 41 |
+
assert np.allclose(result, ex_bins[1:], atol=1e-2)
|
| 42 |
+
|
| 43 |
+
ex_levels = cut(arr, ex_bins, include_lowest=True)
|
| 44 |
+
tm.assert_categorical_equal(labels, ex_levels)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_qcut_bounds():
|
| 48 |
+
arr = np.random.default_rng(2).standard_normal(1000)
|
| 49 |
+
|
| 50 |
+
factor = qcut(arr, 10, labels=False)
|
| 51 |
+
assert len(np.unique(factor)) == 10
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_qcut_specify_quantiles():
|
| 55 |
+
arr = np.random.default_rng(2).standard_normal(100)
|
| 56 |
+
factor = qcut(arr, [0, 0.25, 0.5, 0.75, 1.0])
|
| 57 |
+
|
| 58 |
+
expected = qcut(arr, 4)
|
| 59 |
+
tm.assert_categorical_equal(factor, expected)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_qcut_all_bins_same():
|
| 63 |
+
with pytest.raises(ValueError, match="edges.*unique"):
|
| 64 |
+
qcut([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 3)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_qcut_include_lowest():
|
| 68 |
+
values = np.arange(10)
|
| 69 |
+
ii = qcut(values, 4)
|
| 70 |
+
|
| 71 |
+
ex_levels = IntervalIndex(
|
| 72 |
+
[
|
| 73 |
+
Interval(-0.001, 2.25),
|
| 74 |
+
Interval(2.25, 4.5),
|
| 75 |
+
Interval(4.5, 6.75),
|
| 76 |
+
Interval(6.75, 9),
|
| 77 |
+
]
|
| 78 |
+
)
|
| 79 |
+
tm.assert_index_equal(ii.categories, ex_levels)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_qcut_nas():
|
| 83 |
+
arr = np.random.default_rng(2).standard_normal(100)
|
| 84 |
+
arr[:20] = np.nan
|
| 85 |
+
|
| 86 |
+
result = qcut(arr, 4)
|
| 87 |
+
assert isna(result[:20]).all()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def test_qcut_index():
|
| 91 |
+
result = qcut([0, 2], 2)
|
| 92 |
+
intervals = [Interval(-0.001, 1), Interval(1, 2)]
|
| 93 |
+
|
| 94 |
+
expected = Categorical(intervals, ordered=True)
|
| 95 |
+
tm.assert_categorical_equal(result, expected)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_qcut_binning_issues(datapath):
|
| 99 |
+
# see gh-1978, gh-1979
|
| 100 |
+
cut_file = datapath(os.path.join("reshape", "data", "cut_data.csv"))
|
| 101 |
+
arr = np.loadtxt(cut_file)
|
| 102 |
+
result = qcut(arr, 20)
|
| 103 |
+
|
| 104 |
+
starts = []
|
| 105 |
+
ends = []
|
| 106 |
+
|
| 107 |
+
for lev in np.unique(result):
|
| 108 |
+
s = lev.left
|
| 109 |
+
e = lev.right
|
| 110 |
+
assert s != e
|
| 111 |
+
|
| 112 |
+
starts.append(float(s))
|
| 113 |
+
ends.append(float(e))
|
| 114 |
+
|
| 115 |
+
for (sp, sn), (ep, en) in zip(
|
| 116 |
+
zip(starts[:-1], starts[1:]), zip(ends[:-1], ends[1:])
|
| 117 |
+
):
|
| 118 |
+
assert sp < sn
|
| 119 |
+
assert ep < en
|
| 120 |
+
assert ep <= sn
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_qcut_return_intervals():
|
| 124 |
+
ser = Series([0, 1, 2, 3, 4, 5, 6, 7, 8])
|
| 125 |
+
res = qcut(ser, [0, 0.333, 0.666, 1])
|
| 126 |
+
|
| 127 |
+
exp_levels = np.array(
|
| 128 |
+
[Interval(-0.001, 2.664), Interval(2.664, 5.328), Interval(5.328, 8)]
|
| 129 |
+
)
|
| 130 |
+
exp = Series(exp_levels.take([0, 0, 0, 1, 1, 1, 2, 2, 2])).astype(
|
| 131 |
+
CategoricalDtype(ordered=True)
|
| 132 |
+
)
|
| 133 |
+
tm.assert_series_equal(res, exp)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@pytest.mark.parametrize("labels", ["foo", 1, True])
|
| 137 |
+
def test_qcut_incorrect_labels(labels):
|
| 138 |
+
# GH 13318
|
| 139 |
+
values = range(5)
|
| 140 |
+
msg = "Bin labels must either be False, None or passed in as a list-like argument"
|
| 141 |
+
with pytest.raises(ValueError, match=msg):
|
| 142 |
+
qcut(values, 4, labels=labels)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@pytest.mark.parametrize("labels", [["a", "b", "c"], list(range(3))])
|
| 146 |
+
def test_qcut_wrong_length_labels(labels):
|
| 147 |
+
# GH 13318
|
| 148 |
+
values = range(10)
|
| 149 |
+
msg = "Bin labels must be one fewer than the number of bin edges"
|
| 150 |
+
with pytest.raises(ValueError, match=msg):
|
| 151 |
+
qcut(values, 4, labels=labels)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@pytest.mark.parametrize(
|
| 155 |
+
"labels, expected",
|
| 156 |
+
[
|
| 157 |
+
(["a", "b", "c"], Categorical(["a", "b", "c"], ordered=True)),
|
| 158 |
+
(list(range(3)), Categorical([0, 1, 2], ordered=True)),
|
| 159 |
+
],
|
| 160 |
+
)
|
| 161 |
+
def test_qcut_list_like_labels(labels, expected):
|
| 162 |
+
# GH 13318
|
| 163 |
+
values = range(3)
|
| 164 |
+
result = qcut(values, 3, labels=labels)
|
| 165 |
+
tm.assert_categorical_equal(result, expected)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@pytest.mark.parametrize(
|
| 169 |
+
"kwargs,msg",
|
| 170 |
+
[
|
| 171 |
+
({"duplicates": "drop"}, None),
|
| 172 |
+
({}, "Bin edges must be unique"),
|
| 173 |
+
({"duplicates": "raise"}, "Bin edges must be unique"),
|
| 174 |
+
({"duplicates": "foo"}, "invalid value for 'duplicates' parameter"),
|
| 175 |
+
],
|
| 176 |
+
)
|
| 177 |
+
def test_qcut_duplicates_bin(kwargs, msg):
|
| 178 |
+
# see gh-7751
|
| 179 |
+
values = [0, 0, 0, 0, 1, 2, 3]
|
| 180 |
+
|
| 181 |
+
if msg is not None:
|
| 182 |
+
with pytest.raises(ValueError, match=msg):
|
| 183 |
+
qcut(values, 3, **kwargs)
|
| 184 |
+
else:
|
| 185 |
+
result = qcut(values, 3, **kwargs)
|
| 186 |
+
expected = IntervalIndex([Interval(-0.001, 1), Interval(1, 3)])
|
| 187 |
+
tm.assert_index_equal(result.categories, expected)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@pytest.mark.parametrize(
|
| 191 |
+
"data,start,end", [(9.0, 8.999, 9.0), (0.0, -0.001, 0.0), (-9.0, -9.001, -9.0)]
|
| 192 |
+
)
|
| 193 |
+
@pytest.mark.parametrize("length", [1, 2])
|
| 194 |
+
@pytest.mark.parametrize("labels", [None, False])
|
| 195 |
+
def test_single_quantile(data, start, end, length, labels):
|
| 196 |
+
# see gh-15431
|
| 197 |
+
ser = Series([data] * length)
|
| 198 |
+
result = qcut(ser, 1, labels=labels)
|
| 199 |
+
|
| 200 |
+
if labels is None:
|
| 201 |
+
intervals = IntervalIndex([Interval(start, end)] * length, closed="right")
|
| 202 |
+
expected = Series(intervals).astype(CategoricalDtype(ordered=True))
|
| 203 |
+
else:
|
| 204 |
+
expected = Series([0] * length, dtype=np.intp)
|
| 205 |
+
|
| 206 |
+
tm.assert_series_equal(result, expected)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@pytest.mark.parametrize(
|
| 210 |
+
"ser",
|
| 211 |
+
[
|
| 212 |
+
Series(DatetimeIndex(["20180101", NaT, "20180103"])),
|
| 213 |
+
Series(TimedeltaIndex(["0 days", NaT, "2 days"])),
|
| 214 |
+
],
|
| 215 |
+
ids=lambda x: str(x.dtype),
|
| 216 |
+
)
|
| 217 |
+
def test_qcut_nat(ser, unit):
|
| 218 |
+
# see gh-19768
|
| 219 |
+
ser = ser.dt.as_unit(unit)
|
| 220 |
+
td = Timedelta(1, unit=unit).as_unit(unit)
|
| 221 |
+
|
| 222 |
+
left = Series([ser[0] - td, np.nan, ser[2] - Day()], dtype=ser.dtype)
|
| 223 |
+
right = Series([ser[2] - Day(), np.nan, ser[2]], dtype=ser.dtype)
|
| 224 |
+
intervals = IntervalIndex.from_arrays(left, right)
|
| 225 |
+
expected = Series(Categorical(intervals, ordered=True))
|
| 226 |
+
|
| 227 |
+
result = qcut(ser, 2)
|
| 228 |
+
tm.assert_series_equal(result, expected)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
@pytest.mark.parametrize("bins", [3, np.linspace(0, 1, 4)])
|
| 232 |
+
def test_datetime_tz_qcut(bins):
|
| 233 |
+
# see gh-19872
|
| 234 |
+
tz = "US/Eastern"
|
| 235 |
+
ser = Series(date_range("20130101", periods=3, tz=tz))
|
| 236 |
+
|
| 237 |
+
result = qcut(ser, bins)
|
| 238 |
+
expected = Series(
|
| 239 |
+
IntervalIndex(
|
| 240 |
+
[
|
| 241 |
+
Interval(
|
| 242 |
+
Timestamp("2012-12-31 23:59:59.999999999", tz=tz),
|
| 243 |
+
Timestamp("2013-01-01 16:00:00", tz=tz),
|
| 244 |
+
),
|
| 245 |
+
Interval(
|
| 246 |
+
Timestamp("2013-01-01 16:00:00", tz=tz),
|
| 247 |
+
Timestamp("2013-01-02 08:00:00", tz=tz),
|
| 248 |
+
),
|
| 249 |
+
Interval(
|
| 250 |
+
Timestamp("2013-01-02 08:00:00", tz=tz),
|
| 251 |
+
Timestamp("2013-01-03 00:00:00", tz=tz),
|
| 252 |
+
),
|
| 253 |
+
]
|
| 254 |
+
)
|
| 255 |
+
).astype(CategoricalDtype(ordered=True))
|
| 256 |
+
tm.assert_series_equal(result, expected)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@pytest.mark.parametrize(
|
| 260 |
+
"arg,expected_bins",
|
| 261 |
+
[
|
| 262 |
+
[
|
| 263 |
+
timedelta_range("1day", periods=3),
|
| 264 |
+
TimedeltaIndex(["1 days", "2 days", "3 days"]),
|
| 265 |
+
],
|
| 266 |
+
[
|
| 267 |
+
date_range("20180101", periods=3),
|
| 268 |
+
DatetimeIndex(["2018-01-01", "2018-01-02", "2018-01-03"]),
|
| 269 |
+
],
|
| 270 |
+
],
|
| 271 |
+
)
|
| 272 |
+
def test_date_like_qcut_bins(arg, expected_bins):
|
| 273 |
+
# see gh-19891
|
| 274 |
+
ser = Series(arg)
|
| 275 |
+
result, result_bins = qcut(ser, 2, retbins=True)
|
| 276 |
+
tm.assert_index_equal(result_bins, expected_bins)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
@pytest.mark.parametrize("bins", [6, 7])
|
| 280 |
+
@pytest.mark.parametrize(
|
| 281 |
+
"box, compare",
|
| 282 |
+
[
|
| 283 |
+
(Series, tm.assert_series_equal),
|
| 284 |
+
(np.array, tm.assert_categorical_equal),
|
| 285 |
+
(list, tm.assert_equal),
|
| 286 |
+
],
|
| 287 |
+
)
|
| 288 |
+
def test_qcut_bool_coercion_to_int(bins, box, compare):
|
| 289 |
+
# issue 20303
|
| 290 |
+
data_expected = box([0, 1, 1, 0, 1] * 10)
|
| 291 |
+
data_result = box([False, True, True, False, True] * 10)
|
| 292 |
+
expected = qcut(data_expected, bins, duplicates="drop")
|
| 293 |
+
result = qcut(data_result, bins, duplicates="drop")
|
| 294 |
+
compare(result, expected)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@pytest.mark.parametrize("q", [2, 5, 10])
|
| 298 |
+
def test_qcut_nullable_integer(q, any_numeric_ea_dtype):
|
| 299 |
+
arr = pd.array(np.arange(100), dtype=any_numeric_ea_dtype)
|
| 300 |
+
arr[::2] = pd.NA
|
| 301 |
+
|
| 302 |
+
result = qcut(arr, q)
|
| 303 |
+
expected = qcut(arr.astype(float), q)
|
| 304 |
+
|
| 305 |
+
tm.assert_categorical_equal(result, expected)
|
shared/package-files/d1/d17715b895804e35e43e4a58f764b71cfa6776456950d711dd3ec7a0899f0172/_nested_get_offsets.h
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <c10/util/Optional.h>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/_nested_get_offsets_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::_nested_get_offsets(Tensor self) -> Tensor
|
| 26 |
+
inline at::Tensor _nested_get_offsets(const at::Tensor & self) {
|
| 27 |
+
return at::_ops::_nested_get_offsets::call(self);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
}
|
shared/package-files/d1/d18db3d2b95eba710fe685b9dd20c03708d8acca258ed48b297261c633dfedf6/dtypes.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from narwhals.stable.v1._dtypes import (
|
| 4 |
+
Array,
|
| 5 |
+
Binary,
|
| 6 |
+
Boolean,
|
| 7 |
+
Categorical,
|
| 8 |
+
Date,
|
| 9 |
+
Datetime,
|
| 10 |
+
Decimal,
|
| 11 |
+
DType,
|
| 12 |
+
Duration,
|
| 13 |
+
Enum,
|
| 14 |
+
Field,
|
| 15 |
+
Float16,
|
| 16 |
+
Float32,
|
| 17 |
+
Float64,
|
| 18 |
+
FloatType,
|
| 19 |
+
Int8,
|
| 20 |
+
Int16,
|
| 21 |
+
Int32,
|
| 22 |
+
Int64,
|
| 23 |
+
Int128,
|
| 24 |
+
IntegerType,
|
| 25 |
+
List,
|
| 26 |
+
NestedType,
|
| 27 |
+
NumericType,
|
| 28 |
+
Object,
|
| 29 |
+
SignedIntegerType,
|
| 30 |
+
String,
|
| 31 |
+
Struct,
|
| 32 |
+
Time,
|
| 33 |
+
UInt8,
|
| 34 |
+
UInt16,
|
| 35 |
+
UInt32,
|
| 36 |
+
UInt64,
|
| 37 |
+
UInt128,
|
| 38 |
+
Unknown,
|
| 39 |
+
UnsignedIntegerType,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
__all__ = [
|
| 43 |
+
"Array",
|
| 44 |
+
"Binary",
|
| 45 |
+
"Boolean",
|
| 46 |
+
"Categorical",
|
| 47 |
+
"DType",
|
| 48 |
+
"Date",
|
| 49 |
+
"Datetime",
|
| 50 |
+
"Decimal",
|
| 51 |
+
"Duration",
|
| 52 |
+
"Enum",
|
| 53 |
+
"Field",
|
| 54 |
+
"Float16",
|
| 55 |
+
"Float32",
|
| 56 |
+
"Float64",
|
| 57 |
+
"FloatType",
|
| 58 |
+
"Int8",
|
| 59 |
+
"Int16",
|
| 60 |
+
"Int32",
|
| 61 |
+
"Int64",
|
| 62 |
+
"Int128",
|
| 63 |
+
"IntegerType",
|
| 64 |
+
"List",
|
| 65 |
+
"NestedType",
|
| 66 |
+
"NumericType",
|
| 67 |
+
"Object",
|
| 68 |
+
"SignedIntegerType",
|
| 69 |
+
"String",
|
| 70 |
+
"Struct",
|
| 71 |
+
"Time",
|
| 72 |
+
"UInt8",
|
| 73 |
+
"UInt16",
|
| 74 |
+
"UInt32",
|
| 75 |
+
"UInt64",
|
| 76 |
+
"UInt128",
|
| 77 |
+
"Unknown",
|
| 78 |
+
"UnsignedIntegerType",
|
| 79 |
+
]
|
shared/package-files/d1/d19128733490ab9f7338677f79693ab1f002b7adaf7509ad87789aeeea961533/_matrix_io.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
|
| 7 |
+
# Make loading safe vs. malicious input
|
| 8 |
+
PICKLE_KWARGS = dict(allow_pickle=False)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def save_npz(file, matrix, compressed=True):
|
| 12 |
+
""" Save a sparse matrix or array to a file using ``.npz`` format.
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
----------
|
| 16 |
+
file : str or file-like object
|
| 17 |
+
Either the file name (string) or an open file (file-like object)
|
| 18 |
+
where the data will be saved. If file is a string, the ``.npz``
|
| 19 |
+
extension will be appended to the file name if it is not already
|
| 20 |
+
there.
|
| 21 |
+
matrix: spmatrix or sparray
|
| 22 |
+
The sparse matrix or array to save.
|
| 23 |
+
Supported formats: ``csc``, ``csr``, ``bsr``, ``dia`` or ``coo``.
|
| 24 |
+
compressed : bool, optional
|
| 25 |
+
Allow compressing the file. Default: True
|
| 26 |
+
|
| 27 |
+
See Also
|
| 28 |
+
--------
|
| 29 |
+
scipy.sparse.load_npz: Load a sparse matrix from a file using ``.npz`` format.
|
| 30 |
+
numpy.savez: Save several arrays into a ``.npz`` archive.
|
| 31 |
+
numpy.savez_compressed : Save several arrays into a compressed ``.npz`` archive.
|
| 32 |
+
|
| 33 |
+
Examples
|
| 34 |
+
--------
|
| 35 |
+
Store sparse matrix to disk, and load it again:
|
| 36 |
+
|
| 37 |
+
>>> import numpy as np
|
| 38 |
+
>>> import scipy as sp
|
| 39 |
+
>>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]])
|
| 40 |
+
>>> sparse_matrix
|
| 41 |
+
<Compressed Sparse Column sparse matrix of dtype 'int64'
|
| 42 |
+
with 2 stored elements and shape (2, 3)>
|
| 43 |
+
>>> sparse_matrix.toarray()
|
| 44 |
+
array([[0, 0, 3],
|
| 45 |
+
[4, 0, 0]], dtype=int64)
|
| 46 |
+
|
| 47 |
+
>>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
|
| 48 |
+
>>> sparse_matrix = sp.sparse.load_npz('/tmp/sparse_matrix.npz')
|
| 49 |
+
|
| 50 |
+
>>> sparse_matrix
|
| 51 |
+
<Compressed Sparse Column sparse matrix of dtype 'int64'
|
| 52 |
+
with 2 stored elements and shape (2, 3)>
|
| 53 |
+
>>> sparse_matrix.toarray()
|
| 54 |
+
array([[0, 0, 3],
|
| 55 |
+
[4, 0, 0]], dtype=int64)
|
| 56 |
+
"""
|
| 57 |
+
arrays_dict = {}
|
| 58 |
+
if matrix.format in ('csc', 'csr', 'bsr'):
|
| 59 |
+
arrays_dict.update(indices=matrix.indices, indptr=matrix.indptr)
|
| 60 |
+
elif matrix.format == 'dia':
|
| 61 |
+
arrays_dict.update(offsets=matrix.offsets)
|
| 62 |
+
elif matrix.format == 'coo':
|
| 63 |
+
arrays_dict.update(row=matrix.row, col=matrix.col)
|
| 64 |
+
else:
|
| 65 |
+
msg = f'Save is not implemented for sparse matrix of format {matrix.format}.'
|
| 66 |
+
raise NotImplementedError(msg)
|
| 67 |
+
arrays_dict.update(
|
| 68 |
+
format=matrix.format.encode('ascii'),
|
| 69 |
+
shape=matrix.shape,
|
| 70 |
+
data=matrix.data
|
| 71 |
+
)
|
| 72 |
+
if isinstance(matrix, sp.sparse.sparray):
|
| 73 |
+
arrays_dict.update(_is_array=True)
|
| 74 |
+
if compressed:
|
| 75 |
+
np.savez_compressed(file, **arrays_dict)
|
| 76 |
+
else:
|
| 77 |
+
np.savez(file, **arrays_dict)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def load_npz(file):
|
| 81 |
+
""" Load a sparse array/matrix from a file using ``.npz`` format.
|
| 82 |
+
|
| 83 |
+
Parameters
|
| 84 |
+
----------
|
| 85 |
+
file : str or file-like object
|
| 86 |
+
Either the file name (string) or an open file (file-like object)
|
| 87 |
+
where the data will be loaded.
|
| 88 |
+
|
| 89 |
+
Returns
|
| 90 |
+
-------
|
| 91 |
+
result : csc_array, csr_array, bsr_array, dia_array or coo_array
|
| 92 |
+
A sparse array/matrix containing the loaded data.
|
| 93 |
+
|
| 94 |
+
Raises
|
| 95 |
+
------
|
| 96 |
+
OSError
|
| 97 |
+
If the input file does not exist or cannot be read.
|
| 98 |
+
|
| 99 |
+
See Also
|
| 100 |
+
--------
|
| 101 |
+
scipy.sparse.save_npz: Save a sparse array/matrix to a file using ``.npz`` format.
|
| 102 |
+
numpy.load: Load several arrays from a ``.npz`` archive.
|
| 103 |
+
|
| 104 |
+
Examples
|
| 105 |
+
--------
|
| 106 |
+
Store sparse array/matrix to disk, and load it again:
|
| 107 |
+
|
| 108 |
+
>>> import numpy as np
|
| 109 |
+
>>> import scipy as sp
|
| 110 |
+
>>> sparse_array = sp.sparse.csc_array([[0, 0, 3], [4, 0, 0]])
|
| 111 |
+
>>> sparse_array
|
| 112 |
+
<Compressed Sparse Column sparse array of dtype 'int64'
|
| 113 |
+
with 2 stored elements and shape (2, 3)>
|
| 114 |
+
>>> sparse_array.toarray()
|
| 115 |
+
array([[0, 0, 3],
|
| 116 |
+
[4, 0, 0]], dtype=int64)
|
| 117 |
+
|
| 118 |
+
>>> sp.sparse.save_npz('/tmp/sparse_array.npz', sparse_array)
|
| 119 |
+
>>> sparse_array = sp.sparse.load_npz('/tmp/sparse_array.npz')
|
| 120 |
+
|
| 121 |
+
>>> sparse_array
|
| 122 |
+
<Compressed Sparse Column sparse array of dtype 'int64'
|
| 123 |
+
with 2 stored elements and shape (2, 3)>
|
| 124 |
+
>>> sparse_array.toarray()
|
| 125 |
+
array([[0, 0, 3],
|
| 126 |
+
[4, 0, 0]], dtype=int64)
|
| 127 |
+
|
| 128 |
+
In this example we force the result to be csr_array from csr_matrix
|
| 129 |
+
>>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]])
|
| 130 |
+
>>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
|
| 131 |
+
>>> tmp = sp.sparse.load_npz('/tmp/sparse_matrix.npz')
|
| 132 |
+
>>> sparse_array = sp.sparse.csr_array(tmp)
|
| 133 |
+
"""
|
| 134 |
+
with np.load(file, **PICKLE_KWARGS) as loaded:
|
| 135 |
+
sparse_format = loaded.get('format')
|
| 136 |
+
if sparse_format is None:
|
| 137 |
+
raise ValueError(f'The file {file} does not contain '
|
| 138 |
+
f'a sparse array or matrix.')
|
| 139 |
+
sparse_format = sparse_format.item()
|
| 140 |
+
|
| 141 |
+
if not isinstance(sparse_format, str):
|
| 142 |
+
# Play safe with Python 2 vs 3 backward compatibility;
|
| 143 |
+
# files saved with SciPy < 1.0.0 may contain unicode or bytes.
|
| 144 |
+
sparse_format = sparse_format.decode('ascii')
|
| 145 |
+
|
| 146 |
+
if loaded.get('_is_array'):
|
| 147 |
+
sparse_type = sparse_format + '_array'
|
| 148 |
+
else:
|
| 149 |
+
sparse_type = sparse_format + '_matrix'
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
cls = getattr(sp.sparse, f'{sparse_type}')
|
| 153 |
+
except AttributeError as e:
|
| 154 |
+
raise ValueError(f'Unknown format "{sparse_type}"') from e
|
| 155 |
+
|
| 156 |
+
if sparse_format in ('csc', 'csr', 'bsr'):
|
| 157 |
+
return cls((loaded['data'], loaded['indices'], loaded['indptr']),
|
| 158 |
+
shape=loaded['shape'])
|
| 159 |
+
elif sparse_format == 'dia':
|
| 160 |
+
return cls((loaded['data'], loaded['offsets']),
|
| 161 |
+
shape=loaded['shape'])
|
| 162 |
+
elif sparse_format == 'coo':
|
| 163 |
+
return cls((loaded['data'], (loaded['row'], loaded['col'])),
|
| 164 |
+
shape=loaded['shape'])
|
| 165 |
+
else:
|
| 166 |
+
raise NotImplementedError(f'Load is not implemented for '
|
| 167 |
+
f'sparse matrix of format {sparse_format}.')
|
shared/package-files/d1/d19a7033230c463a7a56d9db153d219ae5719f31ed260f694f10c961133c9fa6/selecting.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Iterator, Tuple, TypeVar
|
| 2 |
+
|
| 3 |
+
from torch.utils.data.datapipes._decorator import functional_datapipe
|
| 4 |
+
from torch.utils.data.datapipes.datapipe import IterDataPipe
|
| 5 |
+
from torch.utils.data.datapipes.dataframe import dataframe_wrapper as df_wrapper
|
| 6 |
+
from torch.utils.data.datapipes.utils.common import (
|
| 7 |
+
_check_unpickable_fn,
|
| 8 |
+
StreamWrapper,
|
| 9 |
+
validate_input_col
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
__all__ = ["FilterIterDataPipe", ]
|
| 14 |
+
|
| 15 |
+
T = TypeVar('T')
|
| 16 |
+
T_co = TypeVar('T_co', covariant=True)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@functional_datapipe('filter')
|
| 20 |
+
class FilterIterDataPipe(IterDataPipe[T_co]):
|
| 21 |
+
r"""
|
| 22 |
+
Filters out elements from the source datapipe according to input ``filter_fn`` (functional name: ``filter``).
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
datapipe: Iterable DataPipe being filtered
|
| 26 |
+
filter_fn: Customized function mapping an element to a boolean.
|
| 27 |
+
input_col: Index or indices of data which ``filter_fn`` is applied, such as:
|
| 28 |
+
|
| 29 |
+
- ``None`` as default to apply ``filter_fn`` to the data directly.
|
| 30 |
+
- Integer(s) is used for list/tuple.
|
| 31 |
+
- Key(s) is used for dict.
|
| 32 |
+
|
| 33 |
+
Example:
|
| 34 |
+
>>> # xdoctest: +SKIP
|
| 35 |
+
>>> from torchdata.datapipes.iter import IterableWrapper
|
| 36 |
+
>>> def is_even(n):
|
| 37 |
+
... return n % 2 == 0
|
| 38 |
+
>>> dp = IterableWrapper(range(5))
|
| 39 |
+
>>> filter_dp = dp.filter(filter_fn=is_even)
|
| 40 |
+
>>> list(filter_dp)
|
| 41 |
+
[0, 2, 4]
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
datapipe: IterDataPipe[T_co]
|
| 45 |
+
filter_fn: Callable
|
| 46 |
+
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
datapipe: IterDataPipe[T_co],
|
| 50 |
+
filter_fn: Callable,
|
| 51 |
+
input_col=None,
|
| 52 |
+
) -> None:
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.datapipe = datapipe
|
| 55 |
+
|
| 56 |
+
_check_unpickable_fn(filter_fn)
|
| 57 |
+
self.filter_fn = filter_fn # type: ignore[assignment]
|
| 58 |
+
|
| 59 |
+
self.input_col = input_col
|
| 60 |
+
validate_input_col(filter_fn, input_col)
|
| 61 |
+
|
| 62 |
+
def _apply_filter_fn(self, data) -> bool:
|
| 63 |
+
if self.input_col is None:
|
| 64 |
+
return self.filter_fn(data)
|
| 65 |
+
elif isinstance(self.input_col, (list, tuple)):
|
| 66 |
+
args = tuple(data[col] for col in self.input_col)
|
| 67 |
+
return self.filter_fn(*args)
|
| 68 |
+
else:
|
| 69 |
+
return self.filter_fn(data[self.input_col])
|
| 70 |
+
|
| 71 |
+
def __iter__(self) -> Iterator[T_co]:
|
| 72 |
+
for data in self.datapipe:
|
| 73 |
+
condition, filtered = self._returnIfTrue(data)
|
| 74 |
+
if condition:
|
| 75 |
+
yield filtered
|
| 76 |
+
else:
|
| 77 |
+
StreamWrapper.close_streams(data)
|
| 78 |
+
|
| 79 |
+
def _returnIfTrue(self, data: T) -> Tuple[bool, T]:
|
| 80 |
+
condition = self._apply_filter_fn(data)
|
| 81 |
+
|
| 82 |
+
if df_wrapper.is_column(condition):
|
| 83 |
+
# We are operating on DataFrames filter here
|
| 84 |
+
result = []
|
| 85 |
+
for idx, mask in enumerate(df_wrapper.iterate(condition)):
|
| 86 |
+
if mask:
|
| 87 |
+
result.append(df_wrapper.get_item(data, idx))
|
| 88 |
+
if len(result):
|
| 89 |
+
return True, df_wrapper.concat(result)
|
| 90 |
+
else:
|
| 91 |
+
return False, None # type: ignore[return-value]
|
| 92 |
+
|
| 93 |
+
if not isinstance(condition, bool):
|
| 94 |
+
raise ValueError("Boolean output is required for `filter_fn` of FilterIterDataPipe, got", type(condition))
|
| 95 |
+
|
| 96 |
+
return condition, data
|