# examples/d-fine.py
"""Deterministic scalar D-FINE reference using the Python standard library.

Implements distribution arithmetic, not a detector or a training reproduction.
The paper's normalized support is used; edge order is left, top, right, bottom.
"""

import argparse
import bisect
import json
import math
from collections import Counter


def softmax(logits, temperature=1.0):
    """Normalizes finite logits stably."""
    if not logits or temperature <= 0 or not all(map(math.isfinite, logits)):
        raise ValueError("Expected finite logits and positive temperature.")
    peak = max(logits)
    values = [math.exp((x - peak) / temperature) for x in logits]
    return [x / sum(values) for x in values]


# region: support
def support_values(n=32, a=0.5, c=0.25):
    """Returns N+1 non-uniform offsets from paper Eq. 4."""
    if n < 4 or n % 2 or a <= 0 or c <= 0:
        raise ValueError("Use even N >= 4 and positive a, c.")
    values = []
    for i in range(n + 1):
        if i in (0, n):
            value = -2 * a if i == 0 else 2 * a
        else:
            magnitude = c * ((1 + a / c) ** (abs(n - 2 * i) / (n - 2)) - 1)
            value = -magnitude if i < n / 2 else magnitude
        values.append(value)
    return values
# endregion: support


# region: refinement
def refine(previous, residual, support):
    """Adds logits, then integrates probabilities; never adds probabilities."""
    if not len(previous) == len(residual) == len(support):
        raise ValueError("Distribution shapes must agree.")
    logits = [old + delta for old, delta in zip(previous, residual)]
    probabilities = softmax(logits)
    offset = sum(p * value for p, value in zip(probabilities, support))
    return logits, probabilities, offset
# endregion: refinement


# region: decode
def decode_box(reference, offsets):
    """Decodes L,T,R,B offsets against a fixed [cx, cy, w, h] reference."""
    x, y, width, height = reference
    left, top, right, bottom = offsets
    if width <= 0 or height <= 0:
        raise ValueError("Reference dimensions must be positive.")
    return [x - width * (0.5 + left), y - height * (0.5 + top),
            x + width * (0.5 + right), y + height * (0.5 + bottom)]


def encode_offsets(reference, box):
    """Inverts decode_box, returning normalized L,T,R,B corrections."""
    x, y, width, height = reference
    if width <= 0 or height <= 0:
        raise ValueError("Reference dimensions must be positive.")
    return [(x - box[0]) / width - 0.5, (y - box[1]) / height - 0.5,
            (box[2] - x) / width - 0.5, (box[3] - y) / height - 0.5]
# endregion: decode


# region: localization
def target_weights(target, support):
    """Interpolates neighboring support values, saturating outside the range."""
    right = min(max(bisect.bisect_right(support, target), 1), len(support) - 1)
    left = right - 1
    weight_right = min(max((target - support[left]) /
                           (support[right] - support[left]), 0.0), 1.0)
    return left, right, 1 - weight_right, weight_right


def localization_loss(logits, target, support, iou=1.0):
    """Computes one edge's IoU-weighted two-bin cross entropy, Eq. 5."""
    left, right, weight_left, weight_right = target_weights(target, support)
    peak = max(logits)
    log_z = peak + math.log(sum(math.exp(x - peak) for x in logits))
    return iou * (weight_left * (log_z - logits[left]) +
                  weight_right * (log_z - logits[right]))
# endregion: localization


# region: distillation
def distillation_loss(student, teacher, temperature=5.0):
    """Returns T² KL(teacher || student); no autograd or teacher gradients."""
    if len(student) != len(teacher):
        raise ValueError("Teacher and student shapes must agree.")
    def log_probabilities(logits):
        softmax(logits, temperature)  # Validate the same input contract.
        peak = max(logits)
        shifted = [(value - peak) / temperature for value in logits]
        log_z = math.log(sum(math.exp(value) for value in shifted))
        return [value - log_z for value in shifted]

    log_p = log_probabilities(teacher)
    log_q = log_probabilities(student)
    return temperature ** 2 * sum(
        math.exp(p) * (p - q) for p, q in zip(log_p, log_q))


def balanced_distillation(matched, unmatched):
    """Combines preweighted edge-loss group means as in released criterion."""
    def mean(values):
        return sum(values) / len(values) if values else 0.0

    m, u = math.sqrt(len(matched)), math.sqrt(len(unmatched))
    return (m * mean(matched) + u * mean(unmatched)) / (m + u) if m + u else 0.0
# endregion: distillation


def union_matches(layers):
    """Votes by frequency per query; smallest target ID breaks authored ties."""
    counts = Counter(pair for layer in layers for pair in layer)
    winners = {}
    ordered = sorted(
        counts.items(), key=lambda item: (-item[1], item[0][1]))
    for (query, target), _ in ordered:
        winners.setdefault(query, target)
    return sorted(winners.items())


def smoke():
    """Checks independent arithmetic identities and prints calculated values."""
    support = support_values(8)
    assert len(support) == 9 and support[0] == -1 and support[-1] == 1
    assert all(math.isclose(x, -y, abs_tol=1e-12)
               for x, y in zip(support, reversed(support)))
    reference = [100, 80, 40, 20]
    box = [76, 69, 122, 92]
    decoded = decode_box(reference, encode_offsets(reference, box))
    assert all(math.isclose(x, y) for x, y in zip(decoded, box))
    left, right, wl, wr = target_weights(0.17, support)
    assert math.isclose(wl * support[left] + wr * support[right], 0.17)
    assert math.isclose(distillation_loss([0, 1, 2], [0, 1, 2]), 0)
    assert math.isclose(balanced_distillation([2], [8] * 9), 6.5)
    matches = union_matches([[(0, 0)], [(0, 1)], [(0, 1), (2, 0)]])
    assert matches == [(0, 1), (2, 0)]
    print(json.dumps({"evidence": "calculated scalar reference; no checkpoint",
                      "support": support, "round_trip_box": decoded,
                      "fgl_uniform": localization_loss([0] * 9, 0.17, support),
                      "balanced_ddf": 6.5}, indent=2))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--smoke", action="store_true",
        help="Run deterministic arithmetic checks.")
    parser.parse_args()
    smoke()
