Skip to content

Instantly share code, notes, and snippets.

@popcornell
Last active May 16, 2023 05:20
Show Gist options
  • Save popcornell/bc29d1b7ba37d824335ab7b6280f7fec to your computer and use it in GitHub Desktop.
Save popcornell/bc29d1b7ba37d824335ab7b6280f7fec to your computer and use it in GitHub Desktop.
Gaussian elimination for binary matrices ( all elements in GF(2) ) implemented in numba python and numpy for efficiency.
import numpy as np
import numba
@numba.jit(nopython=True, parallel=True) #parallel speeds up computation only over very large matrices
# M is a mxn matrix binary matrix
# all elements in M should be uint8
def gf2elim(M):
m,n = M.shape
i=0
j=0
while i < m and j < n:
# find value and index of largest element in remainder of column j
k = np.argmax(M[i:, j]) +i
# swap rows
#M[[k, i]] = M[[i, k]] this doesn't work with numba
temp = np.copy(M[k])
M[k] = M[i]
M[i] = temp
aijn = M[i, j:]
col = np.copy(M[:, j]) #make a copy otherwise M will be directly affected
col[i] = 0 #avoid xoring pivot row with itself
flip = np.outer(col, aijn)
M[:, j:] = M[:, j:] ^ flip
i += 1
j +=1
return M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment