0
# Field Arrays and Arithmetic
1
2
Core finite field array classes and factory functions for creating and manipulating Galois field arrays. This module provides the foundation for all finite field arithmetic operations with full NumPy integration and optimized performance through just-in-time compilation.
3
4
## Capabilities
5
6
### Field Factory Function
7
8
Creates `FieldArray` subclasses for specific finite fields GF(p^m) with customizable compilation modes and field parameters.
9
10
```python { .api }
11
def GF(order, *, irreducible_poly=None, primitive_element=None, verify=True, compile=None, repr=None):
12
"""
13
Creates a FieldArray subclass for GF(p^m).
14
15
Parameters:
16
- order (int): The order p^m of the field GF(p^m). Must be a prime power.
17
- irreducible_poly (PolyLike, optional): Irreducible polynomial defining field arithmetic.
18
Defaults to Conway polynomial if None.
19
- primitive_element (int | PolyLike, optional): Primitive element for exponential/log tables.
20
Defaults to automatically found primitive element if None.
21
- verify (bool): Whether to verify irreducible polynomial and primitive element. Default True.
22
- compile (str, optional): Compilation mode - "auto", "jit-lookup", "jit-calculate", or "python-calculate"
23
- repr (str, optional): Element representation - "int", "poly", or "power"
24
25
Returns:
26
Type[FieldArray]: A FieldArray subclass for the specified field
27
"""
28
29
def GF(characteristic, degree, *, irreducible_poly=None, primitive_element=None, verify=True, compile=None, repr=None):
30
"""
31
Alternative signature using characteristic and degree.
32
33
Parameters:
34
- characteristic (int): The characteristic p of the field GF(p^m). Must be prime.
35
- degree (int): The degree m of the field GF(p^m). Must be positive integer.
36
- Other parameters same as above
37
38
Returns:
39
Type[FieldArray]: A FieldArray subclass for GF(characteristic^degree)
40
"""
41
42
def Field(order, *, irreducible_poly=None, primitive_element=None, verify=True, compile=None, repr=None):
43
"""
44
Alternative name for GF() factory function.
45
46
Parameters: Same as GF()
47
Returns: Same as GF()
48
"""
49
```
50
51
### Base Field Array Class
52
53
Abstract base class for all finite field arrays, extending NumPy arrays with finite field arithmetic operations.
54
55
```python { .api }
56
class FieldArray(np.ndarray):
57
"""
58
Abstract NumPy ndarray subclass over GF(p^m).
59
60
Note: Cannot be instantiated directly. Use GF() factory to create subclasses.
61
"""
62
63
# Class properties (available on field classes created by GF())
64
@property
65
def characteristic(self) -> int:
66
"""The characteristic p of the field GF(p^m)."""
67
68
@property
69
def degree(self) -> int:
70
"""The degree m of the field GF(p^m)."""
71
72
@property
73
def order(self) -> int:
74
"""The order p^m of the field."""
75
76
@property
77
def irreducible_poly(self) -> Poly:
78
"""The irreducible polynomial defining the field."""
79
80
@property
81
def primitive_element(self) -> FieldArray:
82
"""A primitive element of the field."""
83
84
@property
85
def elements(self) -> FieldArray:
86
"""All elements of the field as a 1-D array."""
87
88
@property
89
def units(self) -> FieldArray:
90
"""All non-zero (invertible) elements of the field."""
91
92
@property
93
def zeros(self) -> FieldArray:
94
"""The zero element of the field."""
95
96
@property
97
def ones(self) -> FieldArray:
98
"""The one element of the field."""
99
100
# Instance methods
101
def __init__(self, array, dtype=None, copy=True, order="K", subok=False, ndmin=0):
102
"""
103
Create a field array from array-like input.
104
105
Parameters:
106
- array: Array-like input to convert to field array
107
- dtype: Data type (optional)
108
- copy: Whether to copy the data
109
- order: Memory layout order
110
- subok: Whether to allow subclasses
111
- ndmin: Minimum number of dimensions
112
"""
113
114
def multiplicative_order(self) -> np.ndarray:
115
"""
116
Compute multiplicative order of each element.
117
118
Returns:
119
np.ndarray: Multiplicative orders with same shape as input
120
"""
121
122
def is_primitive_element(self) -> np.ndarray:
123
"""
124
Test if elements are primitive (generators of multiplicative group).
125
126
Returns:
127
np.ndarray: Boolean array indicating primitive elements
128
"""
129
130
def minimal_poly(self) -> Poly:
131
"""
132
Compute minimal polynomial of elements over the prime subfield.
133
134
Returns:
135
Poly: Minimal polynomial(s)
136
"""
137
138
def characteristic_poly(self) -> Poly:
139
"""
140
Compute characteristic polynomial of elements.
141
142
Returns:
143
Poly: Characteristic polynomial(s)
144
"""
145
146
# Class methods
147
@classmethod
148
def compile(cls, mode):
149
"""
150
Recompile the ufuncs for the specified mode.
151
152
Parameters:
153
- mode (str): Compilation mode - "auto", "jit-lookup", "jit-calculate", or "python-calculate"
154
"""
155
156
@classmethod
157
def Random(cls, shape=(), low=0, high=None, dtype=None):
158
"""
159
Create random field array with specified shape.
160
161
Parameters:
162
- shape: Output shape
163
- low: Lower bound (inclusive)
164
- high: Upper bound (exclusive), defaults to field order
165
- dtype: Data type
166
167
Returns:
168
FieldArray: Random field array
169
"""
170
171
@classmethod
172
def Zeros(cls, shape, dtype=None):
173
"""
174
Create field array of zeros.
175
176
Parameters:
177
- shape: Output shape
178
- dtype: Data type
179
180
Returns:
181
FieldArray: Array of zeros
182
"""
183
184
@classmethod
185
def Ones(cls, shape, dtype=None):
186
"""
187
Create field array of ones.
188
189
Parameters:
190
- shape: Output shape
191
- dtype: Data type
192
193
Returns:
194
FieldArray: Array of ones
195
"""
196
197
@classmethod
198
def Identity(cls, size, dtype=None):
199
"""
200
Create identity matrix.
201
202
Parameters:
203
- size: Matrix size
204
- dtype: Data type
205
206
Returns:
207
FieldArray: Identity matrix
208
"""
209
210
@classmethod
211
def Range(cls, start, stop=None, step=1, dtype=None):
212
"""
213
Create field array with range of values.
214
215
Parameters:
216
- start: Start value (or stop if stop is None)
217
- stop: Stop value (exclusive)
218
- step: Step size
219
- dtype: Data type
220
221
Returns:
222
FieldArray: Range array
223
"""
224
```
225
226
### Optimized Binary Field Class
227
228
Specialized optimized implementation for GF(2) binary field operations with enhanced performance.
229
230
```python { .api }
231
class GF2(FieldArray):
232
"""
233
Optimized FieldArray implementation for GF(2).
234
235
This class provides optimized arithmetic for the binary field GF(2)
236
where addition is XOR and multiplication is AND.
237
"""
238
239
# All FieldArray methods available with GF(2) optimizations
240
# Additional GF(2)-specific optimizations are transparent to the user
241
```
242
243
## Usage Examples
244
245
### Creating Field Classes
246
247
```python
248
import galois
249
250
# Create GF(2^8) using order
251
GF256 = galois.GF(256)
252
print(f"Field: {GF256.name}")
253
print(f"Order: {GF256.order}")
254
255
# Create GF(5^3) using characteristic and degree
256
GF125 = galois.GF(5, 3)
257
print(f"Characteristic: {GF125.characteristic}")
258
print(f"Degree: {GF125.degree}")
259
260
# Create with custom irreducible polynomial
261
irreducible = galois.Poly([1, 0, 1, 1, 1], field=galois.GF(2)) # x^4 + x^2 + x + 1
262
GF16 = galois.GF(2**4, irreducible_poly=irreducible)
263
264
# Use optimized GF(2) class
265
binary_field = galois.GF2
266
```
267
268
### Creating and Using Field Arrays
269
270
```python
271
import galois
272
import numpy as np
273
274
# Create field class
275
GF = galois.GF(2**4)
276
277
# Create field arrays (similar to NumPy)
278
a = GF([1, 2, 3, 4])
279
b = GF([5, 6, 7, 8])
280
281
# Basic arithmetic (all in finite field)
282
c = a + b # Addition
283
d = a * b # Multiplication
284
e = a ** 2 # Exponentiation
285
f = a / b # Division (multiplication by inverse)
286
287
# Matrix operations
288
A = GF([[1, 2], [3, 4]])
289
x = GF([1, 2])
290
y = A @ x # Matrix multiplication
291
292
# NumPy integration works seamlessly
293
trace = np.trace(A)
294
det = np.linalg.det(A)
295
inv = np.linalg.inv(A)
296
```
297
298
### Advanced Field Operations
299
300
```python
301
import galois
302
303
GF = galois.GF(2**8)
304
305
# Field properties
306
print(f"Primitive element: {GF.primitive_element}")
307
print(f"Irreducible polynomial: {GF.irreducible_poly}")
308
309
# Element analysis
310
x = GF([100, 200, 50])
311
orders = x.multiplicative_order()
312
is_primitive = x.is_primitive_element()
313
minimal_polys = x.minimal_poly()
314
315
# Random generation
316
random_array = GF.Random((3, 4))
317
zeros = GF.Zeros((2, 3))
318
ones = GF.Ones((2, 3))
319
identity = GF.Identity(4)
320
321
# Performance tuning
322
GF.compile("jit-lookup") # Use lookup tables for speed
323
```
324
325
## Performance Notes
326
327
- **Compilation Modes**:
328
- `"jit-lookup"`: Fast for small fields using precomputed tables
329
- `"jit-calculate"`: Memory-efficient for large fields using explicit calculation
330
- `"python-calculate"`: Fallback for very large fields
331
- **Memory vs Speed**: Lookup tables trade memory for speed
332
- **NumPy Integration**: All NumPy linear algebra functions work with field arrays
333
- **Optimizations**: GF(2) uses specialized bit operations for maximum performance