"""Deterministic tabular dataset aggregation in an eight-step offset simulator; no neural training, driving deployment, or claim to reproduce the paper benchmarks.
Run with Python 3.10+; standard library only. Writes results.json in the current directory.
"""
def expert(offset):
    return -1 if offset > 0 else 1 if offset < 0 else 0

def rollout(policy, start=0):
    offset = start
    states, trace = [], [offset]
    for step in range(8):
        states.append(offset)
        action = policy.get(offset, 0)
        disturbance = {2: 1, 5: -1}.get(step, 0)
        offset += action + disturbance
        trace.append(offset)
    error = sum(abs(value) for value in trace[1:])
    return states, trace, error

policy = {0: 0}
baseline = rollout(policy)[2]
for iteration in range(3):
    states, trace, error = rollout(policy)
    print(f"iteration={iteration} error={error} trace={trace}")
    print(f"  visited={sorted(set(states))}")
    labels = {state: expert(state) for state in states}
    policy.update(labels)

states, trace, final_error = rollout(policy)
assert final_error <= baseline
assert policy[1] == -1 and policy[-1] == 1
print(f"Aggregated table: {dict(sorted(policy.items()))}")
print(f"Centered test error={final_error}")
print(f"Unseen offset-2 test error={rollout(policy, start=2)[2]}")

# Extended experiment: deterministic parameter sweep and invariants.
from itertools import product
learners=[];table={0:0};training=[]
for iteration in range(3):
    learners.append(dict(table));states,trace,error=rollout(table)
    training.append(dict(iteration=iteration,trace=trace,error=error,known_states=sorted(table)))
    table.update({s:expert(s) for s in states})
def evaluate(policy,start,disturbances):
    x=start;error=0;unknown=0
    for noise in disturbances:
        unknown+=x not in policy;x+=policy.get(x,0)+noise;error+=abs(x)
    return error,unknown
heldout=[]
for iteration,learner in enumerate(learners):
    for start in range(-3,4):
        total_error=unknown=0
        for disturbances in product([-1,0,1],repeat=6):
            error,miss=evaluate(learner,start,disturbances);total_error+=error;unknown+=miss
        heldout.append(dict(iteration=iteration,start=start,sequences=729,
                            mean_error=total_error/729,unknown_decision_fraction=unknown/(729*6)))
assert training[0]['error']==3 and training[1]['error']==4 and training[2]['error']==2
data=dict(training=training,heldout=heldout,final_lookup=sorted(table.items()),
          test_design='All 729 length-six disturbance sequences in {-1,0,1}^6 at each initial offset; equal weighting.')
for iteration in range(3):
    centered=next(r for r in heldout if r['iteration']==iteration and r['start']==0)
    print(f"table round={iteration}, exhaustive centered mean error={centered['mean_error']:.4f}, unknown-state decisions={centered['unknown_decision_fraction']:.4%}")

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