import numpy as np
from scipy.io.wavfile import read
import pylab as plt
from scipy.fftpack import dct, idct


# Load training and test data
X_train = read('../X_train.wav')[1].reshape(-1, 784)
y_train = (read('../y_train.wav')[1] * 9).astype(int)
X_test = read('../X_test.wav')[1].reshape(-1, 784)
y_test = (read('../y_test.wav')[1] * 9).astype(int)
X20 = X_test[:1000]
yt20 = y_test[:1000]

# Define the MLP Classifier
class MLPClassifier:
    def __init__(self, input_size, hidden_size, output_size, learning_rate=np.random.rand(4)):
        self.W1 = np.random.randn(input_size, hidden_size) * 0.01
        self.b1 = np.zeros((1, hidden_size))
        self.W2 = np.random.randn(hidden_size, output_size) * 0.01
        self.b2 = np.zeros((1, output_size))
        self.learning_rate = learning_rate
    
    def relu(self, x):
        return np.maximum(0, x)
    
    def relu_derivative(self, x):
        return np.where(x > 0, 1, 0)
    
    def softmax(self, x):
        exp_x = np.exp(x - np.max(x, axis=1, keepdims=True))
        return exp_x / np.sum(exp_x, axis=1, keepdims=True)
    
    def forward(self, X):
        self.z1 = np.dot(X, self.W1) + self.b1
        self.a1 = self.relu(self.z1)
        self.z2 = np.dot(self.a1, self.W2) + self.b2
        output = self.softmax(self.z2)
        return output
    
    def compute_loss(self, y_true, y_pred):
        m = y_true.shape[0]
        loss = -np.sum(y_true * np.log(y_pred + 1e-9)) / m
        return loss
    
    def backward(self, X, y_true, y_pred):
        m = y_true.shape[0]
        dz2 = y_pred - y_true
        dW2 = np.dot(self.a1.T, dz2) / m
        db2 = np.sum(dz2, axis=0, keepdims=True) / m
        da1 = np.dot(dz2, self.W2.T)
        dz1 = da1 * self.relu_derivative(self.z1)
        dW1 = np.dot(X.T, dz1) / m
        db1 = np.sum(dz1, axis=0, keepdims=True) / m
        return dW1, db1, dW2, db2
    
    def update(self, X, y_true):
        y_pred = self.forward(X)
        dW1, db1, dW2, db2 = self.backward(X, y_true, y_pred)
        self.W1 -= self.learning_rate[0] * dW1
        self.b1 -= self.learning_rate[1] * db1
        self.W2 -= self.learning_rate[2] * dW2
        self.b2 -= self.learning_rate[3] * db2
    
    def predict(self, X):
        probabilities = self.forward(X)
        return np.argmax(probabilities, axis=1)

    def score(self, X, y_true):
        y = self.predict(X)
        return np.mean(y == y_true)


import numpy as np
from scipy.fftpack import dct, idct

def compress_W1(W1, keep_size=8):
    """
    Compresses W1 from (784, 100) to a tiny parameter set using 2D-DCT.
    If keep_size=4, params size is 4 * 4 * 100 = 1600 coefficients (instead of 78,400).
    """
    # Reshape to 3D image-like features per hidden unit
    W_tensor = W1.reshape(28, 28, 10, 10)
    
    # Apply 2D DCT
    dct_2d = dct(dct(dct(dct(W_tensor, axis=0, norm='ortho'), axis=1, norm='ortho'), axis=2, norm='ortho'), axis=3, norm='ortho')
    
    # Store only the low-frequency parameters
    params = dct_2d[:keep_size, :keep_size, :5, :5]
    return params

def functional_W1(params):
    """
    Reconstructs the full W1 matrix from the small parameter set.
    """
    keep_size, _, keep_size2, _ = params.shape
    
    # Pad back to full 28x28 resolution with zeros
    padded_dct = np.zeros((28, 28, 10, 10))
    padded_dct[:keep_size, :keep_size, :5, :5] = params
    
    # Apply Inverse 2D DCT
    #idct_2d = idct(idct(padded_dct, axis=1, norm='ortho'), axis=0, norm='ortho')
    idct_2d = idct(idct(idct(idct(padded_dct, axis=3, norm='ortho'), axis=2, norm='ortho'), axis=1, norm='ortho'), axis=0, norm='ortho')
    # Reshape back to original W1 size
    return idct_2d.reshape(784, 100)
        
# Initialize and train the MLP Classifier
learning_rate = np.random.rand(4)
f = MLPClassifier(input_size=784, hidden_size=100, output_size=10, learning_rate=learning_rate)

i = 0
while True:
    idx = np.random.randint(1000, 60000, 100)
    X = X_train[idx]
    yt = y_train[idx]
    print(i, f.score(X20,yt20))
    f.update(X, np.eye(10)[yt])
    i += 1
    if i == 300:break


params = compress_W1(f.W1, keep_size=5)
err = f.W1 - functional_W1(params)
params += 0.01 * compress_W1(err, keep_size=5)
print(f.score(X20,yt20))


