## Hamming code [7,4,3]

from PyECC import *

# Hamming [4,7]
R1 = [1,1,1]
R2 = [0,1,1]
R3 = [1,0,1]
R4 = [1,1,0]
R = matrix(Zn(2), [R1,R2,R3,R4])
show(R)


# Generating matrix
G = splice(I_(4),R)


# Control matrix
H = stack(R,I_(3)) 


# encoder: u is a binary list or vector of length 4
def f(u): 
    x = matrix(u)*G
    n = ncols(x)
    return x[0]

u = [1,1,0,1]
x = f(u)
show('x :',x)

# simulate 1 error in the index 1 position
y = flip(x,1)

show('y :',y)

# decoder: the index j of the syndrome s=y*H in H
# tells what bit should be corrected in y
def g(y):
    s = y*H
    print('s :',s)
    if is_zero(s): return y[:4]
    j = get_row(s,H)
    y = flip(y,j)
    return y[:4]

u1 = g(y)
show('u1 :',u1)
show('u :',u)