"""Numerically stable focal-loss arithmetic, not a trained RetinaNet detector.
Pinned source: arXiv:1708.02002v2, Equations 3–5 and section 3.3.
Python standard library only. Run with optional --json.
"""
import argparse
import json
import math


def terms(logit, target, gamma, alpha):
    if not math.isfinite(logit) or target not in (0, 1):
        raise ValueError("Require a finite logit and binary target")
    if not math.isfinite(gamma) or gamma < 0:
        raise ValueError("Gamma must be finite and nonnegative")
    if alpha is not None and not (math.isfinite(alpha) and 0 <= alpha <= 1):
        raise ValueError("Alpha must be in [0,1] or None")
    sign = 2*target-1
    z = -sign*logit
    log_pt = -(max(z, 0)+math.log1p(math.exp(-abs(z))))
    pt, q = math.exp(log_pt), -math.expm1(log_pt)
    alpha_t = 1 if alpha is None else alpha if target == 1 else 1-alpha
    return sign, log_pt, pt, q, alpha_t


# region: loss
def focal_loss(logit, target, gamma=2.0, alpha=0.25):
    """Stable alpha_t * (1-p_t)^gamma * BCE, with no probability clipping."""
    _, log_pt, _, q, alpha_t = terms(logit, target, gamma, alpha)
    return -alpha_t*q**gamma*log_pt
# endregion: loss


# region: gradient
def focal_gradient(logit, target, gamma=2.0, alpha=0.25):
    """Differentiate the focusing factor too; do not detach its gradient."""
    sign, log_pt, pt, q, alpha_t = terms(logit, target, gamma, alpha)
    if gamma == 0:
        return -alpha_t*sign*q
    return alpha_t*sign*q**gamma*(gamma*pt*log_pt-q)
# endregion: gradient


# region: population
def population_loss(groups, gamma=2.0, alpha=0.25):
    """Count-weighted loss and absolute gradient; no learned data distribution."""
    output = []
    for label, count, pt, target in groups:
        if not isinstance(count, int) or count < 0 or not 0 < pt < 1:
            raise ValueError("Invalid count or probability")
        logit = (2*target-1)*math.log(pt/(1-pt))
        per = focal_loss(logit, target, gamma, alpha)
        output.append({"label": label, "count": count, "per": per,
                       "total": count*per,
                       "gradient": count*abs(focal_gradient(logit, target, gamma, alpha))})
    return output


def prior_bias(prior=0.01):
    """Set a sigmoid bias to a supplied rare-foreground prior."""
    if not 0 < prior < 1:
        raise ValueError("Prior must be strictly between zero and one")
    return math.log(prior/(1-prior))
# endregion: population


def self_check():
    for target in (0, 1):
        for gamma in (0.0, 0.5, 2.0, 5.0):
            for logit in (-7.0, -1.3, 0.0, 2.7, 7.0):
                eps = 1e-5
                numerical = (focal_loss(logit+eps, target, gamma)
                             - focal_loss(logit-eps, target, gamma))/(2*eps)
                assert abs(numerical-focal_gradient(logit, target, gamma)) < 1e-8
    assert abs(focal_loss(0, 1, gamma=0)-0.25*math.log(2)) < 1e-15
    assert abs(focal_loss(0, 0, gamma=0)-0.75*math.log(2)) < 1e-15
    for logit in (-1000.0, 1000.0):
        for target in (0, 1):
            assert math.isfinite(focal_loss(logit, target))
            assert math.isfinite(focal_gradient(logit, target))
    assert abs(1/(1+math.exp(-prior_bias()))-0.01) < 1e-15


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()
    self_check()
    groups = [("easy negatives", 10000, 0.99, 0),
              ("hard negatives", 100, 0.4, 0), ("positives", 20, 0.6, 1)]
    report = {"kind": "analytical illustration", "population": population_loss(groups),
              "bias": prior_bias(), "values": [
                  {"logit": z, "target": t, "loss": focal_loss(z, t),
                   "gradient": focal_gradient(z, t)}
                  for t in (0, 1) for z in (-7, -1.3, 0, 2.7, 7)]}
    print(json.dumps(report, indent=2) if args.json else "Focal-loss self-check passed: finite-difference gradients, weighted BCE limit, extreme logits and prior bias.")


if __name__ == "__main__":
    main()
