main
John Lauer Publish 0.2.2 6e403aa
"""Resample, measure and compare. Measurements are declared in the study (windows in seconds), so the same
code measures every engine. Agreement = spread of each measurement across engines against a tolerance."""
import numpy as np


def resample(t, sigs, t0, t1, n):
    o = np.argsort(t, kind='stable'); t = t[o]
    g = np.linspace(t0, t1, n)
    return g, {k: np.interp(g, t, v[o]) for k, v in sigs.items()}


def measure(t, s, spec):
    """spec: list of {name, signal, kind, from, to, [ref_window], unit, scale}. kinds: mean, pp, max, min,
    overshoot (max in window minus mean of ref window), undershoot (mean of ref minus min in window),
    t_reach (first time signal crosses frac * mean of ref window), settle (last time |s-ref| > band after 'from')."""
    o = np.argsort(t, kind='stable'); t = t[o]; s = {k: v[o] for k, v in s.items()}
    out = {}
    for m in spec:
        x = s[m['signal']]; w = (t >= m.get('from', t[0])) & (t <= m.get('to', t[-1]))
        ref = None
        if 'ref' in m:
            r = (t >= m['ref'][0]) & (t <= m['ref'][1]); ref = float(x[r].mean())
        k = m['kind']
        if k == 'mean': v = x[w].mean()
        elif k == 'pp': v = np.ptp(x[w])
        elif k == 'max': v = x[w].max()
        elif k == 'min': v = x[w].min()
        elif k == 'overshoot': v = x[w].max() - ref
        elif k == 'undershoot': v = ref - x[w].min()
        elif k == 't_reach': v = t[np.argmax(x > m['frac'] * ref)]
        elif k == 'settle':
            idx = np.where(w & (np.abs(x - ref) > m['band']))[0]
            v = (t[idx[-1]] - m['from']) if len(idx) else 0.0
        else: continue
        out[m['name']] = float(v) * m.get('scale', 1.0)
    return out


def agreement(results, spec, tol):
    """results: {engine: {metric: value}}. Spread = max - min across engines; flagged when it exceeds the
    measurement's abs_tol, or (when it has none) the global relative tolerance times |median|."""
    rows = []
    engines = list(results)
    for m in spec:
        n = m['name']; vals = {e: results[e].get(n) for e in engines if results[e].get(n) is not None}
        if len(vals) < 2:
            rows.append({'metric': n, 'unit': m.get('unit', ''), 'label': m.get('label', n), 'values': vals, 'spread': None, 'ok': None}); continue
        arr = np.array(list(vals.values())); med = float(np.median(arr)); spread = float(arr.max() - arr.min())
        lim = m['abs_tol'] if 'abs_tol' in m else tol['rel'] * abs(med)   # a study's own limit wins over the global %
        rows.append({'metric': n, 'unit': m.get('unit', ''), 'label': m.get('label', n), 'values': vals,
                     'spread': spread, 'limit': lim, 'ok': spread <= lim,
                     'outlier': max(vals, key=lambda e: abs(vals[e] - med)) if spread > lim else None})
    return rows


def waveform_gap(grids, signal, a, b):
    """Max |a-b| of one signal on the common grid (for the 'where do they differ' highlight)."""
    d = np.abs(grids[a][signal] - grids[b][signal]); i = int(np.argmax(d))
    return float(d[i]), i