#!/usr/bin/env python3 """Original arithmetic illustration; no Granite inference or product benchmark. Run: python3 granite-quantile-pooling-lab.py Standard library only. Inputs are authored hypothetical forecasts, not observations. """ import json import math import platform LEVELS = [i / 10 for i in range(1, 10)] def validate(members): if len(members) != 4: raise ValueError('This illustration requires all four authored members') for row in members: if len(row) != len(LEVELS) or not all(math.isfinite(x) for x in row): raise ValueError('Expected nine finite quantiles per member') if any(a > b for a, b in zip(row, row[1:])): raise ValueError('Quantile crossing in input') def empirical_linear_quantile(values, q): """Sorted empirical values, position (n-1)*q, linear interpolation.""" xs = sorted(values) pos = (len(xs) - 1) * q lo, hi = math.floor(pos), math.ceil(pos) return xs[lo] + (pos - lo) * (xs[hi] - xs[lo]) def compare(members): validate(members) pooled = [empirical_linear_quantile([v for row in members for v in row], q) for q in LEVELS] averaged = [sum(row[j] for row in members) / len(members) for j in range(len(LEVELS))] return {'pool': pooled, 'same_quantile_mean': averaged} def run(): # Four hypothetical next-day demand distributions. A/B low, C/D high. members = [[start + j for j in range(9)] for start in [80, 84, 136, 140]] result = compare(members) select = lambda xs: [round(xs[j], 6) for j in [0, 4, 8]] assert select(result['pool']) == [83.5, 114.0, 144.5] assert select(result['same_quantile_mean']) == [110.0, 114.0, 118.0] # A hand-computed 90th-percentile check: sorted positions31 and32 (zero-based). xs = sorted(v for row in members for v in row) assert xs[31:33] == [144, 145] # Countercondition: unanimous point masses have no disagreement to retain. identical = compare([[100] * 9 for _ in range(4)]) assert identical['pool'] == identical['same_quantile_mean'] == [100.0] * 9 failures = [] for label, bad in [('missing_member', members[:3]), ('crossing', [[88-j for j in range(9)]] + members[1:]), ('nonfinite', [[float('nan')] * 9] + members[1:])]: try: compare(bad) except ValueError as e: failures.append({'case': label, 'rejected': True, 'reason': str(e)}) else: raise AssertionError(label) # Recovery verifies the original valid input still gives the same output. assert compare(members) == result orders = {name: math.ceil(values[8]) for name, values in result.items()} scenarios = [] for actual in [90, 145]: scenarios.append({'hypothetical_actual': actual, **{ name: {'order': order, 'leftover': max(order-actual, 0), 'shortfall': max(actual-order, 0)} for name, order in orders.items()}}) # Coverage example is authored, never called Granite accuracy. intervals = [[80, 120]] * 10 actuals = [90, 100, 110, 115, 85, 118, 121, 130, 70, 140] covered = sum(lo <= y <= hi for (lo, hi), y in zip(intervals, actuals)) assert covered == 6 return { 'scope': 'Authored hypothetical arithmetic only; no model weights, forecast inference, business or coverage measurement', 'python': platform.python_version(), 'quantile_convention': 'Sorted empirical values at (n-1)*q with linear interpolation; mirrors unweighted pooling rule, not full Granite package execution', 'levels': LEVELS, 'members': members, 'all_quantiles': result, 'p10_p50_p90': {k: select(v) for k, v in result.items()}, 'orders': orders, 'scenarios': scenarios, 'coverage_illustration': {'intervals': intervals, 'hypothetical_actuals': actuals, 'covered': covered, 'total': 10, 'fraction': covered / 10}, 'validation': failures, 'recovery': 'valid input reproduced', 'limits': ['No continuous-CDF integration; nine supplied quantiles are a discrete approximation.', 'No ranking of actual forecasters.', 'The strict four-member rule is this lab policy, not Granite failure behavior.', 'Order examples assume zero stock, one-day horizon, one-unit lots and no lead-time mismatch.'] } if __name__ == '__main__': print(json.dumps(run(), ensure_ascii=False, indent=2))