-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathfieldmath.py
369 lines (267 loc) · 11.5 KB
/
fieldmath.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#
# Reed-Solomon error-correcting code decoder (Python)
#
# Copyright (c) 2022 Project Nayuki
# All rights reserved. Contact Nayuki for licensing.
# https://www.nayuki.io/page/reed-solomon-error-correcting-code-decoder
#
# ---- Field abstract class ----
class Field:
"""An abstract base class representing a field in abstract algebra. Every field must
satisfy all these axioms, where x, y, z are arbitrary elements of the field:
- 0 is an element of the field, and 0 + x = x. (Existence of additive identity)
- 1 is an element of the field, and 1 * x = x. (Existence of multiplicative identity)
- 0 != 1. (Distinctness of additive and multiplicative identities)
- x + y = y + x. (Commutativity of addition)
- x * y = y * x. (Commutativity of multiplication)
- (x + y) + z = x + (y + z). (Associativity of addition)
- (x * y) * z = x * (y * z). (Associativity of multiplication)
- x * (y + z) = (x * y) + (x * z). (Distributivity of multiplication over addition)
- -x is an element of the field, such that x + (-x) = 0. (Existence of additive inverse)
- If x != 0, then x^-1 is an element of the field, such that x * (x^-1) = 1. (Existence of multiplicative inverse)
Each Field object should be stateless and immutable. The field element objects should be immutable too."""
# -- Constant values --
def zero(self):
"""Returns the additive identity constant of this field."""
raise NotImplementedError()
def one(self):
"""Returns the multiplicative identity constant of this field."""
raise NotImplementedError()
# -- Comparison --
def equals(self, x, y):
"""Tests whether the two given elements are equal.
Note that the elements are not required to implement their own __eq__() correctly.
This means x == y is allowed to mismatch f.equals(x, y)."""
raise NotImplementedError()
# -- Addition/subtraction --
def negate(self, x):
"""Returns the additive inverse of the given element."""
raise NotImplementedError()
def add(self, x, y):
"""Returns the sum of the two given elements."""
raise NotImplementedError()
def subtract(self, x, y):
"""Returns the difference of the two given elements.
A correct default implementation is provided."""
return self.add(x, self.negate(y))
# -- Multiplication/division --
def reciprocal(self, x):
"""Returns the multiplicative inverse of the given non-zero element."""
raise NotImplementedError()
def multiply(self, x, y):
"""Returns the product of the two given elements."""
raise NotImplementedError()
def divide(self, x, y):
"""Returns the quotient of the given elements.
A correct default implementation is provided."""
return self.multiply(x, self.reciprocal(y))
# ---- PrimeField class ----
class PrimeField(Field):
"""A finite field of the form Z_p, where p is a prime number.
Each element of this kind of field is an integer in the range [0, p).
Both the field and the elements are immutable and thread-safe."""
def __init__(self, mod):
"""Constructs a prime field with the given modulus. The modulus must be a
prime number, but this crucial property is not checked by the constructor."""
if mod < 2:
raise ValueError("Modulus must be prime")
# The modulus of this field, which is also the number of elements in this finite field. Must be prime.
self.modulus = mod
def zero(self):
return 0
def one(self):
return 1
def equals(self, x, y):
return self._check(x) == self._check(y)
def negate(self, x):
return -self._check(x) % self.modulus
def add(self, x, y):
return (self._check(x) + self._check(y)) % self.modulus
def subtract(self, x, y):
return (self._check(x) - self._check(y)) % self.modulus
def multiply(self, x, y):
return (self._check(x) * self._check(y)) % self.modulus
def reciprocal(self, w):
return pow(self._check(w), -1, self.modulus)
# Checks if the given object is the correct type and within
# the range of valid values, and returns the value itself.
def _check(self, x):
if not isinstance(x, int):
raise TypeError()
if not (0 <= x < self.modulus):
raise ValueError("Not an element of this field: " + str(x))
return x
# ---- BinaryField class ----
class BinaryField(Field):
"""A Galois field of the form GF(2^n/mod). Each element of this kind of field is a
polynomial of degree less than n where each monomial coefficient is either 0 or 1.
Both the field and the elements are immutable and thread-safe."""
def __init__(self, mod):
"""Constructs a binary field with the given modulus. The modulus must have
degree at least 1. Also the modulus must be irreducible (not factorable) in Z_2,
but this critical property is not checked by the constructor."""
if mod <= 1:
raise ValueError("Invalid modulus")
# The modulus of this field represented as a string of bits in natural order.
# For example, the modulus x^5 + x^1 + x^0 is represented by the integer value 0b100011 (binary) or 35 (decimal).
self.modulus = mod
# The number of (unique) elements in this field. It is a positive power of 2, e.g. 2, 4, 8, 16, etc.
# The size of the field is equal to 2 to the power of the degree of the modulus.
self.size = 1 << (mod.bit_length() - 1)
def zero(self):
return 0
def one(self):
return 1
def equals(self, x, y):
return self._check(x) == self._check(y)
def negate(self, x):
return self._check(x)
def add(self, x, y):
return self._check(x) ^ self._check(y)
def subtract(self, x, y):
return self.add(x, y)
def multiply(self, x, y):
self._check(x)
self._check(y)
result = 0
while y != 0:
if y & 1 != 0:
result ^= x
x <<= 1
if x >= self.size:
x ^= self.modulus
y >>= 1
return result
def reciprocal(self, w):
# Extended Euclidean GCD algorithm
x = self.modulus
y = self._check(w)
if y == 0:
raise ValueError("Division by zero")
a = 0
b = 1
while y != 0:
q, r = self._divide_and_remainder(x, y)
if q == self.modulus:
q = 0
x, y = y, r
a, b = b, (a ^ self.multiply(q, b))
if x == 1:
return a
else: # All non-zero values must have a reciprocal
raise AssertionError("Field modulus is not irreducible")
# Returns a new tuple containing the pair of values (x div y, x mod y).
def _divide_and_remainder(self, x, y):
quotient = 0
ylen = y.bit_length()
for i in reversed(range(x.bit_length() - ylen + 1)):
if x.bit_length() == ylen + i:
x ^= y << i
quotient |= 1 << i
return (quotient, x)
# Checks if the given object is the correct type and within the
# range of valid values, and returns the same value.
def _check(self, x):
if not isinstance(x, int):
raise TypeError()
if not (0 <= x < self.size):
raise ValueError("Not an element of this field: " + str(x))
return x
# ---- Matrix class ----
class Matrix:
"""Represents a mutable matrix of field elements, supporting linear algebra operations.
Note that the dimensions of a matrix cannot be changed after construction. Not thread-safe."""
def __init__(self, rows, cols, field):
"""Constructs a blank matrix with the given number of rows and columns,
with operations from the given field. All the elements are initially None."""
if rows <= 0 or cols <= 0:
raise ValueError("Invalid number of rows or columns")
if not isinstance(field, Field):
raise TypeError()
# The field used to operate on the values in the matrix.
self.f = field
# The values of the matrix stored in row-major order, with each element initially None.
self.values = [[None] * cols for _ in range(rows)]
# -- Basic matrix methods --
def row_count(self):
"""Returns the number of rows in this matrix, which is a positive integer."""
return len(self.values)
def column_count(self):
"""Returns the number of columns in this matrix, which is a positive integer."""
return len(self.values[0])
def get(self, row, col):
"""Returns the element at the given location in this matrix. The result may be None."""
if not (0 <= row < len(self.values) and 0 <= col < len(self.values[row])):
raise IndexError("Row or column index out of bounds")
return self.values[row][col]
def set(self, row, col, val):
"""Stores the given element at the given location in this matrix. The value to store can be None."""
if not (0 <= row < len(self.values) and 0 <= col < len(self.values[row])):
raise IndexError("Row or column index out of bounds")
self.values[row][col] = val
def __str__(self):
"""Returns a string representation of this matrix. The format is subject to change."""
result = "["
for (i, row) in enumerate(self.values):
if i > 0:
result += ",\n "
result += "[" + ", ".join(str(val) for val in row) + "]"
return result + "]"
# -- Simple matrix row operations --
def swap_rows(self, row0, row1):
"""Swaps the two given rows of this matrix. If the two row indices are the same, the swap is a no-op.
Any matrix element can be None when performing this operation."""
if not (0 <= row0 < len(self.values) and 0 <= row1 < len(self.values)):
raise IndexError("Row index out of bounds")
self.values[row0], self.values[row1] = self.values[row1], self.values[row0]
def multiply_row(self, row, factor):
"""Multiplies the given row in this matrix by the given factor. In other words, row *= factor.
The elements of the given row should all be non-None when performing this operation."""
if not (0 <= row < len(self.values)):
raise IndexError("Row index out of bounds")
self.values[row] = [self.f.multiply(val, factor) for val in self.values[row]]
def add_rows(self, srcrow, destrow, factor):
"""Adds the first given row in this matrix multiplied by the given factor to the second given row.
In other words, destdow += srcrow * factor. The elements of the given two rows
should all be non-None when performing this operation."""
if not (0 <= srcrow < len(self.values) and 0 <= destrow < len(self.values)):
raise IndexError("Row index out of bounds")
self.values[destrow] = [self.f.add(destval, self.f.multiply(srcval, factor))
for (srcval, destval) in zip(self.values[srcrow], self.values[destrow])]
# -- Advanced matrix operations --
def reduced_row_echelon_form(self):
"""Converts this matrix to reduced row echelon form (RREF) using Gauss-Jordan elimination.
All elements of this matrix should be non-None when performing this operation.
Always succeeds, as long as the field follows the mathematical rules and does not raise an exception.
The time complexity of this operation is O(rows * cols * min(rows, cols))."""
rows = self.row_count()
cols = self.column_count()
# Compute row echelon form (REF)
numpivots = 0
for j in range(cols): # For each column
if numpivots >= rows:
break
pivotrow = numpivots
while pivotrow < rows and self.f.equals(self.get(pivotrow, j), self.f.zero()):
pivotrow += 1
if pivotrow == rows:
continue # Cannot eliminate on this column
self.swap_rows(numpivots, pivotrow)
pivotrow = numpivots
numpivots += 1
# Simplify the pivot row
self.multiply_row(pivotrow, self.f.reciprocal(self.get(pivotrow, j)))
# Eliminate rows below
for i in range(pivotrow + 1, rows):
self.add_rows(pivotrow, i, self.f.negate(self.get(i, j)))
# Compute reduced row echelon form (RREF)
for i in reversed(range(numpivots)):
# Find pivot
pivotcol = 0
while pivotcol < cols and self.f.equals(self.get(i, pivotcol), self.f.zero()):
pivotcol += 1
if pivotcol == cols:
continue # Skip this all-zero row
# Eliminate rows above
for j in range(i):
self.add_rows(i, j, self.f.negate(self.get(j, pivotcol)))