File size: 18,799 Bytes
2983a9c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | #!/usr/bin/env python3
"""Tests for the Argument Check environment: python3 tests/test_argument_check.py
Hand-worked truth tables for each family (checked against gen.py's formula functions), agreement of the
three separately written parsers, and accept/reject cases for every custom validator.
"""
import importlib.util, itertools, os, random, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from envs.argument_check import gen
def load(name):
spec = importlib.util.spec_from_file_location("argument_check_" + name, os.path.join(ROOT, "envs", "argument_check", name + ".py"))
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m); return m
oracle, val = load("oracle"), load("validators")
P = gen.parse
# ------------------------------------------------------------ syntax: precedence and grouping
def test_syntax():
assert P("A & B | C") == ("|", ("&", "A", "B"), "C")
assert P("A | B & C") == ("|", "A", ("&", "B", "C"))
assert P("~A & B") == ("&", ("~", "A"), "B")
assert P("A | B -> C & D") == ("->", ("|", "A", "B"), ("&", "C", "D"))
assert P("A -> B <-> C") == ("<->", ("->", "A", "B"), "C")
assert P("A & B & C") == ("&", ("&", "A", "B"), "C")
assert P("A | B | C") == ("|", ("|", "A", "B"), "C")
assert P("A -> B -> C") == ("->", "A", ("->", "B", "C"))
assert P("A <-> B <-> C") == ("<->", "A", ("<->", "B", "C"))
assert P("~~A") == ("~", ("~", "A")) and P("~(A|B)") == ("~", ("|", "A", "B"))
assert P("A<->B->~C|D&E") == ("<->", "A", ("->", "B", ("|", ("~", "C"), ("&", "D", "E"))))
# printing keeps the tree, in both styles
for s in ["A -> B -> C", "(A -> B) -> C", "A & (B & C)", "~(A & B) | C <-> (D <-> E)", "A & B | C & ~D", "(A | B) & (C | D)"]:
f = P(s)
assert P(gen.show(f, "lean")) == f and P(gen.show(f, "full")) == f
assert gen.show(P("(A -> B) -> C")) == "(A -> B) -> C" and gen.show(P("A -> (B -> C)")) == "A -> B -> C"
assert gen.show(P("A & B | C"), "full") == "(A & B) | C"
def truth(f, order, bits):
return gen.ev(f, dict(zip(order, bits)))
def test_three_parsers_agree():
r = random.Random(7)
for i in range(3000):
atoms = sorted(r.sample("ABCDEFGH", r.randint(2, 5)))
f = gen.rand_formula(r, atoms, r.randint(0, 4))
s = gen.show(f, r.choice(["lean", "full"]), r if i % 2 else None)
if i % 5 == 0: s = s.replace(" ", "")
assert gen.parse(s) == f
rpn, tree = oracle.to_rpn(s), val._read(s)
assert oracle.letters([rpn]) == gen.atoms_of([f]) == sorted(val._atoms([tree]))
for v in gen.table(gen.atoms_of([f])):
assert gen.ev(f, v) == oracle.run(rpn, v) == val._value(tree, v), s
for bad in ["", "A &", "A B", "(A", "A)", "A -> -> B", "a", "A <- B", "~", "A ~ B", "()", "A & (B", "A = B", "A <-> ", "& A", "A (B)", "1", "AB"]:
for fn in (gen.parse, oracle.to_rpn, val._read):
try: fn(bad)
except Exception: continue
raise AssertionError("%r accepted by %s" % (bad, fn.__name__))
# ------------------------------------------------------------ validity, worked by hand
def test_validity_hand():
# 1. Modus ponens. Rows (A,B): TT both premises true, B true. TF: A->B false. FT, FF: A false.
# So 1 row with all premises true, no counterexample. Without premise 1, row TF refutes; without premise 2, row FF refutes.
prem, c = [P("A -> B"), P("A")], P("B")
assert gen.arg_stats(prem, c) == (["A", "B"], 1, 0) and gen.essential_premises(prem, c) == [1, 2]
# 2. Affirming the consequent. Premises true in TT and FT (2 rows); in FT the conclusion A is false (1 counterexample).
assert gen.arg_stats([P("A -> B"), P("B")], P("A")) == (["A", "B"], 2, 1)
# 3. Precedence: "A | B -> C" is (A | B) -> C. With ~C true, C is false, so A | B must be false: only A=F,B=F,C=F (1 row),
# where ~A & ~B is true. Read wrongly as A | (B -> C) it would be 3 rows (A,B = TT, TF, FF with C false).
assert gen.arg_stats([P("A | B -> C"), P("~C")], P("~A & ~B")) == (["A", "B", "C"], 1, 0)
# 4. Premises that cannot all be true: A, ~A therefore B. 0 premise rows, so valid. Dropping either premise lets B be false.
prem, c = [P("A"), P("~A")], P("B")
assert gen.arg_stats(prem, c) == (["A", "B"], 0, 0) and gen.essential_premises(prem, c) == [1, 2]
# 5. An idle premise: A -> B, C, A therefore B. Over A,B,C (8 rows) all premises hold only at A=T,B=T,C=T.
# Premise 2 (C) can go; premises 1 and 3 cannot.
prem, c = [P("A -> B"), P("C"), P("A")], P("B")
assert gen.arg_stats(prem, c) == (["A", "B", "C"], 1, 0) and gen.essential_premises(prem, c) == [1, 3]
# 6. Grouping to the right: A -> B -> A is A -> (B -> A), true in all 4 rows; B is false in 2 of them.
# (Grouped to the left it would be (A -> B) -> A, true in only 2 rows.)
assert gen.arg_stats([P("A -> B -> A")], P("B")) == (["A", "B"], 4, 2)
# 7. Disjunctive syllogism gone wrong: A | B, A therefore ~B. Premises true in TT and TF; TT is the one counterexample.
assert gen.arg_stats([P("A | B"), P("A")], P("~B")) == (["A", "B"], 2, 1)
# ------------------------------------------------------------ consistency, worked by hand
def test_consistency_hand():
# 1. {A | B, ~A, ~B}. TT: 1 true. TF: A|B and ~B, 2 true. FT: 2 true. FF: ~A and ~B, 2 true. No model; at most 2 together.
# Deleting any one sentence leaves a satisfiable pair.
st = gen.set_stats([P("A | B"), P("~A"), P("~B")])
assert (st["models"], st["most"], st["restoring"]) == (0, 2, [1, 2, 3])
# 2. {A -> B, B -> C, A}: A true forces B then C. One model, TTT; every atom forced true.
st = gen.set_stats([P("A -> B"), P("B -> C"), P("A")])
assert (st["models"], st["most"], st["forced_true"], st["forced_false"]) == (1, 3, ["A", "B", "C"], [])
# 3. {A | B, ~A | ~B}: exactly one of A, B true. Models TF and FT; nothing forced.
st = gen.set_stats([P("A | B"), P("~A | ~B")])
assert (st["models"], st["forced_true"], st["forced_false"]) == (2, [], [])
# 4. {A <-> B, A & ~B, C}: sentences 1 and 2 clash. Best rows make 2 true. Deleting 1 or 2 restores; deleting 3 does not.
st = gen.set_stats([P("A <-> B"), P("A & ~B"), P("C")])
assert (st["models"], st["most"], st["restoring"]) == (0, 2, [1, 2])
# 5. {P, P -> Q, ~Q | R, ~R}: P gives Q gives R, against ~R. P=T,Q=T,R=F makes 3 true. Any single deletion restores.
st = gen.set_stats([P("P"), P("P -> Q"), P("~Q | R"), P("~R")])
assert (st["models"], st["most"], st["restoring"]) == (0, 3, [1, 2, 3, 4])
# 6. {A & ~B, C -> B, A | C}: A=T, B=F, so C=F. One model; A forced true, B and C forced false.
st = gen.set_stats([P("A & ~B"), P("C -> B"), P("A | C")])
assert (st["models"], st["forced_true"], st["forced_false"]) == (1, ["A"], ["B", "C"])
# ------------------------------------------------------------ equivalence, worked by hand
def test_equivalence_hand():
def st(l, r_):
s = gen.pair_stats(P(l), P(r_)); return (s["left_models"], s["right_models"], s["left_only"], s["right_only"], s["relation"])
# 1. De Morgan: both false only at TT. 3 models each.
assert st("~(A & B)", "~A | ~B") == (3, 3, 0, 0, "equivalent")
# 2. Conditional and converse: A -> B true at TT, FT, FF; B -> A true at TT, TF, FF. They differ at FT and TF.
assert st("A -> B", "B -> A") == (3, 3, 1, 1, "neither")
# 3. A & B (TT only) against A | B (TT, TF, FT).
assert st("A & B", "A | B") == (1, 3, 0, 2, "left-entails-right")
assert st("A | B", "A & B") == (3, 1, 2, 0, "right-entails-left")
# 4. Absorption, counted over both atoms A and B: each side is true in the 2 rows with A true.
assert st("A & (A | B)", "A") == (2, 2, 0, 0, "equivalent")
# 5. A <-> B <-> C is A <-> (B <-> C): true at TTT, TFF, FTF, FFT (4 rows). (A <-> B) & (B <-> C) is true at TTT, FFF.
# Left only: TFF, FTF, FFT (3). Right only: FFF (1).
assert st("A <-> B <-> C", "(A <-> B) & (B <-> C)") == (4, 2, 3, 1, "neither")
# 6. Exportation: (A & B) -> C and A -> (B -> C) are both false only at TTF. 7 models each.
assert st("A & B -> C", "A -> B -> C") == (7, 7, 0, 0, "equivalent")
# normal forms are judged on the parsed tree
nf = gen.is_normal_form
assert nf(P("(A | ~B) & C"), "cnf") and nf(P("A | B"), "cnf") and nf(P("~A"), "cnf") and nf(P("A & B"), "cnf")
assert not nf(P("A | B & C"), "cnf") and nf(P("A | B & C"), "dnf") and nf(P("A & ~B | C"), "dnf")
assert not nf(P("~(A | B)"), "cnf") and not nf(P("~(A | B)"), "dnf") and not nf(P("A -> B"), "cnf") and not nf(P("~~A"), "dnf")
assert not nf(P("(A | B) & C"), "dnf") and nf(P("(A | (B | ~C)) & ((D | A) & B)"), "cnf")
# ------------------------------------------------------------ validators
def test_counterexample_validator():
args = {"id": "ARG01", "premises": ["A -> B", "B"], "conclusion": "A"} # only counterexample: A false, B true
def a(x): return {"arguments": {"ARG01": {"counterexample": x}}}
assert val.counterexample(a({"A": False, "B": True}), args) is True
wrong = [{"A": True, "B": True}, # conclusion true
{"A": False, "B": False}, # premise B false
{"A": True, "B": False}, # premise A -> B false
{"A": False}, # atom missing
{"A": False, "B": True, "C": True}, # atom that does not occur
{"A": 0, "B": 1}, # not booleans
{"A": "false", "B": "true"}, None, [False, True], "A=F,B=T", {}]
for w in wrong: assert val.counterexample(a(w), args) is False, w
for junk in [None, {}, [], "x", 3, {"arguments": None}, {"arguments": {"ARG02": {"counterexample": {"A": False, "B": True}}}}, {"arguments": {"ARG01": [1]}}]:
assert val.counterexample(junk, args) is False
# precedence matters to the validator too: (A | B) -> C, ~C therefore A has the single counterexample FFF
args2 = {"id": "X", "premises": ["A | B -> C", "~C"], "conclusion": "A"}
assert val.counterexample({"arguments": {"X": {"counterexample": {"A": False, "B": False, "C": False}}}}, args2) is True
assert val.counterexample({"arguments": {"X": {"counterexample": {"A": False, "B": True, "C": False}}}}, args2) is False
def test_satisfying_validator():
args = {"id": "SET01", "sentences": ["A | B", "~A | ~B", "B -> C"]} # models: TFT, TFF, FTT
def a(x): return {"sets": {"SET01": {"valuation": x}}}
for ok in [{"A": True, "B": False, "C": False}, {"A": True, "B": False, "C": True}, {"A": False, "B": True, "C": True}]:
assert val.satisfying_valuation(a(ok), args) is True
wrong = [{"A": True, "B": True, "C": True}, # sentence 2 false
{"A": False, "B": True, "C": False}, # sentence 3 false
{"A": False, "B": False, "C": True}, # sentence 1 false
{"A": True, "B": False}, # atom missing
{"A": True, "B": False, "C": False, "D": False}, # extra atom
{"A": 1, "B": 0, "C": 0}, {"a": True, "b": False, "c": False}, None, "TFF", []]
for w in wrong: assert val.satisfying_valuation(a(w), args) is False, w
for junk in [None, {}, [], 3, {"sets": []}, {"sets": {"SET01": None}}]: assert val.satisfying_valuation(junk, args) is False
def test_distinguishing_validator():
args = {"id": "PAIR01", "left": "A -> B", "right": "B -> A"} # they differ at FT and TF
def a(x): return {"pairs": {"PAIR01": {"distinguishing": x}}}
assert val.distinguishing_valuation(a({"A": False, "B": True}), args) is True
assert val.distinguishing_valuation(a({"A": True, "B": False}), args) is True
wrong = [{"A": True, "B": True}, # both true
{"A": False, "B": False}, # both true
{"A": False}, # atom missing
{"A": False, "B": True, "Z": True}, # extra atom
{"A": "F", "B": "T"}, {"A": None, "B": True}, None, 1, [{"A": False, "B": True}]]
for w in wrong: assert val.distinguishing_valuation(a(w), args) is False, w
# atoms are those of either formula: A & (A | B) against A & B differ at A true, B false; B must be given
args2 = {"id": "P", "left": "A & (A | B)", "right": "A & B"}
assert val.distinguishing_valuation({"pairs": {"P": {"distinguishing": {"A": True, "B": False}}}}, args2) is True
assert val.distinguishing_valuation({"pairs": {"P": {"distinguishing": {"A": True}}}}, args2) is False
for junk in [None, {}, [], "x", {"pairs": 5}]: assert val.distinguishing_valuation(junk, args) is False
def test_normal_form_validator():
# A -> B & C is A -> (B & C), equivalent to (~A | B) & (~A | C)
cnf = {"id": "F01", "formula": "A -> B & C", "form": "cnf"}
dnf = {"id": "F01", "formula": "A -> B & C", "form": "dnf"}
def a(x, form="cnf"): return {form: {"F01": x}}
for ok in ["(~A | B) & (~A | C)", "((~A|B))&(C|~A)", "(B | ~A) & (~A | C) & (~A | B | C)", "(~A | B | B) & (C | ~A)"]:
assert val.normal_form(a(ok), cnf) is True, ok
wrong = ["~A | B & C", # equivalent, but parses as ~A | (B & C): not a CNF
"(~A | B) & (A | C)", # CNF, not equivalent
"(~A | B) & (~A | C) & (D | ~D)", # atom D does not occur in the formula
"A -> B & C", # the formula itself: not a normal form
"~(A & ~B) & (~A | C)", # negation of a compound
"(~~~A | B) & (~A | C)", # ~~~A is not a literal
"(~A | B) & (~A | C", # does not parse
"(~A | B) & (~A | C) " + "& (~A | C) " * 200, # longer than 2000 characters
"", None, 5, ["(~A | B) & (~A | C)"], {"f": "(~A | B) & (~A | C)"}]
for w in wrong: assert val.normal_form(a(w), cnf) is False, w
for ok in ["~A | B & C", "~A | (B & C)", "(~A & B) | (~A & ~B) | (B & C)"]:
assert val.normal_form(a(ok, "dnf"), dnf) is True, ok
for w in ["(~A | B) & (~A | C)", "~A | B", "~A | B & C | D & ~D", "~(A & ~(B & C))", "~A | B & C |", None]:
assert val.normal_form(a(w, "dnf"), dnf) is False, w
assert val.normal_form({"dnf": {"F01": "(~A | B) & (~A | C)"}}, cnf) is False # right text under the wrong key
assert val.normal_form(a("(~A | B) & (~A | C)"), {"id": "F01", "formula": "A -> B & C", "form": "nnf"}) is False
assert val.normal_form(a("(" * 1500 + "A" + ")" * 1500), cnf) is False # deep nesting must not raise
for junk in [None, {}, [], "x", {"cnf": "x"}, {"cnf": {"F02": "(~A | B) & (~A | C)"}}]: assert val.normal_form(junk, cnf) is False
def test_validators_against_generator():
"""On generated tasks, each valuation validator accepts exactly the rows gen.py's own evaluator says qualify,
and the normal-form validator accepts the truth-table forms and rejects the same forms with one literal flipped."""
seen = {"counterexample": 0, "satisfying_valuation": 0, "distinguishing_valuation": 0, "normal_form": 0}
for seed in range(45):
for d in (1, 2, 3):
t = gen.generate(seed, d)
for c in t.checks:
if c["type"] != "custom": continue
g = c["args"]; seen[c["name"]] += 1
if c["name"] == "counterexample":
fs = [P(x) for x in g["premises"]]; con = P(g["conclusion"]); atoms = gen.atoms_of(fs + [con]); n_ok = 0
for v in gen.table(atoms):
want = all(gen.ev(f, v) for f in fs) and not gen.ev(con, v); n_ok += want
assert val.counterexample({"arguments": {g["id"]: {"counterexample": v}}}, g) is want
assert n_ok >= 1
elif c["name"] == "satisfying_valuation":
fs = [P(x) for x in g["sentences"]]; n_ok = 0
for v in gen.table(gen.atoms_of(fs)):
want = all(gen.ev(f, v) for f in fs); n_ok += want
assert val.satisfying_valuation({"sets": {g["id"]: {"valuation": v}}}, g) is want
assert n_ok >= 1
elif c["name"] == "distinguishing_valuation":
l, r_ = P(g["left"]), P(g["right"]); n_ok = 0
for v in gen.table(gen.atoms_of([l, r_])):
want = gen.ev(l, v) != gen.ev(r_, v); n_ok += want
assert val.distinguishing_valuation({"pairs": {g["id"]: {"distinguishing": v}}}, g) is want
assert n_ok >= 1
else:
f = P(g["formula"]); atoms = gen.atoms_of([f]); rows = gen.table(atoms); form = g["form"]
if form == "cnf": parts = ["(" + " | ".join(("~" if v[x] else "") + x for x in atoms) + ")" for v in rows if not gen.ev(f, v)]
else: parts = ["(" + " & ".join(("" if v[x] else "~") + x for x in atoms) + ")" for v in rows if gen.ev(f, v)]
good = (" & " if form == "cnf" else " | ").join(parts)
assert val.normal_form({form: {g["id"]: good}}, g) is True
a0 = atoms[0]
flipped = good.replace("(~" + a0, "(#", 1) if good.startswith("(~" + a0) else good.replace("(" + a0, "(~" + a0, 1)
flipped = flipped.replace("(#", "(" + a0)
assert flipped != good and val.normal_form({form: {g["id"]: flipped}}, g) is False
assert val.normal_form({form: {g["id"]: g["formula"]}}, g) is False # the unconverted formula
other = "dnf" if form == "cnf" else "cnf"
if len(parts) > 1 and len(atoms) > 1:
assert val.normal_form({form: {g["id"]: good.replace("&", "#").replace("|", "&").replace("#", "|")}}, g) is False
assert all(n > 20 for n in seen.values()), seen
def test_generated_tasks_are_balanced():
for fam, key in (("validity", "valid"), ("consistency", "satisfiable"), ("equivalence", "equivalent")):
for d in (1, 2, 3):
yes = no = 0
for seed in range(40):
for c in gen.generate(seed, d, fam).checks:
if c["type"] == "bool" and c["path"].endswith("." + key): yes += c["value"]; no += not c["value"]
assert 0.42 <= yes / float(yes + no) <= 0.58, (fam, d, yes, no)
if __name__ == "__main__":
tests = [(k, v) for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
for name, fn in tests:
fn(); print("ok " + name)
print("argument_check: %d tests passed" % len(tests))
|