#!/usr/bin/env python3
"""Reproduce the digital spectra. Requires Python 3 and NumPy.

Example: python noise-spectra-method.py --white white.wav --pink pink.wav --brown brown.wav
Obtain the three exact WAV files from noise-spectra.json. No network access is used.
These are digital file measurements, not a sound-pressure or infant-sleep test.
"""
import argparse
import hashlib
import json
from pathlib import Path
import wave
import numpy as np


def measure(path, sound):
    with wave.open(str(path), 'rb') as wav:
        if wav.getsampwidth() != 2 or wav.getnchannels() != 1:
            raise ValueError('Expected a mono 16-bit PCM WAV file')
        rate = wav.getframerate()
        samples = np.frombuffer(wav.readframes(wav.getnframes()), dtype='<i2').astype(float) / 32768
    window_size, hop = 16384, 8192
    points = np.geomspace(100, 10000, 100)
    frames = np.lib.stride_tricks.sliding_window_view(samples, window_size)[::hop].copy()
    frames -= frames.mean(axis=1, keepdims=True)
    window = np.hanning(window_size)
    psd = np.mean(np.abs(np.fft.rfft(frames * window)) ** 2, axis=0) / (rate * np.sum(window ** 2))
    psd[1:-1] *= 2
    frequencies = np.fft.rfftfreq(window_size, 1 / rate)
    band = 2 ** (1 / 24)
    smoothed = np.array([psd[(frequencies >= f / band) & (frequencies <= f * band)].mean() for f in points])
    reference = psd[(frequencies >= 1000 / band) & (frequencies <= 1000 * band)].mean()
    db = 10 * np.log10(smoothed / reference)
    slope = float(np.polyfit(np.log2(points), db, 1)[0])
    return {'id': 'noise-' + sound, 'sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
            'durationSeconds': len(samples) / rate, 'sampleRate': rate, 'windows': len(frames),
            'slopeDbPerOctave': round(slope, 3), 'frequencyHz': points.round(3).tolist(),
            'relativeDb': db.round(3).tolist()}


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    for sound in ['white', 'pink', 'brown']:
        parser.add_argument('--' + sound, type=Path, required=True)
    args = parser.parse_args()
    print(json.dumps({'curves': [measure(getattr(args, sound), sound) for sound in ['white', 'pink', 'brown']]}, indent=2))
