"""Exhaustive three-machine scheduling experiment. Python standard library only.""" from argparse import ArgumentParser from collections import Counter, defaultdict from fractions import Fraction from functools import cache from itertools import combinations, combinations_with_replacement import json def canonical(groups): """Represent identical machines without labels, preserving job sizes.""" return tuple(sorted(tuple(sorted(group, reverse=True)) for group in groups)) def profile(schedule): return tuple(sorted(map(sum, schedule), reverse=True)) def lpt(jobs, prefer_more_jobs=False): groups = [[], [], []] loads = [0, 0, 0] for job in jobs: index = min(range(3), key=lambda i: (loads[i], -len(groups[i]) if prefer_more_jobs else 0, i)) groups[index].append(job) loads[index] += job return canonical(groups) def all_lpt(jobs): frontier = {((), (), ())} for job in jobs: next_frontier = set() for groups in frontier: loads = list(map(sum, groups)) for i, load in enumerate(loads): if load == min(loads): moved = list(groups) moved[i] += (job,) next_frontier.add(canonical(moved)) frontier = next_frontier return frontier def neighbors(groups): """All one-job moves and all one-for-one swaps.""" for i, j in combinations(range(3), 2): for a, x in enumerate(groups[i]): moved = list(groups) moved[i] = groups[i][:a] + groups[i][a + 1:] moved[j] += (x,) yield canonical(moved) for b, y in enumerate(groups[j]): if x != y: swapped = list(groups) swapped[i] = groups[i][:a] + (y,) + groups[i][a + 1:] swapped[j] = groups[j][:b] + (x,) + groups[j][b + 1:] yield canonical(swapped) for b, y in enumerate(groups[j]): moved = list(groups) moved[j] = groups[j][:b] + groups[j][b + 1:] moved[i] += (y,) yield canonical(moved) def exact_optimum(jobs, upper): """Find the first feasible cap, with symmetric branches collapsed.""" lower = max(jobs[0], (sum(jobs) + 2) // 3) for cap in range(lower, upper): @cache def fits(remaining, loads): if remaining == len(jobs): return True job = jobs[remaining] for i, load in enumerate(loads): if i and loads[i - 1] == load: continue if load + job <= cap: changed = list(loads) changed[i] += job if fits(remaining + 1, tuple(sorted(changed))): return True return False if fits(0, (0, 0, 0)): return cap return upper def endpoints(start, lexicographic): """All terminal schedules reachable by any strictly improving step.""" def score(groups): v = profile(groups) return v if lexicographic else v[:1] @cache def walk(groups): current = score(groups) next_steps = {g for g in neighbors(groups) if score(g) < current} if not next_steps: return {groups} return set.union(*(walk(g) for g in next_steps)) return walk(start) def lookahead_descent(start, overshoot=0): """Check two-step improvements before committing either move.""" groups = start trace = [groups] while True: current = profile(groups)[0] best = None for intermediate in {groups, *neighbors(groups)}: middle = profile(intermediate)[0] if current <= middle <= current + overshoot: for nxt in neighbors(intermediate): if profile(nxt)[0] < current: key = (profile(nxt), middle, intermediate != groups, nxt, intermediate) if best is None or key < best: best = key if best is None: return groups, trace _, _, _, groups, intermediate = best if intermediate != trace[-1]: trace.append(intermediate) trace.append(groups) def record(jobs, start, optimum, starts): capped, path = lookahead_descent(start) exposed, exposed_path = lookahead_descent(start, overshoot=1) return { 'jobs': jobs, 'lpt': start, 'optimum': optimum, 'lpt_profiles': sorted({profile(s) for s in starts}), 'most_jobs_tiebreak_lpt': lpt(jobs, prefer_more_jobs=True), 'strict_terminals_by_lpt_start': [ {'start': s, 'terminals': sorted(endpoints(s, False))} for s in sorted(starts) ], 'lexicographic_terminals_by_lpt_start': [ {'start': s, 'terminals': sorted(endpoints(s, True))} for s in sorted(starts) ], 'plateau_trace': path, 'plateau_makespan': profile(capped)[0], 'overshoot_trace': exposed_path, 'overshoot_makespan': profile(exposed)[0], } def experiment(max_jobs, max_duration): examples = {} by_size = defaultdict(Counter) worst = {} for n in range(1, max_jobs + 1): jobs_in_order = combinations_with_replacement(range(1, max_duration + 1), n) for asc in jobs_in_order: jobs = asc[::-1] key = (n, max(jobs), sum(jobs), asc) row = by_size[n] row['instances'] += 1 start = lpt(jobs) lpt_cost = profile(start)[0] optimum = exact_optimum(jobs, lpt_cost) row['lpt_optimal'] += lpt_cost == optimum if lpt_cost == optimum: continue starts = all_lpt(jobs) strict_end = endpoints(start, False) lex_end = endpoints(start, True) plateau_end, _ = lookahead_descent(start) overshoot_end, _ = lookahead_descent(start, overshoot=1) scores = { 'strict': min(profile(s)[0] for s in strict_end), 'lex': min(profile(s)[0] for s in lex_end), 'plateau_one': profile(plateau_end)[0], 'overshoot_one': profile(overshoot_end)[0], } robust = all(profile(t)[0] > optimum for s in starts for t in endpoints(s, True)) row['strict_recovers'] += scores['strict'] == optimum row['lex_recovers'] += scores['lex'] == optimum row['plateau_recovers'] += scores['plateau_one'] == optimum row['overshoot_recovers'] += scores['overshoot_one'] == optimum row['robust_lex_failure'] += robust categories = { 'strict_failure': scores['strict'] > optimum, 'lex_failure': scores['lex'] > optimum, 'robust_lex_failure': robust, 'plateau_failure': scores['plateau_one'] > optimum, 'overshoot_failure': scores['overshoot_one'] > optimum, } for name, passes in categories.items(): if passes and (name not in examples or key < examples[name][0]): examples[name] = (key, jobs) for name, cost in (('lpt', lpt_cost), *scores.items()): ratio = Fraction(cost, optimum) if name not in worst or ratio > worst[name][0]: worst[name] = (ratio, jobs, cost, optimum) best_examples = {} for name, (_, jobs) in examples.items(): start = lpt(jobs) cost = exact_optimum(jobs, profile(start)[0]) best_examples[name] = record(jobs, start, cost, all_lpt(jobs)) return { 'max_jobs': max_jobs, 'max_duration': max_duration, 'by_size': by_size, 'examples': best_examples, 'worst_in_range': {name: {'ratio': str(ratio), 'jobs': jobs, 'cost': cost, 'optimum': opt} for name, (ratio, jobs, cost, opt) in worst.items()}, } if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('output') parser.add_argument('--max-jobs', default=7, type=int) parser.add_argument('--max-duration', default=12, type=int) inputs = parser.parse_args() report = experiment(inputs.max_jobs, inputs.max_duration) with open(inputs.output, 'w', encoding='utf-8') as out: json.dump(report, out, indent=2) out.write('\n') print(json.dumps({k: v for k, v in report.items() if k != 'examples'}, indent=2))