"""Exact finite-support Gittins index worksheet, not a queue simulator.""" from fractions import Fraction as F import hashlib import json from pathlib import Path import sys def rational(value): if isinstance(value, bool) or not isinstance(value, (int, str, F)): raise ValueError("Use integer, rational string or Fraction inputs") try: return F(value) except (ValueError, ZeroDivisionError) as error: raise ValueError("Invalid rational input") from error def evaluate(distribution, age=0): """Pairs are (total service, probability); age is attained service.""" age = rational(age) if age < 0: raise ValueError("Age must be nonnegative") mass = {} for size, probability in distribution: size, probability = rational(size), rational(probability) if size <= 0 or probability <= 0: raise ValueError("Service and probability must be positive") mass[size] = mass.get(size, F(0)) + probability if sum(mass.values()) != 1: raise ValueError("Probabilities must sum to one") survivors = sorted((size, p) for size, p in mass.items() if size > age) survival = sum(p for _, p in survivors) if not survival: raise ValueError("No unfinished job at this age") mean = sum(p * (size - age) for size, p in survivors) / survival # Between support points completion mass is constant while work increases. # Sweep endpoints rather than rescanning all jobs at each candidate. completed, work, previous = F(0), F(0), age rows = [] for cutoff, p in survivors: work += (survival - completed) * (cutoff - previous) completed += p rows.append(dict(cutoff=cutoff, completion_probability=completed / survival, expected_service=work / survival, index=completed / work)) previous = cutoff best = max(rows, key=lambda row: row["index"]) return dict(age=age, survival_probability=survival, mean_remaining=mean, index=best["index"], rank=1 / best["index"], best_cutoff=best["cutoff"], candidates=rows) def encode(value): if isinstance(value, F): return str(value) if isinstance(value, list): return [encode(item) for item in value] if isinstance(value, dict): return {key: encode(item) for key, item in value.items()} return value def result(): law = [(1, "9/10"), (100, "1/10")] outcomes = [] for size, probability in law: outcomes.append(dict(new_size=size, probability=F(probability), old_first_responses=[F(10), F(10 + size)], probe_first_responses=[F(11), F(1 if size == 1 else 110)])) means = {policy: sum(row["probability"] * sum(row[policy + "_responses"]) for row in outcomes) / 2 for policy in ("old_first", "probe_first")} return encode(dict( schema_version=1, kind="synthetic finite-support scheduling worksheet", units=dict(service="ms", index="1/ms", rank="ms"), distribution=[dict(service=size, probability=F(p)) for size, p in law], fresh=evaluate(law), old=evaluate(law, 90), decision=dict(serpt="old", gittins="fresh"), two_job_outcomes=outcomes, mean_response=means, limitations="No arrival-process simulation, device data, p99 or optimality proof.", generator_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest())) if __name__ == "__main__": if sys.argv[1:] not in ([], ["--check"]): raise SystemExit("Use model.py [--check]") path = Path(__file__).with_name("results.json") encoded = json.dumps(result(), indent=2) + "\n" if sys.argv[1:]: if path.read_text() != encoded: raise SystemExit("Published results differ from the exact calculation") print("Exact Gittins worksheet verified") else: path.write_text(encoded)