-
Notifications
You must be signed in to change notification settings - Fork 25
/
_number.py
224 lines (180 loc) · 6.08 KB
/
_number.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
from typing import Any, Union, Type
import numpy
from typish import Literal, get_mro
from nptyping.types._nptype import NPType, SimpleNPTypeMeta
DEFAULT_INT_BITS = numpy.dtype(int).itemsize * 8
DEFAULT_FLOAT_BITS = numpy.dtype(float).itemsize * 8
class _NumberMeta(SimpleNPTypeMeta):
"""
Super metaclass for the Number class.
"""
base = None
npbase = None
_bits = None
_hashes = {}
_repr_args = None
def __eq__(cls, other):
return hash(cls) == hash(other)
def __hash__(cls):
key = (cls.base, cls.npbase, cls._bits)
if key not in cls._hashes:
cls._hashes[key] = int(numpy.prod([hash(elem) for elem in key]))
return cls._hashes[key]
def __instancecheck__(cls, instance: Any) -> bool:
from nptyping.functions._get_type import get_type
if cls == instance or type(instance) in (int, float):
# Covers Python types.
return True
return issubclass(get_type(instance), cls)
def __subclasscheck__(cls, subclass: type) -> bool:
result = False
if cls == subclass:
result = True
elif _is_a(subclass, Number):
# Cover nptyping number types.
result = _is_number_subclass_of(subclass, cls)
elif _is_number_type(subclass):
result = _is_numpy_or_python_type_subclass_of(subclass, cls)
return result
class Number(NPType, metaclass=_NumberMeta):
"""
Superclass for number types (integers and floating point numbers). Can be
optionally given the number of bits.
"""
base = None
npbase = None
_bits = None
_repr_args = None
@classmethod
def _after_subscription(cls, args: Any) -> None:
if isinstance(args, tuple):
cls.base = args[0]
cls.npbase = args[1]
return
if not isinstance(args, int):
raise TypeError('Number takes only an int as generic type. '
'Given: {}'.format(type(args).__name__))
cls._bits = args
cls._repr_args = args
if not hasattr(numpy, '{}{}'.format(cls.base.__name__, cls._bits)):
raise TypeError('Unsupported number of bits: {}'.format(args))
@classmethod
def bits(cls) -> Union[int, Literal[Any]]:
"""
Return the number of bits of this Number type.
:return: the number of bits or Any.
"""
return cls._bits
class Int(Number[int, numpy.signedinteger]):
"""
A (signed) numpy int. Can be given the number of bits optionally.
>>> Int[32]
Int[32]
"""
@classmethod
def type_of(cls, obj: Any) -> Type['Int']:
"""
Return the NPType that corresponds to obj.
:param obj: an int compatible object.
:return: a Int type.
"""
from nptyping.functions._get_type import get_type_int
return get_type_int(obj)
@staticmethod
def fitting(number: int) -> Type['Int']:
"""
Return the Int type that fits the given number.
:param number: the number of which the Int type is to be found.
:return: a type of Int.
"""
bitlen = number.bit_length()
for bits in [8, 16, 32, 64]:
if bitlen <= bits - 1: # subtract sign bit.
break
return Int[bits]
class UInt(Number[int, numpy.unsignedinteger]):
"""
An unsigned numpy int. Can be given the number of bits optionally.
>>> UInt[32]
UInt[32]
"""
@classmethod
def type_of(cls, obj: Any) -> Type['UInt']:
"""
Return the NPType that corresponds to obj.
:param obj: an uint compatible object.
:return: an UInt type.
"""
from nptyping.functions._get_type import get_type_uint
return get_type_uint(obj)
@staticmethod
def fitting(number: int) -> Type['UInt']:
"""
Return the UInt type that fits the given number.
:param number: the number of which the UInt type is to be found.
:return: a type of UInt.
"""
bitlen = number.bit_length()
for bits in [8, 16, 32, 64]:
if bitlen <= bits:
break
return UInt[bits]
class Float(Number[float, numpy.floating]):
"""
A numpy float. Can be given the number of bits optionally.
>>> Float[32]
Float[32]
"""
@staticmethod
def type_of(obj: Any) -> Type['Float']:
"""
Return the NPType that corresponds to obj.
:param obj: a float compatible object.
:return: a Float type.
"""
from nptyping.functions._get_type import get_type_float
return get_type_float(obj)
def _is_a(this: Any, that: type) -> bool:
# Return whether this is a subclass of that, considering the mro.
return that in get_mro(this)
def _is_number_subclass_of(
subclass: Type[Number],
superclass: Type[Number]) -> bool:
# Return whether subclass (which must be a type of Number) subclasses
# superclass.
base_is_eq = (not superclass.npbase
or issubclass(subclass.npbase, superclass.npbase))
bits_is_eq = not superclass.bits() or subclass.bits() == superclass.bits()
return base_is_eq and bits_is_eq
def _is_numpy_or_python_type_subclass_of(
subclass: Any,
superclass: Type[Number]) -> bool:
# Return whether subclass (which must be a numpy type or a Python type)
# subclasses superclass.
if not superclass.npbase:
# superclass is Number.
result = True
else:
try:
nptype = superclass.type_of(subclass)
except TypeError:
result = False
else:
result = issubclass(nptype, superclass)
return result
def _is_number_type(type_: type) -> bool:
# Return whether type_ is a numpy/Python number type.
return (issubclass(type_, numpy.number)
or issubclass(type_, int)
or issubclass(type_, float))
Int8 = Int[8]
Int16 = Int[16]
Int32 = Int[32]
Int64 = Int[64]
UInt8 = UInt[8]
UInt16 = UInt[16]
UInt32 = UInt[32]
UInt64 = UInt[64]
Float16 = Float[16]
Float32 = Float[32]
Float64 = Float[64]