"""Equation-level smoothing and once-per-round marked-event reduction for a prescribed fraction sequence; additive increase and the network feedback loop are intentionally outside this component.
Run with Python 3.10+; standard library only. Writes results.json in the current directory.
"""
fractions = [0.0, 0.25, 1.0, 0.0, 0.0, 0.5]

def reduction_trace(gain):
    alpha = 0.0
    window = 100.0
    rows = []
    for round_number, fraction in enumerate(fractions, 1):
        alpha = (1.0 - gain) * alpha + gain * fraction
        before = window
        if fraction > 0.0:
            window *= 1.0 - alpha / 2.0
        else:
            assert window == before
        assert 0.0 <= alpha <= 1.0 and window > 0.0
        rows.append((round_number, fraction, alpha, window))
    return rows

for gain in [1 / 16, 0.5]:
    print(f"gain={gain:.4f}")
    for step, fraction, alpha, window in reduction_trace(gain):
        print(f"  round={step} F={fraction:.2f} alpha={alpha:.6f} cwnd={window:.3f}")

gain, fraction, rounds = 1 / 16, 0.4, 256
alpha = 0.0
for _ in range(rounds):
    alpha = (1.0 - gain) * alpha + gain * fraction
closed_form = fraction * (1.0 - (1.0 - gain) ** rounds)
assert abs(alpha - closed_form) < 1e-12
assert abs(alpha - fraction) < 1e-6
print(f"Constant-fraction recurrence check: passed, alpha={alpha:.6f}")

# Extended experiment: deterministic parameter sweep and invariants.
import math
step_sweep=[]
for gain in [1/64,1/16,.25,.5]:
    alpha=0.;rows=[]
    for k in range(1,257):
        alpha=(1-gain)*alpha+gain*.4
        closed=.4*(1-(1-gain)**k)
        assert abs(alpha-closed)<1e-12
        rows.append(dict(round=k,alpha=alpha))
    first90=next(r['round'] for r in rows if r['alpha']>=.36)
    exact90=math.ceil(math.log(.1)/math.log(1-gain))
    assert first90==exact90
    step_sweep.append(dict(gain=gain,rounds_to_90_percent=first90,half_life_rounds=math.log(.5)/math.log(1-gain),rows=rows))
components=[dict(gain=gain,rows=[dict(round=k,fraction=f,alpha=a,window=w) for k,f,a,w in reduction_trace(gain)]) for gain in [1/16,.5]]
data=dict(components=components,constant_fraction=.4,step_response=step_sweep)
for row in step_sweep:
    print(f"gain={row['gain']:.6f}: 90% step response in {row['rounds_to_90_percent']} observation windows; half-life={row['half_life_rounds']:.3f} windows")

import json
from pathlib import Path
Path("results.json").write_text(json.dumps(data,indent=2,allow_nan=False)+"\n",encoding="utf-8")
