payoff 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
payoff/__init__.py ADDED
@@ -0,0 +1,69 @@
1
+ """payoff: decide whether an AI system is worth using, and how to review it.
2
+
3
+ Prices every outcome of a system whose output people review in part, finds
4
+ the best review threshold within capacity, works out the payback on the
5
+ build, shows which inputs to measure first, and turns reviewer measurements
6
+ into rates.
7
+ """
8
+
9
+ from payoff.discretion import decide
10
+ from payoff.measure import (
11
+ Range,
12
+ SensitivityRow,
13
+ Simulation,
14
+ beta_posterior_mean,
15
+ cost_of_minutes,
16
+ implied_error_rate,
17
+ seeded_errors_needed,
18
+ sensitivity,
19
+ simulate,
20
+ value_of_information,
21
+ wilson_interval,
22
+ )
23
+ from payoff.model import (
24
+ Params,
25
+ RoutingPoint,
26
+ advantage,
27
+ best_within_capacity,
28
+ break_even_accuracy_full_automation,
29
+ break_even_accuracy_review_all,
30
+ capacity_value,
31
+ evaluate,
32
+ expected_value_by_hand,
33
+ expected_value_full_automation,
34
+ expected_value_review_all,
35
+ net_value,
36
+ normal_cdf,
37
+ payback_months,
38
+ )
39
+
40
+ __all__ = [
41
+ "Params",
42
+ "Range",
43
+ "RoutingPoint",
44
+ "SensitivityRow",
45
+ "Simulation",
46
+ "advantage",
47
+ "best_within_capacity",
48
+ "beta_posterior_mean",
49
+ "break_even_accuracy_full_automation",
50
+ "break_even_accuracy_review_all",
51
+ "capacity_value",
52
+ "cost_of_minutes",
53
+ "decide",
54
+ "evaluate",
55
+ "expected_value_by_hand",
56
+ "expected_value_full_automation",
57
+ "expected_value_review_all",
58
+ "implied_error_rate",
59
+ "net_value",
60
+ "normal_cdf",
61
+ "payback_months",
62
+ "seeded_errors_needed",
63
+ "sensitivity",
64
+ "simulate",
65
+ "value_of_information",
66
+ "wilson_interval",
67
+ ]
68
+
69
+ __version__ = "0.1.0"
payoff/discretion.py ADDED
@@ -0,0 +1,26 @@
1
+ """When the numbers say no: weighing a project's option value and waiting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ Decision = Literal["Proceed now", "Wait", "Stop"]
8
+
9
+
10
+ def decide(
11
+ project_value: float, option_value: float, wait_value: float = 0.0
12
+ ) -> Decision:
13
+ """Compares going ahead now with stopping and with waiting.
14
+
15
+ Args:
16
+ project_value: The project's own expected value, net of its costs.
17
+ option_value: Value of what the project lets the organization do next.
18
+ wait_value: Expected value of deciding later, discounted to today.
19
+
20
+ Returns:
21
+ "Proceed now" if the project plus its option beats both stopping and
22
+ waiting, else "Wait" if waiting has value, else "Stop".
23
+ """
24
+ if project_value + option_value > max(0.0, wait_value):
25
+ return "Proceed now"
26
+ return "Wait" if wait_value > 0 else "Stop"
payoff/measure.py ADDED
@@ -0,0 +1,284 @@
1
+ """Turning estimates and measurements into the inputs the model needs.
2
+
3
+ Covers ranges and which inputs to measure first, and the statistics for
4
+ reviewer catch and overturn rates.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import dataclasses
10
+ import math
11
+ import random
12
+ from collections.abc import Mapping
13
+
14
+ from payoff import model
15
+
16
+ FIELDS = tuple(f.name for f in dataclasses.fields(model.Params))
17
+
18
+
19
+ def cost_of_minutes(minutes: float, hourly_cost: float) -> float:
20
+ """Returns the cost of a task from its minutes and a loaded hourly cost."""
21
+ return minutes / 60.0 * hourly_cost
22
+
23
+
24
+ @dataclasses.dataclass(frozen=True)
25
+ class Range:
26
+ """A low, likely, and high value for one input.
27
+
28
+ Attributes:
29
+ low: Lowest plausible value.
30
+ likely: Most likely value.
31
+ high: Highest plausible value.
32
+ """
33
+
34
+ low: float
35
+ likely: float
36
+ high: float
37
+
38
+ def __post_init__(self) -> None:
39
+ """Rejects a range that is out of order or not finite."""
40
+ values = (self.low, self.likely, self.high)
41
+ if not all(math.isfinite(v) for v in values):
42
+ raise ValueError("range values must be finite")
43
+ if not self.low <= self.likely <= self.high:
44
+ raise ValueError("range needs low <= likely <= high")
45
+
46
+ def sample(self, u: float) -> float:
47
+ """Maps a uniform draw u in [0, 1) through a triangular distribution."""
48
+ lo, mode, hi = self.low, self.likely, self.high
49
+ if hi == lo:
50
+ return lo
51
+ if u < (mode - lo) / (hi - lo):
52
+ return lo + math.sqrt(u * (hi - lo) * (mode - lo))
53
+ return hi - math.sqrt((1 - u) * (hi - lo) * (hi - mode))
54
+
55
+
56
+ @dataclasses.dataclass(frozen=True)
57
+ class SensitivityRow:
58
+ """How one input moves the decision across its range.
59
+
60
+ Attributes:
61
+ name: Input name, matching a ``Params`` field.
62
+ at_low: Advantage with this input at its low value.
63
+ at_high: Advantage with this input at its high value.
64
+ """
65
+
66
+ name: str
67
+ at_low: float
68
+ at_high: float
69
+
70
+ @property
71
+ def swing(self) -> float:
72
+ """Returns the distance between the two advantages."""
73
+ return abs(self.at_high - self.at_low)
74
+
75
+ @property
76
+ def can_flip(self) -> bool:
77
+ """Returns True if the decision changes sign within the range."""
78
+ return (
79
+ min(self.at_low, self.at_high) < 0 < max(self.at_low, self.at_high)
80
+ )
81
+
82
+
83
+ def _check(ranges: Mapping[str, Range]) -> None:
84
+ """Raises ValueError unless there is exactly one range per input."""
85
+ if set(ranges) != set(FIELDS):
86
+ missing = sorted(set(FIELDS) - set(ranges))
87
+ extra = sorted(set(ranges) - set(FIELDS))
88
+ raise ValueError(f"ranges missing {missing}, unexpected {extra}")
89
+
90
+
91
+ def _params(values: Mapping[str, float]) -> model.Params:
92
+ return model.Params(**{name: values[name] for name in FIELDS})
93
+
94
+
95
+ def sensitivity(
96
+ ranges: Mapping[str, Range], *, steps: int = 400, exact: bool = True
97
+ ) -> tuple[float, list[SensitivityRow]]:
98
+ """Moves each input from low to high with the others at their likely values.
99
+
100
+ Args:
101
+ ranges: One range per ``Params`` field.
102
+ steps: Grid intervals for the routing search.
103
+ exact: Passed to ``model.best_within_capacity``. False matches the
104
+ workbook.
105
+
106
+ Returns:
107
+ The advantage at the likely values, and one row per input sorted by
108
+ swing, widest first.
109
+ """
110
+ _check(ranges)
111
+ base = _params({k: r.likely for k, r in ranges.items()})
112
+ rows = [
113
+ SensitivityRow(
114
+ name=name,
115
+ at_low=model.advantage(
116
+ base.replace(**{name: ranges[name].low}),
117
+ steps=steps,
118
+ exact=exact,
119
+ ),
120
+ at_high=model.advantage(
121
+ base.replace(**{name: ranges[name].high}),
122
+ steps=steps,
123
+ exact=exact,
124
+ ),
125
+ )
126
+ for name in FIELDS
127
+ ]
128
+ rows.sort(key=lambda r: r.swing, reverse=True)
129
+ return model.advantage(base, steps=steps, exact=exact), rows
130
+
131
+
132
+ @dataclasses.dataclass(frozen=True)
133
+ class Simulation:
134
+ """Advantage under many joint draws of the inputs.
135
+
136
+ Attributes:
137
+ draws: Each draw's input values.
138
+ advantages: The advantage for each draw, in the same order.
139
+ """
140
+
141
+ draws: list[dict[str, float]]
142
+ advantages: list[float]
143
+
144
+ @property
145
+ def share_positive(self) -> float:
146
+ """Returns the share of draws in which the system beats manual work."""
147
+ return sum(a > 0 for a in self.advantages) / len(self.advantages)
148
+
149
+ @property
150
+ def mean(self) -> float:
151
+ """Returns the mean advantage across draws."""
152
+ return sum(self.advantages) / len(self.advantages)
153
+
154
+
155
+ def simulate(
156
+ ranges: Mapping[str, Range],
157
+ *,
158
+ draws: int = 2000,
159
+ seed: int = 0,
160
+ steps: int = 150,
161
+ ) -> Simulation:
162
+ """Draws every input from a triangular distribution over its range.
163
+
164
+ Args:
165
+ ranges: One range per ``Params`` field.
166
+ draws: Number of joint draws.
167
+ seed: Random seed, so results repeat.
168
+ steps: Grid intervals for each routing search.
169
+
170
+ Returns:
171
+ The draws and their advantages.
172
+ """
173
+ _check(ranges)
174
+ rng = random.Random(seed) # noqa: S311 - simulation, not security
175
+ samples = [
176
+ {name: ranges[name].sample(rng.random()) for name in FIELDS}
177
+ for _ in range(draws)
178
+ ]
179
+ return Simulation(
180
+ draws=samples,
181
+ advantages=[model.advantage(_params(s), steps=steps) for s in samples],
182
+ )
183
+
184
+
185
+ def value_of_information(
186
+ sim: Simulation, name: str, *, bins: int = 20
187
+ ) -> float:
188
+ """Estimates what knowing one input exactly is worth, per item.
189
+
190
+ This is the expected value of perfect partial information. Draws are
191
+ grouped into equal-count bins of the input, and each bin's mean advantage
192
+ stands in for the advantage given that input. Multiply by volume to
193
+ compare with the cost of measuring.
194
+
195
+ Args:
196
+ sim: A simulation from ``simulate``.
197
+ name: The input to value.
198
+ bins: Number of bins.
199
+
200
+ Returns:
201
+ The estimated value of knowing the input, never below zero.
202
+ """
203
+ pairs = sorted(
204
+ zip(sim.draws, sim.advantages, strict=True), key=lambda d: d[0][name]
205
+ )
206
+ n = len(pairs)
207
+ informed = 0.0
208
+ for b in range(bins):
209
+ chunk = [a for _, a in pairs[b * n // bins : (b + 1) * n // bins]]
210
+ if chunk:
211
+ informed += max(0.0, sum(chunk) / len(chunk)) * len(chunk) / n
212
+ return max(0.0, informed - max(0.0, sim.mean))
213
+
214
+
215
+ def beta_posterior_mean(
216
+ prior_mean: float, prior_strength: float, successes: int, trials: int
217
+ ) -> float:
218
+ """Updates a rate stated as a prior mean held as firmly as n observations.
219
+
220
+ Args:
221
+ prior_mean: The rate expected before any data.
222
+ prior_strength: How many observations the prior is worth.
223
+ successes: Observed successes, such as seeded errors caught.
224
+ trials: Observed trials, such as seeded errors shown.
225
+
226
+ Returns:
227
+ The posterior mean of a Beta prior updated with the data.
228
+ """
229
+ alpha = prior_mean * prior_strength + successes
230
+ beta = (1 - prior_mean) * prior_strength + trials - successes
231
+ return alpha / (alpha + beta)
232
+
233
+
234
+ def wilson_interval(
235
+ successes: int, trials: int, z: float = 1.96
236
+ ) -> tuple[float, float]:
237
+ """Returns the Wilson score interval for a rate.
238
+
239
+ It behaves better than the usual normal interval near 0 and 1 and for
240
+ small samples.
241
+
242
+ Raises:
243
+ ValueError: If trials is not positive.
244
+ """
245
+ if trials <= 0:
246
+ raise ValueError("trials must be positive")
247
+ p = successes / trials
248
+ centre = p + z * z / (2 * trials)
249
+ half = z * math.sqrt(p * (1 - p) / trials + z * z / (4 * trials * trials))
250
+ denom = 1 + z * z / trials
251
+ return (centre - half) / denom, (centre + half) / denom
252
+
253
+
254
+ def seeded_errors_needed(
255
+ expected_rate: float, half_width: float, z: float = 1.96
256
+ ) -> int:
257
+ """Returns how many seeded errors estimate a rate to within +/- half_width.
258
+
259
+ Uses the normal approximation, rounded up.
260
+ """
261
+ n = z * z * expected_rate * (1 - expected_rate) / half_width**2
262
+ return math.ceil(round(n, 9))
263
+
264
+
265
+ def implied_error_rate(
266
+ edit_rate: float,
267
+ material_share: float,
268
+ catch_rate: float,
269
+ overturn_rate: float = 0.0,
270
+ ) -> float | None:
271
+ """Returns the model's error rate implied by how often reviewers edit.
272
+
273
+ Material edits are the errors caught plus the correct outputs overturned,
274
+ so the error rate is (material_share * edit_rate - overturn_rate) /
275
+ (catch_rate - overturn_rate).
276
+
277
+ Returns:
278
+ The implied error rate, or None if catch_rate <= overturn_rate.
279
+ """
280
+ if catch_rate <= overturn_rate:
281
+ return None
282
+ return (material_share * edit_rate - overturn_rate) / (
283
+ catch_rate - overturn_rate
284
+ )
payoff/model.py ADDED
@@ -0,0 +1,297 @@
1
+ """Expected value of an AI system whose output people review in part.
2
+
3
+ A model scores each item for confidence. Items scoring at or above a
4
+ threshold go straight through; the rest go to a person, who confirms correct
5
+ drafts, fixes the wrong ones they catch, and now and then changes a correct
6
+ draft into a wrong one. Every quantity is per item, in whatever money unit the
7
+ inputs use.
8
+
9
+ The confidence score is modeled as normal with unit variance: mean
10
+ ``separation`` for correct outputs and mean 0 for wrong ones.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import dataclasses
16
+ import math
17
+
18
+ _RATES = ("accuracy", "catch_rate", "overturn_rate", "capacity")
19
+ _HALVINGS = 60 # Bisection steps for the cut-off that fills capacity.
20
+
21
+
22
+ @dataclasses.dataclass(frozen=True)
23
+ class Params:
24
+ """Inputs for one system. Money inputs share one unit, such as dollars.
25
+
26
+ Attributes:
27
+ value: Value of one correct output.
28
+ error_cost: Cost of an error that reaches the outcome, on top of the
29
+ value lost.
30
+ hand_cost: Cost of a person doing one item from scratch.
31
+ confirm_cost: Cost of a person confirming a correct draft.
32
+ fix_cost: Cost of a person fixing a wrong draft.
33
+ accuracy: Share of outputs that are right, from 0 to 1.
34
+ separation: How well confidence tells right from wrong, in standard
35
+ deviations. Zero means the score carries no information.
36
+ catch_rate: Share of wrong drafts a reviewer catches.
37
+ overturn_rate: Share of correct drafts a reviewer changes to wrong.
38
+ capacity: Share of items people can review.
39
+ run_cost: Cost of running the system, per item.
40
+ """
41
+
42
+ value: float
43
+ error_cost: float
44
+ hand_cost: float
45
+ confirm_cost: float
46
+ fix_cost: float
47
+ accuracy: float
48
+ separation: float
49
+ catch_rate: float
50
+ overturn_rate: float = 0.0
51
+ capacity: float = 1.0
52
+ run_cost: float = 0.0
53
+
54
+ def __post_init__(self) -> None:
55
+ """Rejects inputs that are not finite, negative, or out of range."""
56
+ for field in dataclasses.fields(self):
57
+ x = getattr(self, field.name)
58
+ if isinstance(x, bool) or not isinstance(x, (int, float)):
59
+ raise TypeError(f"{field.name} must be a number, got {x!r}")
60
+ if not math.isfinite(x) or x < 0:
61
+ raise ValueError(f"{field.name} must be finite and >= 0")
62
+ for name in _RATES:
63
+ if getattr(self, name) > 1:
64
+ raise ValueError(f"{name} must be between 0 and 1")
65
+
66
+ def replace(self, **changes: float) -> Params:
67
+ """Returns a copy with some inputs changed."""
68
+ return dataclasses.replace(self, **changes)
69
+
70
+
71
+ @dataclasses.dataclass(frozen=True)
72
+ class RoutingPoint:
73
+ """Outcome of routing at one confidence threshold.
74
+
75
+ Attributes:
76
+ threshold: Items scoring at or above this go straight through.
77
+ share_reviewed: Share of items sent to a person.
78
+ expected_value: Expected value per item, net of all costs.
79
+ error_share_in_queue: Share of reviewed items whose draft is wrong.
80
+ error_rate: Share of items whose error reaches the outcome.
81
+ """
82
+
83
+ threshold: float
84
+ share_reviewed: float
85
+ expected_value: float
86
+ error_share_in_queue: float
87
+ error_rate: float
88
+
89
+
90
+ def normal_cdf(z: float) -> float:
91
+ """Returns the standard normal distribution function at z."""
92
+ return 0.5 * (1.0 + math.erf(z / math.sqrt(2.0)))
93
+
94
+
95
+ def evaluate(params: Params, threshold: float) -> RoutingPoint:
96
+ """Evaluates routing at one threshold.
97
+
98
+ Args:
99
+ params: System inputs.
100
+ threshold: Confidence score at or above which items skip review.
101
+
102
+ Returns:
103
+ The routing outcome at that threshold.
104
+ """
105
+ p = params
106
+ right_reviewed = p.accuracy * normal_cdf(threshold - p.separation)
107
+ wrong_reviewed = (1 - p.accuracy) * normal_cdf(threshold)
108
+ right_through = p.accuracy - right_reviewed
109
+ wrong_through = (1 - p.accuracy) - wrong_reviewed
110
+ lost = p.error_cost + p.confirm_cost
111
+ value = (
112
+ right_through * p.value
113
+ - wrong_through * p.error_cost
114
+ + right_reviewed
115
+ * (
116
+ (1 - p.overturn_rate) * (p.value - p.confirm_cost)
117
+ - p.overturn_rate * lost
118
+ )
119
+ + wrong_reviewed
120
+ * (p.catch_rate * (p.value - p.fix_cost) - (1 - p.catch_rate) * lost)
121
+ - p.run_cost
122
+ )
123
+ reviewed = right_reviewed + wrong_reviewed
124
+ return RoutingPoint(
125
+ threshold=threshold,
126
+ share_reviewed=reviewed,
127
+ expected_value=value,
128
+ error_share_in_queue=wrong_reviewed / reviewed if reviewed else 0.0,
129
+ error_rate=(
130
+ wrong_through
131
+ + wrong_reviewed * (1 - p.catch_rate)
132
+ + right_reviewed * p.overturn_rate
133
+ ),
134
+ )
135
+
136
+
137
+ def expected_value_by_hand(params: Params) -> float:
138
+ """Returns the expected value per item of the current, manual process."""
139
+ return params.value - params.hand_cost
140
+
141
+
142
+ def expected_value_full_automation(params: Params) -> float:
143
+ """Returns the expected value per item with no review at all."""
144
+ p = params
145
+ return p.accuracy * p.value - (1 - p.accuracy) * p.error_cost - p.run_cost
146
+
147
+
148
+ def expected_value_review_all(params: Params) -> float:
149
+ """Returns the expected value per item when people review every item."""
150
+ return evaluate(params, math.inf).expected_value
151
+
152
+
153
+ def break_even_accuracy_full_automation(params: Params) -> float:
154
+ """Returns the accuracy at which full automation matches the manual process.
155
+
156
+ Args:
157
+ params: System inputs; accuracy is ignored.
158
+
159
+ Returns:
160
+ The break-even accuracy. Above 1 means no accuracy is enough.
161
+ """
162
+ p = params
163
+ return 1 - (p.hand_cost - p.run_cost) / (p.value + p.error_cost)
164
+
165
+
166
+ def break_even_accuracy_review_all(params: Params) -> float | None:
167
+ """Returns the accuracy at which reviewing everything matches manual work.
168
+
169
+ Assumes review catches every error and overturns nothing.
170
+
171
+ Args:
172
+ params: System inputs; accuracy, catch and overturn rates are ignored.
173
+
174
+ Returns:
175
+ The break-even accuracy, where zero or less means any accuracy pays,
176
+ or None if fixing a draft costs no more than confirming one.
177
+ """
178
+ p = params
179
+ if p.fix_cost <= p.confirm_cost:
180
+ return None
181
+ return 1 - (p.hand_cost - p.run_cost - p.confirm_cost) / (
182
+ p.fix_cost - p.confirm_cost
183
+ )
184
+
185
+
186
+ def _grid(params: Params, steps: int) -> list[RoutingPoint]:
187
+ """Returns routing outcomes at steps + 1 thresholds from -6 to sep + 6."""
188
+ span = params.separation + 12.0
189
+ return [evaluate(params, -6.0 + span * i / steps) for i in range(steps + 1)]
190
+
191
+
192
+ def _on_capacity(params: Params, capacity: float) -> RoutingPoint:
193
+ """Returns the routing point that reviews exactly the given share."""
194
+ low, high = -12.0, params.separation + 12.0
195
+ for _ in range(_HALVINGS):
196
+ mid = (low + high) / 2
197
+ if evaluate(params, mid).share_reviewed > capacity:
198
+ high = mid
199
+ else:
200
+ low = mid
201
+ return evaluate(params, low)
202
+
203
+
204
+ def best_within_capacity(
205
+ params: Params,
206
+ *,
207
+ steps: int = 400,
208
+ exact: bool = True,
209
+ capacity: float | None = None,
210
+ ) -> RoutingPoint:
211
+ """Finds the threshold with the highest expected value within capacity.
212
+
213
+ Args:
214
+ params: System inputs.
215
+ steps: Number of grid intervals between thresholds -6 and sep + 6.
216
+ exact: If True, also tries the threshold that reviews exactly the
217
+ capacity, which the grid can step over. If False, the result
218
+ matches the workbook's grid search.
219
+ capacity: Review capacity to use instead of ``params.capacity``.
220
+
221
+ Returns:
222
+ The best routing point found.
223
+ """
224
+ cap = params.capacity if capacity is None else capacity
225
+ best = max(
226
+ (pt for pt in _grid(params, steps) if pt.share_reviewed <= cap + 1e-9),
227
+ key=lambda pt: pt.expected_value,
228
+ )
229
+ if exact and 0 < cap < 1:
230
+ edge = _on_capacity(params, cap)
231
+ if edge.expected_value > best.expected_value:
232
+ best = edge
233
+ return best
234
+
235
+
236
+ def advantage(params: Params, *, steps: int = 400, exact: bool = True) -> float:
237
+ """Returns how much the best design within capacity beats manual work.
238
+
239
+ Positive means the system is worth having, per item, before any option
240
+ value.
241
+ """
242
+ best = best_within_capacity(params, steps=steps, exact=exact)
243
+ return best.expected_value - expected_value_by_hand(params)
244
+
245
+
246
+ def capacity_value(params: Params, *, step: float = 0.01) -> float:
247
+ """Returns the value per item of one more unit of review capacity.
248
+
249
+ This is the shadow price of the capacity constraint, estimated with a
250
+ forward difference. Multiply by ``step`` for the value of a step.
251
+ """
252
+ here = best_within_capacity(params).expected_value
253
+ more = min(1.0, params.capacity + step)
254
+ there = best_within_capacity(params, capacity=more).expected_value
255
+ return (there - here) / step
256
+
257
+
258
+ def payback_months(build_cost: float, yearly_savings: float) -> float | None:
259
+ """Returns the months after launch until savings cover the build.
260
+
261
+ Assumes the savings arrive in full from launch. Add the months to build
262
+ for the time from funding to payback.
263
+
264
+ Args:
265
+ build_cost: One-time cost to build and set up the system.
266
+ yearly_savings: Savings per year once running, such as
267
+ ``advantage(params) * volume``.
268
+
269
+ Returns:
270
+ Months to pay back the build, or None if the savings are not
271
+ positive.
272
+ """
273
+ if yearly_savings <= 0:
274
+ return None
275
+ return build_cost / (yearly_savings / 12)
276
+
277
+
278
+ def net_value(
279
+ build_cost: float,
280
+ yearly_savings: float,
281
+ years: int,
282
+ discount_rate: float = 0.0,
283
+ ) -> float:
284
+ """Returns the value of the system over its years of use, after the build.
285
+
286
+ Args:
287
+ build_cost: One-time cost to build and set up the system.
288
+ yearly_savings: Savings per year once running.
289
+ years: Years of use to count.
290
+ discount_rate: Annual rate for discounting later years; 0 means none.
291
+
292
+ Returns:
293
+ The discounted savings over the years of use, minus the build cost.
294
+ """
295
+ return -build_cost + sum(
296
+ yearly_savings / (1 + discount_rate) ** t for t in range(1, years + 1)
297
+ )
payoff/py.typed ADDED
File without changes
@@ -0,0 +1,234 @@
1
+ Metadata-Version: 2.5
2
+ Name: payoff
3
+ Version: 0.1.0
4
+ Summary: Decide whether an AI system is worth using, and how much of its output people should check.
5
+ Project-URL: Homepage, https://github.com/ChristopherDaigle/payoff
6
+ Project-URL: Source, https://github.com/ChristopherDaigle/payoff
7
+ Project-URL: Issues, https://github.com/ChristopherDaigle/payoff/issues
8
+ Project-URL: Changelog, https://github.com/ChristopherDaigle/payoff/blob/main/CHANGELOG.md
9
+ Project-URL: Article, https://quantchris.com/posts/2026-11-29-is-it-possible-and-is-it-worth-it.html
10
+ Author: Christopher Daigle
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: decision analysis,expected value,human in the loop,model evaluation,value of information
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Financial and Insurance Industry
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Scientific/Engineering
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+
28
+ # payoff
29
+
30
+ Decide whether an AI system is worth using, and how much of its output
31
+ people should check.
32
+
33
+ [![CI](https://github.com/ChristopherDaigle/payoff/actions/workflows/ci.yml/badge.svg)](https://github.com/ChristopherDaigle/payoff/actions/workflows/ci.yml)
34
+
35
+ Most AI work is funded on a model metric (accuracy, F1, AUC) and a business
36
+ case that assumes the model does all the work. Neither says whether the
37
+ *system* is worth having: the model, the cut-off someone chose, the people who
38
+ check some of its output, and the capacity they have. `payoff` prices every
39
+ outcome of that system, finds the best share of work to send to people, and
40
+ shows which uncertain inputs are worth measuring before you decide.
41
+
42
+ The name is the decision-theory term. Every way a decision can turn out has a
43
+ payoff, and the best design is the one with the highest expected payoff once
44
+ the model's errors, the reviewers' time, and the build are all counted.
45
+
46
+ It is the code companion to two articles:
47
+
48
+ - [Is It Possible, and Is It Worth It?](https://quantchris.com/posts/2026-11-29-is-it-possible-and-is-it-worth-it.html)
49
+ covers what to do with the costs and benefits.
50
+ - [Where the Numbers Come From](https://quantchris.com/posts/2026-11-29-where-the-numbers-come-from.html)
51
+ covers how to get them.
52
+
53
+ The same calculations are in a
54
+ [workbook](https://quantchris.com/assets/files/payoff-workbook.xlsx) for
55
+ readers who prefer a spreadsheet. The tests check that this package and the
56
+ workbook give the same numbers.
57
+
58
+ ## Install
59
+
60
+ With [uv](https://docs.astral.sh/uv/):
61
+
62
+ ```bash
63
+ uv add payoff
64
+ ```
65
+
66
+ or with pip: `pip install payoff`.
67
+ Python 3.10 or later. No runtime dependencies.
68
+
69
+ ## Quick start
70
+
71
+ ```python
72
+ import payoff
73
+
74
+ # A refund team: 100,000 requests a year, dollars per request.
75
+ hourly = 50.0 # loaded cost per hour of a support rep
76
+ params = payoff.Params(
77
+ value=10.0, # a correct decision is worth what it costs to make today
78
+ error_cost=50.0, # a wrong decision that reaches a customer
79
+ hand_cost=payoff.cost_of_minutes(12, hourly),
80
+ confirm_cost=payoff.cost_of_minutes(3, hourly),
81
+ fix_cost=payoff.cost_of_minutes(6, hourly),
82
+ accuracy=0.80,
83
+ separation=1.5,
84
+ catch_rate=0.90,
85
+ overturn_rate=0.02,
86
+ capacity=0.40,
87
+ run_cost=0.50,
88
+ )
89
+
90
+ best = payoff.best_within_capacity(params)
91
+ best.share_reviewed # 0.40: check 40% of requests
92
+ payoff.advantage(params) # 4.81: dollars saved per request versus today
93
+ payoff.payback_months(200_000, payoff.advantage(params) * 100_000) # 5.0
94
+ ```
95
+
96
+ `examples/quickstart.py` adds sensitivity, simulation, and the value of
97
+ measuring each input:
98
+
99
+ ```text
100
+ $ uv run python examples/quickstart.py
101
+ Check 40% of items.
102
+ Advantage over doing it by hand: $4.81 per item,
103
+ $480,911 per year.
104
+ Pays back the build 5.0 months after launch, 9.0 after funding.
105
+ One more point of capacity is worth $4,375 per year.
106
+
107
+ What to measure first (advantage per year, low to high):
108
+ error_cost $646,782 to -$348,443 <- can change the answer
109
+ hand_cost $230,911 to $730,911
110
+ ...
111
+ Beats the current process in 66% of 2,000 draws.
112
+ Knowing error_cost exactly is worth about $71,054 per year.
113
+ ```
114
+
115
+ ## What it answers
116
+
117
+ | Question | Function |
118
+ |---|---|
119
+ | What is each design worth per item? | `expected_value_by_hand`, `expected_value_full_automation`, `expected_value_review_all`, `evaluate` |
120
+ | What accuracy does each design need? | `break_even_accuracy_full_automation`, `break_even_accuracy_review_all` |
121
+ | What share should people check, given their capacity? | `best_within_capacity`, `advantage` |
122
+ | What is more review capacity worth? | `capacity_value` |
123
+ | When does the build pay back, and what is it worth over its life? | `payback_months`, `net_value` |
124
+ | Which inputs could change the answer? | `Range`, `sensitivity` |
125
+ | How likely is the system to beat the current process? | `simulate` |
126
+ | Which measurement is worth paying for? | `value_of_information` |
127
+ | What are reviewers' catch and overturn rates? | `beta_posterior_mean`, `wilson_interval`, `seeded_errors_needed` |
128
+ | What error rate do the edits imply? | `implied_error_rate` |
129
+ | The numbers say no: proceed, wait, or stop? | `decide` |
130
+
131
+ Every public function has a docstring with its arguments and return value.
132
+
133
+ ## The model
134
+
135
+ Each item gets a confidence score. Items at or above a cut-off go straight
136
+ through; the rest go to a person, up to the review capacity. A person
137
+ confirms a correct draft, fixes a wrong one they catch, misses the rest, and
138
+ now and then changes a correct draft into a wrong one.
139
+
140
+ | Input | Meaning |
141
+ |---|---|
142
+ | `value` | Value of one correct result |
143
+ | `error_cost` | Cost of an error that gets through, on top of the value lost |
144
+ | `hand_cost` | Cost of doing one item from scratch |
145
+ | `confirm_cost`, `fix_cost` | Cost of confirming a correct draft, fixing a wrong one |
146
+ | `accuracy` | Share of outputs that are right |
147
+ | `separation` | How well the score tells right from wrong, in standard deviations |
148
+ | `catch_rate` | Share of wrong drafts people catch |
149
+ | `overturn_rate` | Share of correct drafts people change to wrong |
150
+ | `capacity` | Share of items people can check |
151
+ | `run_cost` | Cost of running the system, per item |
152
+
153
+ Money inputs can be in any one unit. The articles, the workbook, and these
154
+ examples use dollars, with a refund team as the running example. Setting
155
+ `value=1` instead measures everything relative to the value of a correct
156
+ result, which is handy for comparing very different systems.
157
+
158
+ Assumptions, stated so you can judge whether they fit:
159
+
160
+ - Scores are normal with unit variance: mean `separation` for correct
161
+ outputs, mean 0 for wrong ones. Calibrate against your own score
162
+ distributions before relying on the routing result.
163
+ - One error cost per item. Systems with several kinds of error should price
164
+ them separately and use a weighted average, or extend the model.
165
+ - Reviewers' catch and overturn rates do not depend on the cut-off. In
166
+ practice they move when the review queue changes; the articles explain how
167
+ to measure them per queue.
168
+
169
+ ## How it matches the workbook
170
+
171
+ `best_within_capacity` searches a grid of cut-offs and then checks the
172
+ cut-off that fills capacity exactly, found by bisection. The workbook does the
173
+ same with formulas (201 cut-offs, 60 bisection steps).
174
+ `tests/test_workbook.py` reads the workbook's computed values and recomputes
175
+ each one from its inputs.
176
+
177
+ ## Project layout
178
+
179
+ ```text
180
+ src/payoff/
181
+ model.py outcomes, routing, break-even, capacity value, payback
182
+ measure.py ranges, sensitivity, simulation, reviewer statistics
183
+ discretion.py proceed, wait, or stop
184
+ tests/
185
+ test_model.py properties that hold for any inputs
186
+ test_measure.py measurement helpers
187
+ test_workbook.py parity with the published workbook
188
+ test_repo.py every text file is plain ASCII
189
+ data/payoff-workbook.xlsx
190
+ examples/quickstart.py
191
+ ```
192
+
193
+ ## Development
194
+
195
+ ```bash
196
+ uv sync # creates .venv from uv.lock
197
+ uv run pytest # tests
198
+ uv run ruff check # lint (Google docstring convention)
199
+ uv run ruff format --check # formatting
200
+ uv run mypy # strict type checks
201
+ ```
202
+
203
+ CI runs all four on Python 3.10 to 3.13. Releases go to PyPI from a version
204
+ tag; see [RELEASING.md](RELEASING.md).
205
+
206
+ ## Design choices
207
+
208
+ - **No runtime dependencies.** The math needs only the standard library, so
209
+ there is nothing to audit or pin for users.
210
+ - **Frozen dataclasses with validation.** Bad inputs fail when they are
211
+ created, with a message naming the field.
212
+ - **Repeatable randomness.** `simulate` takes a seed and defaults to 0.
213
+ - **Plain text.** A test keeps every text file ASCII, so nothing renders
214
+ differently from one terminal or editor to the next.
215
+
216
+ ## Roadmap
217
+
218
+ The articles climb a ladder, and the package will follow it:
219
+
220
+ 1. A classic model: two kinds of error, thresholds from costs, ranking under
221
+ fixed capacity.
222
+ 2. Extraction: many fields per document and many documents per case, where
223
+ correctness compounds.
224
+ 3. AI agents: a sequence of steps that take actions, with approval at
225
+ irreversible ones.
226
+ 4. Several AI agents: handoffs, and AI agents checking each other.
227
+
228
+ ## Citing
229
+
230
+ See `CITATION.cff`, or use GitHub's "Cite this repository" button.
231
+
232
+ ## License
233
+
234
+ MIT. See `LICENSE`.
@@ -0,0 +1,9 @@
1
+ payoff/__init__.py,sha256=E8jwvR1V8ZFs-76SULZ-y59Jljan1MbRUElLuKcifM8,1615
2
+ payoff/discretion.py,sha256=iCBxsZLFJ2cAzQXunsFENinIPG40jgtBLehv8gElzXk,897
3
+ payoff/measure.py,sha256=x91X_GleLujKgNU5O5EXjDuxSI0WalyyVzJD7haocwM,8869
4
+ payoff/model.py,sha256=yG32ym9NQooKv0obGUsnk07JE03j1bYfyb4xUlXg0qU,10331
5
+ payoff/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ payoff-0.1.0.dist-info/METADATA,sha256=dcw9_VnVR68h3fRUOiVQ53CMEW0D72NPpQQYSU8cHKY,9570
7
+ payoff-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ payoff-0.1.0.dist-info/licenses/LICENSE,sha256=pt7CeoQwyOq1ptod_hNcsLyLON0WuUcdLj6VVmgOJik,1075
9
+ payoff-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Christopher Daigle
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.