## A512 - Andrés Mingorance

import numpy as np

# Synonyms
Id = np.eye
sqrt = np.sqrt
array = np.array
stack = np.vstack
splice= np.hstack
dot = np.dot
ls  = np.linspace
zeros=np.zeros
mat=np.matrix


# Basic constants
nd = 4
r2=sqrt(2); r3=sqrt(3);
a1=(1+r3)/(4*r2); a2=(3+r3)/(4*r2);
a3=(3-r3)/(4*r2); a4=(1-r3)/(4*r2);
[b1,b2,b3,b4] = [a4,-a3,a2,-a1]

'''
I) D4trend, D4fluct, D4
'''

def D4trend_rec(f, r=1):
    N = len(f)
    f = list(f)
    if r == 0: return array(f)
    if N % 2**r:
        return "D4trend_rec: %d is not divisible by 2**%d " % (N, r)
    if r == 1:
        f = f + f[:2]
        return \
            array([a1*f[2*j]+a2*f[2*j+1]+a3*f[2*j+2]+a4*f[2*j+3] \
              for j in range(N//2)])
    else: return D4trend_rec( D4trend_rec(f,1),r-1)

def D4fluct_rec(f,r=1):
    N = len(f)
    f = list(f)
    if r == 0: return zeros(N)
    if N % 2**r:
        return "D4fluct_rec: %d is not divisible by 2**%d " % (N, r)
    if r == 1:
        f = f + f[:2]
        return \
            array([b1*f[2*j]+b2*f[2*j+1]+b3*f[2*j+2]+b4*f[2*j+3] \
            for j in range(N//2)])
    else: return D4fluct_rec(D4trend_rec(f,r-1),1)


def D4trend(f, r=1):
    N = len(f)
    if r == 0: return array(f)
    if N % 2**r:
        return "D4trend: %d is not divisible by 2**%d " % (N, r)
    while r >= 1:
        N = len(f)
        f = array([a1*f[2*j]+a2*f[2*j+1]+ \
              a3*f[(2*j+2)%N]+a4*f[(2*j+3)%N] \
              for j in range(N//2)])
        r -= 1
    return f

def D4fluct(f,r=1):
    N = len(f)
    if r == 0: return zeros(N)
    if N % 2**r:
        return "D4fluct: %d is not divisible by 2**%d " % (N, r)
    a = D4trend(f,r-1)
    N = len(a)
    d = array([b1*a[2*j]+b2*a[2*j+1]+b3*a[(2*j+2)%N]+b4*a[(2*j+3)%N] \
            for j in range(N//2)])
    return d

def D4(f,r=1):
    N = len(f)
    f = list(f)
    if r == 0: return array(f)
    if N % 2**r: return "D4: %d is not divisible by 2**%d " % (N, r)
    d = []
    while r>= 1:
        a = D4trend(f)
        d = splice([D4fluct(f),d])
        f = a
        r -=1
    return splice([f,d])


'''
II) Daub4 scaling and wavelet arrays
'''

# To construct the array of D4 level r scaling vectors
# from the array V of D4 level r-1 scaling vectors
def D4V(V):   # analogous to HaarV(V)
    N = len(V)
    X = a1*V[0,:]+a2*V[1,:]+a3*V[2%N,:]+a4*V[3%N,:]
    for j in range(1,N//2):
        v = a1*V[2*j,:]+a2*V[2*j+1,:]+ \
            a3*V[(2*j+2)%N,:]+a4*V[(2*j+3)%N,:]
        X = stack([X,v])
    return X

# To construct the array of D4 level r wavelet vectors
# from the array V of D4 level r-1 scaling vectors
def D4W(V):  # analogous to HaarW(V)
    N = len(V)
    Y = b1*V[0,:]+b2*V[1,:]+b3*V[2%N,:]+b4*V[3%N,:]
    for j in range(1,N//2):
        w = b1*V[2*j,:]+b2*V[2*j+1,:]+ \
            b3*V[(2*j+2)%N,:]+b4*V[(2*j+3)%N,:]
        Y = stack([Y,w])
    return Y

# To construct the pair formed with the array V
# of all D4 scale vectors and the array W of all
# D4 wavelet vectors.
def D4VW(N):  # analogous to HaarVW(V)
    V = Id(N)
    X = [V]
    Y = []
    while N > 2:
        W = D4W(V)
        V = D4V(V)
        X += [V]
        Y += [W]
        N = len(V)
    W = D4W(V)
    V = D4V(V)
    X += [[V]]
    Y += [[W]]
    return (X, Y)

# Orthogonal projection in orthonormal basis
def proj(f,V):
    x = zeros(len(V[0]))
    for v in V:
        x = x + dot(f,v)*v
    return x

# Projection coefficients
def proj_coeffs(f,V):
    return array([dot(f,v) for v in V])

# The Daub4 = D4 Transform using D4V and D4W
def D4T(f,r=1):
    V, W = D4VW(len(f))
    x = proj_coeffs(f, V[r])
    for j in range(r, 0, -1) :
        d = proj_coeffs(f, W[j-1])
        x = splice([x, d])
    return x


'''
2. Define functions
'''

def up_sample(a) :
    x = []
    for t in a :
        x += [t,0]
    return x
U_ = up_sample

def dual(h) :
    s = 1
    hd = []
    for t in reversed(h) :
        hd += [s*t]
        s = - s
    return hd

a_ = [a1,a2,a3,a4]
b_ = dual(a_)

def filter(h,x) :
    m = len(h)
    n = len(x)
    y = zeros(m+n-1)
    for l in range(m+n-1) :
        a = max(0, l-m+1); b = min(l+1, n)
        s = sum(h[l-j]*x[j] for j in range(a,b))
        y[l] = s
    for i in range(n,n+m-1):
        y[i%n] += y[i]
    return y[:n]

def H4(x) :
    return filter(a_,x)

def G4(x) :
    return filter(b_,x)

def HF4(f, r=1) :
    if r == 0 : return f
    a = D4trend(f,r)
    for _ in range(r) :
        a = H4(U_(a))
    return array(a)

def LF4(f, r=1) :
    if r == 0 : return zeros(len(f))
    d = G4( U_(D4fluct(f,r)) )
    for _ in range(r-1) :
        d = H4(U_(d))
    return array(d)

## ---------------------------------------------------------------------------------

def D4A(f,r):
    V = Id(len(f)); A = f
    for _ in range(r) :
        V = D4V(V)
        A = D4trend(A)
    return sum(a*v for a,v in zip(A,V))

def D4D(f,r):
    W = Id(len(f)); D = f
    for _ in range(r-1) :
        W = D4V(W)
        D = D4trend(D)
    W = D4W(W)
    D = D4fluct(D)
    return sum(d*w for d,w in zip(D,W))


from numpy import cos, pi
from cdi import sample
import matplotlib.pyplot as plt

class CDIPlotter :
    def __init__(self, title = "", rows = 1, cols = 1, grid = False, tight = True, baseIdx=1) :
        plt.figure(title)
        self.title = title
        self.nrows = rows
        self.ncols = cols
        self.grid = grid
        self.tight = tight
        self.index = baseIdx
        self.baseIdx = baseIdx

    def plot(self, f, title = "", color = 'b') :
        if self.index > self.nrows * self.ncols :
            plt.figure(self.title)
            self.index = self.baseIdx
        plt.subplot(self.nrows, self.ncols, self.index)
        plt.title(title)
        self.index = self.index + 1
        plt.plot(f, color)
        plt.xlim(0, len(f))
        if self.grid : plt.grid()
        if self.tight : plt.tight_layout()

    def show(self): plt.show()

N = 2**10
F = lambda x: 15**x**2 * 2*(1-x)**4 * cos(9*pi*x)
f = sample(F, N-1)
F_txt = '$15^{x^2} 2(1-x)^4 cos(9pi x)$'
max_r = 5
plotter = CDIPlotter("D4A vs HF4", max_r, 2)
for r in range(1, max_r + 1) :
    plotter.plot(D4A(f, r), 'D4A(f,r), f=' + F_txt if r == 1 else '', 'b')
    plt.ylabel("r = " + str(r))
    plotter.plot(HF4(f, r), 'HF4(f,r), f=' + F_txt if r == 1 else '', 'r')

plotter = CDIPlotter("D4D vs LF4", max_r, 2)
for r in range(1, max_r + 1) :
    plotter.plot(D4D(f, r), 'D4D(f,r), f=' + F_txt if r == 1 else '', 'g')
    plt.ylabel("r = " + str(r))
    plotter.plot(LF4(f, r), 'LF4(f,r), f=' + F_txt if r == 1 else '', 'm')

plotter.show()
