summaryrefslogtreecommitdiff
path: root/gr-fec/python
diff options
context:
space:
mode:
authorjfmadeira <jf.madeira@campus.fct.unl.pt>2021-07-14 15:39:03 +0100
committermormj <34754695+mormj@users.noreply.github.com>2021-07-19 06:45:27 -0400
commit9fae70445d6849a074877d95fe436b1de8fbc688 (patch)
tree0399a4f1da1c3928bd27b40ba567255c7d3917f3 /gr-fec/python
parenta53fabf139ee145cb0d945547db77b30eb887f0e (diff)
fec: Removed star import numpy, ran auto formatter
Signed-off-by: jfmadeira <jf.madeira@campus.fct.unl.pt>
Diffstat (limited to 'gr-fec/python')
-rw-r--r--gr-fec/python/fec/LDPC/Generate_LDPC_matrix_functions.py308
1 files changed, 160 insertions, 148 deletions
diff --git a/gr-fec/python/fec/LDPC/Generate_LDPC_matrix_functions.py b/gr-fec/python/fec/LDPC/Generate_LDPC_matrix_functions.py
index d37e8c6106..0a5d732dd4 100644
--- a/gr-fec/python/fec/LDPC/Generate_LDPC_matrix_functions.py
+++ b/gr-fec/python/fec/LDPC/Generate_LDPC_matrix_functions.py
@@ -9,13 +9,16 @@
#
-import string, sys
-from numpy import *
-from numpy.random import shuffle, randint
+import string
+import sys
+
+import numpy as np
from numpy.linalg import inv, det
+from numpy.random import shuffle, randint
+
# 0 gives no debug output, 1 gives a little, 2 gives a lot
-#verbose = 1 #######################################################
+# verbose = 1 #######################################################
def read_alist_file(filename):
"""
@@ -25,22 +28,23 @@ def read_alist_file(filename):
http://www.inference.phy.cam.ac.uk/mackay/codes/alist.html
"""
- myfile = open(filename,'r')
- data = myfile.readlines()
- size = data[0].split()
- numCols = int(size[0])
- numRows = int(size[1])
- H = zeros((numRows,numCols))
- for lineNumber in arange(4,4+numCols):
+ myfile = open(filename, 'r')
+ data = myfile.readlines()
+ size = data[0].split()
+ numCols = int(size[0])
+ numRows = int(size[1])
+ H = zeros((numRows, numCols))
+ for lineNumber in np.arange(4, 4 + numCols):
indices = data[lineNumber].split()
for index in indices:
- H[int(index)-1,lineNumber-4] = 1
+ H[int(index) - 1, lineNumber - 4] = 1
# The subsequent lines in the file list the indices for where
# the 1s are in the rows, but this is redundant
# information.
return H
+
def write_alist_file(filename, H, verbose=0):
"""
This function writes an alist file for the parity check
@@ -49,7 +53,7 @@ def write_alist_file(filename, H, verbose=0):
"""
try:
- myfile = open(filename,'w')
+ myfile = open(filename, 'w')
except EnvironmentError:
# This is an api, we should be using a logging interface and not
# terminating the application directly.
@@ -65,30 +69,30 @@ def write_alist_file(filename, H, verbose=0):
tempstring1 = ''
tempstring2 = ''
maxRowWeight = 0
- for rowNum in arange(numRows):
- nonzeros = array(H[rowNum,:].nonzero())
+ for rowNum in np.arange(numRows):
+ nonzeros = array(H[rowNum, :].nonzero())
rowWeight = nonzeros.shape[1]
if rowWeight > maxRowWeight:
maxRowWeight = rowWeight
tempstring1 = tempstring1 + repr(rowWeight) + ' '
for tempArray in nonzeros:
for index in tempArray:
- tempstring2 = tempstring2 + repr(index+1) + ' '
+ tempstring2 = tempstring2 + repr(index + 1) + ' '
tempstring2 = tempstring2 + '\n'
tempstring1 = tempstring1 + '\n'
tempstring3 = ''
tempstring4 = ''
maxColWeight = 0
- for colNum in arange(numCols):
- nonzeros = array(H[:,colNum].nonzero())
+ for colNum in np.arange(numCols):
+ nonzeros = array(H[:, colNum].nonzero())
colWeight = nonzeros.shape[1]
if colWeight > maxColWeight:
maxColWeight = colWeight
tempstring3 = tempstring3 + repr(colWeight) + ' '
for tempArray in nonzeros:
for index in tempArray:
- tempstring4 = tempstring4 + repr(index+1) + ' '
+ tempstring4 = tempstring4 + repr(index + 1) + ' '
tempstring4 = tempstring4 + '\n'
tempstring3 = tempstring3 + '\n'
@@ -109,9 +113,10 @@ def write_alist_file(filename, H, verbose=0):
class LDPC_matrix(object):
""" Class for a LDPC parity check matrix """
- def __init__(self, alist_filename = None,
- n_p_q = None,
- H_matrix = None):
+
+ def __init__(self, alist_filename=None,
+ n_p_q=None,
+ H_matrix=None):
if (alist_filename != None):
self.H = read_alist_file(alist_filename)
elif (n_p_q != None):
@@ -126,9 +131,9 @@ class LDPC_matrix(object):
self.rank = linalg.matrix_rank(self.H)
self.numRows = self.H.shape[0]
self.n = self.H.shape[1]
- self.k = self.n -self.numRows
+ self.k = self.n - self.numRows
- def regular_LDPC_code_contructor(self,n_p_q):
+ def regular_LDPC_code_contructor(self, n_p_q):
"""
This function constructs a LDPC parity check matrix
H. The algorithm follows Gallager's approach where we create
@@ -150,33 +155,33 @@ class LDPC_matrix(object):
# For this algorithm, n/p must be an integer, because the
# number of rows in each submatrix must be a whole number.
- ratioTest = (n*1.0) / q
- if ratioTest%1 != 0:
+ ratioTest = (n * 1.0) / q
+ if ratioTest % 1 != 0:
print('\nError in regular_LDPC_code_contructor: The ', end='')
print('ratio of inputs n/q must be a whole number.\n')
return
# First submatrix first:
- m = (n*p) / q # number of rows in H matrix
- submatrix1 = zeros((m / p,n))
- for row in arange(m / p):
- range1 = row*q
- range2 = (row+1)*q
- submatrix1[row,range1:range2] = 1
+ m = (n * p) / q # number of rows in H matrix
+ submatrix1 = zeros((m / p, n))
+ for row in np.arange(m / p):
+ range1 = row * q
+ range2 = (row + 1) * q
+ submatrix1[row, range1:range2] = 1
H = submatrix1
# Create the other submatrices and vertically stack them on.
submatrixNum = 2
- newColumnOrder = arange(n)
+ newColumnOrder = np.arange(n)
while submatrixNum <= p:
- submatrix = zeros((m / p,n))
+ submatrix = zeros((m / p, n))
shuffle(newColumnOrder)
- for columnNum in arange(n):
- submatrix[:,columnNum] = \
- submatrix1[:,newColumnOrder[columnNum]]
+ for columnNum in np.arange(n):
+ submatrix[:, columnNum] = \
+ submatrix1[:, newColumnOrder[columnNum]]
- H = vstack((H,submatrix))
+ H = vstack((H, submatrix))
submatrixNum = submatrixNum + 1
# Double check the row weight and column weights.
@@ -185,21 +190,22 @@ class LDPC_matrix(object):
cols = size[1]
# Check the row weights.
- for rowNum in arange(rows):
- nonzeros = array(H[rowNum,:].nonzero())
+ for rowNum in np.arange(rows):
+ nonzeros = array(H[rowNum, :].nonzero())
if nonzeros.shape[1] != q:
print('Row', rowNum, 'has incorrect weight!')
return
# Check the column weights
- for columnNum in arange(cols):
- nonzeros = array(H[:,columnNum].nonzero())
+ for columnNum in np.arange(cols):
+ nonzeros = array(H[:, columnNum].nonzero())
if nonzeros.shape[1] != p:
print('Row', columnNum, 'has incorrect weight!')
return
return H
+
def greedy_upper_triangulation(H, verbose=0):
"""
This function performs row/column permutations to bring
@@ -207,7 +213,7 @@ def greedy_upper_triangulation(H, verbose=0):
upper triangulation method outlined in Modern Coding
Theory Appendix 1, Section A.2
"""
- H_t = H.copy()
+ H_t = H.copy()
# Per email from Dr. Urbanke, author of this textbook, this
# algorithm requires H to be full rank
@@ -222,17 +228,17 @@ def greedy_upper_triangulation(H, verbose=0):
k = n - size[0]
g = t = 0
- while t != (n-k-g):
- H_residual = H_t[t:n-k-g,t:n]
- size = H_residual.shape
- numRows = size[0]
- numCols = size[1]
+ while t != (n - k - g):
+ H_residual = H_t[t:n - k - g, t:n]
+ size = H_residual.shape
+ numRows = size[0]
+ numCols = size[1]
- minResidualDegrees = zeros((1,numCols), dtype=int)
+ minResidualDegrees = zeros((1, numCols), dtype=int)
- for colNum in arange(numCols):
- nonZeroElements = array(H_residual[:,colNum].nonzero())
- minResidualDegrees[0,colNum] = nonZeroElements.shape[1]
+ for colNum in np.arange(numCols):
+ nonZeroElements = array(H_residual[:, colNum].nonzero())
+ minResidualDegrees[0, colNum] = nonZeroElements.shape[1]
# Find the minimum nonzero residual degree
nonZeroElementIndices = minResidualDegrees.nonzero()
@@ -243,50 +249,50 @@ def greedy_upper_triangulation(H, verbose=0):
# Get indices of all of the columns in H_t that have degree
# equal to the min positive residual degree, then pick a
# random column c.
- indices = (minResidualDegrees == minimumResidualDegree)\
- .nonzero()[1]
+ indices = (minResidualDegrees == minimumResidualDegree) \
+ .nonzero()[1]
indices = indices + t
if indices.shape[0] == 1:
columnC = indices[0]
else:
- randomIndex = randint(0,indices.shape[0],(1,1))[0][0]
+ randomIndex = randint(0, indices.shape[0], (1, 1))[0][0]
columnC = indices[randomIndex]
Htemp = H_t.copy()
if minimumResidualDegree == 1:
# This is the 'extend' case
- rowThatContainsNonZero = H_residual[:,columnC-t].nonzero()[0][0]
+ rowThatContainsNonZero = H_residual[:, columnC - t].nonzero()[0][0]
# Swap column c with column t. (Book says t+1 but we
# index from 0, not 1.)
- Htemp[:,columnC] = H_t[:,t]
- Htemp[:,t] = H_t[:,columnC]
+ Htemp[:, columnC] = H_t[:, t]
+ Htemp[:, t] = H_t[:, columnC]
H_t = Htemp.copy()
Htemp = H_t.copy()
# Swap row r with row t. (Book says t+1 but we index from
# 0, not 1.)
- Htemp[rowThatContainsNonZero + t,:] = H_t[t,:]
- Htemp[t,:] = H_t[rowThatContainsNonZero + t,:]
+ Htemp[rowThatContainsNonZero + t, :] = H_t[t, :]
+ Htemp[t, :] = H_t[rowThatContainsNonZero + t, :]
H_t = Htemp.copy()
Htemp = H_t.copy()
else:
# This is the 'choose' case.
- rowsThatContainNonZeros = H_residual[:,columnC-t]\
- .nonzero()[0]
+ rowsThatContainNonZeros = H_residual[:, columnC - t] \
+ .nonzero()[0]
# Swap column c with column t. (Book says t+1 but we
# index from 0, not 1.)
- Htemp[:,columnC] = H_t[:,t]
- Htemp[:,t] = H_t[:,columnC]
+ Htemp[:, columnC] = H_t[:, t]
+ Htemp[:, t] = H_t[:, columnC]
H_t = Htemp.copy()
Htemp = H_t.copy()
# Swap row r1 with row t
r1 = rowsThatContainNonZeros[0]
- Htemp[r1+t,:] = H_t[t,:]
- Htemp[t,:] = H_t[r1+t,:]
- numRowsLeft = rowsThatContainNonZeros.shape[0]-1
+ Htemp[r1 + t, :] = H_t[t, :]
+ Htemp[t, :] = H_t[r1 + t, :]
+ numRowsLeft = rowsThatContainNonZeros.shape[0] - 1
H_t = Htemp.copy()
Htemp = H_t.copy()
@@ -294,18 +300,18 @@ def greedy_upper_triangulation(H, verbose=0):
# bottom of the matrix. We can't just swap them,
# otherwise we will be pulling up rows that we pushed
# down before. So, use a rotation method.
- for index in arange (1,numRowsLeft+1):
+ for index in np.arange(1, numRowsLeft + 1):
rowInH_residual = rowsThatContainNonZeros[index]
- rowInH_t = rowInH_residual + t - index +1
- m = n-k
+ rowInH_t = rowInH_residual + t - index + 1
+ m = n - k
# Move the row with the nonzero element to the
# bottom; don't update H_t.
- Htemp[m-1,:] = H_t[rowInH_t,:]
+ Htemp[m - 1, :] = H_t[rowInH_t, :]
# Now rotate the bottom rows up.
sub_index = 1
while sub_index < (m - rowInH_t):
- Htemp[m-sub_index-1,:] = H_t[m-sub_index,:]
- sub_index = sub_index+1
+ Htemp[m - sub_index - 1, :] = H_t[m - sub_index, :]
+ sub_index = sub_index + 1
H_t = Htemp.copy()
Htemp = H_t.copy()
@@ -323,15 +329,15 @@ def greedy_upper_triangulation(H, verbose=0):
# We need to ensure phi is nonsingular.
T = H_t[0:t, 0:t]
- E = H_t[t:t+g,0:t]
- A = H_t[0:t,t:t+g]
- C = H_t[t:t+g,t:t+g]
- D = H_t[t:t+g,t+g:n]
+ E = H_t[t:t + g, 0:t]
+ A = H_t[0:t, t:t + g]
+ C = H_t[t:t + g, t:t + g]
+ D = H_t[t:t + g, t + g:n]
invTmod2array = inv_mod2(T)
- temp1 = dot(E,invTmod2array) % 2
- temp2 = dot(temp1,A) % 2
- phi = (C - temp2) % 2
+ temp1 = dot(E, invTmod2array) % 2
+ temp2 = dot(temp1, A) % 2
+ phi = (C - temp2) % 2
if phi.any():
try:
# Try to take the inverse of phi.
@@ -353,7 +359,7 @@ def greedy_upper_triangulation(H, verbose=0):
# shuffling them around in an attempt to find a good phi.
if not (C.any() or D.any()):
if verbose:
- print('C and D are all zeros. There is no hope in',)
+ print('C and D are all zeros. There is no hope in', )
print('finding a nonsingular phi matrix. ')
return
@@ -364,8 +370,8 @@ def greedy_upper_triangulation(H, verbose=0):
# number of max iterations to perform, then break.
maxIterations = 300
iterationCount = 0
- columnsToShuffle = arange(t,n)
- rowsToShuffle = arange(t,t+g)
+ columnsToShuffle = np.arange(t, n)
+ rowsToShuffle = np.arange(t, t + g)
while iterationCount < maxIterations:
if verbose > 1:
@@ -375,29 +381,29 @@ def greedy_upper_triangulation(H, verbose=0):
shuffle(columnsToShuffle)
shuffle(rowsToShuffle)
index = 0
- for newDestinationColumnNumber in arange(t,n):
+ for newDestinationColumnNumber in np.arange(t, n):
oldColumnNumber = columnsToShuffle[index]
- tempH[:,newDestinationColumnNumber] = \
- H_t[:,oldColumnNumber]
- index +=1
+ tempH[:, newDestinationColumnNumber] = \
+ H_t[:, oldColumnNumber]
+ index += 1
tempH2 = tempH.copy()
index = 0
- for newDesinationRowNumber in arange(t,t+g):
+ for newDesinationRowNumber in np.arange(t, t + g):
oldRowNumber = rowsToShuffle[index]
- tempH[newDesinationRowNumber,:] = tempH2[oldRowNumber,:]
- index +=1
+ tempH[newDesinationRowNumber, :] = tempH2[oldRowNumber, :]
+ index += 1
# Now test this new H matrix.
H_t = tempH.copy()
T = H_t[0:t, 0:t]
- E = H_t[t:t+g,0:t]
- A = H_t[0:t,t:t+g]
- C = H_t[t:t+g,t:t+g]
+ E = H_t[t:t + g, 0:t]
+ A = H_t[0:t, t:t + g]
+ C = H_t[t:t + g, t:t + g]
invTmod2array = inv_mod2(T)
- temp1 = dot(E,invTmod2array) % 2
- temp2 = dot(temp1,A) % 2
- phi = (C - temp2) % 2
+ temp1 = dot(E, invTmod2array) % 2
+ temp2 = dot(temp1, A) % 2
+ phi = (C - temp2) % 2
if phi.any():
try:
# Try to take the inverse of phi.
@@ -409,20 +415,21 @@ def greedy_upper_triangulation(H, verbose=0):
else:
# Phi is nonsingular, so we're done.
if verbose:
- print('Found a nonsingular phi on',)
+ print('Found a nonsingular phi on', )
print('iterationCount = ', iterationCount)
return [H_t, g, t]
else:
if verbose > 1:
print('phi is all zeros')
- iterationCount +=1
+ iterationCount += 1
# If we've reached this point, then we haven't found a
# version of H that has a nonsingular phi.
if verbose:
print('--- Error: nonsingular phi matrix not found.')
+
def inv_mod2(squareMatrix, verbose=0):
"""
Calculates the mod 2 inverse of a matrix.
@@ -435,37 +442,37 @@ def inv_mod2(squareMatrix, verbose=0):
return array([1])
Ainverse = inv(A)
- B = det(A)*Ainverse
+ B = det(A) * Ainverse
C = B % 2
# Encountered lots of rounding errors with this function.
# Previously tried floor, C.astype(int), and casting with (int)
# and none of that works correctly, so doing it the tedious way.
- test = dot(A,C) % 2
+ test = dot(A, C) % 2
tempTest = zeros_like(test)
- for colNum in arange(test.shape[1]):
- for rowNum in arange(test.shape[0]):
- value = test[rowNum,colNum]
- if (abs(1-value)) < 0.01:
+ for colNum in np.arange(test.shape[1]):
+ for rowNum in np.arange(test.shape[0]):
+ value = test[rowNum, colNum]
+ if (abs(1 - value)) < 0.01:
# this is a 1
- tempTest[rowNum,colNum] = 1
- elif (abs(2-value)) < 0.01:
+ tempTest[rowNum, colNum] = 1
+ elif (abs(2 - value)) < 0.01:
# there shouldn't be any 2s after B % 2, but I'm
# seeing them!
- tempTest[rowNum,colNum] = 0
- elif (abs(0-value)) < 0.01:
+ tempTest[rowNum, colNum] = 0
+ elif (abs(0 - value)) < 0.01:
# this is a 0
- tempTest[rowNum,colNum] = 0
+ tempTest[rowNum, colNum] = 0
else:
if verbose > 1:
- print('In inv_mod2. Rounding error on this',)
- print('value? Mod 2 has already been done.',)
+ print('In inv_mod2. Rounding error on this', )
+ print('value? Mod 2 has already been done.', )
print('value:', value)
test = tempTest.copy()
- if (test - eye(t,t) % 2).any():
+ if (test - eye(t, t) % 2).any():
if verbose:
print('Error in inv_mod2: did not find inverse.')
# TODO is this the most appropriate error to raise?
@@ -473,16 +480,18 @@ def inv_mod2(squareMatrix, verbose=0):
else:
return C
-def swap_columns(a,b,arrayIn):
+
+def swap_columns(a, b, arrayIn):
"""
Swaps two columns in a matrix.
"""
arrayOut = arrayIn.copy()
- arrayOut[:,a] = arrayIn[:,b]
- arrayOut[:,b] = arrayIn[:,a]
+ arrayOut[:, a] = arrayIn[:, b]
+ arrayOut[:, b] = arrayIn[:, a]
return arrayOut
-def move_row_to_bottom(i,arrayIn):
+
+def move_row_to_bottom(i, arrayIn):
""""
Moves a specified row (just one) to the bottom of the matrix,
then rotates the rows at the bottom up.
@@ -494,14 +503,15 @@ def move_row_to_bottom(i,arrayIn):
arrayOut = arrayIn.copy()
numRows = arrayOut.shape[0]
# Push the specified row to the bottom.
- arrayOut[numRows-1] = arrayIn[i,:]
+ arrayOut[numRows - 1] = arrayIn[i, :]
# Now rotate the bottom rows up.
index = 2
- while (numRows-index) >= i:
- arrayOut[numRows-index,:] = arrayIn[numRows-index+1]
+ while (numRows - index) >= i:
+ arrayOut[numRows - index, :] = arrayIn[numRows - index + 1]
index = index + 1
return arrayOut
+
def get_full_rank_H_matrix(H, verbose=False):
"""
This function accepts a parity check matrix H and, if it is not
@@ -521,35 +531,35 @@ def get_full_rank_H_matrix(H, verbose=False):
i = 0
# Create an array to save the column permutations.
- columnOrder = arange(numColumns).reshape(1,numColumns)
+ columnOrder = np.arange(numColumns).reshape(1, numColumns)
# Create an array to save the row permutations. We just need
# this to know which dependent rows to delete.
- rowOrder = arange(numRows).reshape(numRows,1)
+ rowOrder = np.arange(numRows).reshape(numRows, 1)
while i < limit:
if verbose:
print('In get_full_rank_H_matrix; i:', i)
# Flag indicating that the row contains a non-zero entry
- found = False
- for j in arange(i, numColumns):
+ found = False
+ for j in np.arange(i, numColumns):
if tempArray[i, j] == 1:
# Encountered a non-zero entry at (i, j)
- found = True
+ found = True
# Increment rank by 1
rank = rank + 1
# Make the entry at (i,i) be 1
- tempArray = swap_columns(j,i,tempArray)
+ tempArray = swap_columns(j, i, tempArray)
# Keep track of the column swapping
- columnOrder = swap_columns(j,i,columnOrder)
+ columnOrder = swap_columns(j, i, columnOrder)
break
if found == True:
- for k in arange(0,numRows):
+ for k in np.arange(0, numRows):
if k == i: continue
# Checking for 1's
if tempArray[k, i] == 1:
# Add row i to row k
- tempArray[k,:] = tempArray[k,:] + tempArray[i,:]
+ tempArray[k, :] = tempArray[k, :] + tempArray[i, :]
# Addition is mod2
tempArray = tempArray.copy() % 2
# All the entries above & below (i, i) are now 0
@@ -557,11 +567,11 @@ def get_full_rank_H_matrix(H, verbose=False):
if found == False:
# Push the row of 0s to the bottom, and move the bottom
# rows up (sort of a rotation thing).
- tempArray = move_row_to_bottom(i,tempArray)
+ tempArray = move_row_to_bottom(i, tempArray)
# Decrease limit since we just found a row of 0s
limit -= 1
# Keep track of row swapping
- rowOrder = move_row_to_bottom(i,rowOrder)
+ rowOrder = move_row_to_bottom(i, rowOrder)
# Don't need the dependent rows
finalRowOrder = rowOrder[0:i]
@@ -570,13 +580,13 @@ def get_full_rank_H_matrix(H, verbose=False):
# First, put rows in order, omitting the dependent rows.
newNumberOfRowsForH = finalRowOrder.shape[0]
newH = zeros((newNumberOfRowsForH, numColumns))
- for index in arange(newNumberOfRowsForH):
- newH[index,:] = H[finalRowOrder[index],:]
+ for index in np.arange(newNumberOfRowsForH):
+ newH[index, :] = H[finalRowOrder[index], :]
# Next, put the columns in order.
tempHarray = newH.copy()
- for index in arange(numColumns):
- newH[:,index] = tempHarray[:,columnOrder[0,index]]
+ for index in np.arange(numColumns):
+ newH[:, index] = tempHarray[:, columnOrder[0, index]]
if verbose:
print('original H.shape:', H.shape)
@@ -584,6 +594,7 @@ def get_full_rank_H_matrix(H, verbose=False):
return newH
+
def get_best_matrix(H, numIterations=100, verbose=0):
"""
This function will run the Greedy Upper Triangulation algorithm
@@ -618,15 +629,15 @@ def get_best_matrix(H, numIterations=100, verbose=0):
bestH = betterH.copy()
bestT = t
-
if hadFirstJoy:
return [bestH, bestGap]
else:
if verbose:
- print('Error: Could not find appropriate H form',)
+ print('Error: Could not find appropriate H form', )
print('for encoding.')
return
+
def getSystematicGmatrix(GenMatrix):
"""
This function finds the systematic form of the generator
@@ -647,22 +658,22 @@ def getSystematicGmatrix(GenMatrix):
while i < limit:
# Flag indicating that the row contains a non-zero entry
found = False
- for j in arange(i, numColumns):
+ for j in np.arange(i, numColumns):
if tempArray[i, j] == 1:
# Encountered a non-zero entry at (i, j)
found = True
# Increment rank by 1
rank = rank + 1
# make the entry at (i,i) be 1
- tempArray = swap_columns(j,i,tempArray)
+ tempArray = swap_columns(j, i, tempArray)
break
if found == True:
- for k in arange(0,numRows):
+ for k in np.arange(0, numRows):
if k == i: continue
# Checking for 1's
if tempArray[k, i] == 1:
# add row i to row k
- tempArray[k,:] = tempArray[k,:] + tempArray[i,:]
+ tempArray[k, :] = tempArray[k, :] + tempArray[i, :]
# Addition is mod2
tempArray = tempArray.copy() % 2
# All the entries above & below (i, i) are now 0
@@ -670,13 +681,14 @@ def getSystematicGmatrix(GenMatrix):
if found == False:
# push the row of 0s to the bottom, and move the bottom
# rows up (sort of a rotation thing)
- tempArray = move_row_to_bottom(i,tempArray)
+ tempArray = move_row_to_bottom(i, tempArray)
# decrease limit since we just found a row of 0s
limit -= 1
# the rows below i are the dependent rows, which we discard
- G = tempArray[0:i,:]
+ G = tempArray[0:i, :]
return G
+
def getSystematicGmatrixFromH(H, verbose=False):
"""
If given a parity check matrix H, this function returns a
@@ -696,16 +708,16 @@ def getSystematicGmatrixFromH(H, verbose=False):
tempArray = getSystematicGmatrix(H)
# Next, swap I and m columns so the matrix takes the forms [m|I].
- n = H.shape[1]
- k = n - H.shape[0]
- I_temp = tempArray[:,0:(n-k)]
- m = tempArray[:,(n-k):n]
- newH = concatenate((m,I_temp),axis=1)
+ n = H.shape[1]
+ k = n - H.shape[0]
+ I_temp = tempArray[:, 0:(n - k)]
+ m = tempArray[:, (n - k):n]
+ newH = concatenate((m, I_temp), axis=1)
# Now the submatrix m is the transpose of the parity submatrix,
# i.e. H is in the form H = [P'|I]. So G is just [I|P]
k = m.shape[1]
- G = concatenate((identity(k),m.T),axis=1)
+ G = concatenate((identity(k), m.T), axis=1)
if verbose:
print('returning G with size: ', G.shape)
return G