movedby 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.
movedby/__init__.py ADDED
@@ -0,0 +1,64 @@
1
+ """movedby: which facts moved a typed decision model's answer, measured from outside.
2
+
3
+ A decision model (Jev, OpenAI's Decisions API, Kairos) reads one state and answers typed
4
+ questions with probabilities and no reason. movedby asks it again with facts removed and
5
+ reduces the answers to attributions, as SHAP does for a tabular model, with what a paid,
6
+ remote, noisy judge needs on top: a noise floor, a quote before paying, a ledger that never
7
+ pays twice, and planted cases with known answers.
8
+
9
+ The names a run needs are here; the report (`movedby.report`), the charts (`movedby.plot`,
10
+ which needs the `plot` extra), the planted controls (`movedby.controls`) and case files
11
+ (`movedby.casefile`) are imported from their modules.
12
+ """
13
+
14
+ from importlib.metadata import PackageNotFoundError, version
15
+
16
+ from movedby.answers import ChoiceAnswer, NoulAnswer, Refusal, ScoreAnswer
17
+ from movedby.case import BadCase, Case, Delete, Fact, Replace, validate
18
+ from movedby.estimators import Exact, LeaveOneOut, Orders, Stories
19
+ from movedby.judges import Decisions, Function, Judge, Kairos, Price, TypeSafe
20
+ from movedby.result import Err, Ok, Result
21
+ from movedby.run import Budget, Explanation, Quote, explain
22
+ from movedby.target import Choice, Expected, Gap, Loss, P, Policy
23
+
24
+ try:
25
+ __version__ = version("movedby")
26
+ except PackageNotFoundError: # a source tree that was never installed
27
+ __version__ = "0+unknown"
28
+
29
+ __all__ = [
30
+ "BadCase",
31
+ "Budget",
32
+ "Case",
33
+ "Choice",
34
+ "ChoiceAnswer",
35
+ "Decisions",
36
+ "Delete",
37
+ "Err",
38
+ "Exact",
39
+ "Expected",
40
+ "Explanation",
41
+ "Fact",
42
+ "Function",
43
+ "Gap",
44
+ "Judge",
45
+ "Kairos",
46
+ "LeaveOneOut",
47
+ "Loss",
48
+ "NoulAnswer",
49
+ "Ok",
50
+ "Orders",
51
+ "P",
52
+ "Policy",
53
+ "Price",
54
+ "Quote",
55
+ "Refusal",
56
+ "Replace",
57
+ "Result",
58
+ "ScoreAnswer",
59
+ "Stories",
60
+ "TypeSafe",
61
+ "__version__",
62
+ "explain",
63
+ "validate",
64
+ ]
movedby/answers.py ADDED
@@ -0,0 +1,112 @@
1
+ """The answers every judge's parser hands back, one shape for every provider.
2
+
3
+ Jev's `noul` and Decisions' `predicate` are both a `NoulAnswer`; a `choice` is a
4
+ `ChoiceAnswer`, a `score` a `ScoreAnswer` (levels "0", "1", ... with their probabilities,
5
+ and the provider's own expected level). A refused question is a `Refusal`, never a number.
6
+ The parsers check ranges; these are plain values.
7
+ """
8
+
9
+ import math
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass, field
12
+
13
+ from movedby.result import Err, Ok, Result
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class NoulAnswer:
18
+ """The probability that the statement is true."""
19
+
20
+ p: float
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class ChoiceAnswer:
25
+ probabilities: Mapping[str, float]
26
+ choice: str | None = None
27
+ confidence: float | None = None
28
+
29
+
30
+ @dataclass(frozen=True, slots=True)
31
+ class ScoreAnswer:
32
+ probabilities: Mapping[str, float] = field(default_factory=dict)
33
+ score: float | None = None
34
+ confidence: float | None = None
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class Refusal:
39
+ reason: str = ""
40
+
41
+
42
+ type Answer = NoulAnswer | ChoiceAnswer | ScoreAnswer | Refusal
43
+ type Answers = Mapping[str, Answer]
44
+
45
+
46
+ def encode(answers: Answers) -> dict:
47
+ """The answers as plain JSON, for the ledger."""
48
+ out = {}
49
+ for question, a in answers.items():
50
+ match a:
51
+ case NoulAnswer(p=p):
52
+ out[question] = {"kind": "noul", "p": p}
53
+ case ChoiceAnswer(probabilities=probs, choice=choice, confidence=conf):
54
+ out[question] = {"kind": "choice", "probabilities": dict(probs), "choice": choice,
55
+ "confidence": conf}
56
+ case ScoreAnswer(probabilities=probs, score=score, confidence=conf):
57
+ out[question] = {"kind": "score", "probabilities": dict(probs), "score": score,
58
+ "confidence": conf}
59
+ case Refusal(reason=reason):
60
+ out[question] = {"kind": "refusal", "reason": reason}
61
+ return out
62
+
63
+
64
+ def is_number(x: object) -> bool:
65
+ """A finite number and no boolean; an integer too large for a float is none."""
66
+ if isinstance(x, bool) or not isinstance(x, int | float):
67
+ return False
68
+ try:
69
+ return math.isfinite(x)
70
+ except OverflowError:
71
+ return False
72
+
73
+
74
+ def graded_ok(a: Mapping, pick: str) -> bool:
75
+ """Whether a stored choice or score holds what its answer needs: numbers where numbers go."""
76
+ probs, sure, own = a.get("probabilities"), a.get("confidence"), a.get(pick)
77
+ if not isinstance(probs, Mapping) or not all(is_number(p) for p in probs.values()):
78
+ return False
79
+ if sure is not None and not is_number(sure):
80
+ return False
81
+ if pick == "choice":
82
+ return own is None or isinstance(own, str)
83
+ return own is None or is_number(own)
84
+
85
+
86
+ def decode(data: object) -> Result[Answers, str]:
87
+ """`encode` undone: `Ok(answers)`, or `Err` naming the question it cannot read.
88
+
89
+ A row can be damaged in its numbers as well as in its shape, and a target would raise
90
+ on it much later: so every number is checked here.
91
+ """
92
+ if not isinstance(data, Mapping):
93
+ return Err("the row holds no answers")
94
+ out: dict[str, Answer] = {}
95
+ for question, a in data.items():
96
+ kind = a.get("kind") if isinstance(a, Mapping) else None
97
+ probs = a.get("probabilities") if isinstance(a, Mapping) else None
98
+ p = a.get("p") if isinstance(a, Mapping) else None
99
+ match kind:
100
+ case "noul" if isinstance(p, int | float) and is_number(p):
101
+ out[question] = NoulAnswer(float(p))
102
+ case "choice" if isinstance(probs, Mapping) and graded_ok(a, "choice"):
103
+ out[question] = ChoiceAnswer(probs, a.get("choice"), a.get("confidence"))
104
+ case "score" if isinstance(probs, Mapping) and graded_ok(a, "score"):
105
+ out[question] = ScoreAnswer(probs, a.get("score"), a.get("confidence"))
106
+ case "refusal":
107
+ out[question] = Refusal(str(a.get("reason") or ""))
108
+ case "noul" | "choice" | "score":
109
+ return Err(f"answer to {question!r} is damaged: {str(a)[:120]}")
110
+ case other:
111
+ return Err(f"answer to {question!r} has an unknown kind {other!r}")
112
+ return Ok(out)
movedby/case.py ADDED
@@ -0,0 +1,118 @@
1
+ """A case: the state a judge reads, the facts that may be taken out of it, and the questions.
2
+
3
+ A fact is a path into the state plus a removal rule. `Delete` takes a list item out and
4
+ nothing slides into its place; `Replace` puts a declared neutral value where the fact was
5
+ (desk101 already writes "not stated" for a missing `wrong_if`). The rule is part of the
6
+ explanation: a deleted headline and a neutral one in its place give different numbers.
7
+ """
8
+
9
+ from collections import Counter
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass
12
+
13
+ from movedby.result import Err, Ok, Result
14
+
15
+ type Path = tuple[str | int, ...]
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class Delete:
20
+ """Take the list item out; the items after it move up one place."""
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class Replace:
25
+ """Put `value` where the fact was."""
26
+
27
+ value: object
28
+
29
+
30
+ @dataclass(frozen=True, slots=True)
31
+ class Fact:
32
+ id: str
33
+ path: Path
34
+ removal: Delete | Replace = Delete()
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class Case:
39
+ state: Mapping
40
+ facts: tuple[Fact, ...]
41
+ questions: Mapping
42
+ stories: tuple[tuple[str, ...], ...] = ()
43
+
44
+ @property
45
+ def players(self) -> tuple[str, ...]:
46
+ return tuple(f.id for f in self.facts)
47
+
48
+
49
+ @dataclass(frozen=True, slots=True)
50
+ class BadCase:
51
+ problems: tuple[str, ...]
52
+
53
+
54
+ def lookup(state, path: Path):
55
+ """The value at `path`, or `None` with the reason it is not there."""
56
+ node = state
57
+ for step in path:
58
+ in_map = isinstance(node, Mapping) and isinstance(step, str) and step in node
59
+ in_list = isinstance(node, list) and isinstance(step, int) and 0 <= step < len(node)
60
+ if in_map or in_list:
61
+ node = node[step]
62
+ else:
63
+ return None, f"{step!r} is not in the state"
64
+ return node, None
65
+
66
+
67
+ def problems_of(fact: Fact, state) -> list[str]:
68
+ if not fact.path: # the whole state is no fact: there is nothing left to hold it in
69
+ return [f"fact {fact.id!r} has no path: a fact is a part of the state, not all of it"]
70
+ _, missing = lookup(state, fact.path)
71
+ if missing:
72
+ return [f"fact {fact.id!r} at {fact.path}: {missing}"]
73
+ if isinstance(fact.removal, Delete):
74
+ parent, _ = lookup(state, fact.path[:-1])
75
+ if not (isinstance(parent, list) and isinstance(fact.path[-1], int)):
76
+ return [f"fact {fact.id!r} at {fact.path}: Delete is for list items; use Replace for a field"]
77
+ return []
78
+
79
+
80
+ def validate(case: Case) -> Result[Case, BadCase]:
81
+ """The case unchanged, or every problem with it at once."""
82
+ problems: list[str] = []
83
+ if not case.facts:
84
+ problems.append("no facts to remove")
85
+ ids = Counter(f.id for f in case.facts)
86
+ problems += [f"two facts are called {i!r}" for i, n in ids.items() if n > 1]
87
+ paths = Counter(f.path for f in case.facts)
88
+ problems += [f"two facts share the path {p}" for p, n in paths.items() if n > 1]
89
+ for fact in case.facts:
90
+ problems += problems_of(fact, case.state)
91
+ problems += [
92
+ f"fact {inner.id!r} lies inside fact {outer.id!r}"
93
+ for outer in case.facts
94
+ for inner in case.facts
95
+ if len(outer.path) < len(inner.path) and inner.path[: len(outer.path)] == outer.path
96
+ ]
97
+ if not case.questions:
98
+ problems.append("no questions")
99
+ problems += story_problems(case.stories, set(ids))
100
+ return Err(BadCase(tuple(problems))) if problems else Ok(case)
101
+
102
+
103
+ def story_problems(stories: tuple[tuple[str, ...], ...], ids: set[str]) -> list[str]:
104
+ """What is wrong with `stories` over the facts `ids`.
105
+
106
+ A name that is no fact, a fact in two stories, and a label two rows would share: a story
107
+ is reported under its facts joined by "+", a fact outside every story under its own name,
108
+ and two rows with one label would leave one of them unreported.
109
+ """
110
+ seen: Counter[str] = Counter(i for story in stories for i in story)
111
+ problems = [f"story names {i!r}, which is no fact" for i in seen if i not in ids]
112
+ problems += [f"fact {i!r} is in two stories" for i, n in seen.items() if n > 1 and i in ids]
113
+ labels = Counter(["+".join(story) for story in stories] + [i for i in ids if i not in seen])
114
+ return problems + [
115
+ f"the label {label!r} would stand for two rows (a story and a fact, or two stories): rename a fact"
116
+ for label, n in labels.items()
117
+ if n > 1
118
+ ]
movedby/casefile.py ADDED
@@ -0,0 +1,242 @@
1
+ """A case file: one JSON document that names the judge, the state, the facts, the target and the plan.
2
+
3
+ {
4
+ "judge": {"kind": "jev"} | {"kind": "kairos"} | {"kind": "decisions", "model": "gpt-6-luna"}
5
+ | {"kind": "function", "ref": "package.module:function", "version": "1"},
6
+ "state": {...},
7
+ "list_facts": [{"path": ["headlines"], "prefix": "h"}], every item of a list, deleted
8
+ "facts": [{"id": "wrong_if", "path": ["idea", "wrong_if"], "replace": "not stated"}],
9
+ "stories": [["h1", "h4"]], groups to leave out at once
10
+ "questions": {...}, TypeSafe's form
11
+ "target": {"p": "against"} | {"choice": "hold", "option": "1d"} | {"expected": "overclaim"},
12
+ plus "reference": 0.5 for the gap to it, or "outcome": 1 and "rule" for a loss,
13
+ "estimator": "exact" | "loo" | "stories" | {"orders": {"pairs": 10, "seed": 1}}
14
+ | {"stories": [["h1", "h4"]]},
15
+ "line": 0.05, required
16
+ "monotone": true, "repeats": 5, "shuffles": 5, "noise_sd": null,
17
+ "budget": {"usd": 1.0, "calls": null},
18
+ "ledger": "case.ledger.jsonl" next to the case file by default
19
+ }
20
+
21
+ `load(path)` is `Ok(Spec)` or `Err(BadCase)` with every problem at once; it does not raise
22
+ on a malformed file.
23
+
24
+ A case file is trusted input: a `function` judge names a Python module, and loading the
25
+ file imports it. Do not run a case file you would not run as a script.
26
+ """
27
+
28
+ import importlib
29
+ import json
30
+ from dataclasses import dataclass
31
+ from pathlib import Path
32
+
33
+ from movedby.case import BadCase, Case, Delete, Fact, Replace, lookup, validate
34
+ from movedby.estimators import Estimator, Exact, LeaveOneOut, Orders, Stories
35
+ from movedby.judges import Decisions, Function, Judge, Kairos, TypeSafe
36
+ from movedby.result import Err, Ok, Result
37
+ from movedby.run import REPEATS, Budget
38
+ from movedby.target import Choice, Expected, Gap, Loss, P, Target
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Spec:
43
+ judge: Judge
44
+ case: Case
45
+ target: Target
46
+ estimator: Estimator
47
+ line: float
48
+ monotone: bool
49
+ repeats: int
50
+ shuffles: int
51
+ noise_sd: float | None
52
+ budget: Budget
53
+ ledger: Path
54
+
55
+
56
+ def is_number(x) -> bool:
57
+ return isinstance(x, int | float) and not isinstance(x, bool)
58
+
59
+
60
+ def judge_of(raw, problems: list[str]) -> Judge | None:
61
+ kind = raw.get("kind") if isinstance(raw, dict) else None
62
+ match kind:
63
+ case "jev":
64
+ return TypeSafe(model=raw["model"]) if "model" in raw else TypeSafe()
65
+ case "kairos":
66
+ return Kairos(model=raw["model"]) if "model" in raw else Kairos()
67
+ case "decisions":
68
+ return Decisions(model=raw["model"]) if "model" in raw else Decisions()
69
+ case "function":
70
+ ref = str(raw.get("ref", ""))
71
+ module, _, attr = ref.partition(":")
72
+ try: # importing runs the module: whatever it raises is a problem with the file, not a crash
73
+ fn = getattr(importlib.import_module(module), attr)
74
+ except Exception as e:
75
+ problems.append(f"judge ref {ref!r} cannot be imported: {type(e).__name__}: {e}")
76
+ return None
77
+ version = raw.get("version")
78
+ name = str(raw.get("name", attr))
79
+ return Function(fn, name=name, version=None if version is None else str(version))
80
+ problems.append(f"judge kind {kind!r} is not one of 'jev', 'kairos', 'decisions', 'function'")
81
+ return None
82
+
83
+
84
+ def is_path(path) -> bool:
85
+ """A list of steps, each a key (a string) or an index (a whole number)."""
86
+ return isinstance(path, list) and all(
87
+ isinstance(step, str) or (isinstance(step, int) and not isinstance(step, bool)) for step in path
88
+ )
89
+
90
+
91
+ def entries(raw: dict, name: str, problems: list[str]) -> list:
92
+ """The list under `name`; anything else there is a problem, and no entries."""
93
+ given = raw.get(name)
94
+ if given is None:
95
+ return []
96
+ if not isinstance(given, list):
97
+ problems.append(f"{name} must be a list, not {type(given).__name__}")
98
+ return []
99
+ return given
100
+
101
+
102
+ def facts_of(raw: dict, state, problems: list[str]) -> tuple[Fact, ...]:
103
+ facts = []
104
+ for entry in entries(raw, "list_facts", problems):
105
+ if not isinstance(entry, dict) or not is_path(entry.get("path")):
106
+ problems.append(f"a list_facts entry needs a path (a list of keys and indices): {entry}")
107
+ continue
108
+ path = tuple(entry["path"])
109
+ items, missing = lookup(state, path)
110
+ if missing or not isinstance(items, list):
111
+ problems.append(f"list_facts path {path} is not a list in the state")
112
+ continue
113
+ prefix = str(entry.get("prefix", ""))
114
+ facts += [Fact(f"{prefix}{i}", (*path, i), Delete()) for i in range(len(items))]
115
+ for entry in entries(raw, "facts", problems):
116
+ if not isinstance(entry, dict) or "id" not in entry or not is_path(entry.get("path")):
117
+ problems.append(f"a fact needs an id and a path (a list of keys and indices): {entry}")
118
+ continue
119
+ removal = Replace(entry["replace"]) if "replace" in entry else Delete()
120
+ facts.append(Fact(str(entry["id"]), tuple(entry["path"]), removal))
121
+ return tuple(facts)
122
+
123
+
124
+ def target_of(raw, problems: list[str]) -> Target | None:
125
+ raw = raw if isinstance(raw, dict) else {}
126
+ if "p" in raw:
127
+ base: Target = P(str(raw["p"]))
128
+ elif "choice" in raw and "option" in raw:
129
+ base = Choice(str(raw["choice"]), str(raw["option"]))
130
+ elif "expected" in raw:
131
+ base = Expected(str(raw["expected"]))
132
+ else:
133
+ problems.append(f"target needs one of 'p', 'choice' with 'option', 'expected': {raw}")
134
+ return None
135
+ for name in ("reference", "outcome"):
136
+ if name in raw and not is_number(raw[name]):
137
+ problems.append(f"target {name} must be a number, not {raw[name]!r}")
138
+ return None
139
+ if "reference" in raw:
140
+ return Gap(base, float(raw["reference"]))
141
+ if "outcome" in raw:
142
+ try:
143
+ return Loss(base, float(raw["outcome"]), str(raw.get("rule", "brier")))
144
+ except ValueError as e:
145
+ problems.append(str(e))
146
+ return None
147
+ return base
148
+
149
+
150
+ def groups(raw, problems: list[str]) -> tuple[tuple[str, ...], ...]:
151
+ if not isinstance(raw, list) or not all(isinstance(s, list) for s in raw):
152
+ problems.append(f"stories must be a list of lists of fact ids, not {raw!r}")
153
+ return ()
154
+ return tuple(tuple(str(i) for i in s) for s in raw)
155
+
156
+
157
+ def estimator_of(raw, problems: list[str]) -> Estimator | None:
158
+ try:
159
+ match raw:
160
+ case "exact":
161
+ return Exact()
162
+ case "loo":
163
+ return LeaveOneOut()
164
+ case "stories":
165
+ return Stories()
166
+ case {"exact": dict(opts)}:
167
+ return Exact(**opts)
168
+ case {"orders": dict(opts)}:
169
+ return Orders(**opts)
170
+ case {"stories": stories}:
171
+ return Stories(groups(stories, problems))
172
+ except (TypeError, ValueError) as e: # an option the estimator does not have, or one it refuses
173
+ problems.append(f"estimator {raw!r}: {e}")
174
+ return None
175
+ problems.append(f"estimator {raw!r} is not 'exact', 'loo', 'stories', or an orders / stories / exact "
176
+ "object")
177
+ return None
178
+
179
+
180
+ def count(raw: dict, name: str, default: int, least: int, problems: list[str]) -> int:
181
+ found = raw.get(name, default)
182
+ if isinstance(found, bool) or not isinstance(found, int) or found < least:
183
+ problems.append(f"{name} must be a whole number of at least {least}, not {found!r}")
184
+ return default
185
+ return found
186
+
187
+
188
+ def budget_of(raw, problems: list[str]) -> Budget:
189
+ if raw is None:
190
+ return Budget()
191
+ if not isinstance(raw, dict):
192
+ problems.append(f"budget must be an object with usd and calls, not {raw!r}")
193
+ return Budget()
194
+ usd, calls = raw.get("usd", 1.0), raw.get("calls")
195
+ if usd is not None and not is_number(usd):
196
+ problems.append(f"budget usd must be a number or null, not {usd!r}")
197
+ usd = 1.0
198
+ if calls is not None and (isinstance(calls, bool) or not isinstance(calls, int)):
199
+ problems.append(f"budget calls must be a whole number or null, not {calls!r}")
200
+ calls = None
201
+ return Budget(usd, calls)
202
+
203
+
204
+ def load(path: Path) -> Result[Spec, BadCase]:
205
+ path = Path(path)
206
+ try:
207
+ raw = json.loads(path.read_text())
208
+ except (OSError, UnicodeError, json.JSONDecodeError) as e: # unreadable, not text, not JSON
209
+ return Err(BadCase((f"{path}: {e}",)))
210
+ if not isinstance(raw, dict):
211
+ return Err(BadCase((f"{path}: a case file is one JSON object, not {type(raw).__name__}",)))
212
+ problems: list[str] = []
213
+ for name in ("state", "questions", "target", "estimator", "judge"):
214
+ if name not in raw:
215
+ problems.append(f"the case file has no {name!r}")
216
+ state = raw.get("state", {})
217
+ judge = judge_of(raw.get("judge"), problems)
218
+ facts = facts_of(raw, state, problems)
219
+ target = target_of(raw.get("target"), problems)
220
+ estimator = estimator_of(raw.get("estimator"), problems)
221
+ line = raw.get("line")
222
+ if not is_number(line):
223
+ problems.append(f"line must be a number (the line a fact must clear), not {line!r}")
224
+ noise_sd = raw.get("noise_sd")
225
+ if noise_sd is not None and not is_number(noise_sd):
226
+ problems.append(f"noise_sd must be a number or null, not {noise_sd!r}")
227
+ repeats = count(raw, "repeats", REPEATS, 1, problems)
228
+ shuffles = count(raw, "shuffles", 5, 0, problems)
229
+ budget = budget_of(raw.get("budget"), problems)
230
+ stories = groups(raw["stories"], problems) if "stories" in raw else ()
231
+ questions = raw.get("questions", {})
232
+ if not isinstance(state, dict) or not isinstance(questions, dict):
233
+ problems.append("state and questions must be JSON objects")
234
+ else:
235
+ match validate(Case(state, facts, questions, stories)):
236
+ case Err(bad):
237
+ problems += [p for p in bad.problems if p not in problems]
238
+ if problems or judge is None or target is None or estimator is None or not isinstance(line, int | float):
239
+ return Err(BadCase(tuple(problems)))
240
+ ledger = path.parent / str(raw.get("ledger", f"{path.stem}.ledger.jsonl"))
241
+ return Ok(Spec(judge, Case(state, facts, questions, stories), target, estimator, float(line),
242
+ bool(raw.get("monotone", False)), repeats, shuffles, noise_sd, budget, ledger))
movedby/cli.py ADDED
@@ -0,0 +1,123 @@
1
+ """The command line. Nothing is paid without `--pay`.
2
+
3
+ movedby plan CASE.json the quote: new calls, cached calls, the upper cost
4
+ movedby run CASE.json [--pay] [--json] the explanation (a quote while calls are missing, without --pay)
5
+ movedby control --judge jev [--pay] the three planted cases and their gates; exit 1 on a failed gate
6
+ """
7
+
8
+ import argparse
9
+ import json
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ from movedby.casefile import load
14
+ from movedby.controls import CASES, planted, verdict
15
+ from movedby.estimators import Exact
16
+ from movedby.judges import Decisions, Judge, Kairos, TypeSafe
17
+ from movedby.report import as_json, problem_text, quote_text, text, verdict_text
18
+ from movedby.result import Err, Ok
19
+ from movedby.run import Budget, Explanation, NoAccess, Quote, explain
20
+ from movedby.target import P
21
+
22
+
23
+ def parser() -> argparse.ArgumentParser:
24
+ p = argparse.ArgumentParser(prog="movedby", description="What moved the decision.")
25
+ sub = p.add_subparsers(dest="command", required=True)
26
+ plan = sub.add_parser("plan", help="the quote for a case file; calls nothing")
27
+ plan.add_argument("case", type=Path)
28
+ run = sub.add_parser("run", help="explain a case file")
29
+ run.add_argument("case", type=Path)
30
+ run.add_argument("--pay", action="store_true", help="ask the calls the quote names")
31
+ run.add_argument("--json", action="store_true")
32
+ run.add_argument("--workers", type=int, default=8)
33
+ run.add_argument("--retry-failed", action="store_true")
34
+ control = sub.add_parser("control", help="the planted cases with known answers")
35
+ control.add_argument("--judge", choices=("jev", "kairos", "decisions"), required=True)
36
+ control.add_argument("--model")
37
+ control.add_argument("--pay", action="store_true")
38
+ control.add_argument("--ledger", type=Path, default=Path("control.ledger.jsonl"))
39
+ return p
40
+
41
+
42
+ def run_case(args, *, pay: bool) -> int:
43
+ match load(args.case):
44
+ case Err(bad):
45
+ print(problem_text(bad), file=sys.stderr)
46
+ return 1
47
+ case Ok(spec):
48
+ pass
49
+ result = explain(spec.judge, spec.case, spec.target, spec.estimator, ledger=spec.ledger, line=spec.line,
50
+ budget=spec.budget, pay=pay, repeats=spec.repeats, shuffles=spec.shuffles,
51
+ workers=getattr(args, "workers", 8), retry_failed=getattr(args, "retry_failed", False),
52
+ monotone=spec.monotone, noise_sd=spec.noise_sd)
53
+ match result:
54
+ case Ok(Quote() as q):
55
+ print(quote_text(q) + ("" if args.command == "plan" else "\nnothing was asked: add --pay to ask"))
56
+ return 0
57
+ case Ok(Explanation() as ex):
58
+ print(json.dumps(as_json(ex, spec.case), indent=1) if getattr(args, "json", False)
59
+ else text(ex, spec.case))
60
+ return 0
61
+ case Err(problem):
62
+ print(problem_text(problem), file=sys.stderr)
63
+ return 1
64
+ return 1
65
+
66
+
67
+ CONTROL_BUDGET = Budget(usd=0.05) # per planted case: 16 calls, far under a cent on a priced judge
68
+ CONTROL_CALLS = 16 # every subset of a planted case's four facts
69
+
70
+
71
+ def control_budget(judge: Judge) -> Budget:
72
+ """The limit per planted case: dollars for a priced judge, the call count where no price is known."""
73
+ return CONTROL_BUDGET if judge.price.known else Budget(usd=None, calls=CONTROL_CALLS)
74
+
75
+
76
+ def control(judge: Judge, ledger: Path, pay: bool) -> int:
77
+ """The three planted cases on `judge`: 0 when no gate fails, 1 when one does or a case cannot be run."""
78
+ failed = False
79
+ for name, planted_case in ((n, planted()[n]) for n in CASES):
80
+ result = explain(judge, planted_case.case, P("yes"), Exact(), ledger=ledger, line=0.05,
81
+ budget=control_budget(judge), pay=pay, repeats=1, shuffles=0)
82
+ match result:
83
+ case Ok(Quote() as q):
84
+ print(f"{name:<11} {quote_text(q)}")
85
+ case Ok(Explanation() as ex):
86
+ v = verdict(name, planted_case.case.players, ex.game, planted_case.marked)
87
+ failed |= v.passed is False
88
+ print(verdict_text(v))
89
+ case Err(NoAccess() as problem):
90
+ print(problem_text(problem), file=sys.stderr)
91
+ return 1 # the other cases would be refused the same way
92
+ case Err(problem):
93
+ print(f"{name:<11} {problem_text(problem)}", file=sys.stderr)
94
+ failed = True
95
+ if not pay:
96
+ print("nothing was asked: add --pay to ask")
97
+ return 1 if failed else 0
98
+
99
+
100
+ def run_control(args) -> int:
101
+ judges: dict[str, type[TypeSafe | Kairos | Decisions]] = {
102
+ "jev": TypeSafe,
103
+ "kairos": Kairos,
104
+ "decisions": Decisions,
105
+ }
106
+ judge = judges[args.judge](model=args.model) if args.model else judges[args.judge]()
107
+ return control(judge, args.ledger, args.pay)
108
+
109
+
110
+ def main(argv: list[str] | None = None) -> int:
111
+ args = parser().parse_args(argv)
112
+ match args.command:
113
+ case "plan":
114
+ return run_case(args, pay=False)
115
+ case "run":
116
+ return run_case(args, pay=args.pay)
117
+ case "control":
118
+ return run_control(args)
119
+ return 2
120
+
121
+
122
+ if __name__ == "__main__":
123
+ sys.exit(main())