"""Reproduce the Watt2Work 24-hour meter-clock example. Tested on CPU with Python 3.12.12 and PyTorch 2.15.0.
Run: python meter_clock.py > checkpoints.csv
The inputs are generated clock labels. No meter readings or plant data are used in training.
"""
import csv
import sys

import torch
from torch import nn
from torch.nn import functional as F


HOURS = 24
TRAIN_SIZE = 384
UPDATES = 12000
SAMPLE_INTERVAL = 100
EXAMPLE_START = 23
EXAMPLE_DELAY = 3


class ClockModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.hidden = nn.Linear(2 * HOURS, 128, bias=False)
        self.output = nn.Linear(128, HOURS, bias=False)

    def forward(self, pairs):
        hidden = self.hidden(pairs)
        return self.output(hidden.square())


def main():
    torch.set_num_threads(1)
    torch.use_deterministic_algorithms(True)
    torch.manual_seed(24)

    starts = torch.arange(HOURS).repeat_interleave(HOURS)
    delays = torch.arange(1, HOURS + 1).repeat(HOURS)
    inputs = torch.cat([F.one_hot(starts, HOURS), F.one_hot(delays - 1, HOURS)], dim=1).float()
    labels = (starts + delays) % HOURS

    # Reserve the midnight example before drawing the rest of the split.
    example = EXAMPLE_START * HOURS + EXAMPLE_DELAY - 1
    ids = torch.arange(len(labels))
    pool = ids[ids != example]
    split_rng = torch.Generator().manual_seed(20261124)
    shuffled = pool[torch.randperm(len(pool), generator=split_rng)]
    train_ids = shuffled[:TRAIN_SIZE]
    held_out_ids = torch.cat([shuffled[TRAIN_SIZE:], ids[example:example + 1]])

    model = ClockModel()
    optimizer = torch.optim.AdamW(model.parameters(), lr=0.003, weight_decay=0.3)
    x_train, y_train = inputs[train_ids], labels[train_ids]

    writer = csv.writer(sys.stdout, lineterminator="\n")
    writer.writerow(["updates", "training_correct", "training_total", "held_out_correct",
                     "held_out_total", "predicted_hour_for_23_plus_3"])
    for step in range(UPDATES + 1):
        if step % SAMPLE_INTERVAL == 0:
            with torch.no_grad():
                predictions = model(inputs).argmax(dim=1)
                correct = predictions == labels
                writer.writerow([step, correct[train_ids].sum().item(), len(train_ids),
                                 correct[held_out_ids].sum().item(), len(held_out_ids),
                                 predictions[example].item()])
        if step < UPDATES:
            optimizer.zero_grad()
            loss = F.cross_entropy(model(x_train), y_train)
            loss.backward()
            optimizer.step()


if __name__ == "__main__":
    main()
