Skip to content

Commit 930c8f3

Browse files
soodokuclaude
andauthored
Add flip budgets, priced movement, and regime simulations (#13)
Queue Shift previously matched NFR interpolation on queue movement only, which silently dropped the negative-flip protection the baseline exists to provide. The solver now also caps (MILP) or penalizes (min-cost flow) case churn or expected negative flips, prices movement per queue so budgets can count cases, hours, or money, and returns per-queue dual prices from the flow form. A regime simulation maps when holding queue totals is costly (updates that move volume) versus nearly free (updates that reorder cases), and compares learned queue prices with exact per-batch assignment. The paper is rewritten around these results; all tables and figures are regenerated. Breaking: solve_assignment takes incumbent labels instead of incumbent loads. Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent b89dab7 commit 930c8f3

37 files changed

Lines changed: 18217 additions & 16297 deletions

‎CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
# Changelog
22

3+
## Unreleased
4+
5+
- Add a budget or penalty on case churn or expected negative flips, and match comparisons on
6+
both queue movement and expected flips.
7+
- Price movement by queue (`queue_costs`), so budgets can count cases, hours, or money.
8+
- Return per-queue dual prices from the flow solver.
9+
- Breaking: `solve_assignment` takes incumbent labels instead of incumbent loads.
10+
- Add a regime simulation mapping when holding queue totals is costly and how learned prices
11+
compare with exact per-batch assignment.
12+
313
## 0.1.0 - 2026-08-17
414

515
- Define queue shift as incumbent-relative workload movement across predicted queues.

‎Makefile‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ PYTHON := uv run python
22
SOURCE_DATE_EPOCH := 1786960800
33
export SOURCE_DATE_EPOCH
44

5-
.PHONY: sync format lint test build theory oracle estimated analyze reproduce check-generated paper research-check check clean
5+
.PHONY: sync format lint test build theory oracle estimated regimes analyze reproduce check-generated paper research-check check clean
66

77
sync:
88
uv sync --all-groups --all-extras
@@ -32,6 +32,9 @@ oracle:
3232
estimated:
3333
$(PYTHON) -m experiments.run_estimated --outdir results/estimated
3434

35+
regimes:
36+
$(PYTHON) -m experiments.run_regimes --outdir results/regimes
37+
3538
analyze:
3639
MPLCONFIGDIR=/tmp/queue-shift-matplotlib $(PYTHON) -m experiments.analyze_oracle \
3740
results/oracle \
@@ -45,8 +48,17 @@ analyze:
4548
--tex paper/generated/estimated_summary.tex \
4649
--figure paper/figures/estimated_validation.pdf \
4750
--macros paper/generated/estimated_numbers.tex
48-
49-
reproduce: oracle estimated analyze
51+
MPLCONFIGDIR=/tmp/queue-shift-matplotlib $(PYTHON) -m experiments.analyze_regimes \
52+
results/regimes \
53+
--out results/regimes_summary.csv \
54+
--lock-out results/regimes_lock_cost.csv \
55+
--lock-tex paper/generated/regimes_lock_cost.tex \
56+
--tex paper/generated/regimes_offsets.tex \
57+
--frontier paper/figures/regimes_frontier.pdf \
58+
--mix-gap paper/figures/regimes_mix_gap.pdf \
59+
--macros paper/generated/regimes_numbers.tex
60+
61+
reproduce: oracle estimated regimes analyze
5062

5163
check-generated:
5264
@tmp=$$(mktemp -d) && \
@@ -56,12 +68,22 @@ check-generated:
5668
MPLCONFIGDIR=/tmp/queue-shift-matplotlib $(PYTHON) -m experiments.analyze_estimated \
5769
results/estimated --out $$tmp/estimated_summary.csv --tex $$tmp/estimated_summary.tex \
5870
--figure $$tmp/estimated_validation.pdf --macros $$tmp/estimated_numbers.tex >/dev/null && \
71+
MPLCONFIGDIR=/tmp/queue-shift-matplotlib $(PYTHON) -m experiments.analyze_regimes \
72+
results/regimes --out $$tmp/regimes_summary.csv --lock-out $$tmp/regimes_lock_cost.csv \
73+
--lock-tex $$tmp/regimes_lock_cost.tex \
74+
--tex $$tmp/regimes_offsets.tex --frontier $$tmp/regimes_frontier.pdf \
75+
--mix-gap $$tmp/regimes_mix_gap.pdf --macros $$tmp/regimes_numbers.tex >/dev/null && \
5976
diff -q results/oracle_summary.csv $$tmp/oracle_summary.csv && \
6077
diff -q results/estimated_summary.csv $$tmp/estimated_summary.csv && \
6178
diff -q paper/generated/oracle_summary.tex $$tmp/oracle_summary.tex && \
6279
diff -q paper/generated/estimated_summary.tex $$tmp/estimated_summary.tex && \
6380
diff -q paper/generated/oracle_numbers.tex $$tmp/oracle_numbers.tex && \
6481
diff -q paper/generated/estimated_numbers.tex $$tmp/estimated_numbers.tex && \
82+
diff -q results/regimes_summary.csv $$tmp/regimes_summary.csv && \
83+
diff -q results/regimes_lock_cost.csv $$tmp/regimes_lock_cost.csv && \
84+
diff -q paper/generated/regimes_offsets.tex $$tmp/regimes_offsets.tex && \
85+
diff -q paper/generated/regimes_lock_cost.tex $$tmp/regimes_lock_cost.tex && \
86+
diff -q paper/generated/regimes_numbers.tex $$tmp/regimes_numbers.tex && \
6587
rm -rf $$tmp && echo "generated results are synchronized"
6688

6789
paper:

‎README.md‎

Lines changed: 54 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,19 @@ Classifier updates should respect the cost they actually create. When prediction
44
specialized queues, that cost is the change in queue totals, not the number of individual
55
predictions that change.
66

7-
Queue Shift finds the highest-value batch assignment under a limit on queue-load movement. The
8-
problem is a minimum-cost flow, so the solver returns an integral global optimum. At the movement
9-
budget produced by any comparison rule, including a negative-flip method, Queue Shift weakly
10-
improves the accepted model's total probability score. If those probabilities are the true
11-
conditional probabilities, the result is dominance in conditional expected accuracy.
12-
13-
The paper proves the result and reports two stable-distribution experiments. The main validation
14-
estimates both classifiers on finite historical samples, releases the candidate only after an
15-
independent accuracy win, and tests small samples, weak innovation, overconfidence, and
16-
underconfidence.
7+
Queue Shift finds the highest-value batch assignment under two limits: on work moved between
8+
queues, counted in cases, hours, or money, and on expected negative flips. With only the movement
9+
limit, or with a penalty on flips, the problem is a minimum-cost flow with an integral global
10+
optimum and per-queue prices that reproduce it case by case; hard flip budgets and per-queue
11+
prices are solved exactly as small integer programs. At the movement and expected flips of any
12+
comparison rule, including a negative-flip interpolation, Queue Shift has at least the rule's total
13+
probability score. If those probabilities are the true conditional probabilities, the result is
14+
dominance in conditional expected accuracy.
15+
16+
The paper proves the result and uses simulation to map where the constraint matters. Holding queue
17+
totals costs little when an update mostly reorders cases and a lot when it moves volume between
18+
queues. Learned queue prices nearly match exact assignment in accuracy but miss the movement budget
19+
in most batches.
1720

1821
Read the current manuscript: [Queue Shift: Updating Classifiers Under a Staffing
1922
Budget](paper/main.pdf).
@@ -29,7 +32,7 @@ uv sync --all-groups --all-extras
2932
```python
3033
import numpy as np
3134

32-
from queue_shift import solve_assignment
35+
from queue_shift import case_flip_weights, solve_assignment
3336

3437
candidate_probability = np.array(
3538
[
@@ -38,19 +41,52 @@ candidate_probability = np.array(
3841
[0.20, 0.30, 0.50],
3942
]
4043
)
41-
incumbent_loads = np.array([1, 1, 1])
44+
incumbent_labels = np.array([0, 2, 1])
45+
46+
shift_only = solve_assignment(
47+
costs=1 - candidate_probability,
48+
incumbent_labels=incumbent_labels,
49+
move_budget=0,
50+
)
51+
print(shift_only.labels, shift_only.churn) # [0 1 2] 2: a swap keeps totals
4252

43-
result = solve_assignment(
53+
weights = case_flip_weights(
54+
candidate_probability, incumbent_labels, "expected_negative"
55+
)
56+
flip_limited = solve_assignment(
4457
costs=1 - candidate_probability,
45-
incumbent_loads=incumbent_loads,
58+
incumbent_labels=incumbent_labels,
4659
move_budget=0,
60+
flip_weights=weights,
61+
flip_budget=0.2,
62+
)
63+
# [0 2 1] 0.0: the swap would risk 0.1 + 0.3 = 0.4 expected negative flips
64+
print(flip_limited.labels, flip_limited.flip_load)
65+
```
66+
67+
The movement budget limits work added to queues beyond their incumbent loads. By default work is
68+
counted in cases, and the budget equals half the L1 distance between the proposed and incumbent
69+
queue-load vectors. A budget of zero preserves every incumbent queue total while allowing different
70+
cases to fill those slots. Pass `queue_costs` to price a case in each queue, for example in average
71+
handle hours or cost per case; the budget is then in hours or money:
72+
73+
```python
74+
hours_per_case = np.array([0.5, 1.0, 4.0])
75+
by_hours = solve_assignment(
76+
costs=1 - candidate_probability,
77+
incumbent_labels=incumbent_labels,
78+
move_budget=2.0,
79+
queue_costs=hours_per_case,
4780
)
48-
print(result.labels)
81+
print(by_hours.labels, by_hours.workload_shift) # [0 1 2] 0.0
4982
```
5083

51-
The movement budget is half the L1 distance between the proposed and incumbent queue-load
52-
vectors. A budget of zero preserves every incumbent queue total while allowing different cases to
53-
fill those slots.
84+
Flip weights price a case leaving its incumbent queue. `"expected_negative"` weights a move by
85+
the candidate's probability that the incumbent was right, so the weighted total is the expected
86+
number of negative flips; `"churn"` counts every changed label. `flip_budget` caps the total
87+
exactly (solved as a mixed-integer program). `flip_penalty` instead charges for it, which keeps
88+
the problem a minimum-cost flow, scales to large batches, and returns per-queue prices
89+
(`queue_prices`) that reproduce the assignment case by case.
5490

5591
## Reproduce the paper
5692

‎experiments/analyze_estimated.py‎

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,13 @@ def summarize(release: pd.DataFrame, results: pd.DataFrame) -> pd.DataFrame:
4343
raise RuntimeError("an exact assignment exceeded its matched movement budget")
4444
if (results["predicted_gain_pp"] < -1e-9).any():
4545
raise RuntimeError("supplied-score dominance failed")
46+
joint_budget_slack = 2e-6 * (1 + results["n_cases"])
47+
if (
48+
results["joint_expected_flips"] > results["flip_budget"] + joint_budget_slack
49+
).any():
50+
raise RuntimeError("a joint assignment exceeded its matched flip budget")
51+
if (results["joint_predicted_gain_pp"] < -1e-9).any():
52+
raise RuntimeError("joint supplied-score dominance failed")
4653
if (results["conditional_gain_pp"] < results["robust_lower_bound_pp"] - 1e-8).any():
4754
raise RuntimeError("the probability-error lower bound failed")
4855
endpoint = results[results["alpha"] == 1.0]
@@ -54,6 +61,9 @@ def summarize(release: pd.DataFrame, results: pd.DataFrame) -> pd.DataFrame:
5461
).agg(
5562
move_share=("baseline_move_share", "mean"),
5663
nfr=("baseline_nfr", "mean"),
64+
operational_nfr=("operational_nfr", "mean"),
65+
joint_nfr=("joint_nfr", "mean"),
66+
joint_conditional_gain_pp=("joint_conditional_gain_pp", "mean"),
5767
predicted_gain_pp=("predicted_gain_pp", "mean"),
5868
conditional_gain_pp=("conditional_gain_pp", "mean"),
5969
realized_gain_pp=("realized_gain_pp", "mean"),
@@ -63,6 +73,10 @@ def summarize(release: pd.DataFrame, results: pd.DataFrame) -> pd.DataFrame:
6373
repetitions=("realized_gain_pp", "size"),
6474
move_share=("move_share", "mean"),
6575
nfr=("nfr", "mean"),
76+
operational_nfr=("operational_nfr", "mean"),
77+
joint_nfr=("joint_nfr", "mean"),
78+
joint_conditional_gain_pp=("joint_conditional_gain_pp", "mean"),
79+
joint_conditional_gain_se=("joint_conditional_gain_pp", "sem"),
6680
predicted_gain_pp=("predicted_gain_pp", "mean"),
6781
conditional_gain_pp=("conditional_gain_pp", "mean"),
6882
conditional_gain_se=("conditional_gain_pp", "sem"),
@@ -89,17 +103,20 @@ def write_table(summary: pd.DataFrame, path: Path) -> None:
89103
selected = summary[summary["alpha"].isin([0.0, 0.5, 1.0])]
90104
rows = []
91105
for row in selected.itertuples(index=False):
92-
conditional_low = row.conditional_gain_pp - 1.96 * row.conditional_gain_se
93-
conditional_high = row.conditional_gain_pp + 1.96 * row.conditional_gain_se
94-
realized_low = row.realized_gain_pp - 1.96 * row.realized_gain_se
95-
realized_high = row.realized_gain_pp + 1.96 * row.realized_gain_se
106+
qs_low = row.conditional_gain_pp - 1.96 * row.conditional_gain_se
107+
qs_high = row.conditional_gain_pp + 1.96 * row.conditional_gain_se
108+
joint_low = row.joint_conditional_gain_pp - 1.96 * row.joint_conditional_gain_se
109+
joint_high = (
110+
row.joint_conditional_gain_pp + 1.96 * row.joint_conditional_gain_se
111+
)
96112
rows.append(
97113
f"{SCENARIO_LABELS[row.scenario]} & {row.alpha:.1f} & "
98114
f"{100 * row.move_share:.2f} & "
99-
f"{row.predicted_gain_pp:.2f} & "
100-
f"{row.conditional_gain_pp:.2f} "
101-
f"[{conditional_low:.2f}, {conditional_high:.2f}] & "
102-
f"{row.realized_gain_pp:.2f} [{realized_low:.2f}, {realized_high:.2f}] \\\\"
115+
f"{100 * row.nfr:.1f} & {100 * row.operational_nfr:.1f} & "
116+
f"{100 * row.joint_nfr:.1f} & "
117+
f"{row.conditional_gain_pp:.2f} [{qs_low:.2f}, {qs_high:.2f}] & "
118+
f"{row.joint_conditional_gain_pp:.2f} "
119+
f"[{joint_low:.2f}, {joint_high:.2f}] \\\\"
103120
)
104121
content = "\n".join(
105122
[
@@ -108,13 +125,14 @@ def write_table(summary: pd.DataFrame, path: Path) -> None:
108125
r"\caption{Estimated-model validation against NFR interpolation}",
109126
r"\label{tab:estimated-validation}",
110127
r"\scriptsize",
111-
r"\begin{tabular}{lrrrrr}",
128+
r"\begin{tabular}{lrrrrrrr}",
112129
r"\toprule",
113130
(
114-
r"Scenario & $\alpha$ & Shift (\%) & Score gain & "
115-
r"True gain [95\% CI] & Realized gain [95\% CI] \\"
131+
r" & & Shift & \multicolumn{3}{c}{NFR (\%)} & "
132+
r"\multicolumn{2}{c}{True gain over interp. (pp) [95\% CI]} \\"
116133
),
117-
r" & & & (pp) & (pp) & (pp) \\",
134+
r"\cmidrule(lr){4-6}\cmidrule(lr){7-8}",
135+
r"Scenario & $\alpha$ & (\%) & Interp. & QS & QS+flips & QS & QS+flips \\",
118136
r"\midrule",
119137
*rows,
120138
r"\bottomrule",
@@ -125,8 +143,9 @@ def write_table(summary: pd.DataFrame, path: Path) -> None:
125143
r"estimated on historical samples and released only after the candidate "
126144
r"wins on an independent labeled sample. Each row compares exact "
127145
r"assignment with probability interpolation at the same realized queue "
128-
r"shift. True gain uses the simulation's conditional probabilities and "
129-
r"is unavailable in applications. Results average four planning batches "
146+
r"shift (QS), and at both its queue shift and its expected negative flips "
147+
r"(QS+flips). True gain uses the simulation's conditional "
148+
r"probabilities and is unavailable in applications. Results average four planning batches "
130149
r"within each independently trained accepted update before averaging "
131150
r"across updates."
132151
),

0 commit comments

Comments
 (0)