"""Week 2: forward layers, gradient checks, and a reproducible classifier comparison.
Install numpy, scikit-learn, and a processor build of torch first.
"""
import argparse
import copy
import math


def lesson1():
    import torch
    X = torch.tensor([[1., 2.], [3., 4.]])
    W = torch.tensor([[1., 0.], [0., 2.]])
    b = torch.tensor([0.5, -1.])
    product = X @ W
    affine = product + b
    output = torch.relu(affine)
    assert torch.allclose(product, torch.tensor([[1., 4.], [3., 8.]]))
    assert torch.allclose(output, torch.tensor([[1.5, 3.], [3.5, 7.]]))
    assert tuple(output.shape) == (2, 2)
    larger = torch.ones(7, 2) @ W + b
    assert tuple(larger.shape) == (7, 2)
    assert W.numel() + b.numel() == 6
    print('Affine outputs:', affine.tolist())
    print('Seven-row output shape:', tuple(larger.shape), '; shared parameters: 6')
    print('PASS: hand values, shapes, and batch flexibility.')


def lesson2():
    import torch
    weight = torch.tensor(1., dtype=torch.float64, requires_grad=True)
    loss = (weight * 2 - 6) ** 2 / 2
    loss.backward()
    automatic = weight.grad.item()
    def loss_at(w):
        return (w * 2 - 6) ** 2 / 2
    epsilon = 1e-4
    numerical = (loss_at(1 + epsilon) - loss_at(1 - epsilon)) / (2 * epsilon)
    assert math.isclose(automatic, -8, rel_tol=1e-8)
    assert math.isclose(numerical, automatic, rel_tol=1e-7, abs_tol=1e-7)
    assert not math.isclose(numerical, -4, rel_tol=1e-7)
    # Fresh graph, same parameter: gradients deliberately accumulate.
    ((weight * 2 - 6) ** 2 / 2).backward()
    assert math.isclose(weight.grad.item(), -16)
    predictions = torch.tensor([[1.], [2.], [3.]])
    targets = torch.tensor([1., 2., 3.])
    assert tuple((predictions - targets).shape) == (3, 3)
    paired = targets.reshape(-1, 1)
    assert predictions.shape == paired.shape
    assert torch.mean((predictions - paired) ** 2).item() == 0
    print('Automatic gradient:', automatic, '; numerical:', numerical)
    print('Absolute error:', abs(automatic - numerical))
    print('PASS: correct derivative, rejected wrong derivative, accumulation and pairing checks.')


def lesson3():
    import numpy as np
    import torch
    from sklearn.datasets import make_classification
    from sklearn.model_selection import train_test_split
    from sklearn.preprocessing import StandardScaler
    from sklearn.linear_model import LogisticRegression
    from sklearn.metrics import accuracy_score, confusion_matrix

    torch.manual_seed(42)
    torch.set_num_threads(1)
    X, y = make_classification(n_samples=240, n_features=6,
                              n_informative=4, n_redundant=0, random_state=42)
    X_dev, X_test, y_dev, y_test = train_test_split(
        X, y, test_size=0.2, stratify=y, random_state=42)
    X_train, X_val, y_train, y_val = train_test_split(
        X_dev, y_dev, test_size=0.25, stratify=y_dev, random_state=42)
    scaler = StandardScaler().fit(X_train)
    train_x, val_x, test_x = [torch.tensor(scaler.transform(part), dtype=torch.float32)
                            for part in [X_train, X_val, X_test]]
    train_y = torch.tensor(y_train, dtype=torch.float32).reshape(-1, 1)
    val_y = torch.tensor(y_val, dtype=torch.float32).reshape(-1, 1)
    linear = LogisticRegression(max_iter=1000).fit(scaler.transform(X_train), y_train)
    model = torch.nn.Sequential(torch.nn.Linear(6, 12), torch.nn.ReLU(),
                                torch.nn.Dropout(0.1), torch.nn.Linear(12, 1))
    optimizer = torch.optim.Adam(model.parameters(), lr=0.02)
    objective = torch.nn.BCEWithLogitsLoss()
    best_loss, best_state, best_epoch = float('inf'), None, None
    history = []
    for epoch in range(100):
        model.train()
        optimizer.zero_grad()
        loss = objective(model(train_x), train_y)
        assert torch.isfinite(loss)
        loss.backward()
        optimizer.step()
        model.eval()
        with torch.no_grad():
            validation = objective(model(val_x), val_y).item()
        history.append((loss.item(), validation))
        if validation < best_loss:
            best_loss, best_epoch = validation, epoch + 1
            best_state = copy.deepcopy(model.state_dict())
    model.load_state_dict(best_state)
    model.eval()
    with torch.no_grad():
        first = model(test_x)
        second = model(test_x)
        assert torch.equal(first, second)
        predicted = (first.flatten() >= 0).numpy().astype(int)
    assert len(predicted) == len(y_test)
    assert scaler.n_samples_seen_ == len(X_train)
    print('Selected epoch:', best_epoch, '; validation loss:', best_loss)
    print('Sample training/validation loss:', history[0], history[49], history[-1])
    print('Linear test accuracy:', accuracy_score(y_test, linear.predict(scaler.transform(X_test))))
    print('Network test accuracy:', accuracy_score(y_test, predicted))
    print('Network confusion matrix, labels [0,1]:')
    print(confusion_matrix(y_test, predicted, labels=[0, 1]))
    print('Versions:', 'numpy', np.__version__, 'torch', torch.__version__)
    print('PASS: real training, selected-state loading, train-only scaling and stable evaluation.')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--lesson', choices=['1', '2', '3', 'all'], default='all')
    args = parser.parse_args()
    for number, function in [('1', lesson1), ('2', lesson2), ('3', lesson3)]:
        if args.lesson in (number, 'all'):
            function()
