A performant NumPy extension for Galois fields and their applications
—
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.
Creates FieldArray subclasses for specific finite fields GF(p^m) with customizable compilation modes and field parameters.
def GF(order, *, irreducible_poly=None, primitive_element=None, verify=True, compile=None, repr=None):
"""
Creates a FieldArray subclass for GF(p^m).
Parameters:
- order (int): The order p^m of the field GF(p^m). Must be a prime power.
- irreducible_poly (PolyLike, optional): Irreducible polynomial defining field arithmetic.
Defaults to Conway polynomial if None.
- primitive_element (int | PolyLike, optional): Primitive element for exponential/log tables.
Defaults to automatically found primitive element if None.
- verify (bool): Whether to verify irreducible polynomial and primitive element. Default True.
- compile (str, optional): Compilation mode - "auto", "jit-lookup", "jit-calculate", or "python-calculate"
- repr (str, optional): Element representation - "int", "poly", or "power"
Returns:
Type[FieldArray]: A FieldArray subclass for the specified field
"""
def GF(characteristic, degree, *, irreducible_poly=None, primitive_element=None, verify=True, compile=None, repr=None):
"""
Alternative signature using characteristic and degree.
Parameters:
- characteristic (int): The characteristic p of the field GF(p^m). Must be prime.
- degree (int): The degree m of the field GF(p^m). Must be positive integer.
- Other parameters same as above
Returns:
Type[FieldArray]: A FieldArray subclass for GF(characteristic^degree)
"""
def Field(order, *, irreducible_poly=None, primitive_element=None, verify=True, compile=None, repr=None):
"""
Alternative name for GF() factory function.
Parameters: Same as GF()
Returns: Same as GF()
"""Abstract base class for all finite field arrays, extending NumPy arrays with finite field arithmetic operations.
class FieldArray(np.ndarray):
"""
Abstract NumPy ndarray subclass over GF(p^m).
Note: Cannot be instantiated directly. Use GF() factory to create subclasses.
"""
# Class properties (available on field classes created by GF())
@property
def characteristic(self) -> int:
"""The characteristic p of the field GF(p^m)."""
@property
def degree(self) -> int:
"""The degree m of the field GF(p^m)."""
@property
def order(self) -> int:
"""The order p^m of the field."""
@property
def irreducible_poly(self) -> Poly:
"""The irreducible polynomial defining the field."""
@property
def primitive_element(self) -> FieldArray:
"""A primitive element of the field."""
@property
def elements(self) -> FieldArray:
"""All elements of the field as a 1-D array."""
@property
def units(self) -> FieldArray:
"""All non-zero (invertible) elements of the field."""
@property
def zeros(self) -> FieldArray:
"""The zero element of the field."""
@property
def ones(self) -> FieldArray:
"""The one element of the field."""
# Instance methods
def __init__(self, array, dtype=None, copy=True, order="K", subok=False, ndmin=0):
"""
Create a field array from array-like input.
Parameters:
- array: Array-like input to convert to field array
- dtype: Data type (optional)
- copy: Whether to copy the data
- order: Memory layout order
- subok: Whether to allow subclasses
- ndmin: Minimum number of dimensions
"""
def multiplicative_order(self) -> np.ndarray:
"""
Compute multiplicative order of each element.
Returns:
np.ndarray: Multiplicative orders with same shape as input
"""
def is_primitive_element(self) -> np.ndarray:
"""
Test if elements are primitive (generators of multiplicative group).
Returns:
np.ndarray: Boolean array indicating primitive elements
"""
def minimal_poly(self) -> Poly:
"""
Compute minimal polynomial of elements over the prime subfield.
Returns:
Poly: Minimal polynomial(s)
"""
def characteristic_poly(self) -> Poly:
"""
Compute characteristic polynomial of elements.
Returns:
Poly: Characteristic polynomial(s)
"""
# Class methods
@classmethod
def compile(cls, mode):
"""
Recompile the ufuncs for the specified mode.
Parameters:
- mode (str): Compilation mode - "auto", "jit-lookup", "jit-calculate", or "python-calculate"
"""
@classmethod
def Random(cls, shape=(), low=0, high=None, dtype=None):
"""
Create random field array with specified shape.
Parameters:
- shape: Output shape
- low: Lower bound (inclusive)
- high: Upper bound (exclusive), defaults to field order
- dtype: Data type
Returns:
FieldArray: Random field array
"""
@classmethod
def Zeros(cls, shape, dtype=None):
"""
Create field array of zeros.
Parameters:
- shape: Output shape
- dtype: Data type
Returns:
FieldArray: Array of zeros
"""
@classmethod
def Ones(cls, shape, dtype=None):
"""
Create field array of ones.
Parameters:
- shape: Output shape
- dtype: Data type
Returns:
FieldArray: Array of ones
"""
@classmethod
def Identity(cls, size, dtype=None):
"""
Create identity matrix.
Parameters:
- size: Matrix size
- dtype: Data type
Returns:
FieldArray: Identity matrix
"""
@classmethod
def Range(cls, start, stop=None, step=1, dtype=None):
"""
Create field array with range of values.
Parameters:
- start: Start value (or stop if stop is None)
- stop: Stop value (exclusive)
- step: Step size
- dtype: Data type
Returns:
FieldArray: Range array
"""Specialized optimized implementation for GF(2) binary field operations with enhanced performance.
class GF2(FieldArray):
"""
Optimized FieldArray implementation for GF(2).
This class provides optimized arithmetic for the binary field GF(2)
where addition is XOR and multiplication is AND.
"""
# All FieldArray methods available with GF(2) optimizations
# Additional GF(2)-specific optimizations are transparent to the userimport galois
# Create GF(2^8) using order
GF256 = galois.GF(256)
print(f"Field: {GF256.name}")
print(f"Order: {GF256.order}")
# Create GF(5^3) using characteristic and degree
GF125 = galois.GF(5, 3)
print(f"Characteristic: {GF125.characteristic}")
print(f"Degree: {GF125.degree}")
# Create with custom irreducible polynomial
irreducible = galois.Poly([1, 0, 1, 1, 1], field=galois.GF(2)) # x^4 + x^2 + x + 1
GF16 = galois.GF(2**4, irreducible_poly=irreducible)
# Use optimized GF(2) class
binary_field = galois.GF2import galois
import numpy as np
# Create field class
GF = galois.GF(2**4)
# Create field arrays (similar to NumPy)
a = GF([1, 2, 3, 4])
b = GF([5, 6, 7, 8])
# Basic arithmetic (all in finite field)
c = a + b # Addition
d = a * b # Multiplication
e = a ** 2 # Exponentiation
f = a / b # Division (multiplication by inverse)
# Matrix operations
A = GF([[1, 2], [3, 4]])
x = GF([1, 2])
y = A @ x # Matrix multiplication
# NumPy integration works seamlessly
trace = np.trace(A)
det = np.linalg.det(A)
inv = np.linalg.inv(A)import galois
GF = galois.GF(2**8)
# Field properties
print(f"Primitive element: {GF.primitive_element}")
print(f"Irreducible polynomial: {GF.irreducible_poly}")
# Element analysis
x = GF([100, 200, 50])
orders = x.multiplicative_order()
is_primitive = x.is_primitive_element()
minimal_polys = x.minimal_poly()
# Random generation
random_array = GF.Random((3, 4))
zeros = GF.Zeros((2, 3))
ones = GF.Ones((2, 3))
identity = GF.Identity(4)
# Performance tuning
GF.compile("jit-lookup") # Use lookup tables for speed"jit-lookup": Fast for small fields using precomputed tables"jit-calculate": Memory-efficient for large fields using explicit calculation"python-calculate": Fallback for very large fieldsInstall with Tessl CLI
npx tessl i tessl/pypi-galois