0
# Configuration and Types
1
2
Package configuration options and type system for enhanced development experience. This module provides global settings for output formatting and comprehensive type hints for improved code clarity and IDE support.
3
4
## Capabilities
5
6
### Print Configuration
7
8
Global print options for controlling how field arrays and polynomials are displayed, with both permanent settings and temporary context managers.
9
10
```python { .api }
11
def set_printoptions(**kwargs):
12
"""
13
Set global print options for field arrays.
14
15
Parameters:
16
- coeffs (str, optional): Coefficient display format
17
- "int": Display as integers (default)
18
- "poly": Display as polynomial representation
19
- "power": Display as powers of primitive element
20
- details (bool, optional): Show detailed field information, default True
21
- precision (int, optional): Precision for floating point display
22
- threshold (int, optional): Array size threshold for summarization
23
- edgeitems (int, optional): Number of edge items in summarized arrays
24
- linewidth (int, optional): Character width for line wrapping
25
- suppress (bool, optional): Suppress small floating point values
26
"""
27
28
def get_printoptions():
29
"""
30
Get current global print options.
31
32
Returns:
33
dict: Current print option settings
34
"""
35
36
def printoptions(**kwargs):
37
"""
38
Context manager for temporary print option changes.
39
40
Parameters: Same as set_printoptions()
41
42
Returns:
43
Context manager that temporarily modifies print options
44
45
Example:
46
with galois.printoptions(coeffs="poly"):
47
print(field_array) # Uses polynomial representation
48
# Reverts to previous settings after context
49
"""
50
```
51
52
### Type Definitions
53
54
Comprehensive type system providing type hints and aliases for improved code clarity, IDE support, and static type checking.
55
56
```python { .api }
57
# Import the typing module
58
import galois.typing
59
60
# Core type aliases for field elements and arrays
61
ElementLike = Union[int, np.integer, FieldArray]
62
"""Type alias for objects that can be coerced to field elements."""
63
64
IterableLike = Union[Iterable[ElementLike], Iterable[Iterable[ElementLike]]]
65
"""Type alias for iterable objects that can be coerced to field arrays."""
66
67
ArrayLike = Union[FieldArray, IterableLike, ElementLike]
68
"""Type alias for objects that can be coerced to field arrays."""
69
70
ShapeLike = Union[int, Sequence[int]]
71
"""Type alias for objects that can be coerced to array shapes."""
72
73
DTypeLike = Union[np.dtype, type, str]
74
"""Type alias for objects that can be coerced to NumPy dtypes."""
75
76
PolyLike = Union[Poly, ArrayLike, str, int]
77
"""Type alias for objects that can be coerced to polynomials."""
78
```
79
80
## Usage Examples
81
82
### Print Option Configuration
83
84
```python
85
import galois
86
import numpy as np
87
88
# Create a finite field
89
GF = galois.GF(2**4)
90
x = GF([1, 2, 3, 4, 5])
91
92
# Default integer representation
93
print("Default (int) representation:")
94
print(x)
95
96
# Change to polynomial representation
97
galois.set_printoptions(coeffs="poly")
98
print("\nPolynomial representation:")
99
print(x)
100
101
# Change to power representation
102
galois.set_printoptions(coeffs="power")
103
print("\nPower representation:")
104
print(x)
105
106
# Reset to default
107
galois.set_printoptions(coeffs="int")
108
print("\nBack to integer representation:")
109
print(x)
110
```
111
112
### Temporary Print Options with Context Manager
113
114
```python
115
import galois
116
117
GF = galois.GF(3**3)
118
poly = galois.Poly([1, 2, 0, 1], field=GF)
119
array = GF([5, 10, 15, 20])
120
121
print("Default settings:")
122
print(f"Polynomial: {poly}")
123
print(f"Array: {array}")
124
125
# Temporary change to polynomial representation
126
with galois.printoptions(coeffs="poly"):
127
print("\nInside context (poly representation):")
128
print(f"Polynomial: {poly}")
129
print(f"Array: {array}")
130
131
print("\nAfter context (back to default):")
132
print(f"Polynomial: {poly}")
133
print(f"Array: {array}")
134
135
# Multiple temporary changes
136
with galois.printoptions(coeffs="power", details=False):
137
print("\nPower representation without details:")
138
print(f"Array: {array}")
139
```
140
141
### Type Hints in Practice
142
143
```python
144
import galois
145
from galois.typing import ElementLike, ArrayLike, PolyLike
146
from typing import Union
147
import numpy as np
148
149
def create_field_array(data: ArrayLike, field_order: int) -> galois.FieldArray:
150
"""
151
Create field array with proper type hints.
152
153
Args:
154
data: Input data coercible to field array
155
field_order: Order of the finite field
156
157
Returns:
158
Field array over GF(field_order)
159
"""
160
GF = galois.GF(field_order)
161
return GF(data)
162
163
def polynomial_from_input(coeffs: PolyLike, field: type = None) -> galois.Poly:
164
"""
165
Create polynomial from various input types.
166
167
Args:
168
coeffs: Polynomial coefficients (various formats accepted)
169
field: Finite field class
170
171
Returns:
172
Polynomial over specified field
173
"""
174
if isinstance(coeffs, str):
175
# Handle string representation
176
return galois.Poly.Str(coeffs, field=field)
177
elif isinstance(coeffs, int):
178
# Handle integer representation
179
return galois.Poly.Int(coeffs, field=field)
180
else:
181
# Handle array-like coefficients
182
return galois.Poly(coeffs, field=field)
183
184
# Usage examples with type checking
185
GF16 = galois.GF(16)
186
187
# These all satisfy ArrayLike
188
array1 = create_field_array([1, 2, 3], 16) # List input
189
array2 = create_field_array(np.array([4, 5, 6]), 16) # NumPy array input
190
array3 = create_field_array(GF16([7, 8, 9]), 16) # Field array input
191
192
# These all satisfy PolyLike
193
poly1 = polynomial_from_input([1, 0, 1], GF16) # List coefficients
194
poly2 = polynomial_from_input("x^2 + 1", GF16) # String representation
195
poly3 = polynomial_from_input(5, GF16) # Integer representation
196
197
print(f"Arrays created: {array1}, {array2}, {array3}")
198
print(f"Polynomials created: {poly1}, {poly2}, {poly3}")
199
```
200
201
### Advanced Print Configuration
202
203
```python
204
import galois
205
import numpy as np
206
207
# Create larger field for demonstration
208
GF = galois.GF(2**8)
209
210
# Create large array to test threshold settings
211
large_array = GF.Random(20)
212
213
# Default printing
214
print("Default printing:")
215
print(large_array)
216
217
# Modify threshold and edge items
218
galois.set_printoptions(threshold=10, edgeitems=2)
219
print("\nWith threshold=10, edgeitems=2:")
220
print(large_array)
221
222
# Show field details
223
galois.set_printoptions(details=True)
224
print(f"\nWith details=True:")
225
print(f"Field info: {GF}")
226
227
# Polynomial representation with custom formatting
228
galois.set_printoptions(coeffs="poly", linewidth=50)
229
poly_array = GF([1, 2, 3, 4, 5, 6, 7, 8])
230
print(f"\nPolynomial representation with linewidth=50:")
231
print(poly_array)
232
233
# Get current settings
234
current_options = galois.get_printoptions()
235
print(f"\nCurrent print options: {current_options}")
236
237
# Reset to defaults
238
galois.set_printoptions(coeffs="int", threshold=1000, edgeitems=3, details=True, linewidth=75)
239
```
240
241
### Working with Type System for Development
242
243
```python
244
import galois
245
from galois.typing import *
246
from typing import List, Tuple, Optional
247
248
def batch_encode_messages(
249
messages: List[ArrayLike],
250
field_order: int,
251
code_params: Tuple[int, int]
252
) -> List[galois.FieldArray]:
253
"""
254
Batch encode multiple messages using Reed-Solomon code.
255
256
Args:
257
messages: List of message arrays
258
field_order: Finite field order
259
code_params: (n, k) code parameters
260
261
Returns:
262
List of encoded codewords
263
"""
264
n, k = code_params
265
rs = galois.ReedSolomon(n, k)
266
267
encoded = []
268
for msg in messages:
269
# Convert to proper field array
270
field_msg = rs.field(msg)
271
codeword = rs.encode(field_msg)
272
encoded.append(codeword)
273
274
return encoded
275
276
def analyze_polynomial(
277
poly_input: PolyLike,
278
field_class: Optional[type] = None
279
) -> dict:
280
"""
281
Analyze polynomial properties with flexible input handling.
282
283
Args:
284
poly_input: Polynomial in various formats
285
field_class: Field class for polynomial
286
287
Returns:
288
Dictionary of analysis results
289
"""
290
# Convert input to polynomial
291
if isinstance(poly_input, galois.Poly):
292
poly = poly_input
293
else:
294
poly = galois.Poly(poly_input, field=field_class)
295
296
# Perform analysis
297
analysis = {
298
"degree": poly.degree,
299
"is_monic": poly.is_monic(),
300
"is_irreducible": poly.is_irreducible(),
301
"coefficients": poly.coeffs,
302
"field": poly.field.name,
303
}
304
305
return analysis
306
307
# Example usage with proper types
308
messages = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
309
encoded_batch = batch_encode_messages(messages, 16, (15, 9))
310
print(f"Encoded {len(encoded_batch)} messages")
311
312
# Analyze different polynomial inputs
313
poly_analysis1 = analyze_polynomial([1, 0, 1, 1]) # List coefficients
314
poly_analysis2 = analyze_polynomial("x^3 + x + 1") # String format
315
print(f"Analysis 1: {poly_analysis1}")
316
print(f"Analysis 2: {poly_analysis2}")
317
```
318
319
## Performance and Development Notes
320
321
- **Global State**: Print options are stored globally and persist across field operations
322
- **Context Safety**: Context managers ensure settings revert even if exceptions occur
323
- **Type Safety**: Type aliases improve code clarity and enable static type checking tools
324
- **IDE Support**: Enhanced autocompletion and error detection in development environments
325
- **Memory Management**: Print options don't affect computational performance, only display formatting