"""Recompute transferred-magnetization excess kurtosis from Zenodo 10957534, v2.

Download Delta=1_mu=0.0.pickle through Delta=1_mu=0.4.pickle from
https://doi.org/10.5281/zenodo.10957534 into one folder. Run with NumPy:
    python3 spin_transfer.py path/to/folder
The digest check precedes pickle decoding and pins the exact scientific inputs.
"""
import argparse
import hashlib
from pathlib import Path
import pickle
import numpy as np

DIGESTS = (
    '4deafc9b84da14287b1128e6ee5850c9110e64f22e1c1783c9be4b301b0a5fac',
    '0bb3abb2444ce7bd9afdb3e98db96f8ca2c5123790a11d7d1a65c04097d15e57',
    'bcca8e6573ee78fa3dc8aea2519c3d49da62245a810979db231646443db9ce58',
    '49aac5f61bf6b30f66458b50b05bd4d673edabe0885c008e707c012ab9406759',
    '76843f57c2d2e17f5a3f6ced813cb0f4e7412b1756634f3b7ecd4237e11c0506',
)


def load_measurements(directory):
    """Read the five hash-verified imbalance records in increasing mu order."""
    for index, digest in enumerate(DIGESTS):
        path = directory / f'Delta=1_mu={index/10:.1f}.pickle'
        raw = path.read_bytes()
        if hashlib.sha256(raw).hexdigest() != digest:
            raise ValueError(f'File differs from the version 2 deposit: {path}')
        data = pickle.loads(raw)
        if data['n'] != 46 or data['mu'] != index/10:
            raise ValueError(f'Unexpected system size or imbalance in {path}')
        yield data


def main(directory):
    values, errors = [], []
    for data in load_measurements(directory):
        q, err = data['kurtosis'], data['d_kurtosis']
        moments = data['moments']
        print(f"mu={data['mu']:.1f}, Q(20)={q[20]:.6f} +/- {err[20]:.6f}, "
              f"plain moment ratio={moments[4,20]/moments[2,20]**2-3:.6f}")
        values.append(q[:24])
        errors.append(err[:24])
    for start, stop in ((16, 24), (12, 20)):
        q, err = np.array(values)[:, start:stop], np.array(errors)[:, start:stop]
        print(f"cycles {start}-{stop-1}: inverse-variance mean {np.average(q,weights=err**-2):.6f}, "
              f"equal-weight mean {q.mean():.6f}")

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('directory', type=Path)
    main(parser.parse_args().directory)
