## L407_sanchez

'''
1.Define a funtion Y = RC(X,f) that implements residual coding of the numerical list X using the function f (defined for non-negative integers) as a model. Check it with the example on page T5.9. Define also a function X = RD(Y,f) that implements the corresponding decoding.
'''

# Residual coding of numerical list X using the fuction f (defined for 
# non-negative integers) as a model
def RC(X, f):
    Y = [X[k] - f(k+1) for k in range(len(X))]
    return Y
    
# Decoding of the residual coding for the list Y encoded using the function f
def RD(Y, f):
    X = [Y[k] + f(k+1) for k in range(len(Y))]
    return X
    
##Testing residual coding
def func(n): return n**2 - n + 41
L = [41,43,46,52,62,71,82,98,115,131]
E = RC(L, func)
D = RD(E, func)
print('--- Residual coding: Example test ---')
print('Original list:',L)
print('Encoded list:',E)
print('Decoded list:',D)
if (L == D):
    print(">Coding/Decoding has been successful.")
else:
    print(">Coding/Decoding has failed.")


'''
2.Define similar functions Y = PC(X) and X = PD(Y) (predictive coding and decoding), where yj = xj-(xj-2+xj-1)/2, with the convention that x-2=x-1=0. Test them with some suitable examples.
'''

# Predictive coding of X
def PC(X):
    Y = []
    xm1 = 0
    xm2 = 0
    for k in range(len(X)):
        Y.append(X[k] - (xm2+xm1)/2)
        xm2 = xm1
        xm1 = X[k]
    return Y
    
# Decoding of the predictive coding for encoded Y
def PD(Y):
    X = []
    xm1 = 0
    xm2 = 0
    for k in range(len(Y)):
        X.append(Y[k] + (xm2+xm1)/2)
        xm2 = xm1
        xm1 = X[k]
    return X

##Testing predictive coding
L = [41,43,46,52,62,71,82,98,115,131]
E = PC(L)
D = PD(E)
print('--- Predictive coding: Example test ---')
print('Original list:',L)
print('Encoded list:',E)
print('Decoded list:',D)
if (L == D):
    print(">Coding/Decoding has been successful.")
else:
    print(">Coding/Decoding has failed.")
L = [41,43,46,52,62,71,82,98,115,131]
E = PC(L)
D = PD(E)
print('--- Predictive coding: Mean Temperature of Barcelona data test ---')
L = [9,10,12,14,17,21,24,24,22,18,13,10]
E = PC(L)
D = PD(E)
print('Original list:',L)
print('Encoded list:',E)
print('Decoded list:',D)
if (L == D):
    print(">Coding/Decoding has been successful.")
else:
    print(">Coding/Decoding has failed.")
    
