-
Notifications
You must be signed in to change notification settings - Fork 4
/
bases.py
350 lines (251 loc) · 9.54 KB
/
bases.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
"""Baseclasses of rows and columns classes."""
from abc import ABCMeta, abstractmethod
from decimal import Decimal
from numbers import Real
from operator import add, mul, truediv, sub
from .elements import Element
from .. import utils # Only meant to be used for `ROUND_LIMIT`
from ..exceptions import BrokenMatrixView
from ..utils import (
display_adj_slice,
is_iterable,
mangled_attr,
slice_length,
valid_container,
)
__all__ = ("RowsColumns", "RowsColumnsSlice", "RowColumn")
@mangled_attr(_set=False, _del=False)
class RowsColumns(metaclass=ABCMeta):
"""Baseclass of Rows() and Columns()."""
# mainly to disable abitrary atributes.
__slots__ = ("__matrix",)
def __init__(self, matrix):
"""See class Description."""
self.__matrix = matrix
def __repr__(self):
return f"<{type(self).__name__} of {self.__matrix!r}>"
@abstractmethod
def __getitem__(self, sub):
raise NotImplementedError
@abstractmethod
def __setitem__(self, sub, value):
raise NotImplementedError
@abstractmethod
def __delitem__(self, sub):
raise NotImplementedError
@abstractmethod
def __len__(self):
raise NotImplementedError
@abstractmethod
def __iter__(self):
raise NotImplementedError
@mangled_attr(_set=False, _del=False)
class RowsColumnsSlice(metaclass=ABCMeta):
"""Baseclass of RowsSlice() and ColumnsSlice()."""
# mainly to disable abitrary atributes.
__slots__ = ("__matrix", "__slice", "__slice_disp", "__length", "__size_hash")
def __init__(self, matrix, slice_):
"""See class Description."""
self.__matrix = matrix
self.__slice = slice_
self.__slice_disp = display_adj_slice(slice_)
self.__length = slice_length(slice_)
self.__size_hash = hash(matrix.size)
def __repr__(self):
return f"<{type(self).__name__[:-5]} [{self.__slice_disp}] of {self.__matrix!r}>"
def __len__(self):
self.__validity_check()
return self.__length
def __validity_check(self):
"""
Raises an error if the matrix has been resized
since when a "matrix-view" instance was created.
"""
if self.__size_hash != hash(self.__matrix.size):
raise BrokenMatrixView(
"The matrix has been resized after"
f" this matrix-view ({self!r}) was created.",
view_obj=self,
)
@abstractmethod
def __getitem__(self, sub):
raise NotImplementedError
@abstractmethod
def __iter__(self):
raise NotImplementedError
@mangled_attr(_set=False, _del=False)
class RowColumn(metaclass=ABCMeta):
"""Baseclass of Row() and Column()."""
# mainly to disable abitrary atributes.
__slots__ = ("__matrix", "__index", "__size_hash")
def __init__(self, matrix, index):
"""See class Description."""
self.__matrix = matrix
self.__index = index
self.__size_hash = hash(matrix.size)
def __repr__(self):
return f"<{type(self).__name__} {self.__index + 1} of {self.__matrix!r}>"
# The following operations must not return Row/Column instances
# because they are views of the underlying matrix,
# which is not being modified itself.
def __add__(self, other) -> list:
"""
Point-wise addition.
'other' must be an iterable of real numbers
with same length as the row/column.
"""
self.__validity_check()
if isinstance(other, __class__):
if len(self) == len(other):
return _rounded(list(map(add, self._fast_iter(), other._fast_iter())))
raise ValueError("The rows/columns must be of equal length.")
if is_iterable(other):
other = valid_container(other, len(self))
return _rounded(list(map(add, self._fast_iter(), other)))
return NotImplemented
def __radd__(self, other) -> list:
"""Reflected point-wise addition."""
return self.__add__(other)
def __sub__(self, other) -> list:
"""
Point-wise subtraction.
'other' must be an iterable of real numbers
with same length as the row/column.
"""
self.__validity_check()
if isinstance(other, __class__):
if len(self) == len(other):
return _rounded(list(map(sub, self._fast_iter(), other._fast_iter())))
raise ValueError("The rows/columns must be of equal length.")
if is_iterable(other):
other = valid_container(other, len(self))
return _rounded(list(map(sub, self._fast_iter(), other)))
return NotImplemented
def __rsub__(self, other) -> list:
"""Reflected point-wise subtraction."""
self.__validity_check()
if isinstance(other, __class__):
if len(self) == len(other):
return _rounded(list(map(sub, other._fast_iter(), self._fast_iter())))
raise ValueError("The rows/columns must be of equal length.")
if is_iterable(other):
other = valid_container(other, len(self))
return _rounded(list(map(sub, other, self._fast_iter())))
return NotImplemented
def __mul__(self, other) -> list:
"""
Scalar multiplication.
'other' must be a real number.
"""
self.__validity_check()
if not isinstance(other, (Real, Decimal)):
return NotImplemented
return _rounded([elem * other for elem in self._fast_iter()])
def __rmul__(self, other) -> list:
"""Reflected scalar multiplication."""
return self.__mul__(other)
def __matmul__(self, other):
"""
Point-wise multiplication.
'other' must be an iterable of real numbers
with same length as the row/column.
"""
if isinstance(other, __class__):
if len(self) == len(other):
return _rounded(list(map(mul, self._fast_iter(), other._fast_iter())))
raise ValueError("The rows/columns must be of equal length.")
if is_iterable(other):
other = valid_container(other, len(self))
return _rounded(list(map(mul, self._fast_iter(), other)))
return NotImplemented
def __rmatmul__(self, other):
"""Reflected point-wise multiplication"""
return self.__matmul__(other)
def __truediv__(self, other) -> list:
"""
Scalar or point-wise division.
'other' must be a real number
or iterable of real numbers with same length as the row/column.
"""
self.__validity_check()
if isinstance(other, (Real, Decimal)):
return _rounded([elem / other for elem in self._fast_iter()])
if isinstance(other, __class__):
if len(self) == len(other):
return _rounded(list(map(truediv, self._fast_iter(), other._fast_iter())))
raise ValueError("The rows/columns must be of equal length.")
if is_iterable(other):
other = valid_container(other, len(self))
return _rounded(list(map(truediv, self._fast_iter(), other)))
return NotImplemented
def __rtruediv__(self, other) -> list:
"""
Reflected point-wise division
(Scalar division shouldn't be reflected)
"""
self.__validity_check()
if isinstance(other, __class__):
if len(self) == len(other):
return _rounded(list(map(truediv, other._fast_iter(), self._fast_iter())))
raise ValueError("The rows/columns must be of equal length.")
if is_iterable(other):
other = valid_container(other, len(self))
return _rounded(list(map(truediv, other, self._fast_iter())))
return NotImplemented
def __bool__(self):
"""
Returns `False` if all elements in the row/column are zeros
and `True` otherwise.
"""
return any(self._fast_iter())
def __validity_check(self):
"""
Raises an error if the matrix has been resized
since when a "matrix-view" instance was created.
"""
if self.__size_hash != hash(self.__matrix.size):
raise BrokenMatrixView(
"The matrix has been resized after"
f" this matrix-view ({self!r}) was created.",
view_obj=self,
)
@abstractmethod
def __str__(self):
raise NotImplementedError
@abstractmethod
def __getitem__(self, sub):
raise NotImplementedError
@abstractmethod
def __setitem__(self, sub, value):
raise NotImplementedError
@abstractmethod
def __len__(self):
raise NotImplementedError
@abstractmethod
def __iter__(self):
raise NotImplementedError
@abstractmethod
def __contains__(self, item):
raise NotImplementedError
@abstractmethod
def __eq__(self, other):
raise NotImplementedError
@abstractmethod
def __iadd__(self, other):
raise NotImplementedError
@abstractmethod
def __isub__(self, other):
raise NotImplementedError
@abstractmethod
def __imul__(self, other):
raise NotImplementedError
@abstractmethod
def __imatmul__(self, other):
raise NotImplementedError
@abstractmethod
def __itruediv__(self, other):
raise NotImplementedError
# Utility functions
def _rounded(row_col: list) -> list:
limit = Element(f"1e-{utils.ROUND_LIMIT}")
return [Element(round(x)) if 0 < abs(x - round(x)) < limit else x for x in row_col]