"""icoa_metrics — ready-made metrics for a task's scorer.py. Standard library only.

Every metric takes two lists of the same length, row for row:  metric(pred, truth)
    pred   what the contestant submitted for one column   (strings, as read from the CSV)
    truth  the same column of the labels file

Rules shared with the built-in metrics: a missing, unparseable or non-finite prediction counts as 0;
class names are compared after trimming spaces.

    classes        accuracy  balanced_accuracy  macro_f1  weighted_f1  mcc  f1 (labels 0/1)  qwk (grades)
    probabilities  auc  ap  logloss  brier
    numbers        mse  rmse  mae  rmsle  mape  smape  r2  pearson  spearman  kendall_tau
    several columns / groups of rows
                   joint_accuracy  exact_match  group_kendall_tau
                   all_correct  group_all_correct  by_group
    masks (segmentation, one image per row, run-length text)
                   mask_iou  mask_dice  boundary_iou  boundary_f1  mask_area_accuracy
                                                              metric(pred, truth, height, width)
                   per_image=True gives the list of per-image values; mean(list) averages it
    combining      weighted({"name": (weight, value), ...})
"""
import math

__all__ = [
    "accuracy", "balanced_accuracy", "macro_f1", "weighted_f1", "mcc", "f1", "qwk",
    "auc", "ap", "logloss", "brier",
    "mse", "rmse", "mae", "rmsle", "mape", "smape", "r2", "pearson", "spearman", "kendall_tau",
    "by_group", "all_correct", "joint_accuracy", "group_all_correct", "exact_match",
    "group_kendall_tau", "weighted",
    "mask_iou", "mask_dice", "boundary_iou", "boundary_f1", "mask_area_accuracy", "mean",
]

_EPS = 2.220446049250313e-16
_INF = float("inf")


# ── reading values ───────────────────────────────────────────────────────────────────────────────────────────
def _s(v):
    return "" if v is None else str(v).strip()


def _num(v):
    """A prediction as a number; missing / unparseable / non-finite = 0.0."""
    try:
        x = float(v)
    except (TypeError, ValueError):
        return 0.0
    return x if math.isfinite(x) else 0.0


def _tnum(v):
    """A label as a number; a label that is not a number is the setter's mistake, so say so."""
    try:
        return float(v)
    except (TypeError, ValueError):
        raise ValueError("label %r is not a number" % (v,)) from None


def _pos(v):
    """True when the value is the number 1 (the positive class of a 0 / 1 label)."""
    try:
        return _s(v) != "" and float(v) == 1.0
    except (TypeError, ValueError):
        return False


def _same_len(pred, truth):
    pred, truth = list(pred), list(truth)
    if len(pred) != len(truth):
        raise ValueError("pred has %d values, truth has %d — they must be the same rows" % (len(pred), len(truth)))
    return pred, truth


def _pairs(pred, truth):
    pred, truth = _same_len(pred, truth)
    return [(_num(p), _tnum(t)) for p, t in zip(pred, truth)]


def _prob_pairs(pred, truth):
    pred, truth = _same_len(pred, truth)
    return [(_num(p), 1 if _pos(t) else 0) for p, t in zip(pred, truth)]


def _str_pairs(pred, truth):
    pred, truth = _same_len(pred, truth)
    return [(_s(p), _s(t)) for p, t in zip(pred, truth)]


def _mean_of(pt, f):
    if not pt:
        return _INF
    return sum(f(p, t) for p, t in pt) / len(pt)


# ── classes ──────────────────────────────────────────────────────────────────────────────────────────────────
def accuracy(pred, truth):
    pt = _str_pairs(pred, truth)
    if not pt:
        return 0.0
    return sum(1 for p, t in pt if p == t) / len(pt)


def _per_class(pt):
    out = []
    for lab in sorted(set(t for _, t in pt)):
        tp = sum(1 for p, t in pt if p == lab and t == lab)
        fp = sum(1 for p, t in pt if p == lab and t != lab)
        fn = sum(1 for p, t in pt if p != lab and t == lab)
        out.append((tp, fp, fn))
    return out


def _f1_of(tp, fp, fn):
    denom = 2 * tp + fp + fn
    return 2 * tp / denom if denom else 0.0


def macro_f1(pred, truth):
    cls = _per_class(_str_pairs(pred, truth))
    if not cls:
        return 0.0
    return sum(_f1_of(*c) for c in cls) / len(cls)


def balanced_accuracy(pred, truth):
    cls = _per_class(_str_pairs(pred, truth))
    if not cls:
        return 0.0
    return sum(tp / (tp + fn) for tp, _, fn in cls) / len(cls)


def weighted_f1(pred, truth):
    pt = _str_pairs(pred, truth)
    cls = _per_class(pt)
    if not cls:
        return 0.0
    return sum((tp + fn) * _f1_of(tp, fp, fn) for tp, fp, fn in cls) / len(pt)


def mcc(pred, truth):
    pt = _str_pairs(pred, truth)
    n = len(pt)
    if n == 0:
        return 0.0
    tc, pc, c = {}, {}, 0
    for p, t in pt:
        tc[t] = tc.get(t, 0) + 1
        pc[p] = pc.get(p, 0) + 1
        if p == t:
            c += 1
    cov_tp = c * n - sum(v * pc.get(k, 0) for k, v in tc.items())
    cov_tt = n * n - sum(v * v for v in tc.values())
    cov_pp = n * n - sum(v * v for v in pc.values())
    if cov_tt == 0 or cov_pp == 0:
        return 0.0
    return cov_tp / math.sqrt(cov_tt * cov_pp)


def f1(pred, truth):
    """Labels 0 / 1: F1 of class 1."""
    pred, truth = _same_len(pred, truth)
    tp = fp = fn = 0
    for p, t in zip(pred, truth):
        p, y = _pos(p), _pos(t)
        if p and y:
            tp += 1
        elif p and not y:
            fp += 1
        elif y and not p:
            fn += 1
    return _f1_of(tp, fp, fn)


def qwk(pred, truth):
    """Quadratic weighted kappa: grades span min..max of the labels; a prediction is rounded half-up and clamped."""
    pred, truth = _same_len(pred, truth)
    ts = [int(math.floor(_tnum(t) + 0.5)) for t in truth]
    if not ts:
        return 0.0
    lo, hi = min(ts), max(ts)
    n = hi - lo + 1
    if n < 2:
        return 0.0
    ps = [min(max(int(math.floor(_num(p) + 0.5)), lo), hi) for p in pred]
    ht, hp, obs = [0] * n, [0] * n, 0
    for t, p in zip(ts, ps):
        ht[t - lo] += 1
        hp[p - lo] += 1
        obs += (p - t) ** 2
    exp = sum((i - j) ** 2 * ht[i] * hp[j] for i in range(n) for j in range(n)) / len(ts)
    if exp == 0:
        return 0.0
    return 1 - obs / exp


# ── probabilities (labels 0 / 1, prediction = probability of 1) ──────────────────────────────────────────────
def _ranks(xs):
    """Average ranks, 1-based; ties share the mean of their positions."""
    order = sorted(range(len(xs)), key=lambda i: xs[i])
    out = [0.0] * len(xs)
    i = 0
    while i < len(order):
        j = i
        while j + 1 < len(order) and xs[order[j + 1]] == xs[order[i]]:
            j += 1
        for k in range(i, j + 1):
            out[order[k]] = (i + j) / 2 + 1
        i = j + 1
    return out


def auc(pred, truth):
    pt = _prob_pairs(pred, truth)
    n1 = sum(y for _, y in pt)
    n0 = len(pt) - n1
    if n1 == 0 or n0 == 0:
        return 0.5
    r = _ranks([p for p, _ in pt])
    u = sum(r[i] for i in range(len(pt)) if pt[i][1] == 1) - n1 * (n1 + 1) / 2
    return u / (n1 * n0)


def ap(pred, truth):
    """Average precision (area under the precision-recall curve); tied scores enter together."""
    pt = sorted(_prob_pairs(pred, truth), key=lambda x: -x[0])
    n1 = sum(y for _, y in pt)
    if n1 == 0:
        return 0.0
    total, tp, seen, prev, i = 0.0, 0, 0, 0.0, 0
    while i < len(pt):
        j = i
        while j < len(pt) and pt[j][0] == pt[i][0]:
            tp += pt[j][1]
            seen += 1
            j += 1
        rec = tp / n1
        total += (rec - prev) * (tp / seen)
        prev = rec
        i = j
    return total


def logloss(pred, truth):
    def one(p0, y):
        p = min(max(p0, 1e-15), 1 - 1e-15)
        return -math.log(p) if y == 1 else -math.log(1 - p)

    return _mean_of(_prob_pairs(pred, truth), one)


def brier(pred, truth):
    return _mean_of(_prob_pairs(pred, truth), lambda p, y: (p - y) ** 2)


# ── numbers ──────────────────────────────────────────────────────────────────────────────────────────────────
def mse(pred, truth):
    return _mean_of(_pairs(pred, truth), lambda p, t: (p - t) ** 2)


def rmse(pred, truth):
    return math.sqrt(mse(pred, truth))


def mae(pred, truth):
    return _mean_of(_pairs(pred, truth), lambda p, t: abs(p - t))


def rmsle(pred, truth):
    return math.sqrt(
        _mean_of(_pairs(pred, truth), lambda p, t: (math.log1p(max(p, 0.0)) - math.log1p(max(t, 0.0))) ** 2)
    )


def mape(pred, truth):
    return _mean_of(_pairs(pred, truth), lambda p, t: abs(p - t) / max(abs(t), _EPS))


def smape(pred, truth):
    def one(p, t):
        d = abs(p) + abs(t)
        return 2 * abs(p - t) / d if d else 0.0

    return _mean_of(_pairs(pred, truth), one)


def r2(pred, truth):
    pt = _pairs(pred, truth)
    if not pt:
        return 0.0
    mean = sum(t for _, t in pt) / len(pt)
    tot = sum((t - mean) ** 2 for _, t in pt)
    if tot == 0:
        return 0.0
    return 1 - sum((p - t) ** 2 for p, t in pt) / tot


def _corr(xs, ys):
    n = len(xs)
    if n == 0:
        return 0.0
    mx, my = sum(xs) / n, sum(ys) / n
    sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
    sxx = sum((x - mx) ** 2 for x in xs)
    syy = sum((y - my) ** 2 for y in ys)
    if sxx == 0 or syy == 0:
        return 0.0
    return sxy / math.sqrt(sxx * syy)


def pearson(pred, truth):
    pt = _pairs(pred, truth)
    return _corr([p for p, _ in pt], [t for _, t in pt])


def spearman(pred, truth):
    pt = _pairs(pred, truth)
    return _corr(_ranks([p for p, _ in pt]), _ranks([t for _, t in pt]))


def kendall_tau(pred, truth, normalised=False):
    """Kendall tau-b (ties handled), -1 .. 1; 0 when either side is constant or there are fewer than 2 rows.
    normalised=True maps it to 0 .. 1 as (tau + 1) / 2."""
    pt = _pairs(pred, truth)
    conc = disc = tie_p = tie_t = 0
    for i in range(len(pt)):
        for j in range(i + 1, len(pt)):
            dp, dt = pt[i][0] - pt[j][0], pt[i][1] - pt[j][1]
            if dp == 0:
                tie_p += 1
            if dt == 0:
                tie_t += 1
            if dp * dt > 0:
                conc += 1
            elif dp * dt < 0:
                disc += 1
    n0 = len(pt) * (len(pt) - 1) // 2
    denom = math.sqrt((n0 - tie_p) * (n0 - tie_t))
    tau = (conc - disc) / denom if denom else 0.0
    return (tau + 1) / 2 if normalised else tau


# ── several columns, groups of rows ──────────────────────────────────────────────────────────────────────────
def _groups(keys):
    """Row numbers of each group, groups in order of first appearance."""
    out = {}
    for i, k in enumerate(keys):
        out.setdefault(_s(k), []).append(i)
    return list(out.values())


def by_group(keys, fn, *columns):
    """Apply fn inside each group of rows and return the mean over groups.
    by_group(truth["week"], mae, pred["mm"], truth["mm"])"""
    keys = list(keys)
    cols = [list(c) for c in columns]
    for c in cols:
        if len(c) != len(keys):
            raise ValueError("by_group: a column has %d values, the keys have %d" % (len(c), len(keys)))
    groups = _groups(keys)
    if not groups:
        return 0.0
    return sum(fn(*[[c[i] for i in rows] for c in cols]) for rows in groups) / len(groups)


def _col_list(cols):
    """Accept one column (a list of values) or a list of columns."""
    cols = list(cols)
    if cols and not isinstance(cols[0], (list, tuple)):
        return [cols]
    return [list(c) for c in cols]


def all_correct(pred_cols, truth_cols):
    """Per row: True when every listed column is right.  all_correct([pred["a"], pred["b"]], [truth["a"], truth["b"]])"""
    pc, tc = _col_list(pred_cols), _col_list(truth_cols)
    if len(pc) != len(tc):
        raise ValueError("all_correct: %d prediction columns against %d label columns" % (len(pc), len(tc)))
    if not pc:
        return []
    for p, t in zip(pc, tc):
        _same_len(p, t)
    return [all(_s(p[i]) == _s(t[i]) for p, t in zip(pc, tc)) for i in range(len(tc[0]))]


def joint_accuracy(pred_cols, truth_cols):
    """Share of rows where every listed column is right."""
    ok = all_correct(pred_cols, truth_cols)
    return sum(ok) / len(ok) if ok else 0.0


def group_all_correct(keys, pred_cols, truth_cols):
    """Share of groups in which every row is right in every listed column."""
    ok = all_correct(pred_cols, truth_cols)
    keys = list(keys)
    if len(keys) != len(ok):
        raise ValueError("group_all_correct: the keys have %d values, the columns have %d" % (len(keys), len(ok)))
    groups = _groups(keys)
    if not groups:
        return 0.0
    return sum(1 for rows in groups if all(ok[i] for i in rows)) / len(groups)


exact_match = group_all_correct


def group_kendall_tau(keys, pred, truth, normalised=True):
    """Kendall tau inside each group, mean over groups (0 .. 1 by default)."""
    return by_group(keys, lambda p, t: kendall_tau(p, t, normalised=normalised), pred, truth)


# ── masks: segmentation tasks ────────────────────────────────────────────────────────────────────────────────
# One row = one image. A mask travels as run-length text, the form segmentation competitions use:
#     "start length start length ..."      pixels numbered from 1, down each column first, then the next column
#     "-"                                  an empty mask
# height and width are either one number for every image or a column of the labels file (truth["height"]).
# A prediction that is not valid run-length text scores 0 on that image. Pure Python, no numpy needed.
# Options every mask metric takes:
#     first=0          the text numbers its pixels from 0 instead of 1
#     per_image=True   return the list of per-image values instead of their mean — for a formula of your own,
#                      e.g. mean(i * i * a for i, a in zip(iou, area))
# Metrics that look at the outline also take order="row" when the text runs along the rows.
_MASK_EMPTY = frozenset(("", "-", "-1", "none", "nan", "empty"))
_MAX_PIXELS = 64 * 1000 * 1000
_mask_cache = {}
_edge_masks = {}


def _count(bits):
    try:
        return bits.bit_count()
    except AttributeError:  # Python 3.9
        return bin(bits).count("1")


def _rle_bits(text, n, first=1):
    """Run-length text -> the mask as one integer (bit i = pixel i + first). None when the text is not a valid mask."""
    s = _s(text).lower()
    if s in _MASK_EMPTY:
        return 0
    parts = s.split()
    if len(parts) % 2 or len(parts) > 2 * n:
        return None
    pieces = []
    at = 0
    try:
        for k in range(0, len(parts), 2):
            start, length = int(parts[k]) - first, int(parts[k + 1])
            if start < at or length < 1 or start + length > n:
                return None
            pieces.append("0" * (start - at))
            pieces.append("1" * length)
            at = start + length
    except ValueError:
        return None
    return int("".join(pieces)[::-1], 2)


def _size_column(v, n, what):
    if isinstance(v, (list, tuple)):
        if len(v) != n:
            raise ValueError("%s has %d values for %d rows" % (what, len(v), n))
        vals = v
    else:
        vals = [v] * n
    out = []
    for x in vals:
        try:
            k = int(float(x))
        except (TypeError, ValueError):
            raise ValueError("%s %r is not a number" % (what, x)) from None
        if k < 1:
            raise ValueError("%s must be at least 1, got %r" % (what, x))
        out.append(k)
    return out


def _edges(fast, slow):
    """Bit masks that stop a shift from leaking across the end of a column (or a row)."""
    key = (fast, slow)
    if key not in _edge_masks:
        if len(_edge_masks) > 64:
            _edge_masks.clear()
        not_first = int((("0" + "1" * (fast - 1)) * slow)[::-1], 2)
        not_last = int((("1" * (fast - 1) + "0") * slow)[::-1], 2)
        _edge_masks[key] = (not_first, not_last, (1 << (fast * slow)) - 1)
    return _edge_masks[key]


def _band(bits, fast, slow, d):
    """The pixels of a mask within d pixels of its outline (the image border counts as outside)."""
    if not bits:
        return 0
    not_first, not_last, full = _edges(fast, slow)
    inner = bits
    for _ in range(d):
        inner &= ((inner << 1) & not_first) & ((inner >> 1) & not_last)
        inner &= ((inner << fast) & full) & (inner >> fast)
        if not inner:
            break
    return bits & ~inner


def _outline(bits, fast, slow, connect, border):
    """The outline of a mask: its pixels that touch a pixel outside it.
    connect 4 = touching by a side, 8 = by a side or a corner. border: does the edge of the image count as outside."""
    if not bits:
        return 0
    not_first, not_last, full = _edges(fast, slow)
    if border:
        f0 = f1 = s0 = s1 = 0
    else:
        col = (1 << fast) - 1
        f0, f1, s0, s1 = full & ~not_first, full & ~not_last, col, col << (fast * (slow - 1))
    along = bits & (((bits << 1) & not_first) | f0) & (((bits >> 1) & not_last) | f1)
    src = along if connect == 8 else bits
    inner = along & (((src << fast) & full) | s0) & ((src >> fast) | s1)
    return bits & ~inner


def _reach(bits, fast, slow, d, shape):
    """Every pixel within d of a pixel of `bits`. shape: "disk" straight-line distance, "square" d steps that may
    go diagonally, "diamond" d steps along rows and columns only."""
    if not bits:
        return 0
    not_first, not_last, full = _edges(fast, slow)
    if shape == "disk":
        n = int(d)
        runs = [bits]                       # runs[k] = spread k pixels along the fast axis
        for _ in range(n):
            x = runs[-1]
            runs.append(x | ((x << 1) & not_first) | ((x >> 1) & not_last))
        out = runs[n]
        for s in range(1, n + 1):
            x = runs[int(math.sqrt(d * d - s * s) + 1e-9)]
            out |= ((x << (s * fast)) & full) | (x >> (s * fast))
        return out
    out = bits
    for _ in range(int(d)):
        along = out | ((out << 1) & not_first) | ((out >> 1) & not_last)
        src = along if shape == "square" else out
        out = along | ((src << fast) & full) | (src >> fast)
    return out


def _mask_row(p, t, h, w, d, order, first=1):
    """(overlap, union, pred area, truth area, band overlap, band union, valid) for one image."""
    key = (p, t, h, w, d, order, first)
    hit = _mask_cache.get(key)
    if hit is not None:
        return hit
    n = h * w
    if n > _MAX_PIXELS:
        raise ValueError("an image of %d x %d pixels is too large to score" % (h, w))
    tb = _rle_bits(t, n, first)
    if tb is None:
        raise ValueError("label %r... is not a valid mask for %d x %d pixels" % (_s(t)[:40], h, w))
    pb = _rle_bits(p, n, first)
    if pb is None:      # not a mask at all: nothing overlaps, and everything it could have found is missed
        out = (0, max(_count(tb), 1), 0, _count(tb), 0, 1, False)
    else:
        bi = bu = 0
        if d:
            fast, slow = (h, w) if order == "column" else (w, h)
            pe, te = _band(pb, fast, slow, d), _band(tb, fast, slow, d)
            bi, bu = _count(pe & te), _count(pe | te)
        out = (_count(pb & tb), _count(pb | tb), _count(pb), _count(tb), bi, bu, True)
    if len(_mask_cache) > 50000:
        _mask_cache.clear()
    _mask_cache[key] = out
    return out


def _check_mask_options(order, first):
    if order not in ("column", "row"):
        raise ValueError('order must be "column" or "row"')
    if first not in (0, 1):
        raise ValueError("first must be 0 or 1 (the number of the first pixel)")


def _mask_rows(pred, truth, height, width, d_of, order, first=1):
    pred, truth = _same_len(pred, truth)
    _check_mask_options(order, first)
    hs, ws = _size_column(height, len(truth), "height"), _size_column(width, len(truth), "width")
    return [_mask_row(_s(p), _s(t), h, w, d_of(h, w), order, first) for p, t, h, w in zip(pred, truth, hs, ws)]


def _ratio_mean(rows, top, bottom, pooled, per_image=False):
    """Mean over images of top/bottom (an image where both are empty counts as 1), or the pooled ratio."""
    if per_image:
        return [(top(r) / bottom(r)) if bottom(r) else 1.0 for r in rows]
    if not rows:
        return 0.0
    if pooled:
        a, b = sum(top(r) for r in rows), sum(bottom(r) for r in rows)
        return a / b if b else 1.0
    return sum((top(r) / bottom(r)) if bottom(r) else 1.0 for r in rows) / len(rows)


def _distance_of(ratio, distance, whole=True):
    if distance is not None:
        d = float(distance)
        if whole:
            d = int(d)
        if d < 1:
            raise ValueError("distance must be at least 1 pixel")
        return lambda h, w: d
    r = float(ratio)
    if not (0 < r < 1):
        raise ValueError("ratio must be between 0 and 1")
    return lambda h, w: max(1, int(round(r * math.sqrt(h * h + w * w))))


def mask_iou(pred, truth, height, width, pooled=False, first=1, per_image=False):
    """Intersection over union of each predicted mask with its label, mean over images (0 .. 1).
    pooled=True counts the pixels of all images together instead (one large image)."""
    rows = _mask_rows(pred, truth, height, width, lambda h, w: 0, "column", first)
    return _ratio_mean(rows, lambda r: r[0], lambda r: r[1], pooled, per_image)


def mask_dice(pred, truth, height, width, pooled=False, first=1, per_image=False):
    """Dice coefficient 2 x overlap / (pred area + label area), mean over images (0 .. 1)."""
    rows = _mask_rows(pred, truth, height, width, lambda h, w: 0, "column", first)
    return _ratio_mean(rows, lambda r: 2 * r[0], lambda r: r[2] + r[3], pooled, per_image)


def boundary_iou(pred, truth, height, width, ratio=0.02, distance=None, order="column", first=1, per_image=False):
    """Boundary IoU: the same overlap, counted only inside a thin band along each mask's outline, mean over images.
    The band is `distance` pixels wide, or ratio x the image diagonal (2 % by default, at least 1 pixel).
    order: "column" when the run-length text runs down the columns (the usual form), "row" when along the rows."""
    rows = _mask_rows(pred, truth, height, width, _distance_of(ratio, distance), order, first)
    return _ratio_mean(rows, lambda r: r[4], lambda r: r[5], False, per_image)


def mask_area_accuracy(pred, truth, height, width, floor=0.05, first=1, per_image=False):
    """How close the predicted area is to the label's, whatever its place, mean over images (0 .. 1):
        1 - |pred share - label share| / max(label share, floor), never below 0
    where a share is the mask's area / the image's area. floor keeps a tiny label from making the error explode."""
    fl = float(floor)
    if not (0 < fl <= 1):
        raise ValueError("floor must be above 0 and at most 1")
    rows = _mask_rows(pred, truth, height, width, lambda h, w: 0, "column", first)
    hs, ws = _size_column(height, len(rows), "height"), _size_column(width, len(rows), "width")
    out = []
    for r, h, w in zip(rows, hs, ws):
        n = float(h * w)
        out.append(max(0.0, min(1.0, 1.0 - abs(r[2] - r[3]) / n / max(r[3] / n, fl))) if r[6] else 0.0)
    return out if per_image else (sum(out) / len(out) if out else 0.0)


def boundary_f1(pred, truth, height, width, ratio=0.0075, distance=None, order="column", first=1, per_image=False,
                shape="disk", connect=4, border=True):
    """Boundary F1 with a tolerance, mean over images (0 .. 1). The outline of a mask = its pixels that touch the outside.
        precision = share of the predicted outline that lies within the tolerance of the label's outline
        recall    = share of the label's outline that lies within the tolerance of the predicted outline
        F1        = 2 x precision x recall / (precision + recall)
    Both outlines empty -> 1; only one empty -> 0.
    tolerance  `distance` pixels (a fraction is fine with shape="disk"), or ratio x the image diagonal rounded to a
               whole pixel (0.75 % by default, at least 1)
    shape      how the tolerance is measured: "disk" straight-line distance · "square" steps that may go diagonally
               · "diamond" steps along rows and columns only
    connect    4: a pixel is on the outline when a neighbour by a side is outside · 8: by a side or a corner
    border     True: the edge of the image counts as outside (a mask that runs off the image has an outline there)"""
    if shape not in ("disk", "square", "diamond"):
        raise ValueError('shape must be "disk", "square" or "diamond"')
    if connect not in (4, 8):
        raise ValueError("connect must be 4 or 8")
    d_of = _distance_of(ratio, distance, whole=(shape != "disk"))
    pred, truth = _same_len(pred, truth)
    _check_mask_options(order, first)
    hs, ws = _size_column(height, len(truth), "height"), _size_column(width, len(truth), "width")
    out = []
    for p, t, h, w in zip(pred, truth, hs, ws):
        p, t, d = _s(p), _s(t), d_of(h, w)
        key = ("bf1", p, t, h, w, d, order, first, shape, connect, bool(border))
        v = _mask_cache.get(key)
        if v is None:
            n = h * w
            if n > _MAX_PIXELS:
                raise ValueError("an image of %d x %d pixels is too large to score" % (h, w))
            tb = _rle_bits(t, n, first)
            if tb is None:
                raise ValueError("label %r... is not a valid mask for %d x %d pixels" % (t[:40], h, w))
            pb = _rle_bits(p, n, first)
            if pb is None:
                v = 0.0
            else:
                fast, slow = (h, w) if order == "column" else (w, h)
                po, to = _outline(pb, fast, slow, connect, border), _outline(tb, fast, slow, connect, border)
                if not po and not to:
                    v = 1.0
                elif not po or not to:
                    v = 0.0
                else:
                    prec = _count(po & _reach(to, fast, slow, d, shape)) / _count(po)
                    rec = _count(to & _reach(po, fast, slow, d, shape)) / _count(to)
                    v = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
            if len(_mask_cache) > 50000:
                _mask_cache.clear()
            _mask_cache[key] = v
        out.append(v)
    return out if per_image else (sum(out) / len(out) if out else 0.0)


def mean(values):
    """The mean of a list of numbers (0 for an empty list) — for formulas built from per_image=True lists."""
    values = list(values)
    return sum(values) / len(values) if values else 0.0


# ── combining ────────────────────────────────────────────────────────────────────────────────────────────────
def weighted(parts):
    """weighted({"rain": (0.6, 0.81), "amount": (0.4, 0.55)}) -> {"score": 0.706, "parts": {...}}
    The weights must add up to 1."""
    if not parts:
        raise ValueError("weighted: give at least one part")
    total = 0.0
    score = 0.0
    values = {}
    for name, pair in parts.items():
        try:
            w, v = pair
            w, v = float(w), float(v)
        except (TypeError, ValueError):
            raise ValueError('weighted: part "%s" must be (weight, value), two numbers' % name) from None
        total += w
        score += w * v
        values[str(name)] = v
    if abs(total - 1.0) > 1e-9:
        raise ValueError("weighted: the weights add up to %.6g — they must add up to 1" % total)
    return {"score": score, "parts": values}
