"""Replay independent metrics from the portable actual-recording export.

Requires NumPy, not Mozaik or NEST. Compares with the retained upstream
numbers; does not rerun the original framework analysis or simulation.
"""
import gzip
import json
from pathlib import Path
import numpy as np
from metrics import spike_metrics, analog_metrics

ROOT = Path(__file__).resolve().parent
with gzip.open(ROOT/'checks/exported-recordings.json.gz', 'rt') as stream:
    recordings = json.load(stream)
receipt = json.loads((ROOT/'checks/analysis-parity.json').read_text())
results = []
for population in recordings:
    calculated = spike_metrics(population['spikes'], *population['window_ms'],
                               bin_policy='upstream_range')
    for name, signals in population['analog'].items():
        calculated[name] = analog_metrics(signals, signals[0]['unit'])
    for row in receipt['comparisons']:
        if row['population'] != population['population']:
            continue
        value = calculated[row['metric']][row['statistic']]
        expected = row['upstream']
        passed = bool(np.isfinite(value) and np.isfinite(expected) and
                      np.isclose(value, expected, **{k:receipt['tolerance'][k] for k in ['atol','rtol']}))
        results.append({'population':row['population'], 'metric':row['metric'],
                        'statistic':row['statistic'], 'pass':passed,
                        'absolute_difference':abs(value-expected)})
assert len(results) == 48 and all(row['pass'] for row in results), results
print(json.dumps({'scope':'portable helper replay against saved upstream values',
                  'numpy':np.__version__, 'passed':sum(row['pass'] for row in results),
                  'total':len(results),
                  'max_absolute_difference':max(row['absolute_difference'] for row in results)}, indent=2))
