commonground-engine 0.2.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.
commonground/argmap.py ADDED
@@ -0,0 +1,207 @@
1
+ """Where do two positions actually disagree, and what could they both accept?
2
+
3
+ A debate is a set of formal statements, each owned by a position (or shared).
4
+ Three questions are answered by search rather than by labelling:
5
+
6
+ * Are the positions compatible? Yes iff all their premises together have a model.
7
+ * If not, where exactly do they clash? The minimal unsatisfiable subsets (MUSes)
8
+ are the irreducible conflicts; the minimal correction sets (MCSes) are the
9
+ smallest sets of statements whose withdrawal restores consistency, and their
10
+ complements, the maximal satisfiable subsets (MSSes), are the largest bodies of
11
+ statements that can be held together.
12
+ * What does each conclusion really depend on? Its justifications are the minimal
13
+ sets of premises that entail it.
14
+
15
+ Enumeration is MARCO (Liffiton et al.): a SAT solver over "which statements are
16
+ in the subset" proposes unexplored subsets, a satisfiability oracle classifies
17
+ them, and each MUS or MSS found blocks its supersets or subsets.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ from dataclasses import dataclass
24
+ from typing import Callable, Hashable, Iterable
25
+
26
+ from pysat.solvers import Solver
27
+
28
+ from .fol import Formula, Not, parse, to_text
29
+ from .verdict import decide, satisfiable
30
+
31
+
32
+ class Undecided(RuntimeError):
33
+ """The satisfiability oracle could not classify a subset, so the enumeration is not exhaustive."""
34
+
35
+
36
+ class TooMany(RuntimeError):
37
+ """More subsets than the caller's limit; raise the limit or accept a partial picture."""
38
+
39
+
40
+ def enumerate_mus_mss(items: list[Hashable], is_satisfiable: Callable[[frozenset], bool | None],
41
+ limit: int = 2000) -> tuple[list[frozenset], list[frozenset]]:
42
+ """All minimal unsatisfiable and all maximal satisfiable subsets of ``items``.
43
+
44
+ ``is_satisfiable`` must be monotone: every subset of a satisfiable set is satisfiable.
45
+ """
46
+ index = {item: i + 1 for i, item in enumerate(items)}
47
+ cache: dict[frozenset, bool] = {}
48
+
49
+ def sat(subset: frozenset) -> bool:
50
+ if subset not in cache:
51
+ answer = is_satisfiable(subset)
52
+ if answer is None:
53
+ raise Undecided(f"could not decide a subset of {len(subset)} statement(s)")
54
+ cache[subset] = answer
55
+ return cache[subset]
56
+
57
+ muses: list[frozenset] = []
58
+ msses: list[frozenset] = []
59
+ with Solver(name="glucose4") as seeds:
60
+ for i in index.values(): # make every variable known to the solver
61
+ seeds.add_clause([i, -i])
62
+ while seeds.solve():
63
+ model = set(seeds.get_model())
64
+ seed = frozenset(item for item, i in index.items() if i in model)
65
+ if sat(seed):
66
+ for item in items: # grow to a maximal satisfiable subset
67
+ if item not in seed and sat(seed | {item}):
68
+ seed = seed | {item}
69
+ msses.append(seed)
70
+ outside = [index[item] for item in items if item not in seed]
71
+ if not outside:
72
+ break # everything together is satisfiable: one MSS, no MUS
73
+ seeds.add_clause(outside)
74
+ else:
75
+ for item in items: # shrink to a minimal unsatisfiable subset
76
+ if item in seed and not sat(seed - {item}):
77
+ seed = seed - {item}
78
+ muses.append(seed)
79
+ if not seed:
80
+ break # unsatisfiable with no statement at all: the empty set is the only MUS
81
+ seeds.add_clause([-index[item] for item in seed])
82
+ if len(muses) + len(msses) > limit:
83
+ raise TooMany(f"more than {limit} minimal conflicts and maximal consistent sets")
84
+ return muses, msses
85
+
86
+
87
+ def minimal_hitting_sets(sets: list[frozenset], universe: Iterable[Hashable]) -> list[frozenset]:
88
+ """Brute-force minimal hitting sets. Used to cross-check MCSes against MUSes on small inputs."""
89
+ universe = list(universe)
90
+ found: list[frozenset] = []
91
+ for mask in sorted(range(1 << len(universe)), key=lambda m: bin(m).count("1")):
92
+ candidate = frozenset(u for i, u in enumerate(universe) if mask >> i & 1)
93
+ if any(prior <= candidate for prior in found):
94
+ continue
95
+ if all(candidate & s for s in sets):
96
+ found.append(candidate)
97
+ return found
98
+
99
+
100
+ # ------------------------------------------------------------------------------ debates
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class Statement:
105
+ id: str
106
+ owner: str # a position name, or "shared"
107
+ kind: str # "conclusion" marks a statement to be derived; anything else is a premise
108
+ formula: Formula | None
109
+ text: str = ""
110
+
111
+
112
+ def load_debate(path: str) -> tuple[dict, list[Statement]]:
113
+ with open(path, encoding="utf-8") as fh:
114
+ raw = json.load(fh)
115
+ statements = []
116
+ for row in raw["statements"]:
117
+ formula = parse(row["fol"]) if row.get("fol") else None
118
+ statements.append(Statement(row["id"], row["owner"], row["kind"], formula, row.get("text", "")))
119
+ ids = [s.id for s in statements]
120
+ if len(set(ids)) != len(ids):
121
+ raise ValueError("statement ids must be unique")
122
+ return raw, statements
123
+
124
+
125
+ def input_hash(statements: list[Statement]) -> str:
126
+ """Hash of exactly what the analysis depends on, so a stored analysis can be pinned to its input."""
127
+ canon = [[s.id, s.owner, s.kind, to_text(s.formula) if s.formula else None] for s in statements]
128
+ return hashlib.sha256(json.dumps(canon, ensure_ascii=False, separators=(",", ":")).encode()).hexdigest()
129
+
130
+
131
+ def _oracle(formulas: dict[str, Formula], hard: list[Formula], timeout_ms: int):
132
+ def check(subset: frozenset) -> bool | None:
133
+ answer = satisfiable([formulas[i] for i in sorted(subset)] + hard, timeout_ms)
134
+ return {"sat": True, "unsat": False}.get(answer.status)
135
+ return check
136
+
137
+
138
+ def justifications(premises: dict[str, Formula], conclusion: Formula, timeout_ms: int = 5000,
139
+ limit: int = 2000) -> list[list[str]]:
140
+ """Every minimal set of premises that entails ``conclusion`` and is itself consistent."""
141
+ ids = sorted(premises)
142
+ muses, _ = enumerate_mus_mss(ids, _oracle(premises, [Not(conclusion)], timeout_ms), limit)
143
+ consistent = _oracle(premises, [], timeout_ms)
144
+ out = []
145
+ for m in muses:
146
+ status = consistent(m)
147
+ if status is None:
148
+ raise Undecided("could not decide whether a candidate justification is consistent")
149
+ if status: # drop "anything follows from a contradiction"
150
+ out.append(sorted(m))
151
+ return sorted(out, key=lambda j: (len(j), j))
152
+
153
+
154
+ def analyze(statements: list[Statement], timeout_ms: int = 5000, limit: int = 2000) -> dict:
155
+ """The full report for one debate, as plain data."""
156
+ premises = {s.id: s.formula for s in statements if s.kind != "conclusion" and s.formula is not None}
157
+ conclusions = [s for s in statements if s.kind == "conclusion" and s.formula is not None]
158
+ owner = {s.id: s.owner for s in statements}
159
+ positions = sorted({s.owner for s in statements if s.owner != "shared"})
160
+ ids = sorted(premises)
161
+
162
+ muses, msses = enumerate_mus_mss(ids, _oracle(premises, [], timeout_ms), limit)
163
+ compatible = not muses
164
+ witness = satisfiable([premises[i] for i in ids], timeout_ms) if compatible else None
165
+
166
+ def side(position: str) -> dict[str, Formula]:
167
+ return {i: f for i, f in premises.items() if owner[i] in (position, "shared")}
168
+
169
+ report_conclusions = {}
170
+ for c in conclusions:
171
+ from_all = decide([premises[i] for i in ids], c.formula, timeout_ms)
172
+ per_position = {p: decide(list(side(p).values()), c.formula, timeout_ms).label for p in positions}
173
+ report_conclusions[c.id] = {
174
+ "owner": c.owner,
175
+ "from_all_premises": from_all.label,
176
+ "from_each_position": per_position,
177
+ "justifications": justifications(premises, c.formula, timeout_ms, limit),
178
+ }
179
+
180
+ def describe(subset: frozenset) -> dict:
181
+ members = sorted(subset)
182
+ return {"statements": members, "positions": sorted({owner[i] for i in members})}
183
+
184
+ conflicts = sorted((describe(m) for m in muses), key=lambda d: (len(d["statements"]), d["statements"]))
185
+ # A correction set is what must be withdrawn to reach a maximal consistent set. When
186
+ # everything is consistent the only one is empty: there is nothing to concede.
187
+ corrections = [frozenset(ids) - m for m in msses]
188
+ concessions = sorted((describe(c) for c in corrections if c),
189
+ key=lambda d: (len(d["statements"]), d["statements"]))
190
+ in_every_mss = sorted(set(ids).intersection(*msses)) if msses else []
191
+ return {
192
+ "input_hash": input_hash(statements),
193
+ "premise_ids": ids,
194
+ "positions": positions,
195
+ "positions_compatible": compatible,
196
+ "compatibility_witness": (
197
+ {"domain_size": witness.structure.size, "engine": witness.engine,
198
+ "rechecked_by_independent_evaluator": True}
199
+ if witness is not None and witness.structure is not None else None),
200
+ "conflicts": conflicts, # minimal unsatisfiable subsets
201
+ "minimal_concessions": concessions, # minimal correction sets
202
+ "uncontested": in_every_mss, # premises in every maximal consistent set
203
+ "position_consistent": {p: satisfiable(list(side(p).values()), timeout_ms).status == "sat"
204
+ for p in positions},
205
+ "conclusions": report_conclusions,
206
+ "statements_without_formula": sorted(s.id for s in statements if s.formula is None),
207
+ }