#!/usr/bin/env python3
"""Exact interval arithmetic and synthetic partial pairs; no instrument recording."""

from array import array
from fractions import Fraction
import hashlib
import json
import math
from pathlib import Path
import platform
import sys
import wave


BASE = Path(__file__).resolve().parent
SAMPLE_RATE = 48000
SECONDS = 8
FRAME_COUNT = SAMPLE_RATE * SECONDS
TARGET_RMS = 0.12


def cents(ratio):
    return 1200 * math.log2(ratio)


def rms(values):
    return math.sqrt(math.fsum(x * x for x in values) / len(values))


def projection_amplitude(samples, frequency):
    """Goertzel amplitude at a specified frequency, not a frequency estimator."""
    omega = 2 * math.pi * frequency / SAMPLE_RATE
    coefficient = 2 * math.cos(omega)
    previous, older = 0.0, 0.0
    for value in samples:
        current = value + coefficient * previous - older
        older, previous = previous, current
    power = previous**2 + older**2 - coefficient * previous * older
    return 2 * math.sqrt(max(0.0, power)) / len(samples)


def synthesize(filename, f1, f2, probe_times):
    assert 0 < f1 < SAMPLE_RATE / 2 and 0 < f2 < SAMPLE_RATE / 2
    fade_frames = int(0.020 * SAMPLE_RATE)
    floating = []
    for i in range(FRAME_COUNT):
        t = i / SAMPLE_RATE
        fade = min(1.0, i / fade_frames, (FRAME_COUNT - 1 - i) / fade_frames)
        value = (math.sin(2 * math.pi * f1 * t) + math.sin(2 * math.pi * f2 * t)) / 2
        floating.append(fade * value)
    gain = TARGET_RMS / rms(floating)
    pcm = array("h", (round(x * gain * 32767) for x in floating))
    assert max(abs(x) for x in pcm) < 32767
    if sys.byteorder != "little":
        pcm.byteswap()
    path = BASE / filename
    with wave.open(str(path), "wb") as out:
        out.setnchannels(1)
        out.setsampwidth(2)
        out.setframerate(SAMPLE_RATE)
        out.writeframes(pcm.tobytes())

    # Re-open the actual encoded file; all numerical probes below use its PCM.
    with wave.open(str(path), "rb") as source:
        assert source.getnchannels() == 1 and source.getsampwidth() == 2
        assert source.getframerate() == SAMPLE_RATE
        assert source.getnframes() == FRAME_COUNT and source.getcomptype() == "NONE"
        decoded = array("h")
        decoded.frombytes(source.readframes(FRAME_COUNT))
    if sys.byteorder != "little":
        decoded.byteswap()
    samples = [x / 32767 for x in decoded]
    assert len(samples) == FRAME_COUNT and samples[0] == samples[-1] == 0
    measured_rms = rms(samples)
    assert abs(measured_rms - TARGET_RMS) < 1e-4
    probes = {f"{f:.9f}": projection_amplitude(samples, f) for f in sorted({f1, f2, 2000.0})}
    assert all(probes[f"{f:.9f}"] > 0.10 for f in {f1, f2})
    assert probes["2000.000000000"] < 0.001
    windows = []
    half_window = int(0.010 * SAMPLE_RATE)
    for label, t in probe_times:
        middle = round(t * SAMPLE_RATE)
        segment = samples[middle - half_window:middle + half_window]
        assert len(segment) == 2 * half_window
        windows.append({"label": label, "center_seconds": t,
                        "window_seconds": 0.020, "rms_of_decoded_PCM": rms(segment)})
    return {"file": filename, "component_frequencies_Hz": [f1, f2],
            "sample_rate": SAMPLE_RATE, "channels": 1, "bits_per_sample": 16,
            "frames": FRAME_COUNT, "duration_seconds": SECONDS, "fade_seconds_each_end": 0.020,
            "target_digital_rms": TARGET_RMS, "decoded_digital_rms": measured_rms,
            "decoded_peak": max(abs(x) for x in samples),
            "specified_frequency_projection_amplitudes": probes, "windows": windows,
            "file_bytes": path.stat().st_size, "sha256": hashlib.sha256(path.read_bytes()).hexdigest()}


def main():
    fifth = Fraction(3, 2)
    comma = fifth**12 / 2**7
    assert comma == Fraction(531441, 524288) and comma != 1
    semitone = 2**(1 / 12)
    et_fifth = 2**(7 / 12)
    gap_cents = cents(float(fifth)) - 700
    assert abs(cents(float(comma)) - 12 * gap_cents) < 1e-9
    assert abs(semitone**12 - 2) < 1e-12
    assert abs(et_fifth**12 - 128) < 1e-10
    chain = []
    for k in range(13):
        unfolded = fifth**k
        folded, octaves = unfolded, 0
        while folded >= 2:
            folded /= 2
            octaves += 1
        semitones = (7 * k) % 12
        folded_et = 2**(semitones / 12)
        difference = cents(float(folded) / folded_et)
        assert abs(difference - k * gap_cents) < 1e-9
        chain.append({"fifths": k, "removed_octaves": octaves,
                      "pure_ratio_within_octave": str(folded),
                      "pure_frequency_from_440_Hz": 440 * float(folded),
                      "ET_semitones_within_octave": semitones,
                      "ET_frequency_from_440_Hz": 440 * folded_et,
                      "pure_minus_ET_cents": difference})
    references = []
    for base in (220.0, 440.0, 880.0):
        pure, tempered = base * 1.5, base * et_fifth
        references.append({"base_Hz": base, "pure_fifth_Hz": pure,
                           "ET_fifth_Hz": tempered, "difference_Hz": pure - tempered,
                           "difference_cents": cents(pure / tempered)})
    upper_pure, upper_et = 440 * 1.5, 440 * et_fifth
    lower_third = 3 * 440.0
    upper_second_pure, upper_second_et = 2 * upper_pure, 2 * upper_et
    beat = abs(lower_third - upper_second_et)
    probe_times = [("theoretical_envelope_maximum", 1 / beat),
                   ("theoretical_envelope_minimum", 0.5 / beat)]
    pure_audio = synthesize("tuning-fifths-pure-partials.wav", lower_third, upper_second_pure, probe_times)
    et_audio = synthesize("tuning-fifths-tempered-partials.wav", lower_third, upper_second_et, probe_times)
    pure_ratio = pure_audio["windows"][1]["rms_of_decoded_PCM"] / pure_audio["windows"][0]["rms_of_decoded_PCM"]
    et_ratio = et_audio["windows"][1]["rms_of_decoded_PCM"] / et_audio["windows"][0]["rms_of_decoded_PCM"]
    assert 0.95 < pure_ratio < 1.05
    assert et_ratio < 0.05
    report = {
        "date": "2026-10-29", "environment": {"python": platform.python_version(),
            "macos": platform.mac_ver()[0], "machine": platform.machine()},
        "kind": "exact interval arithmetic and generated sine pairs; not a piano recording or listening study",
        "pure_fifth_ratio": "3/2", "pure_fifth_cents": cents(1.5),
        "ET_semitone_ratio": semitone, "ET_fifth_ratio": et_fifth, "ET_fifth_cents": 700,
        "fifth_narrowing_cents": gap_cents, "twelve_pure_fifths_ratio": str(fifth**12),
        "seven_octaves_ratio": 128, "pythagorean_comma_ratio": str(comma),
        "pythagorean_comma_cents": cents(float(comma)),
        "comma_frequency_ratio": float(comma), "chain": chain, "references": references,
        "partial_pair": {"lower_third_Hz": lower_third,
            "pure_upper_second_Hz": upper_second_pure, "ET_upper_second_Hz": upper_second_et,
            "predicted_beat_Hz": beat, "predicted_beat_period_seconds": 1 / beat,
            "pure_window_min_to_max_ratio": pure_ratio, "ET_window_min_to_max_ratio": et_ratio},
        "audio": [pure_audio, et_audio],
        "checks": ["Exact nonclosure ratio from rational arithmetic",
                   "Comma equals twelve fifth narrowings in cents",
                   "Equal-tempered octave and twelve-fifth closure within float tolerance",
                   "All thirteen folded chain rows agree with cumulative cents difference",
                   "Written PCM format, duration, endpoints, peak and RMS re-read from both WAV files",
                   "Specified-frequency projections and a 2000 Hz off-frequency check on decoded PCM",
                   "Decoded 20 ms windows show a flat pure control and a deep tempered-pair minimum"],
        "limits": ["Ideal 2:1 octaves and integer harmonics, fixed 440 Hz reference for the audio model.",
                   "Two selected sinusoidal partials only, not complete A/E notes or piano timbre.",
                   "Digital RMS normalization is not perceptual loudness matching.",
                   "Frequency projections are checks at known inputs, not independent frequency estimation.",
                   "No physical instrument, room, loudspeaker, human audibility or preference measurement."]}
    json.dump(report, sys.stdout, ensure_ascii=False, indent=2)
    print()


if __name__ == "__main__":
    main()
