"""CPU arithmetic examples; no training, image inference or downloaded weights.

Checked with Python 3.10.12 / torch 2.3.1+cu118, using CPU only.
All masks and logits below are hand-specified teaching inputs.
"""

import json
import math
import platform

import torch
from torch.nn import functional as F


def class_metrics(pred, target, classes, ignore=255):
    """Dataset-global confusion, rows=true, cols=predicted; ignore by target.

    Classes absent in BOTH prediction and truth have undefined IoU/Dice,
    represented as None and omitted from macro means. No epsilon smoothing.
    Background is class 0 and is included in the all-class macro means.
    """
    if pred.shape != target.shape:
        raise ValueError("prediction and target must have the same shape")
    if pred.dtype != torch.long or target.dtype != torch.long:
        raise ValueError("class-index masks must be torch.long")
    valid = target != ignore
    truth, guessed = target[valid], pred[valid]
    if ((truth < 0) | (truth >= classes)).any():
        raise ValueError("target class outside valid range")
    if ((guessed < 0) | (guessed >= classes)).any():
        raise ValueError("predicted class outside valid range")
    cm = torch.bincount(truth * classes + guessed,
                        minlength=classes * classes).reshape(classes, classes)
    tp = cm.diag()
    actual, predicted = cm.sum(1), cm.sum(0)
    union = actual + predicted - tp
    denominator = actual + predicted
    iou = [int(t) / int(u) if u else None for t, u in zip(tp, union)]
    dice = [2 * int(t) / int(d) if d else None
            for t, d in zip(tp, denominator)]

    def mean_defined(values):
        defined = [v for v in values if v is not None]
        return sum(defined) / len(defined) if defined else None

    return {
        "confusion_true_rows": cm.tolist(),
        "valid_pixels": int(valid.sum()),
        "pixel_accuracy": int(tp.sum()) / len(truth) if len(truth) else None,
        "iou_per_class": iou,
        "dice_per_class": dice,
        "miou_including_background": mean_defined(iou),
        "macro_dice_including_background": mean_defined(dice),
        "miou_foreground_only": mean_defined(iou[1:]),
    }


def run():
    # IDs 0 and 2 are classes; class 1 does not occur in the input mask.
    mask = torch.tensor([[[[0., 2.], [0., 2.]]]])
    near = F.interpolate(mask, size=(3, 3), mode="nearest-exact")
    linear = F.interpolate(mask, size=(3, 3), mode="bilinear", align_corners=False)
    assert near.unique().tolist() == [0., 2.]
    assert linear.unique().tolist() == [0., 1., 2.]

    target = torch.tensor([[[0, 0, 1], [0, 2, 255]]], dtype=torch.long)
    pred = torch.tensor([[[0, 1, 1], [0, 0, 2]]], dtype=torch.long)
    logits = torch.zeros((1, 3, 2, 3))
    ce = F.cross_entropy(logits, target, ignore_index=255)
    assert math.isclose(float(ce), math.log(3), rel_tol=1e-6)
    # One independent binary foreground channel, same shape and float target.
    binary_target = torch.tensor([[[[0., 0., 1.], [0., 1., 0.]]]])
    bce = F.binary_cross_entropy_with_logits(torch.zeros_like(binary_target),
                                           binary_target)
    assert math.isclose(float(bce), math.log(2), rel_tol=1e-6)
    # BCE has no ignore_index: explicitly select valid elements if applicable.
    valid_binary = (target != 255).unsqueeze(1)
    masked_bce = F.binary_cross_entropy_with_logits(
        torch.zeros_like(binary_target)[valid_binary], binary_target[valid_binary])
    assert math.isclose(float(masked_bce), math.log(2), rel_tol=1e-6)

    metrics = class_metrics(pred, target, 3)
    assert metrics["confusion_true_rows"] == [[2, 1, 0], [0, 1, 0], [1, 0, 0]]
    assert metrics["valid_pixels"] == 5
    assert metrics["iou_per_class"] == [0.5, 0.5, 0.0]
    assert math.isclose(metrics["miou_including_background"], 1 / 3)
    assert metrics["miou_foreground_only"] == 0.25
    empty = class_metrics(torch.zeros((1,), dtype=torch.long),
                          torch.zeros((1,), dtype=torch.long), 3)
    assert empty["iou_per_class"] == [1.0, None, None]
    ignored = class_metrics(torch.zeros((1,), dtype=torch.long),
                            torch.full((1,), 255, dtype=torch.long), 3)
    assert ignored["miou_including_background"] is None

    x = torch.tensor([[[[0., 1.], [2., 3.]]]])
    kernel = x.clone()
    stride1 = F.conv_transpose2d(x, kernel)
    stride2 = F.conv_transpose2d(x, kernel, stride=2)
    assert stride1[0, 0].tolist() == [[0., 0., 1.], [0., 4., 6.], [4., 12., 9.]]
    assert stride2.shape == (1, 1, 4, 4)

    # Transpose is an adjoint, not an inverse. Bias-free, matching geometry.
    original = torch.arange(9.).reshape(1, 1, 3, 3)
    k = torch.ones((1, 1, 2, 2))
    reduced = F.conv2d(original, k)
    returned = F.conv_transpose2d(reduced, k)
    assert returned.shape == original.shape
    assert not torch.equal(returned, original)
    probe = torch.tensor([[[[1., 2.], [3., 4.]]]])
    assert torch.equal((reduced * probe).sum(),
                       (original * F.conv_transpose2d(probe, k)).sum())
    # Both sizes collapse to 2; output_padding selects geometry, not content.
    k3 = torch.ones((1, 1, 3, 3))
    for size in (5, 6):
        assert F.conv2d(torch.zeros(1, 1, size, size), k3, stride=2).shape[-1] == 2
    coarse = torch.zeros(1, 1, 2, 2)
    shapes = [list(F.conv_transpose2d(coarse, k3, stride=2,
                                    output_padding=p).shape[-2:]) for p in (0, 1)]
    assert shapes == [[5, 5], [6, 6]]

    return {
        "environment": {"python": platform.python_version(), "torch": torch.__version__,
                        "device": "cpu", "training": False},
        "nearest_exact_mask": near[0, 0].tolist(),
        "bilinear_mask": linear[0, 0].tolist(),
        "ce_zero_logits": float(ce), "bce_zero_logits": float(bce),
        "bce_valid_pixels_only": float(masked_bce),
        "metrics": metrics, "absent_classes": empty, "all_ignored": ignored,
        "transpose_stride1": stride1[0, 0].tolist(),
        "transpose_stride2": stride2[0, 0].tolist(),
        "transpose_is_not_inverse": returned[0, 0].tolist(),
        "output_padding_shapes": shapes,
    }


if __name__ == "__main__":
    print(json.dumps(run(), ensure_ascii=False, indent=2, allow_nan=False))
